Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee4a7e09b8 | ||
|
|
e0d5916a86 | ||
|
|
e8dc71329b | ||
|
|
30682cd659 | ||
|
|
e09a19b7b4 | ||
|
|
2b7e908d31 | ||
|
|
0ea85752fd | ||
|
|
97b7127ca3 | ||
|
|
db38feba52 | ||
|
|
1bab4df64e | ||
|
|
193130c50f | ||
|
|
c7794a12e7 | ||
|
|
408d8bcda4 | ||
|
|
5a3eebecbd | ||
|
|
713716dacc | ||
|
|
3a7a162f97 | ||
|
|
2f8614d53a | ||
|
|
bdac15afac | ||
|
|
7f49e2f2d7 | ||
|
|
24f1b9a4b8 | ||
|
|
79b91fca44 | ||
|
|
6a821b760e | ||
|
|
6539479d10 | ||
|
|
8ed3e788be | ||
|
|
de8f6a11c9 | ||
|
|
21d53a30c9 | ||
|
|
22656b2e7d | ||
|
|
3a18bcebbc | ||
|
|
7b35c63a74 | ||
|
|
6b9038da6c | ||
|
|
1dd04bf7ca | ||
|
|
15af861389 | ||
|
|
7ea63c525e | ||
|
|
3d0b8a5c97 | ||
|
|
fb39d82c01 | ||
|
|
ae530963bf | ||
|
|
f8554fc991 | ||
|
|
a3dad55c76 | ||
|
|
0b29742bce | ||
|
|
c2c38fa011 | ||
|
|
578217ba41 | ||
|
|
d75bdccfd9 | ||
|
|
412f560677 | ||
|
|
fdccf86458 | ||
|
|
d43a33aa15 | ||
|
|
056b57bcd1 | ||
|
|
688eb3174e | ||
|
|
c38f67bc3b | ||
|
|
67c7a27af6 | ||
|
|
6d1d2a1f92 | ||
|
|
faff7a2237 | ||
|
|
dc63f4b45b | ||
|
|
380fb67090 | ||
|
|
b71632cc29 | ||
|
|
38f7c94a65 | ||
|
|
d91a145657 | ||
|
|
a2e33ff176 | ||
|
|
010b8ef072 | ||
|
|
883703dd0c | ||
|
|
bcf212738b | ||
|
|
fae21ec086 | ||
|
|
22dcf93925 | ||
|
|
4df59b80d0 | ||
|
|
c49b4ec715 | ||
|
|
1c80791109 | ||
|
|
85f87ecd0b | ||
|
|
3d6752a5e4 | ||
|
|
a0921c35b2 | ||
|
|
ace9e84889 | ||
|
|
4ead174c04 | ||
|
|
f628d19ebf | ||
|
|
75de8f1d2b | ||
|
|
1ba8cd5ee1 | ||
|
|
f639825775 | ||
|
|
0b40a69d74 | ||
|
|
6defbff591 | ||
|
|
b5d167e1e7 | ||
|
|
7f97d54206 | ||
|
|
ef3e65ea0b | ||
|
|
d13b3207a9 | ||
|
|
7e08ee54a5 | ||
|
|
6d8e289b81 | ||
|
|
defbb766e4 | ||
|
|
69043748a1 | ||
|
|
8046985574 | ||
|
|
5ce73d2c84 | ||
|
|
2d1d202981 | ||
|
|
73313f9e2d | ||
|
|
097c72bc5d | ||
|
|
71f219b7ca | ||
|
|
bacc9fe07e | ||
|
|
a9c360fb9c | ||
|
|
04926c8491 | ||
|
|
fa1d1ad01b | ||
|
|
c0fc18c344 | ||
|
|
69d69f0a5a | ||
|
|
6d7976e5d8 | ||
|
|
aef1f68875 | ||
|
|
06e5cc6d8b | ||
|
|
7782e9b327 | ||
|
|
b82c4fe0af | ||
|
|
45584810a2 | ||
|
|
bfefd053a0 | ||
|
|
324213de14 | ||
|
|
a041ba90bb | ||
|
|
0dc623eb69 | ||
|
|
3e6876dbe7 | ||
|
|
a60abffd3b | ||
|
|
2b43952c01 | ||
|
|
12f440ab8b | ||
|
|
7221af78bf | ||
|
|
a88b0616f5 | ||
|
|
ea4d5b2a70 | ||
|
|
a439100ad6 | ||
|
|
620d24f796 | ||
|
|
fc3bbd0c59 | ||
|
|
3b5ce9b446 | ||
|
|
37de6067d0 | ||
|
|
45410fcc7d | ||
|
|
166cb543a1 | ||
|
|
a295ff4b27 | ||
|
|
dcc52c4530 | ||
|
|
dc3ad6a598 | ||
|
|
ef59e51e32 | ||
|
|
9bbc22de25 | ||
|
|
335d93a8b8 | ||
|
|
52ff0560d1 | ||
|
|
a5e5dd6592 | ||
|
|
62e41dbc51 | ||
|
|
d8b2fd9e1b | ||
|
|
8ca3249832 | ||
|
|
92574fddb1 | ||
|
|
596114e6a3 | ||
|
|
2868f7a478 | ||
|
|
63ef6b673d | ||
|
|
5a56e1706f | ||
|
|
986814441d | ||
|
|
0ab6fb6f3f | ||
|
|
a966be4db6 | ||
|
|
556084233d | ||
|
|
c38239ec35 | ||
|
|
21041346e3 | ||
|
|
7320aa3bb5 | ||
|
|
d9b8ea625a | ||
|
|
2323e22fef | ||
|
|
b5f8f01301 | ||
|
|
e964ff460e | ||
|
|
21d8d9c3bc | ||
|
|
169cf88306 | ||
|
|
059435f4cb | ||
|
|
4d4d4cdeb1 | ||
|
|
d42e7a033c | ||
|
|
0986c65551 | ||
|
|
694f864d36 | ||
|
|
512854ab9f | ||
|
|
b298496911 | ||
|
|
b6367e2645 | ||
|
|
b0fa4bf5d0 | ||
|
|
cb3dbe4ca4 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: webspeak-skin-development
|
||||
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
|
||||
---
|
||||
|
||||
# WebSpeak skin development
|
||||
|
||||
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
|
||||
|
||||
## Before editing
|
||||
|
||||
- Read [`docs/SKIN_DEVELOPMENT.md`](../../../docs/SKIN_DEVELOPMENT.md) for the current package validator and public hooks.
|
||||
- Use [`docs/examples/illusia-voice/`](../../../docs/examples/illusia-voice/) and [`docs/examples/ILLUSIA-VOICE.md`](../../../docs/examples/ILLUSIA-VOICE.md) as the reference implementation. Do not restore the removed Aurora Voice sample.
|
||||
- Inspect the actual component markup for `data-ws-page`, `data-ws-part`, and `data-ws-state` hooks. Treat Vue classes and incidental DOM structure as private.
|
||||
|
||||
## Preserve the interface
|
||||
|
||||
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
|
||||
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
|
||||
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
|
||||
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
|
||||
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
|
||||
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
|
||||
|
||||
## Verify and package
|
||||
|
||||
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
|
||||
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
|
||||
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
|
||||
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
|
||||
|
||||
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
|
||||
@@ -8,6 +8,7 @@ web/dist
|
||||
data
|
||||
certs
|
||||
release-artifacts
|
||||
scripts/acceleration-poc
|
||||
*.tar.gz
|
||||
*.tar.xz
|
||||
claude.pem
|
||||
|
||||
@@ -34,7 +34,11 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run prepare:sdk
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
@@ -130,7 +134,9 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
|
||||
@@ -22,11 +22,12 @@ jobs:
|
||||
web/package-lock.json
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
- name: Test and build
|
||||
- name: Build application
|
||||
run: |
|
||||
npm test
|
||||
npm run build
|
||||
npm --prefix web run build
|
||||
|
||||
|
||||
@@ -1,5 +1,317 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.5] — 2026-09-27(相对 0.2.4)
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 `.wskin` 视觉皮肤系统:用户可在首页、语音工作区和 `/demo` 选择外观;皮肤可更换背景、美术素材与组件视觉,但页面结构、排版空间、控件位置和交互仍由 WebSpeak 固定提供,管理后台不受皮肤影响。
|
||||
- 管理员可在皮肤库启用/停用自定义皮肤并指定实例默认皮肤;访客手动选择会保留,未手动选择的访客采用实例默认。默认日间、默认夜间和 ILLUSIA 风是受保护内置皮肤,不能删除、停用或替换。
|
||||
- 将完成度不足的 Aurora Voice 示例移除,以 ILLUSIA 风作为完整皮肤开发样例;细化首页装饰、语音区跨层级立绘、耳机场景、聊天空状态和屏幕播放器表现,并修复深色模式控件可读性、组件溢出和皮肤加载闪烁。
|
||||
- 新增官方仓库皮肤开发 Agent Skill,配套更新开发规范与多语言功能说明;访客总数在统计暂不可用时也不会低于当前访客序号。
|
||||
- 缩小 ILLUSIA 语音活动立绘并固定在容器右下角,避免遮挡成员名单和屏幕共享播放器。
|
||||
|
||||
### English
|
||||
|
||||
- Added the `.wskin` visual skin system. Visitors can choose appearances on the home page, voice workspace, and `/demo`; skins may customize artwork and component visuals while WebSpeak retains page structure, layout, control placement, and behavior. The administration console remains unskinned.
|
||||
- Administrators can enable/disable custom skins and set an instance default. Deliberate visitor choices are preserved; visitors without an explicit choice receive the instance default. Default Day, Default Night, and ILLUSIA are protected built-ins that cannot be removed, disabled, or replaced.
|
||||
- Removed the unfinished Aurora Voice sample and made ILLUSIA the complete reference skin. Refined homepage artwork, layered voice-room character art and headphone scene, the empty-chat backdrop, and the screen-share player; fixed dark-mode control contrast, overflow, and skin-load flashes.
|
||||
- Added the repository's official skin-development Agent Skill and synchronized the guide and localized feature notes. The displayed visitor total also remains at least as high as the current visitor ordinal when the counter is unavailable.
|
||||
- Reduced and anchored the ILLUSIA voice-activity artwork to the lower-right corner so it no longer obscures member cards or the screen-share player.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Das visuelle `.wskin`-System wurde ergänzt. Besucher können das Design auf der Startseite, im Sprachbereich und unter `/demo` wählen. Skins dürfen Grafiken und die visuelle Darstellung anpassen; Seitenstruktur, Layout, Positionen der Bedienelemente und Verhalten bleiben von WebSpeak vorgegeben. Die Administrationskonsole bleibt ungestaltet.
|
||||
- Administratoren können eigene Skins aktivieren/deaktivieren und ein Standarddesign für die Instanz festlegen. Eine bewusst getroffene Besucherauswahl bleibt erhalten; ohne eigene Auswahl gilt der Instanzstandard. Tagesmodus, Nachtmodus und ILLUSIA sind geschützte integrierte Skins und können weder gelöscht noch deaktiviert oder ersetzt werden.
|
||||
- Das unfertige Aurora-Voice-Beispiel wurde entfernt; ILLUSIA ist nun das vollständige Referenzdesign. Startseitenkunst, Ebenenillustration und Kopfhörerszene im Sprachbereich, leerer Chat-Hintergrund und Bildschirmfreigabe-Player wurden verfeinert. Außerdem wurden dunkle Bedienelemente, Überläufe und Skin-Ladeblitze korrigiert.
|
||||
- Der offizielle Skin-Entwicklungs-Agent-Skill des Repositorys wurde ergänzt; Anleitung und lokalisierte Funktionsübersichten wurden aktualisiert. Die Besucher-Gesamtzahl fällt bei nicht verfügbarem Zähler nicht unter die aktuelle Besuchernummer.
|
||||
- Die ILLUSIA-Illustration im Sprachbereich wurde verkleinert und unten rechts verankert, damit sie weder Mitgliederkarten noch den Bildschirmfreigabe-Player verdeckt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена визуальная система скинов `.wskin`: посетители могут выбирать оформление на главной странице, в голосовом пространстве и в `/demo`. Скины меняют иллюстрации и внешний вид компонентов, а структуру, компоновку, расположение элементов управления и поведение задаёт WebSpeak. Панель администратора не оформляется скинами.
|
||||
- Администраторы могут включать и отключать пользовательские скины и задавать оформление по умолчанию для экземпляра. Явный выбор посетителя сохраняется; без него используется настройка экземпляра. Дневная тема, ночная тема и ILLUSIA — защищённые встроенные скины, которые нельзя удалить, отключить или заменить.
|
||||
- Удалён незавершённый пример Aurora Voice; полной эталонной темой стала ILLUSIA. Улучшены иллюстрации главной страницы, многослойный персонаж и сцена с наушниками в голосовой комнате, фон пустого чата и проигрыватель трансляции экрана. Исправлены контраст элементов в тёмном режиме, переполнение и вспышки при загрузке скина.
|
||||
- В официальный репозиторий добавлен Agent Skill для разработки скинов, обновлены руководство и локализованные описания функций. При недоступности счётчика общее число посетителей не опускается ниже текущего номера посетителя.
|
||||
- Иллюстрация ILLUSIA в голосовой активности уменьшена и закреплена внизу справа, чтобы не перекрывать список участников и проигрыватель трансляции экрана.
|
||||
|
||||
### 日本語
|
||||
|
||||
- `.wskin` ビジュアルスキン機能を追加しました。ホーム、音声ワークスペース、`/demo` で外観を選択できます。背景や素材、コンポーネントの見た目を変更できますが、ページ構造、レイアウト、操作部品の位置と動作は WebSpeak が管理します。管理コンソールには適用されません。
|
||||
- 管理者はカスタムスキンの有効/無効と、インスタンスのデフォルトスキンを設定できます。訪問者が明示的に選んだスキンは維持され、未選択の場合はインスタンスのデフォルトを使用します。昼、夜、ILLUSIA の3種類は保護された内蔵スキンで、削除・無効化・置換できません。
|
||||
- 未完成の Aurora Voice サンプルを削除し、ILLUSIA を完成版のリファレンスにしました。ホームのアート、音声画面の重ね合わせ立ち絵とヘッドホン背景、空のチャット背景、画面共有プレーヤーを調整し、ダークモードの視認性、はみ出し、読み込み時のちらつきを修正しました。
|
||||
- 公式リポジトリにスキン開発 Agent Skill を追加し、ガイドと各言語の機能説明を更新しました。カウンターを取得できない場合も、訪問者総数が現在の訪問者番号を下回らないようにしました。
|
||||
- 音声アクティビティの ILLUSIA 立ち絵を縮小して右下に固定し、メンバー一覧や画面共有プレーヤーを隠さないようにしました。
|
||||
|
||||
## [0.2.4] — 2026-09-22
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增跨端 P2P 屏幕共享:浏览器用户可以与 TeamSpeak 6 原生客户端互相发现、发起和观看屏幕共享;浏览器之间以及浏览器与原生客户端之间的媒体流优先通过 WebRTC/ICE 直连,WebSpeak 仅负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。
|
||||
- 默认使用 TeamSpeak 官方 STUN 服务发现直连候选,并支持管理员显式配置外部 TURN;即使使用 TURN,媒体也经过外部服务而不是 WebSpeak 网关。
|
||||
- 新增屏幕共享直播状态、观众人数、播放器音量、全屏和退出控制,并提供发送端/接收端 WebRTC 实时统计。
|
||||
- 提供浏览器屏幕采集分辨率和帧率设置,最高支持 1080p、60 FPS;设置改为独立弹窗,避免成员卡片被撑高。
|
||||
- 新增首页访客编号,并优化屏幕共享成员卡片和观看交互。
|
||||
- 修正输出限制的应用方式:保持所选桌面或窗口的原始采集尺寸,由发送端编码器按设置缩放和限帧;首页同时显示当前访客序号和累计访客数。
|
||||
- 修复 TeamSpeak 握手期间服务器拒绝错误被误报为连接超时的问题;昵称长度不符合要求时会显示明确的修改提示。
|
||||
|
||||
### English
|
||||
|
||||
- Added cross-platform P2P screen sharing: browser users can discover, start, and watch screen shares with native TeamSpeak 6 clients. Media between browsers, and between a browser and a native client, prefers a direct WebRTC/ICE path; WebSpeak handles session authorization, share state, and SDP/ICE signaling only and does not carry screen media.
|
||||
- Added TeamSpeak's public STUN services for direct-candidate discovery by default, with optional administrator-configured external TURN. Even with TURN, media uses the external service rather than the WebSpeak gateway.
|
||||
- Added live screen-share status, viewer counts, player volume, fullscreen, and exit controls, plus live sender/receiver WebRTC statistics.
|
||||
- Added browser capture-resolution and frame-rate controls up to 1080p and 60 FPS; moved the controls into a standalone modal so member cards no longer stretch.
|
||||
- Added homepage visitor numbering and refined screen-share member-card and viewing interactions.
|
||||
- Fixed output-limit handling so the selected desktop or window keeps its native capture size while the sender encoder applies the requested scale and frame-rate cap; the homepage now also shows the total visitor count.
|
||||
- Fixed handshake refusals being reported as connection timeouts; invalid nickname lengths now show a clear prompt to change the nickname.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Plattformübergreifendes P2P-Bildschirmteilen ergänzt: Browsernutzer können Bildschirmfreigaben mit nativen TeamSpeak-6-Clients erkennen, starten und ansehen. Die Medienübertragung zwischen Browsern sowie zwischen Browser und nativem Client nutzt möglichst direkte WebRTC-/ICE-Verbindungen; WebSpeak übernimmt nur Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung und transportiert keine Bildschirmmedien.
|
||||
- Öffentliche TeamSpeak-STUN-Dienste werden standardmäßig zur Ermittlung direkter Kandidaten verwendet; ein externes TURN kann ausdrücklich durch den Administrator konfiguriert werden. Auch mit TURN läuft die Medienübertragung über den externen Dienst und nicht über das WebSpeak-Gateway.
|
||||
- Live-Status, Zuschauerzahl, Lautstärke, Vollbild- und Beenden-Steuerung für Bildschirmfreigaben sowie laufende WebRTC-Statistiken für Sender und Empfänger ergänzt.
|
||||
- Aufnahmeauflösung und Bildrate im Browser bis 1080p und 60 FPS konfigurierbar; die Einstellungen wurden in ein eigenes Modal verschoben, damit Mitgliederkarten nicht mehr in die Höhe wachsen.
|
||||
- Besucherzählung auf der Startseite ergänzt und die Interaktion von Bildschirmfreigabe-Karten und Player verbessert.
|
||||
- Die Ausgabelimits werden nun am Sender-Encoder angewendet, während die native Aufnahmegröße des ausgewählten Desktops oder Fensters erhalten bleibt; auf der Startseite wird zusätzlich die Gesamtzahl der Besucher angezeigt.
|
||||
- Behoben, dass Ablehnungen während des TeamSpeak-Handshakes als Zeitüberschreitung angezeigt wurden; bei ungültiger Nicknamenslänge erscheint nun ein klarer Änderungshinweis.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена кроссплатформенная P2P-трансляция экрана: пользователи браузера могут обнаруживать, запускать и смотреть трансляции вместе с нативными клиентами TeamSpeak 6. Медиа между браузерами, а также между браузером и нативным клиентом по возможности передаётся напрямую через WebRTC/ICE; WebSpeak отвечает только за авторизацию сессии, состояние трансляции и SDP/ICE-сигналы и не переносит медиаданные экрана.
|
||||
- По умолчанию добавлено обнаружение прямых кандидатов через публичные STUN-сервисы TeamSpeak; администратор может явно настроить внешний TURN. Даже при использовании TURN медиа идёт через внешний сервис, а не через шлюз WebSpeak.
|
||||
- Добавлены статус трансляции, число зрителей, громкость проигрывателя, полноэкранный режим и выход, а также текущая статистика WebRTC для отправителя и получателя.
|
||||
- Добавлены настройки разрешения и частоты кадров захвата в браузере до 1080p и 60 FPS; настройки вынесены в отдельное окно, чтобы карточки участников не растягивались.
|
||||
- Добавлен номер посетителя на главной странице и улучшено управление карточками и просмотром трансляций.
|
||||
- Исправлено применение ограничений вывода: выбранный рабочий стол или окно сохраняет исходный размер захвата, а запрошенное масштабирование и ограничение частоты кадров применяются кодировщиком отправителя; на главной странице также показывается общее число посетителей.
|
||||
- Исправлено ошибочное отображение отказов TeamSpeak во время рукопожатия как тайм-аута; при недопустимой длине имени показывается понятная просьба изменить его.
|
||||
|
||||
### 日本語
|
||||
|
||||
- クロスプラットフォーム P2P 画面共有を追加しました。ブラウザユーザーは TeamSpeak 6 ネイティブクライアントと互いに画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間のメディアは可能な限り WebRTC/ICE で直接送信され、WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングだけを担当し、画面メディアは運びません。
|
||||
- 初期設定で TeamSpeak 公開 STUN サービスによる直接候補の検出に対応し、管理者が外部 TURN を明示的に設定できるようにしました。TURN 使用時もメディアは外部サービスを経由し、WebSpeak ゲートウェイは経由しません。
|
||||
- 配信状態、視聴者数、プレーヤー音量、全画面、終了操作と、送信側・受信側の WebRTC 統計を追加しました。
|
||||
- ブラウザの画面取得設定で最大 1080p / 60 FPS を選択できます。設定を独立したモーダルに移し、メンバーカードが縦に伸びないようにしました。
|
||||
- ホームページの訪問者番号を追加し、画面共有カードと視聴操作を改善しました。
|
||||
- 出力制限を送信側エンコーダーで適用するよう修正し、選択したデスクトップやウィンドウの元の取得サイズを維持します。ホームページには訪問者番号に加えて累計訪問者数も表示します。
|
||||
- TeamSpeak の接続ハンドシェイク中の拒否がタイムアウトとして表示される問題を修正しました。ニックネームの長さが不適切な場合は、変更を促すメッセージを表示します。
|
||||
|
||||
## [0.2.3] — 2026-09-19
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增频道成员调度入口:保留拖放移动,并在右键菜单提供“调度到”二级菜单和“我所在的频道”快捷项。
|
||||
- 支持按 TeamSpeak 权限直接移动成员;具备权限时无需重复输入频道密码,无权限时不提供该操作。
|
||||
- 支持成员头像显示、麦克风静音状态同步和保存身份恢复,并增强指针拖动兼容性。
|
||||
- 更新中文、English、Deutsch、Русский、日本語五种语言的功能截图和文档页面。
|
||||
- 修复高分辨率桌面端管理员设置页面底部内容被裁切的问题,并收紧中继卡片的宽度约束。
|
||||
|
||||
### English
|
||||
|
||||
- Added member-management entry points: drag-and-drop remains available, while the context menu now provides a “Move to” submenu with a “My channel” shortcut.
|
||||
- Added permission-aware direct member moves: authorized users can move clients without redundant channel-password prompts, while the action is unavailable without the required TeamSpeak permission.
|
||||
- Added client-avatar display, microphone mute-state synchronization, and remembered-identity recovery, with improved pointer-drag compatibility.
|
||||
- Refreshed feature screenshots and documentation pages for all five supported languages.
|
||||
- Fixed clipped lower content in the high-resolution desktop admin settings page and tightened relay-card width constraints.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Neue Einstiege für die Mitgliederverwaltung: Ziehen und Ablegen bleibt verfügbar, zusätzlich bietet das Kontextmenü ein Untermenü „Verschieben nach“ mit dem Eintrag „Mein Kanal“.
|
||||
- Direkte, berechtigungsabhängige Mitgliederverschiebung ergänzt: Benutzer mit den erforderlichen TeamSpeak-Rechten benötigen keine erneute Kanalpasswortabfrage; ohne diese Rechte steht die Aktion nicht zur Verfügung.
|
||||
- Anzeige von Client-Avataren, Synchronisierung des Mikrofon-Stummschaltstatus und Wiederherstellung gespeicherter Identitäten ergänzt; Zeigerbedienung verbessert.
|
||||
- Funktionsscreenshots und Dokumentationsseiten für alle fünf unterstützten Sprachen aktualisiert.
|
||||
- Das Abschneiden unterer Inhalte in den Admin-Einstellungen bei hoher Desktop-Auflösung behoben und die Breitenbegrenzung der Relay-Karten verbessert.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлены способы управления участниками: перетаскивание сохранено, а в контекстном меню появился пункт «Переместить в» с быстрым вариантом «Мой канал».
|
||||
- Добавлено прямое перемещение с учётом прав TeamSpeak: пользователям с нужными правами не нужно повторно вводить пароль канала, а без этих прав действие недоступно.
|
||||
- Добавлены отображение аватаров клиентов, синхронизация состояния микрофона и восстановление сохранённой идентичности; улучшено перетаскивание указателем.
|
||||
- Обновлены функциональные скриншоты и страницы документации для всех пяти поддерживаемых языков.
|
||||
- Исправлено обрезание нижнего содержимого настроек администратора на десктопах с высоким разрешением и ограничена ширина карточек ретрансляторов.
|
||||
|
||||
### 日本語
|
||||
|
||||
- メンバー操作を追加しました。ドラッグ&ドロップに加えて、コンテキストメニューに「移動先」サブメニューと「自分のチャンネル」ショートカットを用意しました。
|
||||
- TeamSpeak 権限に応じた直接移動を追加しました。必要な権限があればチャンネルパスワードを再入力せずに移動でき、権限がなければ操作は表示されません。
|
||||
- クライアントアバターの表示、マイクミュート状態の同期、保存した ID の復元に対応し、ポインター操作も改善しました。
|
||||
- 対応する 5 言語すべての機能スクリーンショットとドキュメントページを更新しました。
|
||||
- 高解像度デスクトップで管理設定の下部が切れる問題を修正し、中継カードの幅制約を改善しました。
|
||||
|
||||
## [0.2.2] — 2026-09-17
|
||||
|
||||
### 中文
|
||||
|
||||
- 提供可开关的浏览器端麦克风降噪功能。
|
||||
- 优化前端音量交互逻辑:桌面端悬停麦克风和整体音量按钮即可调整,降噪开关收纳在麦克风菜单中。
|
||||
- 在 PR #2 基础上优化错误提示和错误代码显示。
|
||||
- 提供俄语和日语界面支持,并支持按语言单独调整欢迎文字。
|
||||
|
||||
### English
|
||||
|
||||
- Added optional browser-side microphone noise suppression.
|
||||
- Refined volume interaction: desktop microphone and master-volume controls open on hover, with noise suppression in the microphone menu.
|
||||
- Improved error messages and error-code display on top of PR #2.
|
||||
- Added Russian and Japanese UI support and per-language welcome text configuration.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Optionale browserseitige Mikrofon-Geräuschunterdrückung hinzugefügt.
|
||||
- Lautstärkeinteraktion verbessert: Desktop-Mikrofon- und Gesamtlautstärkeregler öffnen sich beim Überfahren; die Geräuschunterdrückung befindet sich im Mikrofonmenü.
|
||||
- Fehlertexte und Fehlercodes auf Basis von PR #2 verbessert.
|
||||
- Russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлено опциональное шумоподавление микрофона в браузере.
|
||||
- Улучшено управление громкостью: на компьютере регуляторы открываются при наведении, а шумоподавление находится в меню микрофона.
|
||||
- Улучшены сообщения и коды ошибок на основе PR #2.
|
||||
- Добавлены русский и японский интерфейсы и отдельная настройка приветствия для каждого языка.
|
||||
|
||||
### 日本語
|
||||
|
||||
- ブラウザ側で任意に使えるマイクノイズ抑制を追加しました。
|
||||
- 音量操作を改善し、デスクトップではマイクと全体音量のボタンにカーソルを合わせると調整画面を表示し、ノイズ抑制をマイクメニューにまとめました。
|
||||
- PR #2 を基にエラー表示とエラーコードを改善しました。
|
||||
- ロシア語・日本語 UI と言語別ウェルカム文の設定を追加しました。
|
||||
|
||||
## [0.2.1] — 2026-09-13
|
||||
|
||||
### 中文
|
||||
|
||||
- 统一首页连接错误显示:保留错误代码,未知错误安全截断,并显示可追溯的服务端原因。
|
||||
- 默认支持 IPv6 TeamSpeak 目标,并补充主机、运行时和网络条件说明。
|
||||
|
||||
### English
|
||||
|
||||
- Unified connection-error display on the welcome page: preserve error codes, safely truncate unknown codes, and show traceable server reasons.
|
||||
- Added default IPv6 TeamSpeak target support and documented the required host, runtime, and network conditions.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Verbindungsfehler auf der Willkommensseite vereinheitlicht: Fehlercodes bleiben erhalten, unbekannte Codes werden sicher gekürzt und nachvollziehbare Serverursachen angezeigt.
|
||||
- IPv6-Ziele für TeamSpeak standardmäßig unterstützt und erforderliche Host-, Laufzeit- und Netzwerkbedingungen dokumentiert.
|
||||
|
||||
## [0.2.0] — 2026-09-10
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 README“高级功能”章节,补充 WebRTC 与中继服务器的配置和使用步骤。
|
||||
- 明确 WebRTC 的 UDP 端口、安全组与防火墙要求,以及中继令牌和管理员控制台配置方式。
|
||||
- 标注中继服务为 WebSpeak 自带实现;同时注明 WebRTC 使用 MIT 许可的 `werift` 依赖,TeamSpeak 连接使用项目维护的 SDK fork。
|
||||
- 细分 TeamSpeak 连接失败原因,服务器需要密码时提示用户输入密码并重试。
|
||||
- 优化管理员历史连接日志:能够追溯时显示具体原因,无法追溯时使用通用失败提示,不猜测历史原因。
|
||||
- 新增正式中继部署模式:中继实例不提供前台和管理员后台,只接受带令牌的网关转发会话。
|
||||
- 管理员可配置多个中继节点,访客可在欢迎页为当前连接选择直连或指定中继。
|
||||
- 修复用户正常断开后被管理员运维日志误显示为“请求失败”的问题。
|
||||
|
||||
### English
|
||||
|
||||
- Added an “Advanced features” section to the README with WebRTC and relay configuration and usage steps.
|
||||
- Documented WebRTC UDP, security-group, and firewall requirements, plus relay-token and administration-console setup.
|
||||
- Clarified that the relay is built into WebSpeak, while WebRTC uses the MIT-licensed `werift` dependency and TeamSpeak connectivity uses the project-maintained SDK fork.
|
||||
- Classified TeamSpeak connection failures and prompt users for a server password with a retry when authentication requires one.
|
||||
- Improved administrator connection history: show a specific reason when available and use a generic failure message when older records cannot be traced, without guessing.
|
||||
- Added a formal relay deployment mode: relay instances expose no visitor or admin UI and accept only token-authenticated gateway sessions.
|
||||
- Administrators can configure multiple relay nodes, and visitors can choose direct access or a specific relay for each connection.
|
||||
- Fixed normal user disconnects being shown as “request failed” in administrator connection history.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Einen Abschnitt „Erweiterte Funktionen“ mit Anleitungen für WebRTC und Relay-Server zur README hinzugefügt.
|
||||
- UDP-, Sicherheitsgruppen- und Firewall-Anforderungen für WebRTC sowie Relay-Token und Administrationskonfiguration dokumentiert.
|
||||
- Klargestellt, dass das Relay Bestandteil von WebSpeak ist; WebRTC verwendet die MIT-lizenzierte Abhängigkeit `werift`, die TeamSpeak-Verbindung den projektgepflegten SDK-Fork.
|
||||
- TeamSpeak-Verbindungsfehler genauer klassifiziert und bei erforderlichem Serverpasswort eine Eingabe mit Wiederholung angeboten.
|
||||
- Den Verlauf der Administrator-Verbindungen verbessert: verfügbare Ursachen werden angezeigt, ältere nicht nachvollziehbare Einträge erhalten eine allgemeine Fehlermeldung statt einer Vermutung.
|
||||
- Einen dedizierten Relay-Bereitstellungsmodus ergänzt: Relay-Instanzen stellen keine Besucher- oder Admin-Oberfläche bereit und akzeptieren nur Gateway-Sitzungen mit Token.
|
||||
- Administratoren können mehrere Relay-Knoten konfigurieren; Besucher wählen pro Verbindung Direktzugriff oder ein bestimmtes Relay.
|
||||
- Behoben, dass normale Benutzertrennungen im Administrationsverlauf als „Anfrage fehlgeschlagen“ erschienen.
|
||||
|
||||
## [0.1.8] — 2026-09-08
|
||||
|
||||
### 中文
|
||||
|
||||
- Docker 默认使用 host 网络,支持网关访问同机 TeamSpeak 并直接暴露 WebRTC UDP 端口。
|
||||
- 开放模式统一校验用户提交的目标地址,包括管理员默认目标,修复本机与内网目标绕过限制的问题。
|
||||
- TeamSpeak SDK 连接握手增加 15 秒超时,失败连接会及时清理。
|
||||
- 网络性能面板改为持续监测,打开后每 3 秒更新一次延迟与丢包率。
|
||||
|
||||
### English
|
||||
|
||||
- Docker now uses host networking by default, allowing the gateway to reach a local TeamSpeak server and expose the WebRTC UDP range directly.
|
||||
- Open access now validates every submitted target, including the administrator default, closing loopback and private-network bypasses.
|
||||
- Added a 15-second TeamSpeak SDK handshake timeout with prompt cleanup after failed connections.
|
||||
- The network performance panel now measures continuously and refreshes latency and packet loss every 3 seconds while open.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Docker verwendet standardmäßig das Host-Netzwerk, damit das Gateway einen lokalen TeamSpeak-Server erreicht und den WebRTC-UDP-Bereich direkt bereitstellt.
|
||||
- Der offene Zugriffsmodus prüft nun jedes Ziel einschließlich des Administrator-Standards und schließt Umgehungen für Loopback- und private Netze.
|
||||
- Für den TeamSpeak-SDK-Handshake gilt jetzt ein Timeout von 15 Sekunden; fehlgeschlagene Verbindungen werden zeitnah bereinigt.
|
||||
- Das Netzwerkleistungsfeld misst bei geöffneter Ansicht fortlaufend und aktualisiert Latenz und Paketverlust alle 3 Sekunden.
|
||||
|
||||
## [0.1.7] — 2026-09-06
|
||||
|
||||
### 中文
|
||||
|
||||
- 增加 Deutsch 界面支持和 Telegram 群组入口。
|
||||
- 增加桌面端整体音量滑块,默认收起并在悬停时展开。
|
||||
- 修复伴奏音量忽大忽小的问题。
|
||||
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
|
||||
- 管理员连接测试改用服务端多次主机 Ping 并显示丢包率,不再创建临时 TeamSpeak 客户端。
|
||||
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
|
||||
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
|
||||
- 移除 WebRTC 桥接中的 RMS 静音帧过滤,安静帧仅用于发言状态指示,不再丢弃。
|
||||
- 修复 Docker 运行环境缺少 ICMP Ping 工具导致管理员测试误报 100% 丢包。
|
||||
|
||||
### English
|
||||
|
||||
- Added German UI support and a Telegram community link.
|
||||
- Added a compact desktop master-volume slider that expands on hover.
|
||||
- Fixed accompaniment volume fluctuations.
|
||||
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
|
||||
- Updated the administrator connection test to use repeated host pings, report packet loss, and avoid creating temporary TeamSpeak clients.
|
||||
- Unified the Chinese, English, and German flag/code language menu.
|
||||
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
|
||||
- Removed RMS-based silence filtering from the WebRTC bridge; quiet frames are now retained for the codec timeline.
|
||||
- Fixed Docker admin diagnostics falsely reporting 100% packet loss when the runtime lacked the ICMP ping tool.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Deutsche Benutzeroberfläche und Telegram-Community-Link hinzugefügt.
|
||||
- Kompakten Gesamtlautstärkeregler für den Desktop ergänzt, der sich beim Überfahren öffnet.
|
||||
- Schwankende Lautstärke bei der Begleittonfreigabe behoben.
|
||||
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
|
||||
- Verbindungstest in der Administration auf wiederholte Host-Pings mit Paketverlustanzeige umgestellt, ohne temporäre TeamSpeak-Clients zu erzeugen.
|
||||
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
|
||||
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
|
||||
- RMS-basierte Stillefilterung aus der WebRTC-Brücke entfernt; leise Frames bleiben nun im Codec-Zeitverlauf erhalten.
|
||||
- Falsche 100-%-Paketverlustmeldungen behoben, wenn dem Docker-Laufzeitimage das ICMP-Ping-Tool fehlte.
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
### English
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections in the same browser.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
## [0.1.5] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
|
||||
## [0.1.4] — 2026-09-03
|
||||
|
||||
@@ -2,12 +2,15 @@ FROM node:22-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git python3 make g++ \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY web/package.json web/package-lock.json ./web/
|
||||
RUN npm ci
|
||||
RUN npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
|
||||
RUN npm run prepare:sdk
|
||||
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
RUN npm --prefix web ci
|
||||
|
||||
COPY . .
|
||||
@@ -20,7 +23,7 @@ FROM node:22-bookworm-slim AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 iputils-ping \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /data \
|
||||
&& chown node:node /data
|
||||
@@ -35,8 +38,8 @@ COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 40000-40099/udp
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"
|
||||
CMD ["sh", "-c", "if [ \"$WEBSPEAK_MODE\" = \"relay\" ]; then node -e \"process.exit(0)\"; else node -e \"fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\"; fi"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
@@ -1,332 +1,97 @@
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
|
||||
[](./LICENSE)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
|
||||
<p>
|
||||
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
|
||||
<a href="./docs/README.en.md">English documentation</a> ·
|
||||
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
|
||||
<a href="./docs/README.ru.md">Русская документация</a> ·
|
||||
<a href="./docs/README.ja.md">日本語ドキュメント</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
## 项目简介 · Overview
|
||||
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
## 文档 · Documentation
|
||||
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
## 社区 · Community
|
||||
|
||||
<div align="center">
|
||||
|
||||
# WebSpeak
|
||||
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
**让 TeamSpeak 真正进入浏览器。**
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
|
||||
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4)
|
||||
[](LICENSE)
|
||||
[](https://www.teamspeak.com/)
|
||||
|
||||
[中文](#中文) · [English](#english) · [更新日志](#更新日志--changelog) · [快速开始](#快速开始--quick-start) · [社区](#社区--community)
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
</div>
|
||||
|
||||
## 中文
|
||||
## 友链项目 · Friend projects
|
||||
|
||||
WebSpeak 是一个面向 TeamSpeak 服务器的浏览器客户端。部署一次,用户通过网页即可加入语音空间,不需要安装 TeamSpeak 桌面客户端。
|
||||
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
|
||||
|
||||
### 功能
|
||||
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
- 支持 TeamSpeak 3 和 TeamSpeak 6,自动识别协议。
|
||||
- 浏览频道、在线成员和实时成员状态。
|
||||
- 加入、切换频道,并显示成员所在频道。
|
||||
- 频道文字聊天、服务器消息、私聊和戳一戳。
|
||||
- 浏览器麦克风和扬声器选择、音量调节、输入电平和本地麦克风测试。
|
||||
- 一键闭麦/开麦、VOX 语音激活、发言状态提示。
|
||||
- 可选 WebRTC 低延迟语音,网络不支持时自动回退。
|
||||
- 固定服务器、开放服务器和一次性邀请链接三种访问方式。
|
||||
- 管理控制台:默认目标、邀请链接、在线会话、日志、诊断和数据库备份。
|
||||
- 中英文界面、主题切换、桌面端和移动端适配。
|
||||
- 移动端提供成员操作菜单,桌面端支持右键菜单。
|
||||
## Contributors · 贡献者
|
||||
|
||||
### 快速开始 · Quick Start
|
||||
感谢提交 PR 的贡献者:
|
||||
|
||||
#### Docker Compose(推荐)
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
|
||||
|
||||
要求:安装 Docker Engine 和 Docker Compose。
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
打开 `http://你的服务器地址:3040/`,首次进入管理后台 `/admin` 使用:
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
|
||||
|
||||
```text
|
||||
账号:admin
|
||||
密码:admin
|
||||
```
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
|
||||
首次登录必须修改管理员密码。然后在管理控制台的“服务器”页面设置“默认 TeamSpeak 目标”,例如:
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
|
||||
```text
|
||||
203.0.113.10#9987
|
||||
```
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
|
||||
用户欢迎页没有邀请链接参数时,会自动使用管理员设置的默认目标。开放模式下,用户可以自行输入要连接的服务器地址和端口。
|
||||
## Star History
|
||||
|
||||
数据会保存在 Docker volume `webspeak-data` 中。升级时执行:
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
|
||||
</a>
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要使用 `docker compose down -v`,否则会删除数据库和管理员配置。
|
||||
|
||||
如需更换网页端口:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```
|
||||
|
||||
#### 源码运行
|
||||
|
||||
需要 Node.js `22.5.0` 或更高版本,以及 `@discordjs/opus` 所需的本地编译工具。
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
服务默认监听 `3040` 端口。
|
||||
|
||||
### WebRTC 低延迟语音
|
||||
|
||||
WebRTC 是可选功能,由 WebSpeak 自带,不需要额外部署媒体服务器。
|
||||
|
||||
1. 在管理后台打开“WebRTC 语音”。
|
||||
2. 在部署主机所在云平台安全组或上游防火墙放行入站 UDP `40000–40099`。
|
||||
3. 重新进入语音空间即可生效。
|
||||
|
||||
Docker Compose 已自动发布 `40000–40099/UDP`,但无法替你修改云安全组。Ubuntu 使用 UFW 时可执行:
|
||||
|
||||
```bash
|
||||
sudo ufw allow 40000:40099/udp
|
||||
```
|
||||
|
||||
网页和 WSS 使用 TCP `80/443`。TeamSpeak 的 `9987` 只需要让 WebSpeak 主机能够访问目标 TeamSpeak,不需要在 WebSpeak 主机对公网开放。WebRTC 不支持或端口未放行时,客户端会自动使用兼容模式。
|
||||
|
||||
### 管理员设置
|
||||
|
||||
管理员可以在控制台中:
|
||||
|
||||
- 修改默认 TeamSpeak 目标和服务器密码。
|
||||
- 选择固定目标或允许用户自定义目标。
|
||||
- 创建、撤销和设置有效期的邀请链接。
|
||||
- 查看在线会话、运行日志、诊断信息和审计记录。
|
||||
- 下载诊断报告和 SQLite 数据库备份。
|
||||
- 开启或关闭 WebRTC 低延迟语音。
|
||||
|
||||
### 浏览器要求
|
||||
|
||||
- 使用较新的 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。
|
||||
- 使用麦克风需要浏览器权限;公网部署建议使用 HTTPS。
|
||||
- 目标 TeamSpeak 服务器必须能被 WebSpeak 主机访问。
|
||||
|
||||
### 更新日志 · Changelog
|
||||
|
||||
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- 修复 WebRTC 语音收发与发言状态同步。
|
||||
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
|
||||
- 优化管理员页面、运行日志换行和移动端顶部布局;新增 Bilibili 入口及登录页返回首页。
|
||||
|
||||
#### 2026-09-03 · v0.1.3
|
||||
|
||||
- 增加可选 WebRTC 低延迟语音。
|
||||
- 支持在管理员页面直接启用 WebRTC,无需额外媒体服务器。
|
||||
- 更新 TeamSpeak 集成,改善频道、成员和实时状态同步。
|
||||
- 优化语音缓冲和连接回退,减少网络抖动造成的延迟堆积。
|
||||
- 公网部署放行 UDP `40000–40099` 后,双浏览器语音测试稳定运行,实测间隔峰值约 `27–83ms`。
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
|
||||
- 大幅优化移动端界面和成员操作。
|
||||
- 首页增加 GitHub、当前版本和更新日志入口。
|
||||
- 修复设置按钮错位,优化窄屏布局和滚动体验。
|
||||
- 增加 AudioWorklet、设备选择和更稳定的语音缓冲处理。
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- 正式提供浏览器客户端、管理控制台、邀请链接和运维功能。
|
||||
- 修复成员同步、私聊断开和频道显示问题。
|
||||
- 增加中英文切换、默认目标、首次登录改密和一键闭麦。
|
||||
- 发布 Windows、Linux 和 Docker 部署方式。
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- 首个规范化版本。
|
||||
|
||||
### 社区 · Community
|
||||
|
||||
QQ群:`869500475`
|
||||
|
||||
加入 QQ 群获取使用帮助、版本更新和交流支持:
|
||||
|
||||

|
||||
|
||||
### 许可证
|
||||
|
||||
WebSpeak 使用 [GNU Affero General Public License v3.0](LICENSE) 发布。
|
||||
|
||||
## English
|
||||
|
||||
WebSpeak is a self-hosted browser client for TeamSpeak 3 and TeamSpeak 6. Deploy it once and let users join voice channels from a browser without installing the desktop TeamSpeak client.
|
||||
|
||||
**Live demo: [webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
### Features
|
||||
|
||||
- TeamSpeak 3 and TeamSpeak 6 support with automatic protocol detection.
|
||||
- Live channel tree, online members, member locations, and status updates.
|
||||
- Channel switching and member presence grouped under the correct channel.
|
||||
- Channel text chat, server messages, private messages, and poke actions.
|
||||
- Browser microphone and speaker selection, volume control, input level, and local microphone test.
|
||||
- One-click microphone mute/unmute, VOX activation, and speaking indicators.
|
||||
- Optional low-latency WebRTC audio with automatic compatibility fallback.
|
||||
- Fixed targets, open targets, and expiring one-time invite links.
|
||||
- Admin console for targets, invites, sessions, logs, diagnostics, and database backups.
|
||||
- Chinese and English UI, theme switching, and responsive desktop/mobile layouts.
|
||||
- Mobile member action menus and desktop context menus.
|
||||
|
||||
### Quick Start
|
||||
|
||||
#### Docker Compose (recommended)
|
||||
|
||||
Requirements: Docker Engine and Docker Compose.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://your-server:3040/`. On the first admin login at `/admin`, use:
|
||||
|
||||
```text
|
||||
Username: admin
|
||||
Password: admin
|
||||
```
|
||||
|
||||
You must change the administrator password after the first login. Then configure the **Default TeamSpeak target** in the **Servers** page, for example:
|
||||
|
||||
```text
|
||||
203.0.113.10#9987
|
||||
```
|
||||
|
||||
If a welcome link does not contain an invite target, the default target is pre-filled automatically. In open mode, users may enter their own TeamSpeak address and port.
|
||||
|
||||
Data is stored in the `webspeak-data` Docker volume. To upgrade:
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`, because it removes the database and administrator settings.
|
||||
|
||||
To change the web host port:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_PORT=3041 docker compose up -d
|
||||
```
|
||||
|
||||
#### Run from source
|
||||
|
||||
Requires Node.js `22.5.0` or newer and native build tools for `@discordjs/opus`.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
The service listens on port `3040` by default.
|
||||
|
||||
### Low-latency WebRTC audio
|
||||
|
||||
WebRTC is optional and bundled with WebSpeak. No separate media server is required.
|
||||
|
||||
1. Enable **WebRTC audio** in the admin console.
|
||||
2. Allow inbound UDP `40000–40099` in the cloud security group or upstream firewall for the WebSpeak host.
|
||||
3. Re-enter the voice space to apply the setting.
|
||||
|
||||
Docker Compose publishes `40000–40099/UDP` automatically, but it cannot change a cloud security group. With Ubuntu UFW:
|
||||
|
||||
```bash
|
||||
sudo ufw allow 40000:40099/udp
|
||||
```
|
||||
|
||||
The web page and WSS signaling use TCP `80/443`. TeamSpeak port `9987` only needs to be reachable from WebSpeak to the target TeamSpeak server; it does not need to be exposed publicly on the WebSpeak host. If WebRTC is unavailable, the client automatically uses the compatibility mode.
|
||||
|
||||
### Administrator settings
|
||||
|
||||
The admin console can:
|
||||
|
||||
- Set the default TeamSpeak target and server password.
|
||||
- Choose a fixed target or allow users to enter their own target.
|
||||
- Create, revoke, expire, and limit invite links.
|
||||
- View online sessions, runtime logs, diagnostics, and audit records.
|
||||
- Download diagnostic reports and SQLite backups.
|
||||
- Enable or disable low-latency WebRTC audio.
|
||||
|
||||
### Browser requirements
|
||||
|
||||
- A recent Chrome, Edge, or another modern browser with WebRTC support.
|
||||
- Microphone permission is required for voice input; HTTPS is recommended for public deployments.
|
||||
- The target TeamSpeak server must be reachable from the WebSpeak host.
|
||||
|
||||
### Changelog
|
||||
|
||||
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- Fixed WebRTC voice transport and speaking-state synchronization.
|
||||
- Fixed channel text messages between WebSpeak clients.
|
||||
- Refined admin pages, log wrapping, and narrow-screen header layout; added Bilibili and admin-login home links.
|
||||
|
||||
#### 2026-09-03 · v0.1.3
|
||||
|
||||
- Added optional low-latency WebRTC audio.
|
||||
- Added an admin switch for WebRTC without requiring a separate media server.
|
||||
- Updated TeamSpeak integration for better channel, member, and realtime status synchronization.
|
||||
- Improved audio buffering and connection fallback to reduce delay growth during network jitter.
|
||||
- After allowing inbound UDP `40000–40099`, a two-browser voice test ran reliably with observed peak gaps of about `27–83 ms`.
|
||||
|
||||
#### 2026-09-02 · v0.1.2
|
||||
|
||||
- Major mobile UI and member-action improvements.
|
||||
- Added GitHub, current-version, and changelog entries to the welcome page.
|
||||
- Fixed settings-button alignment and improved narrow-screen layout and scrolling.
|
||||
- Added AudioWorklet, device selection, and more stable voice buffering.
|
||||
|
||||
#### 2026-09-02 · v0.1.1
|
||||
|
||||
- Official browser client, admin console, invite links, and operations tools.
|
||||
- Fixed member synchronization, private-message disconnects, and channel display issues.
|
||||
- Added Chinese/English switching, default targets, first-login password rotation, and one-click mute.
|
||||
- Added Windows, Linux, and Docker deployment options.
|
||||
|
||||
#### 2026-08-31 · v0.1.0
|
||||
|
||||
- First normalized release.
|
||||
|
||||
### Community
|
||||
|
||||
QQ group: `869500475`
|
||||
|
||||
Join the group for support, release updates, and discussion:
|
||||
|
||||

|
||||
|
||||
### License
|
||||
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0](LICENSE).
|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -3,9 +3,9 @@ services:
|
||||
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
|
||||
pull_policy: missing
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${WEBSPEAK_PORT:-3040}:3040"
|
||||
- "40000-40099:40000-40099/udp"
|
||||
# WebSpeak needs to reach a TeamSpeak server running on the same host.
|
||||
# Host networking also exposes the configured WebRTC UDP range directly.
|
||||
network_mode: host
|
||||
volumes:
|
||||
- webspeak-data:/data
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · Deutsch
|
||||
|
||||
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
|
||||
## Live-Demo
|
||||
|
||||
Adresse: <https://webspeak.example.invalid>
|
||||
|
||||
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
|
||||
## ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
|
||||
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
|
||||
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
|
||||
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
|
||||
### Willkommensseite
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
|
||||
|
||||
### Sprachbereich
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
|
||||
|
||||
### Audiosteuerung
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
|
||||
|
||||
## 🧩 Erweiterte Funktionen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
### 1. WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
1. Unter `/admin` anmelden und auf der Seite **Server** die **Erweiterten Einstellungen** öffnen.
|
||||
2. Bei deaktiviertem WebRTC Start- und Endport für UDP festlegen. Der Standardbereich ist `40000–40099`.
|
||||
3. Den gesamten UDP-Bereich in Sicherheitsgruppe und Firewall des WebSpeak-Hosts freigeben.
|
||||
4. **WebRTC** aktivieren und speichern. Nicht unterstützte Browser oder Netzwerke wechseln automatisch zum kompatiblen Transport.
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niemals das WebSpeak-Gateway. Ohne TURN werden nur direkte ICE-Pfade und STUN verwendet.
|
||||
|
||||
### Plattformübergreifendes P2P-Bildschirmteilen
|
||||
|
||||
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
|
||||
|
||||
### 2. Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder Administrationsseite. Sie akzeptiert nur Gateway-Sitzungen mit passendem Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Aus einem Release-Paket starten
|
||||
|
||||
Das passende Paket aus den [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und entpacken:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Unter Windows PowerShell dieselben Variablen setzen und `.\runtime\node.exe .\dist\index.js` ausführen.
|
||||
|
||||
#### Mit Docker starten
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Den UDP-Listening-Port des Relay-Hosts freigeben, standardmäßig `39087`.
|
||||
|
||||
#### Im Gateway aktivieren
|
||||
|
||||
1. **Administration → Server → Relay-Server** öffnen und einen oder mehrere Knoten hinzufügen.
|
||||
2. Für jeden Knoten einen Anzeigenamen, einen Endpunkt wie `relay.example.com#39087` und das passende Token eintragen und speichern.
|
||||
3. Besucher können auf der Willkommensseite Direktzugriff oder einen konfigurierten Relay-Knoten auswählen.
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen.
|
||||
|
||||
### 3. Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
|
||||
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
|
||||
|
||||
## 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt; ILLUSIA-Sprachillustration verkleinert und rechts unten verankert, damit Mitglieder und geteilte Videos sichtbar bleiben. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Verbindungsfehler auf der Willkommensseite verbessert, Fehlercodes erhalten und sicher gekürzt sowie IPv6-Ziele standardmäßig unterstützt. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Passwortabfrage, dedizierter Relay-Modus, Auswahl mehrerer Relays und Ursachendarstellung in der Administration ergänzt. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker-Bereitstellung vereinfacht, lokale TeamSpeak-Ziele unterstützt, 15-Sekunden-Timeout ergänzt und kontinuierliche Netzwerküberwachung eingeführt. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsch, Telegram, Netzwerkleistung und Gesamtlautstärke ergänzt; Lautstärkeschwankungen beim Begleitton behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur gespeicherten Identität und Website-Symbol ergänzt; WebRTC-Mitgliederlautstärke korrigiert. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansicht verbessert. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Bereitstellung
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip` oder `linux-x64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen, in ein eigenes Verzeichnis entpacken und `start-webspeak.cmd` bzw. `./start-webspeak.sh` starten. Die Pakete enthalten Node.js und Produktionsabhängigkeiten.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
## ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · English
|
||||
|
||||
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
|
||||
## Live demo
|
||||
|
||||
URL: <https://webspeak.example.invalid>
|
||||
|
||||
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
|
||||
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
|
||||
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options are provided. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
|
||||
### Welcome page
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
|
||||
|
||||
### Voice workspace
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
|
||||
|
||||
### Audio controls
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
|
||||
|
||||
### Member menu
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
|
||||
|
||||
## 🧩 Advanced features
|
||||
|
||||
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
### 1. WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
1. Sign in at `/admin` and open **Advanced settings** on the **Servers** page.
|
||||
2. While WebRTC is disabled, choose the UDP start and end ports. The default range is `40000–40099`.
|
||||
3. Allow the complete UDP range in the WebSpeak host's security group and firewall.
|
||||
4. Enable **WebRTC** and save. New visitors will negotiate WebRTC; unsupported browsers and networks fall back to the compatibility transport.
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
Screen-share media still prefers a direct browser-to-browser path; WebSpeak only relays negotiation signaling. By default it uses TeamSpeak's public STUN services to discover server-reflexive candidates; STUN does not carry media. If the deployment has an authorized external TURN service, set `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` before starting WebSpeak with a JSON array, for example:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
With TURN configured, media may use that external TURN service but never the WebSpeak gateway; without it, only direct ICE paths and STUN are used.
|
||||
|
||||
### Cross-platform P2P screen sharing
|
||||
|
||||
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
|
||||
|
||||
### 2. Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
A relay instance is a dedicated forwarding service with no visitor page or administration console. It accepts only gateway sessions with a matching token. Use a random token of at least 16 characters.
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Run from a release package
|
||||
|
||||
Download and extract the appropriate package from [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest):
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
On Windows PowerShell, set the same variables and run `.\runtime\node.exe .\dist\index.js`.
|
||||
|
||||
#### Run with Docker
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port, `39087` by default.
|
||||
|
||||
#### Enable it in the gateway
|
||||
|
||||
1. Open **Administration → Servers → Relay server** and add one or more nodes.
|
||||
2. Set a custom display name, endpoint such as `relay.example.com#39087`, and matching token for each node, then save.
|
||||
3. Visitors can choose direct access or one of the configured relays on the welcome page.
|
||||
|
||||
Disable and save the relay configuration to remove the relay option from the welcome page.
|
||||
|
||||
### 3. Dependencies and attribution
|
||||
|
||||
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
|
||||
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
|
||||
|
||||
## 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill; reduced and anchored the ILLUSIA voice artwork to avoid covering members or shared video. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Improved welcome-page connection errors, preserved and safely truncated error codes, and added default IPv6 target support. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Added server-password prompts, formal relay mode, multiple relay selection, and administrator connection-reason reporting. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Simplified Docker deployment, supported local TeamSpeak targets, added a 15-second connection timeout, and made network monitoring continuous. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German, Telegram, network performance, and master-volume features; fixed accompaniment volume fluctuation. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed WebRTC member volume. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme toggle. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC and channel chat and refined administration, logs, and mobile layouts. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering. |
|
||||
|
||||
See the complete history in [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database and administrator settings.
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), extract it into a dedicated directory, and run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux. Packages include the Node.js runtime and production dependencies.
|
||||
|
||||
### From source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
## ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
@@ -0,0 +1,150 @@
|
||||
# WebSpeak · 日本語
|
||||
|
||||
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
|
||||
|
||||
## プロジェクト概要
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
|
||||
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
|
||||
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
アドレス: <https://webspeak.example.invalid>
|
||||
|
||||
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
|
||||
## ✨ 機能
|
||||
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
|
||||
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
|
||||
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
|
||||
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
### WebRTC
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
|
||||
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
|
||||
|
||||
## 🚀 デプロイ
|
||||
|
||||
| 方法 | 用途 |
|
||||
| --- | --- |
|
||||
| Docker Compose | 常時稼働サーバーと簡単な更新 |
|
||||
| Release パッケージ | Node.js やビルドツールを使わない起動 |
|
||||
| ソースから | 開発やカスタマイズ |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から Windows x64 または Linux x64 のパッケージを取得し、専用フォルダーに展開して `start-webspeak.cmd` または `./start-webspeak.sh` を実行します。
|
||||
|
||||
### ソースから
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
|
||||
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
|
||||
- IPv6 にはルーティング可能な IPv6、OS/コンテナで有効な IPv6、適切なファイアウォール設定が必要です。リテラルは `[2001:db8::1]#9987` の形式です。
|
||||
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
|
||||
- BGM共有はデスクトップのみで、WebRTC が必要です。
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
|
||||
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
|
||||
|
||||
## 🧾 更新履歴
|
||||
|
||||
| バージョン | 内容 |
|
||||
| --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加し、音声アクティビティの立ち絵を縮小して右下に固定し、メンバーや共有動画を隠さないようにしました。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 接続エラー表示を改善し、IPv6 接続先を標準対応しました。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | パスワード案内、正式な中継モード、複数中継選択、接続診断を追加しました。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。 |
|
||||
|
||||
完全な履歴は [CHANGELOG.md](../CHANGELOG.md) を参照してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
@@ -0,0 +1,150 @@
|
||||
# WebSpeak · Русский
|
||||
|
||||
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
|
||||
|
||||
## О проекте
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
|
||||
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
|
||||
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адрес: <https://webspeak.example.invalid>
|
||||
|
||||
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
|
||||
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
|
||||
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
|
||||
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
### WebRTC
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
|
||||
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
|
||||
|
||||
## 🚀 Развертывание
|
||||
|
||||
| Способ | Подходит для |
|
||||
| --- | --- |
|
||||
| Docker Compose | Постоянного сервера и простых обновлений |
|
||||
| Пакет Release | Запуска без Node.js и инструментов сборки |
|
||||
| Из исходников | Разработки и настройки проекта |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет Windows x64 или Linux x64 из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), распакуйте в отдельную папку и запустите `start-webspeak.cmd` или `./start-webspeak.sh`.
|
||||
|
||||
### Из исходников
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
|
||||
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
|
||||
- Для IPv6 нужен маршрутизируемый IPv6, включённый IPv6 в ОС/контейнере и правила firewall. Литерал задаётся как `[2001:db8::1]#9987`.
|
||||
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
|
||||
- Фоновая музыка доступна только на компьютере и требует WebRTC.
|
||||
|
||||
## Сообщество и проекты
|
||||
|
||||
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
|
||||
|
||||
## 🧾 История изменений
|
||||
|
||||
| Версия | Изменения |
|
||||
| --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill; иллюстрация ILLUSIA уменьшена и закреплена справа внизу, чтобы не перекрывать участников и видео. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | Улучшены ошибки на странице входа и добавлена поддержка IPv6-целей по умолчанию. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | Добавлены подсказки пароля, режим ретранслятора, выбор нескольких узлов и диагностика подключений. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг. |
|
||||
|
||||
Полная история находится в [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
@@ -0,0 +1,245 @@
|
||||
# WebSpeak · 简体中文
|
||||
|
||||
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
地址:<https://webspeak.example.invalid>
|
||||
|
||||
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
|
||||
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
### 欢迎页
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
|
||||
|
||||
### 语音工作区
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
|
||||
|
||||
### 音量控制
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
|
||||
|
||||
### 成员菜单
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
|
||||
|
||||
## 🧩 高级功能
|
||||
|
||||
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
### 1. WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
1. 登录 `/admin`,打开“服务器”页的“高级参数”。
|
||||
2. 关闭 WebRTC 时设置 UDP 起止端口,默认范围为 `40000–40099`。
|
||||
3. 在 WebSpeak 主机的安全组和防火墙中放行整个 UDP 范围。
|
||||
4. 勾选“启用 WebRTC”并保存,用户重新进入后即可协商;不支持时会回退到兼容传输。
|
||||
|
||||
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
屏幕共享媒体仍优先走浏览器之间的直连,WebSpeak 只转发协商信令。默认使用 TeamSpeak 官方 STUN 服务发现公网候选地址;STUN 不承载媒体。若部署者有合规的外部 TURN 服务,可在启动 WebSpeak 前设置 `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS`,值为 JSON 数组,例如:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
配置 TURN 后,媒体可能经过该外部 TURN 服务,但不会经过 WebSpeak 网关;未配置时只使用直连和 STUN。
|
||||
|
||||
### 跨端 P2P 屏幕共享
|
||||
|
||||
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
|
||||
|
||||
### 2. 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### 发布包启动
|
||||
|
||||
从 [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载并解压对应平台的包:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell 使用同名环境变量后运行 `.\runtime\node.exe .\dist\index.js`。
|
||||
|
||||
#### Docker 启动
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
放行中继主机的 UDP 监听端口,默认是 `39087`。
|
||||
|
||||
#### 在网关中启用
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写自定义名称、地址(例如 `relay.example.com#39087`)和匹配令牌并保存。
|
||||
3. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
|
||||
### 3. 依赖与归属
|
||||
|
||||
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
|
||||
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
|
||||
- TeamSpeak 协议使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork。
|
||||
|
||||
## 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill;缩小 ILLUSIA 语音立绘并固定在右下角,避免遮挡成员与共享画面。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | 优化首页连接错误显示,保留并安全截断错误代码;默认支持 IPv6 TeamSpeak 目标。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 增加服务器密码提示、正式中继部署模式、多中继选择和管理员日志原因显示。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | 简化 Docker 部署,支持同机 TeamSpeak,增加 15 秒连接超时和持续网络监测。 |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语、Telegram、网络性能面板和整体音量;修复伴奏音量波动。 |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 增加桌面端伴奏、身份保持提醒和网站图标;修复 WebRTC 成员独立音量。 |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保存逻辑并优化主题切换。 |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC、频道聊天并优化管理页、日志和移动端布局。 |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | 引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](../CHANGELOG.md)。
|
||||
|
||||
## 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载对应的 `windows-x64.zip` 或 `linux-x64.tar.gz`,解压后运行 Windows 的 `start-webspeak.cmd` 或 Linux 的 `./start-webspeak.sh`。发布包自带 Node.js 运行时和生产依赖。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
## ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
@@ -0,0 +1,249 @@
|
||||
# WebSpeak 皮肤开发规范
|
||||
|
||||
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
|
||||
|
||||
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
|
||||
|
||||
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
|
||||
|
||||
## 使用与发布
|
||||
|
||||
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
|
||||
```text
|
||||
manifest.json # 必需:身份、版本与入口
|
||||
skin.css # 必需:皮肤样式
|
||||
content.json # 可选:首页内容与多语言界面文案
|
||||
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
```
|
||||
|
||||
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
|
||||
|
||||
### `manifest.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.25",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A visual-only art skin using the WebSpeak interface translations.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | 当前必须为数字 `1`。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
|
||||
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
|
||||
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
|
||||
| `description` | 可选,最多 400 个字符。 |
|
||||
|
||||
清单不得重复声明同一个文件为 CSS、内容或预览入口。
|
||||
|
||||
## 首页内容和文案
|
||||
|
||||
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"home": {
|
||||
"eyebrow": "A room of your own",
|
||||
"title": "Talk",
|
||||
"titleAccent": "together",
|
||||
"description": "Join a voice room from your browser.",
|
||||
"welcomeTitle": "Join the room",
|
||||
"welcomeDescription": "Choose a name and connect.",
|
||||
"features": [
|
||||
{ "title": "Clear voice", "description": "Low-latency Opus audio." }
|
||||
]
|
||||
},
|
||||
"messages": {
|
||||
"home.connect": "Enter the room",
|
||||
"voice.activity-heading": "Voice activity",
|
||||
"demo.heroLead": "A preview customized by this skin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。
|
||||
|
||||
`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。
|
||||
|
||||
管理后台的文字不读取皮肤包,不能通过 `messages` 修改。
|
||||
|
||||
## CSS 皮肤接口
|
||||
|
||||
### 自动隔离
|
||||
|
||||
运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内:
|
||||
|
||||
```css
|
||||
/* 选择器必须使用公开的页面/部件钩子;运行时再加上皮肤根作用域。 */
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid var(--skin-accent);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`:
|
||||
|
||||
```css
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"]
|
||||
```
|
||||
|
||||
也可以写 `:root { --skin-accent: ... }` 设置皮肤自己的变量;`:root` 会被转换成当前皮肤根。选择器必须包含 `:root`、`[data-ws-page]` 或 `[data-ws-part]`。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。自定义变量名必须使用 `--skin-` 前缀,不能覆盖 WebSpeak 的内部令牌。
|
||||
|
||||
页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`open`、`closed`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。
|
||||
|
||||
### 已发布的部件名称
|
||||
|
||||
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
|
||||
|
||||
| 页面区域 | `data-ws-part` |
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
`voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。
|
||||
|
||||
`voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。
|
||||
|
||||
皮肤与语言选择器的触发按钮、菜单和每个选项都提供上述通用部件钩子。`skin.option` 另带有 `data-ws-skin-id`(内置项为 `builtin.light`、`builtin.dark` 和 `community.illusia-voice`,实例皮肤项为其清单 ID);`language.option` 带有 `data-ws-language`。皮肤可以据此只装饰自己的选择项,而不影响其他皮肤、语言选项或选择器交互。例如:
|
||||
|
||||
```css
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
background-image: linear-gradient(110deg, #efffff, #c8f3f2);
|
||||
}
|
||||
```
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-page-bg: #091317;
|
||||
--skin-panel: #142329;
|
||||
--skin-text: #edf8f5;
|
||||
--skin-muted: #9db5af;
|
||||
--skin-accent: #47dcc4;
|
||||
--skin-card-radius: 20px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: var(--skin-card-radius);
|
||||
box-shadow: 0 18px 50px #0008, inset 0 0 0 1px color-mix(in srgb, var(--skin-accent) 50%, transparent);
|
||||
}
|
||||
```
|
||||
|
||||
`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例:
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "ILLUSIA Sans";
|
||||
src: url("assets/illusia-sans.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
[data-ws-page="voice"] { font-family: "ILLUSIA Sans", sans-serif; }
|
||||
```
|
||||
|
||||
字体必须随包附带并拥有可再分发许可。自定义字体可能改变不同语言的字宽,因此校验器会给出提示;发布前必须检查中文、英语、德语、俄语和日语下的标题、按钮和长文案是否仍完整可读。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。
|
||||
|
||||
### 固定布局与交互边界
|
||||
|
||||
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
|
||||
|
||||
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
|
||||
|
||||
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
|
||||
|
||||
## 安全边界和限制
|
||||
|
||||
校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下:
|
||||
|
||||
| 项目 | 上限 |
|
||||
| --- | ---: |
|
||||
| ZIP `.wskin` | 20 MiB |
|
||||
| 解压总大小 | 50 MiB |
|
||||
| ZIP 条目数 | 128 |
|
||||
| 单个 CSS 文件 | 512 KiB |
|
||||
| `content.json` | 256 KiB |
|
||||
| 单张图片(包括预览) | 16 MiB |
|
||||
| 单个 WOFF2 字体 | 4 MiB |
|
||||
| 每实例皮肤数 | 50 |
|
||||
| 每实例皮肤包总存储 | 200 MiB |
|
||||
|
||||
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
|
||||
|
||||
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
|
||||
|
||||
```css
|
||||
[data-ws-part="home.hero.eyebrow"]
|
||||
[data-ws-part="home.gateway-status"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.visitors"]
|
||||
[data-ws-part="voice.activity-heading"]
|
||||
[data-ws-part="voice.member.avatar"]
|
||||
[data-ws-part="voice.member.live-indicator"]
|
||||
[data-ws-part="voice.member-row.avatar"]
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"]
|
||||
[data-ws-part="voice.screen-player.live"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="demo.note"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
## 制作与验收
|
||||
|
||||
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
|
||||
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
|
||||
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
|
||||
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
|
||||
Rename-Item .\illusia-voice.zip illusia-voice.wskin
|
||||
```
|
||||
|
||||
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
|
||||
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
|
||||
|
||||
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
|
||||
@@ -0,0 +1,14 @@
|
||||
# ILLUSIA风
|
||||
|
||||
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
|
||||
|
||||
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
|
||||
|
||||
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
|
||||
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
|
||||
```
|
||||
|
||||
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
|
||||
|
After Width: | Height: | Size: 1014 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 358 KiB |
|
After Width: | Height: | Size: 738 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 85 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.27",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.5"
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
/* ILLUSIA风: bright glass surfaces, cyan accents, and project artwork. */
|
||||
:root {
|
||||
--skin-illusia-ink: #123849;
|
||||
--skin-illusia-muted: #4f6974;
|
||||
--skin-illusia-teal: #087e86;
|
||||
--skin-illusia-aqua: #47c9d4;
|
||||
--skin-illusia-glass: rgba(250, 254, 255, .96);
|
||||
--skin-illusia-line: rgba(115, 205, 218, .38);
|
||||
--skin-illusia-shadow: 0 20px 56px rgba(29, 91, 113, .16);
|
||||
}
|
||||
|
||||
/* Homepage uses the full-resolution original-character composition. */
|
||||
[data-ws-part="home"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image:
|
||||
radial-gradient(ellipse at 14% 78%, rgba(90, 222, 230, .28), transparent 34%),
|
||||
radial-gradient(ellipse at 83% 21%, rgba(94, 190, 255, .24), transparent 30%),
|
||||
radial-gradient(ellipse at 52% 56%, rgba(190, 239, 255, .16), transparent 42%),
|
||||
linear-gradient(90deg, rgba(246, 252, 255, .91) 0%, rgba(246, 252, 255, .82) 33%, rgba(246, 252, 255, .32) 60%, rgba(246, 252, 255, .08) 100%),
|
||||
url("assets/background-composite.webp");
|
||||
background-position: 0% 100%, 100% 0%, 50% 50%, center, center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 132% 130%, 122% 124%, 116% 116%, cover, cover;
|
||||
animation: illusia-home-aura 18s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes illusia-home-aura {
|
||||
from { background-position: 0% 100%, 100% 0%, 50% 50%, center, center; }
|
||||
to { background-position: 20% 82%, 78% 18%, 55% 45%, center, center; }
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] {
|
||||
border-color: rgba(255, 255, 255, .85);
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, .8), rgba(255, 255, 255, .45));
|
||||
box-shadow: 0 26px 80px rgba(78, 150, 173, .17), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
backdrop-filter: blur(22px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .76);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .84);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"]:hover {
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
/* ARIA selectors raise specificity over component defaults without private classes. */
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .46);
|
||||
background-image: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
|
||||
background-position: 0% 50%;
|
||||
background-size: 240% 100%;
|
||||
box-shadow: 0 4px 14px rgba(30, 170, 184, .17), inset 0 0 0 1px rgba(255, 255, 255, .86);
|
||||
animation: illusia-option-gradient 8s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] > :first-child {
|
||||
color: #07858a;
|
||||
filter: drop-shadow(0 0 5px rgba(71, 201, 212, .54));
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"][aria-selected="true"] {
|
||||
color: #056e76;
|
||||
border-color: rgba(44, 186, 197, .7);
|
||||
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 5px 18px rgba(30, 170, 184, .23), inset 0 0 0 1px rgba(255, 255, 255, .94);
|
||||
}
|
||||
|
||||
@keyframes illusia-option-gradient {
|
||||
from { background-position: 0% 50%; }
|
||||
to { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="language.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"]:hover,
|
||||
[data-ws-part="language.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="language.option"][role="option"][aria-selected="true"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][role="option"][aria-selected="true"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .82);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] strong,
|
||||
[data-ws-part="home.hero.title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] small,
|
||||
[data-ws-part="home.hero.description"],
|
||||
[data-ws-part="home.join-description"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.title"] em {
|
||||
color: var(--skin-illusia-teal);
|
||||
text-shadow: 0 8px 28px rgba(47, 192, 202, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.eyebrow"] {
|
||||
color: #087a76;
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] {
|
||||
border-color: rgba(255, 255, 255, .94);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, .79);
|
||||
box-shadow: 0 14px 28px rgba(68, 158, 173, .12), inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] > span:first-child {
|
||||
box-shadow: 0 5px 14px rgba(43, 157, 167, .12), inset 0 0 0 1px rgba(255, 255, 255, .56);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] b {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] small {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] {
|
||||
color: #075c67;
|
||||
border-color: var(--skin-illusia-line);
|
||||
background-color: rgba(247, 254, 255, .9);
|
||||
background-image: linear-gradient(105deg, rgba(247, 254, 255, .98), rgba(237, 252, 253, .84));
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 10px 28px rgba(19, 142, 157, .14), inset 0 0 0 1px rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(14px) saturate(1.12);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) {
|
||||
color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/visitor-avatar.webp");
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 0 0 3px rgba(71, 201, 212, .26), 0 5px 16px rgba(19, 142, 157, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) svg {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:last-child {
|
||||
color: #41bdcc;
|
||||
text-shadow: 0 0 12px rgba(71, 201, 212, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .9);
|
||||
border-radius: 26px;
|
||||
background-color: var(--skin-illusia-glass);
|
||||
background-image: url("assets/banner-mascot-blob.webp");
|
||||
background-position: right 18px top 10px;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 96px 68px;
|
||||
box-shadow: var(--skin-illusia-shadow), 0 0 15px rgba(71, 201, 212, .14), inset 0 0 0 1px rgba(255, 255, 255, .84);
|
||||
backdrop-filter: blur(22px);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] {
|
||||
color: #47c9d4;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] i {
|
||||
box-shadow: 0 0 8px rgba(71, 201, 212, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] {
|
||||
color: rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] i {
|
||||
box-shadow: 0 0 12px rgba(71, 201, 212, .16);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] {
|
||||
color: #4f6974;
|
||||
border-color: rgba(134, 190, 200, .42);
|
||||
border-radius: 12px;
|
||||
background: rgba(232, 244, 247, .96);
|
||||
box-shadow: inset 0 0 0 1px rgba(134, 190, 200, .24);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input::placeholder {
|
||||
color: #8ba4aa;
|
||||
}
|
||||
|
||||
[data-ws-part="home.field-label"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"] {
|
||||
color: #fff;
|
||||
border-radius: 14px;
|
||||
background-color: var(--skin-illusia-teal);
|
||||
background:
|
||||
url("assets/button-mascot.webp") right 4px center / 112px 74px no-repeat,
|
||||
linear-gradient(100deg, #38d6d0 0%, #0c9caf 62%, #08788d 100%) center / cover no-repeat;
|
||||
box-shadow: 0 12px 22px rgba(16, 181, 192, .24), inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 0 0 1px rgba(141, 255, 255, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"]:hover {
|
||||
background-color: #087078;
|
||||
box-shadow: 0 14px 30px rgba(8, 126, 134, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="home.security-note"],
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/footer-wave.png");
|
||||
background-position: center top;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 58px;
|
||||
box-shadow: none;
|
||||
backdrop-filter: blur(8px) saturate(1.04);
|
||||
}
|
||||
|
||||
/* Voice room: let the artwork flow through the UI instead of stacking opaque cards. */
|
||||
:root {
|
||||
--skin-room-line: rgba(76, 176, 193, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.shell"] {
|
||||
color-scheme: light;
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #dff4f8;
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.55px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 188px, rgba(71, 201, 212, .13) 189px 190px, transparent 191px 229px, rgba(71, 201, 212, .09) 230px 231px, transparent 232px),
|
||||
radial-gradient(ellipse at 13% 5%, rgba(107, 226, 232, .2), transparent 36%),
|
||||
linear-gradient(125deg, rgba(229, 248, 251, .19), rgba(239, 251, 253, .06) 48%, rgba(190, 235, 242, .22)),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: 0 0, right top, left top, center, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, 560px 450px, auto, auto, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.workspace"] {
|
||||
background: linear-gradient(145deg, rgba(239, 251, 253, .22), rgba(218, 244, 248, .12) 48%, rgba(245, 253, 254, .2));
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
border-color: rgba(113, 211, 222, .62);
|
||||
border-radius: 24px;
|
||||
background-color: rgba(227, 247, 250, .64);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 82% 48%, rgba(91, 215, 224, .19), rgba(91, 215, 224, .04) 34%, transparent 65%),
|
||||
linear-gradient(90deg, rgba(230, 248, 251, .78), rgba(230, 248, 251, .36) 38%, rgba(230, 248, 251, .08) 72%),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: right 5% center, center, center 48%;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 48% 100%, 100% 100%, cover;
|
||||
box-shadow: 0 15px 38px rgba(30, 111, 132, .13), inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
backdrop-filter: blur(10px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: url("assets/banner-character-main.webp");
|
||||
background-position: right 16px bottom 8px;
|
||||
background-size: auto 150px;
|
||||
filter: drop-shadow(0 18px 22px rgba(30, 113, 134, .2));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.header"] {
|
||||
border-color: rgba(126, 191, 203, .36);
|
||||
background: linear-gradient(105deg, rgba(249, 254, 255, .76), rgba(222, 246, 250, .57) 56%, rgba(247, 253, 254, .72));
|
||||
box-shadow: 0 8px 28px rgba(27, 92, 112, .08), inset 0 1px 0 rgba(255, 255, 255, .62);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: var(--skin-room-line);
|
||||
background-color: rgba(221, 245, 249, .66);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(25, 145, 161, .065) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 86px, rgba(71, 201, 212, .16) 87px 88px, transparent 89px 119px, rgba(71, 201, 212, .1) 120px 121px, transparent 122px),
|
||||
radial-gradient(ellipse at 100% 0%, rgba(107, 226, 232, .2), transparent 43%),
|
||||
linear-gradient(155deg, rgba(248, 254, 255, .75), rgba(222, 246, 249, .58) 48%, rgba(213, 241, 246, .7));
|
||||
background-position: 0 0, right top, right top, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 360px 320px, auto, auto;
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
/* Keep the headset as an independent foreground object instead of flattening
|
||||
it into the member rail's background. Its slight perspective and shadow
|
||||
make it sit in front of the room, while the actual controls remain above it. */
|
||||
[data-ws-part="voice.member-panel"]::before {
|
||||
background-image: url("assets/foreground-headphone.webp");
|
||||
background-position: left bottom;
|
||||
background-repeat: no-repeat;
|
||||
background-size: contain;
|
||||
filter: drop-shadow(16px 18px 17px rgba(36, 105, 119, .24));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] {
|
||||
color: #4f7982;
|
||||
border-color: rgba(103, 186, 198, .28);
|
||||
background: linear-gradient(110deg, rgba(232, 249, 251, .86), rgba(216, 242, 247, .68));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .58);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input::placeholder {
|
||||
color: #78979d;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"] {
|
||||
border-color: rgba(8, 126, 134, .32);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"][data-ws-state="current"] {
|
||||
border-color: rgba(8, 126, 134, .48);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"] {
|
||||
color: #386b75;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(100deg, rgba(223, 246, 249, .68), rgba(237, 250, 251, .34));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"][data-ws-state="current"] {
|
||||
color: #087e86;
|
||||
background: linear-gradient(100deg, rgba(179, 235, 239, .78), rgba(224, 248, 249, .5));
|
||||
box-shadow: inset 3px 0 0 rgba(37, 175, 188, .74);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"] {
|
||||
border-radius: 11px;
|
||||
transition: background .16s ease, box-shadow .16s ease;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"]:hover,
|
||||
[data-ws-part="voice.member-row"][data-ws-state="speaking"] {
|
||||
background: linear-gradient(100deg, rgba(198, 240, 243, .38), rgba(238, 251, 252, .28));
|
||||
box-shadow: inset 0 0 0 1px rgba(92, 190, 202, .16);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member"] {
|
||||
border-color: rgba(91, 184, 198, .36);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(222, 246, 249, .7);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 100% 0%, rgba(102, 220, 226, .24), transparent 62%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .72), rgba(224, 246, 249, .62) 56%, rgba(210, 241, 246, .66));
|
||||
box-shadow: 0 12px 32px rgba(31, 99, 123, .12), inset 0 1px 0 rgba(255, 255, 255, .76);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .8);
|
||||
outline-offset: 4px;
|
||||
box-shadow: 0 0 24px rgba(71, 201, 212, .28);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.live-indicator"] {
|
||||
color: #08706f;
|
||||
border-radius: 999px;
|
||||
background: rgba(237, 255, 251, .96);
|
||||
box-shadow: 0 6px 20px rgba(42, 160, 162, .18), inset 0 0 0 1px rgba(71, 201, 212, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(116, 194, 205, .42);
|
||||
border-radius: 22px;
|
||||
background-color: rgba(222, 246, 249, .8);
|
||||
background-image:
|
||||
radial-gradient(circle at 0% 100%, transparent 0 35px, rgba(71, 201, 212, .16) 36px 37px, transparent 38px 57px, rgba(71, 201, 212, .1) 58px 59px, transparent 60px),
|
||||
linear-gradient(125deg, rgba(250, 255, 255, .76), rgba(222, 246, 249, .68) 55%, rgba(205, 238, 244, .76));
|
||||
box-shadow: 0 12px 34px rgba(28, 91, 111, .16), inset 0 1px 0 rgba(255, 255, 255, .74);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat"] {
|
||||
border-color: rgba(100, 184, 198, .34);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(221, 245, 249, .58);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .055) 1px, transparent 1.5px),
|
||||
radial-gradient(ellipse at 0% 100%, rgba(102, 220, 226, .16), transparent 42%),
|
||||
linear-gradient(145deg, rgba(249, 254, 255, .72), rgba(226, 247, 250, .48) 52%, rgba(214, 242, 247, .62));
|
||||
background-position: 0 0, left bottom, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, auto, auto;
|
||||
backdrop-filter: blur(14px) saturate(1.05);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"] {
|
||||
color: #547780;
|
||||
border-color: rgba(95, 180, 193, .24);
|
||||
background: linear-gradient(115deg, rgba(242, 252, 253, .72), rgba(217, 243, 247, .56));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"]:hover,
|
||||
[data-ws-part="voice.chat.tab"][data-ws-state="active"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .48);
|
||||
background: linear-gradient(115deg, rgba(207, 242, 245, .86), rgba(232, 250, 251, .72));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .76), rgba(228, 247, 250, .38) 52%, rgba(205, 240, 245, .26)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 10px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .68), rgba(228, 247, 250, .34) 50%, rgba(205, 240, 245, .08)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::before {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
border-radius: 50%;
|
||||
background-color: rgba(250, 255, 255, .66);
|
||||
background-image:
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px);
|
||||
background-position: 12px 16px, 22px 12px, 32px 9px;
|
||||
background-repeat: no-repeat;
|
||||
box-shadow: 0 3px 8px rgba(48, 115, 132, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::after {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
background: rgba(250, 255, 255, .7);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > strong,
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > span {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] {
|
||||
color: #587a82;
|
||||
border-color: rgba(78, 176, 191, .38);
|
||||
background: linear-gradient(120deg, rgba(223, 247, 249, .68), rgba(235, 250, 251, .42));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] strong {
|
||||
color: #315c66;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #315360;
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .78), rgba(216, 243, 247, .68));
|
||||
box-shadow: 0 4px 14px rgba(34, 117, 136, .08), inset 0 0 0 1px rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message"][data-ws-state="mine"] [data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #fff;
|
||||
background: linear-gradient(130deg, #0b9da1, #087985);
|
||||
box-shadow: 0 5px 16px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] h2,
|
||||
[data-ws-part="voice.chat.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] span,
|
||||
[data-ws-part="voice.chat.heading"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.name"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
/* These controls use the active day/night palette by default. Give them the
|
||||
same readable glass treatment as the rest of this intentionally bright skin. */
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(249, 253, 255, .9);
|
||||
box-shadow: 0 5px 16px rgba(29, 91, 113, .1), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"][aria-expanded="true"] {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .72);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .4);
|
||||
background-color: rgba(223, 246, 249, .96);
|
||||
background-image:
|
||||
radial-gradient(circle at 100% 0%, rgba(71, 201, 212, .16), transparent 52%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .96), rgba(224, 246, 249, .94));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] small,
|
||||
[data-ws-part="voice.performance.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .36);
|
||||
background: rgba(232, 247, 248, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] span,
|
||||
[data-ws-part="voice.performance.metrics"] article,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(115, 205, 218, .28);
|
||||
background: linear-gradient(135deg, rgba(232, 248, 250, .88), rgba(212, 241, 245, .72));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] strong,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] small,
|
||||
[data-ws-part="voice.performance.metrics"] span,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] small,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .4);
|
||||
background: rgba(221, 246, 247, .86);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"],
|
||||
[data-ws-part="voice.audio-dock.output-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(221, 246, 249, .96));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"] strong,
|
||||
[data-ws-part="voice.audio-dock.output-panel"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] {
|
||||
background: linear-gradient(110deg, rgba(249, 254, 255, .82), rgba(225, 247, 250, .76) 58%, rgba(214, 242, 247, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(115, 205, 218, .32), 0 5px 18px rgba(36, 130, 148, .07);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"]:focus-within {
|
||||
background: linear-gradient(110deg, rgba(250, 255, 255, .9), rgba(211, 242, 246, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(71, 201, 212, .55), 0 6px 20px rgba(36, 130, 148, .11);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input::placeholder {
|
||||
color: #718b92;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] button[data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .18);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
box-shadow: 0 5px 13px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"] {
|
||||
color: #086b72;
|
||||
border-color: rgba(71, 201, 212, .45);
|
||||
background: rgba(237, 252, 251, .96);
|
||||
box-shadow: 0 3px 10px rgba(29, 120, 130, .12);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #064f59;
|
||||
border-color: rgba(8, 126, 134, .58);
|
||||
background: rgba(219, 247, 246, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"][data-ws-state="viewing"] {
|
||||
color: #fff;
|
||||
border-color: #087e86;
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.stop-share"] {
|
||||
color: #a43e48;
|
||||
border-color: rgba(255, 255, 255, .96);
|
||||
background: #fff6f5;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(250, 254, 255, .98);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] p,
|
||||
[data-ws-part="voice.screen-share-settings.fields"] label,
|
||||
[data-ws-part="voice.screen-share-settings.note"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] select {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(235, 247, 248, .94);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: rgba(232, 247, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.actions"] [data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .2);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
background-position: 0 0, right 8px center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-position: right 1% center, center, center 48%;
|
||||
background-size: 56% 100%, 100% 100%, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-position: right 12px bottom 6px;
|
||||
background-size: auto 118px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: 24px;
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .96), rgba(220, 245, 250, .94));
|
||||
box-shadow: 0 22px 60px rgba(10, 68, 88, .3), inset 0 0 0 1px rgba(185, 246, 249, .55);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.stage"] {
|
||||
border-radius: 22px;
|
||||
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.video"] {
|
||||
background: #e5f4f8;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.exit"],
|
||||
[data-ws-part="voice.screen-player.fullscreen"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .62);
|
||||
background: rgba(250, 255, 255, .9);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .18);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewers"],
|
||||
[data-ws-part="voice.screen-player.volume"],
|
||||
[data-ws-part="voice.screen-player.source"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: rgba(250, 255, 255, .88);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .16);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
border-color: rgba(250, 255, 255, .96);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.live"] {
|
||||
border-radius: 999px;
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .56);
|
||||
background: rgba(239, 253, 254, .94);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .76), 0 5px 18px rgba(40, 126, 148, .16);
|
||||
text-shadow: none;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
/* The demo keeps its original controls, labels, and interactions. */
|
||||
[data-ws-page="demo"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image: url("assets/foreground-headphone.webp"), linear-gradient(rgba(239, 250, 253, .7), rgba(239, 250, 253, .82)), url("assets/bg-room-main.webp");
|
||||
background-position: left bottom, center, center;
|
||||
background-repeat: no-repeat, no-repeat, no-repeat;
|
||||
background-size: min(34vw, 430px) auto, auto, cover;
|
||||
background-attachment: fixed, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.header"] {
|
||||
border-color: rgba(126, 191, 203, .3);
|
||||
background: rgba(250, 254, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.channels"],
|
||||
[data-ws-part="demo.actions"],
|
||||
[data-ws-part="demo.main"] {
|
||||
border-color: rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(249, 253, 255, .84);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 22px;
|
||||
background-color: #d7f3f7;
|
||||
background-image: linear-gradient(90deg, rgba(239, 251, 254, .94), rgba(227, 248, 251, .48)), url("assets/banner-character-main.webp"), url("assets/banner-mascot-blob.webp");
|
||||
background-position: center, right 46px bottom, right 16px center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover, auto 112%, auto 72%;
|
||||
box-shadow: 0 14px 38px rgba(31, 99, 123, .12), inset 0 0 0 1px rgba(255, 255, 255, .8);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
border-color: rgba(115, 205, 218, .35);
|
||||
border-radius: 19px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
box-shadow: 0 10px 28px rgba(31, 99, 123, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .7);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.chat.send"] {
|
||||
color: #fff;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(110deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-page="demo"] {
|
||||
background-size: min(62vw, 300px) auto, auto, cover;
|
||||
background-attachment: scroll, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
background-position: center, right center;
|
||||
background-size: cover, auto 65%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="home"] {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
[data-ws-part="home.connect"],
|
||||
[data-ws-part="voice.member"],
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
transition-duration: .01ms;
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 61 KiB |
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.2.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.2.5",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6cd83c0fd4f6e00fc9c1ff4ec79dcbfd55",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.2.5",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,14 +11,19 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "tsx --test \"test/**/*.test.ts\"",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts src/server/visitor-count.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build"
|
||||
"web:build": "cd web && npx vite build",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# WebSpeak 加速通道 PoC
|
||||
|
||||
这是第一版隔离测试 Demo,不属于 WebSpeak 生产运行链路,也不会被复制到 Docker 镜像或发布包中。
|
||||
|
||||
它验证以下核心能力:
|
||||
|
||||
- 香港侧客户端向上海侧中继发起认证;
|
||||
- 每个会话动态指定 TeamSpeak 目标地址;
|
||||
- 双向 UDP 数据报转发,并保持数据包边界;
|
||||
- 会话之间按随机 ID 隔离;
|
||||
- 错误密钥不能建立会话;
|
||||
- 不修改系统路由,因此不是 VPN。
|
||||
|
||||
## 本地冒烟
|
||||
|
||||
在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
npm run acceleration:poc
|
||||
```
|
||||
|
||||
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。
|
||||
|
||||
IPv6 回环验证:
|
||||
|
||||
```bash
|
||||
npm run acceleration:ipv6-smoke
|
||||
```
|
||||
|
||||
## 通过隧道连接上海 TeamSpeak
|
||||
|
||||
下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
|
||||
```bash
|
||||
$env:WEBSPEAK_ACCEL_TS_TARGET="203.0.113.10#9987"
|
||||
npm run acceleration:sdk-smoke
|
||||
```
|
||||
|
||||
跨机器验证时,需要在上海启动 `relay-server.mjs`,再把 `WEBSPEAK_ACCEL_RELAY` 指向上海中继地址。当前项目不会自动部署或启动该远程进程。
|
||||
|
||||
## 手动启动中继
|
||||
|
||||
仅用于实验,不要直接暴露到公网:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_ACCEL_TOKEN="change-this-to-a-long-random-token" \
|
||||
WEBSPEAK_ACCEL_HOST="0.0.0.0" \
|
||||
WEBSPEAK_ACCEL_PORT="39087" \
|
||||
node scripts/acceleration-poc/relay-server.mjs
|
||||
```
|
||||
|
||||
当前 Demo 的 UDP 帧协议是实验协议,尚未接入 SDK,也没有替代 GOST 的生产安全审计。正式接入前仍需验证 TeamSpeak 长时间语音、并发会话、IPv6、断线重连和目标地址安全策略。
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export const VERSION = 1;
|
||||
export const HEADER_SIZE = 34;
|
||||
export const MAX_PAYLOAD_SIZE = 60_000;
|
||||
|
||||
export const FrameType = Object.freeze({
|
||||
OPEN: 1,
|
||||
OPEN_OK: 2,
|
||||
OPEN_ERR: 3,
|
||||
DATA: 4,
|
||||
CLOSE: 5,
|
||||
PING: 6,
|
||||
PONG: 7,
|
||||
});
|
||||
|
||||
function asSecret(secret) {
|
||||
if (typeof secret !== "string" || secret.length < 16) {
|
||||
throw new Error("The PoC token must contain at least 16 characters");
|
||||
}
|
||||
return Buffer.from(secret, "utf8");
|
||||
}
|
||||
|
||||
function signFrame(frame, secret, payload) {
|
||||
return createHmac("sha256", asSecret(secret))
|
||||
.update(frame.subarray(0, 18))
|
||||
.update(payload)
|
||||
.digest()
|
||||
.subarray(0, 16);
|
||||
}
|
||||
|
||||
export function encodeFrame(type, sessionId, sequence, payload = Buffer.alloc(0), secret) {
|
||||
const body = Buffer.from(payload);
|
||||
if (!Number.isInteger(type) || type < 1 || type > 255) throw new Error("Invalid frame type");
|
||||
if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > 0xffffffff) throw new Error("Invalid session id");
|
||||
if (!Number.isInteger(sequence) || sequence < 0 || sequence > 0xffffffff) throw new Error("Invalid sequence");
|
||||
if (body.length > MAX_PAYLOAD_SIZE) throw new Error(`Payload exceeds ${MAX_PAYLOAD_SIZE} bytes`);
|
||||
|
||||
const frame = Buffer.alloc(HEADER_SIZE + body.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt16BE(0, 6);
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(body.length, 16);
|
||||
body.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, secret, body).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function decodeFrame(packet) {
|
||||
const frame = Buffer.from(packet);
|
||||
if (frame.length < HEADER_SIZE || !frame.subarray(0, 4).equals(MAGIC)) return null;
|
||||
if (frame[4] !== VERSION) return null;
|
||||
const payloadLength = frame.readUInt16BE(16);
|
||||
if (frame.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return {
|
||||
type: frame[5],
|
||||
sessionId: frame.readUInt32BE(8),
|
||||
sequence: frame.readUInt32BE(12),
|
||||
payload: frame.subarray(HEADER_SIZE),
|
||||
auth: frame.subarray(18, HEADER_SIZE),
|
||||
raw: frame,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyFrame(frame, secret) {
|
||||
const expected = signFrame(frame.raw, secret, frame.payload);
|
||||
return timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
export function randomSessionId() {
|
||||
let id = randomBytes(4).readUInt32BE(0);
|
||||
if (id === 0) id = 1;
|
||||
return id;
|
||||
}
|
||||
|
||||
export function jsonPayload(value) {
|
||||
return Buffer.from(JSON.stringify(value), "utf8");
|
||||
}
|
||||
|
||||
export function parseJsonPayload(payload) {
|
||||
try {
|
||||
return JSON.parse(Buffer.from(payload).toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseEndpoint(value, defaultPort) {
|
||||
if (typeof value !== "string" || !value.trim()) throw new Error("Endpoint is required");
|
||||
const text = value.trim();
|
||||
if (text.startsWith("[")) {
|
||||
const end = text.indexOf("]");
|
||||
if (end < 0) throw new Error(`Invalid endpoint: ${value}`);
|
||||
const host = text.slice(1, end);
|
||||
const portText = text.slice(end + 1).replace(/^[:#]/, "");
|
||||
return { host, port: parsePort(portText || defaultPort, value) };
|
||||
}
|
||||
const hash = text.lastIndexOf("#");
|
||||
if (hash > 0) return { host: text.slice(0, hash), port: parsePort(text.slice(hash + 1), value) };
|
||||
const colon = text.lastIndexOf(":");
|
||||
if (colon > 0 && text.indexOf(":") === colon) {
|
||||
return { host: text.slice(0, colon), port: parsePort(text.slice(colon + 1), value) };
|
||||
}
|
||||
return { host: text, port: parsePort(defaultPort, value) };
|
||||
}
|
||||
|
||||
function parsePort(value, original) {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port in endpoint: ${original}`);
|
||||
return port;
|
||||
}
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, randomSessionId, parseEndpoint, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
export async function createRelayClient({
|
||||
relayHost,
|
||||
relayPort,
|
||||
targetHost,
|
||||
targetPort,
|
||||
token,
|
||||
localHost = "127.0.0.1",
|
||||
localPort = 0,
|
||||
timeoutMs = 5_000,
|
||||
} = {}) {
|
||||
if (!relayHost || !Number.isInteger(relayPort)) throw new Error("Relay endpoint is required");
|
||||
if (!targetHost || !Number.isInteger(targetPort)) throw new Error("Target endpoint is required");
|
||||
const relayFamily = isIP(relayHost) === 6 ? "udp6" : "udp4";
|
||||
const localFamily = isIP(localHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket(localFamily);
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let peer = null;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady;
|
||||
let rejectReady;
|
||||
const readyPromise = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
|
||||
function sendFrame(type, payload = Buffer.alloc(0)) {
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, token);
|
||||
relaySocket.send(packet, relayPort, relayHost);
|
||||
}
|
||||
|
||||
function closeSockets() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try { relaySocket.close(); } catch {}
|
||||
try { localSocket.close(); } catch {}
|
||||
}
|
||||
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
ready = true;
|
||||
resolveReady();
|
||||
} else if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = (() => { try { return JSON.parse(frame.payload.toString("utf8")); } catch { return {}; } })();
|
||||
rejectReady(new Error(detail.code ?? "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
} else if (frame.type === FrameType.DATA && peer) {
|
||||
localSocket.send(frame.payload, peer.port, peer.address);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
closeSockets();
|
||||
}
|
||||
});
|
||||
|
||||
const onSocketError = (error) => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
await Promise.all([
|
||||
new Promise((resolve) => relaySocket.bind(0, relayFamily === "udp6" ? "::" : "0.0.0.0", resolve)),
|
||||
new Promise((resolve) => localSocket.bind(localPort, localHost, resolve)),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, timeoutMs);
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost, targetPort }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const localAddress = localSocket.address();
|
||||
return {
|
||||
sessionId,
|
||||
localHost,
|
||||
localPort: typeof localAddress === "object" ? localAddress.port : localPort,
|
||||
waitReady: () => readyPromise,
|
||||
close() {
|
||||
if (closed) return;
|
||||
if (ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch {}
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseRelayEndpoint(value) {
|
||||
return parseEndpoint(value, 39087);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
function endpointKey(address, port) {
|
||||
return `${address}/${port}`;
|
||||
}
|
||||
|
||||
function isPrivateAddress(host) {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const octets = host.split(".").map(Number);
|
||||
return octets[0] === 10
|
||||
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|
||||
|| octets[0] === 192 && octets[1] === 168
|
||||
|| octets[0] === 127
|
||||
|| octets[0] === 169 && octets[1] === 254
|
||||
|| octets[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLowerCase();
|
||||
return normalized === "::1"
|
||||
|| normalized === "::"
|
||||
|| normalized.startsWith("fc")
|
||||
|| normalized.startsWith("fd")
|
||||
|| normalized.startsWith("fe8")
|
||||
|| normalized.startsWith("fe9")
|
||||
|| normalized.startsWith("fea")
|
||||
|| normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host) {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
export async function createRelayServer({
|
||||
host = "127.0.0.1",
|
||||
port = 0,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
} = {}) {
|
||||
const serverFamily = isIP(host) === 6 ? "udp6" : "udp4";
|
||||
const socket = createSocket(serverFamily);
|
||||
const sessions = new Map();
|
||||
let closed = false;
|
||||
|
||||
function sendToClient(session, type, payload = Buffer.alloc(0)) {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, session.id, session.outSequence++, payload, token);
|
||||
socket.send(packet, session.client.port, session.client.address);
|
||||
}
|
||||
|
||||
function cleanup(session) {
|
||||
if (!session || session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
}
|
||||
|
||||
async function openSession(frame, client) {
|
||||
const request = parseJsonPayload(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) {
|
||||
return;
|
||||
}
|
||||
if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) {
|
||||
const error = { code: "PRIVATE_TARGET_BLOCKED" };
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = sessions.get(frame.sessionId);
|
||||
if (existing) cleanup(existing);
|
||||
const session = {
|
||||
id: frame.sessionId,
|
||||
client,
|
||||
clientKey: endpointKey(client.address, client.port),
|
||||
outSequence: 1,
|
||||
lastActivity: Date.now(),
|
||||
targetSocket: null,
|
||||
closed: false,
|
||||
};
|
||||
sessions.set(session.id, session);
|
||||
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.DATA, payload);
|
||||
});
|
||||
targetSocket.on("error", (error) => {
|
||||
if (!session.closed) sendToClient(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message }));
|
||||
cleanup(session);
|
||||
});
|
||||
targetSocket.connect(request.targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort: request.targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: error.message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openSession(frame, client);
|
||||
return;
|
||||
}
|
||||
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.clientKey !== endpointKey(rinfo.address, rinfo.port)) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) {
|
||||
session.targetSocket.send(frame.payload);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
sendToClient(session, FrameType.CLOSE);
|
||||
cleanup(session);
|
||||
} else if (frame.type === FrameType.PING) {
|
||||
sendToClient(session, FrameType.PONG);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) {
|
||||
if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const onError = (error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
family: serverFamily,
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]?.replaceAll("\\", "/")}`) {
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN;
|
||||
if (!token) throw new Error("Set WEBSPEAK_ACCEL_TOKEN before starting the PoC relay");
|
||||
const host = process.env.WEBSPEAK_ACCEL_HOST ?? "0.0.0.0";
|
||||
const port = Number(process.env.WEBSPEAK_ACCEL_PORT ?? 39087);
|
||||
const server = await createRelayServer({ host, port, token });
|
||||
console.log(`ACCELERATION_RELAY_LISTEN ${server.host}:${server.port}`);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Client, generateIdentity } from "../../../teamspeak-js/dist/index.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { parseEndpoint } from "./protocol.mjs";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN ?? "local-acceleration-poc-token";
|
||||
const target = parseEndpoint(process.env.WEBSPEAK_ACCEL_TS_TARGET ?? "203.0.113.10#9987", 9987);
|
||||
const relayEndpoint = process.env.WEBSPEAK_ACCEL_RELAY;
|
||||
let relayServer = null;
|
||||
let relayClient = null;
|
||||
let tsClient = null;
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error(`${label}_TIMEOUT`)), timeoutMs)),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
let relay;
|
||||
if (relayEndpoint) {
|
||||
relay = parseEndpoint(relayEndpoint, 39087);
|
||||
} else {
|
||||
relayServer = await createRelayServer({ host: "127.0.0.1", port: 0, token, allowPrivate: true });
|
||||
relay = { host: "127.0.0.1", port: relayServer.port };
|
||||
}
|
||||
|
||||
relayClient = await createRelayClient({
|
||||
relayHost: relay.host,
|
||||
relayPort: relay.port,
|
||||
targetHost: target.host,
|
||||
targetPort: target.port,
|
||||
token,
|
||||
});
|
||||
|
||||
tsClient = new Client(generateIdentity(8), `127.0.0.1:${relayClient.localPort}`, "acceleration-sdk-smoke");
|
||||
await withTimeout(tsClient.connect(), 15_000, "TS_CONNECT");
|
||||
console.log(`TS_ACCEL_CONNECTED target=${target.host}#${target.port}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await tsClient.disconnect();
|
||||
console.log("TS_ACCEL_DISCONNECTED");
|
||||
} catch (error) {
|
||||
console.error("TS_ACCEL_SMOKE_FAILED", error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
try { await tsClient?.disconnect(); } catch {}
|
||||
relayClient?.close();
|
||||
relayServer?.close();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-ipv6-acceleration-poc-token";
|
||||
const PACKET_COUNT = 50;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(port, "::1", () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp6");
|
||||
target.on("message", (payload, rinfo) => target.send(payload, rinfo.port, rinfo.address));
|
||||
await bind(target);
|
||||
const targetPort = target.address().port;
|
||||
|
||||
const relay = await createRelayServer({ host: "::1", port: 0, token: TOKEN, allowPrivate: true });
|
||||
const client = await createRelayClient({
|
||||
relayHost: "::1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "::1",
|
||||
targetPort,
|
||||
token: TOKEN,
|
||||
localHost: "::1",
|
||||
});
|
||||
|
||||
const sender = createSocket("udp6");
|
||||
await bind(sender);
|
||||
const pending = new Set(Array.from({ length: PACKET_COUNT }, (_, index) => index));
|
||||
sender.on("message", (payload) => pending.delete(payload.readUInt32BE(0)));
|
||||
for (let index = 0; index < PACKET_COUNT; index++) {
|
||||
const payload = Buffer.alloc(512, index & 0xff);
|
||||
payload.writeUInt32BE(index, 0);
|
||||
sender.send(payload, client.localPort, "::1");
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 3000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
const received = PACKET_COUNT - pending.size;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
console.log(`ipv6_packets=${PACKET_COUNT} received=${received} loss=${((pending.size / PACKET_COUNT) * 100).toFixed(2)}%`);
|
||||
if (received !== PACKET_COUNT) throw new Error("IPV6_ACCELERATION_POC_FAILED");
|
||||
console.log("IPV6_ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-acceleration-poc-token";
|
||||
const PACKET_COUNT = 200;
|
||||
const PACKET_SIZE = 1920;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve) => socket.bind(port, "127.0.0.1", resolve));
|
||||
}
|
||||
|
||||
function close(socket) {
|
||||
try { socket.close(); } catch {}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp4");
|
||||
target.on("message", (payload, rinfo) => {
|
||||
target.send(payload, rinfo.port, rinfo.address);
|
||||
});
|
||||
await bind(target);
|
||||
const targetAddress = target.address();
|
||||
|
||||
const relay = await createRelayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
token: TOKEN,
|
||||
allowPrivate: true,
|
||||
});
|
||||
const client = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: TOKEN,
|
||||
});
|
||||
|
||||
let rejectedBadToken = false;
|
||||
try {
|
||||
const badClient = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: "wrong-token-that-is-long-enough",
|
||||
timeoutMs: 250,
|
||||
});
|
||||
badClient.close();
|
||||
} catch {
|
||||
rejectedBadToken = true;
|
||||
}
|
||||
|
||||
const sender = createSocket("udp4");
|
||||
await bind(sender);
|
||||
const pending = new Map();
|
||||
const samples = [];
|
||||
sender.on("message", (payload) => {
|
||||
const id = payload.readUInt32BE(0);
|
||||
const sentAt = pending.get(id);
|
||||
if (sentAt !== undefined) {
|
||||
pending.delete(id);
|
||||
samples.push(Number(process.hrtime.bigint() - sentAt) / 1_000_000);
|
||||
}
|
||||
});
|
||||
|
||||
for (let id = 0; id < PACKET_COUNT; id++) {
|
||||
const payload = Buffer.alloc(PACKET_SIZE, id & 0xff);
|
||||
payload.writeUInt32BE(id, 0);
|
||||
pending.set(id, process.hrtime.bigint());
|
||||
sender.send(payload, client.localPort, "127.0.0.1");
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
const received = samples.length;
|
||||
const loss = ((PACKET_COUNT - received) / PACKET_COUNT) * 100;
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const percentile = (ratio) => sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * ratio))] : 0;
|
||||
const average = sorted.length ? sorted.reduce((sum, value) => sum + value, 0) / sorted.length : 0;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
|
||||
console.log(`relay=127.0.0.1:${relay.port}`);
|
||||
console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`);
|
||||
console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`);
|
||||
console.log(`bad_token_rejected=${rejectedBadToken}`);
|
||||
if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED");
|
||||
console.log("ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$width = 3200
|
||||
$height = 116
|
||||
$outputPath = Join-Path $PSScriptRoot "..\docs\examples\illusia-voice\assets\footer-wave.png"
|
||||
$bitmap = [System.Drawing.Bitmap]::new($width, $height, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
|
||||
$graphics.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
$topEdge = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$topEdge.StartFigure()
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(0, 20),
|
||||
[System.Drawing.PointF]::new(240, 4),
|
||||
[System.Drawing.PointF]::new(460, 0),
|
||||
[System.Drawing.PointF]::new(700, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(700, 10),
|
||||
[System.Drawing.PointF]::new(1000, 26),
|
||||
[System.Drawing.PointF]::new(1200, 36),
|
||||
[System.Drawing.PointF]::new(1600, 36)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(1600, 36),
|
||||
[System.Drawing.PointF]::new(2000, 36),
|
||||
[System.Drawing.PointF]::new(2200, 26),
|
||||
[System.Drawing.PointF]::new(2500, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(2500, 10),
|
||||
[System.Drawing.PointF]::new(2740, 0),
|
||||
[System.Drawing.PointF]::new(2960, 4),
|
||||
[System.Drawing.PointF]::new(3200, 20)
|
||||
)
|
||||
|
||||
$surface = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$surface.AddPath($topEdge, $false)
|
||||
$surface.AddLine(3200, 20, 3200, $height)
|
||||
$surface.AddLine(3200, $height, 0, $height)
|
||||
$surface.CloseFigure()
|
||||
|
||||
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new(
|
||||
[System.Drawing.Rectangle]::new(0, 0, $width, $height),
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255),
|
||||
[System.Drawing.Drawing2D.LinearGradientMode]::Vertical
|
||||
)
|
||||
$blend = [System.Drawing.Drawing2D.ColorBlend]::new(3)
|
||||
$blend.Colors = [System.Drawing.Color[]]@(
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(194, 248, 253, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255)
|
||||
)
|
||||
$blend.Positions = [single[]]@(0.0, 0.58, 1.0)
|
||||
$brush.InterpolationColors = $blend
|
||||
$pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(118, 103, 210, 221), 1.5)
|
||||
$pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
|
||||
$accentBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(150, 99, 216, 225))
|
||||
$accentPath = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$leftDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(126, 47),
|
||||
[System.Drawing.PointF]::new(136, 58),
|
||||
[System.Drawing.PointF]::new(126, 69),
|
||||
[System.Drawing.PointF]::new(116, 58)
|
||||
)
|
||||
$rightDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(3074, 47),
|
||||
[System.Drawing.PointF]::new(3084, 58),
|
||||
[System.Drawing.PointF]::new(3074, 69),
|
||||
[System.Drawing.PointF]::new(3064, 58)
|
||||
)
|
||||
$accentPen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(94, 91, 211, 223), 1.2)
|
||||
$accentPen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
$accentPen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
|
||||
$graphics.FillPath($brush, $surface)
|
||||
$graphics.DrawPath($pen, $topEdge)
|
||||
$graphics.DrawLine($accentPen, 82, 58, 116, 58)
|
||||
$graphics.DrawLine($accentPen, 136, 58, 170, 58)
|
||||
$graphics.DrawLine($accentPen, 3030, 58, 3064, 58)
|
||||
$graphics.DrawLine($accentPen, 3084, 58, 3118, 58)
|
||||
$accentPath.AddPolygon($leftDiamond)
|
||||
$accentPath.AddPolygon($rightDiamond)
|
||||
$graphics.FillPath($accentBrush, $accentPath)
|
||||
[System.IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null
|
||||
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$accentPen.Dispose()
|
||||
$accentBrush.Dispose()
|
||||
$accentPath.Dispose()
|
||||
$pen.Dispose()
|
||||
$brush.Dispose()
|
||||
$surface.Dispose()
|
||||
$topEdge.Dispose()
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
@@ -0,0 +1,48 @@
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const root = process.cwd();
|
||||
const sdkPackage = "@echosixhiya/teamspeak-client";
|
||||
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const dependency = packageJson.dependencies?.[sdkPackage];
|
||||
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
|
||||
|
||||
if (!match) {
|
||||
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
|
||||
}
|
||||
|
||||
const [, repository, commit] = match;
|
||||
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
|
||||
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
|
||||
|
||||
try {
|
||||
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
|
||||
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
|
||||
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
|
||||
const runNpm = (args) => {
|
||||
if (process.platform === "win32") {
|
||||
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
|
||||
} else {
|
||||
execFileSync("npm", args, npmOptions);
|
||||
}
|
||||
};
|
||||
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
|
||||
runNpm(["run", "build"]);
|
||||
|
||||
const source = join(temporaryRoot, "dist");
|
||||
if (!existsSync(join(source, "index.mjs"))) {
|
||||
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
|
||||
}
|
||||
|
||||
mkdirSync(dirname(destination), { recursive: true });
|
||||
mkdirSync(destination, { recursive: true });
|
||||
for (const entry of readdirSync(source)) {
|
||||
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
|
||||
}
|
||||
console.log(`Prepared ${sdkPackage} from ${commit}`);
|
||||
} finally {
|
||||
rmSync(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,11 +1,28 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string | null;
|
||||
relayTarget: string | null;
|
||||
startedAt: string;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: "active" | "connecting" | "disconnected" | "failed";
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
@@ -18,6 +35,7 @@ export interface AdminRouterOptions {
|
||||
terminateSession?: (id: string) => Promise<boolean>;
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -104,6 +122,81 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.get("/skins", async (_request, response) => {
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
|
||||
const settings = await options.skinRegistry.setDefaultSkin(id);
|
||||
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_DEFAULT_INVALID" ? 400 : 409).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id/enabled", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const body = asRecord(request.body);
|
||||
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
|
||||
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
|
||||
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
|
||||
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_NOT_FOUND" ? 404 : error.code === "SKIN_ENABLE_INVALID" ? 400 : 409;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const skin = await options.skinRegistry.save(request.body, id);
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" || error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
try {
|
||||
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id });
|
||||
response.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/sessions", (_request, response) => {
|
||||
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
|
||||
});
|
||||
@@ -155,7 +248,12 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
|
||||
router.get("/logs", (request, response) => {
|
||||
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
|
||||
const limit = readLimit(request.query.limit, 100);
|
||||
response.json({
|
||||
available: Boolean(options.logFile && existsSync(options.logFile)),
|
||||
entries: readRecentLogs(options.logFile, limit),
|
||||
sessions: readConnectionHistory(options.logFile, limit),
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/diagnostics", (_request, response) => {
|
||||
@@ -306,6 +404,22 @@ function requireSameOrigin(request: Request, response: Response, next: NextFunct
|
||||
next();
|
||||
}
|
||||
|
||||
function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/octet-stream")) {
|
||||
response.status(415).json({ ok: false, code: "BINARY_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
|
||||
} catch {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
service: AdminService,
|
||||
response: Response,
|
||||
@@ -325,6 +439,19 @@ async function runProbe(
|
||||
}
|
||||
|
||||
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
const relayNodes = Array.isArray(body.relayNodes)
|
||||
? body.relayNodes.map((value): RelayNodeInput => {
|
||||
const node = asRecord(value);
|
||||
return {
|
||||
id: typeof node.id === "string" ? node.id.slice(0, 110) : undefined,
|
||||
name: typeof node.name === "string" ? node.name.slice(0, 80) : "",
|
||||
target: typeof node.target === "string" ? node.target.slice(0, 300) : "",
|
||||
enabled: node.enabled === true,
|
||||
token: typeof node.token === "string" ? node.token.slice(0, 512) : undefined,
|
||||
tokenAction: readPasswordAction(node.tokenAction),
|
||||
};
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
target: readString(body, "target", 300),
|
||||
serverPassword: typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : undefined,
|
||||
@@ -332,12 +459,27 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
|
||||
welcomeTextDe: typeof body.welcomeTextDe === "string" ? body.welcomeTextDe.slice(0, 500) : undefined,
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
relayEnabled: body.relayEnabled === true,
|
||||
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
|
||||
relayTarget: typeof body.relayTarget === "string" ? body.relayTarget.slice(0, 300) : undefined,
|
||||
relayToken: typeof body.relayToken === "string" ? body.relayToken.slice(0, 512) : undefined,
|
||||
relayTokenAction: readPasswordAction(body.relayTokenAction),
|
||||
relayNodes,
|
||||
};
|
||||
}
|
||||
|
||||
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
@@ -388,7 +530,7 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
const context: Record<string, string | number | boolean> = {};
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "channel", "reconnect", "port"]) {
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "clientIp", "relayName", "relayTarget", "channel", "reconnect", "port"]) {
|
||||
const value = raw[key];
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") context[key] = value;
|
||||
}
|
||||
@@ -407,6 +549,145 @@ function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEnt
|
||||
}
|
||||
}
|
||||
|
||||
interface StructuredLogEntry {
|
||||
timestamp: string | null;
|
||||
message: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function readConnectionHistory(logFile: string | undefined, limit: number): AdminConnectionRecord[] {
|
||||
if (!logFile) return [];
|
||||
const records = new Map<string, {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string;
|
||||
relayTarget: string;
|
||||
startedAt: string | null;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: AdminConnectionRecord["status"];
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}>();
|
||||
for (const log of readStructuredLogs(logFile)) {
|
||||
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
|
||||
if (!entryId || !log.timestamp) continue;
|
||||
const current = records.get(entryId) ?? {
|
||||
id: entryId,
|
||||
nickname: "",
|
||||
clientIp: "",
|
||||
target: "",
|
||||
relayName: "",
|
||||
relayTarget: "",
|
||||
startedAt: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
durationSeconds: null,
|
||||
status: "connecting" as const,
|
||||
reason: null,
|
||||
failureDetail: null,
|
||||
};
|
||||
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
|
||||
const clientIp = typeof log.raw.clientIp === "string" ? log.raw.clientIp : "";
|
||||
const target = typeof log.raw.target === "string" ? log.raw.target : "";
|
||||
const relayName = typeof log.raw.relayName === "string" ? log.raw.relayName : "";
|
||||
const relayTarget = typeof log.raw.relayTarget === "string" ? log.raw.relayTarget : "";
|
||||
if (nickname) current.nickname = nickname;
|
||||
if (clientIp) current.clientIp = clientIp;
|
||||
if (target) current.target = target;
|
||||
if (relayName) current.relayName = relayName;
|
||||
if (relayTarget) current.relayTarget = relayTarget;
|
||||
if (typeof log.raw.failureDetail === "string" && log.raw.failureDetail) current.failureDetail = log.raw.failureDetail;
|
||||
if (log.message === "WebClient connecting") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.status = "connecting";
|
||||
} else if (log.message === "TS connect failed") {
|
||||
current.reason = typeof log.raw.code === "string" ? log.raw.code : current.reason;
|
||||
current.status = "failed";
|
||||
} else if (log.message === "Web client connected to TeamSpeak") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.connectedAt = log.timestamp;
|
||||
current.status = "active";
|
||||
} else if (log.message === "Client session torn down") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.disconnectedAt = log.timestamp;
|
||||
current.durationSeconds = current.connectedAt && typeof log.raw.durationSeconds === "number"
|
||||
? Math.max(0, Math.floor(log.raw.durationSeconds))
|
||||
: current.connectedAt
|
||||
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
|
||||
: null;
|
||||
current.status = current.connectedAt ? "disconnected" : "failed";
|
||||
// `reason` is also used for ordinary lifecycle teardown (for example
|
||||
// websocket-close when a user clicks Leave). Only preserve an explicit
|
||||
// TeamSpeak failure code here; otherwise a normal disconnect would be
|
||||
// rendered by the admin UI as the generic request-failed message.
|
||||
current.reason = typeof log.raw.failureCode === "string" && log.raw.failureCode
|
||||
? log.raw.failureCode
|
||||
: current.reason;
|
||||
}
|
||||
records.set(entryId, current);
|
||||
}
|
||||
const now = Date.now();
|
||||
return [...records.values()]
|
||||
.filter((record): record is typeof record & { startedAt: string } => Boolean(record.startedAt))
|
||||
.map((record) => {
|
||||
const start = record.connectedAt ?? record.startedAt;
|
||||
const end = record.disconnectedAt ? Date.parse(record.disconnectedAt) : now;
|
||||
return {
|
||||
id: record.id,
|
||||
nickname: record.nickname || "—",
|
||||
clientIp: record.clientIp || "—",
|
||||
target: record.target || "—",
|
||||
relayName: record.relayName || null,
|
||||
relayTarget: record.relayTarget || null,
|
||||
startedAt: record.startedAt,
|
||||
connectedAt: record.connectedAt,
|
||||
disconnectedAt: record.disconnectedAt,
|
||||
durationSeconds: record.durationSeconds ?? (record.status === "active" || record.status === "connecting"
|
||||
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
|
||||
: null),
|
||||
status: record.status,
|
||||
// Older sessions may only contain a teardown record without a
|
||||
// structured failure code. Keep normal disconnects quiet, but make
|
||||
// an untraceable failed connection explicitly visible as the generic
|
||||
// request-failed message instead of implying a guessed cause.
|
||||
reason: record.reason ?? (record.status === "failed" ? "CONNECTION_FAILED" : null),
|
||||
failureDetail: record.failureDetail,
|
||||
};
|
||||
})
|
||||
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
const paths = [logFile, `${logFile}.1`, `${logFile}.2`, `${logFile}.3`].filter((value, index, all) => value && all.indexOf(value) === index);
|
||||
const entries: StructuredLogEntry[] = [];
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) continue;
|
||||
try {
|
||||
for (const line of readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean)) {
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
entries.push({
|
||||
timestamp: typeof raw.time === "string" ? raw.time : null,
|
||||
message: typeof raw.msg === "string" ? raw.msg : "",
|
||||
raw,
|
||||
});
|
||||
} catch {
|
||||
// Non-JSON lines are still shown by the normal log viewer, but cannot
|
||||
// be associated with a user session safely.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A rotated file can disappear between existsSync and readFileSync.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
|
||||
@@ -3,12 +3,15 @@ import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { loadConfig } from "../config.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { type AccessMode, type ManagedInviteRecord, type PersistedRelayNode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
@@ -17,9 +20,29 @@ export interface AdminSettingsInput {
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
relayTarget?: string;
|
||||
relayToken?: string;
|
||||
relayTokenAction?: "keep" | "replace" | "remove";
|
||||
relayNodes?: RelayNodeInput[];
|
||||
}
|
||||
|
||||
export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
@@ -92,11 +115,22 @@ export class AdminService {
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
const welcomeTexts = resolveWelcomeTexts({
|
||||
zh: settings.welcomeText,
|
||||
en: settings.welcomeTextEn,
|
||||
de: settings.welcomeTextDe,
|
||||
ru: settings.welcomeTextRu,
|
||||
ja: settings.welcomeTextJa,
|
||||
});
|
||||
return {
|
||||
version: this.version,
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
// Keep the old fields for older clients, but return the complete,
|
||||
// already-fallback-resolved map for current clients.
|
||||
welcomeText: welcomeTexts.zh,
|
||||
welcomeTextEn: welcomeTexts.en,
|
||||
welcomeTexts,
|
||||
accessMode: settings.accessMode,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
};
|
||||
@@ -110,12 +144,23 @@ export class AdminService {
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
welcomeDefaults: DEFAULT_WELCOME_TEXTS,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayTarget: settings.relayHost ? formatRelayTarget(settings.relayHost, settings.relayPort) : "",
|
||||
hasRelayToken: Boolean(settings.relayTokenEncrypted),
|
||||
relayNodes: this.getRelayNodeViews(),
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
@@ -129,11 +174,35 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
|
||||
const relays: ConfiguredAccelerationRelay[] = [];
|
||||
for (const node of this.database.listRelayNodes()) {
|
||||
if (!node.enabled || !node.host || !node.tokenEncrypted) continue;
|
||||
try {
|
||||
const token = decryptSecret(node.tokenEncrypted, this.masterSecret);
|
||||
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token });
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error), relayId: node.id }, "Stored acceleration relay token could not be decrypted");
|
||||
}
|
||||
}
|
||||
return relays;
|
||||
}
|
||||
|
||||
getAccelerationRelayName(): string | undefined {
|
||||
return this.getAccelerationRelayOptions()[0]?.name;
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const settings = this.normalizeSettings(input, current);
|
||||
const relayNodes = input.relayNodes === undefined ? undefined : this.normalizeRelayNodes(input.relayNodes);
|
||||
const settings = this.normalizeSettings(input, current, relayNodes);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
|
||||
this.database.updateSettings(settings);
|
||||
if (relayNodes !== undefined) {
|
||||
this.database.replaceRelayNodes(relayNodes);
|
||||
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
|
||||
this.database.replaceRelayNodes(this.legacyRelayNodesFromSettings(settings));
|
||||
}
|
||||
if (targetChanged) this.database.clearConnectionTest();
|
||||
}
|
||||
|
||||
@@ -152,7 +221,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<Omit<TeamSpeakProbeResult, "protocol">> {
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<{ ok: boolean; checkType: "network" | "protocol"; passwordVerified: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
@@ -160,13 +229,41 @@ export class AdminService {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
// The admin connection test must not create a temporary TeamSpeak
|
||||
// client: that client becomes visible in the target channel. Use the
|
||||
// WebSpeak host's ICMP route measurement instead. The injected probe is
|
||||
// retained for unit tests and explicit protocol-probe callers.
|
||||
if (this.probe === probeTeamSpeak) {
|
||||
const result = await pingTeamSpeakHost(target.host, { attempts: 4 });
|
||||
const publicResult = {
|
||||
ok: result.ok,
|
||||
checkType: "network" as const,
|
||||
passwordVerified: false,
|
||||
latencyMs: result.latencyMs ?? 0,
|
||||
serverName: null,
|
||||
requiresPassword: false,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
attempts: result.attempts,
|
||||
successfulAttempts: result.successfulAttempts,
|
||||
...(result.errorCode ? { errorCode: result.errorCode } : {}),
|
||||
};
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: result.latencyMs, error: result.ok ? null : (result.errorCode ?? "UNREACHABLE") });
|
||||
this.database.addAudit(result.ok ? "CONNECTION_TEST_SUCCEEDED" : "CONNECTION_TEST_FAILED", {
|
||||
latencyMs: result.latencyMs,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
...(result.errorCode ? { code: result.errorCode } : {}),
|
||||
});
|
||||
}
|
||||
return publicResult;
|
||||
}
|
||||
const result = await this.probe(target, password, this.logger);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
|
||||
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
|
||||
}
|
||||
const { protocol: _protocol, ...publicResult } = result;
|
||||
return publicResult;
|
||||
return { ...publicResult, checkType: "protocol", passwordVerified: true };
|
||||
} catch (error: unknown) {
|
||||
const probeError = error instanceof TeamSpeakProbeError
|
||||
? error
|
||||
@@ -254,7 +351,7 @@ export class AdminService {
|
||||
this.database.setMeta("legacy_import_notice_pending", "0");
|
||||
}
|
||||
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>, relayNodes?: PersistedRelayNode[]): SettingsUpdate {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(input.target);
|
||||
@@ -263,8 +360,16 @@ export class AdminService {
|
||||
}
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
|
||||
const welcomeTextDe = typeof input.welcomeTextDe === "string" ? input.welcomeTextDe.trim() : current.welcomeTextDe;
|
||||
const welcomeTextRu = typeof input.welcomeTextRu === "string" ? input.welcomeTextRu.trim() : current.welcomeTextRu;
|
||||
const welcomeTextJa = typeof input.welcomeTextJa === "string" ? input.welcomeTextJa.trim() : current.welcomeTextJa;
|
||||
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
|
||||
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextEn.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_EN", "English welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextDe.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_DE", "German welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextRu.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_RU", "Russian welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextJa.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_JA", "Japanese welcome text cannot exceed 500 characters");
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
@@ -290,9 +395,62 @@ export class AdminService {
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
if (action === "remove") encryptedPassword = null;
|
||||
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
|
||||
|
||||
let relayConfigured = current.relayConfigured;
|
||||
let relayEnabled = current.relayEnabled;
|
||||
let relayName = current.relayName;
|
||||
let relayHost = current.relayHost;
|
||||
let relayPort = current.relayPort || DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
let relayTokenEncrypted = current.relayTokenEncrypted;
|
||||
const relaySettingsAction = input.relaySettingsAction ?? "keep";
|
||||
if (relaySettingsAction === "remove") {
|
||||
relayConfigured = true;
|
||||
relayEnabled = false;
|
||||
relayName = "";
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = null;
|
||||
} else if (relaySettingsAction === "replace") {
|
||||
const relayTarget = (input.relayTarget ?? "").trim();
|
||||
relayEnabled = input.relayEnabled === true;
|
||||
relayName = (input.relayName ?? "").trim();
|
||||
if (relayName.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 80 characters or fewer");
|
||||
if (relayEnabled && !relayName) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name is required when the relay is enabled");
|
||||
if (relayEnabled && !relayTarget) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is required when the relay is enabled");
|
||||
if (relayTarget) {
|
||||
try {
|
||||
const relay = parseTeamSpeakTarget(relayTarget, DEFAULT_ACCELERATION_RELAY_PORT);
|
||||
relayHost = relay.host;
|
||||
relayPort = relay.port;
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
}
|
||||
} else {
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
}
|
||||
const relayTokenAction = input.relayTokenAction ?? (input.relayToken === undefined ? "keep" : "replace");
|
||||
if (relayTokenAction === "remove") relayTokenEncrypted = null;
|
||||
if (relayTokenAction === "replace") relayTokenEncrypted = input.relayToken ? encryptSecret(input.relayToken, this.masterSecret) : null;
|
||||
if (relayEnabled && !relayTokenEncrypted) throw new AdminInputError("INVALID_RELAY_TOKEN", "Relay token is required when the relay is enabled");
|
||||
relayConfigured = true;
|
||||
}
|
||||
if (relayNodes) {
|
||||
const primary = relayNodes.find((node) => node.enabled) ?? relayNodes[0];
|
||||
relayConfigured = relayNodes.length > 0;
|
||||
relayEnabled = primary?.enabled === true;
|
||||
relayName = primary?.name ?? "";
|
||||
relayHost = primary?.host ?? "";
|
||||
relayPort = primary?.port ?? DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = primary?.tokenEncrypted ?? null;
|
||||
}
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
welcomeTextEn,
|
||||
welcomeTextDe,
|
||||
welcomeTextRu,
|
||||
welcomeTextJa,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
@@ -300,9 +458,91 @@ export class AdminService {
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
relayConfigured,
|
||||
relayEnabled,
|
||||
relayName,
|
||||
relayHost,
|
||||
relayPort,
|
||||
relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeRelayNodes(inputs: RelayNodeInput[]): PersistedRelayNode[] {
|
||||
if (!Array.isArray(inputs) || inputs.length > 16) throw new AdminInputError("INVALID_RELAY_NODES", "At most 16 relay nodes may be configured");
|
||||
const current = new Map(this.database.listRelayNodes().map((node) => [node.id, node]));
|
||||
const seen = new Set<string>();
|
||||
const now = new Date().toISOString();
|
||||
return inputs.map((input) => {
|
||||
const name = typeof input.name === "string" ? input.name.trim() : "";
|
||||
const targetText = typeof input.target === "string" ? input.target.trim() : "";
|
||||
if (!name || name.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 1 to 80 characters");
|
||||
if (!targetText || targetText.length > 300) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
let target: TeamSpeakTarget;
|
||||
try { target = parseTeamSpeakTarget(targetText, DEFAULT_ACCELERATION_RELAY_PORT); }
|
||||
catch { throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid"); }
|
||||
const id = typeof input.id === "string" && /^relay-[a-z0-9-]{1,100}$/i.test(input.id)
|
||||
? input.id
|
||||
: `relay-${randomBytes(8).toString("hex")}`;
|
||||
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
|
||||
seen.add(id);
|
||||
const previous = current.get(id);
|
||||
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
|
||||
let tokenEncrypted = previous?.tokenEncrypted ?? null;
|
||||
if (tokenAction === "remove") tokenEncrypted = null;
|
||||
if (tokenAction === "replace") {
|
||||
const token = typeof input.token === "string" ? input.token.trim() : "";
|
||||
tokenEncrypted = token ? encryptSecret(token, this.masterSecret) : null;
|
||||
}
|
||||
if (input.enabled === true && (!tokenEncrypted || !this.canDecryptToken(tokenEncrypted))) {
|
||||
throw new AdminInputError("INVALID_RELAY_TOKEN", "A relay token of at least 16 characters is required when the relay is enabled");
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
enabled: input.enabled === true,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
tokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private canDecryptToken(encrypted: string): boolean {
|
||||
try {
|
||||
return decryptSecret(encrypted, this.masterSecret).length >= 16;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
|
||||
return this.database.listRelayNodes().map((node) => ({
|
||||
id: node.id,
|
||||
name: node.name,
|
||||
enabled: node.enabled,
|
||||
target: formatRelayTarget(node.host, node.port),
|
||||
hasToken: Boolean(node.tokenEncrypted),
|
||||
}));
|
||||
}
|
||||
|
||||
private legacyRelayNodesFromSettings(settings: SettingsUpdate): PersistedRelayNode[] {
|
||||
if (!settings.relayConfigured || !settings.relayHost || !settings.relayTokenEncrypted) return [];
|
||||
const previous = this.database.listRelayNodes()[0];
|
||||
const now = new Date().toISOString();
|
||||
return [{
|
||||
id: previous?.id ?? "relay-default",
|
||||
name: settings.relayName || "中继加速",
|
||||
enabled: settings.relayEnabled,
|
||||
host: settings.relayHost,
|
||||
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
|
||||
tokenEncrypted: settings.relayTokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
}];
|
||||
}
|
||||
|
||||
private toInviteView(record: ManagedInviteRecord): ManagedInviteView {
|
||||
const now = Date.now();
|
||||
const expired = Date.parse(record.expiresAt) <= now;
|
||||
@@ -324,6 +564,10 @@ export class AdminService {
|
||||
return {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
@@ -331,6 +575,12 @@ export class AdminService {
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayHost: settings.relayHost,
|
||||
relayPort: settings.relayPort,
|
||||
relayTokenEncrypted: settings.relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -342,6 +592,10 @@ export class AdminService {
|
||||
this.database.updateSettings({
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
welcomeTextEn: current.welcomeTextEn,
|
||||
welcomeTextDe: current.welcomeTextDe,
|
||||
welcomeTextRu: current.welcomeTextRu,
|
||||
welcomeTextJa: current.welcomeTextJa,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
@@ -349,6 +603,12 @@ export class AdminService {
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
relayConfigured: current.relayConfigured,
|
||||
relayEnabled: current.relayEnabled,
|
||||
relayName: current.relayName,
|
||||
relayHost: current.relayHost,
|
||||
relayPort: current.relayPort,
|
||||
relayTokenEncrypted: current.relayTokenEncrypted,
|
||||
}, "LEGACY_CONFIG_IMPORTED");
|
||||
this.database.setMeta("legacy_config_imported", "1");
|
||||
this.database.setMeta("legacy_import_notice_pending", "1");
|
||||
@@ -362,6 +622,10 @@ function hashInviteToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function formatRelayTarget(host: string, port: number): string {
|
||||
return `${host.includes(":") ? `[${host}]` : host}#${port}`;
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "sample-skin",
|
||||
name: "Sample skin",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak test",
|
||||
license: "MIT",
|
||||
minAppVersion: "0.2.4",
|
||||
entry: "skin.css",
|
||||
content: "content.json",
|
||||
preview: "assets/preview.png",
|
||||
};
|
||||
|
||||
test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
const firstArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(manifest))],
|
||||
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
|
||||
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
|
||||
["assets/background.png", Buffer.from([1, 2, 3, 4])],
|
||||
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
|
||||
]);
|
||||
const first = await registry.save(firstArchive, "sample-skin");
|
||||
assert.equal(first.id, "sample-skin");
|
||||
assert.equal(first.previewUrl, "/api/skins/sample-skin/preview");
|
||||
assert.equal((await registry.list()).length, 1);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive);
|
||||
assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8]));
|
||||
await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
|
||||
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
|
||||
const secondArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(replacement))],
|
||||
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
|
||||
]);
|
||||
const second = await registry.save(secondArchive, "sample-skin");
|
||||
assert.equal(second.version, "2.0.0");
|
||||
assert.equal(second.installedAt, first.installedAt);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive);
|
||||
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.remove("sample-skin"), false);
|
||||
});
|
||||
|
||||
test("custom skins can be enabled, disabled, and selected as the instance default", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-settings-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const archive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from("[data-ws-part=\"demo.voice-card\"] { color: teal; }")],
|
||||
]);
|
||||
|
||||
const skin = await registry.save(archive, "sample-skin");
|
||||
assert.equal(skin.enabled, true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.getDefaultSkinId(), "sample-skin");
|
||||
|
||||
const disabled = await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(disabled.enabled, false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await assert.rejects(registry.setDefaultSkin("sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_DEFAULT_INVALID");
|
||||
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
});
|
||||
|
||||
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const goodFiles: Array<[string, Buffer]> = [
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from(".voice-card { color: teal; }")],
|
||||
];
|
||||
|
||||
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
|
||||
const mismatched = createZip(goodFiles);
|
||||
mismatched[30] ^= 1;
|
||||
await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID");
|
||||
|
||||
await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles));
|
||||
assert.equal(await registry.readArchive("orphan"), null);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the three bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice"]) {
|
||||
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
}
|
||||
});
|
||||
|
||||
function createZip(files: Array<[string, Buffer]>): Buffer {
|
||||
const localRecords: Buffer[] = [];
|
||||
const centralRecords: Buffer[] = [];
|
||||
let localOffset = 0;
|
||||
for (const [name, bytes] of files) {
|
||||
const filename = Buffer.from(name, "utf8");
|
||||
const checksum = crc32(bytes);
|
||||
const local = Buffer.alloc(30 + filename.length + bytes.length);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(bytes.length, 18);
|
||||
local.writeUInt32LE(bytes.length, 22);
|
||||
local.writeUInt16LE(filename.length, 26);
|
||||
filename.copy(local, 30);
|
||||
bytes.copy(local, 30 + filename.length);
|
||||
localRecords.push(local);
|
||||
|
||||
const central = Buffer.alloc(46 + filename.length);
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(0x0314, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE(0, 8);
|
||||
central.writeUInt16LE(0, 10);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(bytes.length, 20);
|
||||
central.writeUInt32LE(bytes.length, 24);
|
||||
central.writeUInt16LE(filename.length, 28);
|
||||
central.writeUInt32LE(0x81a40000, 38);
|
||||
central.writeUInt32LE(localOffset, 42);
|
||||
filename.copy(central, 46);
|
||||
centralRecords.push(central);
|
||||
localOffset += local.length;
|
||||
}
|
||||
const centralDirectory = Buffer.concat(centralRecords);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralDirectory.length, 12);
|
||||
end.writeUInt32LE(localOffset, 16);
|
||||
return Buffer.concat([...localRecords, centralDirectory, end]);
|
||||
}
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { inflateRawSync } from "node:zlib";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_FILE_COUNT = 128;
|
||||
const MAX_CSS_BYTES = 512 * 1024;
|
||||
const MAX_CONTENT_BYTES = 256 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const MAX_SKINS = 50;
|
||||
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice"] as const;
|
||||
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
const LOCAL_SIGNATURE = 0x04034b50;
|
||||
|
||||
export interface SkinCatalogEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
license: string;
|
||||
description?: string;
|
||||
minAppVersion: string;
|
||||
previewUrl?: string;
|
||||
previewMimeType?: string;
|
||||
installedAt: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SkinRegistrySettings {
|
||||
defaultSkinId: string;
|
||||
}
|
||||
|
||||
interface SkinArchiveEntry {
|
||||
path: string;
|
||||
compressedSize: number;
|
||||
expandedSize: number;
|
||||
compression: number;
|
||||
crc: number;
|
||||
localOffset: number;
|
||||
flags: number;
|
||||
isDirectory: boolean;
|
||||
unixFileType: number;
|
||||
}
|
||||
|
||||
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
|
||||
entry: string;
|
||||
content?: string;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
export class SkinRegistryError extends Error {
|
||||
constructor(message: string, readonly code: string) {
|
||||
super(message);
|
||||
this.name = "SkinRegistryError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isBuiltinSkinId(id: string): boolean {
|
||||
return BUILTIN_SKIN_ID_SET.has(id);
|
||||
}
|
||||
|
||||
export class SkinRegistry {
|
||||
constructor(private readonly directory: string) {}
|
||||
|
||||
async list(): Promise<SkinCatalogEntry[]> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const names = await readdir(this.directory);
|
||||
const entries: SkinCatalogEntry[] = [];
|
||||
for (const filename of names.filter((item) => item.endsWith(".json"))) {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8"));
|
||||
if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue;
|
||||
const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null);
|
||||
if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue;
|
||||
entries.push({ ...value, enabled: value.enabled !== false });
|
||||
} catch {
|
||||
// Ignore incomplete or stale metadata. The archive itself remains untouched.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
async save(bytes: Buffer, expectedId: string): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(expectedId)) throw new SkinRegistryError("Built-in skins cannot be replaced.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID");
|
||||
const parsed = validateSkinArchive(bytes, expectedId);
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const current = await this.list();
|
||||
const replacing = current.some((entry) => entry.id === expectedId);
|
||||
if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT");
|
||||
const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size })));
|
||||
const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength);
|
||||
if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT");
|
||||
|
||||
const previous = current.find((entry) => entry.id === expectedId);
|
||||
const installedAt = previous?.installedAt ?? Date.now();
|
||||
const catalog: SkinCatalogEntry = {
|
||||
...parsed.manifest,
|
||||
installedAt,
|
||||
enabled: previous?.enabled ?? true,
|
||||
...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}),
|
||||
};
|
||||
const nonce = randomBytes(6).toString("hex");
|
||||
const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`);
|
||||
const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`);
|
||||
const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`);
|
||||
try {
|
||||
await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 });
|
||||
await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 });
|
||||
if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 });
|
||||
await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`));
|
||||
await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`));
|
||||
const previewPath = path.join(this.directory, `${expectedId}.preview`);
|
||||
if (parsed.previewBytes) await rename(previewTemp, previewPath);
|
||||
else await unlink(previewPath).catch(() => undefined);
|
||||
} catch (error) {
|
||||
await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined)));
|
||||
throw error;
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
async readArchive(id: string): Promise<Buffer | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
if (!(await this.list()).some((entry) => entry.id === id && entry.enabled)) return null;
|
||||
try { return await readFile(path.join(this.directory, `${id}.wskin`)); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
const catalog = (await this.list()).find((entry) => entry.id === id);
|
||||
if (!catalog?.enabled || !catalog.previewUrl) return null;
|
||||
const mimeType = catalog.previewMimeType || "application/octet-stream";
|
||||
try {
|
||||
const bytes = await readFile(path.join(this.directory, `${id}.preview`));
|
||||
return { bytes, mimeType };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<boolean> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be removed.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(id)) return false;
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const archive = path.join(this.directory, `${id}.wskin`);
|
||||
const catalog = path.join(this.directory, `${id}.json`);
|
||||
const preview = path.join(this.directory, `${id}.preview`);
|
||||
const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean));
|
||||
if (!present) return false;
|
||||
await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
})));
|
||||
if (wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return true;
|
||||
}
|
||||
|
||||
async setEnabled(id: string, enabled: boolean): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be disabled.", "SKIN_BUILTIN_PROTECTED");
|
||||
const entry = (await this.list()).find((item) => item.id === id);
|
||||
if (!entry) throw new SkinRegistryError("The skin was not found.", "SKIN_NOT_FOUND");
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const updated = { ...entry, enabled };
|
||||
await writeAtomicJson(path.join(this.directory, `${id}.json`), updated);
|
||||
if (!enabled && wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return updated;
|
||||
}
|
||||
|
||||
async getDefaultSkinId(): Promise<string> {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, "settings.json"), "utf8"));
|
||||
const id = value && typeof value === "object" ? (value as Record<string, unknown>).defaultSkinId : null;
|
||||
if (typeof id !== "string") return "builtin.light";
|
||||
if (isBuiltinSkinId(id)) return id;
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
return entry ? id : "builtin.light";
|
||||
} catch {
|
||||
return "builtin.light";
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultSkin(id: string): Promise<SkinRegistrySettings> {
|
||||
if (!isBuiltinSkinId(id)) {
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
if (!entry) throw new SkinRegistryError("The default skin must be enabled and installed.", "SKIN_DEFAULT_INVALID");
|
||||
}
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const settings = { defaultSkinId: id };
|
||||
await writeAtomicJson(path.join(this.directory, "settings.json"), settings);
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAtomicJson(filename: string, value: unknown): Promise<void> {
|
||||
const temporary = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||
await rename(temporary, filename);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
|
||||
const entries = inspectArchive(bytes);
|
||||
const regularEntries = entries.filter((entry) => !entry.isDirectory);
|
||||
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
|
||||
const fileBytes = new Map<string, Buffer>();
|
||||
for (const entry of regularEntries) {
|
||||
const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
|
||||
if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const content = extractEntry(bytes, entry);
|
||||
if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID");
|
||||
if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE");
|
||||
fileBytes.set(packagePath, content);
|
||||
}
|
||||
const manifestBytes = fileBytes.get("manifest.json");
|
||||
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
|
||||
const manifest = parseManifest(manifestBytes);
|
||||
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
|
||||
const cssBytes = fileBytes.get(manifest.entry);
|
||||
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
|
||||
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
|
||||
|
||||
let previewBytes: Buffer | undefined;
|
||||
let previewMime: string | undefined;
|
||||
for (const [packagePath, data] of fileBytes) {
|
||||
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
|
||||
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
|
||||
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
|
||||
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
}
|
||||
if (manifest.content) {
|
||||
const content = fileBytes.get(manifest.content);
|
||||
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
|
||||
decodeUtf8(content, "content.json is not valid UTF-8.");
|
||||
try { JSON.parse(content.toString("utf8")); }
|
||||
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
|
||||
}
|
||||
if (manifest.preview) {
|
||||
previewBytes = fileBytes.get(manifest.preview);
|
||||
previewMime = imageMime(manifest.preview) ?? undefined;
|
||||
if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
|
||||
}
|
||||
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
|
||||
}
|
||||
|
||||
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
|
||||
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
|
||||
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
|
||||
let endOffset = -1;
|
||||
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
|
||||
if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; }
|
||||
}
|
||||
if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const disk = bytes.readUInt16LE(endOffset + 4);
|
||||
const centralDisk = bytes.readUInt16LE(endOffset + 6);
|
||||
const entriesOnDisk = bytes.readUInt16LE(endOffset + 8);
|
||||
const entryCount = bytes.readUInt16LE(endOffset + 10);
|
||||
const centralSize = bytes.readUInt32LE(endOffset + 12);
|
||||
const centralOffset = bytes.readUInt32LE(endOffset + 16);
|
||||
const commentLength = bytes.readUInt16LE(endOffset + 20);
|
||||
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) {
|
||||
throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT");
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const entries: SkinArchiveEntry[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
let offset = centralOffset;
|
||||
let totalExpanded = 0;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID");
|
||||
const madeBy = bytes.readUInt16LE(offset + 4);
|
||||
const flags = bytes.readUInt16LE(offset + 8);
|
||||
const compression = bytes.readUInt16LE(offset + 10);
|
||||
const crc = bytes.readUInt32LE(offset + 16);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 20);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 24);
|
||||
const nameLength = bytes.readUInt16LE(offset + 28);
|
||||
const extraLength = bytes.readUInt16LE(offset + 30);
|
||||
const fileCommentLength = bytes.readUInt16LE(offset + 32);
|
||||
const diskStart = bytes.readUInt16LE(offset + 34);
|
||||
const externalAttributes = bytes.readUInt32LE(offset + 38);
|
||||
const localOffset = bytes.readUInt32LE(offset + 42);
|
||||
const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength;
|
||||
if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) {
|
||||
throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
let entryPath: string;
|
||||
try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID");
|
||||
if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const normalizedPath = entryPath.toLowerCase();
|
||||
if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
|
||||
seenPaths.add(normalizedPath);
|
||||
const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0;
|
||||
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
|
||||
const isDirectory = entryPath.endsWith("/");
|
||||
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
|
||||
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
|
||||
if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
|
||||
if (!isDirectory) {
|
||||
totalExpanded += expandedSize;
|
||||
if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE");
|
||||
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
|
||||
}
|
||||
entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType });
|
||||
offset = recordEnd;
|
||||
}
|
||||
if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID");
|
||||
validateLocalEntries(bytes, entries, centralOffset, decoder);
|
||||
return entries;
|
||||
}
|
||||
|
||||
function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void {
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
for (const entry of entries) {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = bytes.readUInt16LE(offset + 6);
|
||||
const compression = bytes.readUInt16LE(offset + 8);
|
||||
const crc = bytes.readUInt32LE(offset + 14);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 18);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 22);
|
||||
const nameLength = bytes.readUInt16LE(offset + 26);
|
||||
const extraLength = bytes.readUInt16LE(offset + 28);
|
||||
const headerEnd = offset + 30 + nameLength + extraLength;
|
||||
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
|
||||
throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
let localPath: string;
|
||||
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
|
||||
const end = headerEnd + entry.compressedSize;
|
||||
if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
|
||||
spans.push({ start: offset, end });
|
||||
}
|
||||
spans.sort((left, right) => left.start - right.start);
|
||||
for (let index = 1; index < spans.length; index += 1) {
|
||||
if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = archive.readUInt16LE(offset + 6);
|
||||
const compression = archive.readUInt16LE(offset + 8);
|
||||
const nameLength = archive.readUInt16LE(offset + 26);
|
||||
const extraLength = archive.readUInt16LE(offset + 28);
|
||||
if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID");
|
||||
const dataStart = offset + 30 + nameLength + extraLength;
|
||||
const dataEnd = dataStart + entry.compressedSize;
|
||||
if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID");
|
||||
const compressed = archive.subarray(dataStart, dataEnd);
|
||||
if (entry.compression === 0) return Buffer.from(compressed);
|
||||
try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); }
|
||||
catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); }
|
||||
}
|
||||
|
||||
function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); }
|
||||
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const value = raw as Record<string, unknown>;
|
||||
const read = (key: string, max: number): string => {
|
||||
const item = value[key];
|
||||
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return item.trim();
|
||||
};
|
||||
const id = read("id", 80);
|
||||
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
const version = read("version", 32);
|
||||
const minAppVersion = read("minAppVersion", 32);
|
||||
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
const entry = read("entry", 120);
|
||||
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
|
||||
const content = readOptional("content", 120);
|
||||
const preview = readOptional("preview", 120);
|
||||
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
if (!paths.length) return "";
|
||||
const firstSlash = paths[0].indexOf("/");
|
||||
if (firstSlash < 1) return "";
|
||||
const prefix = paths[0].slice(0, firstSlash + 1);
|
||||
return paths.every((item) => item.startsWith(prefix)) ? prefix : "";
|
||||
}
|
||||
|
||||
function isSafePackagePath(value: string, allowDirectory = false): boolean {
|
||||
const candidate = allowDirectory ? value.slice(0, -1) : value;
|
||||
return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate)
|
||||
&& candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":"));
|
||||
}
|
||||
|
||||
function isSafeSkinId(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin.");
|
||||
}
|
||||
|
||||
function imageMime(filename: string): string | null {
|
||||
switch (path.extname(filename).toLowerCase()) {
|
||||
case ".png": return "image/png";
|
||||
case ".jpg": case ".jpeg": return "image/jpeg";
|
||||
case ".webp": return "image/webp";
|
||||
case ".avif": return "image/avif";
|
||||
case ".gif": return "image/gif";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeUtf8(bytes: Buffer, message: string): string {
|
||||
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||
catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); }
|
||||
}
|
||||
|
||||
function isCatalogEntry(value: unknown): value is SkinCatalogEntry {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const item = value as Record<string, unknown>;
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false;
|
||||
if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false;
|
||||
if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false;
|
||||
if (item.enabled !== undefined && typeof item.enabled !== "boolean") return false;
|
||||
if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false;
|
||||
const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined;
|
||||
return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType)));
|
||||
}
|
||||
|
||||
function isShortText(value: unknown, limit: number): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.length <= limit;
|
||||
}
|
||||
|
||||
const crcTable = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < table.length; index += 1) {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
table[index] = value >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -1,45 +1,416 @@
|
||||
export type WebSpeakErrorCode =
|
||||
| "invalid_target"
|
||||
| "invalid_nickname"
|
||||
| "nickname_in_use"
|
||||
| "host_not_found"
|
||||
| "unreachable"
|
||||
| "connection_refused"
|
||||
| "connection_reset"
|
||||
| "timeout"
|
||||
| "authentication_failed"
|
||||
| "protocol_negotiation_failed"
|
||||
| "channel_password_required"
|
||||
| "identity_security_level_too_low"
|
||||
| "identity_limit_reached"
|
||||
| "client_version_outdated"
|
||||
| "flooding"
|
||||
| "banned"
|
||||
| "kicked"
|
||||
| "server_shutting_down"
|
||||
| "server_full"
|
||||
| "invalid_parameter_size"
|
||||
| "connection_initialisation_failed"
|
||||
| "protocol_negotiation_failed"
|
||||
| "unknown";
|
||||
|
||||
export type ClientConnectionFailureCode =
|
||||
| "INVALID_TARGET"
|
||||
| "INVALID_NICKNAME"
|
||||
| "NICKNAME_IN_USE"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "SERVER_PASSWORD_REQUIRED"
|
||||
| "INVALID_SERVER_PASSWORD"
|
||||
| "CHANNEL_PASSWORD_REQUIRED"
|
||||
| "IDENTITY_SECURITY_LEVEL_TOO_LOW"
|
||||
| "IDENTITY_LIMIT_REACHED"
|
||||
| "CLIENT_VERSION_OUTDATED"
|
||||
| "FLOOD_PROTECTION"
|
||||
| "BANNED"
|
||||
| "KICKED"
|
||||
| "SERVER_SHUTTING_DOWN"
|
||||
| "SERVER_FULL"
|
||||
| "INVALID_PARAMETER"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "CONNECTION_INITIALISATION_FAILED"
|
||||
| "CONNECTION_FAILED";
|
||||
|
||||
export interface TeamSpeakErrorDiagnostics {
|
||||
name?: string;
|
||||
code?: string;
|
||||
id?: string;
|
||||
serverMessage?: string;
|
||||
message?: string;
|
||||
syscall?: string;
|
||||
address?: string;
|
||||
port?: number | string;
|
||||
cause?: string;
|
||||
}
|
||||
|
||||
export class WebSpeakError extends Error {
|
||||
readonly code: WebSpeakErrorCode;
|
||||
readonly retryable: boolean;
|
||||
readonly cause?: unknown;
|
||||
readonly diagnostics: TeamSpeakErrorDiagnostics;
|
||||
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown) {
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown, diagnostics: TeamSpeakErrorDiagnostics = {}) {
|
||||
super(message);
|
||||
this.name = "WebSpeakError";
|
||||
this.code = code;
|
||||
this.retryable = retryable;
|
||||
this.cause = cause;
|
||||
this.diagnostics = diagnostics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamSpeak server error ids (SDK `public_errors.h`, shared by TS3 and TS6) that
|
||||
* the gateway can name precisely. Ids that are absent on purpose fall through to
|
||||
* the text heuristics below and finally to `unknown`, which still carries the raw
|
||||
* server detail to the browser.
|
||||
*/
|
||||
export const TEAMSPEAK_SERVER_ERROR_IDS: Readonly<Record<string, WebSpeakErrorCode>> = {
|
||||
// Client (0x02xx): nickname, capacity, identity, password, version, flooding.
|
||||
"513": "nickname_in_use",
|
||||
"515": "server_full",
|
||||
"519": "identity_security_level_too_low",
|
||||
"520": "authentication_failed",
|
||||
"521": "identity_limit_reached",
|
||||
"522": "client_version_outdated",
|
||||
"524": "flooding",
|
||||
// Parameter (0x06xx). 1541 is the generic "invalid parameter size" error;
|
||||
// connection-specific classification decides whether that means a nickname.
|
||||
"1536": "invalid_parameter_size",
|
||||
"1537": "invalid_parameter_size",
|
||||
"1538": "invalid_parameter_size",
|
||||
"1539": "invalid_parameter_size",
|
||||
"1540": "invalid_parameter_size",
|
||||
"1541": "invalid_parameter_size",
|
||||
"1542": "invalid_parameter_size",
|
||||
"1543": "protocol_negotiation_failed",
|
||||
// Connection (0x07xx). Keep only ids whose official meaning matches the
|
||||
// normalized code; unrelated SDK operation errors must not be relabelled.
|
||||
"1797": "connection_initialisation_failed",
|
||||
"1798": "host_not_found",
|
||||
"1805": "protocol_negotiation_failed",
|
||||
"1806": "protocol_negotiation_failed",
|
||||
// Server (0x04xx).
|
||||
"1026": "server_shutting_down",
|
||||
"1027": "server_full",
|
||||
"1028": "authentication_failed",
|
||||
"781": "channel_password_required",
|
||||
// Accounting (0x0bxx): the slot and virtual-server limits both surface as a
|
||||
// full server from the user's point of view.
|
||||
"2816": "server_full",
|
||||
"2817": "server_full",
|
||||
// Ban (0x0dxx).
|
||||
"3329": "banned",
|
||||
"3330": "banned",
|
||||
"3331": "flooding",
|
||||
};
|
||||
|
||||
/**
|
||||
* Default (English) message per normalized code. The browser translates these
|
||||
* strings for zh/en/de, so keep them stable and never embed a raw server id here:
|
||||
* the raw detail travels separately in `diagnostics`.
|
||||
*/
|
||||
export const WEBSPEAK_ERROR_MESSAGES: Readonly<Record<WebSpeakErrorCode, string>> = {
|
||||
invalid_target: "The TeamSpeak server address is invalid",
|
||||
invalid_nickname: "TeamSpeak refused the nickname: it must be 3-30 characters long",
|
||||
nickname_in_use: "This nickname is already used by another user on the TeamSpeak server",
|
||||
host_not_found: "TeamSpeak server hostname could not be resolved",
|
||||
unreachable: "TeamSpeak server is unreachable",
|
||||
connection_refused: "TeamSpeak server refused the connection",
|
||||
connection_reset: "TeamSpeak connection was reset",
|
||||
timeout: "TeamSpeak connection timed out",
|
||||
authentication_failed: "TeamSpeak authentication failed",
|
||||
channel_password_required: "The TeamSpeak channel requires a password",
|
||||
identity_security_level_too_low: "This TeamSpeak identity's security level is below the server requirement",
|
||||
identity_limit_reached: "This TeamSpeak identity already holds the maximum number of connections",
|
||||
client_version_outdated: "The TeamSpeak server requires a newer client version",
|
||||
flooding: "The TeamSpeak server's flood protection refused the connection",
|
||||
banned: "You are banned from this TeamSpeak server",
|
||||
kicked: "You were kicked from the TeamSpeak server",
|
||||
server_shutting_down: "The TeamSpeak server is shutting down",
|
||||
connection_initialisation_failed: "The TeamSpeak server refused the connection during initialisation",
|
||||
server_full: "The TeamSpeak server is full",
|
||||
invalid_parameter_size: "TeamSpeak refused a parameter because its length or value is out of range",
|
||||
protocol_negotiation_failed: "TeamSpeak protocol negotiation failed",
|
||||
unknown: "TeamSpeak connection failed",
|
||||
};
|
||||
|
||||
// 不可重连的错误码集合:这些错误原样重连必然失败(如被封禁、昵称被占用等),
|
||||
// 集合与消息表相邻存放便于审计重连决策;unknown 保持不可重连,防止未映射的
|
||||
// 服务器拒绝演变成无限重连循环。
|
||||
/**
|
||||
* Codes for which reconnecting unchanged cannot succeed. Keeping the list next to
|
||||
* the messages makes the retry decision auditable; `unknown` stays non-retryable
|
||||
* so an unmapped server refusal can never turn into a reconnect loop.
|
||||
*/
|
||||
const NON_RETRYABLE_CODES: ReadonlySet<WebSpeakErrorCode> = new Set<WebSpeakErrorCode>([
|
||||
"invalid_target",
|
||||
"invalid_nickname",
|
||||
"nickname_in_use",
|
||||
"authentication_failed",
|
||||
"channel_password_required",
|
||||
"identity_security_level_too_low",
|
||||
"identity_limit_reached",
|
||||
"client_version_outdated",
|
||||
"banned",
|
||||
"kicked",
|
||||
"invalid_parameter_size",
|
||||
"connection_initialisation_failed",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnostics: TeamSpeakErrorDiagnostics): WebSpeakError {
|
||||
return new WebSpeakError(code, WEBSPEAK_ERROR_MESSAGES[code], !NON_RETRYABLE_CODES.has(code), cause, diagnostics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw TeamSpeak server error id to a normalized code. Accepts the
|
||||
* decimal form the SDK forwards (`err.id`, `id=515`) and the hex form used by the
|
||||
* official headers (`0x0203`), because both shapes show up in logs.
|
||||
*/
|
||||
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
|
||||
if (id === undefined || id === null) return null;
|
||||
const text = String(id).trim().toLocaleLowerCase();
|
||||
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
|
||||
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
|
||||
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
// 归一化入口:按「服务器错误ID → 关键词启发式 → 异常类名 → 传输层特征」的
|
||||
// 优先级,把 SDK/Node 抛出的原始错误收敛为带稳定错误码的 WebSpeakError。
|
||||
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
if (error instanceof WebSpeakError) return error;
|
||||
|
||||
const candidate = error as { code?: unknown; message?: unknown } | null;
|
||||
const code = typeof candidate?.code === "string" ? candidate.code : "";
|
||||
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
|
||||
const text = `${code} ${message}`.toLocaleLowerCase();
|
||||
const diagnostics = collectDiagnostics(error);
|
||||
const text = diagnosticText(error).toLocaleLowerCase();
|
||||
|
||||
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
|
||||
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error);
|
||||
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
|
||||
// keyword heuristic below. The inline scan keeps the `id=515` shape
|
||||
// working even when the SDK does not attach the id as a structured field.
|
||||
const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(text)?.[1];
|
||||
const serverErrorCode =
|
||||
teamSpeakServerErrorCode(diagnostics.id) ?? teamSpeakServerErrorCode(diagnostics.code) ?? teamSpeakServerErrorCode(inlineId);
|
||||
if (serverErrorCode) return createTeamSpeakError(serverErrorCode, error, diagnostics);
|
||||
|
||||
// 2) Explicit refusals that arrive without a stable id. Every pattern stays
|
||||
// narrow on purpose: bare words such as "password", "network", "socket",
|
||||
// "crypto" or "denied" also appear in unrelated Teamspeak messages and used
|
||||
// to steal the classification from the real cause.
|
||||
if (/nickname.{0,20}(length|size)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_nickname", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout/.test(text)) {
|
||||
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error);
|
||||
if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_parameter_size", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|enotfound|ehostunreach|enetunreach|network|socket|dns/.test(text)) {
|
||||
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error);
|
||||
if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) {
|
||||
return createTeamSpeakError("nickname_in_use", error, diagnostics);
|
||||
}
|
||||
if (/protocol|handshake|crypto|init1/.test(text)) {
|
||||
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error);
|
||||
if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) {
|
||||
return createTeamSpeakError("channel_password_required", error, diagnostics);
|
||||
}
|
||||
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
|
||||
if (/security ?level|insufficient security|could not validate identity/.test(text)) {
|
||||
return createTeamSpeakError("identity_security_level_too_low", error, diagnostics);
|
||||
}
|
||||
if (/too many clones|clone.{0,20}(limit|connected)|identity.{0,20}(limit|maximum|max).{0,20}connection/.test(text)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/version.{0,25}(outdated|out of date|too old|not allowed|unsupported)|outdated.{0,25}version/.test(text)) {
|
||||
return createTeamSpeakError("client_version_outdated", error, diagnostics);
|
||||
}
|
||||
if (/flood/.test(text)) {
|
||||
return createTeamSpeakError("flooding", error, diagnostics);
|
||||
}
|
||||
if (/\bban(ned)?\b|blacklist|you may retry in/.test(text)) {
|
||||
return createTeamSpeakError("banned", error, diagnostics);
|
||||
}
|
||||
if (/kicked/.test(text)) {
|
||||
return createTeamSpeakError("kicked", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,20}shut ?down|server_shutdown|server is shutting down/.test(text)) {
|
||||
return createTeamSpeakError("server_shutting_down", error, diagnostics);
|
||||
}
|
||||
if (/failed[\s_-]*connection[\s_-]*initiali[sz]ation|connection initiali[sz]ation failed|failed to (initialise|initialize) the connection/.test(text)) {
|
||||
return createTeamSpeakError("connection_initialisation_failed", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,25}full|server is full|maximum (number of )?(clients|slots)|slot limit|client protocol limit/.test(text)) {
|
||||
return createTeamSpeakError("server_full", error, diagnostics);
|
||||
}
|
||||
if (/invalid (server )?password|wrong (server )?password|password (is )?(invalid|incorrect|wrong)|password required|i_server_password|authentication failed|not authorized|invalid credential|login (failed|refused)/.test(text)) {
|
||||
return createTeamSpeakError("authentication_failed", error, diagnostics);
|
||||
}
|
||||
|
||||
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
|
||||
// the class name before falling back to the message text.
|
||||
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
|
||||
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
if (/alreadyconnected/.test(errorName)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/timeout/.test(errorName)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
|
||||
// 4) Transport level failures reported by Node or the TLS layer.
|
||||
if (/enotfound|eai_again|host not found|name or service not known|getaddrinfo/.test(text)) {
|
||||
return createTeamSpeakError("host_not_found", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|connection refused/.test(text)) {
|
||||
return createTeamSpeakError("connection_refused", error, diagnostics);
|
||||
}
|
||||
if (/econnreset|econnaborted|connection reset|connection aborted|socket hang up/.test(text)) {
|
||||
return createTeamSpeakError("connection_reset", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout|etimedout/.test(text)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
if (/ehostunreach|enetunreach|network is unreachable|no route to host|unable to connect|transport error|unexpected eof/.test(text)) {
|
||||
return createTeamSpeakError("unreachable", error, diagnostics);
|
||||
}
|
||||
if (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
return createTeamSpeakError("unknown", error, diagnostics);
|
||||
}
|
||||
|
||||
export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode {
|
||||
if (error.code === "authentication_failed") {
|
||||
return serverPassword.trim() ? "INVALID_SERVER_PASSWORD" : "SERVER_PASSWORD_REQUIRED";
|
||||
}
|
||||
const mapping: Record<WebSpeakErrorCode, ClientConnectionFailureCode> = {
|
||||
invalid_target: "INVALID_TARGET",
|
||||
invalid_nickname: "INVALID_NICKNAME",
|
||||
nickname_in_use: "NICKNAME_IN_USE",
|
||||
host_not_found: "HOST_NOT_FOUND",
|
||||
unreachable: "UNREACHABLE",
|
||||
connection_refused: "CONNECTION_REFUSED",
|
||||
connection_reset: "CONNECTION_RESET",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: "SERVER_PASSWORD_REQUIRED",
|
||||
channel_password_required: "CHANNEL_PASSWORD_REQUIRED",
|
||||
identity_security_level_too_low: "IDENTITY_SECURITY_LEVEL_TOO_LOW",
|
||||
identity_limit_reached: "IDENTITY_LIMIT_REACHED",
|
||||
client_version_outdated: "CLIENT_VERSION_OUTDATED",
|
||||
flooding: "FLOOD_PROTECTION",
|
||||
banned: "BANNED",
|
||||
kicked: "KICKED",
|
||||
server_shutting_down: "SERVER_SHUTTING_DOWN",
|
||||
connection_initialisation_failed: "CONNECTION_INITIALISATION_FAILED",
|
||||
server_full: "SERVER_FULL",
|
||||
// During the initial connect handshake this generic TeamSpeak id is most
|
||||
// commonly emitted for an invalid nickname length/format. Operation errors
|
||||
// still retain the generic invalid_parameter_size message.
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
unknown: "CONNECTION_FAILED",
|
||||
};
|
||||
return mapping[error.code];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the SDK `kicked` event. TeamSpeak reports a kick/ban as a
|
||||
* `clientleftview` whose reason id is 4 (kicked) or 5 (kicked with ban) and whose
|
||||
* `reasonMsg` is written by the admin, e.g. "Slow down!" or "you may retry in
|
||||
* 300 seconds". Before this helper existed the reason text was dropped and the
|
||||
* browser only showed a generic connection failure, which is exactly the
|
||||
* experience this translation layer removes. The ban/kick split prefers the
|
||||
* server text and falls back to reason id 5.
|
||||
*/
|
||||
export function normalizeTeamSpeakKickedReason(reasonMsg: unknown, reasonId?: unknown): WebSpeakError {
|
||||
const text = typeof reasonMsg === "string" ? reasonMsg.trim() : "";
|
||||
const numericReasonId = typeof reasonId === "number" ? reasonId : Number(reasonId);
|
||||
const isBan = /\bban(ned)?\b|blacklist|you may retry in/i.test(text) || numericReasonId === 5;
|
||||
const diagnostics: TeamSpeakErrorDiagnostics = { name: isBan ? "TeamSpeakBan" : "TeamSpeakKick" };
|
||||
if (text) diagnostics.serverMessage = text;
|
||||
if (Number.isFinite(numericReasonId)) diagnostics.id = String(numericReasonId);
|
||||
return createTeamSpeakError(isBan ? "banned" : "kicked", reasonMsg, diagnostics);
|
||||
}
|
||||
|
||||
/** Format useful SDK/Node details for a safe operational log field. */
|
||||
export function describeTeamSpeakError(error: WebSpeakError): string {
|
||||
const details = error.diagnostics;
|
||||
const parts = [
|
||||
details.name,
|
||||
details.code,
|
||||
details.id ? `id=${details.id}` : "",
|
||||
details.serverMessage,
|
||||
details.syscall,
|
||||
details.address ? `address=${details.address}` : "",
|
||||
details.port !== undefined ? `port=${details.port}` : "",
|
||||
details.cause,
|
||||
details.message,
|
||||
].filter(Boolean);
|
||||
return parts.length ? parts.join("; ") : error.message;
|
||||
}
|
||||
|
||||
function diagnosticText(error: unknown): string {
|
||||
const values: string[] = [];
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) values.push(current.name, current.message);
|
||||
else values.push(String(current));
|
||||
if (typeof current === "object") {
|
||||
const candidate = current as { code?: unknown; id?: unknown; serverMessage?: unknown; cause?: unknown };
|
||||
for (const value of [candidate.code, candidate.id, candidate.serverMessage]) if (value !== undefined) values.push(String(value));
|
||||
current = candidate.cause;
|
||||
} else break;
|
||||
}
|
||||
return values.join(" ");
|
||||
}
|
||||
|
||||
function collectDiagnostics(error: unknown): TeamSpeakErrorDiagnostics {
|
||||
const result: TeamSpeakErrorDiagnostics = {};
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) {
|
||||
result.name ??= current.name;
|
||||
result.message ??= current.message;
|
||||
const errorRecord = current as Error & Record<string, unknown>;
|
||||
if (typeof errorRecord.code === "string" || typeof errorRecord.code === "number") result.code ??= String(errorRecord.code);
|
||||
if (typeof errorRecord.id === "string" || typeof errorRecord.id === "number") result.id ??= String(errorRecord.id);
|
||||
if (typeof errorRecord.serverMessage === "string") result.serverMessage ??= errorRecord.serverMessage;
|
||||
if (typeof errorRecord.syscall === "string") result.syscall ??= errorRecord.syscall;
|
||||
if (typeof errorRecord.address === "string") result.address ??= errorRecord.address;
|
||||
if (typeof errorRecord.port === "string" || typeof errorRecord.port === "number") result.port ??= errorRecord.port;
|
||||
const cause = current.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
if (typeof current !== "object") { result.cause ??= String(current); break; }
|
||||
const candidate = current as Record<string, unknown>;
|
||||
if (typeof candidate.name === "string") result.name ??= candidate.name;
|
||||
if (typeof candidate.code === "string" || typeof candidate.code === "number") result.code ??= String(candidate.code);
|
||||
if (typeof candidate.id === "string" || typeof candidate.id === "number") result.id ??= String(candidate.id);
|
||||
if (typeof candidate.serverMessage === "string") result.serverMessage ??= candidate.serverMessage;
|
||||
if (typeof candidate.message === "string") result.message ??= candidate.message;
|
||||
if (typeof candidate.syscall === "string") result.syscall ??= candidate.syscall;
|
||||
if (typeof candidate.address === "string") result.address ??= candidate.address;
|
||||
if (typeof candidate.port === "string" || typeof candidate.port === "number") result.port ??= candidate.port;
|
||||
const cause = candidate.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
import path from "node:path";
|
||||
import { existsSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { createWebServer } from "./server/server.js";
|
||||
import { APP_PORT } from "./constants.js";
|
||||
import { WebSpeakDatabase } from "./persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "./security/master-secret.js";
|
||||
import { AdminService } from "./admin/admin-service.js";
|
||||
import { JoinTicketStore } from "./server/join-ticket.js";
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -19,8 +15,22 @@ const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "d
|
||||
const LOG_DIR = path.join(DATA_DIR, "logs");
|
||||
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
const APP_VERSION = readPackageVersion();
|
||||
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
|
||||
|
||||
async function main() {
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
await runRelayMode();
|
||||
return;
|
||||
}
|
||||
const [{ createLogger }, { createWebServer }, { APP_PORT }, { WebSpeakDatabase }, { loadOrCreateMasterSecret }, { AdminService }, { JoinTicketStore }] = await Promise.all([
|
||||
import("./logger.js"),
|
||||
import("./server/server.js"),
|
||||
import("./constants.js"),
|
||||
import("./persistence/database.js"),
|
||||
import("./security/master-secret.js"),
|
||||
import("./admin/admin-service.js"),
|
||||
import("./server/join-ticket.js"),
|
||||
]);
|
||||
const logger = createLogger(LOG_DIR);
|
||||
const database = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
|
||||
const masterSecret = loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key"));
|
||||
@@ -49,9 +59,19 @@ async function main() {
|
||||
voiceBridgeOptions: {
|
||||
joinTickets,
|
||||
webRtc: () => adminService.getWebRtcAudioOptions(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
// standalone relay process and must never make the relay option appear
|
||||
// in the visitor UI after an administrator disables it.
|
||||
acceleration: () => adminService.getAccelerationRelayOptions(),
|
||||
accelerationName: () => adminService.getAccelerationRelayName(),
|
||||
},
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
});
|
||||
|
||||
await webServer.start();
|
||||
@@ -67,6 +87,22 @@ async function main() {
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
}
|
||||
|
||||
async function runRelayMode(): Promise<void> {
|
||||
const token = (process.env.WEBSPEAK_RELAY_TOKEN || process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN)?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_RELAY_TOKEN is required in relay mode");
|
||||
const host = (process.env.WEBSPEAK_RELAY_HOST || process.env.WEBSPEAK_ACCELERATION_RELAY_HOST)?.trim() || "0.0.0.0";
|
||||
const port = parsePort(process.env.WEBSPEAK_RELAY_PORT || process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087);
|
||||
const allowPrivate = parseBoolean(process.env.WEBSPEAK_RELAY_ALLOW_PRIVATE || process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE);
|
||||
const server = await createAccelerationRelayServer({ host, port, token, allowPrivate });
|
||||
console.log(`WebSpeak relay mode listening on ${server.host}:${server.port}`);
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
function readPackageVersion(): string {
|
||||
try {
|
||||
const packageJson = JSON.parse(readFileSync(path.join(ROOT_DIR, "package.json"), "utf8")) as { version?: unknown };
|
||||
@@ -84,6 +120,28 @@ function removeObsoleteBootstrapFile(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid relay port");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
|
||||
const raw = value?.trim();
|
||||
if (!raw) return normalizeScreenShareIceServers();
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined);
|
||||
} catch {
|
||||
// A simple comma/space-separated list is convenient for STUN-only setups.
|
||||
return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -6,12 +6,16 @@ import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 3;
|
||||
export const DATABASE_SCHEMA_VERSION = 7;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn: string;
|
||||
welcomeTextDe: string;
|
||||
welcomeTextRu: string;
|
||||
welcomeTextJa: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -23,12 +27,22 @@ export interface PersistedSettings {
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -36,6 +50,23 @@ export interface SettingsUpdate {
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
}
|
||||
|
||||
export interface PersistedRelayNode {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
tokenEncrypted: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ManagedInviteRecord {
|
||||
@@ -69,6 +100,10 @@ interface ManagedInviteRow extends Record<string, unknown> {
|
||||
interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
welcome_text_en: string;
|
||||
welcome_text_de: string;
|
||||
welcome_text_ru: string;
|
||||
welcome_text_ja: string;
|
||||
access_mode: string;
|
||||
ts_host: string;
|
||||
ts_port: number;
|
||||
@@ -81,6 +116,23 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
webrtc_public_host: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
relay_configured: number;
|
||||
relay_enabled: number;
|
||||
relay_name: string;
|
||||
relay_host: string;
|
||||
relay_port: number;
|
||||
relay_token_encrypted: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface RelayNodeRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: number;
|
||||
host: string;
|
||||
port: number;
|
||||
token_encrypted: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
@@ -143,6 +195,10 @@ export class WebSpeakDatabase {
|
||||
return {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
welcomeTextEn: row.welcome_text_en,
|
||||
welcomeTextDe: row.welcome_text_de,
|
||||
welcomeTextRu: row.welcome_text_ru,
|
||||
welcomeTextJa: row.welcome_text_ja,
|
||||
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
||||
tsHost: row.ts_host,
|
||||
tsPort: row.ts_port,
|
||||
@@ -154,10 +210,55 @@ export class WebSpeakDatabase {
|
||||
webRtcEnabled: row.webrtc_enabled === 1,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
relayEnabled: row.relay_enabled === 1,
|
||||
relayName: row.relay_name,
|
||||
relayHost: row.relay_host,
|
||||
relayPort: row.relay_port,
|
||||
relayTokenEncrypted: row.relay_token_encrypted,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
listRelayNodes(): PersistedRelayNode[] {
|
||||
const rows = this.database.prepare(
|
||||
"SELECT * FROM relay_nodes ORDER BY created_at ASC, id ASC",
|
||||
).all() as RelayNodeRow[];
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
enabled: row.enabled === 1,
|
||||
host: row.host,
|
||||
port: row.port,
|
||||
tokenEncrypted: row.token_encrypted,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
replaceRelayNodes(nodes: Array<Omit<PersistedRelayNode, "createdAt" | "updatedAt"> & { createdAt?: string; updatedAt?: string }>): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.database.exec("DELETE FROM relay_nodes");
|
||||
const insert = this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const node of nodes) {
|
||||
insert.run(
|
||||
node.id,
|
||||
node.name,
|
||||
node.enabled ? 1 : 0,
|
||||
node.host,
|
||||
node.port,
|
||||
node.tokenEncrypted,
|
||||
node.createdAt ?? now,
|
||||
node.updatedAt ?? now,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
@@ -276,6 +377,25 @@ export class WebSpeakDatabase {
|
||||
).run(key, value);
|
||||
}
|
||||
|
||||
nextVisitorNumber(): number {
|
||||
let nextNumber = 1;
|
||||
this.transaction(() => {
|
||||
const currentValue = this.getMeta("visitor_count");
|
||||
const current = currentValue ? Number.parseInt(currentValue, 10) : 0;
|
||||
nextNumber = Number.isSafeInteger(current) && current >= 0 && current < Number.MAX_SAFE_INTEGER
|
||||
? current + 1
|
||||
: 1;
|
||||
this.setMeta("visitor_count", String(nextNumber));
|
||||
});
|
||||
return nextNumber;
|
||||
}
|
||||
|
||||
getVisitorCount(): number {
|
||||
const value = this.getMeta("visitor_count");
|
||||
const count = value ? Number.parseInt(value, 10) : 0;
|
||||
return Number.isSafeInteger(count) && count >= 0 ? count : 0;
|
||||
}
|
||||
|
||||
addAudit(event: string, details: Record<string, unknown> = {}): void {
|
||||
this.insertAudit(event, details, new Date().toISOString());
|
||||
}
|
||||
@@ -377,19 +497,103 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 3");
|
||||
});
|
||||
version = 3;
|
||||
}
|
||||
if (version === 3) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 4");
|
||||
});
|
||||
version = 4;
|
||||
}
|
||||
if (version === 4) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN relay_configured INTEGER NOT NULL DEFAULT 0 CHECK (relay_configured IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_enabled INTEGER NOT NULL DEFAULT 0 CHECK (relay_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_port INTEGER NOT NULL DEFAULT 39087 CHECK (relay_port BETWEEN 1 AND 65535);
|
||||
ALTER TABLE settings ADD COLUMN relay_token_encrypted TEXT;
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 5");
|
||||
});
|
||||
version = 5;
|
||||
}
|
||||
if (version === 5) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE relay_nodes (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
|
||||
token_encrypted TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX relay_nodes_enabled_idx ON relay_nodes(enabled);
|
||||
`);
|
||||
const legacy = this.database.prepare(
|
||||
`SELECT relay_configured, relay_enabled, relay_name, relay_host, relay_port, relay_token_encrypted
|
||||
FROM settings WHERE id = 1`,
|
||||
).get() as {
|
||||
relay_configured?: number;
|
||||
relay_enabled?: number;
|
||||
relay_name?: string;
|
||||
relay_host?: string;
|
||||
relay_port?: number;
|
||||
relay_token_encrypted?: string | null;
|
||||
} | undefined;
|
||||
if (legacy?.relay_configured === 1 && legacy.relay_host && legacy.relay_token_encrypted) {
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES ('relay-default', ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
legacy.relay_name || "中继加速",
|
||||
legacy.relay_enabled === 1 ? 1 : 0,
|
||||
legacy.relay_host,
|
||||
legacy.relay_port || 39087,
|
||||
legacy.relay_token_encrypted,
|
||||
now,
|
||||
now,
|
||||
);
|
||||
}
|
||||
this.database.exec("PRAGMA user_version = 6");
|
||||
});
|
||||
version = 6;
|
||||
}
|
||||
if (version === 6) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_de TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ru TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ja TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, updated_at = ?
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.welcomeTextEn ?? "",
|
||||
settings.welcomeTextDe ?? "",
|
||||
settings.welcomeTextRu ?? "",
|
||||
settings.welcomeTextJa ?? "",
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
@@ -397,6 +601,12 @@ export class WebSpeakDatabase {
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
settings.relayEnabled ? 1 : 0,
|
||||
settings.relayName,
|
||||
settings.relayHost,
|
||||
settings.relayPort,
|
||||
settings.relayTokenEncrypted,
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_ACCELERATION_RELAY_TOKEN is required");
|
||||
|
||||
const server = await createAccelerationRelayServer({
|
||||
host: process.env.WEBSPEAK_ACCELERATION_RELAY_HOST?.trim() || "0.0.0.0",
|
||||
port: parsePort(process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087),
|
||||
token,
|
||||
allowPrivate: parseBoolean(process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE),
|
||||
});
|
||||
|
||||
console.log(`WebSpeak acceleration relay listening on ${server.host}:${server.port}`);
|
||||
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid WEBSPEAK_ACCELERATION_RELAY_PORT");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { lookup } from "node:dns/promises";
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const VERSION = 1;
|
||||
const HEADER_SIZE = 34;
|
||||
const MAX_PAYLOAD_SIZE = 60_000;
|
||||
export const DEFAULT_ACCELERATION_RELAY_PORT = 39087;
|
||||
|
||||
const enum FrameType {
|
||||
OPEN = 1,
|
||||
OPEN_OK = 2,
|
||||
OPEN_ERR = 3,
|
||||
DATA = 4,
|
||||
CLOSE = 5,
|
||||
PING = 6,
|
||||
PONG = 7,
|
||||
}
|
||||
|
||||
export interface AccelerationRelayOptions {
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
token: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface ConfiguredAccelerationRelay extends AccelerationRelayOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AccelerationTarget {
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface AccelerationRelayClient {
|
||||
readonly localHost: string;
|
||||
readonly localPort: number;
|
||||
readonly sessionId: number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface Frame {
|
||||
type: FrameType;
|
||||
sessionId: number;
|
||||
sequence: number;
|
||||
payload: Buffer;
|
||||
auth: Buffer;
|
||||
raw: Buffer;
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayClient(
|
||||
options: AccelerationRelayOptions & AccelerationTarget,
|
||||
): Promise<AccelerationRelayClient> {
|
||||
validateRelayOptions(options);
|
||||
const relayFamily = isIP(options.relayHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket("udp4");
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady: () => void = () => undefined;
|
||||
let rejectReady: (error: Error) => void = () => undefined;
|
||||
let keepAlive: ReturnType<typeof setInterval> | null = null;
|
||||
const readyPromise = new Promise<void>((resolve, reject) => {
|
||||
resolveReady = resolve;
|
||||
rejectReady = reject;
|
||||
});
|
||||
|
||||
const sendFrame = (type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, options.token);
|
||||
try {
|
||||
relaySocket.send(packet, options.relayPort, options.relayHost);
|
||||
} catch (error) {
|
||||
if (!ready) rejectReady(asError(error));
|
||||
}
|
||||
};
|
||||
|
||||
const closeSockets = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (keepAlive) clearInterval(keepAlive);
|
||||
keepAlive = null;
|
||||
try { relaySocket.close(); } catch { /* already closed */ }
|
||||
try { localSocket.close(); } catch { /* already closed */ }
|
||||
};
|
||||
|
||||
const onSocketError = (error: Error): void => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
let peer: { address: string; port: number } | null = null;
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, options.token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
if (ready) return;
|
||||
ready = true;
|
||||
keepAlive = setInterval(() => sendFrame(FrameType.PING), 10_000);
|
||||
keepAlive.unref?.();
|
||||
resolveReady();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = parseJson(frame.payload);
|
||||
rejectReady(new Error(typeof detail?.code === "string" ? detail.code : "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.DATA && peer) {
|
||||
try { localSocket.send(frame.payload, peer.port, peer.address); } catch { /* peer is gone */ }
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.CLOSE) closeSockets();
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
bindSocket(relaySocket, relayFamily === "udp6" ? "::" : "0.0.0.0"),
|
||||
bindSocket(localSocket, "127.0.0.1"),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, options.timeoutMs ?? 15_000);
|
||||
timer.unref?.();
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost: options.host, targetPort: options.port }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const address = localSocket.address();
|
||||
return {
|
||||
localHost: "127.0.0.1",
|
||||
localPort: typeof address === "object" ? address.port : 0,
|
||||
sessionId,
|
||||
close(): void {
|
||||
if (!closed && ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch { /* best effort */ }
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayServer({
|
||||
host = "0.0.0.0",
|
||||
port = 39087,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
}: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
token: string;
|
||||
allowPrivate?: boolean;
|
||||
idleTimeoutMs?: number;
|
||||
}): Promise<{ host: string; port: number; close(): void }> {
|
||||
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
|
||||
const sessions = new Map<number, RelaySession>();
|
||||
let closed = false;
|
||||
|
||||
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
try { socket.send(encodeFrame(type, session.id, session.outSequence++, payload, token), session.client.port, session.client.address); } catch { /* client is gone */ }
|
||||
};
|
||||
const cleanup = (session: RelaySession): void => {
|
||||
if (session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
};
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup);
|
||||
return;
|
||||
}
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.client.address !== rinfo.address || session.client.port !== rinfo.port) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) session.targetSocket.send(frame.payload);
|
||||
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
|
||||
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
|
||||
});
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref?.();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
close(): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface RelaySession {
|
||||
id: number;
|
||||
client: { address: string; port: number };
|
||||
targetSocket: ReturnType<typeof createSocket> | null;
|
||||
outSequence: number;
|
||||
lastActivity: number;
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
async function openRelaySession(
|
||||
frame: Frame,
|
||||
client: { address: string; port: number },
|
||||
socket: ReturnType<typeof createSocket>,
|
||||
sessions: Map<number, RelaySession>,
|
||||
token: string,
|
||||
allowPrivate: boolean,
|
||||
send: (session: RelaySession, type: FrameType, payload?: Buffer) => void,
|
||||
cleanup: (session: RelaySession) => void,
|
||||
): Promise<void> {
|
||||
const request = parseJson(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return;
|
||||
const targetPort = request.targetPort as number;
|
||||
if (!allowPrivate && isPrivateAddress(request.targetHost)) {
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
const previous = sessions.get(frame.sessionId);
|
||||
if (previous) cleanup(previous);
|
||||
const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false };
|
||||
sessions.set(session.id, session);
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); });
|
||||
targetSocket.on("error", (error) => { if (!session.closed) send(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message })); cleanup(session); });
|
||||
targetSocket.connect(targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
send(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: asError(error).message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
function validateRelayOptions(options: AccelerationRelayOptions & AccelerationTarget): void {
|
||||
if (!options.relayHost || !Number.isInteger(options.relayPort) || options.relayPort < 1 || options.relayPort > 65535) throw new Error("Invalid acceleration relay endpoint");
|
||||
if (!options.host || !Number.isInteger(options.port) || options.port < 1 || options.port > 65535) throw new Error("Invalid accelerated TeamSpeak target");
|
||||
if (!options.token || options.token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
}
|
||||
|
||||
function bindSocket(socket: ReturnType<typeof createSocket>, address: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind(0, address);
|
||||
});
|
||||
}
|
||||
|
||||
function encodeFrame(type: FrameType, sessionId: number, sequence: number, payload: Buffer, token: string): Buffer {
|
||||
if (payload.length > MAX_PAYLOAD_SIZE) throw new Error("Acceleration relay payload is too large");
|
||||
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(payload.length, 16);
|
||||
payload.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, payload, token).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function decodeFrame(packet: Buffer): Frame | null {
|
||||
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== VERSION) return null;
|
||||
const payloadLength = packet.readUInt16BE(16);
|
||||
if (packet.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return { type: packet[5] as FrameType, sessionId: packet.readUInt32BE(8), sequence: packet.readUInt32BE(12), payload: packet.subarray(HEADER_SIZE), auth: packet.subarray(18, HEADER_SIZE), raw: packet };
|
||||
}
|
||||
|
||||
function verifyFrame(frame: Frame, token: string): boolean {
|
||||
const expected = signFrame(frame.raw, frame.payload, token);
|
||||
return expected.length === frame.auth.length && timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
function signFrame(frame: Buffer, payload: Buffer, token: string): Buffer {
|
||||
return createHmac("sha256", Buffer.from(token, "utf8")).update(frame.subarray(0, 18)).update(payload).digest().subarray(0, 16);
|
||||
}
|
||||
|
||||
function randomSessionId(): number {
|
||||
const id = randomBytes(4).readUInt32BE(0);
|
||||
return id === 0 ? 1 : id;
|
||||
}
|
||||
|
||||
function jsonPayload(value: unknown): Buffer { return Buffer.from(JSON.stringify(value), "utf8"); }
|
||||
|
||||
function parseJson(payload: Buffer): Record<string, unknown> | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(payload.toString("utf8"));
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function isPrivateAddress(host: string): boolean {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const parts = host.split(".").map(Number);
|
||||
return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLocaleLowerCase();
|
||||
return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host: string): Promise<{ host: string; family: number }> {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
| { type: "clientEnter"; info: ClientInfo }
|
||||
| { type: "clientLeave"; id: number }
|
||||
| { type: "clientMoved"; id: number; channelID: bigint };
|
||||
| { type: "clientMoved"; id: number; channelID: bigint }
|
||||
| { type: "clientUpdated"; info: DirectoryClientInfo };
|
||||
|
||||
/**
|
||||
* Merges staged welcome snapshots with events received while the snapshot is
|
||||
@@ -14,7 +15,7 @@ type DirectoryDelta =
|
||||
*/
|
||||
export class DirectorySynchronizer {
|
||||
private snapshot: TSDirectorySnapshot | null = null;
|
||||
private clients = new Map<number, ClientInfo>();
|
||||
private clients = new Map<number, DirectoryClientInfo>();
|
||||
private pending: DirectoryDelta[] = [];
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -43,6 +44,10 @@ export class DirectorySynchronizer {
|
||||
this.applyOrQueue({ type: "clientMoved", id, channelID });
|
||||
}
|
||||
|
||||
applyClientUpdated(info: DirectoryClientInfo): void {
|
||||
this.applyOrQueue({ type: "clientUpdated", info });
|
||||
}
|
||||
|
||||
getSnapshot(): TSDirectorySnapshot | null {
|
||||
if (!this.snapshot) return null;
|
||||
return {
|
||||
@@ -74,6 +79,11 @@ export class DirectorySynchronizer {
|
||||
this.clients.delete(delta.id);
|
||||
return;
|
||||
}
|
||||
if (delta.type === "clientUpdated") {
|
||||
const current = this.clients.get(delta.info.id);
|
||||
this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info);
|
||||
return;
|
||||
}
|
||||
const current = this.clients.get(delta.id);
|
||||
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Prevents one persisted TeamSpeak identity from being used by two live
|
||||
* browser sessions at the same target at the same time.
|
||||
*/
|
||||
export class IdentityLeaseStore {
|
||||
private readonly owners = new Map<string, string>();
|
||||
|
||||
acquire(key: string, owner: string): boolean {
|
||||
const currentOwner = this.owners.get(key);
|
||||
if (currentOwner && currentOwner !== owner) return false;
|
||||
this.owners.set(key, owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
release(key: string, owner: string): void {
|
||||
if (this.owners.get(key) === owner) this.owners.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export interface JoinTicketPayload {
|
||||
channel?: string;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
accelerated?: boolean;
|
||||
accelerationRelayId?: string;
|
||||
}
|
||||
|
||||
interface StoredTicket {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export type TeamSpeakPingErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "TIMEOUT"
|
||||
| "PING_UNAVAILABLE"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export interface TeamSpeakPingAttempt {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export interface TeamSpeakPingResult {
|
||||
ok: boolean;
|
||||
latencyMs: number | null;
|
||||
packetLossPercent: number;
|
||||
attempts: number;
|
||||
successfulAttempts: number;
|
||||
samples: number[];
|
||||
errorCode?: TeamSpeakPingErrorCode;
|
||||
}
|
||||
|
||||
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
|
||||
|
||||
export type HostPingExecutor = (host: string, timeoutMs: number) => Promise<number>;
|
||||
|
||||
/**
|
||||
* Measure an already connected TeamSpeak session using the protocol's own
|
||||
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
|
||||
* port 9987 is therefore not a valid reachability test and reports false
|
||||
* packet loss even while voice works normally.
|
||||
*/
|
||||
export async function pingTeamSpeakSession(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
// `version` is read-only and is handled by both TS3 and TS6.
|
||||
await execute("version", timeoutMs);
|
||||
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
errorCode: classifyProbeError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectTeamSpeakPings(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
|
||||
const results: TeamSpeakPingAttempt[] = [];
|
||||
// Keep attempts sequential. This measures the real protocol path without
|
||||
// opening several temporary TeamSpeak sessions at the same time.
|
||||
for (let index = 0; index < attempts; index += 1) {
|
||||
results.push(await probe());
|
||||
}
|
||||
return summarizeTeamSpeakPings(results, attempts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ping the TeamSpeak host from the WebSpeak machine without creating a
|
||||
* TeamSpeak client. This is intentionally a host/network diagnostic: the
|
||||
* TeamSpeak voice port is UDP, so a TCP socket probe is not meaningful and a
|
||||
* client-protocol probe would create an extra visible member.
|
||||
*/
|
||||
export async function pingTeamSpeakHost(
|
||||
host: string,
|
||||
options: { attempts?: number; timeoutMs?: number; execute?: HostPingExecutor } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_000)));
|
||||
const execute = options.execute ?? pingHostOnce;
|
||||
return collectTeamSpeakPings(async () => {
|
||||
try {
|
||||
return { ok: true, latencyMs: await execute(host, timeoutMs) };
|
||||
} catch (error: unknown) {
|
||||
return { ok: false, latencyMs: null, errorCode: classifyProbeError(error) };
|
||||
}
|
||||
}, { attempts: options.attempts ?? 4 });
|
||||
}
|
||||
|
||||
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
|
||||
const normalizedAttempts = Math.max(1, attempts);
|
||||
const samples = results
|
||||
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
|
||||
.map((result) => result.latencyMs)
|
||||
.sort((left, right) => left - right);
|
||||
const errorCode = results.find((result) => result.errorCode)?.errorCode;
|
||||
|
||||
return {
|
||||
ok: samples.length > 0,
|
||||
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
|
||||
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
|
||||
attempts: normalizedAttempts,
|
||||
successfulAttempts: samples.length,
|
||||
samples,
|
||||
...(errorCode ? { errorCode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
// 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输
|
||||
// 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。
|
||||
// Keep the keywords narrow: a bare "password", "version" or "denied" appears in
|
||||
// plenty of unrelated ping/transport output, and guessing here used to send the
|
||||
// user to the wrong remedy. Only explicit phrases are treated as evidence.
|
||||
if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD";
|
||||
if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
|
||||
if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED";
|
||||
return "UNREACHABLE";
|
||||
}
|
||||
|
||||
function pingHostOnce(host: string, timeoutMs: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const windows = process.platform === "win32";
|
||||
const command = windows ? "ping.exe" : "ping";
|
||||
const args = windows
|
||||
? ["-n", "1", "-w", String(timeoutMs), host]
|
||||
: ["-c", "1", "-W", String(Math.max(1, Math.ceil(timeoutMs / 1_000))), host];
|
||||
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
let output = "";
|
||||
let settled = false;
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
callback();
|
||||
};
|
||||
const timer = setTimeout(() => finish(() => {
|
||||
child.kill();
|
||||
reject(new Error("ping timeout"));
|
||||
}), timeoutMs + 250);
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => { output += chunk; });
|
||||
child.stderr.on("data", (chunk: string) => { output += chunk; });
|
||||
child.once("error", (error) => finish(() => reject(error)));
|
||||
child.once("close", (code) => finish(() => {
|
||||
const match = output.match(/(?:time|时间)\s*[=<]\s*([\d.,]+)\s*(?:ms|毫秒)?/i);
|
||||
if (code === 0 && match) {
|
||||
const latencyMs = Number.parseFloat(match[1].replace(",", "."));
|
||||
if (Number.isFinite(latencyMs)) {
|
||||
resolve(Math.max(0, latencyMs));
|
||||
return;
|
||||
}
|
||||
}
|
||||
reject(new Error(output.trim() || `ping exited with code ${code ?? "unknown"}`));
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a small compatibility helper for callers that only need one protocol
|
||||
* attempt. It deliberately has no host/port argument because the connected
|
||||
* TeamSpeak session owns the actual resolved endpoint.
|
||||
*/
|
||||
export function pingTeamSpeakPort(
|
||||
execute: TeamSpeakCommandExecutor,
|
||||
timeoutMs = 1_500,
|
||||
): Promise<TeamSpeakPingAttempt> {
|
||||
return pingTeamSpeakSession(execute, timeoutMs);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function used to open a raw TCP socket to the TeamSpeak voice port.
|
||||
* That transport is not TeamSpeak's client protocol and must not be used for
|
||||
* reachability measurements. Keep the aggregation logic above independent of
|
||||
* the connection setup so admin tests can supply a real protocol probe.
|
||||
*/
|
||||
export async function pingTeamSpeak(
|
||||
probe: () => Promise<TeamSpeakPingAttempt>,
|
||||
options: { attempts?: number } = {},
|
||||
): Promise<TeamSpeakPingResult> {
|
||||
return collectTeamSpeakPings(probe, options);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Screen-share signaling for browser peers and native TeamSpeak peers.
|
||||
*
|
||||
* Media never passes through this module. The gateway only authenticates the
|
||||
* connected TeamSpeak session and relays SDP/ICE messages. Browser peers use
|
||||
* the configured ICE servers only for candidate discovery/negotiation; this
|
||||
* module never handles the resulting media packets.
|
||||
*/
|
||||
|
||||
export interface ScreenShareIceServer {
|
||||
urls: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
/** TeamSpeak's public ICE services are STUN-only, so media remains peer-to-peer. */
|
||||
export const DEFAULT_SCREEN_SHARE_ICE_SERVERS: readonly ScreenShareIceServer[] = [
|
||||
{ urls: "stun:turn.teamspeak.com:3478" },
|
||||
{ urls: "stun:turn2.teamspeak.com:3478" },
|
||||
];
|
||||
|
||||
const SCREEN_SHARE_ICE_URL_PATTERN = /^(?:stun|stuns|turn|turns):/i;
|
||||
const MAX_ICE_SERVER_COUNT = 8;
|
||||
const MAX_ICE_URL_LENGTH = 512;
|
||||
const MAX_ICE_CREDENTIAL_LENGTH = 512;
|
||||
|
||||
/**
|
||||
* Keep ICE configuration server-owned and bounded before exposing it to a
|
||||
* browser. TURN is accepted only as an explicitly configured external server;
|
||||
* the WebSpeak gateway is never inserted into this list.
|
||||
*/
|
||||
export function normalizeScreenShareIceServers(value?: readonly unknown[]): ScreenShareIceServer[] {
|
||||
const source: readonly unknown[] = value ?? DEFAULT_SCREEN_SHARE_ICE_SERVERS;
|
||||
const normalized: ScreenShareIceServer[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of source) {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
|
||||
const candidate = raw as Record<string, unknown>;
|
||||
const rawUrls = candidate.urls;
|
||||
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
|
||||
.filter((url): url is string => typeof url === "string" && url.trim().length > 0 && url.trim().length <= MAX_ICE_URL_LENGTH)
|
||||
.map((url) => url.trim())
|
||||
.filter((url) => SCREEN_SHARE_ICE_URL_PATTERN.test(url));
|
||||
const uniqueUrls = [...new Set(urls)];
|
||||
if (!uniqueUrls.length) continue;
|
||||
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.username
|
||||
: undefined;
|
||||
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
|
||||
? candidate.credential
|
||||
: undefined;
|
||||
const key = JSON.stringify([uniqueUrls, username ?? ""]);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
normalized.push({
|
||||
urls: uniqueUrls.length === 1 ? uniqueUrls[0] : uniqueUrls,
|
||||
...(username !== undefined ? { username } : {}),
|
||||
...(credential !== undefined ? { credential } : {}),
|
||||
});
|
||||
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
|
||||
}
|
||||
if (normalized.length) return normalized;
|
||||
return DEFAULT_SCREEN_SHARE_ICE_SERVERS.map((server) => ({ ...server }));
|
||||
}
|
||||
|
||||
export type ScreenSharePeerSignal =
|
||||
| {
|
||||
kind: "offer" | "answer";
|
||||
sdp: string;
|
||||
}
|
||||
| {
|
||||
kind: "iceCandidate";
|
||||
candidate: string;
|
||||
sdpMid?: string | null;
|
||||
sdpMLineIndex?: number | null;
|
||||
}
|
||||
| {
|
||||
kind: "close";
|
||||
};
|
||||
|
||||
export interface ScreenShareViewerDescription {
|
||||
peerId: string;
|
||||
nickname: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export interface ScreenShareStreamDescription {
|
||||
streamId: string;
|
||||
source: "browser" | "teamspeak";
|
||||
ownerPeerId: string;
|
||||
/** TeamSpeak client id used to match a stream to the member card. */
|
||||
ownerClientId?: number;
|
||||
ownerNickname: string;
|
||||
name: string;
|
||||
audio: boolean;
|
||||
createdAt: number;
|
||||
viewerCount: number;
|
||||
viewers: ScreenShareViewerDescription[];
|
||||
}
|
||||
|
||||
export type ScreenShareClientMessage =
|
||||
| {
|
||||
type: "screenShareList";
|
||||
}
|
||||
| {
|
||||
type: "screenShareStart";
|
||||
requestId?: string;
|
||||
name?: string;
|
||||
audio?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "screenShareStop";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareJoin";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareLeave";
|
||||
requestId?: string;
|
||||
streamId: string;
|
||||
}
|
||||
| {
|
||||
type: "screenShareSignal";
|
||||
streamId: string;
|
||||
targetPeerId: string;
|
||||
signal: ScreenSharePeerSignal;
|
||||
};
|
||||
|
||||
export type ScreenShareMessageParseResult =
|
||||
| ScreenShareClientMessage
|
||||
| { error: { code: string; message: string } };
|
||||
|
||||
const MAX_STREAM_ID_LENGTH = 128;
|
||||
const MAX_PEER_ID_LENGTH = 128;
|
||||
const MAX_NAME_LENGTH = 120;
|
||||
const MAX_SDP_LENGTH = 256 * 1024;
|
||||
const MAX_CANDIDATE_LENGTH = 8 * 1024;
|
||||
|
||||
export function parseScreenShareMessage(raw: string): ScreenShareMessageParseResult | null {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!isRecord(value) || typeof value.type !== "string" || !value.type.startsWith("screenShare")) return null;
|
||||
const requestId = parseRequestId(value.requestId);
|
||||
if (requestId === false) return invalid("INVALID_SCREEN_SHARE_REQUEST", "屏幕共享请求标识无效");
|
||||
|
||||
switch (value.type) {
|
||||
case "screenShareList":
|
||||
return { type: "screenShareList" };
|
||||
case "screenShareStart": {
|
||||
const name = value.name === undefined ? undefined : parseName(value.name);
|
||||
if (name === false) return invalid("INVALID_SCREEN_SHARE_NAME", "屏幕共享名称无效");
|
||||
if (value.audio !== undefined && typeof value.audio !== "boolean") return invalid("INVALID_SCREEN_SHARE_AUDIO", "共享音频选项无效");
|
||||
return {
|
||||
type: "screenShareStart",
|
||||
...(requestId ? { requestId } : {}),
|
||||
...(name ? { name } : {}),
|
||||
...(value.audio === true ? { audio: true } : {}),
|
||||
};
|
||||
}
|
||||
case "screenShareStop":
|
||||
case "screenShareJoin":
|
||||
case "screenShareLeave": {
|
||||
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
|
||||
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
|
||||
return {
|
||||
type: value.type,
|
||||
...(requestId ? { requestId } : {}),
|
||||
streamId,
|
||||
};
|
||||
}
|
||||
case "screenShareSignal": {
|
||||
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
|
||||
const targetPeerId = parseIdentifier(value.targetPeerId, MAX_PEER_ID_LENGTH);
|
||||
const signal = parseSignal(value.signal);
|
||||
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
|
||||
if (!targetPeerId) return invalid("INVALID_SCREEN_SHARE_PEER", "屏幕共享对端无效");
|
||||
if (!signal) return invalid("INVALID_SCREEN_SHARE_SIGNAL", "屏幕共享信令无效");
|
||||
return { type: "screenShareSignal", streamId, targetPeerId, signal };
|
||||
}
|
||||
default:
|
||||
return invalid("UNKNOWN_SCREEN_SHARE_MESSAGE", "不支持的屏幕共享消息");
|
||||
}
|
||||
}
|
||||
|
||||
function parseSignal(value: unknown): ScreenSharePeerSignal | null {
|
||||
if (!isRecord(value) || typeof value.kind !== "string") return null;
|
||||
if (value.kind === "close") return { kind: "close" };
|
||||
if (value.kind === "offer" || value.kind === "answer") {
|
||||
if (typeof value.sdp !== "string" || value.sdp.length === 0 || value.sdp.length > MAX_SDP_LENGTH) return null;
|
||||
return { kind: value.kind, sdp: value.sdp };
|
||||
}
|
||||
if (value.kind !== "iceCandidate" || typeof value.candidate !== "string" || value.candidate.length > MAX_CANDIDATE_LENGTH) return null;
|
||||
if (value.sdpMid !== undefined && value.sdpMid !== null && typeof value.sdpMid !== "string") return null;
|
||||
const sdpMLineIndex = value.sdpMLineIndex;
|
||||
if (sdpMLineIndex !== undefined && sdpMLineIndex !== null && (typeof sdpMLineIndex !== "number" || !Number.isInteger(sdpMLineIndex) || sdpMLineIndex < 0 || sdpMLineIndex > 255)) return null;
|
||||
return {
|
||||
kind: "iceCandidate",
|
||||
candidate: value.candidate,
|
||||
...(value.sdpMid === null || typeof value.sdpMid === "string" ? { sdpMid: value.sdpMid } : {}),
|
||||
...(sdpMLineIndex === null || typeof sdpMLineIndex === "number" ? { sdpMLineIndex } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRequestId(value: unknown): string | undefined | false {
|
||||
if (value === undefined) return undefined;
|
||||
return typeof value === "string" && value.length > 0 && value.length <= 64 ? value : false;
|
||||
}
|
||||
|
||||
function parseName(value: unknown): string | false {
|
||||
if (typeof value !== "string") return false;
|
||||
const name = value.trim();
|
||||
return name.length > 0 && name.length <= MAX_NAME_LENGTH ? name : false;
|
||||
}
|
||||
|
||||
function parseIdentifier(value: unknown, maxLength: number): string | null {
|
||||
if (typeof value !== "string" || value.length === 0 || value.length > maxLength) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function invalid(code: string, message: string): { error: { code: string; message: string } } {
|
||||
return { error: { code, message } };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -12,6 +12,9 @@ import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
@@ -21,7 +24,10 @@ export interface WebServerOptions {
|
||||
certDir?: string; // path to cert.pem + key.pem for HTTPS
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
adminService: AdminService;
|
||||
skinRegistry?: SkinRegistry;
|
||||
logger: Logger;
|
||||
nextVisitorNumber?: () => number;
|
||||
visitorCount?: () => number;
|
||||
}
|
||||
|
||||
export interface WebServer {
|
||||
@@ -29,6 +35,8 @@ export interface WebServer {
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
const VISITOR_NUMBER_COOKIE = "webspeak_visitor_number";
|
||||
|
||||
export function createWebServer(options: WebServerOptions): WebServer {
|
||||
const app = express();
|
||||
const logger = options.logger.child({ component: "web" });
|
||||
@@ -57,9 +65,73 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.get("/health", healthHandler);
|
||||
app.get("/api/health", healthHandler);
|
||||
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
app.get("/api/public-config", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json(options.adminService.getPublicConfig());
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
let visitorNumber = readVisitorNumberCookie(request.header("cookie"));
|
||||
if (visitorNumber === null && options.nextVisitorNumber) {
|
||||
try {
|
||||
visitorNumber = options.nextVisitorNumber();
|
||||
response.setHeader(
|
||||
"Set-Cookie",
|
||||
`${VISITOR_NUMBER_COOKIE}=${visitorNumber}; Max-Age=31536000; Path=/; SameSite=Lax${options.certDir ? "; Secure" : ""}`,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor number could not be assigned");
|
||||
}
|
||||
}
|
||||
let visitorTotal = resolveVisitorTotal(visitorNumber, null);
|
||||
if (options.visitorCount) {
|
||||
try {
|
||||
visitorTotal = resolveVisitorTotal(visitorNumber, options.visitorCount());
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Visitor total could not be read");
|
||||
}
|
||||
} else if (visitorNumber !== null) {
|
||||
visitorTotal = visitorNumber;
|
||||
}
|
||||
response.json({
|
||||
...options.adminService.getPublicConfig(),
|
||||
...(visitorNumber === null ? {} : { visitorNumber }),
|
||||
...(visitorTotal === null ? {} : { visitorTotal }),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins", async (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/package", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const archive = await options.skinRegistry?.readArchive(id);
|
||||
if (!archive) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setHeader("Content-Type", "application/octet-stream");
|
||||
response.setHeader("Content-Disposition", `attachment; filename="${id}.wskin"`);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(archive);
|
||||
});
|
||||
|
||||
app.get("/api/skins/:id/preview", async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const preview = await options.skinRegistry?.readPreview(id);
|
||||
if (!preview) {
|
||||
response.status(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("Cache-Control", "public, max-age=300");
|
||||
response.setHeader("Content-Type", preview.mimeType);
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.send(preview.bytes);
|
||||
});
|
||||
|
||||
app.post("/api/join-ticket", async (request, response) => {
|
||||
@@ -104,15 +176,34 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
let target = managedInvite?.target ?? policy.defaultTarget;
|
||||
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
|
||||
const channel = requestedChannel || managedInvite?.channel || "";
|
||||
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
|
||||
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
if (accelerationRequested && acceleration.length === 0) {
|
||||
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (requestedRelayId && !acceleration.some((relay) => relay.id === requestedRelayId)) {
|
||||
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
if (!managedInvite) {
|
||||
try {
|
||||
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
|
||||
target = parseTeamSpeakTarget(body.target);
|
||||
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
|
||||
if (!isDefault) {
|
||||
target = await resolveSafeOpenTarget(target);
|
||||
serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
}
|
||||
// Open mode must protect the gateway even when a user submits the
|
||||
// same address configured as the administrator's default target.
|
||||
// The default target only controls which server is prefilled; it is
|
||||
// not a trust boundary and must not bypass SSRF protection.
|
||||
target = await resolveSafeOpenTarget(target);
|
||||
if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
else if (typeof body.serverPassword === "string" && body.serverPassword.trim()) serverPassword = body.serverPassword.slice(0, 512);
|
||||
} else if (policy.accessMode === "fixed" && typeof body.serverPassword === "string" && body.serverPassword.trim()) {
|
||||
// The fixed target remains administrator-controlled, but a user may
|
||||
// retry its server password after the gateway reports that one is
|
||||
// required. The target itself is never taken from this request.
|
||||
serverPassword = body.serverPassword.slice(0, 512);
|
||||
}
|
||||
} catch {
|
||||
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
|
||||
@@ -126,6 +217,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
@@ -139,6 +231,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
getCreatedSessions: () => voiceBridge.getCreatedCount(),
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
skinRegistry: options.skinRegistry,
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
@@ -173,10 +266,32 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAccelerationOptions(
|
||||
configured: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]) | undefined,
|
||||
): ConfiguredAccelerationRelay[] {
|
||||
const value = typeof configured === "function" ? configured() : configured;
|
||||
if (!value) return [];
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readVisitorNumberCookie(header: string | undefined): number | null {
|
||||
if (!header) return null;
|
||||
for (const entry of header.split(";")) {
|
||||
const separator = entry.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
const name = entry.slice(0, separator).trim();
|
||||
if (name !== VISITOR_NUMBER_COOKIE) continue;
|
||||
const rawValue = entry.slice(separator + 1).trim();
|
||||
const number = Number.parseInt(rawValue, 10);
|
||||
return Number.isSafeInteger(number) && number > 0 ? number : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
|
||||
@@ -17,6 +17,7 @@ export type SessionTeardownReason =
|
||||
| "websocket-error"
|
||||
| "protocol-error"
|
||||
| "teamSpeak-disconnect"
|
||||
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
|
||||
| "teamSpeak-connect-failed"
|
||||
| "heartbeat-timeout"
|
||||
| "admin-terminated"
|
||||
|
||||
@@ -57,6 +57,8 @@ export class EndpointProtocolCache {
|
||||
|
||||
export const endpointProtocolCache = new EndpointProtocolCache();
|
||||
|
||||
const TEAM_SPEAK_CONNECT_TIMEOUT_MS = 15_000;
|
||||
|
||||
export interface TeamSpeakAdapterOptions {
|
||||
target: TeamSpeakTarget;
|
||||
nickname: string;
|
||||
@@ -109,8 +111,9 @@ export class TeamSpeakAdapter {
|
||||
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
|
||||
try {
|
||||
await this.client.connect();
|
||||
await this.client.waitConnected();
|
||||
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
|
||||
} catch (error: unknown) {
|
||||
await this.client.disconnect().catch(() => undefined);
|
||||
throw normalizeTeamSpeakError(error);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import { TSClient } from "./ts-client.js";
|
||||
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
export type ProbeErrorCode =
|
||||
| "INVALID_NICKNAME"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "PASSWORD_REQUIRED"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
@@ -30,8 +35,10 @@ export class TeamSpeakProbeError extends Error {
|
||||
interface ProbeAdapter {
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
readonly protocol: TeamSpeakProtocol | null;
|
||||
readonly client: {
|
||||
readonly protocol?: TeamSpeakProtocol | null;
|
||||
getProtocol?(): TeamSpeakProtocol | null;
|
||||
execCommandWithResponse?(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
readonly client?: {
|
||||
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
};
|
||||
}
|
||||
@@ -47,7 +54,15 @@ export async function probeTeamSpeak(
|
||||
password: string,
|
||||
logger: Logger,
|
||||
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
|
||||
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
|
||||
(() => {
|
||||
const client = new TSClient({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger);
|
||||
return {
|
||||
connect: () => client.connect(),
|
||||
disconnect: () => client.disconnect(),
|
||||
getProtocol: () => client.getProtocol(),
|
||||
execCommandWithResponse: (command: string, timeoutMs?: number) => client.execCommandWithResponse(command, timeoutMs),
|
||||
};
|
||||
})(),
|
||||
): Promise<TeamSpeakProbeResult> {
|
||||
const startedAt = Date.now();
|
||||
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
|
||||
@@ -55,7 +70,9 @@ export async function probeTeamSpeak(
|
||||
await adapter.connect();
|
||||
let serverName: string | null = null;
|
||||
try {
|
||||
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
|
||||
const execute = adapter.execCommandWithResponse?.bind(adapter) ?? adapter.client?.execCommandWithResponse.bind(adapter.client);
|
||||
if (!execute) throw new Error("Probe adapter does not support commands");
|
||||
const rows = await execute("serverinfo", 3000);
|
||||
const first = rows[0] ?? {};
|
||||
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
|
||||
} catch {
|
||||
@@ -63,13 +80,13 @@ export async function probeTeamSpeak(
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
protocol: adapter.protocol,
|
||||
protocol: adapter.protocol ?? adapter.getProtocol?.() ?? null,
|
||||
latencyMs: Math.max(0, Date.now() - startedAt),
|
||||
serverName,
|
||||
requiresPassword: Boolean(password),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
throw toProbeError(error);
|
||||
throw toProbeError(error, password);
|
||||
} finally {
|
||||
try {
|
||||
await adapter.disconnect();
|
||||
@@ -79,18 +96,38 @@ export async function probeTeamSpeak(
|
||||
}
|
||||
}
|
||||
|
||||
export function toProbeError(error: unknown): TeamSpeakProbeError {
|
||||
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
|
||||
if (error instanceof TeamSpeakProbeError) return error;
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
// 探测只回答「该地址是否可用」,因此把网关能细分的拒绝原因收敛到既有探测码,
|
||||
// 具体原因由连接/重连路径向浏览器上报。
|
||||
// The probe only answers "can this address be used at all", so the richer
|
||||
// rejection reasons the gateway can now name are bucketed into the existing
|
||||
// probe codes; the exact reason is reported by the connect/reconnect path.
|
||||
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
|
||||
invalid_target: "INTERNAL_ERROR",
|
||||
invalid_nickname: "INVALID_NICKNAME",
|
||||
nickname_in_use: "INVALID_NICKNAME",
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
unreachable: "UNREACHABLE",
|
||||
host_not_found: "HOST_NOT_FOUND",
|
||||
connection_refused: "CONNECTION_REFUSED",
|
||||
connection_reset: "CONNECTION_RESET",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: "INVALID_PASSWORD",
|
||||
authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED",
|
||||
channel_password_required: "PASSWORD_REQUIRED",
|
||||
identity_security_level_too_low: "SERVER_REJECTED",
|
||||
identity_limit_reached: "SERVER_REJECTED",
|
||||
client_version_outdated: "SERVER_REJECTED",
|
||||
flooding: "SERVER_REJECTED",
|
||||
banned: "SERVER_REJECTED",
|
||||
kicked: "SERVER_REJECTED",
|
||||
server_shutting_down: "SERVER_REJECTED",
|
||||
connection_initialisation_failed: "SERVER_REJECTED",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
server_full: "SERVER_REJECTED",
|
||||
unknown: "SERVER_REJECTED",
|
||||
@@ -100,6 +137,6 @@ export function toProbeError(error: unknown): TeamSpeakProbeError {
|
||||
|
||||
function extractErrorText(error: unknown): string {
|
||||
if (!error || typeof error !== "object") return String(error ?? "");
|
||||
const candidate = error as { code?: unknown; message?: unknown };
|
||||
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
|
||||
const candidate = error as { code?: unknown; id?: unknown; serverMessage?: unknown; message?: unknown };
|
||||
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.id === "string" || typeof candidate.id === "number" ? candidate.id : ""} ${typeof candidate.serverMessage === "string" ? candidate.serverMessage : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Writable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
clientMove as tsClientMove,
|
||||
@@ -11,11 +12,14 @@ import {
|
||||
type VoiceData,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type RawNotification,
|
||||
type TextMessage,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
|
||||
|
||||
export interface TSClientOptions {
|
||||
target: TeamSpeakTarget;
|
||||
@@ -24,6 +28,7 @@ export interface TSClientOptions {
|
||||
defaultChannel?: string;
|
||||
channelPassword?: string;
|
||||
identity?: Identity;
|
||||
acceleration?: AccelerationRelayOptions;
|
||||
}
|
||||
|
||||
export interface TSVoiceData {
|
||||
@@ -32,8 +37,20 @@ export interface TSVoiceData {
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
export interface TSClientAvatar {
|
||||
/** TeamSpeak's avatar content marker, used to invalidate a cached avatar. */
|
||||
cacheKey: string;
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
// Keep enough room for avatars produced by the native client. The previous
|
||||
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
|
||||
// so every avatar silently fell back to its initial letter.
|
||||
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
|
||||
|
||||
export type TSDirectorySnapshot = DirectorySnapshot;
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
export type TSRawNotification = RawNotification;
|
||||
|
||||
export type TSChatScope = "channel" | "server" | "private";
|
||||
|
||||
@@ -70,6 +87,11 @@ export class TSClient extends EventEmitter {
|
||||
private clientId = 0;
|
||||
private connected = false;
|
||||
private preferredChannelId = 0n;
|
||||
private accelerationClient: AccelerationRelayClient | null = null;
|
||||
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
|
||||
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
|
||||
// reason message to its `kicked` handler, not the reason id.
|
||||
private selfLeaveReasonId: number | null = null;
|
||||
|
||||
constructor(private options: TSClientOptions, logger: Logger) {
|
||||
super();
|
||||
@@ -78,9 +100,19 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.selfLeaveReasonId = null;
|
||||
if (!this.adapter || !this.client) {
|
||||
let transportTarget = this.options.target;
|
||||
if (this.options.acceleration && !this.accelerationClient) {
|
||||
this.accelerationClient = await createAccelerationRelayClient({
|
||||
...this.options.acceleration,
|
||||
host: this.options.target.host,
|
||||
port: this.options.target.port,
|
||||
});
|
||||
transportTarget = { host: this.accelerationClient.localHost, port: this.accelerationClient.localPort };
|
||||
}
|
||||
this.adapter = new TeamSpeakAdapter({
|
||||
target: this.options.target,
|
||||
target: transportTarget,
|
||||
nickname: this.options.nickname,
|
||||
identity: this.identity,
|
||||
serverPassword: this.options.serverPassword,
|
||||
@@ -126,8 +158,9 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("directorySnapshot", { channels, clients });
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not reconcile the TeamSpeak directory snapshot");
|
||||
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
|
||||
failureDetail: error instanceof Error ? error.message : String(error),
|
||||
}, "TeamSpeak directory snapshot unavailable");
|
||||
}
|
||||
|
||||
const connectedChannelId = client.channelID();
|
||||
@@ -153,6 +186,46 @@ export class TSClient extends EventEmitter {
|
||||
this.emit("connected", this.clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a visible client's TeamSpeak avatar through the client protocol.
|
||||
*
|
||||
* TeamSpeak does not include the avatar bytes in directory notifications.
|
||||
* `clientinfo` exposes the avatar marker and the per-identity filename; the
|
||||
* file itself is then read through the normal TeamSpeak file-transfer port.
|
||||
* A missing permission, missing avatar, blocked file-transfer port, or an
|
||||
* oversized image is intentionally reported as `null` so the web client can
|
||||
* keep its generated initial avatar.
|
||||
*/
|
||||
async getClientAvatar(clientId: number, expectedUid = ""): Promise<TSClientAvatar | null> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
const rows = await this.client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
|
||||
const info = rows.find((row) => {
|
||||
if (expectedUid && row.client_unique_identifier !== expectedUid) return false;
|
||||
return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string";
|
||||
});
|
||||
if (!info) return null;
|
||||
const cacheKey = info.client_flag_avatar?.trim() ?? "";
|
||||
const avatarFileKey = info.client_base64HashClientUID?.trim() ?? "";
|
||||
if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null;
|
||||
|
||||
const transfer = await this.client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const destination = new Writable({
|
||||
write(chunk: Buffer | string, _encoding, callback) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
callback();
|
||||
},
|
||||
});
|
||||
await this.client.downloadFileData(this.options.target.host, transfer, destination);
|
||||
const data = Buffer.concat(chunks);
|
||||
if (data.length === 0 || data.length > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
return { cacheKey, data };
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
this.emit("voiceData", {
|
||||
@@ -172,6 +245,13 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
});
|
||||
|
||||
client.on("rawNotification", (notification: RawNotification) => {
|
||||
this.emit("rawNotification", {
|
||||
name: notification.name,
|
||||
params: { ...notification.params },
|
||||
} satisfies TSRawNotification);
|
||||
});
|
||||
|
||||
client.on("textMessage", (msg) => {
|
||||
this.emit("textMessage", toTSChatMessage(msg));
|
||||
});
|
||||
@@ -181,7 +261,15 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("disconnected", (err) => {
|
||||
this.logger.warn({ err: err?.message }, "Disconnected from TS");
|
||||
if (err) {
|
||||
const normalized = normalizeTeamSpeakError(err);
|
||||
this.logger.warn({
|
||||
failureCode: normalized.code.toUpperCase(),
|
||||
failureDetail: describeTeamSpeakError(normalized),
|
||||
}, "TeamSpeak transport disconnected unexpectedly");
|
||||
} else {
|
||||
this.logger.info("TeamSpeak transport disconnected");
|
||||
}
|
||||
this.connected = false;
|
||||
this.clientId = 0;
|
||||
this.emit("disconnected", err);
|
||||
@@ -192,13 +280,31 @@ export class TSClient extends EventEmitter {
|
||||
});
|
||||
|
||||
client.on("clientLeave", (info) => {
|
||||
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
|
||||
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
|
||||
this.emit("clientLeave", info);
|
||||
});
|
||||
|
||||
// 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器
|
||||
// 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。
|
||||
// The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5
|
||||
// (kick with ban) and hands over the admin written reason message. Without
|
||||
// this listener the reason was dropped, so the browser degraded to a generic
|
||||
// "connection failed" right after the transport went away.
|
||||
client.on("kicked", (reasonMsg) => {
|
||||
const reasonId = this.selfLeaveReasonId;
|
||||
this.selfLeaveReasonId = null;
|
||||
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
|
||||
});
|
||||
|
||||
client.on("clientMoved", (info) => {
|
||||
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
|
||||
this.emit("clientMoved", info);
|
||||
});
|
||||
|
||||
client.on("clientUpdated", (event) => {
|
||||
this.emit("clientUpdated", event.info);
|
||||
});
|
||||
}
|
||||
|
||||
sendVoice(data: Buffer, codec: number = 4): void {
|
||||
@@ -230,12 +336,24 @@ export class TSClient extends EventEmitter {
|
||||
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
|
||||
}
|
||||
|
||||
async setInputMuted(muted: boolean): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
await this.client.execCommand(`clientupdate client_input_muted=${muted ? 1 : 0}`);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Move another visible TeamSpeak client; the server enforces both move powers. */
|
||||
async moveClient(clientId: number, channelId: bigint, password?: string): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
await tsClientMove(this.client, clientId, channelId, password);
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
// The SDK learns the real client id during the welcome sequence, before
|
||||
// TSClient.connect() resumes. Reading it from the SDK prevents the first
|
||||
@@ -247,6 +365,21 @@ export class TSClient extends EventEmitter {
|
||||
return this.adapter?.protocol ?? null;
|
||||
}
|
||||
|
||||
async execCommandWithResponse(command: string, timeoutMs = 3000): Promise<Record<string, string>[]> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
return this.client.execCommandWithResponse(command, timeoutMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a TeamSpeak protocol command whose response is delivered later as a
|
||||
* notification (for example setupstream/streamsignaling). The command is
|
||||
* assembled by the trusted server-side stream adapter, never by the browser.
|
||||
*/
|
||||
async sendProtocolCommand(command: string): Promise<void> {
|
||||
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
|
||||
await this.client.sendCommandNoWait(command);
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
}
|
||||
@@ -263,10 +396,16 @@ export class TSClient extends EventEmitter {
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.connected = false;
|
||||
if (this.adapter) await this.adapter.disconnect();
|
||||
this.adapter = null;
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
this.selfLeaveReasonId = null;
|
||||
try {
|
||||
if (this.adapter) await this.adapter.disconnect();
|
||||
} finally {
|
||||
this.accelerationClient?.close();
|
||||
this.accelerationClient = null;
|
||||
this.adapter = null;
|
||||
this.client = null;
|
||||
this.clientId = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
test("visitor total never disappears or falls below the current visitor ordinal", () => {
|
||||
assert.equal(resolveVisitorTotal(3, 0), 3);
|
||||
assert.equal(resolveVisitorTotal(3, 5), 5);
|
||||
assert.equal(resolveVisitorTotal(3, undefined), 3);
|
||||
assert.equal(resolveVisitorTotal(null, 8), 8);
|
||||
assert.equal(resolveVisitorTotal(null, -1), null);
|
||||
assert.equal(resolveVisitorTotal(0, 2), 2);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
export function resolveVisitorTotal(visitorNumber: number | null, recordedTotal: unknown): number | null {
|
||||
const currentVisitor = Number.isSafeInteger(visitorNumber) && Number(visitorNumber) > 0
|
||||
? Number(visitorNumber)
|
||||
: null;
|
||||
const total = typeof recordedTotal === "number" && Number.isSafeInteger(recordedTotal) && recordedTotal >= 0
|
||||
? recordedTotal
|
||||
: null;
|
||||
|
||||
if (total === null) return currentVisitor;
|
||||
return Math.max(total, currentVisitor ?? 0);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted";
|
||||
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
|
||||
requestId?: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
||||
}
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted"]);
|
||||
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -32,6 +32,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
|
||||
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
|
||||
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
|
||||
}
|
||||
if (value.type === "moveClient" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
|
||||
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
|
||||
}
|
||||
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
|
||||
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
|
||||
}
|
||||
@@ -59,6 +68,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
|
||||
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
|
||||
}
|
||||
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
|
||||
}
|
||||
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
|
||||
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
|
||||
}
|
||||
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
@@ -26,10 +26,14 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
// TeamSpeak and browsers can emit valid Opus comfort-noise/silence packets
|
||||
// while a client is muted. Do not turn those packets into a false "speaking"
|
||||
// indicator or forward them to TeamSpeak as if they were voice.
|
||||
const MIN_SPEAKER_RMS = 160;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// This threshold is used only for the speaking indicator. It must never decide
|
||||
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
|
||||
// packets are still valid media and dropping them can break decoder continuity.
|
||||
const SPEAKER_ACTIVITY_RMS = 160;
|
||||
|
||||
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||
// published by the bundled Docker Compose file; advanced administrators can
|
||||
@@ -43,6 +47,7 @@ export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
@@ -51,45 +56,106 @@ export interface WebRtcAudioSessionOptions {
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
microphoneMuted?: boolean;
|
||||
onVoiceFrame: (data: Buffer) => void;
|
||||
accompanimentActive?: boolean;
|
||||
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
onVoiceActivity: (clientIds: number[]) => void;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioStats {
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface PendingAudioFrame {
|
||||
pcm: Buffer;
|
||||
receivedAt: number;
|
||||
/** Preserve a native 20 ms Opus frame when no mix is required. */
|
||||
opus?: Buffer;
|
||||
}
|
||||
|
||||
interface SelectedAudioFrame extends PendingAudioFrame {
|
||||
clientId: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One low-latency WebRTC audio session for one browser connection.
|
||||
*
|
||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||
* audio track in this first transport, so this class mixes only the newest
|
||||
* 20 ms frame from each active speaker and packetizes the result as RTP. The
|
||||
* map is deliberately bounded to one frame per speaker; an old frame is
|
||||
* replaced instead of becoming a playback queue.
|
||||
* audio track in this first transport, so this class mixes one 20 ms frame
|
||||
* from each active speaker and packetizes the result as RTP. Each speaker has
|
||||
* a very small bounded queue so bursts from the TeamSpeak adapter can be
|
||||
* smoothed without turning into an ever-growing playback delay.
|
||||
*/
|
||||
export class WebRtcAudioSession {
|
||||
readonly peer: RTCPeerConnection;
|
||||
private readonly logger: LoggerType;
|
||||
private readonly onVoiceFrame: (data: Buffer) => void;
|
||||
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
|
||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
||||
private readonly pendingFrames = new Map<number, Buffer>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
private readonly activeSpeakerIds = new Set<number>();
|
||||
private readonly opusPayloadTypes = new Set<number>();
|
||||
private readonly audioTimer: ReturnType<typeof setInterval>;
|
||||
private audioTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||
private microphoneMuted: boolean;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||
private closed = false;
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private microphoneMuted: boolean;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
|
||||
constructor(options: WebRtcAudioSessionOptions) {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
||||
@@ -106,14 +172,27 @@ export class WebRtcAudioSession {
|
||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||
audio.onTrack.subscribe((track) => {
|
||||
track.onReceiveRtp.subscribe((rtp) => {
|
||||
if (this.closed || this.microphoneMuted || !this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
if (this.closed) return;
|
||||
const receivedAt = performance.now();
|
||||
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
|
||||
this.lastIngressRtpAt = receivedAt;
|
||||
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcIngressRtpLastAt = Date.now();
|
||||
this.stats.webrtcIngressRtpFrames++;
|
||||
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
const payload = Buffer.from(rtp.payload);
|
||||
// A disabled browser MediaStreamTrack normally still produces RTP
|
||||
// comfort-noise packets. TeamSpeak treats any received voice packet
|
||||
// as activity, so enforce mute/VAD at this gateway boundary instead
|
||||
// of relying on the browser's local speaking indicator.
|
||||
if (!this.hasVoiceEnergy(payload)) return;
|
||||
this.onVoiceFrame(payload);
|
||||
// A muted microphone must stop the browser user's TeamSpeak voice
|
||||
// packets at the gateway. Browser-side track.enabled/gain changes
|
||||
// still produce RTP comfort-silence on some browsers, and forwarding
|
||||
// those packets makes TeamSpeak keep the user in the speaking state.
|
||||
// When accompaniment is active, keep forwarding the mixed track: the
|
||||
// browser has already removed only the microphone component.
|
||||
if (this.microphoneMuted && !this.accompanimentActive) return;
|
||||
// Forward every valid negotiated Opus payload unchanged. Do not
|
||||
// decode it for RMS analysis or pass it through a speech/silence gate:
|
||||
// quiet frames are still part of the codec timeline and dropping them
|
||||
// can cause downstream gaps, clicks, or decoder recovery artifacts.
|
||||
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
|
||||
@@ -125,22 +204,17 @@ export class WebRtcAudioSession {
|
||||
|
||||
try {
|
||||
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
// Use a separate stateful decoder for browser ingress. RTP payloads do
|
||||
// not identify whether a packet contains microphone energy or DTX/CN
|
||||
// audio, so the gateway must decode it before forwarding to TS.
|
||||
this.ingressDecoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
} catch (error: unknown) {
|
||||
this.encoder = null;
|
||||
this.ingressDecoder = null;
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
|
||||
}
|
||||
if (!this.encoder || !this.ingressDecoder) {
|
||||
if (!this.encoder) {
|
||||
this.outgoingTrack.stop();
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
|
||||
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
|
||||
this.audioTimer.unref?.();
|
||||
this.nextAudioDeadline = performance.now();
|
||||
this.scheduleAudioTick();
|
||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||
this.activityTimer.unref?.();
|
||||
this.peer.onconnectionstatechange = () => {
|
||||
@@ -148,6 +222,10 @@ export class WebRtcAudioSession {
|
||||
};
|
||||
}
|
||||
|
||||
getStats(): WebRtcAudioStats {
|
||||
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||
}
|
||||
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
if (this.closed) throw new Error("WebRTC session is closed");
|
||||
this.setOpusPayloadTypes(offer.sdp);
|
||||
@@ -163,7 +241,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || data.codec !== 4) return;
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (!decoder) {
|
||||
try {
|
||||
@@ -178,19 +256,51 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
// Only advertise speaking after a valid TeamSpeak Opus frame has been
|
||||
// decoded. Otherwise the UI can show activity while the mixer has no
|
||||
// audio to send, which is especially confusing on the WebRTC path.
|
||||
if (pcm.length < AUDIO_FRAME_BYTES) return;
|
||||
let sum = 0;
|
||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// RMS is used only for the UI speaking indicator. Every decoded frame,
|
||||
// including quiet/comfort-noise frames, continues into the queue so the
|
||||
// receiver keeps an uninterrupted codec timeline.
|
||||
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
|
||||
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
|
||||
let offset = 0;
|
||||
let enqueued = false;
|
||||
let queue = this.pendingFrames.get(data.clientId);
|
||||
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
|
||||
if (!queue) {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
queue.push({
|
||||
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
|
||||
receivedAt: performance.now(),
|
||||
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
|
||||
});
|
||||
enqueued = true;
|
||||
offset += AUDIO_FRAME_BYTES;
|
||||
}
|
||||
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
|
||||
else this.partialPcmByClient.delete(data.clientId);
|
||||
if (enqueued) {
|
||||
this.lastQueueEnqueuedAt = performance.now();
|
||||
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
|
||||
}
|
||||
if (Math.sqrt(sum / AUDIO_FRAME_SAMPLES) < MIN_SPEAKER_RMS) return;
|
||||
this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
|
||||
this.activeSpeakerIds.add(data.clientId);
|
||||
} catch {
|
||||
this.stats.webrtcDownlinkDecodeErrors++;
|
||||
// A malformed or codec-transition packet is discarded without touching
|
||||
// the peer connection. The next valid Opus frame can recover the stream.
|
||||
}
|
||||
@@ -199,52 +309,104 @@ export class WebRtcAudioSession {
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
clearInterval(this.audioTimer);
|
||||
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||
this.audioTimer = null;
|
||||
clearInterval(this.activityTimer);
|
||||
this.pendingFrames.clear();
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.ingressDecoder = null;
|
||||
this.decoderByClient.clear();
|
||||
this.encoder = null;
|
||||
this.outgoingTrack.stop();
|
||||
await this.peer.close();
|
||||
}
|
||||
|
||||
private scheduleAudioTick(): void {
|
||||
if (this.closed) return;
|
||||
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
|
||||
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
|
||||
this.audioTimer.unref?.();
|
||||
}
|
||||
|
||||
private flushAudio(): void {
|
||||
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
|
||||
if (this.closed) return;
|
||||
const now = performance.now();
|
||||
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
|
||||
this.stats.webrtcPacerLateTicks++;
|
||||
this.nextAudioDeadline = now;
|
||||
this.trimQueuesAfterLateTick();
|
||||
}
|
||||
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
|
||||
this.audioTimer = null;
|
||||
this.mixAndSendAudio();
|
||||
this.scheduleAudioTick();
|
||||
}
|
||||
|
||||
private mixAndSendAudio(): void {
|
||||
if (!this.encoder) {
|
||||
return;
|
||||
}
|
||||
if (!this.pendingFrames.size) {
|
||||
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
let sourceCount = 0;
|
||||
for (const pcm of this.pendingFrames.values()) {
|
||||
sourceCount++;
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
|
||||
const selectedFrames: SelectedAudioFrame[] = [];
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
selectedFrames.push({ ...frame, clientId, volume });
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
|
||||
this.sendRtpAudio(selectedFrames[0].opus);
|
||||
return;
|
||||
}
|
||||
this.pendingFrames.clear();
|
||||
if (!sourceCount) return;
|
||||
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
const scale = 1 / Math.sqrt(sourceCount);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale)));
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
// by simultaneous speakers; never normalize by the active speaker count.
|
||||
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
|
||||
pcm.writeInt16LE(sample, index * 2);
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
this.sendRtpAudio(encoded);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcEgressRtpLastAt = Date.now();
|
||||
this.stats.webrtcEgressRtpFrames++;
|
||||
}
|
||||
|
||||
private flushSpeakerActivity(): void {
|
||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||
const ids = [...this.activeSpeakerIds];
|
||||
@@ -256,23 +418,47 @@ export class WebRtcAudioSession {
|
||||
this.microphoneMuted = muted;
|
||||
}
|
||||
|
||||
private hasVoiceEnergy(data: Buffer): boolean {
|
||||
const decoder = this.ingressDecoder;
|
||||
if (!decoder) return false;
|
||||
try {
|
||||
const pcm = decoder.decode(data);
|
||||
if (pcm.length < AUDIO_FRAME_BYTES) return false;
|
||||
let sum = 0;
|
||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
}
|
||||
return Math.sqrt(sum / AUDIO_FRAME_SAMPLES) >= MIN_SPEAKER_RMS;
|
||||
} catch {
|
||||
// Malformed/transition packets are discarded without interrupting the
|
||||
// rest of the peer. The next valid Opus packet can recover the decoder.
|
||||
return false;
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
this.accompanimentActive = active;
|
||||
}
|
||||
|
||||
setMemberVolume(clientId: number, volume: number): void {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
|
||||
const normalized = Math.max(0, Math.min(4, volume));
|
||||
if (normalized === 1) this.memberVolumes.delete(clientId);
|
||||
else this.memberVolumes.set(clientId, normalized);
|
||||
}
|
||||
|
||||
private calculateRms(pcm: Buffer): number {
|
||||
let sum = 0;
|
||||
let samples = 0;
|
||||
for (let index = 0; index + 1 < pcm.length; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
samples++;
|
||||
}
|
||||
return samples ? Math.sqrt(sum / samples) : 0;
|
||||
}
|
||||
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private getQueueFrameCount(): number {
|
||||
let count = 0;
|
||||
for (const queue of this.pendingFrames.values()) count += queue.length;
|
||||
return count;
|
||||
}
|
||||
|
||||
private setOpusPayloadTypes(sdp: string): void {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
export type SiteLanguage = "zh" | "en" | "de" | "ru" | "ja";
|
||||
|
||||
/**
|
||||
* Built-in welcome-page templates. An empty administrator value always falls
|
||||
* back to one of these strings, so adding a language never leaves the page
|
||||
* with a blank welcome message.
|
||||
*/
|
||||
export const DEFAULT_WELCOME_TEXTS: Record<SiteLanguage, string> = {
|
||||
zh: "无需安装 TeamSpeak 客户端,打开浏览器即可加入语音频道。低延迟、轻量、专注于每一次对话。",
|
||||
en: "No TeamSpeak client installation required. Open your browser and join a voice channel with low-latency audio built for conversation.",
|
||||
de: "Keine Installation des TeamSpeak-Clients nötig. Öffne den Browser und tritt einem Sprachkanal bei – leichtgewichtig und mit geringer Latenz.",
|
||||
ru: "Устанавливать клиент TeamSpeak не нужно: откройте браузер и присоединитесь к голосовому каналу. Низкая задержка и удобное общение в каждом разговоре.",
|
||||
ja: "TeamSpeak クライアントのインストールは不要です。ブラウザを開くだけで音声チャンネルに参加できます。低遅延で軽快な会話を楽しめます。",
|
||||
};
|
||||
|
||||
export function resolveWelcomeTexts(values: Partial<Record<SiteLanguage, string>>): Record<SiteLanguage, string> {
|
||||
return {
|
||||
zh: values.zh?.trim() || DEFAULT_WELCOME_TEXTS.zh,
|
||||
en: values.en?.trim() || DEFAULT_WELCOME_TEXTS.en,
|
||||
de: values.de?.trim() || DEFAULT_WELCOME_TEXTS.de,
|
||||
ru: values.ru?.trim() || DEFAULT_WELCOME_TEXTS.ru,
|
||||
ja: values.ja?.trim() || DEFAULT_WELCOME_TEXTS.ja,
|
||||
};
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createServer } from "node:http";
|
||||
import test from "node:test";
|
||||
import express from "express";
|
||||
import { createAdminRouter } from "../src/admin/admin-router.js";
|
||||
import { AdminService } from "../src/admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../src/admin/admin-session.js";
|
||||
import { WebSpeakDatabase } from "../src/persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("admin API requires the default password to be changed before administration", async (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-api-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
async (_target, password) => ({ ok: true, protocol: "ts6", latencyMs: 7, serverName: "Mock Server", requiresPassword: Boolean(password) }),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({
|
||||
service,
|
||||
sessions: new AdminSessionStore(),
|
||||
logger: silentLogger,
|
||||
getActiveSessions: () => 2,
|
||||
getPeakSessions: () => 4,
|
||||
startedAt: Date.now() - 5000,
|
||||
}));
|
||||
const server = createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
context.after(async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
database.close();
|
||||
});
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === "object");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
|
||||
const status = await request(origin, "/api/admin/status");
|
||||
assert.equal(status.response.status, 200);
|
||||
assert.equal(status.response.headers.get("cache-control"), "no-store");
|
||||
assert.equal(status.body.initialized, true);
|
||||
assert.equal("setupDefaults" in status.body, false);
|
||||
|
||||
const login = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "admin" },
|
||||
});
|
||||
assert.equal(login.response.status, 200);
|
||||
assert.equal(login.body.mustChangePassword, true);
|
||||
assert.equal(typeof login.body.csrfToken, "string");
|
||||
const cookie = login.response.headers.get("set-cookie")?.split(";", 1)[0];
|
||||
assert.ok(cookie?.startsWith("webspeak_admin="));
|
||||
assert.match(login.response.headers.get("set-cookie") ?? "", /HttpOnly/i);
|
||||
assert.match(login.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i);
|
||||
|
||||
const session = await request(origin, "/api/admin/session", { cookie });
|
||||
assert.equal(session.body.authenticated, true);
|
||||
assert.equal(session.body.mustChangePassword, true);
|
||||
|
||||
const blockedOverview = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.equal(blockedOverview.response.status, 403);
|
||||
assert.equal(blockedOverview.body.code, "PASSWORD_CHANGE_REQUIRED");
|
||||
|
||||
const shortPassword = await request(origin, "/api/admin/change-password", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { newPassword: "too-short" },
|
||||
});
|
||||
assert.equal(shortPassword.response.status, 400);
|
||||
assert.equal(shortPassword.body.code, "INVALID_ADMIN_PASSWORD");
|
||||
|
||||
const changed = await request(origin, "/api/admin/change-password", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { newPassword: "integration-admin-password" },
|
||||
});
|
||||
assert.equal(changed.response.status, 200);
|
||||
assert.equal(changed.body.mustChangePassword, false);
|
||||
|
||||
const updatedSession = await request(origin, "/api/admin/session", { cookie });
|
||||
assert.equal(updatedSession.body.mustChangePassword, false);
|
||||
const overview = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.deepEqual(overview.body.sessions, { active: 2, peak: 4, limit: 100 });
|
||||
|
||||
const rejectedMutation = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
body: { target: "voice.example.com:9988", accessMode: "open", siteName: "Changed", welcomeText: "" },
|
||||
});
|
||||
assert.equal(rejectedMutation.response.status, 403);
|
||||
assert.equal(rejectedMutation.body.code, "CSRF_REJECTED");
|
||||
|
||||
const saved = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {
|
||||
target: "voice.example.com:9988",
|
||||
passwordAction: "remove",
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
},
|
||||
});
|
||||
assert.equal(saved.body.ok, true);
|
||||
assert.equal(saved.body.settings.accessMode, "open");
|
||||
assert.equal(saved.body.settings.hasPassword, false);
|
||||
assert.equal(saved.body.settings.webRtcEnabled, true);
|
||||
assert.equal(saved.body.settings.webRtcUdpStart, 41000);
|
||||
assert.equal(saved.body.settings.webRtcUdpEnd, 41099);
|
||||
|
||||
const lockedPorts = await request(origin, "/api/admin/server", {
|
||||
method: "PUT",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {
|
||||
target: "voice.example.com:9988",
|
||||
passwordAction: "keep",
|
||||
accessMode: "open",
|
||||
siteName: "Changed",
|
||||
welcomeText: "Open access",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
},
|
||||
});
|
||||
assert.equal(lockedPorts.response.status, 400);
|
||||
assert.equal(lockedPorts.body.code, "WEBRTC_PORT_LOCKED");
|
||||
|
||||
const invite = await request(origin, "/api/admin/invites", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { channel: "Lobby", expiresInHours: 4, maxUses: 2 },
|
||||
});
|
||||
assert.equal(invite.response.status, 201);
|
||||
assert.equal(invite.body.ok, true);
|
||||
assert.match(invite.body.token, /^[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(invite.body.invite.channel, "Lobby");
|
||||
assert.equal("token" in invite.body.invite, false);
|
||||
|
||||
const invites = await request(origin, "/api/admin/invites", { cookie });
|
||||
assert.equal(invites.body.invites.length, 1);
|
||||
assert.equal(invites.body.invites[0].status, "active");
|
||||
assert.equal(invites.body.invites[0].target, "voice.example.com:9988");
|
||||
|
||||
const sessions = await request(origin, "/api/admin/sessions", { cookie });
|
||||
assert.deepEqual(sessions.body.sessions, []);
|
||||
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
|
||||
assert.equal(diagnostics.body.database.schemaVersion, 3);
|
||||
assert.equal("target" in diagnostics.body.teamSpeak, true);
|
||||
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
|
||||
|
||||
const report = await request(origin, "/api/admin/diagnostics/report", { cookie });
|
||||
assert.equal(report.response.status, 200);
|
||||
assert.match(report.response.headers.get("content-disposition") ?? "", /diagnostic-report\.json/);
|
||||
assert.equal("target" in report.body.teamSpeak, false);
|
||||
assert.equal("protocol" in report.body.teamSpeak, false);
|
||||
assert.equal("serverPassword" in report.body, false);
|
||||
|
||||
const revoked = await request(origin, `/api/admin/invites/${encodeURIComponent(invite.body.invite.id)}/revoke`, {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: {},
|
||||
});
|
||||
assert.equal(revoked.body.ok, true);
|
||||
const revokedList = await request(origin, "/api/admin/invites", { cookie });
|
||||
assert.equal(revokedList.body.invites[0].status, "revoked");
|
||||
|
||||
const backup = await download(origin, "/api/admin/backup", cookie);
|
||||
assert.equal(backup.response.status, 200);
|
||||
assert.equal(backup.response.headers.get("content-type"), "application/octet-stream");
|
||||
assert.ok(backup.bytes.length > 100);
|
||||
assert.equal("serverPassword" in saved.body.settings, false);
|
||||
|
||||
const probe = await request(origin, "/api/admin/server/test", {
|
||||
method: "POST",
|
||||
cookie,
|
||||
csrf: login.body.csrfToken,
|
||||
body: { target: "voice.example.com:9988", passwordAction: "remove" },
|
||||
});
|
||||
assert.equal("protocol" in probe.body, false);
|
||||
const settings = await request(origin, "/api/admin/server", { cookie });
|
||||
assert.equal("detectedProtocol" in settings.body, false);
|
||||
assert.equal(settings.body.lastTestLatencyMs, 7);
|
||||
|
||||
const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} });
|
||||
assert.equal(logout.body.ok, true);
|
||||
const denied = await request(origin, "/api/admin/overview", { cookie });
|
||||
assert.equal(denied.response.status, 401);
|
||||
|
||||
const oldPassword = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "admin" },
|
||||
});
|
||||
assert.equal(oldPassword.response.status, 401);
|
||||
const newPassword = await request(origin, "/api/admin/login", {
|
||||
method: "POST",
|
||||
body: { username: "admin", password: "integration-admin-password" },
|
||||
});
|
||||
assert.equal(newPassword.response.status, 200);
|
||||
assert.equal(newPassword.body.mustChangePassword, false);
|
||||
});
|
||||
|
||||
async function request(
|
||||
origin: string,
|
||||
pathname: string,
|
||||
options: { method?: string; body?: unknown; cookie?: string; csrf?: string } = {},
|
||||
): Promise<{ response: Response; body: any }> {
|
||||
const method = options.method ?? "GET";
|
||||
const response = await fetch(`${origin}${pathname}`, {
|
||||
method,
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
...(method !== "GET" ? { "content-type": "application/json", origin } : {}),
|
||||
...(options.cookie ? { cookie: options.cookie } : {}),
|
||||
...(options.csrf ? { "x-csrf-token": options.csrf } : {}),
|
||||
},
|
||||
...(method !== "GET" ? { body: JSON.stringify(options.body ?? {}) } : {}),
|
||||
});
|
||||
return { response, body: await response.json() };
|
||||
}
|
||||
|
||||
async function download(origin: string, pathname: string, cookie?: string): Promise<{ response: Response; bytes: Uint8Array }> {
|
||||
const response = await fetch(`${origin}${pathname}`, {
|
||||
headers: { accept: "application/octet-stream", ...(cookie ? { cookie } : {}) },
|
||||
});
|
||||
return { response, bytes: new Uint8Array(await response.arrayBuffer()) };
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { AdminService } from "../src/admin/admin-service.js";
|
||||
import { WebSpeakDatabase } from "../src/persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("legacy config imports once, seeds the default admin, and allows password rotation", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-service-"));
|
||||
const legacyPath = path.join(directory, "config.json");
|
||||
const legacyText = JSON.stringify({
|
||||
tsHost: "legacy.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "legacy-secret-value",
|
||||
tsServerProtocol: "ts6",
|
||||
maxClients: 9000,
|
||||
port: 9999,
|
||||
trustProxy: true,
|
||||
}, null, 2);
|
||||
writeFileSync(legacyPath, legacyText);
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
legacyPath,
|
||||
async () => ({ ok: true, protocol: "ts6", latencyMs: 4, serverName: "Mock TS", requiresPassword: true }),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
assert.equal(readFileSync(legacyPath, "utf8"), legacyText);
|
||||
assert.equal(database.getSettings().tsHost, "legacy.example.com");
|
||||
assert.equal(database.getSettings().tsPort, 9988);
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "legacy-secret-value");
|
||||
assert.equal(readFileSync(path.join(directory, "webspeak.db")).includes(Buffer.from("legacy-secret-value")), false);
|
||||
assert.equal(service.isInitialized(), true);
|
||||
assert.equal(await service.verifyPassword("admin", "admin"), true);
|
||||
assert.equal(await service.verifyPassword("wrong-user", "admin"), false);
|
||||
assert.equal(service.isPasswordChangeRequired(), true);
|
||||
await service.changePassword("a-secure-admin-password");
|
||||
assert.equal(await service.verifyPassword("admin", "a-secure-admin-password"), true);
|
||||
assert.equal(await service.verifyPassword("admin", "admin"), false);
|
||||
assert.equal(service.isPasswordChangeRequired(), false);
|
||||
assert.equal(service.getPublicConfig().accessMode, "fixed");
|
||||
assert.equal(service.getPublicConfig().target, "legacy.example.com:9988");
|
||||
|
||||
service.updateSettings({
|
||||
target: "public.example.com:9987",
|
||||
serverPassword: "replacement-secret",
|
||||
passwordAction: "replace",
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
const publicConfig = service.getPublicConfig();
|
||||
assert.equal(publicConfig.target, "public.example.com:9987");
|
||||
assert.equal(publicConfig.accessMode, "open");
|
||||
assert.equal("serverPassword" in service.getAdminSettings(), false);
|
||||
assert.equal(service.getAdminSettings().hasPassword, true);
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
|
||||
assert.equal(service.getAdminSettings().webRtcEnabled, true);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpStart, 41000);
|
||||
assert.equal(service.getAdminSettings().webRtcUdpEnd, 41099);
|
||||
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, udpPortRange: [41000, 41099] });
|
||||
assert.throws(() => service.updateSettings({
|
||||
target: "public.example.com:9987",
|
||||
accessMode: "open",
|
||||
siteName: "Open WebSpeak",
|
||||
welcomeText: "Public gateway",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 42000,
|
||||
webRtcUdpEnd: 42099,
|
||||
}), /Disable WebRTC/);
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("managed invites are opaque, bounded, revocable, and included in database backups", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-invites-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
const created = service.createManagedInvite({ channel: "Lobby", expiresInHours: 2, maxUses: 1 });
|
||||
assert.match(created.token, /^[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(created.invite.channel, "Lobby");
|
||||
assert.equal(created.invite.status, "active");
|
||||
assert.equal("token" in created.invite, false);
|
||||
|
||||
const consumed = service.consumeManagedInvite(created.token);
|
||||
assert.deepEqual(consumed?.target, { host: "127.0.0.1", port: 9987 });
|
||||
assert.equal(consumed?.channel, "Lobby");
|
||||
assert.equal(service.consumeManagedInvite(created.token), null);
|
||||
assert.equal(service.listManagedInvites()[0]?.status, "exhausted");
|
||||
|
||||
database.createManagedInvite({
|
||||
id: "invite-expired-test",
|
||||
tokenHash: "expired-token-hash",
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: 9987,
|
||||
serverPasswordEncrypted: null,
|
||||
channel: "Expired",
|
||||
expiresAt: new Date(Date.now() - 1).toISOString(),
|
||||
maxUses: 0,
|
||||
});
|
||||
assert.equal(database.consumeManagedInvite("expired-token-hash"), null);
|
||||
const revocable = service.createManagedInvite({ channel: "Revocable", expiresInHours: 2, maxUses: 0 });
|
||||
assert.equal(service.revokeManagedInvite(revocable.invite.id), true);
|
||||
assert.equal(service.listManagedInvites().find((invite) => invite.id === revocable.invite.id)?.status, "revoked");
|
||||
|
||||
const backup = database.exportBackup();
|
||||
assert.ok(backup.length > 100);
|
||||
database.close();
|
||||
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
assert.equal(reopened.schemaVersion, 3);
|
||||
assert.equal(reopened.listManagedInvites().length, 3);
|
||||
reopened.close();
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, it } from "node:test";
|
||||
import { migrateConfig, saveConfig } from "../src/config.js";
|
||||
|
||||
describe("legacy config migration", () => {
|
||||
it("drops deprecated runtime controls while preserving the TeamSpeak target", () => {
|
||||
assert.deepEqual(migrateConfig({
|
||||
port: 3999,
|
||||
tsHost: "TS.Example.COM",
|
||||
tsPort: "9988",
|
||||
tsServerPassword: "secret",
|
||||
tsServerProtocol: "ts6",
|
||||
maxClients: 3,
|
||||
trustProxy: true,
|
||||
}), {
|
||||
tsHost: "ts.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "secret",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a host with an embedded port during migration", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "[2001:db8::1]:9988" }), {
|
||||
tsHost: "2001:db8::1",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the address#port form during migration", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "voice.example.com#9988" }), {
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back safely for malformed legacy targets", () => {
|
||||
assert.deepEqual(migrateConfig({ tsHost: "bad host", tsPort: 0 }), {
|
||||
tsHost: "127.0.0.1",
|
||||
tsPort: 9987,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the migrated shape without deprecated runtime controls", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "webspeak-m000-config-"));
|
||||
const path = join(directory, "config.json");
|
||||
try {
|
||||
writeFileSync(path, JSON.stringify({
|
||||
port: 3999,
|
||||
tsHost: "example.com",
|
||||
tsPort: 9988,
|
||||
tsServerProtocol: "ts3",
|
||||
maxClients: 2,
|
||||
trustProxy: true,
|
||||
}), "utf8");
|
||||
saveConfig(path, migrateConfig(JSON.parse(readFileSync(path, "utf8"))));
|
||||
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), {
|
||||
tsHost: "example.com",
|
||||
tsPort: 9988,
|
||||
tsServerPassword: "",
|
||||
});
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { ChannelInfo, ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import { DirectorySynchronizer } from "../src/server/directory-sync.js";
|
||||
|
||||
const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", };
|
||||
const games: ChannelInfo = { id: 2n, parentID: 1n, name: "Games", description: "", };
|
||||
|
||||
function client(id: number, nickname: string, channelID: bigint): ClientInfo {
|
||||
return { id, nickname, uid: `uid-${id}`, channelID, type: 1, serverGroups: [] };
|
||||
}
|
||||
|
||||
test("directory synchronizer merges welcome events that arrive before the snapshot", () => {
|
||||
const sync = new DirectorySynchronizer();
|
||||
sync.applyClientEnter(client(7, "Alice", 1n));
|
||||
sync.applyClientMoved(7, 2n);
|
||||
sync.applySnapshot({ channels: [root, games], clients: [client(3, "Bob", 1n)] });
|
||||
assert.equal(sync.ready, true);
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n], [7, 2n]]);
|
||||
});
|
||||
|
||||
test("directory state and movement events remain isolated per session", () => {
|
||||
const first = new DirectorySynchronizer();
|
||||
const second = new DirectorySynchronizer();
|
||||
const snapshot = { channels: [root, games], clients: [client(3, "Bob", 1n)] };
|
||||
first.applySnapshot(snapshot);
|
||||
second.applySnapshot(snapshot);
|
||||
first.applyClientEnter(client(7, "Alice", 2n));
|
||||
first.applyClientMoved(3, 2n);
|
||||
first.applyClientLeave(7);
|
||||
assert.deepEqual(first.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 2n]]);
|
||||
assert.deepEqual(second.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n]]);
|
||||
});
|
||||
|
||||
test("directory synchronizer keeps clients across staged partial snapshots", () => {
|
||||
const sync = new DirectorySynchronizer();
|
||||
const alice = client(7, "Alice", 1n);
|
||||
const bob = client(8, "Bob", 1n);
|
||||
|
||||
sync.applySnapshot({ channels: [root], clients: [alice, bob] });
|
||||
sync.applySnapshot({ channels: [root], clients: [bob] });
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [7, 8]);
|
||||
|
||||
sync.applyClientLeave(alice.id);
|
||||
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [8]);
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { normalizeTeamSpeakError } from "../src/errors.js";
|
||||
|
||||
describe("normalized connection errors", () => {
|
||||
it("classifies authentication failures as non-retryable", () => {
|
||||
const error = normalizeTeamSpeakError(new Error("invalid server password"));
|
||||
assert.equal(error.code, "authentication_failed");
|
||||
assert.equal(error.retryable, false);
|
||||
});
|
||||
|
||||
it("classifies network and timeout failures", () => {
|
||||
assert.equal(normalizeTeamSpeakError(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })).code, "unreachable");
|
||||
assert.equal(normalizeTeamSpeakError(new Error("ack timeout")).code, "timeout");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { Logger } from "../../src/logger.js";
|
||||
|
||||
export const silentLogger: Logger = {
|
||||
debug: () => undefined,
|
||||
info: () => undefined,
|
||||
warn: () => undefined,
|
||||
error: () => undefined,
|
||||
child: () => silentLogger,
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JoinRateLimiter } from "../src/server/join-rate-limit.js";
|
||||
|
||||
test("join ticket creation is bounded per peer and resets after its window", () => {
|
||||
const limiter = new JoinRateLimiter(2);
|
||||
let now = 10_000;
|
||||
for (let attempt = 0; attempt < 30; attempt++) assert.equal(limiter.allow("peer-a", now), true);
|
||||
assert.equal(limiter.allow("peer-a", now), false);
|
||||
assert.equal(limiter.allow("peer-b", now), true);
|
||||
now += 60_000;
|
||||
assert.equal(limiter.allow("peer-a", now), true);
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { generateIdentity } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinTicketStore } from "../src/server/join-ticket.js";
|
||||
|
||||
test("join tickets are opaque, one-time, and expire", () => {
|
||||
const store = new JoinTicketStore(1000, 2);
|
||||
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest" };
|
||||
const token = store.create(payload, 100);
|
||||
assert.equal(token.includes("secret"), false);
|
||||
assert.deepEqual(store.consume(token, 101), payload);
|
||||
assert.equal(store.consume(token, 102), null);
|
||||
const expired = store.create(payload, 200);
|
||||
assert.equal(store.consume(expired, 1201), null);
|
||||
});
|
||||
|
||||
test("join tickets carry identity only in memory and never expose it in the opaque token", () => {
|
||||
const store = new JoinTicketStore();
|
||||
const identity = generateIdentity(8).toString();
|
||||
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest", identity, rememberIdentity: true };
|
||||
const token = store.create(payload);
|
||||
assert.equal(token.includes(identity), false);
|
||||
assert.deepEqual(store.consume(token), payload);
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../src/constants.js";
|
||||
|
||||
describe("session safety limit", () => {
|
||||
it("uses the fixed 100-session product limit", () => {
|
||||
assert.equal(MAX_ACTIVE_SESSIONS, 100);
|
||||
assert.equal(canAcceptSession(99), true);
|
||||
assert.equal(canAcceptSession(100), false);
|
||||
assert.equal(canAcceptSession(101), false);
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { AdminLoginRateLimiter } from "../src/admin/login-rate-limit.js";
|
||||
|
||||
test("admin login limiter blocks repeated failures for one peer", () => {
|
||||
const limiter = new AdminLoginRateLimiter();
|
||||
const start = 1_000_000;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("peer-a", start + attempt);
|
||||
assert.ok(limiter.retryAfterMs("peer-a", start + 5) > 0);
|
||||
assert.equal(limiter.retryAfterMs("peer-a", start + 5 * 60 * 1000), 0);
|
||||
});
|
||||
|
||||
test("admin login limiter evicts old peers when its bounded table is full", () => {
|
||||
const limiter = new AdminLoginRateLimiter(2);
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("oldest", 10 + attempt);
|
||||
limiter.recordFailure("second", 20);
|
||||
limiter.recordFailure("newest", 30);
|
||||
assert.equal(limiter.retryAfterMs("oldest", 31), 0);
|
||||
assert.equal(limiter.retryAfterMs("second", 31), 0);
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isRestrictedAddress, resolveSafeOpenTarget } from "../src/security/open-target-policy.js";
|
||||
|
||||
test("open mode blocks loopback, private, link-local, multicast and reserved ranges", () => {
|
||||
for (const address of [
|
||||
"0.0.0.0", "10.1.2.3", "100.64.0.1", "127.0.0.1", "169.254.1.2",
|
||||
"172.16.0.1", "192.168.1.2", "224.0.0.1", "255.255.255.255",
|
||||
"::", "::1", "::7f00:1", "fc00::1", "fe80::1", "fec0::1", "ff02::1", "2001:db8::1",
|
||||
]) assert.equal(isRestrictedAddress(address), true, address);
|
||||
assert.equal(isRestrictedAddress("8.8.8.8"), false);
|
||||
assert.equal(isRestrictedAddress("2606:4700:4700::1111"), false);
|
||||
});
|
||||
|
||||
test("validated literal target is returned for the actual connection", async () => {
|
||||
assert.deepEqual(await resolveSafeOpenTarget({ host: "8.8.8.8", port: 9987 }), { host: "8.8.8.8", port: 9987 });
|
||||
await assert.rejects(resolveSafeOpenTarget({ host: "127.0.0.1", port: 9987 }));
|
||||
});
|
||||
@@ -1,84 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import test from "node:test";
|
||||
import { WebSpeakDatabase, DATABASE_SCHEMA_VERSION } from "../src/persistence/database.js";
|
||||
import { hashAdminPassword } from "../src/security/admin-password.js";
|
||||
|
||||
test("SQLite persistence initializes schema and stores the single admin/settings model", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-"));
|
||||
const dbPath = path.join(directory, "webspeak.db");
|
||||
const database = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
|
||||
assert.equal(database.hasAdmin(), false);
|
||||
assert.equal(database.getSettings().accessMode, "fixed");
|
||||
|
||||
const credential = await hashAdminPassword("database-admin-password");
|
||||
database.initializeAdmin(credential, {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
});
|
||||
assert.equal(database.hasAdmin(), true);
|
||||
assert.equal(database.getAdminCredential()?.hash, credential.hash);
|
||||
assert.deepEqual(database.getSettings(), {
|
||||
siteName: "Private Voice",
|
||||
welcomeText: "Welcome",
|
||||
accessMode: "open",
|
||||
tsHost: "voice.example.com",
|
||||
tsPort: 9988,
|
||||
tsPasswordEncrypted: "v1:ciphertext",
|
||||
detectedProtocol: null,
|
||||
lastTestAt: null,
|
||||
lastTestLatencyMs: null,
|
||||
lastTestError: null,
|
||||
webRtcEnabled: true,
|
||||
webRtcUdpStart: 41000,
|
||||
webRtcUdpEnd: 41099,
|
||||
updatedAt: database.getSettings().updatedAt,
|
||||
});
|
||||
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
|
||||
database.close();
|
||||
|
||||
const reopened = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(reopened.hasAdmin(), true);
|
||||
assert.equal(reopened.getSettings().siteName, "Private Voice");
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
test("SQLite schema v1 upgrades to v3 with a migration copy", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-"));
|
||||
const dbPath = path.join(directory, "webspeak.db");
|
||||
const legacy = new DatabaseSync(dbPath);
|
||||
legacy.exec(`
|
||||
CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE admin_credentials (id INTEGER PRIMARY KEY CHECK (id = 1), credential_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
|
||||
CREATE TABLE settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1), site_name TEXT NOT NULL, welcome_text TEXT NOT NULL,
|
||||
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')), ts_host TEXT NOT NULL,
|
||||
ts_port INTEGER NOT NULL, ts_password_encrypted TEXT, detected_protocol TEXT,
|
||||
last_test_at TEXT, last_test_latency_ms INTEGER, last_test_error TEXT, updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE audit_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT NOT NULL, details_json TEXT NOT NULL, created_at TEXT NOT NULL);
|
||||
INSERT INTO settings VALUES (1, 'Legacy', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, '2026-01-01T00:00:00.000Z');
|
||||
PRAGMA user_version = 1;
|
||||
`);
|
||||
legacy.close();
|
||||
|
||||
const upgraded = new WebSpeakDatabase(dbPath);
|
||||
assert.equal(upgraded.schemaVersion, 3);
|
||||
assert.equal(upgraded.getSettings().webRtcEnabled, false);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
|
||||
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
|
||||
assert.equal(upgraded.listManagedInvites().length, 0);
|
||||
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
|
||||
upgraded.close();
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { probeTeamSpeak, toProbeError } from "../src/server/teamspeak-probe.js";
|
||||
import { silentLogger } from "./helpers/logger.js";
|
||||
|
||||
test("connection probe reports protocol/server and always tears down", async () => {
|
||||
let disconnected = false;
|
||||
const result = await probeTeamSpeak({ host: "example.com", port: 9987 }, "", silentLogger, () => ({
|
||||
protocol: "ts6",
|
||||
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Example TS" }] },
|
||||
connect: async () => undefined,
|
||||
disconnect: async () => { disconnected = true; },
|
||||
}));
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.protocol, "ts6");
|
||||
assert.equal(result.serverName, "Example TS");
|
||||
assert.equal(disconnected, true);
|
||||
});
|
||||
|
||||
test("connection probe normalizes DNS errors and tears down failures", async () => {
|
||||
let disconnected = false;
|
||||
await assert.rejects(
|
||||
probeTeamSpeak({ host: "missing.invalid", port: 9987 }, "", silentLogger, () => ({
|
||||
protocol: null,
|
||||
client: { execCommandWithResponse: async () => [] },
|
||||
connect: async () => { throw Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" }); },
|
||||
disconnect: async () => { disconnected = true; },
|
||||
})),
|
||||
(error: unknown) => Boolean(error && typeof error === "object" && "code" in error && error.code === "HOST_NOT_FOUND"),
|
||||
);
|
||||
assert.equal(disconnected, true);
|
||||
assert.equal(toProbeError(new Error("authentication invalid password")).code, "INVALID_PASSWORD");
|
||||
});
|
||||
|
||||
test("connection probe keeps a successful result when cleanup reports an error", async () => {
|
||||
const result = await probeTeamSpeak(
|
||||
{ host: "voice.example.com", port: 9987 },
|
||||
"",
|
||||
silentLogger,
|
||||
() => ({
|
||||
protocol: "ts6",
|
||||
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Cleanup Test" }] },
|
||||
connect: async () => {},
|
||||
disconnect: async () => { throw new Error("already disconnected"); },
|
||||
}),
|
||||
);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.serverName, "Cleanup Test");
|
||||
});
|
||||