mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 20:12:52 +08:00
Compare commits
9
Commits
v0.2.8
..
b9fccb8757
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9fccb8757 | ||
|
|
4bff2133b6 | ||
|
|
88439181ae | ||
|
|
941cff30d7 | ||
|
|
9c4a2c4a51 | ||
|
|
bb5905eb39 | ||
|
|
452e6f09ca | ||
|
|
0af3236c30 | ||
|
|
180bfeb52f |
No files matched your search
@@ -47,8 +47,6 @@ jobs:
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
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
|
||||
@@ -157,7 +155,6 @@ jobs:
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
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")"
|
||||
@@ -261,7 +258,6 @@ jobs:
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
npm version --no-git-tag-version "$release_version"
|
||||
fi
|
||||
npm run prepare:sdk
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
npm run android:sync
|
||||
|
||||
@@ -25,7 +25,6 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
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 application
|
||||
|
||||
@@ -144,17 +144,18 @@ Settings responses merge against the submitted snapshot instead of replacing new
|
||||
|
||||
The current SQLite schema version is defined in `src/persistence/database.ts`. Keep schema migrations separate from structural refactors. Legacy fields such as `voiceToken`, `tsApiKey`, `tsQueryPort`, `port` and `maxClients` do not configure the current gateway.
|
||||
|
||||
Optional TS administration lives in `src/admin/ts-admin-service.ts` and `/admin/ts-admin`. It uses the published SDK's typed commands through `QueryClient` over WebQuery, SSH or TCP, separately from guest voice and WebSpeak administration. Never require these credentials for a voice connection. WebQuery has no notifications: omit `events` entirely; `events: false` is also rejected by this SDK. Bind queued mutations to the reviewed configuration, recheck a member's live UID before acting, and never ban the shared gateway IP. Keep credentials encrypted with distinct purpose strings and return only presence flags. Management writes are not automatically retried; a failed refresh cannot imply an acknowledged write failed.
|
||||
|
||||
The gateway HTTP port is `3040`. Its admission ceiling is `100` sessions, defined in `src/constants.ts`; this is an application limit, not a TeamSpeak license allowance or a measured performance guarantee. Target server capacity and permissions still apply.
|
||||
|
||||
The server uses HTTPS when `certs/cert.pem` and `certs/key.pem` are supplied; otherwise it starts HTTP. It does not generate certificates. Use an appropriate secure browser origin for microphone and screen capture, typically HTTPS in public deployments. Feature support depends on the browser and selected transport; do not infer a universal minimum browser version from WebCodecs alone.
|
||||
|
||||
## Development and verification
|
||||
|
||||
Server deployments require Node.js 22.5 or newer. CI uses Node.js 22.22.2. Root and frontend dependencies are installed separately. The pinned Git SDK and native Opus module require the preparation steps used by CI:
|
||||
Server deployments require Node.js 22.12 or newer. CI uses Node.js 22.22.2. Root and frontend dependencies are installed separately. The SDK is installed from the npm registry; only native Opus needs a rebuild after installing with scripts disabled:
|
||||
|
||||
```sh
|
||||
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
|
||||
npm run verify
|
||||
|
||||
+2
-4
@@ -2,14 +2,12 @@ FROM node:22-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates 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 --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
|
||||
|
||||
@@ -39,7 +37,7 @@ COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./script
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
EXPOSE 3040/tcp 3041/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
@@ -77,11 +77,12 @@ Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music
|
||||
|
||||
## Contributors · 贡献者
|
||||
|
||||
感谢通过 PR 改进 WebSpeak 的贡献者。以下按 GitHub 的合并记录列出。
|
||||
感谢上游 SDK 作者及通过 PR 改进 WebSpeak 的贡献者。以下列出上游基础项目、已合并的 PR,以及已移植为独立皮肤包的原始贡献。
|
||||
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
|
||||
+39
-11
@@ -17,7 +17,7 @@ Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, V
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll anhand der gemeldeten Version 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. |
|
||||
@@ -33,6 +33,26 @@ Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, V
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Pakete für Windows x64 und Linux x64/ARM64, Docker für amd64/arm64 und Android-APKs für arm64-v8a, armeabi-v7a und x86_64. |
|
||||
|
||||
## TeamSpeak-Versionskompatibilität
|
||||
|
||||
Sprachverbindungen verwenden das TeamSpeak-Clientprotokoll und benötigen keine Query-Zugangsdaten. Die optionale TS-Verwaltung verwendet eigene WebQuery-/ServerQuery-Zugangsdaten.
|
||||
|
||||
- **TeamSpeak 3**: Die Erkennung wertet die führende `3.x`-Versionsnummer aus. Ältere Serverversionen sollten in der jeweiligen Umgebung geprüft werden, da nicht jede historische Version separat getestet wurde.
|
||||
- **TeamSpeak 6**: Unterstützt, einschließlich Bildschirmfreigabe mit nativen TeamSpeak-6-Clients.
|
||||
- **Automatische Erkennung**: Das Gateway liest die `version`-Antwort des Servers und hält das erkannte Protokoll in der Verbindungsdiagnose fest.
|
||||
- Das Gateway verwendet das Upstream-SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak richtet sich an TeamSpeak 3 und 6.
|
||||
|
||||
## Optionale TeamSpeak-Verwaltung
|
||||
|
||||
WebSpeak-Verwaltung und Sprachverbindungen sind davon unabhängig. Im Modus mit festem Server die TS-Verbindung unter `/admin/ts-admin` einrichten.
|
||||
|
||||
1. WebQuery auf dem TS-Server aktivieren und einen berechtigten TS-Administrator einen API-Schlüssel erstellen lassen. HTTP-/HTTPS-URL von WebQuery und Schlüssel eintragen. Gemeint ist der TS-Query-Dienst, nicht die WebSpeak-Webseite. Unterstützt werden TS3 ab 3.12 und TS6.
|
||||
2. Virtuelle Server-ID `0` wählt anhand des festen Sprachports aus. Bei eingeschränkten Schlüsseln die freigegebene Server-ID eintragen. Änderungen erfordern einen schreibbaren Geltungsbereich und entsprechende TS-Rechte; Leseschlüssel dienen zur Anzeige.
|
||||
3. Alternativ ServerQuery SSH oder bei TS3 ServerQuery TCP wählen. Query-Host (leer: festes Ziel), Query-Port, Benutzername und Passwort eintragen; SSH benötigt einen vertrauenswürdigen Hostschlüssel-Fingerabdruck. Dies ist kein SSH-Zugang zum Betriebssystem. TCP ist unverschlüsselt und nur für vertrauenswürdige Netze geeignet. HTTPS-Zertifikate müssen vom Gateway als vertrauenswürdig erkannt werden.
|
||||
4. Speichern und verbinden oder aktualisieren. Verfügbar sind Servereinstellungen, Kanalverwaltung, Verschieben/Ausschließen/Sperren von Mitgliedern, Gruppenzuweisung und Entsperren. Aktionen benötigen Bestätigung und TS-Rechte; Listen werden manuell aktualisiert.
|
||||
|
||||
Zugangsdaten werden serverseitig verschlüsselt und nie von der API zurückgegeben. Datenbank und `master.key` gemeinsam sichern. Verbindungsfehler beeinflussen weder WebSpeak-Verwaltung noch Sprache. Sperren verwenden die Benutzer-UID, damit andere Nutzer derselben Gateway-IP nicht betroffen sind.
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
@@ -86,7 +106,7 @@ Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegense
|
||||
|
||||
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.
|
||||
Eine Relay-Instanz betreibt sowohl die ältere UDP-Kompatibilitätsweiterleitung als auch ein separates Sprach-Gateway, jedoch keine Besucher- oder Administrationsseite. Das Eingangs-Gateway signiert mit dem gemeinsamen Token ein einmaliges Sprach-Ticket und delegiert es; anschließend verbindet sich der Browser direkt mit dem Relay, das seinerseits TeamSpeak erreicht. Die Seite bleibt unter der URL des Eingangs-Gateways. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
@@ -94,7 +114,6 @@ Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder
|
||||
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' \
|
||||
@@ -138,12 +157,20 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Den UDP-Listening-Port des Relay-Hosts freigeben, standardmäßig `39087`.
|
||||
Das Sprach-Gateway lauscht standardmäßig auf `127.0.0.1:3041`. Eine HTTPS-Domain für das Relay einrichten und sie mit Caddy oder einem vergleichbaren Proxy an `127.0.0.1:3041` weiterleiten, zum Beispiel:
|
||||
|
||||
```caddyfile
|
||||
relay.example.com {
|
||||
reverse_proxy 127.0.0.1:3041
|
||||
}
|
||||
```
|
||||
|
||||
In den Relay-Einstellungen des Eingangs-Gateways als **Voice gateway address** diesen HTTPS-Ursprung eintragen, etwa `https://relay.example.com`. Die Seite bleibt auf ihrem ursprünglichen Gateway und öffnet danach eine WSS-Verbindung zum Relay. WebRTC ist auf dem Relay standardmäßig aktiviert. Zusätzlich UDP `40000-40099` freigeben und `WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST` auf eine öffentliche Relay-IP oder direkt erreichbare Domain setzen. Bei geänderter WebRTC-Portspanne auch die Firewall anpassen. UDP `39087` für ältere Kompatibilitätsweiterleitungen offen lassen.
|
||||
|
||||
#### 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.
|
||||
2. Anzeigename, UDP-Endpunkt wie `relay.example.com#39087`, HTTPS-Ursprung des Sprach-Gateways wie `https://relay.example.com` 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.
|
||||
@@ -254,7 +281,7 @@ Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchron
|
||||
| --- | --- | --- |
|
||||
| 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/ARM64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.12+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
@@ -294,7 +321,6 @@ Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfüg
|
||||
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
|
||||
@@ -325,9 +351,11 @@ Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
|
||||
## Kürzlich zusammengeführte Beiträge
|
||||
## Mitwirkende und Beiträge
|
||||
|
||||
- Die Liste folgt den GitHub-Merge-Einträgen.
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) verbesserte Browser-Fehlermeldungen; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) korrigierte Skalierung, schwebendes Layout und Fußzeile der Startseite.
|
||||
Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusammengeführten GitHub-PRs sowie ursprüngliche Arbeiten, die in eigenständig verteilte Skin-Pakete übernommen wurden.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Autor des [teamspeak-js-SDKs (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), das den von WebSpeak verwendeten TeamSpeak-Protokollclient bereitstellt.
|
||||
- [LainHE](https://github.com/LainHE) — [zusammengeführte PRs #2, #8, #28, #31–#35, #37, #38 und #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): Browser-Fehlerübersetzungen, Skalierung und Startseitenlayout, Bildschirmfreigabe-Bitrate und Zuschaueravatare, Relay-Zielprüfung und Wiederverbindung, vertrauenswürdige Proxys, Weitergabe von Verbindungsfehlern, Audio-Fehlermeldungen und Ressourcenfreigabe bei WebRTC-Fehlern.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele in Einstellungen, Favoriten und Einladungen.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) verbesserte das Beibehalten des KAAK-Arbeitsbereichs und die Wiederverbindung nach der ersten Verbindung. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) und [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) lieferten das ursprüngliche Design und die Implementierung des Discord-Skins (Commit-Autor **yumi**), die das WebSpeak-Projekt in einen [eigenständig verteilten `.wskin`-Skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) überführte.
|
||||
+39
-11
@@ -19,7 +19,7 @@ Network conditions and load may vary at either demo. Latency, disconnections, or
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6, automatically detecting the target protocol from the reported version. |
|
||||
| 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. |
|
||||
@@ -35,6 +35,26 @@ Network conditions and load may vary at either demo. Latency, disconnections, or
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; packages include Windows x64 and Linux x64/ARM64, Docker supports amd64/arm64, and Android APKs target arm64-v8a, armeabi-v7a, and x86_64. |
|
||||
|
||||
## TeamSpeak version compatibility
|
||||
|
||||
Voice uses the standard TeamSpeak client protocol and needs no Query credentials. Optional TeamSpeak administration uses separate WebQuery / ServerQuery credentials.
|
||||
|
||||
- **TeamSpeak 3**: protocol detection recognizes the leading `3.x` version. Older server releases should be validated with the specific deployment because not every historical release has been independently tested.
|
||||
- **TeamSpeak 6**: supported, including screen sharing with native TeamSpeak 6 clients.
|
||||
- **Auto-detection**: the gateway reads the server's `version` response and records the detected protocol in connection diagnostics.
|
||||
- The gateway uses the upstream [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK; WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
|
||||
|
||||
## Optional TeamSpeak administration
|
||||
|
||||
WebSpeak administration and visitor voice do not depend on this feature. In fixed-server mode, open `/admin/ts-admin` to configure the TS management connection.
|
||||
|
||||
1. Enable WebQuery on the TS server and have an authorized TS administrator create an API key. Enter the WebQuery HTTP/HTTPS URL and key. This is the TS Query endpoint, not the WebSpeak website. TS3 (3.12+) and TS6 are supported.
|
||||
2. Virtual server ID `0` selects the fixed target's voice port. For a restricted key, enter its authorized server ID. Read-only keys support viewing; changes require writable scope and the corresponding TS permissions.
|
||||
3. Alternatively, choose ServerQuery SSH, or ServerQuery TCP for TS3. Enter the Query host (blank uses the fixed target), Query port, username and password; SSH also requires a trusted host-key fingerprint. This is the TS Query service, not an operating-system SSH login. TCP is unencrypted and suitable only for trusted networks. HTTPS certificates must be trusted by the gateway.
|
||||
4. Save and connect or refresh to inspect the server, channels, members, server groups and bans. Actions include server settings, channel creation/renaming/deletion, moving/kicking/banning members by identity, group assignment and removing bans. Actions require confirmation and TS permission checks; lists refresh manually.
|
||||
|
||||
Credentials are encrypted on the server and never returned by the API. Back up both the database and `master.key`. A failed management connection does not affect WebSpeak administration or ordinary voice. UID bans avoid banning other users sharing the gateway IP.
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
@@ -96,7 +116,7 @@ Browser users and native TeamSpeak 6 clients can discover, start, and watch each
|
||||
|
||||
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.
|
||||
A relay instance runs both the legacy UDP compatibility forwarder and a separate voice gateway, with no visitor page or administration console. The ingress gateway signs and delegates a one-time voice ticket with the shared token; the browser then connects directly to the relay, and the relay connects to TeamSpeak. The page stays on the ingress gateway URL. Use a random token of at least 16 characters.
|
||||
|
||||
#### Run from source
|
||||
|
||||
@@ -104,7 +124,6 @@ A relay instance is a dedicated forwarding service with no visitor page or admin
|
||||
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' \
|
||||
@@ -148,12 +167,20 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port, `39087` by default.
|
||||
The voice gateway listens on `127.0.0.1:3041` by default. Give the relay an HTTPS hostname and reverse-proxy it to `127.0.0.1:3041` with Caddy or an equivalent proxy, for example:
|
||||
|
||||
```caddyfile
|
||||
relay.example.com {
|
||||
reverse_proxy 127.0.0.1:3041
|
||||
}
|
||||
```
|
||||
|
||||
In the ingress gateway's relay settings, set **Voice gateway address** to that HTTPS origin (for example, `https://relay.example.com`). The page remains on its original gateway, then opens a WSS connection to this relay hostname. WebRTC is enabled by default on the relay; also allow UDP `40000-40099` and set `WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST` to a public relay IP or directly reachable hostname. Update firewall rules if you change the WebRTC UDP range. Keep UDP `39087` open for compatibility with older forwarding.
|
||||
|
||||
#### 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.
|
||||
2. Set a display name, UDP endpoint such as `relay.example.com#39087`, HTTPS voice gateway origin such as `https://relay.example.com`, 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.
|
||||
@@ -264,7 +291,7 @@ Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchroniz
|
||||
| --- | --- | --- |
|
||||
| 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/ARM64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
| From source | Development, debugging, and customization | Node.js 22.12+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
@@ -304,7 +331,6 @@ Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. The
|
||||
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
|
||||
@@ -335,9 +361,11 @@ Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
| 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. |
|
||||
|
||||
## Recent contributors
|
||||
## Contributors and contributions
|
||||
|
||||
- Listed from GitHub's merge records; the version summaries above describe only changes included in each release.
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) improved browser error translations; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) fixed scaling, floating layout, and the homepage footer.
|
||||
This list acknowledges the upstream SDK author, contributions through merged GitHub PRs, and original work adapted into independently distributed skin packages.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Author of the upstream [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK, which provides the TeamSpeak protocol client used by WebSpeak.
|
||||
- [LainHE](https://github.com/LainHE) — [merged PRs #2, #8, #28, #31–#35, #37, #38 and #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE), covering browser error translations, scaling and home layout, screen-share bitrate and viewer avatars, relay target validation and recovery, trusted proxy handling, connection-failure propagation, audio fault reporting, and WebRTC failure cleanup.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added connections through registered TeamSpeak nicknames and preserved nickname targets in settings, favorites, and invitations.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added registered TeamSpeak nickname connections and preserved nickname targets; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) improved KAAK workspace retention and reconnection after the first connection. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) and [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) supplied the original Discord skin design and implementation (commit author **yumi**), later adapted by the WebSpeak project into an [independently distributed `.wskin` skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
+28
-7
@@ -23,7 +23,7 @@
|
||||
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、サーバーのバージョンから対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
@@ -39,6 +39,26 @@
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
| デプロイ | Windows x64、Linux x64/ARM64 パッケージ、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 APK。 |
|
||||
|
||||
## TeamSpeak のバージョン互換性
|
||||
|
||||
音声接続には標準の TeamSpeak クライアントプロトコルを使い、Query の認証情報は不要です。任意の TS 管理機能では、別途 WebQuery / ServerQuery の認証情報を使用します。
|
||||
|
||||
- **TeamSpeak 3**: 先頭の `3.x` バージョンを使ってプロトコルを判定します。すべての旧バージョンを個別に検証しているわけではないため、古いサーバーは実際の環境で確認してください。
|
||||
- **TeamSpeak 6**: 対応しています。TeamSpeak 6 ネイティブクライアントとの画面共有も可能です。
|
||||
- **自動検出**: ゲートウェイはサーバーの `version` 応答を読み取り、接続診断に判定結果を記録します。
|
||||
- ゲートウェイは上流 SDK 1.0 の [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) を使用し、WebSpeak は TeamSpeak 3 と 6 を対象とします。
|
||||
|
||||
## 任意の TeamSpeak 管理
|
||||
|
||||
WebSpeak 管理画面と音声接続は、この機能に依存しません。固定サーバーモードで `/admin/ts-admin` を開き、TS 管理用の接続を設定します。
|
||||
|
||||
1. TS サーバーで WebQuery を有効にし、権限のある TS 管理者に API キーを作成してもらいます。WebQuery の HTTP/HTTPS URL とキーを入力します。WebSpeak のサイトではなく、TS Query サービスの URL です。TS3(3.12 以降)と TS6 に対応します。
|
||||
2. 仮想サーバー ID `0` は固定接続先の音声ポートから選択します。制限付きキーでは許可された ID を入力してください。読み取りキーでは閲覧ができ、変更には書き込み可能なスコープと対応する TS 権限が必要です。
|
||||
3. ServerQuery SSH、または TS3 の ServerQuery TCP も選べます。Query ホスト(空欄は固定接続先)、ポート、ユーザー名、パスワードを入力し、SSH では信頼できるホストキーのフィンガープリントも指定します。OS への SSH ログインではありません。TCP は暗号化されないため信頼できるネットワークで使用します。HTTPS 証明書はゲートウェイで信頼されている必要があります。
|
||||
4. 保存して接続または更新します。サーバー設定、チャンネル管理、メンバーの移動・退出・ID による BAN、グループ割り当て、BAN 解除に対応します。操作には確認が必要で、TS が権限を検証します。リストは手動更新します。
|
||||
|
||||
認証情報はサーバーで暗号化され、API から返されません。データベースと `master.key` を一緒にバックアップしてください。管理接続の失敗は WebSpeak 管理画面や音声に影響しません。UID による BAN で同じゲートウェイ IP を使う他のユーザーへの影響を避けます。
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
@@ -112,7 +132,6 @@ docker compose up -d
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
@@ -122,7 +141,7 @@ npm start
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- ソースからのビルドには Node.js `>=22.12` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
|
||||
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
|
||||
@@ -214,9 +233,11 @@ Docker 起動を簡略化し、15秒の接続タイムアウトと継続的な
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
|
||||
## 最近マージされた貢献
|
||||
## 貢献者と主な貢献
|
||||
|
||||
- GitHub のマージ記録に基づく一覧です。上のバージョン概要には、各リリースに実際に含まれる変更のみを記載しています。
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) でブラウザのエラー翻訳を改善し、[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) で拡大縮小、フローティングレイアウト、ホームのフッターを修正。
|
||||
上流 SDK の作者、マージ済みの GitHub PR、および独立配布のスキンパッケージへ移植された原作の貢献を記載しています。
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上流 SDK [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) の作者。WebSpeak の TeamSpeak プロトコル通信を支えるクライアントライブラリを提供。
|
||||
- [LainHE](https://github.com/LainHE) — [マージ済み PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE)。ブラウザのエラー翻訳、拡大縮小とホームのレイアウト、画面共有のビットレートと視聴者アバター、中継先の検証と再接続、信頼済みプロキシの扱い、接続失敗の通知、音声エラー報告、WebRTC 失敗時のリソース解放を改善。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネームによる接続に対応し、設定・お気に入り・招待リンクにニックネームの接続先を保持。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネーム接続と接続先の保持に対応し、[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) で初回接続後の KAAK ワークスペース保持と再接続を改善。[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) と [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) では Discord スキンの原作デザインと実装を提供(コミット名義 **yumi**)。その後、WebSpeak プロジェクトが[独立配布の `.wskin` スキン](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)へ移植。
|
||||
+28
-7
@@ -25,7 +25,7 @@
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола по версии сервера. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
@@ -41,6 +41,26 @@
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
| Развёртывание | Пакеты Windows x64 и Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64. |
|
||||
|
||||
## Совместимость версий TeamSpeak
|
||||
|
||||
Голосовые соединения используют стандартный клиентский протокол TeamSpeak и не требуют учётных данных Query. Необязательное управление TS использует отдельные данные WebQuery / ServerQuery.
|
||||
|
||||
- **TeamSpeak 3**: определение распознаёт ведущую версию `3.x`. Старые версии сервера следует проверять отдельно в конкретной среде: не каждая историческая версия тестировалась независимо.
|
||||
- **TeamSpeak 6**: поддерживается, включая демонстрацию экрана с нативными клиентами TeamSpeak 6.
|
||||
- **Автоопределение**: шлюз читает ответ сервера `version` и записывает распознанный протокол в диагностику подключения.
|
||||
- Шлюз использует upstream SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak рассчитан на TeamSpeak 3 и 6.
|
||||
|
||||
## Необязательное управление TeamSpeak
|
||||
|
||||
Панель WebSpeak и голосовые соединения работают независимо от этой функции. В режиме фиксированного сервера откройте `/admin/ts-admin` для настройки управления TS.
|
||||
|
||||
1. Включите WebQuery на сервере TS и попросите уполномоченного администратора TS создать API-ключ. Укажите HTTP/HTTPS-адрес WebQuery и ключ. Это Query-служба TS, а не сайт WebSpeak. Поддерживаются TS3 начиная с 3.12 и TS6.
|
||||
2. ID виртуального сервера `0` выбирает сервер по голосовому порту фиксированной цели. Для ограниченного ключа укажите разрешённый ID. Ключ чтения позволяет просматривать данные; изменения требуют области с правом записи и соответствующих прав TS.
|
||||
3. Можно выбрать ServerQuery SSH или ServerQuery TCP для TS3. Укажите Query-хост (пустое поле использует фиксированную цель), порт, имя пользователя и пароль; SSH также требует доверенный отпечаток ключа хоста. Это не SSH-вход в операционную систему. TCP не шифруется и подходит только для доверенных сетей. HTTPS-сертификат должен быть доверенным для шлюза.
|
||||
4. Сохраните и подключитесь или обновите данные. Доступны настройки сервера, управление каналами, перемещение/исключение/блокировка участников, назначение групп и снятие блокировок. Действия требуют подтверждения и проверяются TS; списки обновляются вручную.
|
||||
|
||||
Учётные данные хранятся на сервере в зашифрованном виде и не возвращаются API. Сохраняйте базу данных вместе с `master.key`. Ошибка управления не влияет на панель WebSpeak и голос. Блокировка по UID не затрагивает других пользователей с общим IP шлюза.
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
@@ -114,7 +134,6 @@ docker compose up -d
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
@@ -124,7 +143,7 @@ npm start
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Node.js `>=22.12` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
|
||||
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
|
||||
@@ -216,9 +235,11 @@ npm start
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
|
||||
## Недавно объединённые вклады
|
||||
## Участники и вклад в проект
|
||||
|
||||
- Список составлен по записям о слиянии на GitHub; сводки выше описывают только изменения, вошедшие в соответствующий релиз.
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) улучшил переводы ошибок браузера; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) исправил масштабирование, плавающую компоновку и нижний колонтитул главной страницы.
|
||||
Список отмечает автора SDK, используемого в основе проекта, вклад через объединённые PR на GitHub и исходные работы, перенесённые в отдельно распространяемые пакеты скинов.
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — Автор SDK [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), который предоставляет используемый WebSpeak клиент протокола TeamSpeak.
|
||||
- [LainHE](https://github.com/LainHE) — [объединённые PR #2, #8, #28, #31–#35, #37, #38 и #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): переводы ошибок браузера, масштабирование и компоновка главной страницы, битрейт трансляции и аватары зрителей, проверка целей и восстановление ретранслятора, доверенные прокси, передача ошибок подключения, сообщения об ошибках аудио и освобождение ресурсов при сбоях WebRTC.
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak и сохранение имени цели в настройках, избранном и приглашениях.
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak с сохранением имени цели; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) улучшил сохранение рабочего пространства KAAK и повторное подключение после первого соединения. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) и [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) содержали исходный дизайн и реализацию скина Discord (автор коммитов **yumi**), которые проект WebSpeak перенёс в [отдельно распространяемый скин `.wskin`](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
|
||||
+40
-10
@@ -19,7 +19,7 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并根据服务器报告的版本自动探测协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
@@ -35,6 +35,26 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
|
||||
|
||||
## TeamSpeak 版本兼容性
|
||||
|
||||
语音连接使用标准 TeamSpeak 客户端协议,无需 Query 凭据。可选的 TS 管理功能使用独立的 WebQuery / ServerQuery 凭据。
|
||||
|
||||
- **TeamSpeak 3**:协议识别会读取版本号开头的 `3.x`。并非所有历史服务器版本都经过独立验证,部署旧版本时请针对实际服务器进行测试。
|
||||
- **TeamSpeak 6**:支持,也支持与 TeamSpeak 6 原生客户端进行屏幕共享。
|
||||
- **自动探测**:网关读取服务器的 `version` 响应并在连接诊断中记录识别到的协议。
|
||||
- 网关使用上游 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK;WebSpeak 面向 TeamSpeak 3 和 TeamSpeak 6。
|
||||
|
||||
## 可选的 TeamSpeak 管理
|
||||
|
||||
WebSpeak 后台和访客语音不依赖此功能。在固定服务器模式下,打开 `/admin/ts-admin`,可集中配置 TS 管理连接。
|
||||
|
||||
1. 在 TS 服务端启用 WebQuery,并由有权限的 TS 管理员创建 API Key。填写 WebQuery 的 HTTP/HTTPS 地址和 API Key;地址指向 TS Query 服务,而非 WebSpeak 网页。支持 TS3(3.12+)和 TS6。
|
||||
2. 虚拟服务器 ID 填 `0` 时,按固定目标的语音端口选择;受限 Key 应填写其被授权的服务器 ID。只读 Key 可查看,修改需要可写作用域及相应的 TS 权限。
|
||||
3. 也可选择 ServerQuery SSH 或 TS3 ServerQuery TCP,填写 Query 主机(留空沿用固定目标)、Query 端口、用户名和密码;SSH 还需要可信的主机密钥指纹。这是 TS 的 Query 服务,并非服务器操作系统的 SSH。TCP 不加密,仅适合可信网络;HTTPS 证书须受网关信任。
|
||||
4. 保存后连接或刷新,可查看服务器、频道、成员、服务器组和封禁,执行服务器设置、频道创建/重命名/删除、成员移动/移出/身份封禁、服务器组分配和解封。操作需确认,由 TS 核验权限;列表手动刷新。
|
||||
|
||||
凭据仅加密保存在服务端,接口不返回密码或 API Key;备份时同时保留数据库和 `master.key`。管理连接失败不影响 WebSpeak 后台和普通语音。封禁按 UID 创建,避免误封共用网关 IP 的其他用户。
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
@@ -98,7 +118,7 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
中继实例同时运行 UDP 兼容转发和独立语音网关,不提供访客首页或管理员后台。网关收到用户的入场请求后,会用共享令牌签名并转交一次性语音票据;浏览器随后直接连接中继节点,语音网关再从中继节点连接 TeamSpeak。网页地址仍保持在入口网关,不需要跳转。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
@@ -106,7 +126,6 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
|
||||
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' \
|
||||
@@ -152,10 +171,20 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
|
||||
放行中继主机的 UDP 监听端口,默认是 `39087`。
|
||||
|
||||
语音网关默认监听 `127.0.0.1:3041`。为中继节点配置 HTTPS 域名,并让 Caddy 等反向代理把该域名转发到 `127.0.0.1:3041`,例如:
|
||||
|
||||
```caddyfile
|
||||
relay.example.com {
|
||||
reverse_proxy 127.0.0.1:3041
|
||||
}
|
||||
```
|
||||
|
||||
管理员后台的中继节点设置中,将“语音网关地址”填写为该 HTTPS 源站(例如 `https://relay.example.com`)。网页仍从原入口网关加载,之后会通过 WSS 连接这个中继域名。语音网关默认启用 WebRTC;还需放行 UDP `40000-40099`,并设置 `WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST` 为可从用户网络直接访问的中继公网 IP 或直连域名。若修改了 WebRTC UDP 范围,同时更新防火墙规则。UDP `39087` 保留给旧版兼容转发。
|
||||
|
||||
#### 在网关中启用
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写自定义名称、地址(例如 `relay.example.com#39087`)和匹配令牌并保存。
|
||||
2. 为每个节点填写自定义名称、UDP 地址(例如 `relay.example.com#39087`)、HTTPS 语音网关源站(例如 `https://relay.example.com`)和匹配令牌并保存。
|
||||
3. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
@@ -266,7 +295,7 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.12+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
@@ -306,7 +335,6 @@ Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它
|
||||
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
|
||||
@@ -337,9 +365,11 @@ npm start
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
|
||||
## 近期合并贡献者
|
||||
## 贡献者与贡献来源
|
||||
|
||||
- 以下依据 GitHub 合并记录列出。
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
|
||||
以下列出上游 SDK 作者、已合并的 GitHub PR,以及已移植为独立皮肤包的原始贡献。
|
||||
|
||||
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
|
||||
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
|
||||
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
|
||||
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
|
||||
@@ -1,6 +1,6 @@
|
||||
# WebSpeak 0.2.7 皮肤系统开发指南
|
||||
# WebSpeak 0.2.8 皮肤系统开发指南
|
||||
|
||||
本文是 WebSpeak 0.2.7 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
|
||||
本文是 WebSpeak 0.2.8 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
|
||||
|
||||
## 目标:皮肤是可移植的外挂包
|
||||
|
||||
@@ -32,6 +32,58 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
### GitHub 皮肤商店分发
|
||||
|
||||
管理员在 `/admin/skins` 的“皮肤商店”页安装仓库分发的皮肤;“实例皮肤”页负责导入、启停、删除和设置默认值。安装和更新不改变默认皮肤,更新保留原启停状态。商店网络故障不会影响已安装皮肤。访客仍需自行批准皮肤组件权限,管理员安装不能替访客授权。
|
||||
|
||||
官方索引为 [Huddle-Up-Forge/webspeak-skins](https://github.com/Huddle-Up-Forge/webspeak-skins) 的 `master/index.json`。索引仅登记稳定的皮肤 ID 和公开 GitHub 仓库地址,不包含皮肤实现:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"skins": [{
|
||||
"id": "community.discord-voice",
|
||||
"repository": "https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
每个皮肤仓库的默认分支根目录提供 `skin.json`(位于 `.wskin` **之外**),例如:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.example-skin",
|
||||
"name": "Example skin",
|
||||
"version": "1.0.0",
|
||||
"author": "Example author",
|
||||
"license": "CC-BY-4.0",
|
||||
"description": "A portable WebSpeak skin.",
|
||||
"minAppVersion": "0.2.8",
|
||||
"package": {
|
||||
"ref": "v1.0.0",
|
||||
"path": "example.wskin",
|
||||
"sha256": "填写最终归档文件的 64 位小写 SHA-256"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、名称、版本、作者、许可证和最低应用版本一致。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
|
||||
|
||||
发布步骤:先构建并用客户端和服务端导入器验证最终归档;计算 SHA-256;提交源码、归档、许可证和 `skin.json`;为这个提交创建版本 tag;最后提交中央索引条目。后续更新只需在皮肤仓库发布新版本并更新默认分支的 `skin.json`,无需同步修改中央索引。安装时服务端重新检查索引及元数据,核对摘要并运行普通 `.wskin` 校验;校验失败不替换实例皮肤。同 ID 已安装且版本相同或更新时,不提供覆盖或降级操作。多个管理员同时修改实例皮肤时,过期的安装请求会被拒绝,需刷新后重试。
|
||||
|
||||
仓库地址限定为 `https://github.com/owner/repository`。索引最多 50 项;索引最大 128 KiB,单个 `skin.json` 最大 16 KiB,归档最大 20 MiB,下载有超时限制。商店不执行皮肤构建脚本,也不从仓库加载未打入归档的资源。
|
||||
|
||||
### 工作区接口 v1(WebSpeak 0.2.8 当前运行时)
|
||||
|
||||
v3/v4 开放皮肤可在 `manifest.json` 中声明 `"workspace": { "apiVersion": 1, "mode": "persistent" }`。未声明时保留原先的首页流程。该通用接口不识别皮肤 ID,也不授予额外网络或存储权限;皮肤包本身不能读写此偏好。旧运行时不认识该字段或权限时会拒绝导入,不能仅凭应用版本号认定支持;使用它的包需要 `minAppVersion: "0.2.8"` 及工作区接口 v1。
|
||||
|
||||
首次使用仍显示连接表单;只有成功连接才记录 `hasConnected`。旧的成功连接历史会迁移为已使用状态,只有昵称或失败尝试不算。启用此策略的皮肤在主动断开或刷新回访后仍进入工作区,但不会自动连接、采集麦克风或切换服务器。普通回访可由宿主恢复最近目标;显式邀请、目标或频道链接优先。切换到未声明策略的皮肤恢复其原有流程,清除本地数据会重置此记录。
|
||||
|
||||
可信控件 `voice.connection-status` 需要 `session.status.read` 与 `voice.connect`,显示本地化的连接/失败状态、可编辑昵称与重连按钮;忙碌时禁用重复提交,服务器密码和新增服务器对话框仍由宿主管理。公开部件为 `voice.connection-status`、`voice.connection-status.message`、`voice.connection-status.nickname`、`voice.connection-status.nickname.input`、`voice.connection-status.reconnect`。皮肤负责这些部件的位置、响应式布局和外观。
|
||||
|
||||
声明式动作 `voice.connect` 使用同名权限且不接受参数;它只在明确可信点击后连接宿主当前选定的目标,不能携带地址、密码、身份材料、邀请令牌或自动执行。服务器配置和身份未就绪、正在连接/重连、已经连接或对话框尚待处理时,宿主拒绝重复发起。它和既有的 `quickServers.switch`、服务器栏加号共用宿主连接流程;异步读取浏览器已保存密码不会被误判为连接失败。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
@@ -137,6 +189,10 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
|
||||
|
||||
申请 `session.channels.read` 的 `session.channels` 列表还提供 `memberCount`、两位数显示用的 `memberCountLabel`、`maxClients` 和 `maxClientsLimited`。后两个字段仅在 TeamSpeak 返回有效上限数据时出现;`maxClientsLimited: false` 表示频道不限人数。它们与频道树一起属于公开只读数据,不会授予服务器写入能力。
|
||||
|
||||
频道显示接口增补(0.2.8):同一权限下新增 `displayName`、`isSpacer`、`spacerAlignment` 与 `spacerStyle`,声明式 v3 和 Wasm v4 均可读取。`name` 始终保留服务器原名,`displayName` 仅对永久、顶层且名称以 `[spacer…]`、`[lspacer…]`、`[cspacer…]`、`[rspacer…]` 或 `[*spacer…]` 开头的频道移除前缀(大小写不敏感,省略或自定义标识均可)。分隔栏的 `spacerAlignment` 为 `left`、`center`、`right` 或 `repeat`;`spacerStyle` 为 `text`、`solid`、`dashed`、`dotted`、`dash-dot` 或 `dash-dot-dot`,五种线型对应 `___`、`---`、`...`、`-.-`、`-..`。普通频道的 `displayName` 等于 `name`、`isSpacer: false`、两个格式字段为空字符串。旧运行时可能不含新增字段;兼容包应回退到 `name`,不能只凭相同的 0.2.8 版本号推断字段存在。分隔栏仍为真实 TS 频道,不增加加入限制,不隐藏其中的成员或子频道;管理编辑继续使用原名。
|
||||
|
||||
宿主 `voice.channel-tree` 与 `voice.channel-panel` 自动使用上述显示规则;分隔栏隐藏普通频道图标和人数,不显示空成员提示。新增稳定部件 `voice.channel-spacer`,提供 `data-alignment` 与 `data-spacer-style` 属性;频道树行 `voice.channel-tree.row` 和成员面板标题 `voice.channel-group.heading` 在分隔栏上提供 `data-spacer="true"`。颜色和字体继承皮肤,文字及重复填充在可用宽度内裁剪,空文本保留分隔间距。皮肤无需新增权限或修改传输逻辑。
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Discord Voice skin
|
||||
|
||||
This example turns the Discord-inspired voice interface into a portable WebSpeak `open-skin` v3 package. Its page structure is declared in `components.json`; its palette and layout are in `skin.css`; localized skin copy lives in `content.json`.
|
||||
|
||||
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.11 requires WebSpeak 0.2.8 with the current public skin API.
|
||||
|
||||
The package uses WebSpeak's public TeamSpeak widgets for channel navigation, member cards, chat, audio controls, screen sharing, performance status, server switching and invite links. That keeps connection logic and trusted actions in WebSpeak while the skin controls the visible layout. The Discord visual language and color palette are retained, while host-owned controls keep their supported behavior and accessibility.
|
||||
|
||||
The skin requires explicit approval to replace the home and voice pages. It does not include JavaScript, depend on Vue internals, or change WebSpeak runtime code. It can be imported from `/admin/skins` as an ordinary `.wskin` package.
|
||||
|
||||
- Source: [discord-voice](./discord-voice/)
|
||||
- Package: [discord-voice.wskin](./discord-voice.wskin)
|
||||
- Format and runtime contract: [skin development guide](../SKIN_DEVELOPMENT.md)
|
||||
|
||||
Build the package from the repository root with:
|
||||
|
||||
```powershell
|
||||
node web/scripts/build-discord-voice-skin.mjs
|
||||
```
|
||||
|
||||
Native fullscreen and the bespoke screen-share settings shortcut from the built-in Vue version are not part of the current public skin API. The standard package keeps screen sharing reachable through WebSpeak's trusted screen-share controls and uses the standard audio settings panel.
|
||||
@@ -28,6 +28,12 @@ The existing WebSpeak noise-suppression switch is available in the audio setting
|
||||
|
||||
The owner authorized inspection of the first two voice rooms in the KOOK server. Both rooms were entered and viewed; the microphone remained off and no message was sent. The in-room view confirmed a single large participant tile in the center, a separate right-side panel for the active voice channel's text chat, a narrow server rail, grouped voice channels, and a compact voice-control dock near the lower left. The chat was empty, so no message contents were recorded. Server/room identifiers and member names were not recorded.
|
||||
|
||||
## Returning to the workspace
|
||||
|
||||
KAAK 3.1.127 requires WebSpeak 0.2.8 with workspace API v1. Its manifest opts into the generic persistent workspace policy: first-time visitors keep the connection home until a successful voice connection; returning visitors and disconnected users retain the workspace and server rail. Restoring the workspace never starts a connection or captures the microphone. The host restores the recent target only for ordinary visits, preserving explicit invitation and target links. Clearing browser data resets this history.
|
||||
|
||||
The permission-gated `voice.connection-status` host widget provides the connection state, nickname and explicit reconnect button beside server navigation at desktop and narrow widths. Open-mode server switching and adding servers reuse the host connection flow, including saved-password lookup and trusted password prompts; fixed mode retains its restrictions. All KAAK layout and styling remain in the package.
|
||||
|
||||
## Components and permissions
|
||||
|
||||
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. When a screen-share peer is active, the performance panel shows browser-side video codec and transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,451 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"components": [
|
||||
{
|
||||
"id": "discord-home",
|
||||
"name": "{{skin.messages.homeComponentName}}",
|
||||
"page": "home",
|
||||
"mode": "surface",
|
||||
"accessibleName": "{{skin.messages.homeAccessibleName}}",
|
||||
"permissions": ["ui.surface.replace", "session.status.read"],
|
||||
"actions": {},
|
||||
"root": {
|
||||
"tag": "main",
|
||||
"part": "home",
|
||||
"className": "join-page",
|
||||
"children": [
|
||||
{
|
||||
"tag": "header",
|
||||
"part": "home-header",
|
||||
"className": "join-header",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "brand-lockup",
|
||||
"children": [
|
||||
{ "tag": "span", "className": "dc-brand-mark", "children": [{ "text": "W" }] },
|
||||
{
|
||||
"tag": "div",
|
||||
"children": [
|
||||
{ "tag": "strong", "children": [{ "text": "WebSpeak" }] },
|
||||
{ "tag": "small", "children": [{ "text": "{{skin.messages.tagline}}" }] }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-header-tools",
|
||||
"className": "join-header-tools",
|
||||
"children": [
|
||||
{ "widget": "home.social-links", "part": "social-links" },
|
||||
{ "tag": "div", "className": "workspace-skin-switcher", "children": [{ "widget": "app.skin-switcher", "part": "skin-switcher" }] },
|
||||
{ "tag": "div", "className": "workspace-language", "children": [{ "widget": "app.language-switcher", "part": "language-switcher" }] }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "main",
|
||||
"part": "home-content",
|
||||
"className": "join-content",
|
||||
"children": [
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "home-hero",
|
||||
"className": "join-copy",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-hero-eyebrow",
|
||||
"className": "eyebrow",
|
||||
"children": [
|
||||
{ "tag": "span", "className": "eyebrow-dot" },
|
||||
{ "text": "{{skin.messages.eyebrow}}" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "h1",
|
||||
"part": "home-hero-title",
|
||||
"children": [
|
||||
{ "text": "{{skin.messages.heroTitle}}" },
|
||||
{ "tag": "em", "children": [{ "text": "{{skin.messages.heroAccent}}" }] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "p",
|
||||
"part": "home-hero-description",
|
||||
"className": "join-description",
|
||||
"children": [{ "text": "{{skin.messages.heroDescription}}" }]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-features",
|
||||
"className": "promise-list",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-feature",
|
||||
"className": "promise-item",
|
||||
"children": [
|
||||
{ "tag": "span", "className": "promise-icon mint", "children": [{ "text": "01" }] },
|
||||
{ "tag": "span", "children": [
|
||||
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureOneTitle}}" }] },
|
||||
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureOneBody}}" }] }
|
||||
] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-feature",
|
||||
"className": "promise-item",
|
||||
"children": [
|
||||
{ "tag": "span", "className": "promise-icon sand", "children": [{ "text": "02" }] },
|
||||
{ "tag": "span", "children": [
|
||||
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureTwoTitle}}" }] },
|
||||
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureTwoBody}}" }] }
|
||||
] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "home-feature",
|
||||
"className": "promise-item",
|
||||
"children": [
|
||||
{ "tag": "span", "className": "promise-icon mint", "children": [{ "text": "03" }] },
|
||||
{ "tag": "span", "children": [
|
||||
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureThreeTitle}}" }] },
|
||||
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureThreeBody}}" }] }
|
||||
] }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "tag": "div", "className": "dc-visitor-slot", "children": [{ "widget": "home.visitor-count", "part": "visitor-count" }] },
|
||||
{ "tag": "div", "className": "announcement-wrap", "children": [{ "widget": "home.server-announcement", "part": "announcement" }] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "home-join-card",
|
||||
"className": "join-card",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "join-card-effects", "attributes": { "aria-hidden": "true" }, "children": [
|
||||
{ "tag": "span", "className": "join-card-waveform", "children": [
|
||||
{ "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }
|
||||
] },
|
||||
{ "tag": "span", "className": "join-card-sonar", "children": [{ "tag": "i" }, { "tag": "i" }, { "tag": "i" }] }
|
||||
] },
|
||||
{ "tag": "h2", "part": "home-join-title", "children": [{ "text": "{{skin.messages.connectTitle}}" }] },
|
||||
{ "tag": "p", "part": "home-join-description", "className": "card-lead", "children": [{ "text": "{{skin.messages.connectDescription}}" }] },
|
||||
{ "widget": "home.connection-status", "part": "connection-status" },
|
||||
{ "widget": "home.connection-form", "part": "connection-form" },
|
||||
{ "tag": "p", "part": "home-security-note", "className": "join-meta", "children": [{ "text": "{{skin.messages.securityNote}}" }] }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "footer",
|
||||
"part": "home-footer",
|
||||
"className": "join-footer",
|
||||
"children": [
|
||||
{ "tag": "span", "children": [{ "text": "WebSpeak" }] },
|
||||
{ "tag": "span", "className": "footer-separator", "children": [{ "text": "·" }] },
|
||||
{ "tag": "span", "children": [{ "text": "TeamSpeak" }] },
|
||||
{ "tag": "span", "className": "footer-spacer" },
|
||||
{ "tag": "span", "children": [{ "text": "{{skin.messages.footerNote}}" }] }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "discord-workspace",
|
||||
"name": "{{skin.messages.voiceComponentName}}",
|
||||
"page": "voice",
|
||||
"mode": "surface",
|
||||
"accessibleName": "{{skin.messages.voiceAccessibleName}}",
|
||||
"stateScope": "session.status.channelId",
|
||||
"permissions": [
|
||||
"ui.surface.replace",
|
||||
"session.status.read",
|
||||
"session.invite.copy",
|
||||
"session.channels.read",
|
||||
"session.members.read",
|
||||
"session.memberAvatars.read",
|
||||
"session.channel.join",
|
||||
"servers.quickList.read",
|
||||
"servers.quickList.switch",
|
||||
"chat.channel.read",
|
||||
"chat.channel.send",
|
||||
"audio.status.read",
|
||||
"audio.microphone.control",
|
||||
"audio.output.control",
|
||||
"audio.settings.open",
|
||||
"voice.disconnect",
|
||||
"voice.screenShare.status.read",
|
||||
"voice.screenShare.read",
|
||||
"voice.screenShare.control",
|
||||
"voice.whisper.status.read",
|
||||
"voice.whisper.control"
|
||||
],
|
||||
"actions": {
|
||||
"switch-server": { "type": "quickServers.switch", "args": { "quickServerId": "{{server.id}}" } },
|
||||
"copy-invite-link": { "type": "session.copyInviteLink", "args": {} },
|
||||
"stop-screen-share": { "type": "voice.stopScreenShare", "args": {} },
|
||||
"toggle-accompaniment": { "type": "audio.toggleAccompaniment", "args": {} },
|
||||
"open-audio-settings": { "type": "audio.openSettings", "args": {} },
|
||||
"toggle-chat": { "type": "ui.toggleState", "args": { "key": "chatopen" } }
|
||||
},
|
||||
"state": { "chatopen": true },
|
||||
"root": {
|
||||
"tag": "main",
|
||||
"part": "voice-shell",
|
||||
"className": "app-shell discord-app-shell",
|
||||
"children": [
|
||||
{
|
||||
"tag": "nav",
|
||||
"part": "server-rail",
|
||||
"className": "dc-rail",
|
||||
"attributes": { "aria-label": "{{skin.messages.serverRailLabel}}" },
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-rail-list",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "quick-server-item",
|
||||
"className": "dc-rail-item",
|
||||
"repeat": { "path": "servers.quickList", "as": "server" },
|
||||
"children": [
|
||||
{ "tag": "span", "className": "dc-rail-pill", "attributes": { "aria-hidden": "true" } },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "quick-server",
|
||||
"className": "dc-rail-icon dc-rail-server",
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-label": "{{skin.messages.switchServer}} {{server.label}}",
|
||||
"aria-pressed": "{{server.current}}",
|
||||
"aria-disabled": "{{server.switchRestricted}}",
|
||||
"title": "{{server.switchTitle}}"
|
||||
},
|
||||
"events": { "click": "switch-server" },
|
||||
"children": [{ "tag": "span", "className": "dc-rail-avatar", "children": [{ "text": "{{server.monogram}}" }] }]
|
||||
},
|
||||
{ "tag": "span", "className": "dc-rail-tooltip", "attributes": { "role": "tooltip" }, "children": [{ "tag": "strong", "children": [{ "text": "{{server.label}}" }] }] },
|
||||
{ "tag": "span", "className": "dc-rail-fav", "when": { "path": "server.favorite", "equals": true }, "attributes": { "aria-label": "{{skin.messages.favoriteServer}}" }, "children": [{ "text": "★" }] }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "aside",
|
||||
"part": "member-panel",
|
||||
"className": "dc-sidebar",
|
||||
"children": [
|
||||
{
|
||||
"tag": "header",
|
||||
"className": "dc-server-header",
|
||||
"children": [
|
||||
{ "tag": "strong", "children": [{ "text": "{{session.status.serverLabel}}" }] },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "invite-copy",
|
||||
"className": "dc-header-icon",
|
||||
"attributes": { "type": "button", "aria-label": "{{skin.messages.copyInvite}}", "title": "{{skin.messages.copyInvite}}" },
|
||||
"events": { "click": "copy-invite-link" },
|
||||
"children": [{ "text": "↗" }]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-sidebar-scroll",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-category", "children": [{ "text": "{{skin.messages.voiceChannels}}" }] },
|
||||
{ "tag": "div", "className": "dc-channel-list", "children": [{ "widget": "voice.channel-tree", "part": "channel-tree", "options": { "layout": "server-sidebar", "memberActions": true, "memberDragDrop": true } }] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "connected-status",
|
||||
"className": "dc-connected",
|
||||
"when": { "path": "session.status.connected", "equals": true },
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-connected-row",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-connected-copy", "children": [
|
||||
{ "tag": "strong", "children": [{ "text": "{{skin.messages.voiceConnected}}" }] },
|
||||
{ "tag": "small", "children": [{ "text": "{{session.status.channelName}}" }] }
|
||||
] },
|
||||
{ "tag": "div", "className": "dc-performance", "children": [{ "widget": "voice.performance-panel", "part": "performance-panel" }] }
|
||||
]
|
||||
},
|
||||
{ "tag": "div", "className": "dc-connected-actions", "children": [{ "widget": "voice.connection-controls", "part": "connection-controls" }] }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "audio-dock",
|
||||
"className": "dc-user-bar",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-user-info", "children": [
|
||||
{ "tag": "span", "className": "dc-user-avatar", "children": [{ "tag": "i", "children": [{ "text": "{{session.status.userName}}" }] }] },
|
||||
{ "tag": "span", "className": "dc-user-text", "children": [{ "tag": "strong", "children": [{ "text": "{{session.status.userName}}" }] }, { "tag": "small", "children": [{ "text": "{{skin.messages.online}}" }] }] }
|
||||
] },
|
||||
{ "tag": "div", "className": "dc-user-actions", "children": [
|
||||
{ "widget": "voice.audio-controls", "part": "audio-controls" },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "mobile-audio-settings",
|
||||
"className": "dc-mobile-audio-settings",
|
||||
"attributes": { "type": "button", "aria-label": "{{skin.messages.audioSettings}}", "title": "{{skin.messages.audioSettings}}" },
|
||||
"events": { "click": "open-audio-settings" },
|
||||
"children": [{
|
||||
"tag": "svg",
|
||||
"attributes": { "width": 20, "height": 20, "viewbox": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke-width": 1.8, "stroke-linecap": "round", "aria-hidden": "true" },
|
||||
"children": [
|
||||
{ "tag": "path", "attributes": { "d": "M4 6h4m4 0h8M4 12h8m4 0h4M4 18h2m4 0h10" } },
|
||||
{ "tag": "circle", "attributes": { "cx": 10, "cy": 6, "r": 2 } },
|
||||
{ "tag": "circle", "attributes": { "cx": 14, "cy": 12, "r": 2 } },
|
||||
{ "tag": "circle", "attributes": { "cx": 8, "cy": 18, "r": 2 } }
|
||||
]
|
||||
}]
|
||||
}
|
||||
] }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "section",
|
||||
"part": "workspace",
|
||||
"className": "dc-stage",
|
||||
"children": [
|
||||
{
|
||||
"tag": "header",
|
||||
"part": "voice-header",
|
||||
"className": "dc-stage-header",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-stage-title", "children": [{ "tag": "h2", "children": [{ "text": "{{session.status.channelName}}" }] }] },
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "header-actions",
|
||||
"className": "dc-stage-header-actions",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "workspace-skin-switcher", "children": [{ "widget": "app.skin-switcher", "part": "skin-switcher" }] },
|
||||
{ "tag": "div", "className": "workspace-language", "children": [{ "widget": "app.language-switcher", "part": "language-switcher" }] },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "chat-toggle",
|
||||
"className": "dc-stage-icon",
|
||||
"attributes": { "type": "button", "aria-expanded": "{{state.chatopen}}", "aria-label": "{{skin.messages.toggleChat}}", "title": "{{skin.messages.toggleChat}}" },
|
||||
"events": { "click": "toggle-chat" },
|
||||
"children": [{ "text": "#" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "tag": "div", "className": "dc-stage-notices" },
|
||||
{
|
||||
"tag": "div",
|
||||
"part": "voice-activity",
|
||||
"className": "dc-stage-canvas",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-stage-grid",
|
||||
"children": [
|
||||
{ "widget": "voice.screen-share-player", "part": "screen-share-player" },
|
||||
{ "widget": "voice.member-cards", "part": "member-cards", "options": { "screenShare": true, "memberActions": true } },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "invite-tile",
|
||||
"className": "dc-invite-tile",
|
||||
"attributes": { "type": "button", "aria-label": "{{skin.messages.invitePeople}}" },
|
||||
"events": { "click": "copy-invite-link" },
|
||||
"children": [{ "tag": "strong", "children": [{ "text": "{{skin.messages.invitePeople}}" }] }]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "widget": "voice.whisper-controls", "part": "whisper-controls" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "footer",
|
||||
"className": "dc-stage-controls",
|
||||
"attributes": { "aria-label": "{{skin.messages.voiceControls}}" },
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-stage-controls-side" },
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-stage-controls-main",
|
||||
"children": [
|
||||
{
|
||||
"tag": "div",
|
||||
"className": "dc-stage-pill",
|
||||
"children": [
|
||||
{ "widget": "voice.screen-share-start", "part": "screen-share-start", "when": { "path": "screenShare.status.active", "equals": false } },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "screen-share-stop",
|
||||
"className": "dc-stage-btn",
|
||||
"when": { "path": "screenShare.status.active", "equals": true },
|
||||
"attributes": { "type": "button", "aria-pressed": "true", "aria-label": "{{skin.messages.stopScreenShare}}", "title": "{{skin.messages.stopScreenShare}}" },
|
||||
"events": { "click": "stop-screen-share" },
|
||||
"children": [{ "text": "▣" }]
|
||||
},
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "accompaniment-toggle",
|
||||
"className": "dc-stage-btn",
|
||||
"attributes": { "type": "button", "aria-label": "{{skin.messages.toggleAccompaniment}}", "title": "{{skin.messages.toggleAccompaniment}}" },
|
||||
"events": { "click": "toggle-accompaniment" },
|
||||
"children": [{ "text": "♫" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "tag": "div", "className": "dc-stage-controls-side end" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "aside",
|
||||
"part": "chat-panel",
|
||||
"className": "dc-chat",
|
||||
"when": { "path": "state.chatopen", "equals": true },
|
||||
"children": [
|
||||
{
|
||||
"tag": "header",
|
||||
"className": "dc-chat-header",
|
||||
"children": [
|
||||
{ "tag": "div", "className": "dc-chat-title", "children": [{ "tag": "strong", "children": [{ "text": "{{session.status.channelName}}" }] }] },
|
||||
{
|
||||
"tag": "button",
|
||||
"part": "chat-close",
|
||||
"className": "dc-stage-icon",
|
||||
"attributes": { "type": "button", "aria-label": "{{skin.messages.closeChat}}", "title": "{{skin.messages.closeChat}}" },
|
||||
"events": { "click": "toggle-chat" },
|
||||
"children": [{ "text": "×" }]
|
||||
}
|
||||
]
|
||||
},
|
||||
{ "widget": "voice.chat-panel", "part": "chat", "className": "dc-chat-body" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"messages": {
|
||||
"homeComponentName": "Discord-style connection home",
|
||||
"homeAccessibleName": "Discord-style WebSpeak connection page",
|
||||
"voiceComponentName": "Discord-style voice workspace",
|
||||
"voiceAccessibleName": "Discord-style WebSpeak voice workspace",
|
||||
"tagline": "YOUR VOICE, EVERYWHERE.",
|
||||
"eyebrow": "VOICE, TOGETHER",
|
||||
"heroTitle": "Your people.",
|
||||
"heroAccent": "Your voice.",
|
||||
"heroDescription": "Join your TeamSpeak community from the browser, with the controls you already know.",
|
||||
"featureOneTitle": "No client install",
|
||||
"featureOneBody": "Connect directly from your browser.",
|
||||
"featureTwoTitle": "Low-latency voice",
|
||||
"featureTwoBody": "Use browser audio with your TeamSpeak server.",
|
||||
"featureThreeTitle": "One familiar space",
|
||||
"featureThreeBody": "Keep channels, members and chat together.",
|
||||
"connectTitle": "Connect to a TeamSpeak server",
|
||||
"connectDescription": "Enter a server address to join voice.",
|
||||
"securityNote": "Your connection and identity stay under WebSpeak's control.",
|
||||
"footerNote": "Voice in your browser",
|
||||
"serverRailLabel": "Saved and recent servers",
|
||||
"switchServer": "Switch to",
|
||||
"favoriteServer": "Saved server",
|
||||
"copyInvite": "Copy invite link",
|
||||
"voiceChannels": "VOICE CHANNELS",
|
||||
"voiceConnected": "VOICE CONNECTED",
|
||||
"online": "Online",
|
||||
"audioSettings": "Audio settings",
|
||||
"toggleChat": "Toggle channel chat",
|
||||
"invitePeople": "Invite people",
|
||||
"closeChat": "Close chat",
|
||||
"voiceControls": "Voice controls",
|
||||
"stopScreenShare": "Stop screen sharing",
|
||||
"toggleAccompaniment": "Toggle accompaniment"
|
||||
}
|
||||
},
|
||||
"zh-CN": {
|
||||
"messages": {
|
||||
"homeComponentName": "Discord 风格连接首页",
|
||||
"homeAccessibleName": "Discord 风格 WebSpeak 连接页",
|
||||
"voiceComponentName": "Discord 风格语音工作区",
|
||||
"voiceAccessibleName": "Discord 风格 WebSpeak 语音工作区",
|
||||
"tagline": "你的声音,随时随地。",
|
||||
"eyebrow": "一起语音",
|
||||
"heroTitle": "和熟悉的人,",
|
||||
"heroAccent": "畅快交流。",
|
||||
"heroDescription": "在浏览器中加入你的 TeamSpeak 社区,使用熟悉的语音控制。",
|
||||
"featureOneTitle": "无需安装客户端",
|
||||
"featureOneBody": "直接从浏览器连接。",
|
||||
"featureTwoTitle": "低延迟语音",
|
||||
"featureTwoBody": "通过浏览器连接 TeamSpeak 服务器。",
|
||||
"featureThreeTitle": "熟悉的语音空间",
|
||||
"featureThreeBody": "频道、成员和聊天一目了然。",
|
||||
"connectTitle": "连接 TeamSpeak 服务器",
|
||||
"connectDescription": "填写服务器地址即可加入语音。",
|
||||
"securityNote": "连接和身份信息由 WebSpeak 安全管理。",
|
||||
"footerNote": "在浏览器中语音聊天",
|
||||
"serverRailLabel": "收藏和最近连接的服务器",
|
||||
"switchServer": "切换到",
|
||||
"favoriteServer": "已收藏的服务器",
|
||||
"copyInvite": "复制邀请链接",
|
||||
"voiceChannels": "语音频道",
|
||||
"voiceConnected": "语音已连接",
|
||||
"online": "在线",
|
||||
"audioSettings": "音频设置",
|
||||
"toggleChat": "打开或关闭频道聊天",
|
||||
"invitePeople": "邀请成员",
|
||||
"closeChat": "关闭聊天",
|
||||
"voiceControls": "语音控制",
|
||||
"stopScreenShare": "停止屏幕共享",
|
||||
"toggleAccompaniment": "切换伴奏"
|
||||
}
|
||||
},
|
||||
"de": {
|
||||
"messages": {
|
||||
"homeComponentName": "Discord-inspirierte Verbindungsseite",
|
||||
"homeAccessibleName": "Discord-inspirierte WebSpeak-Verbindungsseite",
|
||||
"voiceComponentName": "Discord-inspirierter Sprachbereich",
|
||||
"voiceAccessibleName": "Discord-inspirierter WebSpeak-Sprachbereich",
|
||||
"tagline": "DEINE STIMME, ÜBERALL.",
|
||||
"eyebrow": "ZUSAMMEN SPRECHEN",
|
||||
"heroTitle": "Deine Leute.",
|
||||
"heroAccent": "Deine Stimme.",
|
||||
"heroDescription": "Tritt deiner TeamSpeak-Community direkt im Browser bei.",
|
||||
"featureOneTitle": "Keine Installation",
|
||||
"featureOneBody": "Verbinde dich direkt im Browser.",
|
||||
"featureTwoTitle": "Sprachkommunikation mit geringer Latenz",
|
||||
"featureTwoBody": "Nutze Browser-Audio mit deinem TeamSpeak-Server.",
|
||||
"featureThreeTitle": "Ein vertrauter Bereich",
|
||||
"featureThreeBody": "Kanäle, Mitglieder und Chat an einem Ort.",
|
||||
"connectTitle": "Mit einem TeamSpeak-Server verbinden",
|
||||
"connectDescription": "Gib die Serveradresse ein, um beizutreten.",
|
||||
"securityNote": "WebSpeak schützt deine Verbindung und Identität.",
|
||||
"footerNote": "Sprache im Browser",
|
||||
"serverRailLabel": "Gespeicherte und zuletzt verwendete Server",
|
||||
"switchServer": "Wechseln zu",
|
||||
"favoriteServer": "Gespeicherter Server",
|
||||
"copyInvite": "Einladungslink kopieren",
|
||||
"voiceChannels": "SPRACHKANÄLE",
|
||||
"voiceConnected": "SPRACHE VERBUNDEN",
|
||||
"online": "Online",
|
||||
"audioSettings": "Audioeinstellungen",
|
||||
"toggleChat": "Kanalchat umschalten",
|
||||
"invitePeople": "Mitglieder einladen",
|
||||
"closeChat": "Chat schließen",
|
||||
"voiceControls": "Sprachsteuerung",
|
||||
"stopScreenShare": "Bildschirmfreigabe beenden",
|
||||
"toggleAccompaniment": "Begleitung umschalten"
|
||||
}
|
||||
},
|
||||
"ru": {
|
||||
"messages": {
|
||||
"homeComponentName": "Главная WebSpeak в стиле Discord",
|
||||
"homeAccessibleName": "Страница подключения WebSpeak в стиле Discord",
|
||||
"voiceComponentName": "Голосовое пространство в стиле Discord",
|
||||
"voiceAccessibleName": "Голосовое пространство WebSpeak в стиле Discord",
|
||||
"tagline": "ТВОЙ ГОЛОС — ВЕЗДЕ.",
|
||||
"eyebrow": "ОБЩАЙТЕСЬ ВМЕСТЕ",
|
||||
"heroTitle": "Твои друзья.",
|
||||
"heroAccent": "Твой голос.",
|
||||
"heroDescription": "Подключайтесь к сообществу TeamSpeak прямо в браузере.",
|
||||
"featureOneTitle": "Без установки клиента",
|
||||
"featureOneBody": "Подключайтесь прямо из браузера.",
|
||||
"featureTwoTitle": "Голос с низкой задержкой",
|
||||
"featureTwoBody": "Используйте браузерное аудио с сервером TeamSpeak.",
|
||||
"featureThreeTitle": "Привычное пространство",
|
||||
"featureThreeBody": "Каналы, участники и чат в одном месте.",
|
||||
"connectTitle": "Подключиться к серверу TeamSpeak",
|
||||
"connectDescription": "Введите адрес сервера, чтобы подключиться.",
|
||||
"securityNote": "WebSpeak защищает подключение и данные личности.",
|
||||
"footerNote": "Голосовое общение в браузере",
|
||||
"serverRailLabel": "Избранные и недавние серверы",
|
||||
"switchServer": "Переключиться на",
|
||||
"favoriteServer": "Сохранённый сервер",
|
||||
"copyInvite": "Скопировать ссылку-приглашение",
|
||||
"voiceChannels": "ГОЛОСОВЫЕ КАНАЛЫ",
|
||||
"voiceConnected": "ГОЛОС ПОДКЛЮЧЁН",
|
||||
"online": "В сети",
|
||||
"audioSettings": "Настройки звука",
|
||||
"toggleChat": "Показать или скрыть чат канала",
|
||||
"invitePeople": "Пригласить участников",
|
||||
"closeChat": "Закрыть чат",
|
||||
"voiceControls": "Управление голосом",
|
||||
"stopScreenShare": "Остановить показ экрана",
|
||||
"toggleAccompaniment": "Переключить сопровождение"
|
||||
}
|
||||
},
|
||||
"ja": {
|
||||
"messages": {
|
||||
"homeComponentName": "Discord 風の接続ホーム",
|
||||
"homeAccessibleName": "Discord 風 WebSpeak 接続ページ",
|
||||
"voiceComponentName": "Discord 風のボイスワークスペース",
|
||||
"voiceAccessibleName": "Discord 風 WebSpeak ボイスワークスペース",
|
||||
"tagline": "あなたの声を、どこでも。",
|
||||
"eyebrow": "一緒にボイスチャット",
|
||||
"heroTitle": "仲間と、",
|
||||
"heroAccent": "声をつなごう。",
|
||||
"heroDescription": "ブラウザーから TeamSpeak コミュニティに参加できます。",
|
||||
"featureOneTitle": "クライアント不要",
|
||||
"featureOneBody": "ブラウザーから直接接続。",
|
||||
"featureTwoTitle": "低遅延の音声",
|
||||
"featureTwoBody": "TeamSpeak サーバーでブラウザー音声を利用。",
|
||||
"featureThreeTitle": "使い慣れた空間",
|
||||
"featureThreeBody": "チャンネル、メンバー、チャットをまとめて表示。",
|
||||
"connectTitle": "TeamSpeak サーバーに接続",
|
||||
"connectDescription": "サーバーアドレスを入力して参加します。",
|
||||
"securityNote": "接続と ID 情報は WebSpeak が安全に管理します。",
|
||||
"footerNote": "ブラウザーでボイスチャット",
|
||||
"serverRailLabel": "保存済み・最近のサーバー",
|
||||
"switchServer": "切り替え先",
|
||||
"favoriteServer": "保存済みサーバー",
|
||||
"copyInvite": "招待リンクをコピー",
|
||||
"voiceChannels": "ボイスチャンネル",
|
||||
"voiceConnected": "ボイス接続中",
|
||||
"online": "オンライン",
|
||||
"audioSettings": "音声設定",
|
||||
"toggleChat": "チャンネルチャットの表示切替",
|
||||
"invitePeople": "メンバーを招待",
|
||||
"closeChat": "チャットを閉じる",
|
||||
"voiceControls": "ボイスコントロール",
|
||||
"stopScreenShare": "画面共有を停止",
|
||||
"toggleAccompaniment": "伴奏を切り替え"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schemaVersion": 3,
|
||||
"packageType": "open-skin",
|
||||
"id": "community.discord-voice",
|
||||
"name": "Discord Voice",
|
||||
"version": "1.0.11",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A Discord-inspired dark voice workspace built with WebSpeak's portable open-skin interface.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.8"
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -395,6 +395,7 @@
|
||||
"audio.microphone.control",
|
||||
"audio.output.control",
|
||||
"audio.settings.open",
|
||||
"voice.connect",
|
||||
"voice.disconnect",
|
||||
"voice.screenShare.status.read",
|
||||
"voice.screenShare.read",
|
||||
@@ -501,7 +502,8 @@
|
||||
"attributes": {
|
||||
"type": "button",
|
||||
"aria-current": "{{server.current}}",
|
||||
"aria-label": "切换到 {{server.label}}"
|
||||
"aria-label": "{{server.switchTitle}}",
|
||||
"title": "{{server.switchTitle}}"
|
||||
},
|
||||
"events": {
|
||||
"click": "switch-server"
|
||||
@@ -579,6 +581,10 @@
|
||||
{
|
||||
"widget": "app.language-switcher",
|
||||
"part": "rail-language"
|
||||
},
|
||||
{
|
||||
"widget": "home.social-links",
|
||||
"part": "rail-links"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -862,6 +868,10 @@
|
||||
"widget": "voice.server-banner",
|
||||
"part": "server-banner"
|
||||
},
|
||||
{
|
||||
"widget": "voice.connection-status",
|
||||
"part": "connection-status"
|
||||
},
|
||||
{
|
||||
"tag": "nav",
|
||||
"part": "channel-list",
|
||||
|
||||
@@ -61,7 +61,11 @@
|
||||
"kaakScreenShare": "屏幕共享",
|
||||
"kaakLeaveVoice": "退出",
|
||||
"kaakCurrentIdentity": "当前 TeamSpeak 身份",
|
||||
"kaakOnline": "在线"
|
||||
"kaakOnline": "在线",
|
||||
"githubRepository": "Webspeak项目Github",
|
||||
"qqGroup": "WebSpeak项目QQ群",
|
||||
"adminConsole": "管理控制台",
|
||||
"communityLinks": "社区与管理入口"
|
||||
}
|
||||
},
|
||||
"en": {
|
||||
@@ -124,7 +128,11 @@
|
||||
"kaakScreenShare": "Screen share",
|
||||
"kaakLeaveVoice": "Leave",
|
||||
"kaakCurrentIdentity": "Current TeamSpeak identity",
|
||||
"kaakOnline": "Online"
|
||||
"kaakOnline": "Online",
|
||||
"githubRepository": "WebSpeak project GitHub",
|
||||
"qqGroup": "WebSpeak project QQ group",
|
||||
"adminConsole": "Admin console",
|
||||
"communityLinks": "Community and administration"
|
||||
}
|
||||
},
|
||||
"de": {
|
||||
@@ -187,7 +195,11 @@
|
||||
"kaakScreenShare": "Bildschirm teilen",
|
||||
"kaakLeaveVoice": "Verlassen",
|
||||
"kaakCurrentIdentity": "Aktuelle TeamSpeak-Identität",
|
||||
"kaakOnline": "Online"
|
||||
"kaakOnline": "Online",
|
||||
"githubRepository": "GitHub-Repository des WebSpeak-Projekts",
|
||||
"qqGroup": "QQ-Gruppe des WebSpeak-Projekts",
|
||||
"adminConsole": "Administrationskonsole",
|
||||
"communityLinks": "Community und Verwaltung"
|
||||
}
|
||||
},
|
||||
"ru": {
|
||||
@@ -250,7 +262,11 @@
|
||||
"kaakScreenShare": "Демонстрация экрана",
|
||||
"kaakLeaveVoice": "Выйти",
|
||||
"kaakCurrentIdentity": "Текущая личность TeamSpeak",
|
||||
"kaakOnline": "В сети"
|
||||
"kaakOnline": "В сети",
|
||||
"githubRepository": "GitHub проекта WebSpeak",
|
||||
"qqGroup": "Группа QQ проекта WebSpeak",
|
||||
"adminConsole": "Панель администратора",
|
||||
"communityLinks": "Сообщество и управление"
|
||||
}
|
||||
},
|
||||
"ja": {
|
||||
@@ -313,7 +329,11 @@
|
||||
"kaakScreenShare": "画面共有",
|
||||
"kaakLeaveVoice": "退出",
|
||||
"kaakCurrentIdentity": "現在の TeamSpeak ID",
|
||||
"kaakOnline": "オンライン"
|
||||
"kaakOnline": "オンライン",
|
||||
"githubRepository": "WebSpeak プロジェクトの GitHub",
|
||||
"qqGroup": "WebSpeak プロジェクトの QQ グループ",
|
||||
"adminConsole": "管理コンソール",
|
||||
"communityLinks": "コミュニティと管理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,16 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.kaak-voice",
|
||||
"name": "KAAK",
|
||||
"version": "3.1.121",
|
||||
"version": "3.1.127",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "AGPL-3.0-only",
|
||||
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
|
||||
"entry": "skin.css",
|
||||
"components": "components.json",
|
||||
"content": "content.json",
|
||||
"minAppVersion": "0.2.7"
|
||||
"minAppVersion": "0.2.8",
|
||||
"workspace": {
|
||||
"apiVersion": 1,
|
||||
"mode": "persistent"
|
||||
}
|
||||
}
|
||||
@@ -577,7 +577,9 @@
|
||||
grid-template-columns: 86px 304px minmax(280px, 1fr) minmax(340px, min(38vw, 520px));
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
width: 100%;
|
||||
height: 100dvh;
|
||||
/* The app zooms on large displays; keep this surface within the real viewport. */
|
||||
height: calc(var(--ws-viewport-height, 100dvh) / var(--ui-scale, 1));
|
||||
max-height: calc(var(--ws-viewport-height, 100dvh) / var(--ui-scale, 1));
|
||||
min-height: 560px;
|
||||
overflow: hidden;
|
||||
color: var(--skin-kaak-text);
|
||||
@@ -4565,3 +4567,139 @@
|
||||
inset-inline-start: 70px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Workspace API v1: reconnect stays beside server navigation on every width. */
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] {
|
||||
flex: 0 0 auto;
|
||||
min-width: 0;
|
||||
margin: 10px 8px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"]:not(:has([data-ws-part="voice.connection-status"])) { display: none; }
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status"] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--skin-kaak-border);
|
||||
border-radius: 12px;
|
||||
color: var(--skin-kaak-text);
|
||||
background: var(--skin-kaak-raised);
|
||||
box-shadow: none;
|
||||
font-family: var(--skin-kaak-font);
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status.message"] {
|
||||
flex: 0 0 auto;
|
||||
margin: 0;
|
||||
color: var(--skin-kaak-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-state="failed"] [data-ws-part="voice.connection-status.message"] { color: #ffaaaa; }
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status.nickname"] {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
color: var(--skin-kaak-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 44px;
|
||||
padding: 9px 10px;
|
||||
border: 1px solid #4b4e55;
|
||||
border-radius: 7px;
|
||||
color: var(--skin-kaak-text);
|
||||
background: var(--skin-kaak-panel);
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] button {
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
min-height: 44px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 7px;
|
||||
color: #152000;
|
||||
background: var(--skin-kaak-accent);
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] button:hover:not(:disabled) { background: var(--skin-kaak-accent-hover); }
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] input:focus-visible,
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] button:focus-visible { outline: 2px solid #a8ed50; outline-offset: 3px; }
|
||||
@media (max-width: 820px) {
|
||||
[data-ws-plugin-part="kaak-workspace.connection-status"] { margin: 10px 4px; }
|
||||
}
|
||||
|
||||
/* Shared public links: management follows Add; community links finish the rail. */
|
||||
[data-ws-plugin-part="kaak-workspace.server-rail"] {
|
||||
gap: 10px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.server-list"] { min-height: 58px; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"],
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] [data-ws-part="home.social-links"] { display: contents; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a {
|
||||
position: relative;
|
||||
display: grid;
|
||||
flex: 0 0 44px;
|
||||
place-items: center;
|
||||
box-sizing: border-box;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 14px;
|
||||
color: #b7bbc4;
|
||||
background: transparent;
|
||||
text-decoration: none;
|
||||
transition: color .15s ease, background-color .15s ease, border-color .15s ease;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a .ui-icon { display: block; width: 22px; height: 22px; flex: 0 0 auto; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href="/admin"] {
|
||||
order: 3;
|
||||
flex-basis: 58px;
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
border-color: #3d4048;
|
||||
border-radius: 18px;
|
||||
color: #d1d5dc;
|
||||
background: var(--skin-kaak-rail-item-bg);
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] { order: 4; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] { order: 5; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href*="github.com/"] { order: 6; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href*="qm.qq.com/"] { order: 7; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a:hover,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a:focus-visible {
|
||||
border-color: #699b32;
|
||||
color: #a8ed50;
|
||||
background: #2b3524;
|
||||
}
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a:focus-visible { outline: 2px solid #a8ed50; outline-offset: 3px; }
|
||||
@media (max-height: 620px) {
|
||||
[data-ws-plugin-part="kaak-workspace.server-rail"] { gap: 8px; padding-top: 10px; padding-bottom: max(82px, env(safe-area-inset-bottom)); }
|
||||
[data-ws-plugin-part="kaak-workspace.server-add"],
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href="/admin"],
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"],
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] { flex: 0 0 44px; width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-trigger,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-switcher,
|
||||
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-plugin-part="kaak-workspace.rail-links"] a { transition: none; }
|
||||
}
|
||||
+2
-3
@@ -6,11 +6,10 @@ The Android app packages the Vue client with a small local gateway. Capacitor st
|
||||
|
||||
Use a short checkout path such as `C:\src\webspeak`. The Node.js plugin's CMake/Ninja object paths can exceed the Windows toolchain limit in deeply nested workspaces. A clean build in a nested validation directory failed with CMake's 250-character object-path warning and a Ninja `mkdir` error; the same source and dependencies built successfully from a shorter path. Changing application code or the embedded runtime is not required for this build-host issue.
|
||||
|
||||
Use the server development Node.js version (22.5 or newer) on the build host. Install all three dependency sets, then prepare and sync the Android project:
|
||||
Use Node.js 22.12 or newer on the build host. Install all three dependency sets, then prepare and sync the Android project:
|
||||
|
||||
```powershell
|
||||
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
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
@@ -34,5 +33,5 @@ Gradle writes one APK per supported CPU architecture under `web/android/app/buil
|
||||
- The local gateway serves the join page, public configuration, skin package, join-ticket endpoint, and voice WebSocket bridge.
|
||||
- The admin console and server-side skin management are not available in the Android package.
|
||||
- Mobile audio encoding uses the JavaScript/WASM Opus codec. The normal server build continues to use the native Opus codec.
|
||||
- The embedded runtime supplied by the current Capacitor Node.js plugin is Node.js 18.20.4. The gateway, identity parsing, and Opus encode/decode paths have been smoke-checked on that runtime. The TeamSpeak SDK declares Node.js 20.19 or newer, so real TeamSpeak connectivity and two-way audio remain unverified on Android; the APKs are for sideload testing.
|
||||
- The embedded runtime supplied by the current Capacitor Node.js plugin is Node.js 18.20.4. The gateway, identity parsing, and Opus encode/decode paths have been smoke-checked on that runtime. The upstream TeamSpeak SDK 1.0 declares Node.js 22.12 or newer, so real TeamSpeak connectivity and two-way audio remain unverified on Android; the APKs are for sideload testing.
|
||||
- Android WebView on the tested emulator does not expose `getDisplayMedia`; screen sharing needs a native MediaProjection integration. A persistent Android foreground service and real-device background audio behavior also remain to be implemented and verified.
|
||||
Generated
+21
-13
@@ -8,7 +8,7 @@
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
@@ -16,18 +16,6 @@
|
||||
"ws": "^8.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+ssh://git@github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"integrity": "sha512-Ho5yY60McMzI8lQd/DOYudEhzjxpN7cf0JniFR046IPeKybCIeF0TMyrxajHGqyAACR/nMVHuPLnosaYTEbJDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
}
|
||||
},
|
||||
"node_modules/@fidm/asn1": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",
|
||||
@@ -50,6 +38,26 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.19",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.19.tgz",
|
||||
"integrity": "sha512-5srWgwbcMx1j4JpwYonxKkOYla8hx7ojX+dYOC0hiv5NCjozMRsy8aIYzwSpzHr2y3q/aKljnPyM426DTRekrA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ssh2": "^1.17.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ssh2": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@leichtgewicht/ip-codec": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
"dependencies": {
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
|
||||
Generated
+95
-13
@@ -10,12 +10,13 @@
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"ssh2": "^1.17.0",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
@@ -27,7 +28,7 @@
|
||||
"typescript": "^6.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.5.0"
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@discordjs/node-pre-gyp": {
|
||||
@@ -64,17 +65,6 @@
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.5",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -539,6 +529,26 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.19",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.19.tgz",
|
||||
"integrity": "sha512-5srWgwbcMx1j4JpwYonxKkOYla8hx7ojX+dYOC0hiv5NCjozMRsy8aIYzwSpzHr2y3q/aKljnPyM426DTRekrA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ssh2": "^1.17.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ssh2": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/fs-minipass": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
|
||||
@@ -973,6 +983,15 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1": {
|
||||
"version": "0.2.6",
|
||||
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
||||
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": "~2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1js": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
|
||||
@@ -1022,6 +1041,21 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bcrypt-pbkdf": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
||||
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tweetnacl": "^0.14.3"
|
||||
}
|
||||
},
|
||||
"node_modules/bcrypt-pbkdf/node_modules/tweetnacl": {
|
||||
"version": "0.14.5",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
||||
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
@@ -1093,6 +1127,15 @@
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/buildcheck": {
|
||||
"version": "0.0.7",
|
||||
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
|
||||
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@@ -1201,6 +1244,20 @@
|
||||
"node": ">=6.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cpu-features": {
|
||||
"version": "0.0.10",
|
||||
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
|
||||
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"buildcheck": "~0.0.6",
|
||||
"nan": "^2.19.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cssesc": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
|
||||
@@ -1916,6 +1973,13 @@
|
||||
"multicast-dns": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/nan": {
|
||||
"version": "2.29.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.29.0.tgz",
|
||||
"integrity": "sha512-GlGk3HIvitbvs+LT3g6XUP1kpirKNvmDFwF/bmo6XNWSb/eYEs/O4bfgIEIXCZ+lIOTS5xNwDvSGMw6FJdAhtA==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.20",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||
@@ -2531,6 +2595,24 @@
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/ssh2": {
|
||||
"version": "1.17.0",
|
||||
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
|
||||
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
|
||||
"hasInstallScript": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"asn1": "^0.2.6",
|
||||
"bcrypt-pbkdf": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"cpu-features": "~0.0.10",
|
||||
"nan": "^2.23.0"
|
||||
}
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
|
||||
+4
-4
@@ -6,12 +6,12 @@
|
||||
"type": "module",
|
||||
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
|
||||
"engines": {
|
||||
"node": ">=22.5.0"
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
|
||||
"test": "node --import tsx --test web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
@@ -23,7 +23,6 @@
|
||||
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
|
||||
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
|
||||
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
@@ -31,12 +30,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.19",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"postcss": "^8.5.29",
|
||||
"postcss-selector-parser": "^7.1.6",
|
||||
"postcss-value-parser": "^4.2.0",
|
||||
"ssh2": "^1.17.0",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Client, generateIdentity } from "../../../teamspeak-js/dist/index.mjs";
|
||||
import { Client, generateIdentitySync } from "@honeybbq/teamspeak/client";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { parseEndpoint } from "./protocol.mjs";
|
||||
@@ -38,7 +38,7 @@ try {
|
||||
token,
|
||||
});
|
||||
|
||||
tsClient = new Client(generateIdentity(8), `127.0.0.1:${relayClient.localPort}`, "acceleration-sdk-smoke");
|
||||
tsClient = new Client(generateIdentitySync(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));
|
||||
|
||||
@@ -13,16 +13,12 @@ export function healthcheckUsesHttps(certDirectory = defaultCertDirectory) {
|
||||
}
|
||||
|
||||
export function runDockerHealthcheck({ mode = process.env.WEBSPEAK_MODE, certDirectory = defaultCertDirectory } = {}) {
|
||||
if (mode?.trim().toLowerCase() === "relay") {
|
||||
process.exitCode = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const secure = healthcheckUsesHttps(certDirectory);
|
||||
const relayMode = mode?.trim().toLowerCase() === "relay";
|
||||
const secure = !relayMode && healthcheckUsesHttps(certDirectory);
|
||||
const client = secure ? https : http;
|
||||
const request = client.get({
|
||||
hostname: "127.0.0.1",
|
||||
port: 3040,
|
||||
port: relayMode ? process.env.WEBSPEAK_VOICE_GATEWAY_PORT || 3041 : 3040,
|
||||
path: "/health",
|
||||
...(secure ? { rejectUnauthorized: false } : {}),
|
||||
}, (response) => {
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "AdminInputError";
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
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, type RelayNodeInput } from "./admin-service.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput, type TsAdminSettingsInput } 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";
|
||||
import { SkinStore } from "./skin-store.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
@@ -36,6 +37,7 @@ export interface AdminRouterOptions {
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
skinRegistry?: SkinRegistry;
|
||||
skinStore?: SkinStore;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -43,6 +45,21 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
const router = Router();
|
||||
const limiter = new AdminLoginRateLimiter();
|
||||
const logger = options.logger.child({ component: "admin-api" });
|
||||
const skinStore = options.skinStore ?? new SkinStore(options.version ?? "0.0.0");
|
||||
// Include uploads, enable/default changes and deletion in the same queue as store installs.
|
||||
let skinMutation: Promise<unknown> = Promise.resolve();
|
||||
function mutateSkins<T>(run: () => Promise<T>): Promise<T> {
|
||||
const next = skinMutation.then(run, run);
|
||||
skinMutation = next.catch(() => undefined);
|
||||
return next;
|
||||
}
|
||||
function sendStoreError(response: Response, error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_STORE_UNAVAILABLE" ? 502 : error.code === "SKIN_STORE_NOT_FOUND" ? 404
|
||||
: ["SKIN_STORE_CHANGED", "SKIN_STORE_INSTALLED_CHANGED", "SKIN_STORE_NOT_NEWER", "SKIN_STORE_INCOMPATIBLE"].includes(error.code) ? 409 : 400;
|
||||
response.status(status).json({ ok: false, code: error.code });
|
||||
} else sendAdminError(response, error);
|
||||
}
|
||||
|
||||
router.use((_request, response, next) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
@@ -122,6 +139,32 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.get("/ts-admin/settings", (_request, response) => {
|
||||
response.json(options.service.getTsAdminSettings());
|
||||
});
|
||||
|
||||
router.put("/ts-admin/settings", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.saveTsAdminSettings(readTsAdminSettingsInput(asRecord(request.body)));
|
||||
response.json({ ok: true, settings: options.service.getTsAdminSettings() });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/ts-admin/overview", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
|
||||
try {
|
||||
response.json(await options.service.getTsAdminOverview());
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/ts-admin/action", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try { response.json(await options.service.runTsAdminAction(request.body)); }
|
||||
catch (error: unknown) { sendAdminError(response, error); }
|
||||
});
|
||||
|
||||
router.get("/skins", async (_request, response) => {
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
@@ -129,11 +172,32 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/skin-store", async (_request, response) => {
|
||||
try { response.json(await skinStore.list()); }
|
||||
catch (error) { sendStoreError(response, error); }
|
||||
});
|
||||
|
||||
router.post("/skin-store/refresh", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
|
||||
try { response.json(await skinStore.list(true)); }
|
||||
catch (error) { sendStoreError(response, error); }
|
||||
});
|
||||
|
||||
router.post("/skin-store/install", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const registry = options.skinRegistry;
|
||||
const skin = await mutateSkins(() => skinStore.install(registry, request.body));
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version, source: "github-store" });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error) { sendStoreError(response, error); }
|
||||
});
|
||||
|
||||
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);
|
||||
const registry = options.skinRegistry;
|
||||
const settings = await mutateSkins(() => registry.setDefaultSkin(id));
|
||||
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
@@ -149,7 +213,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
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);
|
||||
const registry = options.skinRegistry, enabled = body.enabled;
|
||||
const skin = await mutateSkins(() => registry.setEnabled(id, 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) {
|
||||
@@ -166,7 +231,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
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);
|
||||
const registry = options.skinRegistry, bytes = request.body;
|
||||
const skin = await mutateSkins(() => registry.save(bytes, id));
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error: unknown) {
|
||||
@@ -182,7 +248,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
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)) {
|
||||
const registry = options.skinRegistry;
|
||||
if (!registry || !await mutateSkins(() => registry.remove(id))) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
@@ -446,6 +513,7 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
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) : "",
|
||||
voiceEndpoint: typeof node.voiceEndpoint === "string" ? node.voiceEndpoint.slice(0, 300) : undefined,
|
||||
enabled: node.enabled === true,
|
||||
token: typeof node.token === "string" ? node.token.slice(0, 512) : undefined,
|
||||
tokenAction: readPasswordAction(node.tokenAction),
|
||||
@@ -479,6 +547,28 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
};
|
||||
}
|
||||
|
||||
function readTsAdminSettingsInput(body: Record<string, unknown>): TsAdminSettingsInput {
|
||||
if (typeof body.enabled !== "boolean") throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Expected enabled flag");
|
||||
if (body.transport !== undefined && !["web", "ssh", "tcp"].includes(String(body.transport))) throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Invalid transport");
|
||||
for (const key of ["apiKeyAction", "passwordAction"]) {
|
||||
if (body[key] !== undefined && !["keep", "replace", "remove"].includes(String(body[key]))) throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Invalid credential action");
|
||||
}
|
||||
return {
|
||||
enabled: body.enabled === true,
|
||||
transport: body.transport as TsAdminSettingsInput["transport"],
|
||||
queryHost: body.queryHost === undefined ? undefined : readString(body, "queryHost", 253),
|
||||
webQueryUrl: body.webQueryUrl === undefined ? undefined : readString(body, "webQueryUrl", 2048),
|
||||
apiKey: body.apiKey === undefined ? undefined : readString(body, "apiKey", 4096),
|
||||
apiKeyAction: readPasswordAction(body.apiKeyAction),
|
||||
serverId: body.serverId === undefined ? undefined : readOptionalNumber(body, "serverId", 0),
|
||||
queryPort: readOptionalNumber(body, "queryPort", 10022),
|
||||
username: readOptionalString(body, "username", 128),
|
||||
password: readOptionalString(body, "password", 1024),
|
||||
passwordAction: readPasswordAction(body.passwordAction),
|
||||
hostKeyFingerprint: readOptionalString(body, "hostKeyFingerprint", 128),
|
||||
};
|
||||
}
|
||||
|
||||
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
+49
-12
@@ -1,8 +1,9 @@
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import { isIP } from "node:net";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { loadConfig } from "../config.js";
|
||||
import { DEFAULT_TEAM_SPEAK_PORT, formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -18,6 +19,9 @@ 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";
|
||||
import { TsAdminService, type TsAdminQueryClientFactory } from "./ts-admin-service.js";
|
||||
import { AdminInputError } from "./admin-errors.js";
|
||||
export { AdminInputError } from "./admin-errors.js";
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: string;
|
||||
@@ -40,6 +44,7 @@ export interface ManagedInviteView {
|
||||
type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
private readonly tsAdmin: TsAdminService;
|
||||
constructor(
|
||||
readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
@@ -47,7 +52,13 @@ export class AdminService {
|
||||
private readonly legacyConfigPath: string,
|
||||
private readonly probe: ProbeFunction = probeTeamSpeak,
|
||||
private readonly version = "0.1.0",
|
||||
) {}
|
||||
tsAdminClientFactory?: TsAdminQueryClientFactory,
|
||||
) {
|
||||
this.tsAdmin = new TsAdminService(database, masterSecret, logger, () => {
|
||||
const settings = database.getSettings();
|
||||
return { mode: settings.accessMode, target: settings.tsTarget || formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }) };
|
||||
}, tsAdminClientFactory);
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
this.importLegacyConfigOnce();
|
||||
@@ -154,7 +165,7 @@ export class AdminService {
|
||||
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 });
|
||||
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token, voiceEndpoint: node.voiceEndpoint || defaultRelayVoiceEndpoint(node.host) });
|
||||
} 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");
|
||||
}
|
||||
@@ -172,6 +183,10 @@ export class AdminService {
|
||||
const settings = this.normalizeSettings(input, current, relayNodes);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort || current.tsTarget !== settings.tsTarget;
|
||||
this.database.updateSettings(settings);
|
||||
if (settings.accessMode === "open") {
|
||||
const tsAdmin = this.database.getTsAdminSettings();
|
||||
if (tsAdmin.enabled) this.database.updateTsAdminSettings({ ...tsAdmin, enabled: false });
|
||||
}
|
||||
if (relayNodes !== undefined) {
|
||||
this.database.replaceRelayNodes(relayNodes);
|
||||
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
|
||||
@@ -311,6 +326,11 @@ export class AdminService {
|
||||
return revoked;
|
||||
}
|
||||
|
||||
getTsAdminSettings() { return this.tsAdmin.settings(); }
|
||||
saveTsAdminSettings(input: TsAdminSettingsInput): void { this.tsAdmin.save(input); }
|
||||
getTsAdminOverview() { return this.tsAdmin.overview(); }
|
||||
runTsAdminAction(input: unknown) { return this.tsAdmin.action(input); }
|
||||
|
||||
getManagedInvite(token: string): { target: string; channel: string } | null {
|
||||
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
|
||||
const record = this.database.getManagedInvite(hashInviteToken(token));
|
||||
@@ -482,6 +502,8 @@ export class AdminService {
|
||||
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
|
||||
seen.add(id);
|
||||
const previous = current.get(id);
|
||||
const voiceEndpointInput = typeof input.voiceEndpoint === "string" ? input.voiceEndpoint.trim() : previous?.voiceEndpoint ?? "";
|
||||
const voiceEndpoint = normalizeRelayVoiceEndpoint(voiceEndpointInput, target.host);
|
||||
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
|
||||
let tokenEncrypted = previous?.tokenEncrypted ?? null;
|
||||
if (tokenAction === "remove") tokenEncrypted = null;
|
||||
@@ -498,6 +520,7 @@ export class AdminService {
|
||||
enabled: input.enabled === true,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
voiceEndpoint,
|
||||
tokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
@@ -513,12 +536,13 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
|
||||
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; voiceEndpoint: string; hasToken: boolean }> {
|
||||
return this.database.listRelayNodes().map((node) => ({
|
||||
id: node.id,
|
||||
name: node.name,
|
||||
enabled: node.enabled,
|
||||
target: formatRelayTarget(node.host, node.port),
|
||||
voiceEndpoint: node.voiceEndpoint || defaultRelayVoiceEndpoint(node.host),
|
||||
hasToken: Boolean(node.tokenEncrypted),
|
||||
}));
|
||||
}
|
||||
@@ -533,6 +557,7 @@ export class AdminService {
|
||||
enabled: settings.relayEnabled,
|
||||
host: settings.relayHost,
|
||||
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
|
||||
voiceEndpoint: defaultRelayVoiceEndpoint(settings.relayHost),
|
||||
tokenEncrypted: settings.relayTokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
@@ -630,13 +655,25 @@ function settingsTarget(settings: { tsHost: string; tsPort: number; tsTarget?: s
|
||||
return settings.tsTarget ?? formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort });
|
||||
}
|
||||
|
||||
function defaultRelayVoiceEndpoint(host: string): string {
|
||||
const formattedHost = isIP(host) === 6 ? `[${host}]` : host;
|
||||
return `https://${formattedHost}`;
|
||||
}
|
||||
|
||||
function normalizeRelayVoiceEndpoint(value: string, relayHost: string): string {
|
||||
const endpoint = value || defaultRelayVoiceEndpoint(relayHost);
|
||||
let parsed: URL;
|
||||
try { parsed = new URL(endpoint); }
|
||||
catch { throw new AdminInputError("INVALID_RELAY_VOICE_ENDPOINT", "Relay voice gateway address must be an HTTP(S) origin"); }
|
||||
const hostname = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
||||
const local = hostname === "localhost" || hostname === "::1" || hostname === "127.0.0.1" || hostname.startsWith("127.");
|
||||
if ((parsed.protocol !== "https:" && !(parsed.protocol === "http:" && local))
|
||||
|| parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
|
||||
throw new AdminInputError("INVALID_RELAY_VOICE_ENDPOINT", "Relay voice gateway must use HTTPS and contain only an origin");
|
||||
}
|
||||
return parsed.origin;
|
||||
}
|
||||
|
||||
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);
|
||||
this.name = "AdminInputError";
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../shared/skin-workspace.js";
|
||||
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
|
||||
import { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js";
|
||||
import { parseSkinLayoutJson } from "../shared/skin-layout.js";
|
||||
@@ -58,6 +59,7 @@ type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" |
|
||||
content?: string;
|
||||
components?: string;
|
||||
plugins?: string;
|
||||
workspace?: SkinWorkspacePolicy;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
@@ -214,7 +216,7 @@ async function writeAtomicJson(filename: string, value: unknown): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
|
||||
export 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));
|
||||
@@ -472,7 +474,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion >= 2) {
|
||||
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
|
||||
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); }
|
||||
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); }
|
||||
if (schemaVersion === 4) fields.add("plugins");
|
||||
const unknown = Object.keys(value).find((key) => !fields.has(key));
|
||||
if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
|
||||
@@ -482,6 +484,9 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
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();
|
||||
};
|
||||
let workspace: SkinWorkspacePolicy | undefined;
|
||||
try { workspace = parseSkinWorkspacePolicy(value.workspace, schemaVersion); }
|
||||
catch (error) { throw new SkinRegistryError(error instanceof Error ? error.message : "Invalid workspace policy.", "SKIN_MANIFEST_INVALID"); }
|
||||
const id = read("id", 80);
|
||||
if (!isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 2 && (value.packageType !== "layout-skin" || !Array.isArray(value.permissions) || value.permissions.length !== 0)) {
|
||||
@@ -507,7 +512,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
return { schemaVersion, ...(workspace ? { workspace } : {}), ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { SkinRegistry, SkinRegistryError, validateSkinArchive, isBuiltinSkinId } from "./skin-registry.js";
|
||||
import {
|
||||
SKIN_STORE_INDEX_URL, SKIN_STORE_REPOSITORY, compareSkinVersions, isSkinStoreVersion,
|
||||
type SkinStoreCatalog, type SkinStoreEntry, type SkinStoreMetadata, type SkinStoreInstallInput,
|
||||
} from "../shared/skin-store.js";
|
||||
|
||||
const MAX_PACK_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_INDEX_BYTES = 128 * 1024;
|
||||
const MAX_METADATA_BYTES = 16 * 1024;
|
||||
const CACHE_MS = 5 * 60 * 1000;
|
||||
const ID = /^[a-z0-9][a-z0-9.-]{0,79}$/;
|
||||
const SHA = /^[a-f0-9]{64}$/;
|
||||
const fail = (code: string): never => { throw new SkinRegistryError(code, code); };
|
||||
const record = (value: unknown): Record<string, unknown> => {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return fail("SKIN_STORE_INVALID");
|
||||
return value as Record<string, unknown>;
|
||||
};
|
||||
|
||||
export function skinRepository(value: unknown): string {
|
||||
if (typeof value !== "string" || !/^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/.test(value)
|
||||
|| value.endsWith("/.") || value.endsWith("/..") || value.endsWith(".git")) return fail("SKIN_STORE_INVALID");
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseIndex(value: unknown): { id: string; repository: string }[] {
|
||||
const root = record(value);
|
||||
if (root.schemaVersion !== 1 || !Array.isArray(root.skins) || root.skins.length > 50) return fail("SKIN_STORE_INVALID");
|
||||
const seen = new Set<string>();
|
||||
return root.skins.map(item => {
|
||||
const entry = record(item);
|
||||
if (typeof entry.id !== "string" || !ID.test(entry.id) || isBuiltinSkinId(entry.id) || entry.id.startsWith("builtin.") || seen.has(entry.id)) return fail("SKIN_STORE_INVALID");
|
||||
seen.add(entry.id);
|
||||
return { id: entry.id, repository: skinRepository(entry.repository) };
|
||||
});
|
||||
}
|
||||
|
||||
function parseMetadata(value: unknown, id: string): SkinStoreMetadata {
|
||||
const root = record(value), pack = record(root.package);
|
||||
const field = (key: string, max: number, empty = false): string => {
|
||||
const value = root[key];
|
||||
if (typeof value !== "string" || value.length > max || (!empty && !value.trim()) || /[\u0000-\u001f\u007f]/.test(value)) return fail("SKIN_STORE_INVALID");
|
||||
return value;
|
||||
};
|
||||
if (root.schemaVersion !== 1 || root.id !== id || !isSkinStoreVersion(root.version) || !isSkinStoreVersion(root.minAppVersion)
|
||||
|| typeof pack.ref !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(pack.ref)
|
||||
|| typeof pack.path !== "string" || !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.wskin$/.test(pack.path) || pack.path.length > 200
|
||||
|| typeof pack.sha256 !== "string" || !SHA.test(pack.sha256)) return fail("SKIN_STORE_INVALID");
|
||||
return { schemaVersion: 1, id, name: field("name", 80), author: field("author", 80), license: field("license", 80),
|
||||
description: field("description", 400, true), version: root.version, minAppVersion: root.minAppVersion,
|
||||
package: { ref: pack.ref, path: pack.path, sha256: pack.sha256 } };
|
||||
}
|
||||
|
||||
export class SkinStore {
|
||||
private cached: SkinStoreCatalog | null = null;
|
||||
private loading: Promise<SkinStoreCatalog> | null = null;
|
||||
constructor(private readonly appVersion: string, private readonly fetcher: typeof fetch = fetch) {}
|
||||
|
||||
/** No arbitrary URLs, redirects, credentials, or unbounded downloads enter the server. */
|
||||
private async download(url: string, limit: number): Promise<Buffer> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 20_000);
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.origin !== "https://raw.githubusercontent.com" || parsed.username || parsed.password) return fail("SKIN_STORE_INVALID");
|
||||
const response = await this.fetcher(url, { redirect: "error", signal: controller.signal, headers: { accept: "application/octet-stream" }, credentials: "omit" });
|
||||
if (!response.ok || !response.body) return fail("SKIN_STORE_UNAVAILABLE");
|
||||
const declared = response.headers.get("content-length");
|
||||
if (declared && Number(declared) > limit) { await response.body.cancel(); return fail("SKIN_STORE_TOO_LARGE"); }
|
||||
const reader = response.body.getReader(), chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
size += part.value.byteLength;
|
||||
if (size > limit) { await reader.cancel(); return fail("SKIN_STORE_TOO_LARGE"); }
|
||||
chunks.push(part.value);
|
||||
}
|
||||
} finally { reader.releaseLock(); }
|
||||
return Buffer.concat(chunks, size);
|
||||
} catch (error) {
|
||||
if (error instanceof SkinRegistryError) throw error;
|
||||
return fail("SKIN_STORE_UNAVAILABLE");
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
private async json(url: string, limit: number): Promise<unknown> {
|
||||
const bytes = await this.download(url, limit);
|
||||
try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
|
||||
catch { return fail("SKIN_STORE_INVALID"); }
|
||||
}
|
||||
private async entry(source: { id: string; repository: string }): Promise<SkinStoreEntry> {
|
||||
const metadata = parseMetadata(await this.json(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/HEAD/skin.json`, MAX_METADATA_BYTES), source.id);
|
||||
return { ...source, metadata, revision: createHash("sha256").update(JSON.stringify({ ...source, metadata })).digest("hex"),
|
||||
compatible: isSkinStoreVersion(this.appVersion) && compareSkinVersions(this.appVersion, metadata.minAppVersion) >= 0, error: null };
|
||||
}
|
||||
async list(refresh = false): Promise<SkinStoreCatalog> {
|
||||
if (this.loading) return this.loading;
|
||||
if (!refresh && this.cached && Date.now() - this.cached.fetchedAt < CACHE_MS) return this.cached;
|
||||
const pending = this.readCatalog();
|
||||
this.loading = pending;
|
||||
try { this.cached = await pending; return this.cached; }
|
||||
finally { this.loading = null; }
|
||||
}
|
||||
private async readCatalog(): Promise<SkinStoreCatalog> {
|
||||
const sources = parseIndex(await this.json(SKIN_STORE_INDEX_URL, MAX_INDEX_BYTES));
|
||||
const entries: SkinStoreEntry[] = new Array(sources.length);
|
||||
let cursor = 0;
|
||||
await Promise.all(Array.from({ length: Math.min(4, sources.length) }, async () => {
|
||||
while (cursor < sources.length) {
|
||||
const index = cursor++;
|
||||
try { entries[index] = await this.entry(sources[index]); }
|
||||
catch (error) { entries[index] = { ...sources[index], metadata: null, revision: "", compatible: false,
|
||||
error: error instanceof SkinRegistryError ? error.code : "SKIN_STORE_UNAVAILABLE" }; }
|
||||
}
|
||||
}));
|
||||
return { repository: SKIN_STORE_REPOSITORY, appVersion: this.appVersion, fetchedAt: Date.now(), entries };
|
||||
}
|
||||
/** Caller serializes this with all other registry mutations. */
|
||||
async install(registry: SkinRegistry, value: unknown) {
|
||||
const input = record(value) as unknown as SkinStoreInstallInput;
|
||||
if (typeof input.id !== "string" || !ID.test(input.id) || typeof input.revision !== "string" || !SHA.test(input.revision)
|
||||
|| !(input.installedVersion === null || isSkinStoreVersion(input.installedVersion))) return fail("SKIN_STORE_INVALID");
|
||||
const sources = parseIndex(await this.json(SKIN_STORE_INDEX_URL, MAX_INDEX_BYTES));
|
||||
const source = sources.find(entry => entry.id === input.id);
|
||||
if (!source) return fail("SKIN_STORE_NOT_FOUND");
|
||||
const entry = await this.entry(source);
|
||||
if (entry.revision !== input.revision) return fail("SKIN_STORE_CHANGED");
|
||||
if (!entry.compatible) return fail("SKIN_STORE_INCOMPATIBLE");
|
||||
const installed = (await registry.list()).find(item => item.id === input.id);
|
||||
if ((installed?.version ?? null) !== input.installedVersion) return fail("SKIN_STORE_INSTALLED_CHANGED");
|
||||
const metadata = entry.metadata!;
|
||||
if (installed && compareSkinVersions(metadata.version, installed.version) <= 0) return fail("SKIN_STORE_NOT_NEWER");
|
||||
const bytes = await this.download(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/${metadata.package.ref}/${metadata.package.path}`, MAX_PACK_BYTES);
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== metadata.package.sha256) return fail("SKIN_STORE_CHECKSUM");
|
||||
const { manifest } = validateSkinArchive(bytes, input.id);
|
||||
for (const key of ["id", "name", "version", "author", "license", "minAppVersion"] as const) {
|
||||
if (manifest[key] !== metadata[key]) return fail("SKIN_STORE_PACKAGE_MISMATCH");
|
||||
}
|
||||
return registry.save(bytes, input.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { createServer } from "node:http";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { QueryClient, type QueryClientOptions } from "@honeybbq/teamspeak/query";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { decryptSecret } from "../security/secret-crypto.js";
|
||||
import type { TsAdminAction } from "../shared/admin-inputs.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { TsAdminService } from "./ts-admin-service.js";
|
||||
import { webQueryFetch } from "./webquery-fetch.js";
|
||||
|
||||
const uid = "a-real-voice-identity=";
|
||||
const channel = { cid: "1", cpid: "0", channel_name: "Lobby", total_clients: "1", channel_flag_password: "0" };
|
||||
const member = { clid: "42", client_database_id: "77", client_unique_identifier: uid, client_nickname: "Guest", cid: "1", client_type: "0", client_servergroups: "6,7" };
|
||||
type Reply = { body: Record<string, string>[]; status: { code: number; message: string } };
|
||||
const ok = (body: Reply["body"] = []): Reply => ({ body, status: { code: 0, message: "ok" } });
|
||||
const denied = (): Reply => ({ body: [], status: { code: 2568, message: "insufficient permissions: secret-value-must-not-escape" } });
|
||||
function deferred() { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done; }); return { resolve, promise }; }
|
||||
const hasCode = (code: string) => (error: any) => error.code === code && error.message === code;
|
||||
|
||||
/** Real published QueryClient + WebQuery transport, with a disposable HTTP server. */
|
||||
async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
|
||||
const directory = mkdtempSync(join(tmpdir(), "webspeak-ts-admin-"));
|
||||
const database = new WebSpeakDatabase(join(directory, "test.sqlite"));
|
||||
const master = Buffer.alloc(32, 5), logs: unknown[] = [];
|
||||
const logger: Logger = { debug() {}, info() {}, error() {}, warn(...args: unknown[]) { logs.push(args); }, child() { return this; } };
|
||||
const policy = { mode: "fixed" as "fixed" | "open", target: "127.0.0.1:9987" };
|
||||
const calls: Array<{ path: string; command: string; params: Record<string, string>; key: string }> = [];
|
||||
const clients: QueryClient[] = [];
|
||||
const clientOptions: QueryClientOptions[] = [];
|
||||
let httpStatus = 200;
|
||||
let httpCommand: string | undefined;
|
||||
let jsonErrors = false;
|
||||
let reply: (command: string, params: Record<string, string>) => Reply | Promise<Reply> = command => {
|
||||
switch (command) {
|
||||
case "version": return ok([{ version: family === "ts3" ? "3.13.7" : "6.0.0-beta13" }]);
|
||||
case "whoami": return ok([{ client_id: "99" }]);
|
||||
case "serverinfo": return ok([{ virtualserver_name: "Test TeamSpeak", virtualserver_welcomemessage: "Welcome", virtualserver_maxclients: "32", virtualserver_uptime: "123" }]);
|
||||
case "channellist": return ok([channel]);
|
||||
case "clientlist": return ok([member]);
|
||||
case "servergrouplist": return ok([{ sgid: "6", name: "Member", type: "1" }, { sgid: "1", name: "Query template", type: "0" }]);
|
||||
case "banlist": return ok([{ banid: "8", uid, lastnickname: "Guest", reason: "Test", duration: "3600", created: "1700000000" }]);
|
||||
case "channelcreate": return ok([{ cid: "2" }]);
|
||||
case "banadd": return ok([{ banid: "9" }]);
|
||||
default: return ok();
|
||||
}
|
||||
};
|
||||
const server = createServer(async (req, res) => {
|
||||
let body = "";
|
||||
for await (const chunk of req) body += String(chunk);
|
||||
const path = req.url!, command = path.split("/").at(-1)!;
|
||||
const params = JSON.parse(body || "{}");
|
||||
calls.push({ path, command, params, key: String(req.headers["x-api-key"]) });
|
||||
const answer = await reply(command, params);
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.statusCode = httpCommand === undefined || httpCommand === command ? httpStatus : 200;
|
||||
res.end(res.statusCode === 200 || jsonErrors ? JSON.stringify(answer) : "Access denied");
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
const service = new TsAdminService(database, master, logger, () => policy, options => {
|
||||
clientOptions.push(options);
|
||||
const client = new QueryClient(options); clients.push(client); return client;
|
||||
});
|
||||
const settings = { enabled: true, transport: "web" as const, queryPort: 10022, queryHost: "", username: "", hostKeyFingerprint: "",
|
||||
webQueryUrl: `http://127.0.0.1:${address.port}/query`, serverId: 7, apiKey: "secret-local-fixture-api-key", apiKeyAction: "replace" as const };
|
||||
service.save(settings);
|
||||
t.after(async () => {
|
||||
await Promise.all(clients.map(client => client.disconnect()));
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
database.close(); rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
return { service, database, master, settings, calls, policy, logs, clientOptions,
|
||||
action: (operation: unknown) => service.action({ operation, configurationRevision: service.settings().configurationRevision }),
|
||||
set httpStatus(value: number) { httpStatus = value; },
|
||||
set httpCommand(value: string) { httpCommand = value; },
|
||||
set jsonErrors(value: boolean) { jsonErrors = value; },
|
||||
get reply() { return reply; }, set reply(value) { reply = value; } };
|
||||
}
|
||||
|
||||
for (const family of ["ts3", "ts6"] as const) test(`WebQuery ${family} selects the virtual server, parses typed data and sends no login or notifications`, async t => {
|
||||
const f = await fixture(t, family);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.serverFamily, family); assert.equal(result.serverName, "Test TeamSpeak");
|
||||
assert.equal(result.welcomeMessage, "Welcome"); assert.equal(result.maxClients, 32);
|
||||
assert.equal(result.channels[0].id, "1"); assert.equal(result.clients[0].uid, uid);
|
||||
assert.deepEqual(result.groups, [{ id: "6", name: "Member" }]);
|
||||
assert.equal(result.bans[0].durationSeconds, 3600);
|
||||
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/") && call.key === f.settings.apiKey));
|
||||
assert.ok(!f.calls.some(call => /login|notify|clientupdate/.test(call.command)));
|
||||
assert.equal(f.clientOptions[0].events, undefined, "WebQuery rejects even an explicit events:false option");
|
||||
assert.equal(f.clientOptions[0].reconnect, undefined);
|
||||
f.service.save({ ...f.settings, serverId: 0, apiKeyAction: "keep", apiKey: undefined });
|
||||
f.calls.length = 0;
|
||||
await f.service.overview();
|
||||
assert.ok(f.calls.every(call => call.path.startsWith("/query/byport/9987/")));
|
||||
});
|
||||
|
||||
test("Query credentials are encrypted separately, projected out, and keep/remove is explicit", async t => {
|
||||
const f = await fixture(t);
|
||||
f.service.save({ ...f.settings, passwordAction: "replace", password: "local-query-password" });
|
||||
const stored = f.database.getTsAdminSettings();
|
||||
assert.notEqual(stored.apiKeyEncrypted, f.settings.apiKey);
|
||||
assert.equal(decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-webquery-api-key:v1"), f.settings.apiKey);
|
||||
assert.equal(decryptSecret(stored.passwordEncrypted, f.master, "webspeak:ts-admin-query-password:v1"), "local-query-password");
|
||||
assert.throws(() => decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-query-password:v1"));
|
||||
const shown = f.service.settings();
|
||||
assert.equal(shown.hasApiKey, true); assert.equal(shown.hasPassword, true);
|
||||
assert.ok(!("apiKeyEncrypted" in shown) && !("passwordEncrypted" in shown));
|
||||
f.service.save({ ...f.settings, apiKey: "ignored", apiKeyAction: "keep" });
|
||||
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted);
|
||||
assert.throws(() => f.service.save({ ...f.settings, apiKeyAction: "remove" }), hasCode("INVALID_TS_ADMIN_API_KEY"));
|
||||
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted, "invalid settings must be atomic");
|
||||
f.service.save({ ...f.settings, enabled: false, apiKeyAction: "remove", passwordAction: "remove" });
|
||||
assert.equal(f.service.settings().hasApiKey, false);
|
||||
assert.equal(f.service.settings().hasPassword, false);
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_NOT_CONFIGURED"));
|
||||
assert.equal(f.calls.length, 0);
|
||||
});
|
||||
|
||||
test("invalid endpoints and selectors are rejected without changing stored settings", async t => {
|
||||
const f = await fixture(t), stored = f.database.getTsAdminSettings();
|
||||
for (const webQueryUrl of ["file:///etc/passwd", "https://user:password@example.com", "https://example.com?api_key=secret", "https://example.com/#fragment", "no-url"]) {
|
||||
assert.throws(() => f.service.save({ ...f.settings, webQueryUrl }), hasCode("INVALID_TS_ADMIN_URL"));
|
||||
}
|
||||
for (const serverId of [-1, 1.2, 4_294_967_296]) assert.throws(() => f.service.save({ ...f.settings, serverId }), hasCode("INVALID_TS_ADMIN_SERVER_ID"));
|
||||
assert.throws(() => f.service.save({ ...f.settings, queryHost: "host:10022" }), hasCode("INVALID_TS_ADMIN_HOST"));
|
||||
assert.deepEqual(f.database.getTsAdminSettings(), stored);
|
||||
f.policy.mode = "open";
|
||||
assert.throws(() => f.service.save(f.settings), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
|
||||
});
|
||||
|
||||
test("limited list permissions preserve the rest of the overview and error details stay private", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => ["servergrouplist", "banlist"].includes(command) ? denied() : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.bansAvailable, false);
|
||||
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED"); assert.equal(result.bansErrorCode, "TS_ADMIN_PERMISSION_DENIED");
|
||||
assert.equal(result.channels.length, 1); assert.equal(result.clients.length, 1);
|
||||
f.reply = (command, params) => command === "serverinfo" ? denied() : original(command, params);
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_PERMISSION_DENIED"));
|
||||
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
|
||||
assert.ok(!JSON.stringify(f.logs).includes(f.settings.apiKey));
|
||||
});
|
||||
|
||||
test("Query connections never appear in member lists or channel and server member counts", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => {
|
||||
if (command === "clientlist") return ok([member, { ...member, clid: "99", client_type: "1", client_nickname: "serveradmin" }]);
|
||||
if (command === "channellist") return ok([{ ...channel, total_clients: "2" }, { ...channel, cid: "2", channel_name: "Empty" }]);
|
||||
return original(command, params);
|
||||
};
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.clientCount, 1); assert.deepEqual(result.clients.map(entry => entry.id), [42]);
|
||||
assert.deepEqual(result.channels.map(entry => entry.totalClients), [1, 0]);
|
||||
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, clid: "99", client_type: "1" }]) : original(command, params);
|
||||
const empty = await f.service.overview();
|
||||
assert.equal(empty.clientCount, 0); assert.deepEqual(empty.clients, []); assert.equal(empty.channels[0].totalClients, 0);
|
||||
});
|
||||
|
||||
for (const [code, expected] of [[524, "TS_ADMIN_RATE_LIMITED"], [2568, "TS_ADMIN_PERMISSION_DENIED"], [1538, "TS_ADMIN_READ_FAILED"]] as const) {
|
||||
test(`optional list error ${code} retains its cause rather than inventing a permission failure`, async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => command === "servergrouplist" ? { body: [], status: { code, message: "private-error-detail" } } : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
|
||||
assert.equal(result.bansAvailable, true); assert.equal(result.bansErrorCode, null);
|
||||
assert.equal(result.clients.length, 1); assert.ok(!JSON.stringify(result).includes("private-error-detail"));
|
||||
});
|
||||
}
|
||||
|
||||
for (const state of ["disconnected", "reused-id"] as const) test(`a successful UID ban with ${state} does not kick another connection or report partial failure`, async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
let banned = false;
|
||||
f.reply = (command, params) => {
|
||||
if (command === "banadd") banned = true;
|
||||
if (command === "clientlist" && banned) return ok(state === "disconnected" ? [] : [{ ...member, client_unique_identifier: "replacement-identity=" }]);
|
||||
return original(command, params);
|
||||
};
|
||||
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
|
||||
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
|
||||
assert.ok(!f.calls.some(call => call.command === "clientkick"));
|
||||
assert.ok(!f.database.recentAudit(50).some(entry => entry.event === "TS_ADMIN_ACTION_PARTIAL"));
|
||||
});
|
||||
|
||||
test("a banned client leaving between the fresh identity check and kick is successful", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => command === "clientkick" ? { body: [], status: { code: 512, message: "invalid clientID" } } : original(command, params);
|
||||
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
|
||||
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
|
||||
});
|
||||
|
||||
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [408, "TS_ADMIN_TIMEOUT"], [504, "TS_ADMIN_TIMEOUT"]] as const) test(`HTTP ${status} has a specific safe Query failure`, async t => {
|
||||
const f = await fixture(t);
|
||||
f.httpStatus = status;
|
||||
await assert.rejects(f.service.overview(), hasCode(expected));
|
||||
});
|
||||
|
||||
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [503, "TS_ADMIN_READ_FAILED"]] as const) test(`HTTP ${status} cannot become a successful list through a JSON status.code=0 body`, async t => {
|
||||
const f = await fixture(t);
|
||||
f.httpStatus = status; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
|
||||
assert.equal(result.bansAvailable, true); assert.equal(result.clientCount, 1);
|
||||
});
|
||||
|
||||
test("HTTP errors carrying genuine TS permission errors keep the SDK error classification", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.httpStatus = 403; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
|
||||
f.reply = (command, params) => command === "servergrouplist" ? denied() : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED");
|
||||
});
|
||||
|
||||
test("administrator actions use typed SDK commands, escaping and UID-only bans", async t => {
|
||||
const f = await fixture(t);
|
||||
const actions: TsAdminAction[] = [
|
||||
{ action: "server.update", name: "A | name", welcomeMessage: "Hello\nworld", maxClients: 48 },
|
||||
{ action: "channel.create", name: "Channel | special", parentId: "1", description: "Line1\nLine2", permanent: true, password: "test password" },
|
||||
{ action: "channel.update", channelId: "2", name: "New name" },
|
||||
{ action: "channel.delete", channelId: "2" },
|
||||
{ action: "client.move", clientId: 42, clientUid: uid, channelId: "1" },
|
||||
{ action: "client.kick", clientId: 42, clientUid: uid, reason: "Test reason" },
|
||||
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: false },
|
||||
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: true },
|
||||
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID ban", durationSeconds: 3600 },
|
||||
{ action: "ban.delete", banId: "9" },
|
||||
];
|
||||
for (const action of actions) assert.deepEqual(await f.action(action), { ok: true });
|
||||
const command = (name: string) => f.calls.find(call => call.command === name)!.params;
|
||||
assert.deepEqual(command("serveredit"), { virtualserver_name: "A | name", virtualserver_welcomemessage: "Hello\nworld", virtualserver_maxclients: "48" });
|
||||
assert.equal(command("channelcreate").channel_description, "Line1\nLine2");
|
||||
assert.equal(command("channelcreate").channel_password, "test password");
|
||||
assert.deepEqual(command("channeledit"), { cid: "2", channel_name: "New name" }, "rename must preserve unread channel metadata");
|
||||
assert.equal(command("channeldelete").force, "0");
|
||||
assert.deepEqual(command("clientmove"), { clid: "42", cid: "1" });
|
||||
assert.equal(command("clientkick").reasonid, "5");
|
||||
assert.deepEqual(command("servergroupaddclient"), { sgid: "6", cldbid: "77" });
|
||||
assert.deepEqual(command("servergroupdelclient"), { sgid: "6", cldbid: "77" });
|
||||
assert.deepEqual(command("banadd"), { uid, time: "3600", banreason: "UID ban" });
|
||||
assert.equal(command("bandel").banid, "9");
|
||||
});
|
||||
|
||||
test("stale client identities never receive a mutation, and failed writes are not retried", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, client_unique_identifier: "replacement-identity=" }]) : original(command, params);
|
||||
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_CLIENT_CHANGED"));
|
||||
assert.ok(!f.calls.some(call => call.command === "clientkick"));
|
||||
f.reply = (command, params) => command === "clientkick" ? denied() : original(command, params);
|
||||
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_PERMISSION_DENIED"));
|
||||
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
|
||||
await assert.rejects(f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: 0 }), hasCode("TS_ADMIN_PARTIAL_SUCCESS"));
|
||||
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
|
||||
assert.equal(f.calls.find(call => call.command === "banadd")!.params.time, undefined, "permanent UID ban has no expiry");
|
||||
});
|
||||
|
||||
test("configuration changes cancel in-flight and queued writes instead of targeting another server", async t => {
|
||||
const f = await fixture(t), original = f.reply, entered = deferred(), release = deferred();
|
||||
f.reply = async (command, params) => {
|
||||
if (command === "clientlist") { entered.resolve(); await release.promise; }
|
||||
return original(command, params);
|
||||
};
|
||||
const first = f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" });
|
||||
const queued = f.action({ action: "channel.delete", channelId: "1" });
|
||||
const firstCheck = assert.rejects(first, hasCode("TS_ADMIN_CONFIG_CHANGED"));
|
||||
const queuedCheck = assert.rejects(queued, hasCode("TS_ADMIN_CONFIG_CHANGED"));
|
||||
await entered.promise;
|
||||
f.service.save({ ...f.settings, serverId: 8 });
|
||||
release.resolve();
|
||||
await Promise.all([firstCheck, queuedCheck]);
|
||||
assert.ok(!f.calls.some(call => ["clientkick", "channeldelete"].includes(call.command)));
|
||||
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/")));
|
||||
f.reply = original;
|
||||
assert.deepEqual(await f.action({ action: "channel.delete", channelId: "2" }), { ok: true }, "failed queue entries must not block later work");
|
||||
});
|
||||
|
||||
test("an old browser snapshot cannot mutate a newly configured management server", async t => {
|
||||
const f = await fixture(t);
|
||||
const snapshot = await f.service.overview();
|
||||
const operation: TsAdminAction = { action: "channel.delete", channelId: "1" };
|
||||
f.service.save({ ...f.settings, serverId: 8 });
|
||||
f.calls.length = 0;
|
||||
assert.throws(() => f.service.action({ operation, configurationRevision: snapshot.configurationRevision }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
|
||||
assert.throws(() => f.service.action({ operation }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
|
||||
assert.equal(f.calls.length, 0, "stale UI must fail before connecting to the new server");
|
||||
});
|
||||
|
||||
test("administrator command whitelist rejects arbitrary commands and invalid object identifiers", async t => {
|
||||
const f = await fixture(t);
|
||||
for (const action of [null, [], { action: "serverstop" }, { action: "channel.delete", channelId: "0" },
|
||||
{ action: "channel.delete", channelId: "1|serverstop" }, { action: "channel.delete", channelId: "18446744073709551616" },
|
||||
{ action: "client.kick", clientId: 42, clientUid: "", reason: "" },
|
||||
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: -1 },
|
||||
{ action: "server.update", name: "", welcomeMessage: "", maxClients: 32 },
|
||||
]) assert.throws(() => f.action(action), hasCode("INVALID_TS_ADMIN_ACTION"));
|
||||
assert.equal(f.calls.length, 0);
|
||||
});
|
||||
|
||||
test("WebQuery HTTP and TS API-key authentication failures have a useful safe error", async t => {
|
||||
const f = await fixture(t);
|
||||
for (const status of [401, 403]) {
|
||||
f.httpStatus = status;
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
|
||||
}
|
||||
f.httpStatus = 200;
|
||||
f.reply = () => ({ body: [], status: { code: 5122, message: "invalid API key: secret-value-must-not-escape" } });
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
|
||||
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
|
||||
});
|
||||
|
||||
test("disposing an administrator request cancels its underlying WebQuery HTTP request", async t => {
|
||||
const f = await fixture(t), entered = deferred(), release = deferred(), controller = new AbortController();
|
||||
f.reply = async () => { entered.resolve(); await release.promise; return ok(); };
|
||||
const pending = webQueryFetch(controller.signal)(`${f.settings.webQueryUrl}/7/version`, { method: "POST", body: "{}" });
|
||||
const check = assert.rejects(pending, (error: any) => error.name === "AbortError");
|
||||
await entered.promise;
|
||||
controller.abort(); await check;
|
||||
release.resolve();
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
import { isIP } from "node:net";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
addBan, addClientToServerGroup, asBanID, asChannelID, asClientID, asServerGroupID,
|
||||
createChannel, deleteBan, deleteChannel, editChannel, editServer, getServerInfo, kickClient,
|
||||
listBans, listChannels, listClients, listServerGroups, moveClient, Reason,
|
||||
removeClientFromServerGroup, ServerError, ErrorCode, CommandTimeoutError, type CommandOptions,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import { QueryClient, WebQueryHttpError, type QueryClientOptions } from "@honeybbq/teamspeak/query";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import type { TsAdminAction, TsAdminSettingsInput } from "../shared/admin-inputs.js";
|
||||
import { resolveTeamSpeakTarget } from "../server/teamspeak-alias.js";
|
||||
import { AdminInputError } from "./admin-errors.js";
|
||||
import { webQueryFetch } from "./webquery-fetch.js";
|
||||
|
||||
const PASSWORD_PURPOSE = "webspeak:ts-admin-query-password:v1";
|
||||
const API_KEY_PURPOSE = "webspeak:ts-admin-webquery-api-key:v1";
|
||||
export type TsAdminQueryClientFactory = (options: QueryClientOptions) => QueryClient;
|
||||
type Policy = { mode: "fixed" | "open"; target: string };
|
||||
|
||||
/** Optional administrator access. Guest voice and WebSpeak management never use these credentials. */
|
||||
export class TsAdminService {
|
||||
private actions: Promise<unknown> = Promise.resolve();
|
||||
constructor(
|
||||
private readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
private readonly logger: Logger,
|
||||
private readonly policy: () => Policy,
|
||||
private readonly createClient: TsAdminQueryClientFactory = options => new QueryClient(options),
|
||||
) {}
|
||||
|
||||
settings() {
|
||||
const { passwordEncrypted, apiKeyEncrypted, ...settings } = this.database.getTsAdminSettings();
|
||||
return { ...settings, configurationRevision: this.configuration(), fixedMode: this.policy().mode === "fixed", hasPassword: Boolean(passwordEncrypted), hasApiKey: Boolean(apiKeyEncrypted) };
|
||||
}
|
||||
|
||||
save(input: TsAdminSettingsInput): void {
|
||||
this.assertFixed();
|
||||
const current = this.database.getTsAdminSettings();
|
||||
const transport = input.transport ?? current.transport;
|
||||
if (!["web", "ssh", "tcp"].includes(transport) || typeof input.enabled !== "boolean") fail("INVALID_TS_ADMIN_SETTINGS");
|
||||
const queryPort = input.queryPort;
|
||||
if (!Number.isInteger(queryPort) || queryPort < 1 || queryPort > 65535) fail("INVALID_TS_ADMIN_QUERY_PORT");
|
||||
const username = text(input.username, 128).trim();
|
||||
const hostKeyFingerprint = text(input.hostKeyFingerprint, 128).trim();
|
||||
const queryHost = text(input.queryHost ?? current.queryHost, 253).trim();
|
||||
if (queryHost && !isIP(queryHost) && !/^(?=.{1,253}$)[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i.test(queryHost)) fail("INVALID_TS_ADMIN_HOST");
|
||||
let webQueryUrl = text(input.webQueryUrl ?? current.webQueryUrl, 2048).trim();
|
||||
if (webQueryUrl) {
|
||||
try {
|
||||
const url = new URL(webQueryUrl);
|
||||
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash) throw new Error();
|
||||
webQueryUrl = url.toString().replace(/\/+$/, "");
|
||||
} catch { fail("INVALID_TS_ADMIN_URL"); }
|
||||
}
|
||||
const serverId = input.serverId ?? current.serverId;
|
||||
if (!Number.isSafeInteger(serverId) || serverId < 0 || serverId > 4_294_967_295) fail("INVALID_TS_ADMIN_SERVER_ID");
|
||||
const passwordEncrypted = this.secret(input.password, input.passwordAction, current.passwordEncrypted, PASSWORD_PURPOSE, 1024);
|
||||
const apiKeyEncrypted = this.secret(input.apiKey, input.apiKeyAction, current.apiKeyEncrypted, API_KEY_PURPOSE, 4096);
|
||||
if (input.enabled) {
|
||||
if (transport === "web") {
|
||||
if (!webQueryUrl) fail("INVALID_TS_ADMIN_URL");
|
||||
if (!apiKeyEncrypted) fail("INVALID_TS_ADMIN_API_KEY");
|
||||
} else {
|
||||
if (!username) fail("INVALID_TS_ADMIN_USERNAME");
|
||||
if (!passwordEncrypted) fail("INVALID_TS_ADMIN_PASSWORD");
|
||||
if (transport === "ssh" && !/^SHA256:[A-Za-z0-9+/]{43}$/.test(hostKeyFingerprint)) fail("INVALID_TS_ADMIN_HOST_KEY");
|
||||
}
|
||||
}
|
||||
this.database.updateTsAdminSettings({ enabled: input.enabled, transport, queryHost, queryPort, username,
|
||||
passwordEncrypted, apiKeyEncrypted, webQueryUrl, serverId, hostKeyFingerprint });
|
||||
}
|
||||
|
||||
async overview() {
|
||||
return this.withClient(async (client, options, assertCurrent) => {
|
||||
const [server, channels, clients] = await Promise.all([
|
||||
getServerInfo(client, options), listChannels(client, options),
|
||||
listClients(client, { ...options, uid: true, away: true, voice: true, groups: true }),
|
||||
]);
|
||||
const [groups, bans] = await Promise.allSettled([listServerGroups(client, options), listBans(client, options)]);
|
||||
assertCurrent();
|
||||
const voiceClients = clients.filter(entry => entry.type === 0);
|
||||
const channelMembers = new Map<string, number>();
|
||||
for (const entry of voiceClients) {
|
||||
const id = String(entry.channelID);
|
||||
channelMembers.set(id, (channelMembers.get(id) ?? 0) + 1);
|
||||
}
|
||||
this.database.addAudit("TS_ADMIN_OVERVIEW_READ", { channels: channels.length, clients: voiceClients.length });
|
||||
return {
|
||||
configurationRevision: this.configuration(),
|
||||
serverName: server.virtualserver_name ?? "", serverVersion: client.serverVersion, serverFamily: client.serverFamily,
|
||||
welcomeMessage: server.virtualserver_welcomemessage ?? "", maxClients: numeric(server.virtualserver_maxclients),
|
||||
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: voiceClients.length,
|
||||
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
|
||||
description: channel.description, totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: entry.serverGroups.map(String), away: entry.isAway, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
groups: groups.status === "fulfilled" ? groups.value.filter(group => group.type === 1).map(group => ({ id: String(group.id), name: group.name })) : [],
|
||||
bans: bans.status === "fulfilled" ? bans.value.map(ban => ({ id: String(ban.id), name: ban.name || ban.lastNickname,
|
||||
uid: ban.uid, reason: ban.reason, durationSeconds: ban.durationMs / 1000, createdAt: ban.createdAt?.toISOString() ?? null })) : [],
|
||||
groupsAvailable: groups.status === "fulfilled", bansAvailable: bans.status === "fulfilled",
|
||||
groupsErrorCode: groups.status === "fulfilled" ? null : classifyError(groups.reason, "TS_ADMIN_READ_FAILED"),
|
||||
bansErrorCode: bans.status === "fulfilled" ? null : classifyError(bans.reason, "TS_ADMIN_READ_FAILED"),
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
}, undefined, "TS_ADMIN_READ_FAILED");
|
||||
}
|
||||
|
||||
/** Serialize writes, then revalidate live client identities immediately before changing them. */
|
||||
action(raw: unknown): Promise<{ ok: true }> {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
|
||||
const request = raw as Record<string, unknown>;
|
||||
const action = readAction(request.operation);
|
||||
// Bind queued work to the configuration the administrator reviewed.
|
||||
const expected = this.configuration();
|
||||
if (request.configurationRevision !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
|
||||
const operation = this.actions.then(() => this.withClient(async (client, options, assertCurrent) => {
|
||||
assertCurrent();
|
||||
switch (action.action) {
|
||||
case "server.update":
|
||||
await editServer(client, { virtualserver_name: action.name, virtualserver_welcomemessage: action.welcomeMessage,
|
||||
virtualserver_maxclients: String(action.maxClients) }, options); break;
|
||||
case "channel.create":
|
||||
await createChannel(client, { name: action.name, parentID: asChannelID(BigInt(action.parentId)),
|
||||
description: action.description, isPermanent: action.permanent, password: action.password }, options); break;
|
||||
case "channel.update":
|
||||
await editChannel(client, asChannelID(BigInt(action.channelId)), { name: action.name }, options); break;
|
||||
case "channel.delete":
|
||||
await deleteChannel(client, asChannelID(BigInt(action.channelId)), { ...options, force: false }); break;
|
||||
case "ban.delete":
|
||||
await deleteBan(client, asBanID(BigInt(action.banId)), options); break;
|
||||
default: {
|
||||
const current = (await listClients(client, { ...options, uid: true, groups: true })).find(entry => Number(entry.id) === action.clientId);
|
||||
if (!current || !current.uid || current.uid !== action.clientUid || current.type !== 0) fail("TS_ADMIN_CLIENT_CHANGED");
|
||||
assertCurrent();
|
||||
if (action.action === "client.move") await moveClient(client, current.id, asChannelID(BigInt(action.channelId)), options);
|
||||
else if (action.action === "client.kick") await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason });
|
||||
else if (action.action === "client.group") {
|
||||
if (!current.databaseID) fail("TS_ADMIN_CLIENT_CHANGED");
|
||||
const change = action.remove ? removeClientFromServerGroup : addClientToServerGroup;
|
||||
await change(client, asServerGroupID(BigInt(action.groupId)), current.databaseID, options);
|
||||
} else {
|
||||
// Banning the gateway's IP would disconnect unrelated WebSpeak users.
|
||||
await addBan(client, { uid: current.uid, reason: action.reason, durationMs: action.durationSeconds * 1000 }, options);
|
||||
try {
|
||||
assertCurrent();
|
||||
// TS may disconnect the banned identity itself. Never kick a replacement that reused its ID.
|
||||
const remaining = (await listClients(client, { ...options, uid: true })).find(entry => entry.id === current.id);
|
||||
assertCurrent();
|
||||
if (remaining?.uid === current.uid && remaining.type === 0) {
|
||||
try { await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason }); }
|
||||
catch (error) {
|
||||
// The same client can leave between the fresh list and the kick.
|
||||
if (!(error instanceof ServerError && error.code === ErrorCode.ClientInvalidID)) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { this.database.addAudit("TS_ADMIN_ACTION_PARTIAL", { action: action.action }); fail("TS_ADMIN_PARTIAL_SUCCESS"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
this.database.addAudit("TS_ADMIN_ACTION_SUCCEEDED", { action: action.action });
|
||||
return { ok: true as const };
|
||||
}, expected)).catch(error => {
|
||||
this.database.addAudit("TS_ADMIN_ACTION_FAILED", { action: action.action });
|
||||
throw error;
|
||||
});
|
||||
this.actions = operation.catch(() => undefined);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private configuration(): string {
|
||||
return createHash("sha256").update(JSON.stringify([this.policy(), this.database.getTsAdminSettings()])).digest("hex");
|
||||
}
|
||||
|
||||
private async withClient<T>(run: (client: QueryClient, options: CommandOptions, assertCurrent: () => void) => Promise<T>, expected?: string, failureCode = "TS_ADMIN_OPERATION_FAILED"): Promise<T> {
|
||||
this.assertFixed();
|
||||
if (expected !== undefined && this.configuration() !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
|
||||
const settings = this.database.getTsAdminSettings();
|
||||
if (!settings.enabled) fail("TS_ADMIN_NOT_CONFIGURED");
|
||||
const policy = this.policy();
|
||||
const captured = JSON.stringify(settings);
|
||||
const assertCurrent = () => {
|
||||
this.assertFixed();
|
||||
if (this.policy().target !== policy.target || JSON.stringify(this.database.getTsAdminSettings()) !== captured) fail("TS_ADMIN_CONFIG_CHANGED");
|
||||
};
|
||||
let target: { host: string; port: number } | undefined;
|
||||
if (!settings.serverId || settings.transport !== "web" && !settings.queryHost) {
|
||||
try { target = await resolveTeamSpeakTarget(policy.target); } catch { fail("TS_ADMIN_TARGET_UNAVAILABLE"); }
|
||||
}
|
||||
const lifetime = new AbortController();
|
||||
let transport: QueryClientOptions["transport"];
|
||||
if (settings.transport === "web") {
|
||||
if (!settings.webQueryUrl || !settings.apiKeyEncrypted) fail("TS_ADMIN_NOT_CONFIGURED");
|
||||
transport = { kind: "web", url: settings.webQueryUrl, apiKey: this.decrypt(settings.apiKeyEncrypted, API_KEY_PURPOSE), fetch: webQueryFetch(lifetime.signal) };
|
||||
} else {
|
||||
if (!settings.passwordEncrypted || !settings.username) fail("TS_ADMIN_NOT_CONFIGURED");
|
||||
const host = settings.queryHost || target!.host;
|
||||
const password = this.decrypt(settings.passwordEncrypted, PASSWORD_PURPOSE);
|
||||
transport = settings.transport === "tcp"
|
||||
? { kind: "tcp", host, port: settings.queryPort, login: { name: settings.username, password } }
|
||||
: { kind: "ssh", host, port: settings.queryPort, username: settings.username, password, hostKey: key => {
|
||||
if (key.fingerprint !== settings.hostKeyFingerprint) fail("TS_ADMIN_HOST_KEY_MISMATCH");
|
||||
} };
|
||||
}
|
||||
assertCurrent();
|
||||
let client: QueryClient | undefined;
|
||||
let connected = false;
|
||||
try {
|
||||
client = this.createClient({ transport, server: settings.serverId ? { id: settings.serverId } : { port: target!.port },
|
||||
nickname: "WebSpeak Admin", ...(settings.transport === "web" ? {} : { events: false }) });
|
||||
const signal = AbortSignal.timeout(20_000);
|
||||
await client.connect({ signal }); connected = true; assertCurrent();
|
||||
return await run(client, { signal, timeoutMs: 8_000 }, assertCurrent);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminInputError) throw error;
|
||||
const code = classifyError(error, connected ? failureCode : "TS_ADMIN_CONNECTION_FAILED");
|
||||
this.logger.warn({ code, transport: settings.transport }, "TeamSpeak administrator request failed");
|
||||
return fail(code);
|
||||
} finally {
|
||||
lifetime.abort();
|
||||
try { await client?.disconnect(); } catch { /* no connection can outlive its request */ }
|
||||
}
|
||||
}
|
||||
|
||||
private assertFixed(): void { if (this.policy().mode !== "fixed") fail("TS_ADMIN_FIXED_MODE_REQUIRED"); }
|
||||
private decrypt(value: string, purpose: string): string {
|
||||
try { return decryptSecret(value, this.masterSecret, purpose); } catch { fail("TS_ADMIN_CREDENTIALS_UNAVAILABLE"); }
|
||||
}
|
||||
private secret(value: string | undefined, action: "keep" | "replace" | "remove" | undefined, current: string | null, purpose: string, max: number): string | null {
|
||||
if (action === "remove") return null;
|
||||
if (action === "replace" || action === undefined && value !== undefined) {
|
||||
const secret = text(value ?? "", max);
|
||||
return secret ? encryptSecret(secret, this.masterSecret, purpose) : null;
|
||||
}
|
||||
if (action !== undefined && action !== "keep") fail("INVALID_TS_ADMIN_SETTINGS");
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(code: string): never { throw new AdminInputError(code, code); }
|
||||
function text(value: unknown, max: number, required = false): string {
|
||||
if (typeof value !== "string" || value.length > max || /[\0]/.test(value) || required && !value.trim()) fail("INVALID_TS_ADMIN_ACTION");
|
||||
return value;
|
||||
}
|
||||
function numeric(value: string | undefined): number { const n = Number(value); return Number.isFinite(n) && n >= 0 ? n : 0; }
|
||||
function id(value: unknown, zero = false): string {
|
||||
const v = text(value, 20, true);
|
||||
if (!/^\d+$/.test(v) || BigInt(v) > 18_446_744_073_709_551_615n || !zero && BigInt(v) === 0n) fail("INVALID_TS_ADMIN_ACTION");
|
||||
return v;
|
||||
}
|
||||
function readAction(raw: unknown): TsAdminAction {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
|
||||
const r = raw as Record<string, unknown>;
|
||||
const action = r.action;
|
||||
if (action === "server.update") {
|
||||
if (!Number.isInteger(r.maxClients) || Number(r.maxClients) < 1 || Number(r.maxClients) > 65535) fail("INVALID_TS_ADMIN_ACTION");
|
||||
return { action, name: text(r.name, 64, true), welcomeMessage: text(r.welcomeMessage, 4096), maxClients: Number(r.maxClients) };
|
||||
}
|
||||
if (action === "channel.create") {
|
||||
if (typeof r.permanent !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
|
||||
return { action, name: text(r.name, 40, true), parentId: id(r.parentId, true), description: text(r.description, 8192),
|
||||
permanent: r.permanent, ...(r.password === undefined ? {} : { password: text(r.password, 512) }) };
|
||||
}
|
||||
if (action === "channel.update") return { action, channelId: id(r.channelId), name: text(r.name, 40, true) };
|
||||
if (action === "channel.delete") return { action, channelId: id(r.channelId) };
|
||||
if (action === "ban.delete") return { action, banId: id(r.banId) };
|
||||
if (!Number.isInteger(r.clientId) || Number(r.clientId) < 1 || Number(r.clientId) > 65535) fail("INVALID_TS_ADMIN_ACTION");
|
||||
const member = { clientId: Number(r.clientId), clientUid: text(r.clientUid, 128, true) };
|
||||
if (action === "client.move") return { action, ...member, channelId: id(r.channelId) };
|
||||
if (action === "client.kick") return { action, ...member, reason: text(r.reason, 200) };
|
||||
if (action === "client.group") {
|
||||
if (typeof r.remove !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
|
||||
return { action, ...member, groupId: id(r.groupId), remove: r.remove };
|
||||
}
|
||||
if (action === "client.ban") {
|
||||
if (!Number.isSafeInteger(r.durationSeconds) || Number(r.durationSeconds) < 0 || Number(r.durationSeconds) > 31_536_000) fail("INVALID_TS_ADMIN_ACTION");
|
||||
return { action, ...member, reason: text(r.reason, 200), durationSeconds: Number(r.durationSeconds) };
|
||||
}
|
||||
fail("INVALID_TS_ADMIN_ACTION");
|
||||
}
|
||||
function classifyError(error: unknown, fallback: string): string {
|
||||
const seen = new Set<unknown>();
|
||||
while (error instanceof Error && !seen.has(error)) {
|
||||
seen.add(error);
|
||||
if (error.message === "TS_ADMIN_HOST_KEY_MISMATCH") return error.message;
|
||||
if (error instanceof WebQueryHttpError && [401, 403].includes(error.status)) return "TS_ADMIN_AUTH_FAILED";
|
||||
if (error instanceof WebQueryHttpError && error.status === 429) return "TS_ADMIN_RATE_LIMITED";
|
||||
if (error instanceof CommandTimeoutError || ["TimeoutError", "AbortError"].includes(error.name)
|
||||
|| error instanceof WebQueryHttpError && [408, 504].includes(error.status)) return "TS_ADMIN_TIMEOUT";
|
||||
if (error instanceof ServerError) {
|
||||
if ([2568, 2569, 2570, 5120].includes(error.code)) return "TS_ADMIN_PERMISSION_DENIED";
|
||||
if ([520, 5122, 5124].includes(error.code)) return "TS_ADMIN_AUTH_FAILED";
|
||||
if (error.code === 524) return "TS_ADMIN_RATE_LIMITED";
|
||||
}
|
||||
if (/CERT|SELF_SIGNED|UNABLE_TO_VERIFY/i.test(String((error as NodeJS.ErrnoException).code ?? ""))) return "TS_ADMIN_TLS_FAILED";
|
||||
error = error.cause;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { request as httpRequest } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
import { WebQueryHttpError } from "@honeybbq/teamspeak/query";
|
||||
|
||||
/** Keep the SDK's WebQuery protocol, but bound HTTP requests to this admin operation.
|
||||
* Node's global fetch blocks WebQuery's default port 10080. */
|
||||
export function webQueryFetch(lifetime: AbortSignal): typeof fetch {
|
||||
return ((url: string, init: RequestInit) => new Promise<Response>((resolve, reject) => {
|
||||
const request = new URL(url).protocol === "https:" ? httpsRequest : httpRequest;
|
||||
const req = request(url, {
|
||||
method: init.method, headers: init.headers as Record<string, string>,
|
||||
signal: AbortSignal.any([lifetime, AbortSignal.timeout(8_000)]),
|
||||
}, res => {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
size += chunk.length;
|
||||
if (size > 8 * 1024 * 1024) { res.destroy(new Error("WebQuery response too large")); return; }
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on("error", reject);
|
||||
res.on("end", () => {
|
||||
const body = Buffer.concat(chunks), status = res.statusCode ?? 502;
|
||||
if (status < 200 || status >= 300) {
|
||||
// SDK beta.19 accepts status.code=0 even on HTTP failures. Keep genuine TS errors,
|
||||
// but never turn a proxy's failed HTTP response into a successful empty result.
|
||||
let tsError = false;
|
||||
try {
|
||||
const code: unknown = JSON.parse(body.toString("utf8"))?.status?.code;
|
||||
tsError = typeof code === "number" && Number.isSafeInteger(code) && code > 0;
|
||||
} catch { /* HTTP status is authoritative when no TS error is present. */ }
|
||||
if (!tsError) { reject(new WebQueryHttpError(status, res.statusMessage ?? "")); return; }
|
||||
}
|
||||
resolve(new Response(body, { status, statusText: res.statusMessage ?? "" }));
|
||||
});
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.end(init.body as string);
|
||||
})) as typeof fetch;
|
||||
}
|
||||
+45
-4
@@ -94,11 +94,52 @@ async function runRelayMode(): Promise<void> {
|
||||
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 voiceHost = process.env.WEBSPEAK_VOICE_GATEWAY_HOST?.trim() || "127.0.0.1";
|
||||
const voicePort = parsePort(process.env.WEBSPEAK_VOICE_GATEWAY_PORT, 3041);
|
||||
const webRtcUdpStart = parsePort(process.env.WEBSPEAK_RELAY_WEBRTC_UDP_START, 40000);
|
||||
const webRtcUdpEnd = parsePort(process.env.WEBSPEAK_RELAY_WEBRTC_UDP_END, 40099);
|
||||
if (webRtcUdpStart > webRtcUdpEnd) throw new Error("Invalid relay WebRTC UDP port range");
|
||||
const [{ createLogger }, { createVoiceGatewayServer }] = await Promise.all([
|
||||
import("./logger.js"),
|
||||
import("./server/voice-gateway.js"),
|
||||
]);
|
||||
const logger = createLogger(LOG_DIR);
|
||||
const voiceGateway = createVoiceGatewayServer({
|
||||
host: voiceHost,
|
||||
port: voicePort,
|
||||
sharedToken: token,
|
||||
logger,
|
||||
webRtc: {
|
||||
enabled: process.env.WEBSPEAK_RELAY_WEBRTC_ENABLED === undefined
|
||||
? true
|
||||
: parseBoolean(process.env.WEBSPEAK_RELAY_WEBRTC_ENABLED),
|
||||
...(process.env.WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST?.trim()
|
||||
? { publicHost: process.env.WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST.trim() }
|
||||
: {}),
|
||||
ipv6Enabled: parseBoolean(process.env.WEBSPEAK_RELAY_WEBRTC_IPV6_ENABLED),
|
||||
...(process.env.WEBSPEAK_RELAY_WEBRTC_STUN_SERVER?.trim()
|
||||
? { stunServer: process.env.WEBSPEAK_RELAY_WEBRTC_STUN_SERVER.trim() }
|
||||
: {}),
|
||||
udpPortRange: [webRtcUdpStart, webRtcUdpEnd] as [number, number],
|
||||
},
|
||||
screenShareIceServers: SCREEN_SHARE_ICE_SERVERS,
|
||||
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
|
||||
});
|
||||
const voiceAddress = await voiceGateway.start();
|
||||
let relay: Awaited<ReturnType<typeof createAccelerationRelayServer>>;
|
||||
try {
|
||||
relay = await createAccelerationRelayServer({ host, port, token, allowPrivate });
|
||||
} catch (error) {
|
||||
await voiceGateway.stop();
|
||||
throw error;
|
||||
}
|
||||
console.log(`WebSpeak relay mode listening on ${relay.host}:${relay.port}; voice gateway on ${voiceAddress.host}:${voiceAddress.port}`);
|
||||
let stopping = false;
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
if (stopping) return;
|
||||
stopping = true;
|
||||
relay.close();
|
||||
void voiceGateway.stop().finally(() => process.exit(0));
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@ import express from "express";
|
||||
import { createServer } from "node:http";
|
||||
import path from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { createLogger } from "../logger.js";
|
||||
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore } from "../server/join-ticket.js";
|
||||
@@ -79,7 +79,7 @@ app.post("/api/join-ticket", (request, response) => {
|
||||
let identity: string | undefined;
|
||||
if (typeof body.identity === "string" && body.identity.length <= 8192) {
|
||||
try {
|
||||
identityFromString(body.identity);
|
||||
parseIdentity(body.identity);
|
||||
identity = body.identity;
|
||||
} catch {
|
||||
// Corrupt local identity should not prevent an ephemeral join.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
|
||||
import { DATABASE_SCHEMA_VERSION, WebSpeakDatabase } from "./database.js";
|
||||
|
||||
test("relay voice endpoint is stored by the current database migration", (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-relay-db-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.sqlite"));
|
||||
context.after(() => {
|
||||
database.close();
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
assert.equal(DATABASE_SCHEMA_VERSION, 12);
|
||||
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
|
||||
assert.equal(database.getTsAdminSettings().transport, "web");
|
||||
assert.equal(database.getTsAdminSettings().enabled, false);
|
||||
database.replaceRelayNodes([{
|
||||
id: "de-relay",
|
||||
name: "Germany relay",
|
||||
enabled: true,
|
||||
host: "relay.example.com",
|
||||
port: 39087,
|
||||
voiceEndpoint: "https://relay.example.com",
|
||||
tokenEncrypted: null,
|
||||
}]);
|
||||
assert.equal(database.listRelayNodes()[0]?.voiceEndpoint, "https://relay.example.com");
|
||||
});
|
||||
|
||||
test("schema 11 migration preserves encrypted SSH credentials and does not silently switch transport", t => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-ts-admin-migration-"));
|
||||
const filename = path.join(directory, "test.sqlite"), master = Buffer.alloc(32, 9);
|
||||
const encrypted = encryptSecret("fixture-ssh-password", master, "webspeak:ts-admin-query-password:v1");
|
||||
const original = new WebSpeakDatabase(filename);
|
||||
original.close();
|
||||
const old = new DatabaseSync(filename);
|
||||
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; PRAGMA user_version = 11;");
|
||||
old.prepare("UPDATE ts_admin_settings SET enabled=1, query_port=10222, username='query-owner', password_encrypted=?, host_key_fingerprint=?").run(encrypted, `SHA256:${"A".repeat(43)}`);
|
||||
old.close();
|
||||
const migrated = new WebSpeakDatabase(filename);
|
||||
t.after(() => { migrated.close(); rmSync(directory, { recursive: true, force: true }); });
|
||||
const settings = migrated.getTsAdminSettings();
|
||||
assert.equal(migrated.schemaVersion, 12);
|
||||
assert.equal(settings.transport, "ssh"); assert.equal(settings.enabled, true);
|
||||
assert.equal(settings.queryPort, 10222); assert.equal(settings.username, "query-owner");
|
||||
assert.equal(settings.passwordEncrypted, encrypted);
|
||||
assert.equal(decryptSecret(settings.passwordEncrypted, master, "webspeak:ts-admin-query-password:v1"), "fixture-ssh-password");
|
||||
assert.equal(settings.apiKeyEncrypted, null); assert.equal(settings.webQueryUrl, ""); assert.equal(settings.serverId, 0);
|
||||
});
|
||||
+108
-3
@@ -6,7 +6,7 @@ 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 = 9;
|
||||
export const DATABASE_SCHEMA_VERSION = 12;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -72,6 +72,7 @@ export interface PersistedRelayNode {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
voiceEndpoint: string;
|
||||
tokenEncrypted: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -92,6 +93,20 @@ export interface ManagedInviteRecord {
|
||||
revokedAt: string | null;
|
||||
}
|
||||
|
||||
export interface PersistedTsAdminSettings {
|
||||
enabled: boolean;
|
||||
transport: "web" | "ssh" | "tcp";
|
||||
queryHost: string;
|
||||
webQueryUrl: string;
|
||||
apiKeyEncrypted: string | null;
|
||||
serverId: number;
|
||||
queryPort: number;
|
||||
username: string;
|
||||
passwordEncrypted: string | null;
|
||||
hostKeyFingerprint: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface ManagedInviteRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
token_hash: string;
|
||||
@@ -138,12 +153,27 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface TsAdminSettingsRow extends Record<string, unknown> {
|
||||
enabled: number;
|
||||
transport: "web" | "ssh" | "tcp";
|
||||
query_host: string;
|
||||
web_query_url: string;
|
||||
api_key_encrypted: string | null;
|
||||
server_id: number;
|
||||
query_port: number;
|
||||
username: string;
|
||||
password_encrypted: string | null;
|
||||
host_key_fingerprint: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface RelayNodeRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: number;
|
||||
host: string;
|
||||
port: number;
|
||||
voice_endpoint: string;
|
||||
token_encrypted: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
@@ -247,6 +277,7 @@ export class WebSpeakDatabase {
|
||||
enabled: row.enabled === 1,
|
||||
host: row.host,
|
||||
port: row.port,
|
||||
voiceEndpoint: row.voice_endpoint,
|
||||
tokenEncrypted: row.token_encrypted,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
@@ -258,8 +289,8 @@ export class WebSpeakDatabase {
|
||||
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 (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, voice_endpoint, token_encrypted, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const node of nodes) {
|
||||
insert.run(
|
||||
@@ -268,6 +299,7 @@ export class WebSpeakDatabase {
|
||||
node.enabled ? 1 : 0,
|
||||
node.host,
|
||||
node.port,
|
||||
node.voiceEndpoint,
|
||||
node.tokenEncrypted,
|
||||
node.createdAt ?? now,
|
||||
node.updatedAt ?? now,
|
||||
@@ -333,6 +365,37 @@ export class WebSpeakDatabase {
|
||||
return rows.map(mapManagedInviteRow);
|
||||
}
|
||||
|
||||
getTsAdminSettings(): PersistedTsAdminSettings {
|
||||
const row = this.database.prepare("SELECT * FROM ts_admin_settings WHERE id = 1").get() as TsAdminSettingsRow;
|
||||
return {
|
||||
enabled: row.enabled === 1,
|
||||
transport: row.transport,
|
||||
queryHost: row.query_host,
|
||||
webQueryUrl: row.web_query_url,
|
||||
apiKeyEncrypted: row.api_key_encrypted,
|
||||
serverId: row.server_id,
|
||||
queryPort: row.query_port,
|
||||
username: row.username,
|
||||
passwordEncrypted: row.password_encrypted,
|
||||
hostKeyFingerprint: row.host_key_fingerprint,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
updateTsAdminSettings(settings: Omit<PersistedTsAdminSettings, "updatedAt">): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.database.prepare(
|
||||
`UPDATE ts_admin_settings
|
||||
SET enabled = ?, transport = ?, query_host = ?, web_query_url = ?, api_key_encrypted = ?, server_id = ?,
|
||||
query_port = ?, username = ?, password_encrypted = ?, host_key_fingerprint = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(settings.enabled ? 1 : 0, settings.transport, settings.queryHost, settings.webQueryUrl, settings.apiKeyEncrypted, settings.serverId,
|
||||
settings.queryPort, settings.username, settings.passwordEncrypted, settings.hostKeyFingerprint, now);
|
||||
this.insertAudit("TS_ADMIN_SETTINGS_UPDATED", { enabled: settings.enabled, transport: settings.transport }, now);
|
||||
});
|
||||
}
|
||||
|
||||
getManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
|
||||
const nowIso = new Date(now).toISOString();
|
||||
const row = this.database.prepare(
|
||||
@@ -626,6 +689,48 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 9");
|
||||
});
|
||||
version = 9;
|
||||
}
|
||||
if (version === 9) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE ts_admin_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
||||
query_port INTEGER NOT NULL DEFAULT 10022 CHECK (query_port BETWEEN 1 AND 65535),
|
||||
username TEXT NOT NULL DEFAULT '',
|
||||
password_encrypted TEXT,
|
||||
host_key_fingerprint TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
this.database.prepare(
|
||||
`INSERT INTO ts_admin_settings (id, enabled, query_port, username, password_encrypted, host_key_fingerprint, updated_at)
|
||||
VALUES (1, 0, 10022, '', NULL, '', ?)`,
|
||||
).run(new Date().toISOString());
|
||||
this.database.exec("PRAGMA user_version = 10");
|
||||
});
|
||||
version = 10;
|
||||
}
|
||||
if (version === 10) {
|
||||
this.transaction(() => {
|
||||
this.database.exec("ALTER TABLE relay_nodes ADD COLUMN voice_endpoint TEXT NOT NULL DEFAULT ''");
|
||||
this.database.exec("PRAGMA user_version = 11");
|
||||
});
|
||||
version = 11;
|
||||
}
|
||||
if (version === 11) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE ts_admin_settings ADD COLUMN transport TEXT NOT NULL DEFAULT 'web' CHECK (transport IN ('web', 'ssh', 'tcp'));
|
||||
ALTER TABLE ts_admin_settings ADD COLUMN query_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE ts_admin_settings ADD COLUMN web_query_url TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE ts_admin_settings ADD COLUMN api_key_encrypted TEXT;
|
||||
ALTER TABLE ts_admin_settings ADD COLUMN server_id INTEGER NOT NULL DEFAULT 0 CHECK (server_id BETWEEN 0 AND 4294967295);
|
||||
UPDATE ts_admin_settings SET transport = 'ssh' WHERE enabled = 1 OR password_encrypted IS NOT NULL OR host_key_fingerprint <> '';
|
||||
PRAGMA user_version = 12;
|
||||
`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,20 +2,20 @@ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
|
||||
const ALGORITHM = "aes-256-gcm";
|
||||
const VERSION = "v1";
|
||||
const AAD = Buffer.from("webspeak:teamspeak-password:v1", "utf8");
|
||||
const DEFAULT_AAD = "webspeak:teamspeak-password:v1";
|
||||
|
||||
export function encryptSecret(value: string, masterKey: Buffer): string {
|
||||
export function encryptSecret(value: string, masterKey: Buffer, purpose = DEFAULT_AAD): string {
|
||||
if (!value) return "";
|
||||
assertMasterKey(masterKey);
|
||||
const nonce = randomBytes(12);
|
||||
const cipher = createCipheriv(ALGORITHM, masterKey, nonce);
|
||||
cipher.setAAD(AAD);
|
||||
cipher.setAAD(Buffer.from(purpose, "utf8"));
|
||||
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return [VERSION, nonce.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(":");
|
||||
}
|
||||
|
||||
export function decryptSecret(payload: string | null | undefined, masterKey: Buffer): string {
|
||||
export function decryptSecret(payload: string | null | undefined, masterKey: Buffer, purpose = DEFAULT_AAD): string {
|
||||
if (!payload) return "";
|
||||
assertMasterKey(masterKey);
|
||||
const [version, nonceText, tagText, ciphertextText, ...extra] = payload.split(":");
|
||||
@@ -23,7 +23,7 @@ export function decryptSecret(payload: string | null | undefined, masterKey: Buf
|
||||
throw new Error("Unsupported encrypted secret format");
|
||||
}
|
||||
const decipher = createDecipheriv(ALGORITHM, masterKey, Buffer.from(nonceText, "base64url"));
|
||||
decipher.setAAD(AAD);
|
||||
decipher.setAAD(Buffer.from(purpose, "utf8"));
|
||||
decipher.setAuthTag(Buffer.from(tagText, "base64url"));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(ciphertextText, "base64url")),
|
||||
|
||||
@@ -30,6 +30,8 @@ export interface AccelerationRelayOptions {
|
||||
export interface ConfiguredAccelerationRelay extends AccelerationRelayOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
/** HTTPS origin of the WebSpeak voice gateway on this relay node. */
|
||||
voiceEndpoint?: string;
|
||||
}
|
||||
|
||||
export interface AccelerationTarget {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { DirectoryClientInfo, DirectorySnapshot } from "@echosixhiya/teamspeak-client";
|
||||
import type { DirectoryClientInfo, DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
|
||||
function member(id: number, channelID = 1n, overrides: Partial<DirectoryClientInfo> = {}): DirectoryClientInfo {
|
||||
@@ -31,6 +31,15 @@ test("partial snapshots retain earlier clients and state omitted by a later snap
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n, { inputMuted: true }), member(2), member(3)]);
|
||||
});
|
||||
|
||||
test("complete SDK views remove unsubscribed clients instead of retaining them as partial welcome data", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot({ ...snapshot(member(1), member(2)), complete: true });
|
||||
directory.applySnapshot({ ...snapshot(member(1, 1n, { inputMuted: true })), complete: true });
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 1n, { inputMuted: true })]);
|
||||
directory.applySnapshot({ ...snapshot(member(1), member(2, 2n)), complete: true });
|
||||
assert.deepEqual(directory.getSnapshot()?.clients.map(client => client.id), [1, 2]);
|
||||
});
|
||||
|
||||
test("a stale partial snapshot cannot bring back a departed client before an explicit rejoin", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
@@ -28,6 +28,9 @@ export class DirectorySynchronizer {
|
||||
|
||||
applySnapshot(snapshot: TSDirectorySnapshot): void {
|
||||
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
|
||||
// A native SDK view is the complete visible roster. In particular, an
|
||||
// unsubscribe removes clients without individual leave notifications.
|
||||
if (snapshot.complete) this.clients.clear();
|
||||
for (const client of snapshot.clients) {
|
||||
if (this.departedClientIds.has(client.id)) continue;
|
||||
const previous = this.clients.get(client.id);
|
||||
|
||||
@@ -9,6 +9,20 @@ const directory = (): TSDirectorySnapshot => ({
|
||||
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
|
||||
});
|
||||
|
||||
test("permanent channel flags survive the gateway wire, without guessing omitted flags", () => {
|
||||
const source = directory();
|
||||
source.channels[0] = { ...source.channels[0], name: "[cspacer0]Section", isPermanent: true };
|
||||
source.channels[1] = { ...source.channels[1], isPermanent: false };
|
||||
const channels = mapChannelTree(source);
|
||||
const message = parseServerMessage(JSON.parse(JSON.stringify({ type: "channelList", channels })));
|
||||
assert.ok(message?.type === "channelList");
|
||||
assert.equal(message.channels[0].name, "[cspacer0]Section");
|
||||
assert.equal(message.channels[0].isPermanent, true);
|
||||
assert.equal(message.channels[1].isPermanent, false);
|
||||
assert.equal(Object.hasOwn(mapChannelTree(directory())[0], "isPermanent"), false);
|
||||
assert.equal(parseServerMessage({ type: "channelList", channels: [{ ...channels[0], isPermanent: "true" }] }), null);
|
||||
});
|
||||
|
||||
test("self restoration uses the connected channel before a snapshot or requested channel", () => {
|
||||
const source = directory();
|
||||
const result = normalizeDirectorySnapshot(source, 2, 18446744073709551615n, "Self", "Lobby");
|
||||
|
||||
@@ -12,6 +12,7 @@ export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new
|
||||
? { maxClients: channel.maxClients, maxClientsLimited: channel.maxClientsLimited }
|
||||
: {}),
|
||||
...(typeof channel.passwordProtected === "boolean" ? { passwordProtected: channel.passwordProtected } : {}),
|
||||
...(typeof channel.isPermanent === "boolean" ? { isPermanent: channel.isPermanent } : {}),
|
||||
members: snapshot.clients
|
||||
.filter((client) => client.channelID === channel.id)
|
||||
.map((client) => {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer as createPortProbe } from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { AdminService, type AdminSettingsInput } from "../admin/admin-service.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createWebServer } from "./server.js";
|
||||
import { createVoiceGatewayServer } from "./voice-gateway.js";
|
||||
|
||||
const noop = () => {};
|
||||
const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child: () => logger };
|
||||
|
||||
test("ingress keeps the page origin and delegates the voice ticket to the selected relay", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-relay-delegation-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const relayPort = await availablePort();
|
||||
const ingressPort = await availablePort();
|
||||
const relayToken = "integration-test-relay-token";
|
||||
const relayEndpoint = `http://127.0.0.1:${relayPort}`;
|
||||
const relay = createVoiceGatewayServer({
|
||||
host: "127.0.0.1",
|
||||
port: relayPort,
|
||||
sharedToken: relayToken,
|
||||
logger,
|
||||
webRtc: { enabled: false },
|
||||
});
|
||||
const service = new AdminService(
|
||||
database,
|
||||
Buffer.alloc(32, 7),
|
||||
logger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
async () => ({ ok: true, protocol: "ts3", latencyMs: 1, serverName: "Test", requiresPassword: false }),
|
||||
);
|
||||
const localTickets = new JoinTicketStore();
|
||||
const ingress = createWebServer({
|
||||
port: ingressPort,
|
||||
adminService: service,
|
||||
voiceBridgeOptions: { joinTickets: localTickets, acceleration: () => service.getAccelerationRelayOptions() },
|
||||
logger,
|
||||
});
|
||||
context.after(async () => {
|
||||
await ingress.stop();
|
||||
await relay.stop();
|
||||
database.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
await service.initialize();
|
||||
const settings: AdminSettingsInput = {
|
||||
target: "203.0.113.20#9987",
|
||||
accessMode: "fixed",
|
||||
siteName: "WebSpeak",
|
||||
welcomeText: "",
|
||||
webRtcEnabled: false,
|
||||
relayNodes: [{
|
||||
id: "de-relay",
|
||||
name: "Germany relay",
|
||||
target: "relay.example.com#39087",
|
||||
voiceEndpoint: relayEndpoint,
|
||||
enabled: true,
|
||||
token: relayToken,
|
||||
tokenAction: "replace",
|
||||
}],
|
||||
};
|
||||
service.updateSettings(settings);
|
||||
await relay.start();
|
||||
await ingress.start();
|
||||
|
||||
const origin = `http://127.0.0.1:${ingressPort}`;
|
||||
const response = await fetch(`${origin}/api/join-ticket`, {
|
||||
method: "POST",
|
||||
headers: { origin, "content-type": "application/json" },
|
||||
body: JSON.stringify({ nickname: "Tester", accelerated: true }),
|
||||
});
|
||||
assert.equal(response.status, 201);
|
||||
assert.equal(response.headers.get("cache-control"), "no-store");
|
||||
const result = await response.json() as { ticket?: string; voiceEndpoint?: string };
|
||||
assert.ok(result.ticket);
|
||||
assert.equal(result.voiceEndpoint, relayEndpoint);
|
||||
assert.equal(localTickets.consume(result.ticket!), null);
|
||||
});
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
const socket = createPortProbe();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = socket.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
|
||||
return address.port;
|
||||
}
|
||||
+41
-4
@@ -12,9 +12,10 @@ import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget, TeamSpeakTargetResolutionError } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
@@ -171,7 +172,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
let identity: string | undefined;
|
||||
if (requestedIdentity) {
|
||||
try {
|
||||
identityFromString(requestedIdentity);
|
||||
parseIdentity(requestedIdentity);
|
||||
identity = requestedIdentity;
|
||||
} catch {
|
||||
// A stale/corrupt local identity must not block a normal ephemeral join.
|
||||
@@ -235,13 +236,29 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
serverPassword = consumedInvite.serverPassword;
|
||||
}
|
||||
|
||||
const ticket = options.voiceBridgeOptions.joinTickets.create({
|
||||
const sessionPayload: DelegatedVoiceSession = {
|
||||
target,
|
||||
serverPassword,
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
|
||||
};
|
||||
const selectedRelay = accelerationRequested
|
||||
? requestedRelayId ? acceleration.find((relay) => relay.id === requestedRelayId) : acceleration[0]
|
||||
: undefined;
|
||||
if (selectedRelay?.voiceEndpoint) {
|
||||
try {
|
||||
const ticket = await createRemoteVoiceTicket(selectedRelay, sessionPayload);
|
||||
response.status(201).json({ ok: true, ticket, voiceEndpoint: selectedRelay.voiceEndpoint });
|
||||
return;
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ relayId: selectedRelay.id, err: error instanceof Error ? error.message : String(error) }, "Relay voice gateway ticket request failed; using legacy UDP acceleration");
|
||||
}
|
||||
}
|
||||
|
||||
const ticket = options.voiceBridgeOptions.joinTickets.create({
|
||||
...sessionPayload,
|
||||
...(accelerationRequested && selectedRelay ? { accelerated: true, accelerationRelayId: selectedRelay.id } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
@@ -298,6 +315,26 @@ function resolveAccelerationOptions(
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
async function createRemoteVoiceTicket(relay: ConfiguredAccelerationRelay, payload: DelegatedVoiceSession): Promise<string> {
|
||||
const endpoint = new URL("/api/relay/voice-ticket", relay.voiceEndpoint);
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...createVoiceGatewayAuthHeaders(relay.token, payload),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) throw new Error(`Relay voice gateway returned HTTP ${response.status}`);
|
||||
const result: unknown = await response.json().catch(() => null);
|
||||
if (!isRecord(result) || result.ok !== true || typeof result.ticket !== "string" || result.ticket.length < 16) {
|
||||
throw new Error("Relay voice gateway returned an invalid ticket");
|
||||
}
|
||||
return result.ticket;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import { SessionEventCoordinator, type SessionDirectoryState } from "./session-events.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { EventEmitter } from "node:events";
|
||||
import type { WebSpeakError } from "../errors.js";
|
||||
import type { ChannelInfo, ChannelMember } from "../shared/voice-models.js";
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { detectTeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
test("detects TeamSpeak 3 from the leading version number", () => {
|
||||
assert.equal(detectTeamSpeakProtocol("3.13.7 build=1645123456 platform=Linux"), "ts3");
|
||||
assert.equal(detectTeamSpeakProtocol("3.0.0"), "ts3");
|
||||
});
|
||||
|
||||
test("does not misclassify a TeamSpeak 3 minor as TeamSpeak 6", () => {
|
||||
assert.equal(detectTeamSpeakProtocol("3.6.7 build=1645123456 platform=Linux"), "ts3");
|
||||
assert.equal(detectTeamSpeakProtocol("3.6.0"), "ts3");
|
||||
assert.equal(detectTeamSpeakProtocol("3.16.0"), "ts3");
|
||||
});
|
||||
|
||||
test("detects TeamSpeak 6 from the leading version number or product name", () => {
|
||||
assert.equal(detectTeamSpeakProtocol("6.0.0-beta.1"), "ts6");
|
||||
assert.equal(detectTeamSpeakProtocol("6.2.0"), "ts6");
|
||||
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6.0.0"), "ts6");
|
||||
assert.equal(detectTeamSpeakProtocol("TeamSpeak 3 Server 3.13.7"), "ts3");
|
||||
});
|
||||
|
||||
test("returns null for unknown or unsupported version formats", () => {
|
||||
assert.equal(detectTeamSpeakProtocol(""), null);
|
||||
assert.equal(detectTeamSpeakProtocol("build=1645123456 platform=Linux"), null);
|
||||
assert.equal(detectTeamSpeakProtocol("5.0.0-beta"), null);
|
||||
assert.equal(detectTeamSpeakProtocol("7.0.0"), null);
|
||||
});
|
||||
@@ -1,10 +1,5 @@
|
||||
import {
|
||||
Client as TeamSpeakClient,
|
||||
generateIdentity,
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import { generateIdentitySync } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type Identity, type TeamSpeakClientOptions } from "./teamspeak-sdk.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -75,7 +70,7 @@ export interface TeamSpeakAdapterOptions {
|
||||
* successfully observed server generation for later connections.
|
||||
*/
|
||||
export class TeamSpeakAdapter {
|
||||
readonly client: TeamSpeakClient;
|
||||
readonly client: TeamSpeakSdkClient;
|
||||
readonly identity: Identity;
|
||||
private detectedProtocol: TeamSpeakProtocol | null = null;
|
||||
|
||||
@@ -84,9 +79,8 @@ export class TeamSpeakAdapter {
|
||||
private readonly logger: Logger,
|
||||
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
|
||||
) {
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
const clientOptions: ClientOptions = {
|
||||
resolver: new WebSpeakTeamSpeakResolver(),
|
||||
this.identity = options.identity ?? generateIdentitySync(8);
|
||||
const clientOptions: TeamSpeakClientOptions = {
|
||||
serverPassword: options.serverPassword,
|
||||
defaultChannel: options.defaultChannel,
|
||||
defaultChannelPassword: options.channelPassword,
|
||||
@@ -97,7 +91,7 @@ export class TeamSpeakAdapter {
|
||||
error: (msg: string) => this.logger.error(msg),
|
||||
},
|
||||
};
|
||||
this.client = new TeamSpeakClient(
|
||||
this.client = new TeamSpeakSdkClient(
|
||||
this.identity,
|
||||
formatTeamSpeakTarget(options.target),
|
||||
options.nickname,
|
||||
@@ -112,14 +106,14 @@ export class TeamSpeakAdapter {
|
||||
const cachedProtocol = this.protocolCache.get(this.target);
|
||||
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
|
||||
try {
|
||||
await this.client.connect();
|
||||
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
|
||||
await this.client.connect({ signal: AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS) });
|
||||
} catch (error: unknown) {
|
||||
await this.client.disconnect().catch(() => undefined);
|
||||
throw normalizeTeamSpeakError(error);
|
||||
}
|
||||
|
||||
const observedProtocol = await this.detectProtocol();
|
||||
const family = this.client.serverFamily;
|
||||
const observedProtocol = family === "ts3" || family === "ts6" ? family : null;
|
||||
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
|
||||
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
|
||||
}
|
||||
@@ -136,24 +130,17 @@ export class TeamSpeakAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
private async detectProtocol(): Promise<TeamSpeakProtocol | null> {
|
||||
try {
|
||||
const rows = await this.client.execCommandWithResponse("version", 3000);
|
||||
const versionText = rows
|
||||
.flatMap((row) => Object.values(row))
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.join(" ");
|
||||
return detectTeamSpeakProtocol(versionText);
|
||||
} catch {
|
||||
// Version discovery is an optimization; connection success is enough to proceed.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function detectTeamSpeakProtocol(versionText: string): TeamSpeakProtocol | null {
|
||||
const text = versionText.trim().toLocaleLowerCase();
|
||||
if (/teamspeak\s*6|(?:^|\D)6\.\d+/.test(text)) return "ts6";
|
||||
if (/teamspeak\s*3|(?:^|\D)3\.\d+/.test(text)) return "ts3";
|
||||
const text = versionText.trim().toLowerCase();
|
||||
// The `version` command starts with the server version, optionally preceded
|
||||
// by the product name. Match only that leading major version: scanning the
|
||||
// whole string mistakes TeamSpeak 3.6.7 for TeamSpeak 6.
|
||||
const match = /^(?:teamspeak\s*)?(\d+)/.exec(text);
|
||||
if (!match) return null;
|
||||
const major = Number(match[1]);
|
||||
if (major === 6) return "ts6";
|
||||
if (major === 3) return "ts3";
|
||||
return null;
|
||||
}
|
||||
@@ -130,11 +130,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
|
||||
});
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(file);
|
||||
legacy.exec("ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(file);
|
||||
try {
|
||||
assert.equal(migrated.schemaVersion, 9);
|
||||
assert.equal(migrated.schemaVersion, 12);
|
||||
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
|
||||
assert.equal(migrated.getSettings().tsTarget, null);
|
||||
const invite = migrated.consumeManagedInvite("legacy-token");
|
||||
|
||||
@@ -1,82 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
|
||||
|
||||
function fixedResolver(result: ResolvedAddr[], onResolve?: (signal?: AbortSignal) => void): AddrResolver {
|
||||
return {
|
||||
resolve: async (_address, signal) => {
|
||||
onResolve?.(signal);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("private short hostnames use local DNS directly without cloud nickname discovery", async () => {
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async (hostname) => {
|
||||
assert.equal(hostname, "teamspeak");
|
||||
return [{ address: "172.18.0.6", family: 4 }];
|
||||
},
|
||||
baseResolver: {
|
||||
resolve: async () => {
|
||||
baseCalls++;
|
||||
return [];
|
||||
},
|
||||
test("private short hostnames resolve locally before upstream discovery", async () => {
|
||||
let lookedUp = "";
|
||||
const address = await resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async (hostname) => {
|
||||
lookedUp = hostname;
|
||||
return [
|
||||
{ address: "203.0.113.4", family: 4 },
|
||||
{ address: "172.18.0.6", family: 4 },
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9988");
|
||||
assert.equal(result[0]?.addr, "172.18.0.6:9988");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseCalls, 0);
|
||||
assert.equal(lookedUp, "teamspeak");
|
||||
assert.equal(address, "172.18.0.6");
|
||||
});
|
||||
|
||||
test("undotted nickname discovery is bounded and falls back to the direct host", async () => {
|
||||
let baseSignal: AbortSignal | undefined;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => [],
|
||||
baseResolver: {
|
||||
resolve: async (_address, signal) => {
|
||||
baseSignal = signal;
|
||||
return new Promise<ResolvedAddr[]>(() => undefined);
|
||||
},
|
||||
},
|
||||
localAliasLookupTimeoutMs: 20,
|
||||
nicknameLookupTimeoutMs: 25,
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9987");
|
||||
assert.equal(result[0]?.addr, "teamspeak:9987");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseSignal?.aborted, true);
|
||||
});
|
||||
|
||||
test("dotted hostnames preserve the SDK resolver path", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "voice.example.com:9987", source: "Direct", expiry: new Date(0) }];
|
||||
test("public and dotted names are left to the upstream resolver", async () => {
|
||||
let lookupCalls = 0;
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => {
|
||||
assert.equal(await resolveLocalTeamSpeakAlias("public-alias", {
|
||||
lookup: async () => {
|
||||
lookupCalls++;
|
||||
return [];
|
||||
return [{ address: "203.0.113.4", family: 4 }];
|
||||
},
|
||||
baseResolver: fixedResolver(expected, () => { baseCalls++; }),
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("voice.example.com:9987"), expected);
|
||||
assert.equal(lookupCalls, 0);
|
||||
assert.equal(baseCalls, 1);
|
||||
}), undefined);
|
||||
assert.equal(await resolveLocalTeamSpeakAlias("voice.example.com", {
|
||||
lookup: async () => {
|
||||
lookupCalls++;
|
||||
return [{ address: "10.0.0.2", family: 4 }];
|
||||
},
|
||||
}), undefined);
|
||||
assert.equal(lookupCalls, 1);
|
||||
});
|
||||
|
||||
test("DNS resolution failures continue through bounded nickname discovery", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "public.example.com:9987", source: "Nickname", expiry: new Date(0) }];
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => { throw new Error("ENOTFOUND"); },
|
||||
baseResolver: fixedResolver(expected),
|
||||
nicknameLookupTimeoutMs: 100,
|
||||
test("a slow local lookup is bounded and falls through to upstream DNS", async () => {
|
||||
const result = await resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async () => new Promise(() => undefined),
|
||||
timeoutMs: 20,
|
||||
});
|
||||
assert.equal(result, undefined);
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("public-alias"), expected);
|
||||
test("aborting a local lookup preserves the connection cancellation", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new Error("connect cancelled");
|
||||
const pending = resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async () => new Promise(() => undefined),
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort(failure);
|
||||
await assert.rejects(pending, failure);
|
||||
});
|
||||
@@ -1,90 +1,15 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver as TeamSpeakResolver } from "@echosixhiya/teamspeak-client/discovery";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const LOCAL_ALIAS_LOOKUP_TIMEOUT_MS = 1_000;
|
||||
const NICKNAME_LOOKUP_TIMEOUT_MS = 3_000;
|
||||
|
||||
type LocalAddress = { address: string; family: number };
|
||||
type LocalLookup = (hostname: string) => Promise<LocalAddress[]>;
|
||||
|
||||
interface WebSpeakTeamSpeakResolverOptions {
|
||||
baseResolver?: AddrResolver;
|
||||
localLookup?: LocalLookup;
|
||||
localAliasLookupTimeoutMs?: number;
|
||||
nicknameLookupTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep TeamSpeak nickname discovery for normal names, while allowing an
|
||||
* internal short hostname (for example a Docker Compose service name) to use
|
||||
* the local resolver directly. Bound cloud nickname discovery so a network
|
||||
* black hole cannot prevent the SDK's direct-host fallback indefinitely.
|
||||
* Resolve an internal short hostname before the upstream SDK's SRV/TSDNS and
|
||||
* optional nickname resolution. Public hosts are left to the SDK's resolver.
|
||||
*/
|
||||
export class WebSpeakTeamSpeakResolver implements AddrResolver {
|
||||
private readonly baseResolver: AddrResolver;
|
||||
private readonly localLookup: LocalLookup;
|
||||
private readonly localAliasLookupTimeoutMs: number;
|
||||
private readonly nicknameLookupTimeoutMs: number;
|
||||
|
||||
constructor(options: WebSpeakTeamSpeakResolverOptions = {}) {
|
||||
this.baseResolver = options.baseResolver ?? new TeamSpeakResolver();
|
||||
this.localLookup = options.localLookup ?? ((hostname) => lookup(hostname, { all: true, verbatim: true }));
|
||||
this.localAliasLookupTimeoutMs = options.localAliasLookupTimeoutMs ?? LOCAL_ALIAS_LOOKUP_TIMEOUT_MS;
|
||||
this.nicknameLookupTimeoutMs = options.nicknameLookupTimeoutMs ?? NICKNAME_LOOKUP_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
async resolve(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
if (signal?.aborted) throw signal.reason ?? new Error("TeamSpeak address resolution was aborted");
|
||||
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(address);
|
||||
} catch {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const { host, port } = target;
|
||||
if (isIP(host) || host === "localhost" || host.includes(".")) {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const localAddress = await resolveLocalTeamSpeakAlias(host, {
|
||||
lookup: this.localLookup, timeoutMs: this.localAliasLookupTimeoutMs, signal,
|
||||
});
|
||||
if (localAddress) {
|
||||
return [directAddress(localAddress, port)];
|
||||
}
|
||||
|
||||
const baseResults = await this.resolveBaseWithTimeout(address, signal);
|
||||
return baseResults?.length ? baseResults : [directAddress(host, port)];
|
||||
}
|
||||
|
||||
private resolveBase(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
return this.baseResolver.resolve(address, signal);
|
||||
}
|
||||
|
||||
private async resolveBaseWithTimeout(address: string, signal?: AbortSignal): Promise<ResolvedAddr[] | null> {
|
||||
const timeoutController = new AbortController();
|
||||
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
||||
try {
|
||||
return await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.baseResolver.resolve(address, combinedSignal)),
|
||||
this.nicknameLookupTimeoutMs,
|
||||
signal,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
} finally {
|
||||
timeoutController.abort(new Error("TeamSpeak nickname lookup timed out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep Docker/service names local before attempting public nickname discovery. */
|
||||
export async function resolveLocalTeamSpeakAlias(
|
||||
host: string,
|
||||
options: { lookup?: LocalLookup; timeoutMs?: number; signal?: AbortSignal } = {},
|
||||
@@ -102,14 +27,6 @@ export async function resolveLocalTeamSpeakAlias(
|
||||
return addresses?.find(({ address }) => isPrivateNetworkAddress(address))?.address;
|
||||
}
|
||||
|
||||
function directAddress(host: string, port: number): ResolvedAddr {
|
||||
return {
|
||||
addr: formatTeamSpeakTarget({ host, port }),
|
||||
source: "Direct",
|
||||
expiry: new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
function isPrivateNetworkAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import test from "node:test";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
|
||||
const identity = generateIdentitySync(8);
|
||||
const uid = "AAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||
function channel(id = 1): Channel {
|
||||
return { id: asChannelID(BigInt(id)), parentID: asChannelID(0n), order: asChannelID(0n), name: "Lobby",
|
||||
description: "", hasPassword: true, isPermanent: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
|
||||
}
|
||||
function member(id = 1): ClientEntry {
|
||||
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
|
||||
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
|
||||
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
const native = Object.assign(new EventEmitter(), {
|
||||
view: {
|
||||
status: "live", revision: 1,
|
||||
channels: new Map([[asChannelID(1n), channel()]]),
|
||||
clients: new Map([[asClientID(1), member()]]),
|
||||
serverName: "Shanghai", serverIconID: undefined, serverBannerImageURL: "https://example.invalid/banner",
|
||||
server: { virtualserver_welcomemessage: "Welcome" },
|
||||
whenReady: async (_options?: { signal?: AbortSignal }) => {},
|
||||
},
|
||||
serverCapabilities: { family: "ts6", welcomeMessage: "Old welcome" },
|
||||
queries: [] as string[],
|
||||
async exec(command: string) { this.queries.push(command); throw new Error("insufficient client permissions (code 2568)"); },
|
||||
});
|
||||
const state = sdk as unknown as { sdkClient: Client | null; attachUpstreamEvents(client: Client): void };
|
||||
state.sdkClient = native as unknown as Client;
|
||||
state.attachUpstreamEvents(native as unknown as Client);
|
||||
return { sdk, native, state };
|
||||
}
|
||||
|
||||
test("ordinary-client directories and avatar metadata use the live view without list permissions", async () => {
|
||||
const { sdk, native } = fixture();
|
||||
assert.deepEqual(await sdk.listDirectoryChannels(), [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "",
|
||||
passwordProtected: true, isPermanent: true, maxClients: 12, maxClientsLimited: true }]);
|
||||
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: "Member 1", uid, channelID: 1n, type: 0,
|
||||
serverGroups: [], away: true, awayMessage: "Away", inputMuted: true, outputMuted: false, channelCommander: true }]);
|
||||
assert.deepEqual(await sdk.getClientAvatarMetadata(1), { uid, cacheKey: "avatar-hash", path: `/${avatarFileName(uid)}` });
|
||||
assert.equal(await sdk.getClientAvatarMetadata(2), null);
|
||||
assert.deepEqual(sdk.serverInfo, { name: "Shanghai", iconId: null, hostBannerGfxUrl: "https://example.invalid/banner", welcomeMessage: "Welcome" });
|
||||
assert.equal(sdk.serverFamily, "ts6");
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
|
||||
const { sdk, native } = fixture();
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
native.emit("viewReady");
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.length, 1, "an unchanged revision does not duplicate the directory");
|
||||
assert.equal(snapshots[0]?.complete, true);
|
||||
native.view.clients.clear();
|
||||
native.view.channels.set(asChannelID(1n), { ...channel(), name: "Renamed", hasPassword: false, isPermanent: false, maxClients: 20 });
|
||||
native.view.revision++;
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.name, "Renamed");
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, false);
|
||||
assert.equal(snapshots[0]?.channels[0]?.isPermanent, true);
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.isPermanent, false);
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 20);
|
||||
assert.deepEqual(snapshots.at(-1)?.clients, []);
|
||||
assert.equal(snapshots[0]?.clients.length, 1, "earlier snapshots stay independent");
|
||||
native.view.status = "stale";
|
||||
native.view.revision++;
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.length, 2, "a stale view cannot initialize a session");
|
||||
});
|
||||
|
||||
test("member status changes use the SDK's current record and retired views cannot publish", async () => {
|
||||
const { sdk, native, state } = fixture();
|
||||
const updates: unknown[] = [];
|
||||
const snapshots: unknown[] = [];
|
||||
sdk.on("clientUpdated", update => updates.push(update));
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
native.view.clients.set(asClientID(1), { ...member(), isInputMuted: false, isOutputMuted: true, isAway: false });
|
||||
native.emit("clientUpdated", { clientID: asClientID(1), changes: { isInputMuted: false } });
|
||||
assert.equal((updates[0] as { info: { inputMuted: boolean } }).info.inputMuted, false);
|
||||
assert.equal((updates[0] as { info: { outputMuted: boolean } }).info.outputMuted, true);
|
||||
state.sdkClient = null;
|
||||
native.emit("viewChanged");
|
||||
native.emit("clientUpdated", { clientID: asClientID(1) });
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(snapshots.length, 0);
|
||||
state.sdkClient = native as unknown as Client;
|
||||
native.view.status = "stale";
|
||||
await assert.rejects(sdk.listDirectoryChannels(), /view is not ready/);
|
||||
});
|
||||
|
||||
test("connect waits for the welcome view and propagates its connection deadline", async t => {
|
||||
const { native } = fixture();
|
||||
native.view.status = "loading";
|
||||
let welcome!: () => void;
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
native.view.whenReady = options => {
|
||||
observedSignal = options?.signal;
|
||||
return new Promise<void>(resolve => { welcome = resolve; });
|
||||
};
|
||||
t.mock.method(Client.prototype, "connect", async () => {});
|
||||
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
const controller = new AbortController();
|
||||
let connected = false;
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
const pending = sdk.connect({ signal: controller.signal }).then(() => { connected = true; });
|
||||
await nextTurn();
|
||||
assert.equal(connected, false, "handshake success alone is not a usable directory");
|
||||
assert.equal(observedSignal, controller.signal);
|
||||
native.view.status = "live";
|
||||
welcome();
|
||||
await pending;
|
||||
assert.equal(connected, true);
|
||||
assert.equal(snapshots.length, 1);
|
||||
assert.equal(snapshots[0]?.clients[0]?.id, 1);
|
||||
});
|
||||
|
||||
test("an interrupted welcome rejects connect instead of leaving initialization pending", async t => {
|
||||
const { native } = fixture();
|
||||
const failure = new Error("welcome connection deadline");
|
||||
native.view.status = "loading";
|
||||
native.view.whenReady = async options => { options?.signal?.throwIfAborted(); };
|
||||
t.mock.method(Client.prototype, "connect", async () => {});
|
||||
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
await assert.rejects(sdk.connect({ signal: AbortSignal.abort(failure) }), error => error === failure);
|
||||
});
|
||||
@@ -0,0 +1,341 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { Writable } from "node:stream";
|
||||
import {
|
||||
asChannelID,
|
||||
asClientID,
|
||||
avatarFileName,
|
||||
initFileDownload,
|
||||
moveClient,
|
||||
pokeClient,
|
||||
sendChannelMessage,
|
||||
sendPrivateMessage,
|
||||
sendServerMessage,
|
||||
type Channel,
|
||||
type ClientEntry,
|
||||
type Codec,
|
||||
type CommandExecutor,
|
||||
type FileDownloadInfo,
|
||||
type ServerFamily,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import { Client, type ClientOptions, type Identity } from "@honeybbq/teamspeak/client";
|
||||
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export type { Identity };
|
||||
export type TeamSpeakClientOptions = Pick<ClientOptions, "serverPassword" | "defaultChannel" | "defaultChannelPassword" | "logger">;
|
||||
|
||||
export interface ClientInfo {
|
||||
id: number;
|
||||
nickname: string;
|
||||
uid: string;
|
||||
serverGroups: string[];
|
||||
channelID: bigint;
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface DirectoryClientInfo extends ClientInfo {
|
||||
away?: boolean;
|
||||
awayMessage?: string;
|
||||
inputMuted?: boolean;
|
||||
outputMuted?: boolean;
|
||||
channelCommander?: boolean;
|
||||
}
|
||||
|
||||
export interface DirectoryChannelInfo {
|
||||
id: bigint;
|
||||
parentID: bigint;
|
||||
order: bigint;
|
||||
name: string;
|
||||
description: string;
|
||||
passwordProtected?: boolean;
|
||||
isPermanent?: boolean;
|
||||
maxClients?: number;
|
||||
maxClientsLimited?: boolean;
|
||||
}
|
||||
|
||||
export interface DirectorySnapshot {
|
||||
channels: DirectoryChannelInfo[];
|
||||
clients: DirectoryClientInfo[];
|
||||
/** The SDK's live view replaces the visible roster, including unsubscribed clients. */
|
||||
complete?: boolean;
|
||||
}
|
||||
|
||||
export interface RawNotification {
|
||||
name: string;
|
||||
params: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface VoiceData {
|
||||
clientId: number;
|
||||
codec: number;
|
||||
data: Uint8Array;
|
||||
}
|
||||
|
||||
export interface TextMessage {
|
||||
invokerName: string;
|
||||
invokerUID: string;
|
||||
message: string;
|
||||
invokerGroups: readonly bigint[] | undefined;
|
||||
targetMode: number;
|
||||
targetID: bigint;
|
||||
invokerID: number;
|
||||
}
|
||||
|
||||
export interface ServerInfo {
|
||||
name: string;
|
||||
iconId: number | null;
|
||||
hostBannerGfxUrl: string | null;
|
||||
welcomeMessage: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A narrow compatibility boundary for WebSpeak's old fork-specific SDK events.
|
||||
* Wire I/O and command execution are provided by the upstream 1.0 client; this
|
||||
* class only translates names and shapes that WebSpeak already consumes.
|
||||
*/
|
||||
export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor {
|
||||
private sdkClient: Client | null = null;
|
||||
private directoryRevision = -1;
|
||||
|
||||
constructor(
|
||||
private readonly identity: Identity,
|
||||
private readonly address: string,
|
||||
private readonly nickname: string,
|
||||
private readonly options: TeamSpeakClientOptions,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
get status(): string | number {
|
||||
return this.sdkClient?.status ?? 0;
|
||||
}
|
||||
|
||||
get serverInfo(): ServerInfo | null {
|
||||
const client = this.sdkClient;
|
||||
return client
|
||||
? {
|
||||
name: client.view.serverName,
|
||||
iconId: client.view.serverIconID ?? null,
|
||||
hostBannerGfxUrl: client.view.serverBannerImageURL ?? null,
|
||||
welcomeMessage: client.view.server.virtualserver_welcomemessage ?? client.serverCapabilities.welcomeMessage,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
get serverFamily(): ServerFamily {
|
||||
return this.sdkClient?.serverCapabilities.family ?? "unknown";
|
||||
}
|
||||
|
||||
async connect(options: { signal?: AbortSignal } = {}): Promise<void> {
|
||||
this.directoryRevision = -1;
|
||||
const target = parseTeamSpeakTarget(this.address);
|
||||
const localAlias = await resolveLocalTeamSpeakAlias(target.host, { signal: options.signal });
|
||||
const address = localAlias ? formatTeamSpeakTarget({ host: localAlias, port: target.port }) : this.address;
|
||||
const client = new Client(this.identity, address, this.nickname, {
|
||||
...this.options,
|
||||
// Preserve TeamSpeak nickname addresses. The upstream resolver bounds
|
||||
// the full SRV/TSDNS/nickname lookup and falls back to the given address.
|
||||
nicknameLookup: true,
|
||||
});
|
||||
this.sdkClient = client;
|
||||
this.attachUpstreamEvents(client);
|
||||
await client.connect(options);
|
||||
// connect() accepts the session before the welcome directory is complete.
|
||||
// Share its cancellation/deadline instead of waiting forever for a snapshot.
|
||||
await client.view.whenReady(options);
|
||||
this.publishDirectory(client);
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
await this.sdkClient?.disconnect();
|
||||
}
|
||||
|
||||
async send(request: Parameters<CommandExecutor["send"]>[0], options?: Parameters<CommandExecutor["send"]>[1]) {
|
||||
return this.requireClient().send(request, options);
|
||||
}
|
||||
|
||||
async exec(command: string, options?: { signal?: AbortSignal; timeoutMs?: number }) {
|
||||
return this.requireClient().exec(command, options);
|
||||
}
|
||||
|
||||
clientID(): number {
|
||||
return Number(this.sdkClient?.clientID ?? 0);
|
||||
}
|
||||
|
||||
channelID(): bigint {
|
||||
return this.sdkClient?.channelID ?? 0n;
|
||||
}
|
||||
|
||||
async execCommand(command: string, timeoutMs?: number): Promise<void> {
|
||||
await this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
|
||||
}
|
||||
|
||||
async execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]> {
|
||||
return this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
|
||||
}
|
||||
|
||||
sendVoice(data: Uint8Array, codec: number): void {
|
||||
this.requireClient().sendVoice(data, codec as Codec);
|
||||
}
|
||||
|
||||
sendWhisper(data: Uint8Array, clientIds: number[], codec: number): void {
|
||||
this.requireClient().sendWhisper(data, { clients: clientIds.map(asClientID) }, codec as Codec);
|
||||
}
|
||||
|
||||
async fileTransferInitDownload(channelID: bigint, path: string, password: string): Promise<FileDownloadInfo> {
|
||||
return initFileDownload(this, asChannelID(channelID), path, { password });
|
||||
}
|
||||
|
||||
async downloadFileData(host: string, info: FileDownloadInfo, destination: Writable): Promise<void> {
|
||||
await this.requireClient().downloadFileData(host, info, destination);
|
||||
}
|
||||
|
||||
async listDirectoryChannels(): Promise<DirectoryChannelInfo[]> {
|
||||
return this.readDirectory().channels;
|
||||
}
|
||||
|
||||
async listDirectoryClients(): Promise<DirectoryClientInfo[]> {
|
||||
return this.readDirectory().clients;
|
||||
}
|
||||
|
||||
async getClientAvatarMetadata(clientId: number): Promise<{ uid: string; cacheKey: string; path: string } | null> {
|
||||
const info = this.requireClient().view.clients.get(asClientID(clientId));
|
||||
if (!info?.uid || !info.avatar) return null;
|
||||
return { uid: info.uid, cacheKey: info.avatar, path: `/${avatarFileName(info.uid)}` };
|
||||
}
|
||||
|
||||
private readDirectory(): DirectorySnapshot {
|
||||
const view = this.requireClient().view;
|
||||
if (view.status !== "live") throw new Error("TeamSpeak directory view is not ready");
|
||||
return {
|
||||
channels: [...view.channels.values()].map(toDirectoryChannel),
|
||||
clients: [...view.clients.values()].map(toDirectoryClient),
|
||||
complete: true,
|
||||
};
|
||||
}
|
||||
|
||||
private publishDirectory(client: Client): void {
|
||||
if (this.sdkClient !== client || client.view.status !== "live" || client.view.revision === this.directoryRevision) return;
|
||||
this.directoryRevision = client.view.revision;
|
||||
this.emit("directorySnapshot", this.readDirectory());
|
||||
}
|
||||
|
||||
private requireClient(): Client {
|
||||
if (!this.sdkClient) throw new Error("TeamSpeak session is not ready");
|
||||
return this.sdkClient;
|
||||
}
|
||||
|
||||
private attachUpstreamEvents(client: Client): void {
|
||||
const isCurrent = () => this.sdkClient === client;
|
||||
client.on("viewReady", () => this.publishDirectory(client));
|
||||
client.on("viewChanged", () => this.publishDirectory(client));
|
||||
client.on("voiceData", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
|
||||
});
|
||||
client.on("textMessage", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("textMessage", {
|
||||
...event,
|
||||
invokerGroups: event.invokerGroups,
|
||||
targetID: BigInt(event.targetID),
|
||||
invokerID: Number(event.invokerID),
|
||||
} satisfies TextMessage);
|
||||
});
|
||||
client.on("poked", (event) => { if (isCurrent()) this.emit("poked", event); });
|
||||
client.on("clientEnter", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("clientEnter", toDirectoryClient(event));
|
||||
});
|
||||
client.on("clientUpdated", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const info = client.view.clients.get(event.clientID);
|
||||
if (info) this.emit("clientUpdated", { info: toDirectoryClient(info) });
|
||||
});
|
||||
client.on("clientLeave", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(event.clientID);
|
||||
this.emit("clientLeave", {
|
||||
id,
|
||||
reasonID: event.reason,
|
||||
reasonMsg: event.reasonMessage,
|
||||
targetID: id,
|
||||
});
|
||||
});
|
||||
client.on("clientMoved", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(event.clientID);
|
||||
this.emit("clientMoved", {
|
||||
id,
|
||||
targetChannelID: BigInt(event.targetChannelID),
|
||||
reasonID: event.reason,
|
||||
invokerID: Number(event.invokerID),
|
||||
invokerUID: event.invokerUID,
|
||||
invokerName: event.invokerName,
|
||||
});
|
||||
});
|
||||
client.on("kicked", (event) => { if (isCurrent()) this.emit("kicked", event.reasonMessage); });
|
||||
client.on("disconnected", (event) => { if (isCurrent()) this.emit("disconnected", event.error); });
|
||||
client.on("notification", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const notification = { name: event.name, params: { ...event.params } } satisfies RawNotification;
|
||||
this.emit("rawNotification", notification);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function listChannelsCompat(client: TeamSpeakSdkClient): Promise<DirectoryChannelInfo[]> {
|
||||
return client.listDirectoryChannels();
|
||||
}
|
||||
|
||||
export async function listClientsCompat(client: TeamSpeakSdkClient): Promise<DirectoryClientInfo[]> {
|
||||
return client.listDirectoryClients();
|
||||
}
|
||||
|
||||
export async function moveClientCompat(client: TeamSpeakSdkClient, clientId: number, channelId: bigint, password?: string): Promise<void> {
|
||||
await moveClient(client, asClientID(clientId), asChannelID(channelId), { password });
|
||||
}
|
||||
|
||||
export async function sendTextMessageCompat(client: TeamSpeakSdkClient, mode: number, targetId: bigint, message: string): Promise<void> {
|
||||
if (mode === 1) await sendPrivateMessage(client, asClientID(Number(targetId)), message);
|
||||
else if (mode === 2) await sendChannelMessage(client, message);
|
||||
else await sendServerMessage(client, message);
|
||||
}
|
||||
|
||||
export async function pokeCompat(client: TeamSpeakSdkClient, clientId: number, message: string): Promise<void> {
|
||||
await pokeClient(client, asClientID(clientId), message);
|
||||
}
|
||||
|
||||
export type { Channel, ClientEntry };
|
||||
|
||||
function toDirectoryChannel(channel: Channel): DirectoryChannelInfo {
|
||||
return {
|
||||
id: BigInt(channel.id),
|
||||
parentID: BigInt(channel.parentID),
|
||||
order: BigInt(channel.order),
|
||||
name: channel.name,
|
||||
description: channel.description,
|
||||
passwordProtected: channel.hasPassword,
|
||||
...(typeof channel.isPermanent === "boolean" ? { isPermanent: channel.isPermanent } : {}),
|
||||
...(Number.isInteger(channel.maxClients) && channel.maxClients >= 0 && channel.maxClients <= 65_535
|
||||
&& typeof channel.isMaxClientsUnlimited === "boolean"
|
||||
? { maxClients: channel.maxClients, maxClientsLimited: !channel.isMaxClientsUnlimited }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
|
||||
return {
|
||||
id: Number(entry.id),
|
||||
nickname: entry.nickname,
|
||||
uid: entry.uid,
|
||||
serverGroups: entry.serverGroups.map(String),
|
||||
channelID: BigInt(entry.channelID),
|
||||
type: entry.type,
|
||||
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
|
||||
...(entry.awayMessage !== undefined ? { awayMessage: entry.awayMessage } : {}),
|
||||
...(entry.isInputMuted !== undefined ? { inputMuted: entry.isInputMuted } : {}),
|
||||
...(entry.isOutputMuted !== undefined ? { outputMuted: entry.isOutputMuted } : {}),
|
||||
...(entry.isChannelCommander !== undefined ? { channelCommander: entry.isChannelCommander } : {}),
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import test from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { Writable } from "node:stream";
|
||||
import type { CommandRequest } from "@honeybbq/teamspeak";
|
||||
import pino from "pino";
|
||||
import { TSClient } from "./ts-client.js";
|
||||
|
||||
@@ -22,10 +23,24 @@ class SdkStub extends EventEmitter {
|
||||
name: "兄弟们的teamspeak", iconId: 123456, hostBannerGfxUrl: null, welcomeMessage: "",
|
||||
};
|
||||
inputUpdate = async (_command: string): Promise<void> => {};
|
||||
async send(request: CommandRequest) {
|
||||
const command = [request.command, ...(request.params ?? []).map(([key, value]) => `${key}=${String(value ?? "")}`)].join(" ");
|
||||
this.inputCommands.push(command);
|
||||
await this.inputUpdate(command);
|
||||
return [];
|
||||
}
|
||||
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
|
||||
clientID() { return 1; }
|
||||
channelID() { return 1n; }
|
||||
async listDirectoryChannels() { return [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "", passwordProtected: true }]; }
|
||||
async listDirectoryClients() { return [{ id: 1, nickname: "Test", uid: "self", channelID: 1n, type: 0, serverGroups: [] as string[], inputMuted: true }]; }
|
||||
initialized = 0;
|
||||
downloaded = 0;
|
||||
metadata = async () => rows;
|
||||
async getClientAvatarMetadata() {
|
||||
const [info] = await this.metadata();
|
||||
return info ? { uid: info.client_unique_identifier, cacheKey: info.client_flag_avatar, path: `/avatar_${info.client_base64HashClientUID}` } : null;
|
||||
}
|
||||
transfer = async () => transfer;
|
||||
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
|
||||
execCommandWithResponse(command = "") {
|
||||
@@ -50,6 +65,34 @@ function fixture() {
|
||||
return { client, sdk, state };
|
||||
}
|
||||
|
||||
test("normal startup publishes the subscribed native directory without privileged list queries", async () => {
|
||||
const f = fixture();
|
||||
f.state.connected = false;
|
||||
const state = f.client as unknown as { adapter: { connect(): Promise<void> } };
|
||||
state.adapter = { connect: async () => {} };
|
||||
const snapshots: Array<{ complete?: boolean; clients: Array<{ id: number; inputMuted?: boolean }> }> = [];
|
||||
f.client.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
await f.client.connect();
|
||||
assert.equal(f.client.isConnected(), true);
|
||||
assert.equal(snapshots.at(-1)?.complete, true);
|
||||
assert.equal(snapshots.at(-1)?.clients[0]?.id, 1);
|
||||
assert.equal(snapshots.at(-1)?.clients[0]?.inputMuted, true);
|
||||
assert.deepEqual(f.sdk.inputCommands, ["channelsubscribeall"]);
|
||||
});
|
||||
|
||||
test("a missing native view fails startup instead of leaving a connected session without a directory", async () => {
|
||||
const f = fixture();
|
||||
f.state.connected = false;
|
||||
const state = f.client as unknown as { adapter: { connect(): Promise<void> } };
|
||||
state.adapter = { connect: async () => {} };
|
||||
f.sdk.listDirectoryChannels = async () => { throw new Error("TeamSpeak directory view is not ready"); };
|
||||
let published = false;
|
||||
f.client.on("connected", () => { published = true; });
|
||||
await assert.rejects(f.client.connect(), /view is not ready/);
|
||||
assert.equal(f.client.isConnected(), false);
|
||||
assert.equal(published, false);
|
||||
});
|
||||
|
||||
test("stream commands wait for server acknowledgement and propagate refusals", async () => {
|
||||
const f = fixture();
|
||||
const ack = deferred<void>();
|
||||
|
||||
+45
-79
@@ -1,20 +1,26 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Writable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
clientMove as tsClientMove,
|
||||
listChannels as tsListChannels,
|
||||
listClients as tsListClients,
|
||||
poke as tsPoke,
|
||||
sendTextMessage as tsSendTextMessage,
|
||||
generateIdentity,
|
||||
type Identity,
|
||||
type VoiceData,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type RawNotification,
|
||||
type TextMessage,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
generateIdentitySync,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
import type {
|
||||
ClientInfo,
|
||||
DirectoryChannelInfo,
|
||||
DirectoryClientInfo,
|
||||
DirectorySnapshot,
|
||||
Identity,
|
||||
RawNotification,
|
||||
TextMessage,
|
||||
VoiceData,
|
||||
} from "./teamspeak-sdk.js";
|
||||
import {
|
||||
listChannelsCompat as tsListChannels,
|
||||
listClientsCompat as tsListClients,
|
||||
moveClientCompat as tsClientMove,
|
||||
pokeCompat as tsPoke,
|
||||
sendTextMessageCompat as tsSendTextMessage,
|
||||
TeamSpeakSdkClient,
|
||||
} from "./teamspeak-sdk.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
@@ -23,8 +29,6 @@ import { createAccelerationRelayClient, type AccelerationRelayClient, type Accel
|
||||
import {
|
||||
applyChannelCapacityNotification,
|
||||
applyChannelPasswordProtectionNotification,
|
||||
parseChannelCapacities,
|
||||
parseChannelPasswordProtections,
|
||||
type ChannelCapacity,
|
||||
type ChannelPasswordProtection,
|
||||
} from "./channel-capacity.js";
|
||||
@@ -69,7 +73,7 @@ const MAX_SERVER_ICON_BYTES = 128 * 1024;
|
||||
const MAX_SERVER_BANNER_URL_LENGTH = 2_048;
|
||||
const MAX_SERVER_WELCOME_MESSAGE_LENGTH = 4_096;
|
||||
|
||||
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity> & Partial<ChannelPasswordProtection>;
|
||||
export type TSDirectoryChannel = DirectoryChannelInfo & Partial<ChannelCapacity> & Partial<ChannelPasswordProtection>;
|
||||
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
export type TSRawNotification = RawNotification;
|
||||
@@ -102,7 +106,7 @@ export function toTSChatMessage(msg: TextMessage): TSChatMessage {
|
||||
}
|
||||
|
||||
export class TSClient extends EventEmitter {
|
||||
private client: TS3FullClient | null = null;
|
||||
private client: TeamSpeakSdkClient | null = null;
|
||||
private adapter: TeamSpeakAdapter | null = null;
|
||||
private logger: Logger;
|
||||
private readonly identity: Identity;
|
||||
@@ -125,7 +129,7 @@ export class TSClient extends EventEmitter {
|
||||
constructor(private options: TSClientOptions, logger: Logger) {
|
||||
super();
|
||||
this.logger = logger.child({ nickname: options.nickname });
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
this.identity = options.identity ?? generateIdentitySync(8);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,47 +203,16 @@ export class TSClient extends EventEmitter {
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not subscribe to all TeamSpeak channels");
|
||||
}
|
||||
// Directory snapshots are dispatched through two setImmediate layers in
|
||||
// the SDK. Let both flush before reconciling with a direct client-protocol
|
||||
// snapshot so the gateway's first connected state contains every member.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
// TS6 can finish the welcome event stream before it has exposed every
|
||||
// existing client to a newly connected session. Pull one authoritative
|
||||
// snapshot through this same client protocol session so users who joined
|
||||
// earlier are visible immediately as well. Realtime events continue to
|
||||
// keep the snapshot current after this reconciliation.
|
||||
try {
|
||||
const [channels, clients] = await Promise.all([
|
||||
tsListChannels(client),
|
||||
tsListClients(client),
|
||||
]);
|
||||
try {
|
||||
// The high-level SDK directory type intentionally omits channel limit
|
||||
// metadata. Its raw client-protocol rows still include the public
|
||||
// maximum-client properties, so retain those without another SDK API.
|
||||
// TeamSpeak only includes channel flag fields (including the public
|
||||
// password-required bit) when the client asks for flags explicitly.
|
||||
const rows = await client.execCommandWithResponse("channellist -flags", 5_000);
|
||||
const capacities = parseChannelCapacities(rows);
|
||||
for (const [id, capacity] of capacities) this.channelCapacities.set(id, capacity);
|
||||
for (const [id, passwordProtected] of parseChannelPasswordProtections(rows)) {
|
||||
this.channelPasswordProtection.set(id, passwordProtected);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not read TeamSpeak channel limits");
|
||||
}
|
||||
this.emit("directorySnapshot", {
|
||||
channels: this.applyChannelMetadata(channels),
|
||||
clients,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
|
||||
failureDetail: error instanceof Error ? error.message : String(error),
|
||||
}, "TeamSpeak directory snapshot unavailable");
|
||||
}
|
||||
// The upstream live view contains the welcome and subscription data,
|
||||
// including channel limits and member status. Reading it needs no list
|
||||
// permissions; a failure must fail initialization instead of parking the
|
||||
// browser in `syncing` forever.
|
||||
const [channels, clients] = await Promise.all([tsListChannels(client), tsListClients(client)]);
|
||||
this.emit("directorySnapshot", {
|
||||
channels: this.applyChannelMetadata(channels),
|
||||
clients,
|
||||
complete: true,
|
||||
} satisfies TSDirectorySnapshot);
|
||||
|
||||
const connectedChannelId = client.channelID();
|
||||
if (this.preferredChannelId === 0n) {
|
||||
@@ -284,9 +257,9 @@ export class TSClient extends EventEmitter {
|
||||
/**
|
||||
* 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.
|
||||
* The SDK's live view supplies the avatar marker and identity. Its public
|
||||
* avatar filename helper handles TS3/TS6 identities; the image is 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.
|
||||
@@ -297,18 +270,11 @@ export class TSClient extends EventEmitter {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
const generation = this.connectionGeneration;
|
||||
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
|
||||
const rows = await client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
|
||||
const info = await client.getClientAvatarMetadata(clientId);
|
||||
if (!isCurrent()) return null;
|
||||
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 client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
|
||||
if (!info || expectedUid && info.uid !== expectedUid) return null;
|
||||
const cacheKey = info.cacheKey;
|
||||
const transfer = await client.fileTransferInitDownload(0n, info.path, "");
|
||||
if (!isCurrent()) return null;
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
@@ -380,7 +346,7 @@ export class TSClient extends EventEmitter {
|
||||
return data;
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
private attachClientListeners(client: TeamSpeakSdkClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
if (this.client !== client) return;
|
||||
this.emit("voiceData", {
|
||||
@@ -390,12 +356,12 @@ export class TSClient extends EventEmitter {
|
||||
} as TSVoiceData);
|
||||
});
|
||||
|
||||
// The SDK exposes the directory that TeamSpeak sends during the normal
|
||||
// client welcome sequence. The connect path also reconciles this event
|
||||
// stream with a complete client-protocol snapshot.
|
||||
// The SDK publishes its native live view after the welcome and whenever
|
||||
// the visible channels or members change.
|
||||
client.on("directorySnapshot", (snapshot) => {
|
||||
if (this.client !== client) return;
|
||||
this.emit("directorySnapshot", {
|
||||
complete: snapshot.complete,
|
||||
channels: this.applyChannelMetadata(snapshot.channels),
|
||||
clients: snapshot.clients.slice(),
|
||||
});
|
||||
@@ -625,7 +591,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
return this.identity.export();
|
||||
}
|
||||
|
||||
getChannelId(): bigint {
|
||||
|
||||
@@ -79,7 +79,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
if (overrides.waitForFirstMessage !== false) await first;
|
||||
const entries = (bridge as unknown as { entries: Map<string, {
|
||||
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
|
||||
isAlive: boolean; avatarCache: Map<string, string | null>;
|
||||
isAlive: boolean; lastPongAt: number; missedHeartbeats: number; avatarCache: Map<string, string | null>;
|
||||
members: Map<number, { id: number; uid: string }>; eventLog: unknown[];
|
||||
}> }).entries;
|
||||
return { bridge, sdk, socket, messages, entries, wss };
|
||||
@@ -304,6 +304,44 @@ async function avatarFixture(t: TestContext) {
|
||||
return { ...f, calls, release: () => release(avatar), entry: [...f.entries.values()][0]! };
|
||||
}
|
||||
|
||||
test("a single missed WebSocket heartbeat is retried and a pong resets the miss count", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const bridge = f.bridge as unknown as { checkHeartbeats(): void };
|
||||
// Suppress the network ping so this test can advance heartbeat ticks directly.
|
||||
entry.ws.ping = (() => {}) as typeof entry.ws.ping;
|
||||
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.isAlive, false);
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.missedHeartbeats, 1);
|
||||
assert.equal(entry.ws.readyState, WebSocket.OPEN);
|
||||
|
||||
const previousPongAt = entry.lastPongAt;
|
||||
entry.ws.emit("pong", Buffer.alloc(0));
|
||||
assert.equal(entry.isAlive, true);
|
||||
assert.equal(entry.missedHeartbeats, 0);
|
||||
assert.ok(entry.lastPongAt >= previousPongAt);
|
||||
});
|
||||
|
||||
test("two consecutive missed WebSocket heartbeats terminate the stale session", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const bridge = f.bridge as unknown as { checkHeartbeats(): void };
|
||||
entry.ws.ping = (() => {}) as typeof entry.ws.ping;
|
||||
|
||||
const closed = once(f.socket, "close");
|
||||
bridge.checkHeartbeats();
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.ws.readyState, WebSocket.OPEN);
|
||||
assert.equal(entry.missedHeartbeats, 1);
|
||||
|
||||
bridge.checkHeartbeats();
|
||||
await closed;
|
||||
await nextTurn();
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("avatar completion after teardown cannot refill the cache or start another SDK request", { timeout: 5_000 }, async t => {
|
||||
const f = await avatarFixture(t);
|
||||
await f.bridge.terminateSession(f.entry.id);
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
@@ -164,6 +164,16 @@ test("a current peer construction failure reports a recoverable negotiation erro
|
||||
assert.deepEqual(f.messages, [{ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" }]);
|
||||
});
|
||||
|
||||
test("WebRTC candidates use the voice gateway host when the page Origin belongs to another gateway", () => {
|
||||
const request = {
|
||||
headers: {
|
||||
origin: "https://ingress.example.com",
|
||||
host: "voice-relay.example.com:3041",
|
||||
},
|
||||
} as IncomingMessage;
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
|
||||
});
|
||||
|
||||
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
|
||||
const f = fixture();
|
||||
const inputs: Array<[string, boolean]> = [];
|
||||
|
||||
+67
-16
@@ -12,7 +12,7 @@ import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js";
|
||||
@@ -29,6 +29,17 @@ import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
const MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH = 160;
|
||||
|
||||
function sanitizeWebSocketCloseReason(reason: Buffer): string {
|
||||
return reason.toString("utf8")
|
||||
.replace(/[\u0000-\u001f\u007f]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH);
|
||||
}
|
||||
|
||||
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
|
||||
const serverMessage = error.diagnostics.serverMessage?.trim();
|
||||
const serverId = error.diagnostics.id?.trim();
|
||||
@@ -86,6 +97,8 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
eventLog: ServerEvent[];
|
||||
audioTransport: SessionAudioTransport | null;
|
||||
isAlive: boolean;
|
||||
lastPongAt: number;
|
||||
missedHeartbeats: number;
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
@@ -161,7 +174,7 @@ export class VoiceBridge {
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? identityFromString(connection.identity) : undefined;
|
||||
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
|
||||
} catch {
|
||||
// Send a structured failure before the close so the browser can tell
|
||||
// an invalid remembered identity apart from a real connection failure.
|
||||
@@ -235,6 +248,8 @@ export class VoiceBridge {
|
||||
whisperTargetIds: new Set(),
|
||||
whisperActive: false,
|
||||
isAlive: true,
|
||||
lastPongAt: Date.now(),
|
||||
missedHeartbeats: 0,
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
@@ -475,7 +490,7 @@ export class VoiceBridge {
|
||||
sendJson, addEvent: addServerEvent, onDirectoryReady: sendInitialState,
|
||||
onClientLeave: id => {
|
||||
this.screenShares.onClientLeave(entry!, id);
|
||||
entry!.webrtc?.setMemberVolume(id, 1);
|
||||
entry!.webrtc?.removeClient(id);
|
||||
},
|
||||
onClientMove: (id, channelId) => this.screenShares.onClientMove(entry!, id, channelId),
|
||||
onNotification: notification => this.screenShares.handleNotification(entry!, notification),
|
||||
@@ -536,7 +551,12 @@ export class VoiceBridge {
|
||||
});
|
||||
entry.events = events;
|
||||
|
||||
ws.on("pong", () => { if (entry) entry.isAlive = true; });
|
||||
ws.on("pong", () => {
|
||||
if (!entry) return;
|
||||
entry.isAlive = true;
|
||||
entry.lastPongAt = Date.now();
|
||||
entry.missedHeartbeats = 0;
|
||||
});
|
||||
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
|
||||
if (this.entries.get(entryId) !== entry) return;
|
||||
if (isBinary) {
|
||||
@@ -588,8 +608,19 @@ export class VoiceBridge {
|
||||
void handleCommand(entry!, command, sendJson);
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
this.logger.info({ entryId }, "WebSocket closed");
|
||||
ws.on("close", (code, reason) => {
|
||||
const closedAt = Date.now();
|
||||
this.logger.info({
|
||||
entryId,
|
||||
closeCode: code,
|
||||
closeReason: sanitizeWebSocketCloseReason(reason),
|
||||
abnormalClose: code === 1006,
|
||||
...(entry ? {
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs: Math.max(0, closedAt - entry.lastPongAt),
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
} : {}),
|
||||
}, "WebSocket closed");
|
||||
void this.teardown(entryId, "websocket-close");
|
||||
});
|
||||
|
||||
@@ -712,6 +743,9 @@ export class VoiceBridge {
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
...(entry.accelerationRelay ? { relayName: entry.accelerationRelay.name, relayTarget: entry.accelerationRelay.target } : {}),
|
||||
reason,
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs: Math.max(0, Date.now() - entry.lastPongAt),
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
...(entry.connectionFailureCode ? { failureCode: entry.connectionFailureCode } : {}),
|
||||
durationSeconds: Math.max(0, Math.floor((Date.now() - entry.session.createdAt) / 1000)),
|
||||
audio: { ...entry.audio },
|
||||
@@ -720,19 +754,33 @@ export class VoiceBridge {
|
||||
|
||||
private startHeartbeat(): void {
|
||||
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
if (!entry.isAlive) {
|
||||
this.heartbeatTimer = setInterval(() => this.checkHeartbeats(), HEARTBEAT_INTERVAL_MS);
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
|
||||
private checkHeartbeats(): void {
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
if (!entry.isAlive) {
|
||||
entry.missedHeartbeats += 1;
|
||||
const lastPongAgeMs = Math.max(0, Date.now() - entry.lastPongAt);
|
||||
const timedOut = entry.missedHeartbeats >= MAX_MISSED_HEARTBEATS;
|
||||
this.logger.warn({
|
||||
entryId: entry.id,
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
maxMissedHeartbeats: MAX_MISSED_HEARTBEATS,
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs,
|
||||
}, timedOut ? "WebSocket heartbeat timed out" : "WebSocket heartbeat missed; retrying");
|
||||
if (timedOut) {
|
||||
entry.ws.terminate();
|
||||
void this.teardown(entry.id, "heartbeat-timeout");
|
||||
continue;
|
||||
}
|
||||
entry.isAlive = false;
|
||||
entry.ws.ping();
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
this.heartbeatTimer.unref?.();
|
||||
entry.isAlive = false;
|
||||
entry.ws.ping();
|
||||
}
|
||||
}
|
||||
|
||||
private resolveConnection(url: URL): JoinTicketPayload | null {
|
||||
@@ -845,11 +893,14 @@ export class VoiceBridge {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
const origin = firstHeader(request.headers.origin);
|
||||
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
|
||||
const directHost = firstHeader(request.headers.host);
|
||||
for (const candidate of [origin, forwardedHost, directHost]) {
|
||||
// The page can be hosted on the ingress gateway while its voice socket is
|
||||
// connected to a different relay node. ICE candidates must name the socket's
|
||||
// gateway, not the page's Origin.
|
||||
for (const candidate of [forwardedHost, directHost, origin]) {
|
||||
const host = normalizeWebRtcHost(candidate);
|
||||
if (host) return host;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createVoiceGatewayAuthHeaders, parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice-gateway-auth.js";
|
||||
|
||||
const secret = "relay-auth-secret-long-enough";
|
||||
const payload = {
|
||||
target: { host: "ts.example.invalid", port: 9987 },
|
||||
nickname: "Browser user",
|
||||
serverPassword: "secret",
|
||||
rememberIdentity: true,
|
||||
};
|
||||
|
||||
test("voice gateway request authentication is canonical, time-limited and single-use", () => {
|
||||
const now = 1_800_000_000_000;
|
||||
const headers = createVoiceGatewayAuthHeaders(secret, payload, now, "a".repeat(32));
|
||||
const verifier = new VoiceGatewayRequestVerifier();
|
||||
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: headers["x-webspeak-relay-timestamp"],
|
||||
nonce: headers["x-webspeak-relay-nonce"],
|
||||
signature: headers["x-webspeak-relay-signature"],
|
||||
}, { serverPassword: "secret", nickname: "Browser user", rememberIdentity: true, target: { port: 9987, host: "ts.example.invalid" } }, now), true);
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: headers["x-webspeak-relay-timestamp"],
|
||||
nonce: headers["x-webspeak-relay-nonce"],
|
||||
signature: headers["x-webspeak-relay-signature"],
|
||||
}, payload, now), false, "replayed nonces must be rejected");
|
||||
|
||||
const stale = createVoiceGatewayAuthHeaders(secret, payload, now - 31_000, "b".repeat(32));
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: stale["x-webspeak-relay-timestamp"],
|
||||
nonce: stale["x-webspeak-relay-nonce"],
|
||||
signature: stale["x-webspeak-relay-signature"],
|
||||
}, payload, now), false, "old signed requests must expire");
|
||||
});
|
||||
|
||||
test("delegated voice session parser accepts only bounded TeamSpeak session data", () => {
|
||||
assert.deepEqual(parseDelegatedVoiceSession(payload), {
|
||||
target: { host: "ts.example.invalid", port: 9987 },
|
||||
serverPassword: "secret",
|
||||
nickname: "Browser user",
|
||||
rememberIdentity: true,
|
||||
});
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, target: { host: "127.0.0.1/path", port: 9987 } }), null);
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, nickname: "" }), null);
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, serverPassword: "x".repeat(513) }), null);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const MAX_CLOCK_SKEW_MS = 30_000;
|
||||
const NONCE_TTL_MS = MAX_CLOCK_SKEW_MS * 2;
|
||||
const MAX_NONCES = 10_000;
|
||||
|
||||
export interface DelegatedVoiceSession {
|
||||
target: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
nickname: string;
|
||||
channel?: string;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
}
|
||||
|
||||
export interface VoiceGatewayAuthHeaders {
|
||||
"x-webspeak-relay-timestamp": string;
|
||||
"x-webspeak-relay-nonce": string;
|
||||
"x-webspeak-relay-signature": string;
|
||||
}
|
||||
|
||||
export function createVoiceGatewayAuthHeaders(
|
||||
secret: string,
|
||||
body: unknown,
|
||||
now = Date.now(),
|
||||
nonce = randomBytes(16).toString("hex"),
|
||||
): VoiceGatewayAuthHeaders {
|
||||
const timestamp = String(now);
|
||||
return {
|
||||
"x-webspeak-relay-timestamp": timestamp,
|
||||
"x-webspeak-relay-nonce": nonce,
|
||||
"x-webspeak-relay-signature": signature(secret, timestamp, nonce, body),
|
||||
};
|
||||
}
|
||||
|
||||
/** Verifies short-lived, one-use requests from a configured gateway. */
|
||||
export class VoiceGatewayRequestVerifier {
|
||||
private readonly usedNonces = new Map<string, number>();
|
||||
|
||||
verify(
|
||||
secret: string,
|
||||
headers: { timestamp: string | undefined; nonce: string | undefined; signature: string | undefined },
|
||||
body: unknown,
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (secret.length < 16 || !headers.timestamp || !headers.nonce || !headers.signature) return false;
|
||||
if (!/^\d{10,16}$/.test(headers.timestamp) || !/^[a-f\d]{32}$/i.test(headers.nonce) || !/^[a-f\d]{64}$/i.test(headers.signature)) return false;
|
||||
const timestamp = Number(headers.timestamp);
|
||||
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > MAX_CLOCK_SKEW_MS) return false;
|
||||
|
||||
this.prune(now);
|
||||
if (this.usedNonces.has(headers.nonce) || this.usedNonces.size >= MAX_NONCES) return false;
|
||||
|
||||
const expected = Buffer.from(signature(secret, headers.timestamp, headers.nonce, body), "hex");
|
||||
const received = Buffer.from(headers.signature, "hex");
|
||||
if (expected.length !== received.length || !timingSafeEqual(expected, received)) return false;
|
||||
|
||||
this.usedNonces.set(headers.nonce, timestamp + NONCE_TTL_MS);
|
||||
return true;
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [nonce, expiresAt] of this.usedNonces) {
|
||||
if (expiresAt <= now) this.usedNonces.delete(nonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseDelegatedVoiceSession(value: unknown): DelegatedVoiceSession | null {
|
||||
if (!isRecord(value) || !isRecord(value.target)) return null;
|
||||
const { host, port } = value.target;
|
||||
if (typeof host !== "string" || host.length < 1 || host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(host)) return null;
|
||||
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
if (typeof value.serverPassword !== "string" || value.serverPassword.length > 512) return null;
|
||||
if (typeof value.nickname !== "string" || !value.nickname.trim() || value.nickname.length > 30) return null;
|
||||
if (value.channel !== undefined && (typeof value.channel !== "string" || value.channel.length > 100)) return null;
|
||||
if (value.identity !== undefined && (typeof value.identity !== "string" || value.identity.length > 8192)) return null;
|
||||
if (value.rememberIdentity !== undefined && typeof value.rememberIdentity !== "boolean") return null;
|
||||
|
||||
return {
|
||||
target: { host, port },
|
||||
serverPassword: value.serverPassword,
|
||||
nickname: value.nickname.trim(),
|
||||
...(typeof value.channel === "string" && value.channel ? { channel: value.channel } : {}),
|
||||
...(typeof value.identity === "string" && value.identity ? { identity: value.identity } : {}),
|
||||
...(value.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function signature(secret: string, timestamp: string, nonce: string, body: unknown): string {
|
||||
return createHmac("sha256", Buffer.from(secret, "utf8"))
|
||||
.update(timestamp)
|
||||
.update("\n")
|
||||
.update(nonce)
|
||||
.update("\n")
|
||||
.update(canonicalJson(body))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
||||
const record = value as Record<string, unknown>;
|
||||
const fields = Object.keys(record).filter(key => record[key] !== undefined).sort();
|
||||
return `{${fields.map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import pino from "pino";
|
||||
import { createVoiceGatewayServer } from "./voice-gateway.js";
|
||||
import { createVoiceGatewayAuthHeaders } from "./voice-gateway-auth.js";
|
||||
|
||||
test("voice relay gateway issues a one-time join ticket only for signed session requests", async t => {
|
||||
const sharedToken = "relay-shared-token-that-is-long-enough";
|
||||
const gateway = createVoiceGatewayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
sharedToken,
|
||||
logger: pino({ enabled: false }),
|
||||
webRtc: { enabled: true },
|
||||
});
|
||||
const address = await gateway.start();
|
||||
t.after(() => gateway.stop());
|
||||
const url = `http://127.0.0.1:${address.port}/api/relay/voice-ticket`;
|
||||
const payload = {
|
||||
target: { host: "voice.example.invalid", port: 9987 },
|
||||
serverPassword: "secret",
|
||||
nickname: "Visitor",
|
||||
rememberIdentity: true,
|
||||
};
|
||||
const headers = createVoiceGatewayAuthHeaders(sharedToken, payload);
|
||||
const request = () => fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const accepted = await request();
|
||||
assert.equal(accepted.status, 201);
|
||||
const body = await accepted.json() as { ok?: boolean; ticket?: string };
|
||||
assert.equal(body.ok, true);
|
||||
assert.equal(typeof body.ticket, "string");
|
||||
assert.ok((body.ticket?.length ?? 0) >= 32);
|
||||
assert.equal(accepted.headers.get("cache-control"), "no-store");
|
||||
assert.equal((await request()).status, 401, "the signed request nonce cannot be replayed");
|
||||
|
||||
const invalidPayload = { ...payload, nickname: "" };
|
||||
const invalidHeaders = createVoiceGatewayAuthHeaders(sharedToken, invalidPayload);
|
||||
const invalid = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...invalidHeaders },
|
||||
body: JSON.stringify(invalidPayload),
|
||||
});
|
||||
assert.equal(invalid.status, 400);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { createServer } from "node:http";
|
||||
import express from "express";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice-gateway-auth.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { ScreenShareIceServer } from "./screen-share.js";
|
||||
|
||||
export interface VoiceGatewayServerOptions {
|
||||
host: string;
|
||||
port: number;
|
||||
sharedToken: string;
|
||||
logger: Logger;
|
||||
webRtc: WebRtcAudioOptions;
|
||||
screenShareIceServers?: ScreenShareIceServer[];
|
||||
trustedProxies?: readonly string[];
|
||||
}
|
||||
|
||||
export interface VoiceGatewayServer {
|
||||
start(): Promise<{ host: string; port: number }>;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): VoiceGatewayServer {
|
||||
if (options.sharedToken.trim().length < 16) throw new Error("Voice gateway token must contain at least 16 characters");
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "16kb" }));
|
||||
const tickets = new JoinTicketStore();
|
||||
const verifier = new VoiceGatewayRequestVerifier();
|
||||
const voiceBridgeOptions: VoiceBridgeOptions = {
|
||||
joinTickets: tickets,
|
||||
webRtc: options.webRtc,
|
||||
screenShareIceServers: options.screenShareIceServers,
|
||||
trustedProxies: options.trustedProxies,
|
||||
};
|
||||
const bridge = new VoiceBridge(voiceBridgeOptions, options.logger);
|
||||
const server = createServer(app);
|
||||
|
||||
app.get("/health", (_request, response) => response.json({ status: "ok", role: "voice-gateway" }));
|
||||
app.post("/api/relay/voice-ticket", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json")) {
|
||||
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const authenticated = verifier.verify(options.sharedToken, {
|
||||
timestamp: request.get("x-webspeak-relay-timestamp"),
|
||||
nonce: request.get("x-webspeak-relay-nonce"),
|
||||
signature: request.get("x-webspeak-relay-signature"),
|
||||
}, request.body);
|
||||
if (!authenticated) {
|
||||
response.status(401).json({ ok: false, code: "RELAY_AUTH_REJECTED" });
|
||||
return;
|
||||
}
|
||||
const session = parseDelegatedVoiceSession(request.body);
|
||||
if (!session) {
|
||||
response.status(400).json({ ok: false, code: "RELAY_SESSION_INVALID" });
|
||||
return;
|
||||
}
|
||||
response.status(201).json({ ok: true, ticket: tickets.create(session) });
|
||||
});
|
||||
|
||||
bridge.attach(server);
|
||||
|
||||
return {
|
||||
start(): Promise<{ host: string; port: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error): void => {
|
||||
server.off("listening", onListening);
|
||||
reject(error);
|
||||
};
|
||||
const onListening = (): void => {
|
||||
server.off("error", onError);
|
||||
const address = server.address();
|
||||
resolve({ host: options.host, port: typeof address === "object" && address ? address.port : options.port });
|
||||
};
|
||||
server.once("error", onError);
|
||||
server.once("listening", onListening);
|
||||
server.listen(options.port, options.host);
|
||||
});
|
||||
},
|
||||
async stop(): Promise<void> {
|
||||
await bridge.shutdown();
|
||||
await new Promise<void>((resolve) => {
|
||||
if (!server.listening) { resolve(); return; }
|
||||
server.close(() => resolve());
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -201,3 +201,35 @@ test("an unavailable mixer encoder closes the half-built peer before the constru
|
||||
}
|
||||
assert.equal(closedPeers.size, 1, "the constructor must roll back the peer it already created");
|
||||
});
|
||||
|
||||
test("removeClient releases only the leaving speaker's decoder and buffered state", () => {
|
||||
const f = fixture();
|
||||
f.resources.pendingFrames.set(2, []);
|
||||
f.resources.memberVolumes.set(2, 0.5);
|
||||
f.resources.partialPcmByClient.set(2, Buffer.alloc(2));
|
||||
f.resources.activeSpeakerIds.add(2);
|
||||
|
||||
f.session.removeClient(1);
|
||||
|
||||
assert.deepEqual(f.released, ["decoder-1"]);
|
||||
assert.equal(f.resources.decoderByClient.has(1), false);
|
||||
assert.equal(f.resources.pendingFrames.has(1), false);
|
||||
assert.equal(f.resources.partialPcmByClient.has(1), false);
|
||||
assert.equal(f.resources.memberVolumes.has(1), false);
|
||||
assert.equal(f.resources.activeSpeakerIds.has(1), false);
|
||||
assert.equal(f.resources.decoderByClient.has(2), true);
|
||||
assert.equal(f.resources.pendingFrames.has(2), true);
|
||||
assert.equal(f.resources.partialPcmByClient.has(2), true);
|
||||
assert.equal(f.resources.memberVolumes.has(2), true);
|
||||
assert.equal(f.resources.activeSpeakerIds.has(2), true);
|
||||
});
|
||||
|
||||
test("removeClient is idempotent and tolerates a throwing decoder disposal", () => {
|
||||
const f = fixture();
|
||||
|
||||
f.session.removeClient(1);
|
||||
f.session.removeClient(1);
|
||||
|
||||
assert.deepEqual(f.released, ["decoder-1"]);
|
||||
assert.equal(f.resources.decoderByClient.has(1), false);
|
||||
});
|
||||
@@ -441,6 +441,18 @@ export class WebRtcAudioSession {
|
||||
else this.memberVolumes.set(clientId, normalized);
|
||||
}
|
||||
|
||||
removeClient(clientId: number): void {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) return;
|
||||
this.pendingFrames.delete(clientId);
|
||||
this.partialPcmByClient.delete(clientId);
|
||||
this.memberVolumes.delete(clientId);
|
||||
this.activeSpeakerIds.delete(clientId);
|
||||
const decoder = this.decoderByClient.get(clientId);
|
||||
if (!decoder) return;
|
||||
this.decoderByClient.delete(clientId);
|
||||
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
|
||||
}
|
||||
|
||||
private calculateRms(pcm: Buffer): number {
|
||||
let sum = 0;
|
||||
let samples = 0;
|
||||
|
||||
@@ -28,6 +28,8 @@ export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
/** HTTPS origin of the WebSpeak voice gateway hosted on this relay. */
|
||||
voiceEndpoint?: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
@@ -38,3 +40,36 @@ export interface ManagedInviteInput {
|
||||
expiresInHours: number;
|
||||
maxUses: number;
|
||||
}
|
||||
|
||||
export interface TsAdminSettingsInput {
|
||||
enabled: boolean;
|
||||
transport?: "web" | "ssh" | "tcp";
|
||||
queryHost?: string;
|
||||
webQueryUrl?: string;
|
||||
apiKey?: string;
|
||||
apiKeyAction?: "keep" | "replace" | "remove";
|
||||
/** 0 selects the fixed instance by its voice port. */
|
||||
serverId?: number;
|
||||
queryPort: number;
|
||||
username: string;
|
||||
password?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
hostKeyFingerprint: string;
|
||||
}
|
||||
|
||||
export type TsAdminAction =
|
||||
| { action: "server.update"; name: string; welcomeMessage: string; maxClients: number }
|
||||
| { action: "channel.create"; name: string; parentId: string; description: string; permanent: boolean; password?: string }
|
||||
| { action: "channel.update"; channelId: string; name: string }
|
||||
| { action: "channel.delete"; channelId: string }
|
||||
| { action: "client.move"; clientId: number; clientUid: string; channelId: string }
|
||||
| { action: "client.kick"; clientId: number; clientUid: string; reason: string }
|
||||
| { action: "client.ban"; clientId: number; clientUid: string; reason: string; durationSeconds: number }
|
||||
| { action: "client.group"; clientId: number; clientUid: string; groupId: string; remove: boolean }
|
||||
| { action: "ban.delete"; banId: string };
|
||||
|
||||
export interface TsAdminActionRequest {
|
||||
/** Revision of the management configuration used to read the selected objects. */
|
||||
configurationRevision: string;
|
||||
operation: TsAdminAction;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ function object<T extends Record<string, Reader>>(fields: T): AdminResponseReade
|
||||
}
|
||||
|
||||
const auditEvent = object({ event: text, createdAt: text });
|
||||
const relayNode = object({ id: text, name: text, enabled: boolean, target: text, hasToken: boolean });
|
||||
const relayNode = object({ id: text, name: text, enabled: boolean, target: text, voiceEndpoint: text, hasToken: boolean });
|
||||
const welcomeTexts = object({ zh: text, en: text, de: text, ru: text, ja: text });
|
||||
const settings = object({
|
||||
target: text, hasPassword: boolean, accessMode: choice("fixed", "open"), siteName: text,
|
||||
@@ -64,6 +64,34 @@ const skin = object({
|
||||
description: optional(text), previewUrl: optional(text), previewMimeType: optional(text),
|
||||
builtIn: optional(boolean), enabled: optional(boolean), previewKind: optional(choice("day", "night", "illusia")),
|
||||
});
|
||||
const storeMetadata = object({
|
||||
schemaVersion: value => value === 1 ? 1 as const : invalid(),
|
||||
id: text, name: text, version: text, author: text, license: text, description: text, minAppVersion: text,
|
||||
package: object({ ref: text, path: text, sha256: text }),
|
||||
});
|
||||
const skinStore = object({
|
||||
repository: text, appVersion: text, fetchedAt: number,
|
||||
entries: array(object({ id: text, repository: text, metadata: nullable(storeMetadata), revision: text, compatible: boolean, error: nullable(text) })),
|
||||
});
|
||||
const tsAdminSettings = object({
|
||||
configurationRevision: text,
|
||||
fixedMode: boolean, enabled: boolean, queryPort: number, username: text,
|
||||
transport: choice("web", "ssh", "tcp"), queryHost: text, webQueryUrl: text, serverId: number, hasApiKey: boolean,
|
||||
hasPassword: boolean, hostKeyFingerprint: text, updatedAt: text,
|
||||
});
|
||||
const tsAdminOverview = object({
|
||||
configurationRevision: text,
|
||||
serverName: text, serverVersion: text, serverFamily: choice("ts3", "ts6", "unknown"),
|
||||
channelCount: number, clientCount: number,
|
||||
welcomeMessage: text, maxClients: number, uptimeSeconds: number,
|
||||
channels: array(object({ id: text, parentID: text, name: text, description: text, totalClients: number, hasPassword: boolean })),
|
||||
clients: array(object({ id: number, uid: text, nickname: text, channelID: text, serverGroups: array(text), away: boolean, inputMuted: boolean, outputMuted: boolean })),
|
||||
groups: array(object({ id: text, name: text })), groupsAvailable: boolean, bansAvailable: boolean,
|
||||
groupsErrorCode: optional(nullable(text)), bansErrorCode: optional(nullable(text)),
|
||||
bans: array(object({ id: text, name: text, uid: text, reason: text, durationSeconds: number, createdAt: nullable(text) })),
|
||||
observedAt: text,
|
||||
});
|
||||
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
|
||||
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
|
||||
|
||||
export const adminResponses = {
|
||||
@@ -87,6 +115,10 @@ export const adminResponses = {
|
||||
database: object({ schemaVersion: number }), sessions: object({ created: number }),
|
||||
}),
|
||||
skins: object({ skins: array(skin), defaultSkinId: text }),
|
||||
skinStore,
|
||||
tsAdminSettings,
|
||||
savedTsAdminSettings,
|
||||
tsAdminOverview,
|
||||
defaultSkin: object({ ok: choice(true), defaultSkinId: text }),
|
||||
updatedSkin: object({ ok: choice(true), skin, defaultSkinId: text }),
|
||||
uploadedSkin: object({ ok: choice(true), skin }),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ChannelInfo } from "./voice-models.js";
|
||||
|
||||
export interface ChannelSpacer {
|
||||
text: string;
|
||||
alignment: "left" | "center" | "right" | "repeat";
|
||||
style: "text" | "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot";
|
||||
}
|
||||
|
||||
const LINE_STYLES: Readonly<Record<string, ChannelSpacer["style"]>> = {
|
||||
"___": "solid", "---": "dashed", "...": "dotted", "-.-": "dash-dot", "-..": "dash-dot-dot",
|
||||
};
|
||||
|
||||
/** Spacers are a presentation convention for permanent, root-level TS channels. */
|
||||
export function getChannelSpacer(channel: Pick<ChannelInfo, "name" | "parentID" | "isPermanent">): ChannelSpacer | null {
|
||||
if (channel.parentID !== "0" || channel.isPermanent !== true) return null;
|
||||
const match = /^\[([clr*]?)spacer[^\]\r\n]*\]([\s\S]*)$/i.exec(channel.name);
|
||||
if (!match) return null;
|
||||
const text = match[2];
|
||||
const alignment = ({ c: "center", r: "right", "*": "repeat" } as const)[match[1].toLowerCase() as "c" | "r" | "*"] ?? "left";
|
||||
return { text, alignment, style: Object.hasOwn(LINE_STYLES, text) ? LINE_STYLES[text] : "text" };
|
||||
}
|
||||
|
||||
export function channelDisplayName(channel: Pick<ChannelInfo, "name" | "parentID" | "isPermanent">): string {
|
||||
return getChannelSpacer(channel)?.text ?? channel.name;
|
||||
}
|
||||
@@ -73,6 +73,7 @@ function channel(value: unknown): value is ChannelInfo {
|
||||
&& optional(value.maxClients, maximum => finite(maximum) && Number.isInteger(maximum) && maximum >= 0 && maximum <= 65_535)
|
||||
&& optional(value.maxClientsLimited, boolean)
|
||||
&& optional(value.passwordProtected, boolean)
|
||||
&& optional(value.isPermanent, boolean)
|
||||
&& (value.maxClients === undefined) === (value.maxClientsLimited === undefined)
|
||||
&& optional(value.members, members => arrayOf(members, member));
|
||||
}
|
||||
|
||||
@@ -192,6 +192,7 @@ const PUBLIC_PART_IDS = new Set<string>([
|
||||
"voice.breadcrumbs",
|
||||
"voice.channel-group",
|
||||
"voice.channel-group.heading",
|
||||
"voice.channel-spacer",
|
||||
"voice.channel-group.members",
|
||||
"voice.channel-tree.avatar",
|
||||
"voice.channel-tree.branch",
|
||||
@@ -239,6 +240,10 @@ const PUBLIC_PART_IDS = new Set<string>([
|
||||
"voice.chat.tab",
|
||||
"voice.chat.tabs",
|
||||
"voice.connection-status",
|
||||
"voice.connection-status.message",
|
||||
"voice.connection-status.nickname",
|
||||
"voice.connection-status.nickname.input",
|
||||
"voice.connection-status.reconnect",
|
||||
"voice.content",
|
||||
"voice.context-menu",
|
||||
"voice.context-menu-backdrop",
|
||||
@@ -370,6 +375,7 @@ const ACTION_PART_IDS = new Set([
|
||||
"voice.channel-tree.expander", "voice.channel-tree.row", "demo.skin-switcher", "demo.language-switcher",
|
||||
]);
|
||||
const INTERACTIVE_PART_IDS = new Set([
|
||||
"voice.connection-status.nickname.input", "voice.connection-status.reconnect",
|
||||
"demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select",
|
||||
"demo.chat.input", "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss",
|
||||
"demo.reconnect.restore", "home.connect", "home.favorite-toggle", "home.identity-export.button",
|
||||
|
||||
@@ -32,6 +32,7 @@ export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({
|
||||
"audio.settings.open": Object.freeze({ policyVersion: 1, description: "Open WebSpeak's trusted audio device and processing settings." }),
|
||||
"voice.presence.write": Object.freeze({ policyVersion: 1, description: "Set the user's own away status through the connected TeamSpeak session." }),
|
||||
"voice.whisper.control": Object.freeze({ policyVersion: 1, description: "Enable or disable the user's existing TeamSpeak whisper target selection." }),
|
||||
"voice.connect": Object.freeze({ policyVersion: 1, description: "Connect to the host-selected TeamSpeak target after an explicit user action; the skin cannot provide addresses or credentials." }),
|
||||
"voice.disconnect": Object.freeze({ policyVersion: 1, description: "Disconnect the user's current TeamSpeak voice session." }),
|
||||
"voice.whisper.status.read": Object.freeze({ policyVersion: 1, description: "Read whether whisper is active and how many existing targets are selected." }),
|
||||
"voice.screenShare.status.read": Object.freeze({ policyVersion: 1, description: "Read the user's own screen-share state." }),
|
||||
@@ -63,6 +64,7 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
|
||||
"voice.screen-share-start",
|
||||
"voice.whisper-controls",
|
||||
"voice.performance-panel",
|
||||
"voice.connection-status",
|
||||
"voice.connection-controls",
|
||||
"voice.disconnect-control",
|
||||
] as const);
|
||||
@@ -90,6 +92,7 @@ export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostW
|
||||
"voice.server-banner": widgetPermissions("session.status.read"),
|
||||
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
|
||||
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
|
||||
"voice.connection-status": widgetPermissions("session.status.read", "voice.connect"),
|
||||
"voice.connection-controls": widgetPermissions("voice.disconnect"),
|
||||
"voice.disconnect-control": widgetPermissions("voice.disconnect"),
|
||||
"voice.member-cards": widgetPermissions("session.members.read", "session.memberAvatars.read", "voice.screenShare.read", "voice.screenShare.control"),
|
||||
@@ -123,7 +126,7 @@ export type SkinPluginAction =
|
||||
| "voice.joinChannel" | "favorites.switch" | "quickServers.switch" | "chat.sendMessage" | "chat.togglePanel"
|
||||
| "voice.toggleMicrophone" | "voice.toggleOutputMute" | "voice.setOutputVolume" | "audio.openSettings"
|
||||
| "audio.toggleNoiseSuppression" | "audio.toggleAccompaniment"
|
||||
| "voice.disconnect" | "voice.setAway" | "voice.setWhisperActive"
|
||||
| "voice.connect" | "voice.disconnect" | "voice.setAway" | "voice.setWhisperActive"
|
||||
| "voice.startScreenShare" | "voice.stopScreenShare" | "voice.joinScreenShare" | "voice.leaveScreenShare";
|
||||
|
||||
export interface SkinPluginActionDefinition {
|
||||
@@ -204,11 +207,11 @@ const V3_EVENTS = new Set<string>([
|
||||
const PASSIVE_EVENTS = new Set<string>(["focus", "blur", "pointerenter", "pointerleave", "dragstart", "dragover"]);
|
||||
const ACTIONS = new Set<string>([
|
||||
"ui.setState", "ui.toggleState", "session.copyInviteLink", "voice.joinChannel", "favorites.switch", "quickServers.switch", "chat.sendMessage", "chat.togglePanel",
|
||||
"voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway", "voice.setWhisperActive",
|
||||
"voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.connect", "voice.disconnect", "voice.setAway", "voice.setWhisperActive",
|
||||
"voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
|
||||
]);
|
||||
const V3_ACTIONS = new Set<string>([
|
||||
"ui.toggleState", "session.copyInviteLink", "chat.togglePanel", "voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway",
|
||||
"ui.toggleState", "session.copyInviteLink", "chat.togglePanel", "voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.connect", "voice.disconnect", "voice.setAway",
|
||||
"voice.setWhisperActive", "voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
|
||||
]);
|
||||
const PERMISSIONS = new Set<string>(Object.keys(SKIN_PLUGIN_PERMISSIONS));
|
||||
@@ -228,6 +231,7 @@ const ACTION_ARGS: Record<SkinPluginAction, ReadonlySet<string>> = {
|
||||
"audio.openSettings": new Set([]),
|
||||
"audio.toggleNoiseSuppression": new Set([]),
|
||||
"audio.toggleAccompaniment": new Set([]),
|
||||
"voice.connect": new Set([]),
|
||||
"voice.disconnect": new Set([]),
|
||||
"voice.setAway": new Set(["away", "message"]),
|
||||
"voice.setWhisperActive": new Set(["active"]),
|
||||
@@ -251,6 +255,7 @@ const ACTION_PERMISSION: Record<SkinPluginAction, SkinPluginPermission | null> =
|
||||
"audio.openSettings": "audio.settings.open",
|
||||
"audio.toggleNoiseSuppression": "audio.microphone.control",
|
||||
"audio.toggleAccompaniment": "audio.output.control",
|
||||
"voice.connect": "voice.connect",
|
||||
"voice.disconnect": "voice.disconnect",
|
||||
"voice.setAway": "voice.presence.write",
|
||||
"voice.setWhisperActive": "voice.whisper.control",
|
||||
@@ -271,7 +276,7 @@ const COLLECTION_PERMISSION: Record<string, SkinPluginPermission> = {
|
||||
"screenShare.streams": "voice.screenShare.read",
|
||||
};
|
||||
const COLLECTION_FIELDS: Record<string, ReadonlySet<string>> = {
|
||||
"session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
|
||||
"session.channels": new Set(["id", "name", "displayName", "isSpacer", "spacerAlignment", "spacerStyle", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
|
||||
"session.members": new Set(["id", "name", "avatarInitial", "channelId", "status", "speaking", "self", "screenSharing", "screenShareStreamId"]),
|
||||
"favorites.items": new Set(["id", "label", "current", "kind"]),
|
||||
"servers.quickList": new Set(["id", "label", "monogram", "icon", "tone", "current", "switchRestricted", "switchTitle", "kind", "favorite"]),
|
||||
|
||||
@@ -5,6 +5,15 @@ import {
|
||||
SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES,
|
||||
} from "./skin-runtime-plugin-context.js";
|
||||
|
||||
test("channel spacer metadata is available to custom skins only with channel read permission", () => {
|
||||
const item = { id: "4", name: "[cspacer0]Section", displayName: "Section", isSpacer: true, spacerAlignment: "center", spacerStyle: "text", secret: "hidden" };
|
||||
const context = { session: { channels: [item] } };
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext([], context))), {});
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext(["session.channels.read"], context))), {
|
||||
session: { channels: [{ id: "4", name: item.name, displayName: "Section", isSpacer: true, spacerAlignment: "center", spacerStyle: "text" }] },
|
||||
});
|
||||
});
|
||||
|
||||
test("runtime context exposes only fields covered by declared read permissions", () => {
|
||||
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
|
||||
session: {
|
||||
|
||||
@@ -26,7 +26,7 @@ interface CollectionProjection {
|
||||
}
|
||||
|
||||
const COLLECTIONS: readonly CollectionProjection[] = Object.freeze([
|
||||
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
|
||||
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "displayName", "isSpacer", "spacerAlignment", "spacerStyle", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
|
||||
{
|
||||
path: ["session", "members"],
|
||||
permission: "session.members.read",
|
||||
@@ -54,7 +54,7 @@ const CONTEXTS: readonly ContextProjection[] = Object.freeze([
|
||||
{ path: ["screenShare", "status"], permission: "voice.screenShare.status.read", fields: new Set(["active", "starting", "viewing"]) },
|
||||
]);
|
||||
|
||||
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "screenSharing", "audio", "microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive", "active", "starting", "viewing", "maxClientsLimited", "panelOpen"]);
|
||||
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "screenSharing", "audio", "microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive", "active", "starting", "viewing", "maxClientsLimited", "panelOpen", "isSpacer"]);
|
||||
const NUMBER_FIELDS = new Set(["depth", "memberCount", "targetCount", "ownerClientId", "viewerCount", "maxClients"]);
|
||||
const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
|
||||
id: 128,
|
||||
@@ -63,6 +63,9 @@ const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
|
||||
channelId: 128,
|
||||
parentId: 128,
|
||||
name: 160,
|
||||
displayName: 160,
|
||||
spacerAlignment: 8,
|
||||
spacerStyle: 12,
|
||||
label: 160,
|
||||
channelName: 160,
|
||||
userName: 160,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Public GitHub distribution contract. Packages still use the ordinary .wskin importer. */
|
||||
export const SKIN_STORE_REPOSITORY = "https://github.com/Huddle-Up-Forge/webspeak-skins";
|
||||
export const SKIN_STORE_INDEX_URL = "https://raw.githubusercontent.com/Huddle-Up-Forge/webspeak-skins/master/index.json";
|
||||
|
||||
export interface SkinStoreMetadata {
|
||||
schemaVersion: 1;
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author: string;
|
||||
license: string;
|
||||
description: string;
|
||||
minAppVersion: string;
|
||||
package: { ref: string; path: string; sha256: string };
|
||||
}
|
||||
|
||||
export interface SkinStoreEntry {
|
||||
id: string;
|
||||
repository: string;
|
||||
metadata: SkinStoreMetadata | null;
|
||||
revision: string;
|
||||
compatible: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SkinStoreCatalog {
|
||||
repository: string;
|
||||
appVersion: string;
|
||||
fetchedAt: number;
|
||||
entries: SkinStoreEntry[];
|
||||
}
|
||||
|
||||
export interface SkinStoreInstallInput {
|
||||
id: string;
|
||||
revision: string;
|
||||
/** Compare-and-set: do not overwrite a package another administrator changed. */
|
||||
installedVersion: string | null;
|
||||
}
|
||||
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
export function isSkinStoreVersion(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 32 && semver.test(value);
|
||||
}
|
||||
|
||||
/** SemVer precedence, including prereleases; build metadata does not affect ordering. */
|
||||
export function compareSkinVersions(left: string, right: string): number {
|
||||
const a = semver.exec(left), b = semver.exec(right);
|
||||
if (!a || !b) throw new Error("INVALID_SKIN_VERSION");
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
if (a[i] !== b[i]) return BigInt(a[i]) < BigInt(b[i]) ? -1 : 1;
|
||||
}
|
||||
if (a[4] === b[4]) return 0;
|
||||
if (!a[4]) return 1;
|
||||
if (!b[4]) return -1;
|
||||
const x = a[4].split("."), y = b[4].split(".");
|
||||
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
||||
if (x[i] === undefined) return -1;
|
||||
if (y[i] === undefined) return 1;
|
||||
if (x[i] === y[i]) continue;
|
||||
const nx = /^\d+$/.test(x[i]), ny = /^\d+$/.test(y[i]);
|
||||
if (nx && ny) return BigInt(x[i]) < BigInt(y[i]) ? -1 : 1;
|
||||
if (nx !== ny) return nx ? -1 : 1;
|
||||
return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Public workspace API v1. No skin IDs or connection credentials belong here. */
|
||||
export interface SkinWorkspacePolicy {
|
||||
apiVersion: 1;
|
||||
mode: "persistent";
|
||||
}
|
||||
|
||||
export function parseSkinWorkspacePolicy(value: unknown, schemaVersion: number): SkinWorkspacePolicy | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (schemaVersion < 3 || !value || typeof value !== "object" || Array.isArray(value)) throw new Error("Workspace policy requires an open-skin package.");
|
||||
const policy = value as Record<string, unknown>;
|
||||
if (Object.keys(policy).some(key => key !== "apiVersion" && key !== "mode") || policy.apiVersion !== 1 || policy.mode !== "persistent") {
|
||||
throw new Error("Unsupported workspace policy or API version.");
|
||||
}
|
||||
return { apiVersion: 1, mode: "persistent" };
|
||||
}
|
||||
@@ -25,6 +25,8 @@ export interface ChannelInfo {
|
||||
maxClientsLimited?: boolean;
|
||||
/** TeamSpeak's public channel flag; absent when the connected server omits it. */
|
||||
passwordProtected?: boolean;
|
||||
/** Required to recognize TeamSpeak's permanent, root-level spacer channels. */
|
||||
isPermanent?: boolean;
|
||||
members?: ChannelMember[];
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,13 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { zipSync } from "fflate";
|
||||
|
||||
const sourceDirectory = new URL("../../docs/examples/discord-voice/", import.meta.url);
|
||||
const sourceFiles = ["manifest.json", "components.json", "content.json", "skin.css"];
|
||||
const files = Object.fromEntries(await Promise.all(sourceFiles.map(async (name) => [
|
||||
name,
|
||||
Buffer.from((await readFile(new URL(name, sourceDirectory), "utf8")).replace(/\r\n/g, "\n")),
|
||||
])));
|
||||
const archive = zipSync(files, { level: 9, mtime: new Date("2020-01-01T00:00:00.000Z") });
|
||||
|
||||
await writeFile(fileURLToPath(new URL("../../docs/examples/discord-voice.wskin", import.meta.url)), archive);
|
||||
@@ -1,38 +1,16 @@
|
||||
<template>
|
||||
<section class="page-content operations-page">
|
||||
<div class="page-heading"
|
||||
><div
|
||||
><h2>{{ tr("operations") }}</h2
|
||||
><p>{{ tr("operationsLead") }}</p></div
|
||||
><button
|
||||
class="secondary-button"
|
||||
:disabled="operationsLoading"
|
||||
@click="loadOperations"
|
||||
><span
|
||||
v-if="operationsLoading"
|
||||
class="spinner small"
|
||||
></span
|
||||
><Icon
|
||||
v-else
|
||||
name="refresh"
|
||||
:size="17"
|
||||
/>{{ tr("refresh") }}</button
|
||||
></div
|
||||
>
|
||||
<div class="alert info system-notice"
|
||||
><Icon
|
||||
name="info"
|
||||
:size="16"
|
||||
/><span>{{
|
||||
tr("updateNotice", { version: operations.diagnostics.version || "—" })
|
||||
}}</span></div
|
||||
>
|
||||
<div class="operations-grid operations-primary">
|
||||
<article class="operation-card operation-wide"
|
||||
<section class="page-content operations-page" data-admin-scope="webspeak">
|
||||
<div class="page-heading"><div><h2>{{ tr('adminInstanceOperations') }}</h2><p>{{ tr('adminInstanceOperationsLead') }}</p></div>
|
||||
<button class="secondary-button" type="button" :disabled="operationsLoading" @click="loadOperations"><span v-if="operationsLoading" class="spinner small"></span><Icon v-else name="refresh" :size="17"/>{{ tr('refresh') }}</button>
|
||||
</div>
|
||||
<nav class="admin-section-nav" :aria-label="tr('adminInstanceOperations')">
|
||||
<button v-for="section in sections" :key="section.id" type="button" :aria-current="activeSection === section.id ? 'page' : undefined" @click="activeSection = section.id">{{ section.label }}<span v-if="section.count !== undefined" class="admin-tab-count">{{ section.count }}</span></button>
|
||||
</nav>
|
||||
<div v-show="activeSection === 'sessions'" class="admin-operations-section" data-admin-section="sessions"><article class="operation-card operation-wide"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("sessions") }}</h3
|
||||
><p>{{ tr("sessionsLead") }}</p></div
|
||||
><h3>{{ tr("adminBrowserSessions") }}</h3
|
||||
><p>{{ tr("adminBrowserSessionsLead") }}</p></div
|
||||
><strong>{{ operations.sessions.length }}</strong></header
|
||||
><div
|
||||
v-if="operations.sessions.length"
|
||||
@@ -78,12 +56,12 @@
|
||||
:size="22"
|
||||
/><span>{{ tr("sessionEmpty") }}</span></div
|
||||
></article
|
||||
>
|
||||
<article class="operation-card"
|
||||
></div>
|
||||
<div v-show="activeSection === 'invites'" class="admin-operations-section" data-admin-section="invites"><article class="operation-card"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("invites") }}</h3
|
||||
><p>{{ tr("invitesLead") }}</p></div
|
||||
><p>{{ tr("adminInviteScope") }}</p></div
|
||||
></header
|
||||
><form
|
||||
class="invite-form"
|
||||
@@ -161,47 +139,8 @@
|
||||
></div
|
||||
></div
|
||||
></article
|
||||
>
|
||||
</div>
|
||||
<div class="operations-grid lower-operations">
|
||||
<article class="operation-card diagnostics-card"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("diagnostics") }}</h3
|
||||
><p>{{ tr("diagnosticsLead") }}</p></div
|
||||
><a
|
||||
class="text-link"
|
||||
href="/api/admin/diagnostics/report"
|
||||
>{{ tr("downloadReport") }}</a
|
||||
></header
|
||||
><dl class="diagnostic-list"
|
||||
><div
|
||||
><dt>{{ tr("version") }}</dt
|
||||
><dd>{{ operations.diagnostics.version || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("runtime") }}</dt
|
||||
><dd>{{ operations.diagnostics.node || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("platform") }}</dt
|
||||
><dd
|
||||
>{{ operations.diagnostics.platform || "—" }} /
|
||||
{{ operations.diagnostics.arch || "—" }}</dd
|
||||
></div
|
||||
><div
|
||||
><dt>{{ tr("databaseSchema") }}</dt
|
||||
><dd>v{{ operations.diagnostics.schemaVersion || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("createdSessions") }}</dt
|
||||
><dd>{{ operations.diagnostics.createdSessions }}</dd></div
|
||||
></dl
|
||||
><button
|
||||
class="secondary-button"
|
||||
type="button"
|
||||
@click="downloadBackup"
|
||||
>{{ tr("exportBackup") }}</button
|
||||
></article
|
||||
>
|
||||
<article class="operation-card logs-card"
|
||||
></div>
|
||||
<div v-show="activeSection === 'logs'" class="admin-operations-section" data-admin-section="logs"><article class="operation-card logs-card"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("logViewer") }}</h3
|
||||
@@ -271,8 +210,8 @@
|
||||
:size="22"
|
||||
/><span>{{ tr("noLogs") }}</span></div
|
||||
></article
|
||||
>
|
||||
<article class="operation-card audit-card"
|
||||
></div>
|
||||
<div v-show="activeSection === 'audit'" class="admin-operations-section" data-admin-section="audit"><article class="operation-card audit-card"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("audit") }}</h3
|
||||
@@ -296,12 +235,51 @@
|
||||
>{{ tr("auditEmpty") }}</li
|
||||
></ul
|
||||
></article
|
||||
></div>
|
||||
<div v-show="activeSection === 'maintenance'" class="admin-operations-section" data-admin-section="maintenance"><article class="operation-card diagnostics-card"
|
||||
><header
|
||||
><div
|
||||
><h3>{{ tr("diagnostics") }}</h3
|
||||
><p>{{ tr("diagnosticsLead") }}</p></div
|
||||
><a
|
||||
class="text-link"
|
||||
href="/api/admin/diagnostics/report"
|
||||
>{{ tr("downloadReport") }}</a
|
||||
></header
|
||||
><dl class="diagnostic-list"
|
||||
><div
|
||||
><dt>{{ tr("version") }}</dt
|
||||
><dd>{{ operations.diagnostics.version || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("runtime") }}</dt
|
||||
><dd>{{ operations.diagnostics.node || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("platform") }}</dt
|
||||
><dd
|
||||
>{{ operations.diagnostics.platform || "—" }} /
|
||||
{{ operations.diagnostics.arch || "—" }}</dd
|
||||
></div
|
||||
><div
|
||||
><dt>{{ tr("databaseSchema") }}</dt
|
||||
><dd>v{{ operations.diagnostics.schemaVersion || "—" }}</dd></div
|
||||
><div
|
||||
><dt>{{ tr("createdSessions") }}</dt
|
||||
><dd>{{ operations.diagnostics.createdSessions }}</dd></div
|
||||
></dl
|
||||
><button
|
||||
class="secondary-button"
|
||||
type="button"
|
||||
@click="downloadBackup"
|
||||
>{{ tr("exportBackup") }}</button
|
||||
></article
|
||||
>
|
||||
<div class="alert info system-notice"><Icon name="info" :size="16"/><span>{{ tr('updateNotice', {version: operations.diagnostics.version || '—'}) }}</span></div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import Icon from "../Icon.vue";
|
||||
import type { useAdminOperations } from "../../composables/useAdminOperations.js";
|
||||
import type { useAdminI18n } from "../../composables/useAdminI18n.js";
|
||||
@@ -309,12 +287,25 @@ import type { AdminConnectionRecord } from "../../../../src/shared/admin-respons
|
||||
|
||||
const props = defineProps<{
|
||||
model: ReturnType<typeof useAdminOperations>;
|
||||
initialSection?: string;
|
||||
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText">;
|
||||
}>();
|
||||
// Request ownership, cancellation and drafts remain in the page's controller.
|
||||
const { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
|
||||
loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup } = props.model;
|
||||
const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText } = props.i18n;
|
||||
type OperationsSection = 'sessions' | 'invites' | 'logs' | 'audit' | 'maintenance';
|
||||
const normalizeSection = (value?: string): OperationsSection => value === 'invites' || value === 'logs' || value === 'audit' || value === 'maintenance' ? value : 'sessions';
|
||||
const activeSection = ref<OperationsSection>(normalizeSection(props.initialSection));
|
||||
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
|
||||
const sections = computed(() => [
|
||||
{ id: 'sessions' as const, label: tr('adminBrowserSessions'), count: operations.sessions.length },
|
||||
{ id: 'invites' as const, label: tr('invites'), count: operations.invites.length },
|
||||
{ id: 'logs' as const, label: tr('adminLogsSection'), count: undefined },
|
||||
{ id: 'audit' as const, label: tr('audit'), count: undefined },
|
||||
{ id: 'maintenance' as const, label: tr('adminMaintenanceSection'), count: undefined },
|
||||
]);
|
||||
|
||||
|
||||
function connectionRoute(record: AdminConnectionRecord) {
|
||||
const route = tr("connectionFromTo", { ip: record.clientIp || "—", target: record.target || "—" });
|
||||
|
||||
@@ -1,33 +1,40 @@
|
||||
<template>
|
||||
<section class="page-content server-page">
|
||||
<div class="page-heading"
|
||||
><div
|
||||
><h2>{{ tr("serverSettings") }}</h2
|
||||
><p>{{ tr("serverSettingsLead") }}</p></div
|
||||
><button
|
||||
class="primary-button"
|
||||
:disabled="serverSaving"
|
||||
@click="saveServerSettings"
|
||||
>{{ serverSaving ? tr("saving") : tr("saveChanges") }}</button
|
||||
></div
|
||||
>
|
||||
<div class="settings-grid">
|
||||
<details
|
||||
class="settings-card settings-accordion target-accordion"
|
||||
open
|
||||
>
|
||||
<summary class="settings-accordion-header">
|
||||
<span class="settings-accordion-heading"
|
||||
><strong>{{ tr("teamSpeakTarget") }}</strong
|
||||
><small>{{ serverForm.address || "—" }} · {{ serverForm.port || "—" }}</small></span
|
||||
>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
:size="18"
|
||||
/>
|
||||
</summary>
|
||||
<div class="settings-accordion-content">
|
||||
<div class="target-settings-layout">
|
||||
<section class="page-content server-page" data-admin-scope="webspeak">
|
||||
<div class="page-heading"><div><h2>{{ tr('adminInstanceSettings') }}</h2><p>{{ tr('adminInstanceLead') }}</p></div>
|
||||
<button class="primary-button" type="button" :disabled="serverSaving" @click="saveServerSettings">{{ serverSaving ? tr('saving') : tr('saveChanges') }}</button>
|
||||
</div>
|
||||
<div class="admin-scope-banner"><Icon name="waveform" :size="20"/><div><strong>{{ tr('adminWsGroup') }}</strong><p>{{ tr('adminWsScopeLead') }}</p></div></div>
|
||||
<nav class="admin-section-nav" :aria-label="tr('adminInstanceSettings')">
|
||||
<button v-for="section in sections" :key="section.id" type="button" :aria-current="activeSection === section.id ? 'page' : undefined" @click="activeSection = section.id">{{ section.label }}</button>
|
||||
</nav>
|
||||
<div v-show="activeSection === 'access'" class="settings-grid admin-settings-section" data-admin-section="access">
|
||||
<article class="settings-card admin-setting-card"><header class="admin-card-heading"><h3>{{ tr('accessMode') }}</h3></header><div class="access-settings-layout"><fieldset class="access-mode-fieldset"
|
||||
><legend>{{ tr("accessMode") }}</legend
|
||||
><label
|
||||
class="choice"
|
||||
:class="{ selected: serverForm.accessMode === 'fixed' }"
|
||||
><input
|
||||
v-model="serverForm.accessMode"
|
||||
type="radio"
|
||||
value="fixed"
|
||||
/><span
|
||||
><strong>{{ tr("fixedMode") }}</strong
|
||||
><small>{{ tr("fixedModeLead") }}</small></span
|
||||
></label
|
||||
><label
|
||||
class="choice"
|
||||
:class="{ selected: serverForm.accessMode === 'open' }"
|
||||
><input
|
||||
v-model="serverForm.accessMode"
|
||||
type="radio"
|
||||
value="open"
|
||||
/><span
|
||||
><strong>{{ tr("openMode") }}</strong
|
||||
><small>{{ tr("openModeLead") }}</small></span
|
||||
></label
|
||||
></fieldset
|
||||
></div></article>
|
||||
<article class="settings-card admin-setting-card"><header class="admin-card-heading"><h3>{{ tr('teamSpeakTarget') }}</h3><p>{{ tr('adminTargetScope') }}</p></header><div class="target-settings-layout">
|
||||
<div class="target-fields">
|
||||
<label
|
||||
><span>{{ tr("serverAddress") }}</span
|
||||
@@ -117,53 +124,9 @@
|
||||
></dl
|
||||
></div
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="settings-card settings-accordion">
|
||||
<summary class="settings-accordion-header">
|
||||
<span class="settings-accordion-heading"
|
||||
><strong>{{ tr("accessAndIdentity") }}</strong
|
||||
><small
|
||||
>{{ serverForm.accessMode === "fixed" ? tr("fixedMode") : tr("openMode") }} ·
|
||||
{{ serverForm.siteName || "WebSpeak" }}</small
|
||||
></span
|
||||
>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
:size="18"
|
||||
/>
|
||||
</summary>
|
||||
<div class="settings-accordion-content">
|
||||
<div class="access-settings-layout">
|
||||
<fieldset class="access-mode-fieldset"
|
||||
><legend>{{ tr("accessMode") }}</legend
|
||||
><label
|
||||
class="choice"
|
||||
:class="{ selected: serverForm.accessMode === 'fixed' }"
|
||||
><input
|
||||
v-model="serverForm.accessMode"
|
||||
type="radio"
|
||||
value="fixed"
|
||||
/><span
|
||||
><strong>{{ tr("fixedMode") }}</strong
|
||||
><small>{{ tr("fixedModeLead") }}</small></span
|
||||
></label
|
||||
><label
|
||||
class="choice"
|
||||
:class="{ selected: serverForm.accessMode === 'open' }"
|
||||
><input
|
||||
v-model="serverForm.accessMode"
|
||||
type="radio"
|
||||
value="open"
|
||||
/><span
|
||||
><strong>{{ tr("openMode") }}</strong
|
||||
><small>{{ tr("openModeLead") }}</small></span
|
||||
></label
|
||||
></fieldset
|
||||
>
|
||||
<div class="site-identity-fields">
|
||||
</div></article>
|
||||
</div>
|
||||
<article v-show="activeSection === 'site'" class="settings-card admin-setting-card admin-settings-section" data-admin-section="site"><header class="admin-card-heading"><h3>{{ tr('adminSiteSection') }}</h3><p>{{ tr('adminSiteScope') }}</p></header><div class="site-identity-fields">
|
||||
<label
|
||||
><span>{{ tr("siteName") }}</span
|
||||
><input
|
||||
@@ -173,7 +136,7 @@
|
||||
<div class="welcome-editor"
|
||||
><div class="welcome-editor-heading"
|
||||
><label
|
||||
><span>{{ tr("welcomeLanguage") }}</span
|
||||
><span>{{ tr("adminAnnouncementLanguage") }}</span
|
||||
><select v-model="welcomeLanguage"
|
||||
><option
|
||||
v-for="option in welcomeLanguageOptions"
|
||||
@@ -184,43 +147,17 @@
|
||||
></label
|
||||
><small>{{ tr("welcomeLanguageHint") }}</small></div
|
||||
><label
|
||||
><span>{{ tr("welcomeText") }} · {{ selectedWelcomeLanguageLabel }}</span
|
||||
><span>{{ tr("adminSiteAnnouncement") }} · {{ selectedWelcomeLanguageLabel }}</span
|
||||
><textarea
|
||||
v-model="selectedWelcomeText"
|
||||
maxlength="500"
|
||||
rows="4"
|
||||
:placeholder="selectedWelcomeDefault"
|
||||
></textarea></label
|
||||
><small class="field-help">{{ tr("welcomeFallbackHint") }}</small></div
|
||||
><small class="field-help">{{ tr("adminAnnouncementFallback") }}</small></div
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="settings-card settings-accordion advanced-card">
|
||||
<summary class="settings-accordion-header">
|
||||
<span class="settings-accordion-heading"
|
||||
><strong>{{ tr("advancedSettings") }}</strong
|
||||
><small>{{ tr("advancedSettingsLead") }}</small></span
|
||||
>
|
||||
<span class="settings-accordion-statuses"
|
||||
><span class="settings-summary-chip"
|
||||
><i :class="{ active: serverForm.webRtcEnabled }"></i>{{ tr("webrtcSettings") }} ·
|
||||
{{ serverForm.webRtcEnabled ? tr("enabledStatus") : tr("disabledStatus") }}</span
|
||||
><span class="settings-summary-chip"
|
||||
><i :class="{ active: serverForm.relayNodes.some((relay) => relay.enabled) }"></i
|
||||
>{{ tr("relaySettings") }} ·
|
||||
{{ tr("relayNodeCount", { count: serverForm.relayNodes.length }) }}</span
|
||||
></span
|
||||
>
|
||||
<Icon
|
||||
name="chevron-down"
|
||||
:size="18"
|
||||
/>
|
||||
</summary>
|
||||
<div class="settings-accordion-content">
|
||||
<div class="advanced-settings-grid">
|
||||
</div></article>
|
||||
<article v-show="activeSection === 'network'" class="settings-card admin-setting-card admin-settings-section" data-admin-section="network"><header class="admin-card-heading"><h3>{{ tr('adminNetworkSection') }}</h3><p>{{ tr('advancedSettingsLead') }}</p></header><div class="advanced-settings-grid">
|
||||
<section class="settings-subsection webrtc-card"
|
||||
><header class="settings-subsection-heading"
|
||||
><div
|
||||
@@ -317,6 +254,12 @@
|
||||
v-model.trim="relay.target"
|
||||
maxlength="300"
|
||||
:placeholder="tr('relayTargetPlaceholder')" /></label
|
||||
><label
|
||||
><span>{{ tr("relayVoiceEndpoint") }}</span
|
||||
><input
|
||||
v-model.trim="relay.voiceEndpoint"
|
||||
maxlength="300"
|
||||
:placeholder="tr('relayVoiceEndpointPlaceholder')" /></label
|
||||
><div class="password-row"
|
||||
><label
|
||||
><span>{{ tr("relayToken") }}</span
|
||||
@@ -352,17 +295,16 @@
|
||||
type="button"
|
||||
@click="addRelayNode"
|
||||
>{{ tr("relayAdd") }}</button
|
||||
><small class="field-help">{{ tr("relayVoiceEndpointLead") }}</small
|
||||
><small class="field-help">{{ tr("relayManagedHint") }}</small></section
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div></article>
|
||||
<p class="admin-save-scope"><Icon name="info" :size="15"/>{{ tr('adminSaveScope') }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import Icon from "../Icon.vue";
|
||||
import type { useAdminServerSettings } from "../../composables/useAdminServerSettings.js";
|
||||
import type { useAdminI18n } from "../../composables/useAdminI18n.js";
|
||||
@@ -373,6 +315,7 @@ type WelcomeLanguage = SiteLanguage;
|
||||
type WelcomeTextField = "welcomeText" | "welcomeTextEn" | "welcomeTextDe" | "welcomeTextRu" | "welcomeTextJa";
|
||||
const props = defineProps<{
|
||||
model: ReturnType<typeof useAdminServerSettings>;
|
||||
initialSection?: string;
|
||||
i18n: Pick<ReturnType<typeof useAdminI18n>, "tr" | "formatDate" | "connectionFailureText">;
|
||||
}>();
|
||||
const welcomeLanguage = defineModel<WelcomeLanguage>("welcomeLanguage", { required: true });
|
||||
@@ -380,6 +323,16 @@ const emit = defineEmits<{ webrtcToggle: [] }>();
|
||||
// The page owns one stable feature controller across route changes.
|
||||
const { serverForm, serverSaving, testing, testResult, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode } = props.model;
|
||||
const { tr, formatDate, connectionFailureText } = props.i18n;
|
||||
type SettingsSection = 'access' | 'site' | 'network';
|
||||
const normalizeSection = (value?: string): SettingsSection => value === 'site' || value === 'network' ? value : 'access';
|
||||
const activeSection = ref<SettingsSection>(normalizeSection(props.initialSection));
|
||||
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
|
||||
const sections = computed(() => [
|
||||
{ id: 'access' as const, label: tr('adminAccessSection') },
|
||||
{ id: 'site' as const, label: tr('adminSiteSection') },
|
||||
{ id: 'network' as const, label: tr('adminNetworkSection') },
|
||||
]);
|
||||
|
||||
function handleWebRtcToggle() { emit("webrtcToggle"); }
|
||||
|
||||
const welcomeLanguageOptions: Array<{ value: WelcomeLanguage; label: string }> = [
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<section class="skin-store" :aria-label="tr('skinStore')" :aria-busy="storeLoading">
|
||||
<div class="skin-store-heading">
|
||||
<div><h3>{{ tr('skinStore') }}</h3><p>{{ tr('skinStoreLead') }}</p></div>
|
||||
<button class="secondary-button" type="button" :disabled="storeLoading || skinBusy" @click="loadSkinStore(true)">
|
||||
{{ storeLoading ? tr('loading') : tr('skinStoreRefresh') }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="skin-store-source">{{ tr('skinStoreSource') }} · <a :href="SKIN_STORE_REPOSITORY" target="_blank" rel="noopener noreferrer">Huddle-Up-Forge/webspeak-skins</a></p>
|
||||
<div class="alert info"><Icon name="info" :size="16"/><span>{{ tr('skinStorePermissionNote') }}</span></div>
|
||||
<div v-if="storeError" class="alert error" role="alert">{{ storeError }}</div>
|
||||
<div v-if="storeLoading" class="skin-library-loading" role="status"><span class="spinner"></span>{{ tr('loading') }}</div>
|
||||
<div v-if="storeCatalog?.entries.length" class="skin-library-grid">
|
||||
<article v-for="entry in storeCatalog.entries" :key="entry.id" class="skin-library-card skin-store-card">
|
||||
<div class="skin-library-copy">
|
||||
<div class="skin-library-title"><h3>{{ entry.metadata?.name || entry.id }}</h3><span>{{ entry.id }}</span></div>
|
||||
<template v-if="entry.metadata">
|
||||
<p>{{ entry.metadata.description }}</p>
|
||||
<dl>
|
||||
<div><dt>{{ tr('skinStoreAvailableVersion') }}</dt><dd>v{{ entry.metadata.version }}</dd></div>
|
||||
<div v-if="installedStoreSkin(entry)"><dt>{{ tr('skinStoreCurrentVersion') }}</dt><dd>v{{ installedStoreSkin(entry)!.version }}</dd></div>
|
||||
<div><dt>{{ tr('skinAuthor') }}</dt><dd>{{ entry.metadata.author }}</dd></div>
|
||||
<div><dt>{{ tr('skinLicense') }}</dt><dd>{{ entry.metadata.license }}</dd></div>
|
||||
<div><dt>{{ tr('skinMinVersion') }}</dt><dd>{{ entry.metadata.minAppVersion }}</dd></div>
|
||||
</dl>
|
||||
<p v-if="!entry.compatible" class="skin-store-warning">{{ tr('skinStoreIncompatible') }}</p>
|
||||
</template>
|
||||
<p v-else class="skin-store-warning">{{ tr(entry.error === 'SKIN_STORE_UNAVAILABLE' ? 'skinStoreUnavailable' : 'skinStoreInvalid') }}</p>
|
||||
<div class="skin-library-actions">
|
||||
<a :href="entry.repository" target="_blank" rel="noopener noreferrer" class="text-link">{{ tr('skinStoreRepository') }}</a>
|
||||
<button v-if="entry.metadata" class="primary-button" type="button"
|
||||
:disabled="skinBusy || skinLoading || storeLoading || !entry.compatible || storeVersionOrder(entry) <= 0"
|
||||
@click="installStoreSkin(entry)">
|
||||
<span v-if="storeInstallingId === entry.id" class="spinner small"></span>
|
||||
{{ storeInstallingId === entry.id ? tr('skinStoreInstalling') : storeVersionOrder(entry) < 0 ? tr('skinStoreNewer') : storeVersionOrder(entry) === 0 ? tr('skinStoreInstalled') : installedStoreSkin(entry) ? tr('skinStoreUpdate') : tr('skinStoreInstall') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<p v-else-if="storeCatalog && !storeLoading" class="skin-library-empty">{{ tr('skinStoreEmpty') }}</p>
|
||||
<p v-if="storeCatalog" class="skin-store-source">{{ tr('skinStoreLoadedAt') }} {{ new Date(storeCatalog.fetchedAt).toLocaleString() }} · WebSpeak {{ storeCatalog.appVersion }}</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import Icon from "../Icon.vue";
|
||||
import { SKIN_STORE_REPOSITORY } from "../../../../src/shared/skin-store.js";
|
||||
import type { useAdminSkins } from "../../composables/useAdminSkins.js";
|
||||
import type { useAdminI18n } from "../../composables/useAdminI18n.js";
|
||||
const props = defineProps<{ model: ReturnType<typeof useAdminSkins>; i18n: Pick<ReturnType<typeof useAdminI18n>, "tr"> }>();
|
||||
const { storeCatalog, storeLoading, storeInstallingId, storeError, skinBusy, skinLoading,
|
||||
loadSkinStore, installStoreSkin, installedStoreSkin, storeVersionOrder } = props.model;
|
||||
const { tr } = props.i18n;
|
||||
</script>
|
||||
@@ -33,7 +33,11 @@
|
||||
:size="16"
|
||||
/><span>{{ tr("skinLibraryScope") }}</span></div
|
||||
>
|
||||
<section class="skin-default-control"
|
||||
<nav class="skin-library-tabs" :aria-label="tr('skinLibrary')">
|
||||
<button type="button" :aria-current="skinTab === 'installed' ? 'page' : undefined" @click="selectSkinTab('installed')">{{ tr('skinInstalledTab') }}</button>
|
||||
<button type="button" :aria-current="skinTab === 'store' ? 'page' : undefined" @click="selectSkinTab('store')">{{ tr('skinStore') }}</button>
|
||||
</nav>
|
||||
<section v-if="skinTab === 'installed'" class="skin-default-control"
|
||||
><div
|
||||
><strong>{{ tr("skinDefault") }}</strong
|
||||
><p>{{ tr("skinDefaultLead") }}</p></div
|
||||
@@ -62,6 +66,8 @@
|
||||
role="status"
|
||||
>{{ skinManagerNotice }}</div
|
||||
>
|
||||
<AdminSkinStore v-if="skinTab === 'store'" :model="model" :i18n="i18n" />
|
||||
<div v-else>
|
||||
<div
|
||||
v-if="skinLoading"
|
||||
class="skin-library-loading"
|
||||
@@ -153,12 +159,14 @@
|
||||
><strong>{{ tr("skinEmpty") }}</strong
|
||||
><p>{{ tr("skinEmptyLead") }}</p></div
|
||||
>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import Icon from "../Icon.vue";
|
||||
import AdminSkinStore from "./AdminSkinStore.vue";
|
||||
import type { useAdminSkins } from "../../composables/useAdminSkins.js";
|
||||
import type { useAdminI18n } from "../../composables/useAdminI18n.js";
|
||||
import type { SkinCatalogEntry } from "../../services/skin-catalog.js";
|
||||
@@ -169,6 +177,7 @@ const props = defineProps<{
|
||||
}>();
|
||||
const skinFileInput = ref<HTMLInputElement | null>(null);
|
||||
const { skinEntries, skinLoading, skinUploading, removingSkinId, skinDefaultId, skinBusy,
|
||||
skinTab, selectSkinTab,
|
||||
enabledSkinEntries, skinManagerError, skinManagerNotice, saveSkinDefault, toggleSkinEnabled, onSkinFileChanged, removeSkin } = props.model;
|
||||
const { tr } = props.i18n;
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
<template>
|
||||
<section class="page-content ts-admin-page" data-admin-scope="teamspeak">
|
||||
<div class="page-heading"><div><h2>{{ tr('tsAdminTitle') }}</h2><p>{{ tr('tsAdminLead') }}</p></div><span class="admin-optional">{{ tr('adminOptional') }}</span></div>
|
||||
<div class="admin-scope-banner"><Icon name="shield" :size="20"/><div><strong>{{ tr('adminTsGroup') }}</strong><p>{{ tr('adminTsManageLead') }}</p></div></div>
|
||||
<div v-if="!settings.fixedMode" class="alert info admin-fixed-notice"><Icon name="info" :size="18"/><div><p>{{ tr('tsAdminFixedOnly') }}</p><RouterLink to="/admin/server">{{ tr('adminInstanceSettings') }}</RouterLink></div></div>
|
||||
<template v-else>
|
||||
<div v-if="noticeMessage" class="alert success" role="status">{{ noticeMessage }}</div>
|
||||
<div v-if="refreshWarning" class="alert info" role="status">{{ refreshWarning }}</div>
|
||||
<article v-if="!settings.enabled && !loading" class="operation-card admin-ts-setup">
|
||||
<Icon name="server" :size="26"/><div><h3>{{ tr('adminTsSetupTitle') }}</h3><p>{{ tr('adminTsSetupLead') }}</p></div>
|
||||
<button class="secondary-button" type="button" @click="configureConnection">{{ tr('adminTsConfigure') }}</button>
|
||||
</article>
|
||||
<details ref="connectionPanel" class="operation-card ts-admin-credentials" :open="connectionOpen" @toggle="connectionOpen = ($event.target as HTMLDetailsElement).open">
|
||||
<summary><Icon name="chevron-right" :size="18"/><div><strong>{{ tr('adminTsConnection') }}</strong><small>{{ settings.enabled ? tr('adminTsConfigured') : tr('adminTsNotEnabled') }}</small></div><span class="state-pill">{{ settings.enabled ? settings.transport === 'web' ? tr('tsAdminWeb') : settings.transport === 'ssh' ? tr('tsAdminSsh') : tr('tsAdminTcp') : tr('adminOptional') }}</span></summary>
|
||||
<div class="admin-connection-body"><p class="field-help">{{ tr('adminTsConnectionScope') }}</p>
|
||||
<form class="ts-admin-form" @submit.prevent="saveSettings">
|
||||
<fieldset :disabled="loading || saving || acting || connecting">
|
||||
<label class="choice ts-admin-enable" :class="{ selected: form.enabled }"><input v-model="form.enabled" type="checkbox" />
|
||||
<span><strong>{{ tr('tsAdminEnable') }}</strong><small>{{ tr('tsAdminEnableLead') }}</small></span></label>
|
||||
<div class="ts-admin-fields">
|
||||
<label><span>{{ tr('adminTsSavedTarget') }}</span><input :value="`${targetAddress} · ${targetPort}`" readonly /></label>
|
||||
<label><span>{{ tr('tsAdminTransport') }}</span><select v-model="form.transport"><option value="web">{{ tr('tsAdminWeb') }}</option><option value="ssh">{{ tr('tsAdminSsh') }}</option><option value="tcp">{{ tr('tsAdminTcp') }}</option></select></label>
|
||||
<label v-if="form.transport === 'web'" class="ts-admin-wide"><span>{{ tr('tsAdminUrl') }}</span><input v-model.trim="form.webQueryUrl" type="url" maxlength="2048" placeholder="https://ts.example.com:10443" :required="form.enabled" /></label>
|
||||
<template v-else>
|
||||
<label><span>{{ tr('tsAdminHost') }}</span><input v-model.trim="form.queryHost" maxlength="253" :placeholder="targetAddress" /></label>
|
||||
<label><span>{{ tr('tsAdminQueryPort') }}</span><input v-model.trim="form.queryPort" type="number" min="1" max="65535" required /></label>
|
||||
<label><span>{{ tr('tsAdminUsername') }}</span><input v-model.trim="form.username" autocomplete="username" maxlength="128" :required="form.enabled" /></label>
|
||||
<label v-if="form.transport === 'ssh'"><span>{{ tr('tsAdminHostKey') }}</span><input v-model.trim="form.hostKeyFingerprint" maxlength="128" placeholder="SHA256:…" :required="form.enabled" /></label>
|
||||
</template>
|
||||
<label><span>{{ tr('tsAdminServerId') }}</span><input v-model.number="form.serverId" type="number" min="0" max="4294967295" required /></label>
|
||||
</div>
|
||||
<p class="field-help">{{ tr('tsAdminServerIdHelp') }}</p>
|
||||
<template v-if="form.transport === 'web'">
|
||||
<div class="ts-admin-password-row"><label><span>{{ tr('tsAdminApiKey') }}</span><input v-model="form.apiKey" type="password" autocomplete="new-password" maxlength="4096" :disabled="form.apiKeyAction !== 'replace'" :placeholder="settings.hasApiKey ? tr('tsAdminApiKeyConfigured') : ''" :required="form.enabled && form.apiKeyAction === 'replace'" /></label>
|
||||
<button type="button" :class="{active: form.apiKeyAction === 'replace'}" @click="form.apiKeyAction = 'replace'">{{ tr('tsAdminSetKey') }}</button>
|
||||
<button v-if="settings.hasApiKey" type="button" :class="{danger: form.apiKeyAction === 'remove'}" @click="form.apiKeyAction = form.apiKeyAction === 'remove' ? 'keep' : 'remove'">{{ form.apiKeyAction === 'remove' ? tr('tsAdminKeepKey') : tr('tsAdminRemoveKey') }}</button></div>
|
||||
<p class="field-help">{{ tr('tsAdminWebHelp') }}</p><p class="field-help">{{ tr('tsAdminKeyHelp') }}</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="ts-admin-password-row"><label><span>{{ tr('tsAdminPassword') }}</span><input v-model="form.password" type="password" autocomplete="new-password" maxlength="1024" :disabled="form.passwordAction !== 'replace'" :placeholder="settings.hasPassword ? tr('tsAdminPasswordConfigured') : tr('tsAdminPasswordPlaceholder')" /></label>
|
||||
<button type="button" :class="{active: form.passwordAction === 'replace'}" @click="form.passwordAction = 'replace'">{{ settings.hasPassword ? tr('change') : tr('tsAdminSetPassword') }}</button>
|
||||
<button v-if="settings.hasPassword" type="button" :class="{danger: form.passwordAction === 'remove'}" @click="form.passwordAction = form.passwordAction === 'remove' ? 'keep' : 'remove'">{{ form.passwordAction === 'remove' ? tr('tsAdminKeepPassword') : tr('remove') }}</button></div>
|
||||
<p class="field-help">{{ tr('tsAdminHostHelp') }}</p><p v-if="form.transport === 'ssh'" class="field-help">{{ tr('tsAdminFingerprintHint') }}</p>
|
||||
</template>
|
||||
<div class="ts-admin-actions"><button class="primary-button" type="submit"><span v-if="saving" class="spinner small"></span>{{ saving ? tr('saving') : tr('saveChanges') }}</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
</details>
|
||||
<div v-if="settingsDirty" class="alert info" role="status"><Icon name="info" :size="18"/><span>{{ tr('adminTsConfigPending') }}</span></div>
|
||||
<article v-if="settings.enabled" class="operation-card ts-admin-live">
|
||||
<header><div><h3>{{ tr('tsAdminLiveTitle') }}</h3><p>{{ overview ? tr('tsAdminUpdatedAt', {time: formatDate(overview.observedAt)}) : tr('adminTsConfigurationSaved') }}</p></div>
|
||||
<button class="secondary-button" type="button" :disabled="loading || connecting || saving || acting || settingsDirty" @click="connectAndRefresh"><span v-if="connecting" class="spinner small"></span>{{ connecting ? tr('tsAdminConnecting') : overview ? tr('refresh') : tr('tsAdminConnect') }}</button></header>
|
||||
<div v-if="!overview" class="operation-empty"><Icon name="server" :size="22"/><span>{{ tr('tsAdminEmpty') }}</span></div>
|
||||
<template v-if="overview">
|
||||
<nav class="admin-section-nav" :aria-label="tr('tsAdminTitle')"><button v-for="section in sections" :key="section.id" type="button" :aria-current="activeSection === section.id ? 'page' : undefined" @click="activeSection = section.id">{{ section.label }}<span v-if="section.count !== undefined" class="admin-tab-count">{{ section.count }}</span></button></nav>
|
||||
<article v-if="editor.action" ref="editorPanel" class="operation-card ts-admin-editor" :aria-label="actionTitle">
|
||||
<header><div><h3>{{ actionTitle }}</h3><p>{{ tr('tsAdminActionHelp') }}</p></div></header>
|
||||
<form class="ts-admin-form" @submit.prevent="runAction"><fieldset :disabled="acting || saving || settingsDirty || loading">
|
||||
<p v-if="editor.targetName" class="ts-admin-selected-target">{{ editor.targetName }} <small>#{{ editor.id }}</small></p>
|
||||
<div class="ts-admin-fields">
|
||||
<label v-if="['server.update','channel.create','channel.update'].includes(editor.action)"><span>{{ editor.action === 'server.update' ? tr('tsAdminServer') : tr('tsAdminChannelName') }}</span><input v-model="editor.name" :maxlength="editor.action === 'server.update' ? 64 : 40" required /></label>
|
||||
<template v-if="editor.action === 'server.update'"><label><span>{{ tr('tsAdminSlots') }}</span><input v-model.number="editor.maxClients" type="number" min="1" max="65535" required /></label><label class="ts-admin-wide"><span>{{ tr('tsAdminWelcome') }}</span><textarea v-model="editor.welcomeMessage" maxlength="4096" rows="3"></textarea></label></template>
|
||||
<template v-if="editor.action === 'channel.create'">
|
||||
<label><span>{{ tr('tsAdminParent') }}</span><select v-model="editor.parentId"><option value="0">{{ tr('tsAdminRoot') }}</option><option v-for="channel in overview?.channels" :key="channel.id" :value="channel.id">{{ channel.name }}</option></select></label>
|
||||
<label class="ts-admin-wide"><span>{{ tr('tsAdminDescription') }}</span><textarea v-model="editor.description" maxlength="8192" rows="3"></textarea></label>
|
||||
<label><span>{{ tr('tsAdminChannelPassword') }}</span><input v-model="editor.password" type="password" autocomplete="new-password" maxlength="512" /></label><label class="choice"><input v-model="editor.permanent" type="checkbox" /><span>{{ tr('tsAdminPermanent') }}</span></label>
|
||||
</template>
|
||||
<label v-if="editor.action === 'client.move'"><span>{{ tr('tsAdminChannel') }}</span><select v-model="editor.channelId" required><option v-for="channel in overview?.channels" :key="channel.id" :value="channel.id">{{ channel.name }}</option></select></label>
|
||||
<template v-if="editor.action === 'client.group'"><label><span>{{ tr('tsAdminGroup') }}</span><select v-model="editor.groupId" required><option v-for="group in overview?.groups" :key="group.id" :value="group.id">{{ group.name }} (#{{ group.id }})</option></select></label><label class="choice"><input v-model="editor.remove" type="checkbox" /><span>{{ tr('tsAdminRemoveGroup') }}</span></label></template>
|
||||
<label v-if="editor.action === 'client.kick' || editor.action === 'client.ban'"><span>{{ tr('tsAdminReason') }}</span><input v-model="editor.reason" maxlength="200" /></label>
|
||||
<label v-if="editor.action === 'client.ban'"><span>{{ tr('tsAdminBanDuration') }}</span><input v-model.number="editor.durationSeconds" type="number" min="0" max="31536000" required /></label>
|
||||
</div>
|
||||
<p v-if="editor.action === 'channel.delete'" class="field-help">{{ tr('tsAdminDeleteHelp') }}</p><p v-if="editor.action === 'client.ban'" class="field-help">{{ tr('tsAdminBanHelp') }}</p>
|
||||
<div class="ts-admin-toolbar"><button class="primary-button" type="submit"><span v-if="acting" class="spinner small"></span>{{ tr('tsAdminConfirm') }}</button><button class="secondary-button" type="button" @click="closeAction">{{ tr('tsAdminCancel') }}</button></div>
|
||||
</fieldset></form>
|
||||
</article>
|
||||
<section v-show="activeSection === 'overview'" data-admin-section="overview" class="admin-ts-section">
|
||||
<div class="metric-grid ts-admin-metrics"><article><small>{{ tr('tsAdminServer') }}</small><strong>{{ overview.serverName || '—' }}</strong><em>{{ overview.serverVersion || overview.serverFamily }}</em></article>
|
||||
<article><small>{{ tr('tsAdminChannels') }}</small><strong>{{ overview.channelCount }}</strong></article><article><small>{{ tr('tsAdminClients') }}</small><strong>{{ overview.clientCount }} / {{ overview.maxClients || '—' }}</strong></article></div>
|
||||
|
||||
<div class="ts-admin-toolbar"><button type="button" class="secondary-button" :disabled="loading || saving || acting || settingsDirty" @click="beginAction('server.update')">{{ tr('tsAdminServerSettings') }}</button></div>
|
||||
</section>
|
||||
<div v-show="activeSection === 'channels'" data-admin-section="channels" class="admin-ts-section">
|
||||
<div class="ts-admin-toolbar"><button type="button" class="primary-button" :disabled="loading || saving || acting || settingsDirty" @click="beginAction('channel.create')"><Icon name="plus" :size="16"/>{{ tr('tsAdminCreateChannel') }}</button></div>
|
||||
<section class="operation-card"><header><h3>{{ tr('tsAdminChannels') }}</h3><strong>{{ overview.channels.length }}</strong></header><div class="table-wrap" role="region" tabindex="0" :aria-label="tr('tsAdminChannels')"><table><thead><tr><th>{{ tr('tsAdminChannelName') }}</th><th>{{ tr('tsAdminMembers') }}</th><th>{{ tr('tsAdminChannelType') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody>
|
||||
<tr v-for="channel in overview.channels" :key="channel.id"><td><strong>{{ channel.name }}</strong><small>#{{ channel.id }}</small></td><td>{{ channel.totalClients }}</td><td>{{ channel.hasPassword ? tr('tsAdminProtected') : tr('tsAdminPublic') }}</td><td><div class="ts-admin-row-actions"><button type="button" :disabled="settingsDirty || loading || saving || acting" @click="beginAction('channel.update', channel)">{{ tr('tsAdminRenameChannel') }}</button><button class="danger" type="button" :disabled="settingsDirty || loading || saving || acting" @click="beginAction('channel.delete', channel)">{{ tr('tsAdminDeleteChannel') }}</button></div></td></tr>
|
||||
<tr v-if="!overview.channels.length"><td colspan="4">{{ tr('tsAdminNoChannels') }}</td></tr></tbody></table></div></section>
|
||||
</div>
|
||||
<div v-show="activeSection === 'clients'" data-admin-section="clients" class="admin-ts-section">
|
||||
<p v-if="!overview.groupsAvailable" class="field-help">{{ tr('tsAdminGroup') }}: {{ listErrorText(overview.groupsErrorCode) }}</p>
|
||||
<section class="operation-card"><header><h3>{{ tr('tsAdminClients') }}</h3><strong>{{ overview.clients.length }}</strong></header><div class="table-wrap" role="region" tabindex="0" :aria-label="tr('tsAdminClients')"><table><thead><tr><th>{{ tr('nickname') }}</th><th>{{ tr('tsAdminChannel') }}</th><th>{{ tr('tsAdminGroup') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody>
|
||||
<tr v-for="client in overview.clients" :key="client.id"><td><strong>{{ client.nickname }}</strong><small>#{{ client.id }}</small></td><td>{{ channelNames.get(client.channelID) || client.channelID }}</td><td>{{ client.serverGroups.map(id => groupNames.get(id) || id).join(', ') || '—' }}</td><td><div class="ts-admin-row-actions"><button type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.move', client)">{{ tr('tsAdminMove') }}</button><button type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid || !overview.groupsAvailable" @click="beginAction('client.group', client)">{{ tr('tsAdminGroupAction') }}</button><button class="danger" type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.kick', client)">{{ tr('tsAdminKick') }}</button><button class="danger" type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.ban', client)">{{ tr('tsAdminBan') }}</button></div></td></tr>
|
||||
<tr v-if="!overview.clients.length"><td colspan="4">{{ tr('tsAdminNoClients') }}</td></tr></tbody></table></div></section>
|
||||
</div>
|
||||
<div v-show="activeSection === 'bans'" data-admin-section="bans" class="admin-ts-section"><section class="operation-card"><header><h3>{{ tr('tsAdminBans') }}</h3><strong>{{ overview.bans.length }}</strong></header><p v-if="!overview.bansAvailable" class="field-help">{{ listErrorText(overview.bansErrorCode) }}</p><div v-else class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }} / UID</th><th>{{ tr('tsAdminReason') }}</th><th>{{ tr('tsAdminBanDuration') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody><tr v-for="ban in overview.bans" :key="ban.id"><td>{{ ban.name || ban.uid || `#${ban.id}` }}</td><td>{{ ban.reason || '—' }}</td><td>{{ ban.durationSeconds }}</td><td><button type="button" class="secondary-button" :disabled="settingsDirty || loading || saving || acting" @click="beginAction('ban.delete', ban)">{{ tr('remove') }}</button></td></tr><tr v-if="!overview.bans.length"><td colspan="4">{{ tr('tsAdminNoBans') }}</td></tr></tbody></table></div></section></div>
|
||||
</template>
|
||||
</article>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import type { useAdminTsAdmin } from '../../composables/useAdminTsAdmin.js';
|
||||
import type { useAdminI18n } from '../../composables/useAdminI18n.js';
|
||||
import type { TsAdminAction } from '../../../../src/shared/admin-inputs.js';
|
||||
import type { AdminTranslationKey } from '../../i18n/admin.js';
|
||||
import Icon from '../Icon.vue';
|
||||
const props = defineProps<{ model: ReturnType<typeof useAdminTsAdmin>; i18n: Pick<ReturnType<typeof useAdminI18n>, 'tr' | 'formatDate'>; targetAddress: string; targetPort: string }>();
|
||||
const {tr, formatDate} = props.i18n;
|
||||
const {settings, form, editor, overview, settingsDirty, noticeMessage, refreshWarning, listErrorText, loading, saving, connecting, acting, saveSettings, connectAndRefresh, beginAction, closeAction, runAction} = props.model;
|
||||
const connectionOpen = ref(false);
|
||||
const connectionPanel = ref<HTMLDetailsElement | null>(null);
|
||||
async function configureConnection() {
|
||||
connectionOpen.value = true;
|
||||
await nextTick();
|
||||
connectionPanel.value?.querySelector<HTMLInputElement>('input[type="checkbox"]')?.focus();
|
||||
}
|
||||
type TsSection = 'overview' | 'channels' | 'clients' | 'bans';
|
||||
const activeSection = ref<TsSection>('overview');
|
||||
const sections = computed(() => [
|
||||
{ id: 'overview' as const, label: tr('adminTsOverviewSection'), count: undefined },
|
||||
{ id: 'channels' as const, label: tr('tsAdminChannels'), count: overview.value?.channelCount },
|
||||
{ id: 'clients' as const, label: tr('tsAdminClients'), count: overview.value?.clientCount },
|
||||
{ id: 'bans' as const, label: tr('tsAdminBans'), count: overview.value?.bansAvailable ? overview.value.bans.length : undefined },
|
||||
]);
|
||||
const channelNames = computed(() => new Map((overview.value?.channels ?? []).map(channel => [channel.id, channel.name])));
|
||||
const groupNames = computed(() => new Map((overview.value?.groups ?? []).map(group => [group.id, group.name])));
|
||||
const titles: Record<TsAdminAction['action'], AdminTranslationKey> = { 'server.update': 'tsAdminServerSettings', 'channel.create': 'tsAdminCreateChannel', 'channel.update': 'tsAdminRenameChannel', 'channel.delete': 'tsAdminDeleteChannel', 'client.move': 'tsAdminMove', 'client.kick': 'tsAdminKick', 'client.ban': 'tsAdminBan', 'client.group': 'tsAdminGroupAction', 'ban.delete': 'remove' };
|
||||
const actionTitle = computed(() => editor.action ? tr(titles[editor.action]) : '');
|
||||
const editorPanel = ref<HTMLElement | null>(null);
|
||||
watch(() => editor.action, async action => { if (!action) return; await nextTick(); editorPanel.value?.scrollIntoView?.({block: 'nearest'}); editorPanel.value?.querySelector<HTMLElement>('input,select,textarea,button')?.focus(); });
|
||||
</script>
|
||||
@@ -60,16 +60,19 @@
|
||||
<button
|
||||
class="member-channel-heading"
|
||||
data-ws-part="voice.channel-group.heading"
|
||||
:data-spacer="getChannelSpacer(channelItem) ? 'true' : undefined"
|
||||
:data-ws-state="channelItem.id === currentChannelId ? 'current' : 'idle'"
|
||||
:title="t('switchChannel')"
|
||||
@click="emit('selectChannel', channelItem)"
|
||||
>
|
||||
<Icon
|
||||
v-if="!getChannelSpacer(channelItem)"
|
||||
:name="channelItem.passwordProtected ? 'lock' : 'speaker'"
|
||||
:size="16"
|
||||
/>
|
||||
<span>{{ channelItem.name }}</span>
|
||||
<small>{{ channelItem.members.length }}</small>
|
||||
<ChannelSpacer v-if="getChannelSpacer(channelItem)" :spacer="getChannelSpacer(channelItem)!" />
|
||||
<span v-else>{{ channelItem.name }}</span>
|
||||
<small v-if="!getChannelSpacer(channelItem)">{{ channelItem.members.length }}</small>
|
||||
</button>
|
||||
<div
|
||||
v-if="channelItem.members.length"
|
||||
@@ -170,7 +173,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
v-else-if="!getChannelSpacer(channelItem)"
|
||||
class="channel-no-members"
|
||||
>{{ t("noMembersInChannel") }}</div
|
||||
>
|
||||
@@ -188,6 +191,8 @@
|
||||
<script setup lang="ts">
|
||||
import type { CSSProperties } from "vue";
|
||||
import Icon from "../Icon.vue";
|
||||
import ChannelSpacer from "./ChannelSpacer.vue";
|
||||
import { getChannelSpacer } from "../../../../src/shared/channel-spacer.js";
|
||||
import { memberPresenceKey } from "../../services/member-presence.js";
|
||||
import type { TreeChannel } from "../../composables/useWebClientChannels.js";
|
||||
import type { useWebClientMembers } from "../../composables/useWebClientMembers.js";
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<template>
|
||||
<span
|
||||
class="ws-channel-spacer"
|
||||
data-ws-part="voice.channel-spacer"
|
||||
:data-alignment="spacer.alignment"
|
||||
:data-spacer-style="spacer.style"
|
||||
:aria-label="spacer.text || undefined"
|
||||
><span :aria-hidden="spacer.alignment === 'repeat' || spacer.style !== 'text' ? 'true' : undefined">{{ displayText }}</span></span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import type { ChannelSpacer } from "../../../../src/shared/channel-spacer.js";
|
||||
|
||||
const props = defineProps<{ spacer: ChannelSpacer }>();
|
||||
const displayText = computed(() => {
|
||||
if (props.spacer.style !== "text") return "";
|
||||
const text = props.spacer.text;
|
||||
// Clip a bounded run in CSS rather than measuring DOM or growing with viewport width.
|
||||
return props.spacer.alignment === "repeat" && text
|
||||
? text.repeat(Math.max(1, Math.floor(1024 / text.length)))
|
||||
: text;
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ws-channel-spacer {
|
||||
display: block;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
min-height: 1.3em;
|
||||
overflow: hidden;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
line-height: 1.3;
|
||||
text-align: left;
|
||||
}
|
||||
.ws-channel-spacer > span { white-space: pre; }
|
||||
.ws-channel-spacer[data-alignment="center"] { text-align: center; }
|
||||
.ws-channel-spacer[data-alignment="right"] { text-align: right; }
|
||||
.ws-channel-spacer:where(:not([data-spacer-style="text"]))::before {
|
||||
content: "";
|
||||
display: block;
|
||||
margin-block: .6em;
|
||||
border-top: 1px solid currentColor;
|
||||
opacity: .55;
|
||||
}
|
||||
.ws-channel-spacer[data-spacer-style="dashed"]::before { border-top-style: dashed; }
|
||||
.ws-channel-spacer[data-spacer-style="dotted"]::before { border-top-style: dotted; }
|
||||
.ws-channel-spacer[data-spacer-style="dash-dot"]::before,
|
||||
.ws-channel-spacer[data-spacer-style="dash-dot-dot"]::before {
|
||||
height: 1px;
|
||||
border: 0;
|
||||
background: repeating-linear-gradient(to right, currentColor 0 6px, transparent 6px 9px, currentColor 9px 11px, transparent 11px 14px);
|
||||
}
|
||||
.ws-channel-spacer[data-spacer-style="dash-dot-dot"]::before {
|
||||
background: repeating-linear-gradient(to right, currentColor 0 6px, transparent 6px 9px, currentColor 9px 11px, transparent 11px 14px, currentColor 14px 16px, transparent 16px 19px);
|
||||
}
|
||||
</style>
|
||||
@@ -138,18 +138,35 @@ function updateStageSize(): void {
|
||||
const stage = stageElement.value;
|
||||
const player = playerElement.value ?? stage?.parentElement ?? null;
|
||||
if (!stage || !player) return;
|
||||
if (screenShareFullscreen.value) {
|
||||
// Read the browser's fullscreen element directly. The Vue state is updated
|
||||
// by a separate fullscreenchange listener and can lag the layout transition.
|
||||
if (typeof document !== "undefined" && document.fullscreenElement === player) {
|
||||
const fullscreenHeight = typeof CSS !== "undefined" && CSS.supports("height", "100dvh") ? "100dvh" : "100vh";
|
||||
setInlineStyle(player, "position", "fixed");
|
||||
setInlineStyle(player, "inset", "0");
|
||||
setInlineStyle(player, "width", "100vw");
|
||||
setInlineStyle(player, "height", "100vh");
|
||||
setInlineStyle(player, "height", fullscreenHeight);
|
||||
setInlineStyle(player, "max-width", "none");
|
||||
setInlineStyle(player, "max-height", "none");
|
||||
setInlineStyle(player, "margin", "0");
|
||||
setInlineStyle(stage, "width", "100%");
|
||||
setInlineStyle(stage, "height", "100%");
|
||||
setInlineStyle(stage, "min-height", "0");
|
||||
setInlineStyle(stage, "max-height", "none");
|
||||
setInlineStyle(stage, "aspect-ratio", "auto");
|
||||
return;
|
||||
}
|
||||
setInlineStyle(player, "position", null);
|
||||
setInlineStyle(player, "inset", null);
|
||||
setInlineStyle(player, "width", null);
|
||||
setInlineStyle(player, "height", null);
|
||||
setInlineStyle(player, "max-width", null);
|
||||
setInlineStyle(player, "max-height", null);
|
||||
setInlineStyle(player, "margin", null);
|
||||
setInlineStyle(stage, "width", null);
|
||||
setInlineStyle(stage, "height", null);
|
||||
setInlineStyle(stage, "min-height", null);
|
||||
setInlineStyle(stage, "max-height", null);
|
||||
setInlineStyle(stage, "aspect-ratio", "auto");
|
||||
}
|
||||
|
||||
@@ -168,9 +185,13 @@ function setStageElement(element: unknown): void {
|
||||
updateStageSize();
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener("resize", updateStageSize));
|
||||
onMounted(() => {
|
||||
window.addEventListener("resize", updateStageSize);
|
||||
document.addEventListener("fullscreenchange", updateStageSize);
|
||||
});
|
||||
watch(screenShareFullscreen, updateStageSize);
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("resize", updateStageSize);
|
||||
document.removeEventListener("fullscreenchange", updateStageSize);
|
||||
});
|
||||
</script>
|
||||
@@ -16,7 +16,7 @@
|
||||
type="button"
|
||||
class="ws-voice-channel-expander"
|
||||
data-ws-part="voice.channel-tree.expander"
|
||||
:aria-label="`${expanded ? '收起' : '展开'} ${node.channel.name} / ${expanded ? 'Collapse' : 'Expand'} channel`"
|
||||
:aria-label="`${expanded ? '收起' : '展开'} ${displayName} / ${expanded ? 'Collapse' : 'Expand'} channel`"
|
||||
:aria-expanded="expanded"
|
||||
@click.stop="emit('toggle', node.channel.id)"
|
||||
><Icon :name="expanded ? 'chevron-down' : 'chevron-right'" :size="13" /></button>
|
||||
@@ -24,8 +24,9 @@
|
||||
type="button"
|
||||
class="ws-voice-channel-row"
|
||||
data-ws-part="voice.channel-tree.row"
|
||||
:data-spacer="spacer ? 'true' : undefined"
|
||||
:data-drag-over="memberDragDrop && dragOverChannelId === node.channel.id ? 'true' : undefined"
|
||||
:title="`双击或按 Enter 加入 ${node.channel.name} / Double-click or press Enter to join${node.channel.passwordProtected ? ' · 需要频道密码 / Channel password required' : ''}`"
|
||||
:title="`双击或按 Enter 加入 ${displayName} / Double-click or press Enter to join${node.channel.passwordProtected ? ' · 需要频道密码 / Channel password required' : ''}`"
|
||||
:data-password-protected="node.channel.passwordProtected ? 'true' : undefined"
|
||||
@click="emit('select', node.channel.id)"
|
||||
@dblclick.stop.prevent="join"
|
||||
@@ -35,15 +36,17 @@
|
||||
@drop="handleChannelDrop($event)"
|
||||
>
|
||||
<Icon
|
||||
v-if="!spacer"
|
||||
class="ws-voice-channel-type"
|
||||
data-ws-part="voice.channel-tree.icon"
|
||||
:name="node.channel.passwordProtected ? 'lock' : 'speaker'"
|
||||
:data-password-protected="node.channel.passwordProtected ? 'true' : 'false'"
|
||||
:size="14"
|
||||
/>
|
||||
<span class="ws-voice-channel-name" data-ws-part="voice.channel-tree.name">{{ node.channel.name }}</span>
|
||||
<span v-if="selected && !current" class="ws-voice-channel-join-hint" data-ws-part="voice.channel-tree.join-hint">双击加入</span>
|
||||
<span class="ws-voice-channel-count" data-ws-part="voice.channel-tree.count">
|
||||
<ChannelSpacer v-if="spacer" :spacer="spacer" />
|
||||
<span v-else class="ws-voice-channel-name" data-ws-part="voice.channel-tree.name">{{ node.channel.name }}</span>
|
||||
<span v-if="!spacer && selected && !current" class="ws-voice-channel-join-hint" data-ws-part="voice.channel-tree.join-hint">双击加入</span>
|
||||
<span v-if="!spacer" class="ws-voice-channel-count" data-ws-part="voice.channel-tree.count">
|
||||
{{ memberCount }}<template v-if="node.channel.maxClientsLimited && typeof node.channel.maxClients === 'number'">/{{ node.channel.maxClients }}</template>
|
||||
</span>
|
||||
</button>
|
||||
@@ -230,6 +233,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, type CSSProperties } from "vue";
|
||||
import Icon from "../Icon.vue";
|
||||
import ChannelSpacer from "./ChannelSpacer.vue";
|
||||
import { channelDisplayName, getChannelSpacer } from "../../../../src/shared/channel-spacer.js";
|
||||
import type { ChannelMember } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { TreeChannel } from "../../composables/useWebClientChannels.js";
|
||||
import type { VoiceChannelTreeNode } from "../../services/voice-channel-tree.js";
|
||||
@@ -267,6 +272,8 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const expanded = computed(() => props.expandedIds.has(props.node.channel.id));
|
||||
const spacer = computed(() => getChannelSpacer(props.node.channel));
|
||||
const displayName = computed(() => channelDisplayName(props.node.channel));
|
||||
const hasChildren = computed(() => props.node.children.length > 0);
|
||||
const hasContents = computed(() => hasChildren.value || props.node.channel.members.length > 0);
|
||||
const isExpandable = computed(() => props.layout === "server-sidebar" ? hasChildren.value : hasContents.value);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<section
|
||||
v-if="!connected"
|
||||
class="voice-connection-status"
|
||||
data-ws-part="voice.connection-status"
|
||||
:data-ws-state="connecting ? 'connecting' : error ? 'failed' : 'disconnected'"
|
||||
>
|
||||
<p role="status" aria-live="polite" data-ws-part="voice.connection-status.message">
|
||||
{{ connecting ? t('connecting') : error || t('voiceHealthDisconnected') }}
|
||||
</p>
|
||||
<label data-ws-part="voice.connection-status.nickname">
|
||||
<span>{{ t('nickname') }}</span>
|
||||
<input
|
||||
:value="nickname"
|
||||
:disabled="connecting"
|
||||
maxlength="30"
|
||||
autocomplete="nickname"
|
||||
data-ws-part="voice.connection-status.nickname.input"
|
||||
@input="$emit('update:nickname', ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="!canConnect || connecting"
|
||||
data-ws-part="voice.connection-status.reconnect"
|
||||
@click="$emit('connect')"
|
||||
><Icon v-if="connecting" name="refresh" :size="16" />{{ t('reconnectNow') }}</button>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import Icon from "../Icon.vue";
|
||||
|
||||
defineProps<{
|
||||
connected: boolean;
|
||||
connecting: boolean;
|
||||
nickname: string;
|
||||
error: string;
|
||||
canConnect: boolean;
|
||||
t: (key: string) => string;
|
||||
}>();
|
||||
defineEmits<{ connect: []; 'update:nickname': [value: string] }>();
|
||||
</script>
|
||||
@@ -27,15 +27,30 @@ const eventLabels: Record<string, AdminTranslationKey> = {
|
||||
ADMIN_SKIN_INSTALLED: "skinInstalledEvent", ADMIN_SKIN_REMOVED: "skinRemovedEvent",
|
||||
ADMIN_SKIN_ENABLED: "skinEnabledEvent", ADMIN_SKIN_DISABLED: "skinDisabledEvent",
|
||||
INVITE_CREATED: "inviteCreatedEvent", INVITE_REVOKED: "inviteRevokedEvent", INVITE_CONSUMED: "inviteConsumedEvent",
|
||||
TS_ADMIN_SETTINGS_UPDATED: "tsAdminSaved",
|
||||
TS_ADMIN_OVERVIEW_READ: "tsAdminReadEvent",
|
||||
TS_ADMIN_OVERVIEW_FAILED: "tsAdminReadFailedEvent",
|
||||
TS_ADMIN_ACTION_SUCCEEDED: "tsAdminActionSuccessEvent", TS_ADMIN_ACTION_FAILED: "tsAdminActionFailureEvent", TS_ADMIN_ACTION_PARTIAL: "tsAdminActionPartialEvent",
|
||||
};
|
||||
const errorLabels: Record<string, AdminTranslationKey> = {
|
||||
INVALID_PASSWORD: "invalidPassword", INVALID_ADMIN_PASSWORD: "setupPasswordShort", PASSWORD_CHANGE_REQUIRED: "changePasswordLead", RATE_LIMITED: "rateLimited",
|
||||
INVALID_WEBRTC_PUBLIC_HOST: "invalidWebRtcNetworkError", INVALID_WEBRTC_STUN_SERVER: "invalidWebRtcNetworkError", INVALID_WEBRTC_IPV6: "invalidWebRtcNetworkError",
|
||||
INVALID_WEBRTC_PORT_RANGE: "invalidWebRtcPortRangeError", WEBRTC_PORT_LOCKED: "webRtcPortLockedError",
|
||||
INVALID_RELAY_NAME: "invalidRelayNameError", INVALID_RELAY_TARGET: "invalidRelayTargetError", INVALID_RELAY_TOKEN: "invalidRelayTokenError",
|
||||
INVALID_RELAY_NAME: "invalidRelayNameError", INVALID_RELAY_TARGET: "invalidRelayTargetError", INVALID_RELAY_VOICE_ENDPOINT: "invalidRelayVoiceEndpointError", INVALID_RELAY_TOKEN: "invalidRelayTokenError",
|
||||
INVALID_TARGET: "invalidTargetError", PING_UNAVAILABLE: "icmpUnavailableError", HOST_NOT_FOUND: "probeHostNotFoundError",
|
||||
UNREACHABLE: "probeUnreachableError", TIMEOUT: "probeTimeoutError", PROTOCOL_NEGOTIATION_FAILED: "probeProtocolError",
|
||||
SERVER_REJECTED: "probeRejectedError", TARGET_NOT_ALLOWED: "targetNotAllowedError",
|
||||
TS_ADMIN_FIXED_MODE_REQUIRED: "tsAdminFixedOnlyError", TS_ADMIN_NOT_CONFIGURED: "tsAdminNotConfiguredError",
|
||||
INVALID_TS_ADMIN_QUERY_PORT: "tsAdminInvalidPortError", INVALID_TS_ADMIN_USERNAME: "tsAdminInvalidUsernameError",
|
||||
INVALID_TS_ADMIN_HOST_KEY: "tsAdminInvalidHostKeyError", INVALID_TS_ADMIN_PASSWORD: "tsAdminInvalidPasswordError",
|
||||
TS_ADMIN_HOST_KEY_MISMATCH: "tsAdminHostKeyMismatchError", TS_ADMIN_TARGET_UNAVAILABLE: "tsAdminTargetError",
|
||||
TS_ADMIN_CONNECTION_FAILED: "tsAdminConnectionError", TS_ADMIN_CREDENTIALS_UNAVAILABLE: "tsAdminCredentialError",
|
||||
INVALID_TS_ADMIN_URL: "tsAdminUrlError", INVALID_TS_ADMIN_API_KEY: "tsAdminKeyError", INVALID_TS_ADMIN_HOST: "tsAdminHostError",
|
||||
INVALID_TS_ADMIN_SERVER_ID: "tsAdminServerIdError", INVALID_TS_ADMIN_SETTINGS: "tsAdminActionError", INVALID_TS_ADMIN_ACTION: "tsAdminActionError",
|
||||
TS_ADMIN_PERMISSION_DENIED: "tsAdminPermissionError", TS_ADMIN_AUTH_FAILED: "tsAdminAuthError", TS_ADMIN_OPERATION_FAILED: "tsAdminActionError",
|
||||
TS_ADMIN_CLIENT_CHANGED: "tsAdminClientChanged", TS_ADMIN_CONFIG_CHANGED: "tsAdminConfigChanged", TS_ADMIN_PARTIAL_SUCCESS: "tsAdminPartialError",
|
||||
TS_ADMIN_RATE_LIMITED: "tsAdminRateError", TS_ADMIN_TLS_FAILED: "tsAdminTlsError",
|
||||
TS_ADMIN_READ_FAILED: "tsAdminReadError", TS_ADMIN_TIMEOUT: "tsAdminTimeoutError",
|
||||
};
|
||||
const connectionErrors: Record<string, AdminTranslationKey> = {
|
||||
PASSWORD_REQUIRED: "serverPasswordRequiredError", SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createAdminRequests } from "../services/admin-requests.js";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget, suggestedTeamSpeakPort } from "../services/teamspeak-target.js";
|
||||
|
||||
type SecretAction = "keep" | "replace" | "remove";
|
||||
interface RelayNodeForm { id: string; name: string; enabled: boolean; target: string; token: string; tokenAction: SecretAction; hasToken: boolean }
|
||||
interface RelayNodeForm { id: string; name: string; enabled: boolean; target: string; voiceEndpoint: string; token: string; tokenAction: SecretAction; hasToken: boolean }
|
||||
interface ProbeState { ok: boolean; checkType?: "network" | "protocol"; latencyMs?: number; serverName?: string | null; packetLossPercent?: number; code?: string; errorCode?: string }
|
||||
interface Options { api: AdminApi; errorMessage: Ref<string>; errorText(code?: string): string; refreshOverview(): Promise<void> }
|
||||
|
||||
@@ -23,6 +23,7 @@ const snapshot = (form: ServerForm): ServerForm => JSON.parse(JSON.stringify(for
|
||||
export function useAdminServerSettings(options: Options) {
|
||||
const requests = createAdminRequests();
|
||||
const serverForm = reactive(emptyForm());
|
||||
const savedSettings = ref<AdminSettings | null>(null);
|
||||
const serverSaving = ref(false);
|
||||
const testing = ref(false);
|
||||
const testResult = ref<ProbeState | null>(null);
|
||||
@@ -38,7 +39,7 @@ export function useAdminServerSettings(options: Options) {
|
||||
serverSaving.value = false;
|
||||
testing.value = false;
|
||||
}
|
||||
function reset() { cancelRequests(); Object.assign(serverForm, emptyForm()); testResult.value = null; }
|
||||
function reset() { cancelRequests(); Object.assign(serverForm, emptyForm()); savedSettings.value = null; testResult.value = null; }
|
||||
onScopeDispose(cancelRequests);
|
||||
function invalidateProbe() {
|
||||
probeRevision++;
|
||||
@@ -53,6 +54,7 @@ export function useAdminServerSettings(options: Options) {
|
||||
}, { flush: "sync" });
|
||||
|
||||
function mergeSettings(value: AdminSettings, baseline: ServerForm, observedProbeRevision: number): void {
|
||||
savedSettings.value = structuredClone(value);
|
||||
const target = splitTeamSpeakTarget(value.target);
|
||||
const next: ServerForm = { ...emptyForm(), ...value, address: target.address, port: target.port,
|
||||
relayNodes: value.relayNodes.map(node => ({ ...node, token: "", tokenAction: "keep" })),
|
||||
@@ -85,7 +87,7 @@ export function useAdminServerSettings(options: Options) {
|
||||
const old = oldNodes.get(node.id), saved = savedNodes.get(node.id);
|
||||
if (!old || !saved) return node;
|
||||
const merged = { ...node, hasToken: saved.hasToken };
|
||||
for (const key of ["name", "target", "enabled"] as const) {
|
||||
for (const key of ["name", "target", "voiceEndpoint", "enabled"] as const) {
|
||||
if (node[key] === old[key]) Object.assign(merged, { [key]: saved[key] });
|
||||
}
|
||||
if (node.token === old.token && node.tokenAction === old.tokenAction) {
|
||||
@@ -103,7 +105,7 @@ export function useAdminServerSettings(options: Options) {
|
||||
welcomeText: serverForm.welcomeText, welcomeTextEn: serverForm.welcomeTextEn, welcomeTextDe: serverForm.welcomeTextDe, welcomeTextRu: serverForm.welcomeTextRu, welcomeTextJa: serverForm.welcomeTextJa,
|
||||
webRtcPublicHost: serverForm.webRtcPublicHost, webRtcIpv6Enabled: serverForm.webRtcIpv6Enabled, webRtcStunServer: serverForm.webRtcStunServer,
|
||||
webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd,
|
||||
relayNodes: serverForm.relayNodes.map(node => ({ id: node.id, name: node.name, target: node.target, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) };
|
||||
relayNodes: serverForm.relayNodes.map(node => ({ id: node.id, name: node.name, target: node.target, voiceEndpoint: node.voiceEndpoint, enabled: node.enabled, tokenAction: node.tokenAction, ...(node.tokenAction === "replace" ? { token: node.token } : {}) })) };
|
||||
}
|
||||
function report(error: unknown) {
|
||||
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
|
||||
@@ -148,8 +150,8 @@ export function useAdminServerSettings(options: Options) {
|
||||
} finally { if (request.isCurrent()) testing.value = false; request.finish(); }
|
||||
}
|
||||
function addRelayNode() {
|
||||
serverForm.relayNodes.push({ id: `relay-new-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, name: "", enabled: false, target: "", token: "", tokenAction: "replace", hasToken: false });
|
||||
serverForm.relayNodes.push({ id: `relay-new-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, name: "", enabled: false, target: "", voiceEndpoint: "", token: "", tokenAction: "replace", hasToken: false });
|
||||
}
|
||||
function removeRelayNode(index: number) { serverForm.relayNodes.splice(index, 1); }
|
||||
return { serverForm, serverSaving, testing, testResult, loadServerSettings, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode, cancelRequests, reset };
|
||||
return { serverForm, savedSettings, serverSaving, testing, testResult, loadServerSettings, saveServerSettings, testServerConnection, addRelayNode, removeRelayNode, cancelRequests, reset };
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { computed, onScopeDispose, ref } from "vue";
|
||||
import type { copy } from "../i18n/admin.js";
|
||||
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
|
||||
import { AdminApiError, isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
import { BUILTIN_SKIN_CATALOG, type SkinCatalogEntry } from "../services/skin-catalog.js";
|
||||
import { compareSkinVersions, type SkinStoreCatalog, type SkinStoreEntry } from "../../../src/shared/skin-store.js";
|
||||
|
||||
interface Options { api: AdminApi; tr(key: keyof typeof copy.zh): string }
|
||||
|
||||
@@ -12,20 +13,66 @@ export function useAdminSkins(options: Options) {
|
||||
const skinLoading = ref(false), skinUploading = ref(false), skinDefaultSaving = ref(false);
|
||||
const removingSkinId = ref(""), updatingSkinId = ref(""), skinDefaultId = ref("builtin.light");
|
||||
const skinManagerError = ref(""), skinManagerNotice = ref("");
|
||||
const skinBusy = computed(() => skinUploading.value || skinDefaultSaving.value || Boolean(removingSkinId.value || updatingSkinId.value));
|
||||
const skinTab = ref<"installed" | "store">("installed");
|
||||
const storeCatalog = ref<SkinStoreCatalog | null>(null), storeLoading = ref(false), storeInstallingId = ref("");
|
||||
const storeError = ref("");
|
||||
const skinBusy = computed(() => skinUploading.value || skinDefaultSaving.value || Boolean(removingSkinId.value || updatingSkinId.value || storeInstallingId.value));
|
||||
const enabledSkinEntries = computed(() => skinEntries.value.filter(skin => skin.builtIn || skin.enabled !== false));
|
||||
let savedDefault = "builtin.light";
|
||||
function cancelRequests() {
|
||||
requests.reset();
|
||||
skinLoading.value = false; skinUploading.value = false; skinDefaultSaving.value = false;
|
||||
removingSkinId.value = ""; updatingSkinId.value = "";
|
||||
storeLoading.value = false; storeInstallingId.value = ""; storeError.value = ""; skinTab.value = "installed";
|
||||
skinManagerError.value = ""; skinManagerNotice.value = "";
|
||||
}
|
||||
function reset() { cancelRequests(); skinEntries.value = []; savedDefault = skinDefaultId.value = "builtin.light"; }
|
||||
function reset() { cancelRequests(); skinEntries.value = []; storeCatalog.value = null; savedDefault = skinDefaultId.value = "builtin.light"; }
|
||||
onScopeDispose(reset);
|
||||
function report(error: unknown, upload = false) {
|
||||
if (!isAdminRequestCancelled(error)) skinManagerError.value = upload && error instanceof Error ? error.message : options.tr("operationFailed");
|
||||
}
|
||||
function storeFailure(error: unknown): string {
|
||||
const code = error instanceof AdminApiError ? error.code : "";
|
||||
if (["SKIN_STORE_CHANGED", "SKIN_STORE_INSTALLED_CHANGED", "SKIN_STORE_NOT_NEWER"].includes(code)) return options.tr("skinStoreChanged");
|
||||
if (code === "SKIN_STORE_INCOMPATIBLE") return options.tr("skinStoreIncompatible");
|
||||
if (code.startsWith("SKIN_") && code !== "SKIN_STORE_UNAVAILABLE" && code !== "SKIN_STORAGE_UNAVAILABLE") return options.tr("skinStoreInvalid");
|
||||
return options.tr("skinStoreUnavailable");
|
||||
}
|
||||
async function loadSkinStore(refresh = false) {
|
||||
if (storeLoading.value || skinBusy.value) return;
|
||||
const request = requests.begin("store");
|
||||
storeLoading.value = true; storeError.value = "";
|
||||
try {
|
||||
const [result] = await Promise.all([options.api.skinStore(refresh, request.signal), refresh ? loadSkinCatalog() : Promise.resolve()]);
|
||||
if (request.isCurrent()) storeCatalog.value = result;
|
||||
} catch (error) { if (request.isCurrent() && !isAdminRequestCancelled(error)) storeError.value = storeFailure(error); }
|
||||
finally { if (request.isCurrent()) storeLoading.value = false; request.finish(); }
|
||||
}
|
||||
function selectSkinTab(tab: "installed" | "store") {
|
||||
skinTab.value = tab;
|
||||
if (tab === "store" && !storeCatalog.value) void loadSkinStore();
|
||||
if (tab === "installed" && !skinBusy.value) void loadSkinCatalog();
|
||||
}
|
||||
function installedStoreSkin(entry: SkinStoreEntry) { return skinEntries.value.find(skin => skin.id === entry.id); }
|
||||
function storeVersionOrder(entry: SkinStoreEntry): number {
|
||||
const installed = installedStoreSkin(entry);
|
||||
return installed && entry.metadata ? compareSkinVersions(entry.metadata.version, installed.version) : 1;
|
||||
}
|
||||
async function installStoreSkin(entry: SkinStoreEntry) {
|
||||
if (skinBusy.value || skinLoading.value || !entry.metadata || !entry.compatible || storeVersionOrder(entry) <= 0) return;
|
||||
const installed = installedStoreSkin(entry);
|
||||
if (installed && !window.confirm(`${options.tr("skinStoreConfirm")}\n${entry.metadata.name}: ${installed.version} → ${entry.metadata.version}`)) return;
|
||||
requests.cancel("load"); requests.cancel("store"); storeLoading.value = false;
|
||||
const request = requests.begin("mutation");
|
||||
storeInstallingId.value = entry.id; skinManagerError.value = ""; skinManagerNotice.value = "";
|
||||
try {
|
||||
await options.api.installStoreSkin({ id: entry.id, revision: entry.revision, installedVersion: installed?.version ?? null }, request.signal);
|
||||
if (!request.isCurrent()) return;
|
||||
skinManagerNotice.value = options.tr("skinStoreSuccess");
|
||||
await loadSkinCatalog();
|
||||
} catch (error) { if (request.isCurrent() && !isAdminRequestCancelled(error)) skinManagerError.value = storeFailure(error); }
|
||||
finally { if (request.isCurrent()) storeInstallingId.value = ""; request.finish(); }
|
||||
}
|
||||
async function loadSkinCatalog() {
|
||||
const request = requests.begin("load"), selected = skinDefaultId.value;
|
||||
skinLoading.value = true; skinManagerError.value = "";
|
||||
@@ -98,5 +145,6 @@ export function useAdminSkins(options: Options) {
|
||||
finally { if (request.isCurrent()) removingSkinId.value = ""; request.finish(); }
|
||||
}
|
||||
return { skinEntries, skinLoading, skinUploading, skinDefaultSaving, removingSkinId, updatingSkinId, skinDefaultId,
|
||||
skinTab, storeCatalog, storeLoading, storeInstallingId, storeError, loadSkinStore, selectSkinTab, installStoreSkin, installedStoreSkin, storeVersionOrder,
|
||||
skinManagerError, skinManagerNotice, skinBusy, enabledSkinEntries, loadSkinCatalog, saveSkinDefault, toggleSkinEnabled, onSkinFileChanged, removeSkin, cancelRequests, reset };
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { computed, onScopeDispose, reactive, ref, watch, type Ref } from "vue";
|
||||
import type { TsAdminAction } from "../../../src/shared/admin-inputs.js";
|
||||
import type { copy } from "../i18n/admin.js";
|
||||
import type { AdminApi } from "../services/admin-api.js";
|
||||
import { isAdminRequestCancelled } from "../services/admin-api.js";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
|
||||
interface Options {
|
||||
api: AdminApi; errorMessage: Ref<string>; errorText(code?: string): string;
|
||||
tr(key: keyof typeof copy.zh, vars?: Record<string, string | number>): string;
|
||||
}
|
||||
const emptySettings = () => ({ fixedMode: true, enabled: false, transport: "web" as "web" | "ssh" | "tcp",
|
||||
queryHost: "", webQueryUrl: "", serverId: 0, queryPort: 10022, username: "serveradmin", hasPassword: false,
|
||||
hasApiKey: false, hostKeyFingerprint: "", updatedAt: "", configurationRevision: "" });
|
||||
const emptyForm = () => ({ enabled: false, transport: "web" as "web" | "ssh" | "tcp", queryHost: "", webQueryUrl: "", serverId: 0,
|
||||
queryPort: "10022", username: "serveradmin", password: "", passwordAction: "keep" as "keep" | "replace" | "remove",
|
||||
apiKey: "", apiKeyAction: "keep" as "keep" | "replace" | "remove", hostKeyFingerprint: "" });
|
||||
type Form = ReturnType<typeof emptyForm>;
|
||||
const emptyEditor = () => ({ action: "" as TsAdminAction["action"] | "", id: "", uid: "", targetName: "", name: "", description: "",
|
||||
parentId: "0", channelId: "", groupId: "", password: "", permanent: true, remove: false, reason: "", durationSeconds: 3600,
|
||||
welcomeMessage: "", maxClients: 32 });
|
||||
|
||||
export function useAdminTsAdmin(options: Options) {
|
||||
const requests = createAdminRequests();
|
||||
const settings = reactive(emptySettings()), form = reactive(emptyForm()), editor = reactive(emptyEditor());
|
||||
const overview = ref<Awaited<ReturnType<AdminApi["tsAdminOverview"]>> | null>(null);
|
||||
const noticeMessage = ref("");
|
||||
const refreshWarning = ref("");
|
||||
const loading = ref(false), saving = ref(false), connecting = ref(false), acting = ref(false);
|
||||
const settingsDirty = computed(() => form.enabled !== settings.enabled || form.transport !== settings.transport
|
||||
|| form.queryHost !== settings.queryHost || form.webQueryUrl !== settings.webQueryUrl
|
||||
|| form.serverId !== settings.serverId || form.queryPort !== String(settings.queryPort)
|
||||
|| form.username !== (settings.username || "serveradmin") || form.hostKeyFingerprint !== settings.hostKeyFingerprint
|
||||
|| form.passwordAction !== "keep" || form.apiKeyAction !== "keep" || Boolean(form.password) || Boolean(form.apiKey));
|
||||
let applyingSettings = false;
|
||||
watch(() => form.transport, (next, previous) => {
|
||||
if (applyingSettings) return;
|
||||
if (next === "ssh" && form.queryPort === "10011") form.queryPort = "10022";
|
||||
else if (next === "tcp" && (previous === "web" || form.queryPort === "10022")) form.queryPort = "10011";
|
||||
}, { flush: "sync" });
|
||||
function cancelRequests() {
|
||||
requests.reset(); loading.value = false; saving.value = false; connecting.value = false; acting.value = false;
|
||||
Object.assign(editor, emptyEditor());
|
||||
refreshWarning.value = "";
|
||||
}
|
||||
function reset() {
|
||||
cancelRequests(); Object.assign(settings, emptySettings()); Object.assign(form, emptyForm()); overview.value = null; noticeMessage.value = "";
|
||||
}
|
||||
onScopeDispose(reset);
|
||||
function report(error: unknown) {
|
||||
if (!isAdminRequestCancelled(error)) options.errorMessage.value = options.errorText((error as { code?: string }).code);
|
||||
}
|
||||
function mergeSettings(value: Awaited<ReturnType<AdminApi["tsAdminSettings"]>>, baseline: Form) {
|
||||
if (settings.configurationRevision && settings.configurationRevision !== value.configurationRevision) {
|
||||
requests.cancel("overview"); connecting.value = false; overview.value = null; Object.assign(editor, emptyEditor());
|
||||
refreshWarning.value = "";
|
||||
}
|
||||
Object.assign(settings, value);
|
||||
const next: Form = { enabled: value.enabled, transport: value.transport, queryHost: value.queryHost, webQueryUrl: value.webQueryUrl,
|
||||
serverId: value.serverId, queryPort: String(value.queryPort), username: value.username || "serveradmin", password: "", passwordAction: "keep",
|
||||
apiKey: "", apiKeyAction: "keep", hostKeyFingerprint: value.hostKeyFingerprint };
|
||||
const changedApiKey = form.apiKey !== baseline.apiKey, changedPassword = form.password !== baseline.password;
|
||||
const changedTransport = form.transport !== baseline.transport;
|
||||
applyingSettings = true;
|
||||
try {
|
||||
for (const key of Object.keys(next) as Array<keyof Form>) {
|
||||
if (key === "apiKeyAction" && changedApiKey || key === "passwordAction" && changedPassword || key === "queryPort" && changedTransport) continue;
|
||||
if (form[key] === baseline[key]) Object.assign(form, { [key]: next[key] });
|
||||
}
|
||||
} finally { applyingSettings = false; }
|
||||
}
|
||||
async function loadSettings() {
|
||||
const request = requests.begin("settings"), baseline = { ...form };
|
||||
loading.value = true; options.errorMessage.value = "";
|
||||
try { const value = await options.api.tsAdminSettings(request.signal); if (request.isCurrent()) mergeSettings(value, baseline); }
|
||||
catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) loading.value = false; request.finish(); }
|
||||
}
|
||||
async function saveSettings() {
|
||||
if (saving.value || acting.value) return;
|
||||
requests.cancel("overview"); connecting.value = false;
|
||||
const request = requests.begin("settings"), baseline = { ...form };
|
||||
saving.value = true; loading.value = false; options.errorMessage.value = ""; noticeMessage.value = ""; refreshWarning.value = "";
|
||||
try {
|
||||
const saved = await options.api.saveTsAdminSettings({ ...baseline, queryPort: Number(baseline.queryPort),
|
||||
password: baseline.passwordAction === "replace" ? baseline.password : undefined,
|
||||
apiKey: baseline.apiKeyAction === "replace" ? baseline.apiKey : undefined,
|
||||
}, request.signal);
|
||||
if (!request.isCurrent()) return;
|
||||
mergeSettings(saved.settings, baseline); overview.value = null; Object.assign(editor, emptyEditor());
|
||||
noticeMessage.value = options.tr("tsAdminSaved");
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) saving.value = false; request.finish(); }
|
||||
}
|
||||
function listErrorText(code?: string | null) { return options.errorText(code || "TS_ADMIN_READ_FAILED"); }
|
||||
async function connectAndRefresh() { await readOverview(false); }
|
||||
async function readOverview(afterAction: boolean) {
|
||||
if (loading.value || connecting.value || saving.value || acting.value || settingsDirty.value || !settings.enabled || !settings.fixedMode) return;
|
||||
const request = requests.begin("overview");
|
||||
connecting.value = true; options.errorMessage.value = ""; refreshWarning.value = "";
|
||||
try { const value = await options.api.tsAdminOverview(request.signal); if (request.isCurrent()) overview.value = value; }
|
||||
catch (error) {
|
||||
if (request.isCurrent() && !isAdminRequestCancelled(error)) {
|
||||
if (afterAction) refreshWarning.value = options.tr("tsAdminRefreshError", { error: listErrorText((error as { code?: string }).code) });
|
||||
else report(error);
|
||||
}
|
||||
}
|
||||
finally { if (request.isCurrent()) connecting.value = false; request.finish(); }
|
||||
}
|
||||
function beginAction(action: TsAdminAction["action"], target?: { id: number | string; uid?: string; nickname?: string; name?: string; channelID?: string }) {
|
||||
if (acting.value || saving.value || loading.value || settingsDirty.value || !settings.enabled || !settings.fixedMode || !overview.value) return;
|
||||
Object.assign(editor, emptyEditor(), { action, id: String(target?.id ?? ""), uid: target?.uid ?? "",
|
||||
targetName: target?.nickname || target?.name || target?.uid || String(target?.id ?? ""), name: target?.name ?? "",
|
||||
channelId: target?.channelID ?? overview.value.channels[0]?.id ?? "", groupId: overview.value.groups[0]?.id ?? "",
|
||||
...(action === "server.update" ? { name: overview.value.serverName, welcomeMessage: overview.value.welcomeMessage, maxClients: overview.value.maxClients } : {}),
|
||||
});
|
||||
}
|
||||
function closeAction() { if (!acting.value) Object.assign(editor, emptyEditor()); }
|
||||
function actionPayload(): TsAdminAction {
|
||||
const action = editor.action;
|
||||
if (action === "server.update") return { action, name: editor.name, welcomeMessage: editor.welcomeMessage, maxClients: Number(editor.maxClients) };
|
||||
if (action === "channel.create") return { action, name: editor.name, description: editor.description, parentId: editor.parentId,
|
||||
permanent: editor.permanent, ...(editor.password ? { password: editor.password } : {}) };
|
||||
if (action === "channel.update") return { action, channelId: editor.id, name: editor.name };
|
||||
if (action === "channel.delete") return { action, channelId: editor.id };
|
||||
if (action === "ban.delete") return { action, banId: editor.id };
|
||||
const member = { clientId: Number(editor.id), clientUid: editor.uid };
|
||||
if (action === "client.move") return { action, ...member, channelId: editor.channelId };
|
||||
if (action === "client.kick") return { action, ...member, reason: editor.reason };
|
||||
if (action === "client.ban") return { action, ...member, reason: editor.reason, durationSeconds: Number(editor.durationSeconds) };
|
||||
if (action === "client.group") return { action, ...member, groupId: editor.groupId, remove: editor.remove };
|
||||
throw new Error("INVALID_TS_ADMIN_ACTION");
|
||||
}
|
||||
async function runAction() {
|
||||
if (acting.value || saving.value || loading.value || settingsDirty.value || !settings.enabled || !settings.fixedMode || !editor.action || !overview.value) return;
|
||||
requests.cancel("overview"); connecting.value = false;
|
||||
const request = requests.begin("action"), body = { operation: actionPayload(), configurationRevision: overview.value.configurationRevision };
|
||||
acting.value = true; options.errorMessage.value = ""; noticeMessage.value = ""; refreshWarning.value = "";
|
||||
try {
|
||||
await options.api.tsAdminAction(body, request.signal);
|
||||
if (!request.isCurrent()) return;
|
||||
Object.assign(editor, emptyEditor()); noticeMessage.value = options.tr("tsAdminActionSaved"); overview.value = null;
|
||||
// A failed refresh must never retry the write or report that it did not happen.
|
||||
acting.value = false;
|
||||
await readOverview(true);
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) acting.value = false; request.finish(); }
|
||||
}
|
||||
return { settings, form, editor, overview, settingsDirty, noticeMessage, refreshWarning, listErrorText, loading, saving, connecting, acting,
|
||||
loadSettings, saveSettings, connectAndRefresh, beginAction, closeAction, runAction, cancelRequests, reset };
|
||||
}
|
||||
@@ -944,6 +944,7 @@ export function useVoiceWebSocket() {
|
||||
RATE_LIMITED: "请求过于频繁,请稍后重试",
|
||||
TARGET_NOT_ALLOWED: "此 TeamSpeak 服务器地址不允许连接",
|
||||
ACCELERATION_UNAVAILABLE: "当前中继加速不可用,请关闭加速或联系管理员",
|
||||
VOICE_GATEWAY_UNAVAILABLE: "中继语音网关暂不可连接,请检查管理员配置与 HTTPS 证书",
|
||||
INVALID_NICKNAME: "请输入有效的昵称",
|
||||
INVITE_INVALID: "邀请链接已失效或已被撤销",
|
||||
REQUEST_TIMEOUT: "等待 WebSpeak 网关响应超时,请检查网络后重试",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { computed, onScopeDispose, ref, watch, type Ref } from "vue";
|
||||
import { saveLocalPreferences, type LocalPreferences, type RecentServer } from "../services/local-persistence.js";
|
||||
|
||||
export interface VoiceWorkspaceSnapshot {
|
||||
preferences: LocalPreferences;
|
||||
recent: readonly RecentServer[];
|
||||
}
|
||||
/** The selected package opts in; persistence and lifecycle remain host-owned. */
|
||||
export function useVoiceWorkspace(options: {
|
||||
enabled: Readonly<Ref<boolean>>;
|
||||
connected: Readonly<Ref<boolean>>;
|
||||
save?: typeof saveLocalPreferences;
|
||||
}) {
|
||||
const hasConnected = ref(false);
|
||||
const active = computed(() => options.enabled.value && hasConnected.value);
|
||||
let epoch = 0;
|
||||
let disposed = false;
|
||||
let pendingSave: AbortController | undefined;
|
||||
function remember() {
|
||||
if (disposed) return;
|
||||
hasConnected.value = true;
|
||||
pendingSave?.abort();
|
||||
pendingSave = new AbortController();
|
||||
void (options.save ?? saveLocalPreferences)({ schemaVersion: 1, hasConnected: true }, pendingSave.signal).catch(() => undefined);
|
||||
}
|
||||
watch(options.connected, connected => { if (connected) remember(); }, { flush: "sync", immediate: true });
|
||||
async function restore(
|
||||
load: () => Promise<VoiceWorkspaceSnapshot>,
|
||||
apply?: (snapshot: VoiceWorkspaceSnapshot) => void,
|
||||
): Promise<VoiceWorkspaceSnapshot | undefined> {
|
||||
const owner = epoch;
|
||||
try {
|
||||
const snapshot = await load();
|
||||
if (disposed || owner !== epoch) return;
|
||||
if (snapshot.preferences.hasConnected === true || snapshot.recent.length > 0) {
|
||||
hasConnected.value = true;
|
||||
if (snapshot.preferences.hasConnected !== true) remember();
|
||||
}
|
||||
apply?.(snapshot);
|
||||
return snapshot;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
function reset() {
|
||||
epoch++;
|
||||
pendingSave?.abort();
|
||||
pendingSave = undefined;
|
||||
hasConnected.value = false;
|
||||
}
|
||||
onScopeDispose(() => { disposed = true; reset(); });
|
||||
return { active, hasConnected, restore, reset };
|
||||
}
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user