mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-11-30 18:42:49 +08:00
feat: add GitHub skin store and organize instance administration
Adopt the pinned published TeamSpeak SDK and direct relay routing. Add optional TeamSpeak Query administration with encrypted credentials and separate WebSpeak access, site, operations and skin management. Distribute Discord Voice through the GitHub skin index, preserve skin state during updates, and correct KAAK scaling and screen fullscreen. Validation: 831 tests; backend and frontend builds; five-language UI checks from narrow screens through 4K and local Query fixture actions.
This commit is contained in:
1 parent
180bfeb52f
commit
0af3236c30
95 files changed
+7678
-709
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)
|
||||
|
||||
+25
-8
@@ -35,12 +35,23 @@ Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, V
|
||||
|
||||
## TeamSpeak-Versionskompatibilität
|
||||
|
||||
WebSpeak verwendet das TeamSpeak-Clientprotokoll statt ServerQuery oder WebQuery; Query-Zugangsdaten sind daher nicht erforderlich.
|
||||
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.
|
||||
- Die zugrunde liegende [`@echosixhiya/teamspeak-client`](https://github.com/EchoSixHIYA/teamspeak-js)-Bibliothek unterstützt auch TeamSpeak 5; WebSpeak zielt jedoch auf TeamSpeak 3 und 6.
|
||||
- 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
|
||||
|
||||
@@ -95,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
|
||||
|
||||
@@ -103,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' \
|
||||
@@ -147,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.
|
||||
@@ -263,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)
|
||||
|
||||
@@ -303,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
|
||||
|
||||
+25
-8
@@ -37,12 +37,23 @@ Network conditions and load may vary at either demo. Latency, disconnections, or
|
||||
|
||||
## TeamSpeak version compatibility
|
||||
|
||||
WebSpeak connects through the standard TeamSpeak client protocol, not ServerQuery or WebQuery, so no query credentials are required.
|
||||
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 underlying [`@echosixhiya/teamspeak-client`](https://github.com/EchoSixHIYA/teamspeak-js) also speaks TeamSpeak 5, but WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
|
||||
- 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
|
||||
|
||||
@@ -105,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
|
||||
|
||||
@@ -113,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' \
|
||||
@@ -157,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.
|
||||
@@ -273,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)
|
||||
|
||||
@@ -313,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
|
||||
|
||||
+14
-4
@@ -41,12 +41,23 @@
|
||||
|
||||
## TeamSpeak のバージョン互換性
|
||||
|
||||
WebSpeak は ServerQuery / WebQuery ではなく、標準の TeamSpeak クライアントプロトコルで接続するため、Query の認証情報は不要です。
|
||||
音声接続には標準の TeamSpeak クライアントプロトコルを使い、Query の認証情報は不要です。任意の TS 管理機能では、別途 WebQuery / ServerQuery の認証情報を使用します。
|
||||
|
||||
- **TeamSpeak 3**: 先頭の `3.x` バージョンを使ってプロトコルを判定します。すべての旧バージョンを個別に検証しているわけではないため、古いサーバーは実際の環境で確認してください。
|
||||
- **TeamSpeak 6**: 対応しています。TeamSpeak 6 ネイティブクライアントとの画面共有も可能です。
|
||||
- **自動検出**: ゲートウェイはサーバーの `version` 応答を読み取り、接続診断に判定結果を記録します。
|
||||
- [`@echosixhiya/teamspeak-client`](https://github.com/EchoSixHIYA/teamspeak-js) ライブラリは TeamSpeak 5 も扱えますが、WebSpeak の対象は TeamSpeak 3 と 6 です。
|
||||
- ゲートウェイは上流 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 を使う他のユーザーへの影響を避けます。
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
@@ -121,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
|
||||
@@ -131,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 をリバースプロキシ経由で公開してください。
|
||||
|
||||
+14
-4
@@ -43,12 +43,23 @@
|
||||
|
||||
## Совместимость версий TeamSpeak
|
||||
|
||||
WebSpeak подключается по стандартному клиентскому протоколу TeamSpeak, а не через ServerQuery или WebQuery, поэтому учётные данные Query не нужны.
|
||||
Голосовые соединения используют стандартный клиентский протокол TeamSpeak и не требуют учётных данных Query. Необязательное управление TS использует отдельные данные WebQuery / ServerQuery.
|
||||
|
||||
- **TeamSpeak 3**: определение распознаёт ведущую версию `3.x`. Старые версии сервера следует проверять отдельно в конкретной среде: не каждая историческая версия тестировалась независимо.
|
||||
- **TeamSpeak 6**: поддерживается, включая демонстрацию экрана с нативными клиентами TeamSpeak 6.
|
||||
- **Автоопределение**: шлюз читает ответ сервера `version` и записывает распознанный протокол в диагностику подключения.
|
||||
- Библиотека [`@echosixhiya/teamspeak-client`](https://github.com/EchoSixHIYA/teamspeak-js) также поддерживает TeamSpeak 5, но WebSpeak ориентирован на TeamSpeak 3 и 6.
|
||||
- Шлюз использует 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 шлюза.
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
@@ -123,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
|
||||
@@ -133,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 через обратный прокси.
|
||||
|
||||
+26
-7
@@ -37,12 +37,23 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
|
||||
|
||||
## TeamSpeak 版本兼容性
|
||||
|
||||
WebSpeak 使用标准 TeamSpeak 客户端协议连接,不使用 ServerQuery 或 WebQuery,因此无需查询凭据。
|
||||
语音连接使用标准 TeamSpeak 客户端协议,无需 Query 凭据。可选的 TS 管理功能使用独立的 WebQuery / ServerQuery 凭据。
|
||||
|
||||
- **TeamSpeak 3**:协议识别会读取版本号开头的 `3.x`。并非所有历史服务器版本都经过独立验证,部署旧版本时请针对实际服务器进行测试。
|
||||
- **TeamSpeak 6**:支持,也支持与 TeamSpeak 6 原生客户端进行屏幕共享。
|
||||
- **自动探测**:网关读取服务器的 `version` 响应并在连接诊断中记录识别到的协议。
|
||||
- 底层 [`@echosixhiya/teamspeak-client`](https://github.com/EchoSixHIYA/teamspeak-js) 也支持 TeamSpeak 5,但 WebSpeak 的目标版本是 TeamSpeak 3 和 TeamSpeak 6。
|
||||
- 网关使用上游 [`@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 的其他用户。
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
@@ -107,7 +118,7 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
中继实例同时运行 UDP 兼容转发和独立语音网关,不提供访客首页或管理员后台。网关收到用户的入场请求后,会用共享令牌签名并转交一次性语音票据;浏览器随后直接连接中继节点,语音网关再从中继节点连接 TeamSpeak。网页地址仍保持在入口网关,不需要跳转。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
@@ -115,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' \
|
||||
@@ -161,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. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
@@ -275,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(推荐)
|
||||
|
||||
@@ -315,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
|
||||
|
||||
@@ -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,48 @@ 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,下载有超时限制。商店不执行皮肤构建脚本,也不从仓库加载未打入归档的资源。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
|
||||
@@ -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.5 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.
|
||||
Binary file not shown.
@@ -0,0 +1,431 @@
|
||||
{
|
||||
"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": "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": "visitor-count", "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": {} },
|
||||
"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": "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" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
{
|
||||
"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",
|
||||
"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": "在线",
|
||||
"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",
|
||||
"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": "В сети",
|
||||
"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": "オンライン",
|
||||
"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.5",
|
||||
"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.
@@ -3,7 +3,7 @@
|
||||
"packageType": "open-skin",
|
||||
"id": "community.kaak-voice",
|
||||
"name": "KAAK",
|
||||
"version": "3.1.121",
|
||||
"version": "3.1.122",
|
||||
"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.",
|
||||
|
||||
@@ -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);
|
||||
|
||||
+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/teamspeak-adapter.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-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";
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,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));
|
||||
|
||||
@@ -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,250 @@
|
||||
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 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 = httpStatus;
|
||||
res.end(httpStatus === 200 ? 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; },
|
||||
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.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("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,279 @@
|
||||
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, 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();
|
||||
this.database.addAudit("TS_ADMIN_OVERVIEW_READ", { channels: channels.length, clients: clients.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: clients.length,
|
||||
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
|
||||
description: channel.description, totalClients: channel.totalClients ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: clients.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",
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** 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(); await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason }); }
|
||||
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): 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 ? "TS_ADMIN_OPERATION_FAILED" : "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 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,28 @@
|
||||
import { request as httpRequest } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
|
||||
/** 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", () => resolve(new Response(Buffer.concat(chunks), {
|
||||
status: res.statusCode ?? 502, 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);
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,19 +130,6 @@ 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 {
|
||||
|
||||
@@ -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,136 @@
|
||||
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, 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, 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, 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.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,339 @@
|
||||
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;
|
||||
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,
|
||||
...(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]> = [];
|
||||
|
||||
+66
-15
@@ -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,
|
||||
@@ -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());
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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,33 @@ 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,
|
||||
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 +114,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,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;
|
||||
}
|
||||
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,134 @@
|
||||
<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>
|
||||
<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('tsAdminPassword') }}</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') }}: {{ tr('tsAdminRestricted') }}</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">{{ tr('tsAdminRestricted') }}</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, 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>
|
||||
@@ -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>
|
||||
@@ -27,15 +27,29 @@ 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",
|
||||
};
|
||||
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,141 @@
|
||||
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 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());
|
||||
}
|
||||
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());
|
||||
}
|
||||
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 = "";
|
||||
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(); }
|
||||
}
|
||||
async function connectAndRefresh() {
|
||||
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 = "";
|
||||
try { const value = await options.api.tsAdminOverview(request.signal); if (request.isCurrent()) overview.value = value; }
|
||||
catch (error) { if (request.isCurrent()) 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 = "";
|
||||
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 connectAndRefresh();
|
||||
} catch (error) { if (request.isCurrent()) report(error); }
|
||||
finally { if (request.isCurrent()) acting.value = false; request.finish(); }
|
||||
}
|
||||
return { settings, form, editor, overview, settingsDirty, noticeMessage, 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,107 @@
|
||||
const zh = {
|
||||
adminWsGroup: "WebSpeak 实例", adminTsGroup: "TeamSpeak 服务", adminOptional: "可选",
|
||||
adminInstanceSettings: "接入与站点", adminInstanceLead: "配置此 WebSpeak 实例的语音接入、站点展示和网络传输。",
|
||||
adminInstanceOperations: "会话与运维", adminInstanceOperationsLead: "管理浏览器会话、访问邀请、连接日志和实例备份。",
|
||||
adminWsScopeLead: "以下设置只管理 WebSpeak 实例,无需配置 TeamSpeak 管理凭据。",
|
||||
adminAccessSection: "语音接入", adminSiteSection: "站点展示", adminNetworkSection: "网络与中继",
|
||||
adminTargetScope: "这是 WebSpeak 连接的默认语音目标及入服密码,不会修改 TeamSpeak 服务器配置。",
|
||||
adminSiteScope: "站点名称和公告显示在 WebSpeak 访客页面,与 TeamSpeak 的服务器名称和欢迎消息独立。",
|
||||
adminSiteAnnouncement: "站点公告", adminAnnouncementLanguage: "公告语言", adminAnnouncementFallback: "留空时,使用该语言的默认站点公告。", adminSaveScope: "保存会应用此页面所有分区的更改;TeamSpeak 管理连接单独配置。",
|
||||
adminBrowserSessions: "浏览器会话", adminBrowserSessionsLead: "这里只显示通过此 WebSpeak 实例连接的用户;结束会话会断开对应浏览器。完整 TS 成员列表见 TeamSpeak 服务管理。",
|
||||
adminInviteScope: "这些邀请链接由当前 WebSpeak 实例生成和管理。",
|
||||
adminLogsSection: "连接与日志", adminMaintenanceSection: "诊断与备份",
|
||||
adminWsOverviewTitle: "WebSpeak 管理服务已就绪", adminWsOverviewLead: "先管理实例接入与访客体验;需要管理 TS 服务时,再按需配置独立连接。",
|
||||
adminWsManageLead: "接入策略、站点公告、语音传输、皮肤商店和浏览器会话。",
|
||||
adminTsManageLead: "服务器设置、频道、在线成员、服务器组和封禁。需单独配置 Query 凭据,常规语音连接不需要。",
|
||||
adminTsEntry: "进入服务管理", adminTsConnection: "管理连接", adminTsConfigure: "配置管理连接",
|
||||
adminTsSetupTitle: "按需启用 TeamSpeak 管理", adminTsSetupLead: "只有需要修改 TS 服务、频道或成员时,才需启用并保存管理连接。未启用时,WebSpeak 的其他功能照常可用。",
|
||||
adminTsSavedTarget: "已保存的语音目标", adminTsOverviewSection: "服务概览", adminTsConfigPending: "管理连接有未保存的更改,请先保存,再读取或操作 TS 服务。",
|
||||
adminTsConnectionScope: "连接信息仅供服务端访问 TeamSpeak Query 使用,不能代替 WebSpeak 的管理员登录。",
|
||||
adminTsNotEnabled: "未启用", adminTsConfigured: "已启用 · 按需读取", adminTsConfigurationSaved: "使用已保存的管理连接读取状态;打开此页面不会自动连接 TS。",
|
||||
} as const;
|
||||
type Keys = keyof typeof zh;
|
||||
const en = {
|
||||
adminWsGroup: "WebSpeak instance", adminTsGroup: "TeamSpeak service", adminOptional: "Optional",
|
||||
adminInstanceSettings: "Access & site", adminInstanceLead: "Configure voice access, site presentation and network transport for this WebSpeak instance.",
|
||||
adminInstanceOperations: "Sessions & maintenance", adminInstanceOperationsLead: "Manage browser sessions, access invites, connection logs and instance backups.",
|
||||
adminWsScopeLead: "These settings manage WebSpeak itself. TeamSpeak administration credentials are not required.",
|
||||
adminAccessSection: "Voice access", adminSiteSection: "Site presentation", adminNetworkSection: "Network & relays",
|
||||
adminTargetScope: "The default voice target and join password used by WebSpeak. This does not change TeamSpeak server settings.",
|
||||
adminSiteScope: "The site name and announcement appear on WebSpeak's guest page, independently of the TeamSpeak server name and welcome message.",
|
||||
adminSiteAnnouncement: "Site announcement", adminAnnouncementLanguage: "Announcement language", adminAnnouncementFallback: "Leave blank to use the default site announcement for this language.", adminSaveScope: "Save applies changes in every section on this page. The TeamSpeak management connection is configured separately.",
|
||||
adminBrowserSessions: "Browser sessions", adminBrowserSessionsLead: "Only users connected through this WebSpeak instance are listed here. Ending a session disconnects that browser. Use TeamSpeak service management for the full TS client list.",
|
||||
adminInviteScope: "These invite links are created and managed by this WebSpeak instance.",
|
||||
adminLogsSection: "Connections & logs", adminMaintenanceSection: "Diagnostics & backups",
|
||||
adminWsOverviewTitle: "WebSpeak management is ready", adminWsOverviewLead: "Manage instance access and the guest experience first. Configure an independent TS management connection when you need it.",
|
||||
adminWsManageLead: "Access policy, site announcements, voice transport, the skin store and browser sessions.",
|
||||
adminTsManageLead: "Server settings, channels, clients, server groups and bans. Separate Query credentials are required; ordinary voice connections do not need them.",
|
||||
adminTsEntry: "Open service management", adminTsConnection: "Management connection", adminTsConfigure: "Configure connection",
|
||||
adminTsSetupTitle: "Enable TeamSpeak management when needed", adminTsSetupLead: "Enable and save a management connection only if you need to manage the TS service, channels or clients. Other WebSpeak features work without it.",
|
||||
adminTsSavedTarget: "Saved voice target", adminTsOverviewSection: "Service overview", adminTsConfigPending: "The management connection has unsaved changes. Save before reading or modifying the TS service.",
|
||||
adminTsConnectionScope: "The server uses these credentials to access TeamSpeak Query. They do not replace your WebSpeak administrator login.",
|
||||
adminTsNotEnabled: "Not enabled", adminTsConfigured: "Enabled · read on demand", adminTsConfigurationSaved: "Status requests use the saved connection. Opening this page does not automatically connect to TS.",
|
||||
} satisfies Record<Keys, string>;
|
||||
const de = {
|
||||
adminWsGroup: "WebSpeak-Instanz", adminTsGroup: "TeamSpeak-Dienst", adminOptional: "Optional",
|
||||
adminInstanceSettings: "Zugang & Website", adminInstanceLead: "Sprachzugang, Website-Darstellung und Netzwerktransport dieser WebSpeak-Instanz konfigurieren.",
|
||||
adminInstanceOperations: "Sitzungen & Wartung", adminInstanceOperationsLead: "Browsersitzungen, Einladungen, Verbindungsprotokolle und Instanzsicherungen verwalten.",
|
||||
adminWsScopeLead: "Diese Einstellungen betreffen WebSpeak. Zugangsdaten zur TeamSpeak-Verwaltung sind nicht erforderlich.",
|
||||
adminAccessSection: "Sprachzugang", adminSiteSection: "Website-Darstellung", adminNetworkSection: "Netzwerk & Relays",
|
||||
adminTargetScope: "Standard-Sprachziel und Beitrittspasswort für WebSpeak. Die TeamSpeak-Serverkonfiguration wird hier nicht geändert.",
|
||||
adminSiteScope: "Website-Name und Ankündigung erscheinen auf der WebSpeak-Gastseite, unabhängig von TeamSpeak-Servername und Willkommensnachricht.",
|
||||
adminSiteAnnouncement: "Website-Ankündigung", adminAnnouncementLanguage: "Sprache der Ankündigung", adminAnnouncementFallback: "Leer lassen, um die Standardankündigung dieser Sprache zu verwenden.", adminSaveScope: "Speichern übernimmt alle Bereiche dieser Seite. Die TeamSpeak-Verwaltungsverbindung wird separat konfiguriert.",
|
||||
adminBrowserSessions: "Browsersitzungen", adminBrowserSessionsLead: "Hier stehen nur Nutzer dieser WebSpeak-Instanz. Beenden trennt den jeweiligen Browser. Die vollständige TS-Mitgliederliste befindet sich in der TeamSpeak-Verwaltung.",
|
||||
adminInviteScope: "Diese Einladungslinks werden von dieser WebSpeak-Instanz erstellt und verwaltet.",
|
||||
adminLogsSection: "Verbindungen & Protokolle", adminMaintenanceSection: "Diagnose & Sicherungen",
|
||||
adminWsOverviewTitle: "WebSpeak-Verwaltung ist bereit", adminWsOverviewLead: "Zuerst Instanzzugang und Gastoberfläche verwalten. Eine separate TS-Verbindung nur bei Bedarf einrichten.",
|
||||
adminWsManageLead: "Zugriffsregeln, Website-Ankündigungen, Sprachtransport, Skin-Store und Browsersitzungen.",
|
||||
adminTsManageLead: "Servereinstellungen, Kanäle, Mitglieder, Servergruppen und Sperren. Separate Query-Zugangsdaten sind nötig; normale Sprachverbindungen benötigen sie nicht.",
|
||||
adminTsEntry: "Dienstverwaltung öffnen", adminTsConnection: "Verwaltungsverbindung", adminTsConfigure: "Verbindung konfigurieren",
|
||||
adminTsSetupTitle: "TeamSpeak-Verwaltung bei Bedarf aktivieren", adminTsSetupLead: "Nur zum Verwalten von TS-Dienst, Kanälen oder Mitgliedern aktivieren und speichern. Andere WebSpeak-Funktionen bleiben unabhängig nutzbar.",
|
||||
adminTsSavedTarget: "Gespeichertes Sprachziel", adminTsOverviewSection: "Dienstübersicht", adminTsConfigPending: "Ungespeicherte Änderungen an der Verwaltungsverbindung. Vor dem Lesen oder Ändern des TS-Dienstes speichern.",
|
||||
adminTsConnectionScope: "Der Server verwendet diese Daten für TeamSpeak Query. Sie ersetzen nicht die WebSpeak-Administratoranmeldung.",
|
||||
adminTsNotEnabled: "Nicht aktiviert", adminTsConfigured: "Aktiviert · Abruf bei Bedarf", adminTsConfigurationSaved: "Statusabfragen verwenden die gespeicherte Verbindung. Diese Seite verbindet nicht automatisch mit TS.",
|
||||
} satisfies Record<Keys, string>;
|
||||
const ru = {
|
||||
adminWsGroup: "Экземпляр WebSpeak", adminTsGroup: "Служба TeamSpeak", adminOptional: "Необязательно",
|
||||
adminInstanceSettings: "Доступ и сайт", adminInstanceLead: "Настройте голосовой доступ, оформление сайта и сетевой транспорт этого экземпляра WebSpeak.",
|
||||
adminInstanceOperations: "Сеансы и обслуживание", adminInstanceOperationsLead: "Управляйте сеансами браузеров, приглашениями, журналами подключений и резервными копиями.",
|
||||
adminWsScopeLead: "Эти настройки относятся к WebSpeak. Учётные данные для администрирования TeamSpeak не нужны.",
|
||||
adminAccessSection: "Голосовой доступ", adminSiteSection: "Оформление сайта", adminNetworkSection: "Сеть и ретрансляторы",
|
||||
adminTargetScope: "Голосовой адрес и пароль входа, используемые WebSpeak по умолчанию. Настройки сервера TeamSpeak здесь не изменяются.",
|
||||
adminSiteScope: "Название сайта и объявление показываются на странице WebSpeak и не связаны с названием сервера и приветствием TeamSpeak.",
|
||||
adminSiteAnnouncement: "Объявление сайта", adminAnnouncementLanguage: "Язык объявления", adminAnnouncementFallback: "Оставьте пустым для стандартного объявления на этом языке.", adminSaveScope: "Сохраняются изменения всех разделов этой страницы. Подключение для управления TeamSpeak настраивается отдельно.",
|
||||
adminBrowserSessions: "Сеансы браузеров", adminBrowserSessionsLead: "Здесь только пользователи этого экземпляра WebSpeak. Завершение сеанса отключает соответствующий браузер. Полный список участников TS доступен в управлении TeamSpeak.",
|
||||
adminInviteScope: "Эти ссылки-приглашения создаются и управляются текущим экземпляром WebSpeak.",
|
||||
adminLogsSection: "Подключения и журналы", adminMaintenanceSection: "Диагностика и копии",
|
||||
adminWsOverviewTitle: "Управление WebSpeak готово", adminWsOverviewLead: "Настройте доступ и гостевой интерфейс. Отдельное управление TS подключайте по мере необходимости.",
|
||||
adminWsManageLead: "Политика доступа, объявления сайта, голосовой транспорт, магазин тем и сеансы браузеров.",
|
||||
adminTsManageLead: "Настройки сервера, каналы, участники, серверные группы и блокировки. Нужны отдельные данные Query; для обычного голосового подключения они не требуются.",
|
||||
adminTsEntry: "Открыть управление службой", adminTsConnection: "Подключение управления", adminTsConfigure: "Настроить подключение",
|
||||
adminTsSetupTitle: "Включайте управление TeamSpeak при необходимости", adminTsSetupLead: "Включите и сохраните подключение только для управления службой TS, каналами или участниками. Остальные функции WebSpeak работают без него.",
|
||||
adminTsSavedTarget: "Сохранённый голосовой адрес", adminTsOverviewSection: "Обзор службы", adminTsConfigPending: "Есть несохранённые изменения подключения управления. Сохраните их перед чтением или изменением службы TS.",
|
||||
adminTsConnectionScope: "Эти данные используются сервером для доступа к TeamSpeak Query и не заменяют вход администратора WebSpeak.",
|
||||
adminTsNotEnabled: "Не включено", adminTsConfigured: "Включено · чтение по запросу", adminTsConfigurationSaved: "Статус запрашивается с сохранёнными настройками. Открытие страницы не подключается к TS автоматически.",
|
||||
} satisfies Record<Keys, string>;
|
||||
const ja = {
|
||||
adminWsGroup: "WebSpeak インスタンス", adminTsGroup: "TeamSpeak サービス", adminOptional: "任意",
|
||||
adminInstanceSettings: "接続とサイト", adminInstanceLead: "この WebSpeak の音声接続、サイト表示、ネットワーク転送を設定します。",
|
||||
adminInstanceOperations: "セッションと保守", adminInstanceOperationsLead: "ブラウザーの接続、招待、接続ログ、バックアップを管理します。",
|
||||
adminWsScopeLead: "ここでは WebSpeak 自体を設定します。TeamSpeak 管理用の認証情報は不要です。",
|
||||
adminAccessSection: "音声接続", adminSiteSection: "サイト表示", adminNetworkSection: "ネットワークと中継",
|
||||
adminTargetScope: "WebSpeak が接続する既定の音声接続先と入室パスワードです。TeamSpeak サーバー自体の設定は変更しません。",
|
||||
adminSiteScope: "サイト名とお知らせは WebSpeak の訪問者ページに表示され、TeamSpeak のサーバー名や歓迎メッセージとは独立しています。",
|
||||
adminSiteAnnouncement: "サイトのお知らせ", adminAnnouncementLanguage: "お知らせの言語", adminAnnouncementFallback: "空欄の場合は、この言語の標準のお知らせを使用します。", adminSaveScope: "このページの全区分の変更をまとめて保存します。TeamSpeak 管理接続は別に設定します。",
|
||||
adminBrowserSessions: "ブラウザーセッション", adminBrowserSessionsLead: "この WebSpeak 経由の利用者だけを表示します。終了すると該当のブラウザーが切断されます。TS の全メンバーは TeamSpeak サービス管理で確認できます。",
|
||||
adminInviteScope: "この招待リンクは現在の WebSpeak インスタンスが発行・管理します。",
|
||||
adminLogsSection: "接続とログ", adminMaintenanceSection: "診断とバックアップ",
|
||||
adminWsOverviewTitle: "WebSpeak 管理を利用できます", adminWsOverviewLead: "まず接続方針と訪問者向け画面を管理します。必要な場合だけ、独立した TS 管理接続を設定します。",
|
||||
adminWsManageLead: "アクセス方針、サイトのお知らせ、音声転送、スキンストア、ブラウザー接続。",
|
||||
adminTsManageLead: "サーバー設定、チャンネル、メンバー、サーバーグループ、禁止リスト。専用 Query 認証情報が必要ですが、通常の音声接続には不要です。",
|
||||
adminTsEntry: "サービス管理を開く", adminTsConnection: "管理接続", adminTsConfigure: "管理接続を設定",
|
||||
adminTsSetupTitle: "必要なときだけ TeamSpeak 管理を有効化", adminTsSetupLead: "TS サービス、チャンネル、メンバーを管理する場合に接続を有効化して保存します。ほかの WebSpeak 機能は未設定でも利用できます。",
|
||||
adminTsSavedTarget: "保存済みの音声接続先", adminTsOverviewSection: "サービス概要", adminTsConfigPending: "管理接続に未保存の変更があります。TS の状態取得や操作の前に保存してください。",
|
||||
adminTsConnectionScope: "サーバーが TeamSpeak Query に接続するための認証情報です。WebSpeak 管理者ログインの代わりにはなりません。",
|
||||
adminTsNotEnabled: "無効", adminTsConfigured: "有効・必要時に取得", adminTsConfigurationSaved: "保存済みの接続設定で状態を取得します。このページを開くだけでは TS に接続しません。",
|
||||
} satisfies Record<Keys, string>;
|
||||
export const adminOrganizationCopy = { zh, en, de, ru, ja };
|
||||
@@ -1,5 +1,12 @@
|
||||
import { adminOrganizationCopy } from "./admin-organization.js";
|
||||
import { tsAdminCopy } from "./ts-admin.js";
|
||||
import { skinStoreCopy } from "./skin-store.js";
|
||||
|
||||
export const copy = {
|
||||
zh: {
|
||||
...tsAdminCopy.zh,
|
||||
...adminOrganizationCopy.zh,
|
||||
...skinStoreCopy.zh,
|
||||
uptimeText: "已运行 {{hours}} 小时 {{minutes}} 分钟",
|
||||
ageSeconds: "{{seconds}} 秒",
|
||||
ageMinutes: "{{minutes}} 分钟",
|
||||
@@ -31,6 +38,7 @@ export const copy = {
|
||||
webRtcPortLockedError: "WebRTC 已开启,请先关闭并保存后再修改端口范围。",
|
||||
invalidRelayNameError: "中继名称无效或为空。",
|
||||
invalidRelayTargetError: "中继服务器地址无效。",
|
||||
invalidRelayVoiceEndpointError: "语音网关必须使用 HTTPS 地址,并且只能填写站点源地址。",
|
||||
invalidRelayTokenError: "启用中继时必须填写令牌。",
|
||||
invalidTargetError: "TeamSpeak 服务器地址格式无效。",
|
||||
icmpUnavailableError: "当前运行环境没有可用的 ICMP Ping 工具。",
|
||||
@@ -67,6 +75,54 @@ export const copy = {
|
||||
server: "服务器",
|
||||
operations: "运维",
|
||||
skinLibrary: "皮肤",
|
||||
tsAdminTitle: "TS 管理",
|
||||
tsAdminLead: "可选的 TeamSpeak 管理连接,与 WebSpeak 自身管理功能独立。",
|
||||
tsAdminFixedOnly: "切换到固定实例模式后才能配置和使用 TS 管理面板。",
|
||||
tsAdminCredentials: "ServerQuery 凭据",
|
||||
tsAdminCredentialsLead: "凭据会加密保存在 WebSpeak 管理数据库中,仅由服务端使用。",
|
||||
tsAdminEnable: "启用 TS 管理面板",
|
||||
tsAdminEnableLead: "使用 WebQuery、SSH 或 TCP 管理固定的 TS 实例。",
|
||||
tsAdminTarget: "固定实例目标",
|
||||
tsAdminQueryPort: "Query 端口",
|
||||
tsAdminUsername: "Query 登录名",
|
||||
tsAdminHostKey: "SSH 主机密钥指纹",
|
||||
tsAdminPassword: "Query 密码",
|
||||
tsAdminPasswordConfigured: "密码已保存,留空保持不变",
|
||||
tsAdminPasswordPlaceholder: "输入 ServerQuery SSH 密码",
|
||||
tsAdminSetPassword: "设置密码",
|
||||
tsAdminKeepPassword: "保留密码",
|
||||
tsAdminFingerprintHint: "请从可信的服务器管理渠道核对 SHA256 指纹,再粘贴到此处。不要接受未经核验的主机密钥。",
|
||||
tsAdminSaved: "TS 管理设置已保存。",
|
||||
tsAdminLiveTitle: "服务器实时信息",
|
||||
tsAdminLiveLead: "连接后读取服务器、频道和在线成员列表。",
|
||||
tsAdminUpdatedAt: "更新于 {{time}}",
|
||||
tsAdminConnecting: "连接中…",
|
||||
tsAdminConnect: "连接并读取",
|
||||
tsAdminEmpty: "保存连接设置,然后连接读取并管理 TeamSpeak。",
|
||||
tsAdminServer: "TeamSpeak 服务器",
|
||||
tsAdminChannels: "频道",
|
||||
tsAdminClients: "在线成员",
|
||||
tsAdminChannelName: "频道名称",
|
||||
tsAdminMembers: "成员数",
|
||||
tsAdminChannelType: "访问方式",
|
||||
tsAdminProtected: "有密码",
|
||||
tsAdminPublic: "公开",
|
||||
tsAdminNoChannels: "没有可显示的频道。",
|
||||
tsAdminChannel: "所在频道",
|
||||
tsAdminGroups: "服务器组 ID",
|
||||
tsAdminNoClients: "当前没有在线成员。",
|
||||
tsAdminFixedOnlyError: "TS 管理面板只支持固定实例模式。",
|
||||
tsAdminNotConfiguredError: "请先填写凭据并启用 TS 管理面板。",
|
||||
tsAdminInvalidPortError: "Query 端口无效。",
|
||||
tsAdminInvalidUsernameError: "请输入 Query 登录名。",
|
||||
tsAdminInvalidHostKeyError: "请输入已核验的 SHA256 SSH 主机密钥指纹。",
|
||||
tsAdminInvalidPasswordError: "启用面板时必须保存 Query 密码。",
|
||||
tsAdminHostKeyMismatchError: "服务器 SSH 主机密钥与保存的指纹不一致。",
|
||||
tsAdminTargetError: "无法解析固定 TeamSpeak 服务器地址。",
|
||||
tsAdminConnectionError: "无法连接 TS Query,请检查所选协议、地址、凭据和防火墙。",
|
||||
tsAdminCredentialError: "已保存的 Query 凭据无法解密。请重新保存凭据。",
|
||||
tsAdminReadEvent: "已读取 TeamSpeak 管理信息",
|
||||
tsAdminReadFailedEvent: "TeamSpeak 管理连接失败",
|
||||
skinLibraryLead: "查看访客可选的默认皮肤和实例自定义皮肤;支持导入皮肤包。",
|
||||
skinDay: "默认日间模式",
|
||||
skinNight: "默认夜间模式",
|
||||
@@ -169,6 +225,9 @@ export const copy = {
|
||||
relayNamePlaceholder: "例如:大陆节点、香港节点",
|
||||
relayTarget: "中继服务器地址",
|
||||
relayTargetPlaceholder: "例如:relay.example.com#39087",
|
||||
relayVoiceEndpoint: "语音网关 HTTPS 地址",
|
||||
relayVoiceEndpointPlaceholder: "https://relay.example.com",
|
||||
relayVoiceEndpointLead: "浏览器语音连接将直达此中继网关。留空时使用中继地址的 HTTPS 域名;节点需运行 relay 模式并开放 WebRTC UDP 端口。",
|
||||
relayToken: "中继令牌",
|
||||
relayTokenPlaceholder: "填写中继服务令牌",
|
||||
relayTokenConfigured: "已配置令牌(留空保持不变)",
|
||||
@@ -286,6 +345,9 @@ export const copy = {
|
||||
auditEmpty: "暂无审计记录。",
|
||||
},
|
||||
en: {
|
||||
...tsAdminCopy.en,
|
||||
...adminOrganizationCopy.en,
|
||||
...skinStoreCopy.en,
|
||||
uptimeText: "Up {{hours}}h {{minutes}}m",
|
||||
ageSeconds: "{{seconds}}s",
|
||||
ageMinutes: "{{minutes}}m",
|
||||
@@ -317,6 +379,7 @@ export const copy = {
|
||||
webRtcPortLockedError: "WebRTC is enabled. Turn it off and save before changing the port range.",
|
||||
invalidRelayNameError: "The relay name is invalid or empty.",
|
||||
invalidRelayTargetError: "The relay server address is invalid.",
|
||||
invalidRelayVoiceEndpointError: "The voice gateway must use an HTTPS origin without a path.",
|
||||
invalidRelayTokenError: "A relay token is required when the relay is enabled.",
|
||||
invalidTargetError: "The TeamSpeak server address is invalid.",
|
||||
icmpUnavailableError: "The runtime does not provide an ICMP ping tool.",
|
||||
@@ -353,6 +416,54 @@ export const copy = {
|
||||
server: "Server",
|
||||
operations: "Operations",
|
||||
skinLibrary: "Skins",
|
||||
tsAdminTitle: "TS admin",
|
||||
tsAdminLead: "Optional TeamSpeak management, independent of WebSpeak administration.",
|
||||
tsAdminFixedOnly: "Switch to fixed-instance mode to configure and use the TS admin panel.",
|
||||
tsAdminCredentials: "ServerQuery credentials",
|
||||
tsAdminCredentialsLead: "Credentials are encrypted in the WebSpeak admin database and used only by the server.",
|
||||
tsAdminEnable: "Enable the TS admin panel",
|
||||
tsAdminEnableLead: "Manage the fixed TS instance using WebQuery, SSH or TCP.",
|
||||
tsAdminTarget: "Fixed instance target",
|
||||
tsAdminQueryPort: "Query port",
|
||||
tsAdminUsername: "Query login",
|
||||
tsAdminHostKey: "SSH host-key fingerprint",
|
||||
tsAdminPassword: "Query password",
|
||||
tsAdminPasswordConfigured: "Password saved; leave blank to keep it",
|
||||
tsAdminPasswordPlaceholder: "Enter ServerQuery SSH password",
|
||||
tsAdminSetPassword: "Set password",
|
||||
tsAdminKeepPassword: "Keep password",
|
||||
tsAdminFingerprintHint: "Verify the SHA256 fingerprint through a trusted server-admin channel before saving. Do not accept an unverified host key.",
|
||||
tsAdminSaved: "TS admin settings saved.",
|
||||
tsAdminLiveTitle: "Live server status",
|
||||
tsAdminLiveLead: "Connect to read server, channel, and online-member information.",
|
||||
tsAdminUpdatedAt: "Updated {{time}}",
|
||||
tsAdminConnecting: "Connecting…",
|
||||
tsAdminConnect: "Connect and read",
|
||||
tsAdminEmpty: "Save the connection settings, then connect to manage TeamSpeak.",
|
||||
tsAdminServer: "TeamSpeak server",
|
||||
tsAdminChannels: "Channels",
|
||||
tsAdminClients: "Online members",
|
||||
tsAdminChannelName: "Channel name",
|
||||
tsAdminMembers: "Members",
|
||||
tsAdminChannelType: "Access",
|
||||
tsAdminProtected: "Password protected",
|
||||
tsAdminPublic: "Public",
|
||||
tsAdminNoChannels: "No channels to show.",
|
||||
tsAdminChannel: "Channel",
|
||||
tsAdminGroups: "Server group IDs",
|
||||
tsAdminNoClients: "No members are online.",
|
||||
tsAdminFixedOnlyError: "The TS admin panel is only available in fixed-instance mode.",
|
||||
tsAdminNotConfiguredError: "Enter credentials and enable the TS admin panel first.",
|
||||
tsAdminInvalidPortError: "Invalid Query port.",
|
||||
tsAdminInvalidUsernameError: "Enter a Query login name.",
|
||||
tsAdminInvalidHostKeyError: "Enter the verified SHA256 SSH host-key fingerprint.",
|
||||
tsAdminInvalidPasswordError: "A Query password must be saved to enable the panel.",
|
||||
tsAdminHostKeyMismatchError: "The server SSH host key does not match the saved fingerprint.",
|
||||
tsAdminTargetError: "Could not resolve the fixed TeamSpeak server address.",
|
||||
tsAdminConnectionError: "Cannot connect to TS Query. Check the protocol, endpoint, credentials and firewall.",
|
||||
tsAdminCredentialError: "The saved Query credential could not be decrypted. Save it again.",
|
||||
tsAdminReadEvent: "TeamSpeak admin data read",
|
||||
tsAdminReadFailedEvent: "TeamSpeak admin connection failed",
|
||||
skinLibraryLead: "View the default and custom skins available to visitors; import instance-wide skin packages.",
|
||||
skinDay: "Default day mode",
|
||||
skinNight: "Default night mode",
|
||||
@@ -455,6 +566,9 @@ export const copy = {
|
||||
relayNamePlaceholder: "For example: Mainland relay or Japan relay",
|
||||
relayTarget: "Relay server address",
|
||||
relayTargetPlaceholder: "For example: relay.example.com#39087",
|
||||
relayVoiceEndpoint: "Voice gateway HTTPS address",
|
||||
relayVoiceEndpointPlaceholder: "https://relay.example.com",
|
||||
relayVoiceEndpointLead: "Browser voice connections go directly to this relay gateway. If empty, the relay host is used with HTTPS. The node must run relay mode and allow its WebRTC UDP ports.",
|
||||
relayToken: "Relay token",
|
||||
relayTokenPlaceholder: "Enter the relay service token",
|
||||
relayTokenConfigured: "Token configured (leave blank to keep it)",
|
||||
@@ -657,6 +771,7 @@ export const germanCopy = {
|
||||
webRtcPortLockedError: "WebRTC ist aktiviert. Deaktiviere es und speichere zuerst, bevor du den Portbereich änderst.",
|
||||
invalidRelayNameError: "Der Relay-Name ist ungültig oder leer.",
|
||||
invalidRelayTargetError: "Die Relay-Serveradresse ist ungültig.",
|
||||
invalidRelayVoiceEndpointError: "Das Sprachgateway muss eine HTTPS-Origin ohne Pfad verwenden.",
|
||||
invalidRelayTokenError: "Beim Aktivieren des Relays ist ein Token erforderlich.",
|
||||
invalidTargetError: "Die TeamSpeak-Serveradresse ist ungültig.",
|
||||
icmpUnavailableError: "In der Laufzeitumgebung ist kein ICMP-Ping-Tool verfügbar.",
|
||||
@@ -688,6 +803,54 @@ export const germanCopy = {
|
||||
server: "Server",
|
||||
operations: "Betrieb",
|
||||
skinLibrary: "Skins",
|
||||
tsAdminTitle: "TS-Verwaltung",
|
||||
tsAdminLead: "Optionale TeamSpeak-Verwaltung, unabhängig von der WebSpeak-Verwaltung.",
|
||||
tsAdminFixedOnly: "Wechsle zum Modus für feste Instanzen, um die TS-Verwaltung einzurichten und zu nutzen.",
|
||||
tsAdminCredentials: "ServerQuery-Zugangsdaten",
|
||||
tsAdminCredentialsLead: "Die Zugangsdaten werden verschlüsselt in der WebSpeak-Admin-Datenbank gespeichert und nur serverseitig verwendet.",
|
||||
tsAdminEnable: "TS-Verwaltung aktivieren",
|
||||
tsAdminEnableLead: "Feste TS-Instanz über WebQuery, SSH oder TCP verwalten.",
|
||||
tsAdminTarget: "Ziel der festen Instanz",
|
||||
tsAdminQueryPort: "Query-Port",
|
||||
tsAdminUsername: "Query-Anmeldename",
|
||||
tsAdminHostKey: "SSH-Host-Key-Fingerabdruck",
|
||||
tsAdminPassword: "Query-Passwort",
|
||||
tsAdminPasswordConfigured: "Passwort gespeichert; leer lassen, um es beizubehalten",
|
||||
tsAdminPasswordPlaceholder: "ServerQuery-SSH-Passwort eingeben",
|
||||
tsAdminSetPassword: "Passwort festlegen",
|
||||
tsAdminKeepPassword: "Passwort behalten",
|
||||
tsAdminFingerprintHint: "Prüfe den SHA256-Fingerabdruck über einen vertrauenswürdigen Server-Admin-Kanal. Speichere keinen ungeprüften Host-Key.",
|
||||
tsAdminSaved: "TS-Verwaltungseinstellungen gespeichert.",
|
||||
tsAdminLiveTitle: "Live-Serverstatus",
|
||||
tsAdminLiveLead: "Verbindung herstellen, um Server-, Kanal- und Online-Mitgliedsinformationen abzurufen.",
|
||||
tsAdminUpdatedAt: "Aktualisiert {{time}}",
|
||||
tsAdminConnecting: "Verbindung wird hergestellt…",
|
||||
tsAdminConnect: "Verbinden und lesen",
|
||||
tsAdminEmpty: "Verbindungseinstellungen speichern, dann TeamSpeak verwalten.",
|
||||
tsAdminServer: "TeamSpeak-Server",
|
||||
tsAdminChannels: "Kanäle",
|
||||
tsAdminClients: "Online-Mitglieder",
|
||||
tsAdminChannelName: "Kanalname",
|
||||
tsAdminMembers: "Mitglieder",
|
||||
tsAdminChannelType: "Zugriff",
|
||||
tsAdminProtected: "Passwortgeschützt",
|
||||
tsAdminPublic: "Öffentlich",
|
||||
tsAdminNoChannels: "Keine Kanäle vorhanden.",
|
||||
tsAdminChannel: "Kanal",
|
||||
tsAdminGroups: "Servergruppen-IDs",
|
||||
tsAdminNoClients: "Keine Mitglieder online.",
|
||||
tsAdminFixedOnlyError: "Die TS-Verwaltung ist nur im Modus für feste Instanzen verfügbar.",
|
||||
tsAdminNotConfiguredError: "Gib Zugangsdaten ein und aktiviere zuerst die TS-Verwaltung.",
|
||||
tsAdminInvalidPortError: "Ungültiger Query-Port.",
|
||||
tsAdminInvalidUsernameError: "Gib einen Query-Anmeldenamen ein.",
|
||||
tsAdminInvalidHostKeyError: "Gib den geprüften SHA256-SSH-Host-Key-Fingerabdruck ein.",
|
||||
tsAdminInvalidPasswordError: "Zum Aktivieren muss ein Query-Passwort gespeichert sein.",
|
||||
tsAdminHostKeyMismatchError: "Der SSH-Host-Key stimmt nicht mit dem gespeicherten Fingerabdruck überein.",
|
||||
tsAdminTargetError: "Die feste TeamSpeak-Serveradresse konnte nicht aufgelöst werden.",
|
||||
tsAdminConnectionError: "TS Query nicht erreichbar. Protokoll, Adresse, Zugangsdaten und Firewall prüfen.",
|
||||
tsAdminCredentialError: "Das gespeicherte Query-Passwort kann nicht entschlüsselt werden. Speichere es erneut.",
|
||||
tsAdminReadEvent: "TeamSpeak-Verwaltungsdaten abgerufen",
|
||||
tsAdminReadFailedEvent: "TeamSpeak-Adminverbindung fehlgeschlagen",
|
||||
skinLibraryLead: "Standard- und benutzerdefinierte Skins für Besucher anzeigen und instanzweite Skin-Pakete importieren.",
|
||||
skinDay: "Standard-Tagesmodus",
|
||||
skinNight: "Standard-Nachtmodus",
|
||||
@@ -776,6 +939,9 @@ export const germanCopy = {
|
||||
relayNamePlaceholder: "Zum Beispiel: Festland-Relay oder Japan-Relay",
|
||||
relayTarget: "Relay-Serveradresse",
|
||||
relayTargetPlaceholder: "Zum Beispiel: relay.example.com#39087",
|
||||
relayVoiceEndpoint: "HTTPS-Adresse des Sprachgateways",
|
||||
relayVoiceEndpointPlaceholder: "https://relay.example.com",
|
||||
relayVoiceEndpointLead: "Die Sprachverbindung des Browsers geht direkt zu diesem Relay-Gateway. Ohne Angabe wird der Relay-Host mit HTTPS verwendet. Der Knoten muss im Relay-Modus laufen und seine WebRTC-UDP-Ports freigeben.",
|
||||
relayToken: "Relay-Token",
|
||||
relayTokenPlaceholder: "Token des Relay-Dienstes eingeben",
|
||||
relayTokenConfigured: "Token konfiguriert (leer lassen zum Beibehalten)",
|
||||
@@ -858,6 +1024,9 @@ export const germanCopy = {
|
||||
version: "Version",
|
||||
audit: "Prüfprotokoll",
|
||||
auditEmpty: "Keine Prüfereignisse.",
|
||||
...tsAdminCopy.de,
|
||||
...adminOrganizationCopy.de,
|
||||
...skinStoreCopy.de,
|
||||
} as const satisfies Record<AdminTranslationKey, string>;
|
||||
|
||||
export const russianCopy = {
|
||||
@@ -986,6 +1155,7 @@ export const russianCopy = {
|
||||
webRtcPortLockedError: "WebRTC включён. Сначала отключите его и сохраните настройки, затем изменяйте диапазон портов.",
|
||||
invalidRelayNameError: "Имя ретранслятора отсутствует или некорректно.",
|
||||
invalidRelayTargetError: "Некорректный адрес сервера ретрансляции.",
|
||||
invalidRelayVoiceEndpointError: "Голосовой шлюз должен использовать HTTPS-адрес без пути.",
|
||||
invalidRelayTokenError: "Для включения ретранслятора необходимо указать токен.",
|
||||
invalidTargetError: "Некорректный адрес сервера TeamSpeak.",
|
||||
icmpUnavailableError: "В текущей среде выполнения недоступна утилита ICMP ping.",
|
||||
@@ -1010,6 +1180,54 @@ export const russianCopy = {
|
||||
server: "Сервер",
|
||||
operations: "Операции",
|
||||
skinLibrary: "Оформление",
|
||||
tsAdminTitle: "Администрирование TS",
|
||||
tsAdminLead: "Необязательное управление TeamSpeak, независимое от администрирования WebSpeak.",
|
||||
tsAdminFixedOnly: "Переключитесь в режим фиксированного экземпляра, чтобы настроить и использовать панель TS.",
|
||||
tsAdminCredentials: "Данные ServerQuery",
|
||||
tsAdminCredentialsLead: "Данные шифруются в базе администратора WebSpeak и используются только сервером.",
|
||||
tsAdminEnable: "Включить панель TS",
|
||||
tsAdminEnableLead: "Управляйте фиксированным TS через WebQuery, SSH или TCP.",
|
||||
tsAdminTarget: "Целевой фиксированный сервер",
|
||||
tsAdminQueryPort: "Порт Query",
|
||||
tsAdminUsername: "Имя входа Query",
|
||||
tsAdminHostKey: "Отпечаток SSH-ключа хоста",
|
||||
tsAdminPassword: "Пароль Query",
|
||||
tsAdminPasswordConfigured: "Пароль сохранён; оставьте поле пустым, чтобы не менять его",
|
||||
tsAdminPasswordPlaceholder: "Введите пароль ServerQuery SSH",
|
||||
tsAdminSetPassword: "Задать пароль",
|
||||
tsAdminKeepPassword: "Сохранить пароль",
|
||||
tsAdminFingerprintHint: "Сверьте SHA256-отпечаток через доверенный канал связи с администратором сервера. Не сохраняйте непроверенный ключ.",
|
||||
tsAdminSaved: "Настройки панели TS сохранены.",
|
||||
tsAdminLiveTitle: "Текущее состояние сервера",
|
||||
tsAdminLiveLead: "Подключитесь, чтобы получить сведения о сервере, каналах и участниках онлайн.",
|
||||
tsAdminUpdatedAt: "Обновлено {{time}}",
|
||||
tsAdminConnecting: "Подключение…",
|
||||
tsAdminConnect: "Подключиться и прочитать",
|
||||
tsAdminEmpty: "Сохраните подключение, затем подключитесь для управления TeamSpeak.",
|
||||
tsAdminServer: "Сервер TeamSpeak",
|
||||
tsAdminChannels: "Каналы",
|
||||
tsAdminClients: "Участники онлайн",
|
||||
tsAdminChannelName: "Название канала",
|
||||
tsAdminMembers: "Участники",
|
||||
tsAdminChannelType: "Доступ",
|
||||
tsAdminProtected: "Защищён паролем",
|
||||
tsAdminPublic: "Открытый",
|
||||
tsAdminNoChannels: "Нет каналов для отображения.",
|
||||
tsAdminChannel: "Канал",
|
||||
tsAdminGroups: "ID серверных групп",
|
||||
tsAdminNoClients: "Сейчас нет участников онлайн.",
|
||||
tsAdminFixedOnlyError: "Панель TS доступна только в режиме фиксированного экземпляра.",
|
||||
tsAdminNotConfiguredError: "Сначала укажите данные и включите панель TS.",
|
||||
tsAdminInvalidPortError: "Неверный порт Query.",
|
||||
tsAdminInvalidUsernameError: "Укажите имя входа Query.",
|
||||
tsAdminInvalidHostKeyError: "Укажите проверенный SHA256-отпечаток SSH-ключа хоста.",
|
||||
tsAdminInvalidPasswordError: "Для включения панели необходимо сохранить пароль Query.",
|
||||
tsAdminHostKeyMismatchError: "SSH-ключ сервера не соответствует сохранённому отпечатку.",
|
||||
tsAdminTargetError: "Не удалось разрешить адрес фиксированного сервера TeamSpeak.",
|
||||
tsAdminConnectionError: "Не удалось подключиться к TS Query. Проверьте протокол, адрес, данные и брандмауэр.",
|
||||
tsAdminCredentialError: "Не удалось расшифровать сохранённый пароль Query. Сохраните его снова.",
|
||||
tsAdminReadEvent: "Данные администратора TeamSpeak получены",
|
||||
tsAdminReadFailedEvent: "Не удалось подключиться к TeamSpeak для администрирования",
|
||||
skinLibraryLead: "Просматривайте стандартное и пользовательское оформление и импортируйте пакеты для всего экземпляра.",
|
||||
skinDay: "Стандартная дневная тема",
|
||||
skinNight: "Стандартная ночная тема",
|
||||
@@ -1075,6 +1293,9 @@ export const russianCopy = {
|
||||
relayEnabled: "Включить ретрансляцию",
|
||||
relayName: "Название ретранслятора",
|
||||
relayTarget: "Адрес ретранслятора",
|
||||
relayVoiceEndpoint: "HTTPS-адрес голосового шлюза",
|
||||
relayVoiceEndpointPlaceholder: "https://relay.example.com",
|
||||
relayVoiceEndpointLead: "Браузер подключается к голосовому шлюзу напрямую. Если адрес пуст, используется HTTPS-адрес узла ретрансляции. На узле должен работать режим ретрансляции и быть открыт диапазон WebRTC UDP.",
|
||||
relayToken: "Токен ретранслятора",
|
||||
relayAdd: "Добавить узел ретрансляции",
|
||||
relayNodeEmpty: "Узлы ретрансляции не настроены.",
|
||||
@@ -1145,6 +1366,9 @@ export const russianCopy = {
|
||||
version: "Версия",
|
||||
audit: "Журнал аудита",
|
||||
auditEmpty: "Нет событий аудита.",
|
||||
...tsAdminCopy.ru,
|
||||
...adminOrganizationCopy.ru,
|
||||
...skinStoreCopy.ru,
|
||||
} as const satisfies Record<AdminTranslationKey, string>;
|
||||
|
||||
export const japaneseCopy = {
|
||||
@@ -1273,6 +1497,7 @@ export const japaneseCopy = {
|
||||
webRtcPortLockedError: "WebRTC が有効です。ポート範囲を変更する前に無効にして保存してください。",
|
||||
invalidRelayNameError: "中継名が空欄か、正しくありません。",
|
||||
invalidRelayTargetError: "中継サーバーのアドレスが正しくありません。",
|
||||
invalidRelayVoiceEndpointError: "音声ゲートウェイには、パスを含まない HTTPS オリジンを指定してください。",
|
||||
invalidRelayTokenError: "中継を有効にするにはトークンを入力してください。",
|
||||
invalidTargetError: "TeamSpeak サーバーのアドレス形式が正しくありません。",
|
||||
icmpUnavailableError: "現在の実行環境では ICMP Ping ツールを利用できません。",
|
||||
@@ -1297,6 +1522,54 @@ export const japaneseCopy = {
|
||||
server: "サーバー",
|
||||
operations: "運用",
|
||||
skinLibrary: "スキン",
|
||||
tsAdminTitle: "TS 管理",
|
||||
tsAdminLead: "WebSpeak 管理とは独立した、任意の TeamSpeak 管理接続です。",
|
||||
tsAdminFixedOnly: "TS 管理パネルを設定して使うには、固定インスタンスモードに切り替えてください。",
|
||||
tsAdminCredentials: "ServerQuery 認証情報",
|
||||
tsAdminCredentialsLead: "認証情報は WebSpeak 管理データベースに暗号化して保存し、サーバー側だけで使用します。",
|
||||
tsAdminEnable: "TS 管理パネルを有効にする",
|
||||
tsAdminEnableLead: "WebQuery、SSH、TCP で固定 TS インスタンスを管理します。",
|
||||
tsAdminTarget: "固定インスタンスの接続先",
|
||||
tsAdminQueryPort: "Query ポート",
|
||||
tsAdminUsername: "Query ログイン名",
|
||||
tsAdminHostKey: "SSH ホスト鍵のフィンガープリント",
|
||||
tsAdminPassword: "Query パスワード",
|
||||
tsAdminPasswordConfigured: "保存済みです。変更しない場合は空欄のままにしてください",
|
||||
tsAdminPasswordPlaceholder: "ServerQuery SSH パスワードを入力",
|
||||
tsAdminSetPassword: "パスワードを設定",
|
||||
tsAdminKeepPassword: "パスワードを保持",
|
||||
tsAdminFingerprintHint: "信頼できるサーバー管理者の連絡経路で SHA256 フィンガープリントを確認してください。未確認の鍵は保存しないでください。",
|
||||
tsAdminSaved: "TS 管理設定を保存しました。",
|
||||
tsAdminLiveTitle: "サーバーの現在の状態",
|
||||
tsAdminLiveLead: "接続するとサーバー、チャンネル、オンラインメンバーの情報を読み込みます。",
|
||||
tsAdminUpdatedAt: "更新日時: {{time}}",
|
||||
tsAdminConnecting: "接続中…",
|
||||
tsAdminConnect: "接続して読み込む",
|
||||
tsAdminEmpty: "接続設定を保存してから TeamSpeak に接続してください。",
|
||||
tsAdminServer: "TeamSpeak サーバー",
|
||||
tsAdminChannels: "チャンネル",
|
||||
tsAdminClients: "オンラインメンバー",
|
||||
tsAdminChannelName: "チャンネル名",
|
||||
tsAdminMembers: "メンバー数",
|
||||
tsAdminChannelType: "アクセス",
|
||||
tsAdminProtected: "パスワードあり",
|
||||
tsAdminPublic: "公開",
|
||||
tsAdminNoChannels: "表示できるチャンネルはありません。",
|
||||
tsAdminChannel: "チャンネル",
|
||||
tsAdminGroups: "サーバーグループ ID",
|
||||
tsAdminNoClients: "オンラインメンバーはいません。",
|
||||
tsAdminFixedOnlyError: "TS 管理パネルは固定インスタンスモードでのみ利用できます。",
|
||||
tsAdminNotConfiguredError: "先に認証情報を入力して TS 管理パネルを有効にしてください。",
|
||||
tsAdminInvalidPortError: "Query ポートが無効です。",
|
||||
tsAdminInvalidUsernameError: "Query ログイン名を入力してください。",
|
||||
tsAdminInvalidHostKeyError: "確認済みの SHA256 SSH ホスト鍵フィンガープリントを入力してください。",
|
||||
tsAdminInvalidPasswordError: "パネルを有効にするには Query パスワードを保存してください。",
|
||||
tsAdminHostKeyMismatchError: "サーバーの SSH ホスト鍵が保存済みのフィンガープリントと一致しません。",
|
||||
tsAdminTargetError: "固定 TeamSpeak サーバーのアドレスを解決できませんでした。",
|
||||
tsAdminConnectionError: "TS Query に接続できません。方式、アドレス、認証情報、ファイアウォールを確認してください。",
|
||||
tsAdminCredentialError: "保存済み Query パスワードを復号できません。もう一度保存してください。",
|
||||
tsAdminReadEvent: "TeamSpeak 管理情報を読み込みました",
|
||||
tsAdminReadFailedEvent: "TeamSpeak 管理接続に失敗しました",
|
||||
skinLibraryLead: "訪問者向けの標準スキンとカスタムスキンを表示し、インスタンス共通のパッケージを読み込みます。",
|
||||
skinDay: "標準の昼モード",
|
||||
skinNight: "標準の夜モード",
|
||||
@@ -1362,6 +1635,9 @@ export const japaneseCopy = {
|
||||
relayEnabled: "中継を有効化",
|
||||
relayName: "中継名",
|
||||
relayTarget: "中継サーバーアドレス",
|
||||
relayVoiceEndpoint: "音声ゲートウェイの HTTPS アドレス",
|
||||
relayVoiceEndpointPlaceholder: "https://relay.example.com",
|
||||
relayVoiceEndpointLead: "ブラウザーの音声接続はこの中継ゲートウェイへ直接接続します。空欄の場合、中継先のホストを HTTPS で使用します。ノードでは relay モードを実行し、WebRTC の UDP ポートを開放してください。",
|
||||
relayToken: "中継トークン",
|
||||
relayAdd: "中継ノードを追加",
|
||||
relayNodeEmpty: "中継ノードは設定されていません。",
|
||||
@@ -1432,6 +1708,9 @@ export const japaneseCopy = {
|
||||
version: "バージョン",
|
||||
audit: "監査ログ",
|
||||
auditEmpty: "監査イベントはありません。",
|
||||
...tsAdminCopy.ja,
|
||||
...adminOrganizationCopy.ja,
|
||||
...skinStoreCopy.ja,
|
||||
} as const satisfies Record<AdminTranslationKey, string>;
|
||||
|
||||
export type AdminTranslationKey = keyof typeof copy.zh;
|
||||
@@ -0,0 +1,52 @@
|
||||
const zh = {
|
||||
skinStore: "皮肤商店", skinInstalledTab: "实例皮肤", skinStoreLead: "从 GitHub 皮肤仓库安装到当前实例,再由管理员启用或设为默认。",
|
||||
skinStoreSource: "分发索引", skinStoreRefresh: "刷新商店", skinStoreRepository: "查看仓库", skinStoreInstall: "安装", skinStoreUpdate: "更新",
|
||||
skinStoreInstalling: "正在下载并校验…", skinStoreInstalled: "已安装", skinStoreNewer: "本地版本较新", skinStoreEmpty: "商店暂时没有皮肤。",
|
||||
skinStoreIncompatible: "需要更高版本的 WebSpeak", skinStoreUnavailable: "无法访问皮肤仓库,请稍后刷新重试;实例已有皮肤不受影响。",
|
||||
skinStoreInvalid: "仓库元数据或皮肤包校验失败,未安装此皮肤。", skinStoreChanged: "商店或实例皮肤已发生变化,请刷新后重试。",
|
||||
skinStoreConfirm: "要用商店版本替换当前实例中的这个皮肤吗?", skinStoreSuccess: "皮肤已安装,可在“实例皮肤”中管理。",
|
||||
skinStorePermissionNote: "安装不会更改默认皮肤,也不会代替访客批准皮肤组件权限。更新保留实例的启停状态。",
|
||||
skinStoreCurrentVersion: "实例版本", skinStoreAvailableVersion: "商店版本", skinStoreLoadedAt: "更新于",
|
||||
} as const;
|
||||
type Keys = keyof typeof zh;
|
||||
const en = {
|
||||
skinStore: "Skin store", skinInstalledTab: "Instance skins", skinStoreLead: "Install from GitHub skin repositories, then enable a skin or make it the instance default.",
|
||||
skinStoreSource: "Distribution index", skinStoreRefresh: "Refresh store", skinStoreRepository: "View repository", skinStoreInstall: "Install", skinStoreUpdate: "Update",
|
||||
skinStoreInstalling: "Downloading and validating…", skinStoreInstalled: "Installed", skinStoreNewer: "Local version is newer", skinStoreEmpty: "No skins are available yet.",
|
||||
skinStoreIncompatible: "Requires a newer WebSpeak version", skinStoreUnavailable: "The skin repository is unavailable. Refresh to retry; installed skins are unaffected.",
|
||||
skinStoreInvalid: "Repository metadata or package validation failed. The skin was not installed.", skinStoreChanged: "The store or installed skin has changed. Refresh before retrying.",
|
||||
skinStoreConfirm: "Replace this instance's installed skin with the store version?", skinStoreSuccess: "Skin installed. Manage it under Instance skins.",
|
||||
skinStorePermissionNote: "Installing does not change the default skin or approve component permissions for visitors. Updates preserve the instance's enabled state.",
|
||||
skinStoreCurrentVersion: "Instance version", skinStoreAvailableVersion: "Store version", skinStoreLoadedAt: "Updated",
|
||||
} satisfies Record<Keys, string>;
|
||||
const de = {
|
||||
skinStore: "Skin-Store", skinInstalledTab: "Instanz-Skins", skinStoreLead: "Skins aus GitHub-Repositories installieren und anschließend aktivieren oder als Standard festlegen.",
|
||||
skinStoreSource: "Verteilungsindex", skinStoreRefresh: "Store aktualisieren", skinStoreRepository: "Repository öffnen", skinStoreInstall: "Installieren", skinStoreUpdate: "Aktualisieren",
|
||||
skinStoreInstalling: "Download und Prüfung…", skinStoreInstalled: "Installiert", skinStoreNewer: "Lokale Version ist neuer", skinStoreEmpty: "Noch keine Skins verfügbar.",
|
||||
skinStoreIncompatible: "Neuere WebSpeak-Version erforderlich", skinStoreUnavailable: "Skin-Repository nicht erreichbar. Bitte erneut laden; installierte Skins bleiben verfügbar.",
|
||||
skinStoreInvalid: "Repository-Metadaten oder Paketprüfung fehlgeschlagen. Der Skin wurde nicht installiert.", skinStoreChanged: "Store oder installierter Skin wurde geändert. Bitte zuerst aktualisieren.",
|
||||
skinStoreConfirm: "Den installierten Skin dieser Instanz durch die Store-Version ersetzen?", skinStoreSuccess: "Skin installiert. Verwaltung unter Instanz-Skins.",
|
||||
skinStorePermissionNote: "Die Installation ändert weder den Standard-Skin noch die Berechtigungen der Besucher. Updates behalten den Aktivierungszustand bei.",
|
||||
skinStoreCurrentVersion: "Instanzversion", skinStoreAvailableVersion: "Store-Version", skinStoreLoadedAt: "Aktualisiert",
|
||||
} satisfies Record<Keys, string>;
|
||||
const ru = {
|
||||
skinStore: "Магазин тем", skinInstalledTab: "Темы экземпляра", skinStoreLead: "Устанавливайте темы из репозиториев GitHub, включайте их или назначайте темой по умолчанию.",
|
||||
skinStoreSource: "Каталог распространения", skinStoreRefresh: "Обновить магазин", skinStoreRepository: "Открыть репозиторий", skinStoreInstall: "Установить", skinStoreUpdate: "Обновить",
|
||||
skinStoreInstalling: "Загрузка и проверка…", skinStoreInstalled: "Установлена", skinStoreNewer: "Локальная версия новее", skinStoreEmpty: "В магазине пока нет тем.",
|
||||
skinStoreIncompatible: "Нужна более новая версия WebSpeak", skinStoreUnavailable: "Репозиторий темы недоступен. Обновите каталог позже; установленные темы продолжат работать.",
|
||||
skinStoreInvalid: "Ошибка проверки метаданных или пакета. Тема не установлена.", skinStoreChanged: "Каталог или установленная тема изменились. Обновите данные и повторите попытку.",
|
||||
skinStoreConfirm: "Заменить установленную тему этого экземпляра версией из магазина?", skinStoreSuccess: "Тема установлена. Управление доступно в разделе «Темы экземпляра».",
|
||||
skinStorePermissionNote: "Установка не меняет тему по умолчанию и не выдаёт разрешения за посетителей. Обновления сохраняют состояние включения темы.",
|
||||
skinStoreCurrentVersion: "Версия экземпляра", skinStoreAvailableVersion: "Версия магазина", skinStoreLoadedAt: "Обновлено",
|
||||
} satisfies Record<Keys, string>;
|
||||
const ja = {
|
||||
skinStore: "スキンストア", skinInstalledTab: "インスタンスのスキン", skinStoreLead: "GitHub リポジトリからスキンをインストールし、有効化やデフォルト設定を行います。",
|
||||
skinStoreSource: "配布インデックス", skinStoreRefresh: "ストアを更新", skinStoreRepository: "リポジトリを開く", skinStoreInstall: "インストール", skinStoreUpdate: "更新",
|
||||
skinStoreInstalling: "ダウンロード・検証中…", skinStoreInstalled: "インストール済み", skinStoreNewer: "ローカルのバージョンが新しい", skinStoreEmpty: "公開されているスキンはまだありません。",
|
||||
skinStoreIncompatible: "新しい WebSpeak が必要です", skinStoreUnavailable: "リポジトリに接続できません。後で再読み込みしてください。既存のスキンには影響しません。",
|
||||
skinStoreInvalid: "メタデータまたはパッケージの検証に失敗しました。スキンはインストールされていません。", skinStoreChanged: "ストアまたは既存のスキンが変更されました。更新して再試行してください。",
|
||||
skinStoreConfirm: "このインスタンスの既存のスキンをストア版に置き換えますか?", skinStoreSuccess: "インストールしました。「インスタンスのスキン」で管理できます。",
|
||||
skinStorePermissionNote: "デフォルトスキンと訪問者の権限承認は変更しません。更新時も有効・無効の設定を維持します。",
|
||||
skinStoreCurrentVersion: "インスタンス版", skinStoreAvailableVersion: "ストア版", skinStoreLoadedAt: "更新日時",
|
||||
} satisfies Record<Keys, string>;
|
||||
export const skinStoreCopy = { zh, en, de, ru, ja };
|
||||
@@ -0,0 +1,307 @@
|
||||
/** Optional TeamSpeak administration, translated independently of the public skins. */
|
||||
const zh = {
|
||||
tsAdminTransport: "连接方式",
|
||||
tsAdminWeb: "WebQuery(推荐)",
|
||||
tsAdminSsh: "ServerQuery SSH",
|
||||
tsAdminTcp: "ServerQuery TCP(TS3)",
|
||||
tsAdminUrl: "WebQuery 地址",
|
||||
tsAdminWebHelp: "填写 TeamSpeak WebQuery 的 HTTP/HTTPS 地址,可包含反向代理路径。它不是 WebSpeak 网页地址。HTTPS 使用系统信任的证书。",
|
||||
tsAdminHost: "Query 主机(可选)",
|
||||
tsAdminHostHelp: "留空使用固定 TS 目标主机。这里配置 TeamSpeak 的 Query 服务,并非服务器系统的 SSH 登录。TCP 不加密,只适合可信网络。",
|
||||
tsAdminServerId: "虚拟服务器 ID",
|
||||
tsAdminServerIdHelp: "0:按固定实例的语音端口自动选择。受限 API Key 可填写它被授权的虚拟服务器 ID。",
|
||||
tsAdminApiKey: "WebQuery API Key",
|
||||
tsAdminApiKeyConfigured: "API Key 已保存,留空保持不变",
|
||||
tsAdminKeyHelp: "使用 TS 管理员创建的 WebQuery API Key。只读 Key 可查看状态;修改需要可写作用域及相应 TS 权限。密钥仅加密保存在服务端。",
|
||||
tsAdminSetKey: "设置 / 更换 API Key",
|
||||
tsAdminRemoveKey: "移除 API Key",
|
||||
tsAdminKeepKey: "保留 API Key",
|
||||
tsAdminActionSaved: "TeamSpeak 操作已完成。",
|
||||
tsAdminServerSettings: "服务器设置",
|
||||
tsAdminWelcome: "欢迎消息",
|
||||
tsAdminSlots: "最大在线人数",
|
||||
tsAdminCreateChannel: "创建频道",
|
||||
tsAdminRenameChannel: "重命名频道",
|
||||
tsAdminDeleteChannel: "删除频道",
|
||||
tsAdminParent: "上级频道",
|
||||
tsAdminRoot: "顶层",
|
||||
tsAdminDescription: "频道描述",
|
||||
tsAdminPermanent: "永久频道",
|
||||
tsAdminMove: "移动成员",
|
||||
tsAdminKick: "移出服务器",
|
||||
tsAdminBan: "封禁身份",
|
||||
tsAdminGroupAction: "分配服务器组",
|
||||
tsAdminGroup: "服务器组",
|
||||
tsAdminRemoveGroup: "从该组移除",
|
||||
tsAdminReason: "原因",
|
||||
tsAdminBanDuration: "封禁秒数(0 为永久)",
|
||||
tsAdminBanHelp: "按用户身份封禁,避免误封共享同一网关 IP 的其他用户。",
|
||||
tsAdminBans: "封禁列表",
|
||||
tsAdminNoBans: "暂无封禁。",
|
||||
tsAdminRestricted: "当前凭据无权读取此列表。其他功能仍可使用。",
|
||||
tsAdminConfirm: "确认执行",
|
||||
tsAdminCancel: "取消",
|
||||
tsAdminDeleteHelp: "将删除所选频道;有成员或子频道时拒绝删除。",
|
||||
tsAdminActionHelp: "操作将立即应用到下方所选的 TeamSpeak 对象,请核对后确认。",
|
||||
tsAdminUrlError: "请输入不含凭据、查询参数或片段的 HTTP/HTTPS WebQuery 地址。",
|
||||
tsAdminKeyError: "启用 WebQuery 管理时必须保存 API Key。",
|
||||
tsAdminHostError: "Query 主机格式无效,请将端口单独填写。",
|
||||
tsAdminServerIdError: "虚拟服务器 ID 无效;填写 0 可自动选择。",
|
||||
tsAdminPermissionError: "TS 拒绝了此操作:请检查 Query 账号权限或 API Key 作用域。",
|
||||
tsAdminAuthError: "Query 凭据无效,或 API Key 不允许访问该虚拟服务器。",
|
||||
tsAdminActionError: "TeamSpeak 操作失败,请刷新状态并检查输入及服务器权限。",
|
||||
tsAdminClientChanged: "成员已离线或身份已变化,请刷新后重新选择。",
|
||||
tsAdminConfigChanged: "管理连接或固定服务器配置已变化,请刷新后重试。",
|
||||
tsAdminPartialError: "身份封禁已创建,但移出成员失败。请刷新核对,勿重复提交。",
|
||||
tsAdminRateError: "TS 洪水保护暂时拒绝了请求,请稍后手动重试。",
|
||||
tsAdminTlsError: "WebQuery HTTPS 证书不受信任或已过期,请修复证书或为网关配置可信 CA。",
|
||||
tsAdminActionSuccessEvent: "TeamSpeak 管理操作成功",
|
||||
tsAdminActionFailureEvent: "TeamSpeak 管理操作失败",
|
||||
tsAdminActionPartialEvent: "TeamSpeak 管理操作部分完成",
|
||||
} as const;
|
||||
|
||||
const en = {
|
||||
tsAdminTransport: "Connection",
|
||||
tsAdminWeb: "WebQuery (recommended)",
|
||||
tsAdminSsh: "ServerQuery SSH",
|
||||
tsAdminTcp: "ServerQuery TCP (TS3)",
|
||||
tsAdminUrl: "WebQuery URL",
|
||||
tsAdminWebHelp: "Use the TeamSpeak WebQuery HTTP/HTTPS URL, including a proxy path if needed. This is not the WebSpeak page URL. HTTPS certificates must be trusted.",
|
||||
tsAdminHost: "Query host (optional)",
|
||||
tsAdminHostHelp: "Leave blank to use the fixed TS host. This configures TeamSpeak Query, not the operating system SSH service. TCP is unencrypted; use a trusted network.",
|
||||
tsAdminServerId: "Virtual server ID",
|
||||
tsAdminServerIdHelp: "0 selects by the fixed voice port. For a restricted API key, enter its authorized virtual server ID.",
|
||||
tsAdminApiKey: "WebQuery API key",
|
||||
tsAdminApiKeyConfigured: "API key saved; leave blank to keep it",
|
||||
tsAdminKeyHelp: "Use a WebQuery API key created by a TS administrator. Read-only keys can view status; changes need write scope and TS permissions. Keys are encrypted on the server.",
|
||||
tsAdminSetKey: "Set / replace API key",
|
||||
tsAdminRemoveKey: "Remove API key",
|
||||
tsAdminKeepKey: "Keep API key",
|
||||
tsAdminActionSaved: "TeamSpeak operation completed.",
|
||||
tsAdminServerSettings: "Server settings",
|
||||
tsAdminWelcome: "Welcome message",
|
||||
tsAdminSlots: "Maximum clients",
|
||||
tsAdminCreateChannel: "Create channel",
|
||||
tsAdminRenameChannel: "Rename channel",
|
||||
tsAdminDeleteChannel: "Delete channel",
|
||||
tsAdminParent: "Parent channel",
|
||||
tsAdminRoot: "Top level",
|
||||
tsAdminDescription: "Channel description",
|
||||
tsAdminPermanent: "Permanent channel",
|
||||
tsAdminMove: "Move client",
|
||||
tsAdminKick: "Kick from server",
|
||||
tsAdminBan: "Ban identity",
|
||||
tsAdminGroupAction: "Assign server group",
|
||||
tsAdminGroup: "Server group",
|
||||
tsAdminRemoveGroup: "Remove from group",
|
||||
tsAdminReason: "Reason",
|
||||
tsAdminBanDuration: "Ban duration in seconds (0: permanent)",
|
||||
tsAdminBanHelp: "Bans the identity, avoiding other users sharing the gateway IP.",
|
||||
tsAdminBans: "Bans",
|
||||
tsAdminNoBans: "No bans.",
|
||||
tsAdminRestricted: "These credentials cannot read this list. Other features remain available.",
|
||||
tsAdminConfirm: "Confirm operation",
|
||||
tsAdminCancel: "Cancel",
|
||||
tsAdminDeleteHelp: "Deletes the selected channel; occupied channels or channels with children are refused.",
|
||||
tsAdminActionHelp: "This operation applies immediately to the selected TeamSpeak target below. Review it before confirming.",
|
||||
tsAdminUrlError: "Enter an HTTP/HTTPS WebQuery URL without credentials, query parameters or fragments.",
|
||||
tsAdminKeyError: "Save an API key before enabling WebQuery management.",
|
||||
tsAdminHostError: "Invalid Query host; enter the port separately.",
|
||||
tsAdminServerIdError: "Invalid virtual server ID; use 0 for automatic selection.",
|
||||
tsAdminPermissionError: "TeamSpeak denied this operation. Check Query permissions or API key scope.",
|
||||
tsAdminAuthError: "Invalid Query credentials, or the API key cannot access this virtual server.",
|
||||
tsAdminActionError: "TeamSpeak operation failed. Refresh and check the input and server permissions.",
|
||||
tsAdminClientChanged: "The client left or its identity changed. Refresh and select it again.",
|
||||
tsAdminConfigChanged: "The management connection or fixed server changed. Refresh before retrying.",
|
||||
tsAdminPartialError: "The identity ban was created, but kicking failed. Refresh to check; do not repeat the operation.",
|
||||
tsAdminRateError: "TeamSpeak flood protection refused the request. Wait before retrying manually.",
|
||||
tsAdminTlsError: "The WebQuery HTTPS certificate is untrusted or expired. Fix it or configure a trusted CA for the gateway.",
|
||||
tsAdminActionSuccessEvent: "TeamSpeak admin operation succeeded",
|
||||
tsAdminActionFailureEvent: "TeamSpeak admin operation failed",
|
||||
tsAdminActionPartialEvent: "TeamSpeak admin operation partly completed",
|
||||
} as const satisfies Record<keyof typeof zh, string>;
|
||||
|
||||
const de = {
|
||||
tsAdminTransport: "Verbindung",
|
||||
tsAdminWeb: "WebQuery (empfohlen)",
|
||||
tsAdminSsh: "ServerQuery SSH",
|
||||
tsAdminTcp: "ServerQuery TCP (TS3)",
|
||||
tsAdminUrl: "WebQuery-URL",
|
||||
tsAdminWebHelp: "HTTP/HTTPS-URL von TeamSpeak WebQuery, bei Bedarf mit Proxy-Pfad. Nicht die WebSpeak-Seite. HTTPS benötigt ein vertrauenswürdiges Zertifikat.",
|
||||
tsAdminHost: "Query-Host (optional)",
|
||||
tsAdminHostHelp: "Leer lassen für den festen TS-Host. Gemeint ist TeamSpeak Query, nicht der SSH-Zugang zum Betriebssystem. TCP ist unverschlüsselt und erfordert ein vertrauenswürdiges Netz.",
|
||||
tsAdminServerId: "Virtuelle Server-ID",
|
||||
tsAdminServerIdHelp: "0 wählt den festen Sprachport. Für einen eingeschränkten API-Schlüssel die erlaubte virtuelle Server-ID eintragen.",
|
||||
tsAdminApiKey: "WebQuery-API-Schlüssel",
|
||||
tsAdminApiKeyConfigured: "API-Schlüssel gespeichert; leer lassen zum Beibehalten",
|
||||
tsAdminKeyHelp: "Einen vom TS-Administrator erstellten WebQuery-Schlüssel verwenden. Lesen benötigt Leserechte, Änderungen Schreibumfang und TS-Rechte. Schlüssel werden serverseitig verschlüsselt.",
|
||||
tsAdminSetKey: "API-Schlüssel setzen / ersetzen",
|
||||
tsAdminRemoveKey: "API-Schlüssel entfernen",
|
||||
tsAdminKeepKey: "API-Schlüssel behalten",
|
||||
tsAdminActionSaved: "TeamSpeak-Aktion abgeschlossen.",
|
||||
tsAdminServerSettings: "Servereinstellungen",
|
||||
tsAdminWelcome: "Willkommensnachricht",
|
||||
tsAdminSlots: "Maximale Clientzahl",
|
||||
tsAdminCreateChannel: "Kanal erstellen",
|
||||
tsAdminRenameChannel: "Kanal umbenennen",
|
||||
tsAdminDeleteChannel: "Kanal löschen",
|
||||
tsAdminParent: "Übergeordneter Kanal",
|
||||
tsAdminRoot: "Oberste Ebene",
|
||||
tsAdminDescription: "Kanalbeschreibung",
|
||||
tsAdminPermanent: "Permanenter Kanal",
|
||||
tsAdminMove: "Client verschieben",
|
||||
tsAdminKick: "Vom Server entfernen",
|
||||
tsAdminBan: "Identität sperren",
|
||||
tsAdminGroupAction: "Servergruppe zuweisen",
|
||||
tsAdminGroup: "Servergruppe",
|
||||
tsAdminRemoveGroup: "Aus Gruppe entfernen",
|
||||
tsAdminReason: "Grund",
|
||||
tsAdminBanDuration: "Sperrdauer in Sekunden (0: dauerhaft)",
|
||||
tsAdminBanHelp: "Sperrt die Identität, ohne andere Nutzer derselben Gateway-IP zu treffen.",
|
||||
tsAdminBans: "Sperrliste",
|
||||
tsAdminNoBans: "Keine Sperren.",
|
||||
tsAdminRestricted: "Diese Zugangsdaten dürfen diese Liste nicht lesen. Andere Funktionen bleiben verfügbar.",
|
||||
tsAdminConfirm: "Aktion bestätigen",
|
||||
tsAdminCancel: "Abbrechen",
|
||||
tsAdminDeleteHelp: "Löscht den gewählten Kanal; belegte Kanäle oder Kanäle mit Unterkanälen werden abgelehnt.",
|
||||
tsAdminActionHelp: "Die Aktion gilt sofort für das unten gewählte TeamSpeak-Ziel. Vor der Bestätigung prüfen.",
|
||||
tsAdminUrlError: "HTTP/HTTPS-WebQuery-URL ohne Zugangsdaten, Abfrageparameter oder Fragment eingeben.",
|
||||
tsAdminKeyError: "Vor dem Aktivieren der WebQuery-Verwaltung einen API-Schlüssel speichern.",
|
||||
tsAdminHostError: "Ungültiger Query-Host; Port separat eintragen.",
|
||||
tsAdminServerIdError: "Ungültige virtuelle Server-ID; 0 wählt automatisch.",
|
||||
tsAdminPermissionError: "TeamSpeak hat die Aktion abgelehnt. Query-Rechte oder API-Schlüsselumfang prüfen.",
|
||||
tsAdminAuthError: "Ungültige Query-Zugangsdaten oder kein API-Zugriff auf diesen virtuellen Server.",
|
||||
tsAdminActionError: "TeamSpeak-Aktion fehlgeschlagen. Aktualisieren, Eingaben und Serverrechte prüfen.",
|
||||
tsAdminClientChanged: "Der Client ist offline oder seine Identität hat sich geändert. Aktualisieren und neu auswählen.",
|
||||
tsAdminConfigChanged: "Verwaltungsverbindung oder fester Server geändert. Vor dem Wiederholen aktualisieren.",
|
||||
tsAdminPartialError: "Die Identität wurde gesperrt, aber das Entfernen schlug fehl. Aktualisieren, nicht wiederholen.",
|
||||
tsAdminRateError: "TeamSpeak-Flutschutz hat die Anfrage abgelehnt. Später manuell wiederholen.",
|
||||
tsAdminTlsError: "WebQuery-HTTPS-Zertifikat nicht vertrauenswürdig oder abgelaufen. Zertifikat korrigieren oder vertrauenswürdige CA konfigurieren.",
|
||||
tsAdminActionSuccessEvent: "TeamSpeak-Verwaltungsaktion erfolgreich",
|
||||
tsAdminActionFailureEvent: "TeamSpeak-Verwaltungsaktion fehlgeschlagen",
|
||||
tsAdminActionPartialEvent: "TeamSpeak-Verwaltungsaktion teilweise abgeschlossen",
|
||||
} as const satisfies Record<keyof typeof zh, string>;
|
||||
|
||||
const ru = {
|
||||
tsAdminTransport: "Подключение",
|
||||
tsAdminWeb: "WebQuery (рекомендуется)",
|
||||
tsAdminSsh: "ServerQuery SSH",
|
||||
tsAdminTcp: "ServerQuery TCP (TS3)",
|
||||
tsAdminUrl: "Адрес WebQuery",
|
||||
tsAdminWebHelp: "Укажите HTTP/HTTPS-адрес TeamSpeak WebQuery, при необходимости с путём прокси. Это не адрес WebSpeak. Сертификат HTTPS должен быть доверенным.",
|
||||
tsAdminHost: "Хост Query (необязательно)",
|
||||
tsAdminHostHelp: "Пустое поле означает фиксированный хост TS. Это служба TeamSpeak Query, а не SSH операционной системы. TCP не шифруется: используйте доверенную сеть.",
|
||||
tsAdminServerId: "ID виртуального сервера",
|
||||
tsAdminServerIdHelp: "0 — выбор по голосовому порту. Для ограниченного API-ключа укажите разрешённый ID виртуального сервера.",
|
||||
tsAdminApiKey: "API-ключ WebQuery",
|
||||
tsAdminApiKeyConfigured: "API-ключ сохранён; оставьте пустым для сохранения",
|
||||
tsAdminKeyHelp: "Используйте WebQuery API-ключ администратора TS. Для изменений нужны область записи и права TS. Ключ хранится на сервере в зашифрованном виде.",
|
||||
tsAdminSetKey: "Задать / заменить API-ключ",
|
||||
tsAdminRemoveKey: "Удалить API-ключ",
|
||||
tsAdminKeepKey: "Сохранить API-ключ",
|
||||
tsAdminActionSaved: "Операция TeamSpeak выполнена.",
|
||||
tsAdminServerSettings: "Настройки сервера",
|
||||
tsAdminWelcome: "Приветствие",
|
||||
tsAdminSlots: "Максимум клиентов",
|
||||
tsAdminCreateChannel: "Создать канал",
|
||||
tsAdminRenameChannel: "Переименовать канал",
|
||||
tsAdminDeleteChannel: "Удалить канал",
|
||||
tsAdminParent: "Родительский канал",
|
||||
tsAdminRoot: "Верхний уровень",
|
||||
tsAdminDescription: "Описание канала",
|
||||
tsAdminPermanent: "Постоянный канал",
|
||||
tsAdminMove: "Переместить клиента",
|
||||
tsAdminKick: "Отключить от сервера",
|
||||
tsAdminBan: "Заблокировать личность",
|
||||
tsAdminGroupAction: "Назначить серверную группу",
|
||||
tsAdminGroup: "Серверная группа",
|
||||
tsAdminRemoveGroup: "Удалить из группы",
|
||||
tsAdminReason: "Причина",
|
||||
tsAdminBanDuration: "Блокировка в секундах (0: навсегда)",
|
||||
tsAdminBanHelp: "Блокируется личность, а не общий IP шлюза других пользователей.",
|
||||
tsAdminBans: "Блокировки",
|
||||
tsAdminNoBans: "Блокировок нет.",
|
||||
tsAdminRestricted: "Эти данные не дают доступа к списку. Другие функции доступны.",
|
||||
tsAdminConfirm: "Подтвердить операцию",
|
||||
tsAdminCancel: "Отмена",
|
||||
tsAdminDeleteHelp: "Удаляет выбранный канал. Каналы с участниками или подканалами удалить нельзя.",
|
||||
tsAdminActionHelp: "Операция сразу применяется к выбранному объекту TeamSpeak. Проверьте его перед подтверждением.",
|
||||
tsAdminUrlError: "Укажите HTTP/HTTPS-адрес WebQuery без данных входа, параметров и фрагмента.",
|
||||
tsAdminKeyError: "Перед включением WebQuery сохраните API-ключ.",
|
||||
tsAdminHostError: "Неверный хост Query; укажите порт отдельно.",
|
||||
tsAdminServerIdError: "Неверный ID виртуального сервера; 0 — автовыбор.",
|
||||
tsAdminPermissionError: "TeamSpeak отклонил операцию. Проверьте права Query и область API-ключа.",
|
||||
tsAdminAuthError: "Неверные данные Query или API-ключ не даёт доступа к этому серверу.",
|
||||
tsAdminActionError: "Операция TeamSpeak не выполнена. Обновите данные и проверьте параметры и права.",
|
||||
tsAdminClientChanged: "Клиент отключился или его личность изменилась. Обновите список и выберите снова.",
|
||||
tsAdminConfigChanged: "Изменилось подключение управления или фиксированный сервер. Обновите данные.",
|
||||
tsAdminPartialError: "Блокировка создана, но отключить клиента не удалось. Обновите данные, не повторяйте операцию.",
|
||||
tsAdminRateError: "Защита TeamSpeak от частых запросов отклонила запрос. Повторите позже вручную.",
|
||||
tsAdminTlsError: "Сертификат HTTPS WebQuery недоверенный или просрочен. Исправьте сертификат или настройте доверенный CA шлюза.",
|
||||
tsAdminActionSuccessEvent: "Операция управления TeamSpeak выполнена",
|
||||
tsAdminActionFailureEvent: "Ошибка операции управления TeamSpeak",
|
||||
tsAdminActionPartialEvent: "Операция управления TeamSpeak выполнена частично",
|
||||
} as const satisfies Record<keyof typeof zh, string>;
|
||||
|
||||
const ja = {
|
||||
tsAdminTransport: "接続方式",
|
||||
tsAdminWeb: "WebQuery(推奨)",
|
||||
tsAdminSsh: "ServerQuery SSH",
|
||||
tsAdminTcp: "ServerQuery TCP(TS3)",
|
||||
tsAdminUrl: "WebQuery URL",
|
||||
tsAdminWebHelp: "TeamSpeak WebQuery の HTTP/HTTPS URL を入力します。プロキシのパスも指定できます。WebSpeak の URL ではありません。HTTPS は信頼済み証明書を使用します。",
|
||||
tsAdminHost: "Query ホスト(任意)",
|
||||
tsAdminHostHelp: "空欄では固定 TS ホストを使用します。OS の SSH ではなく TeamSpeak Query の設定です。TCP は暗号化されないため、信頼できるネットワークで使用してください。",
|
||||
tsAdminServerId: "仮想サーバー ID",
|
||||
tsAdminServerIdHelp: "0 は固定音声ポートで自動選択します。制限付き API キーでは許可された仮想サーバー ID を指定してください。",
|
||||
tsAdminApiKey: "WebQuery API キー",
|
||||
tsAdminApiKeyConfigured: "保存済み API キーを維持するには空欄のままにします",
|
||||
tsAdminKeyHelp: "TS 管理者が作成した WebQuery API キーを使用します。変更には書き込みスコープと TS 権限が必要です。キーはサーバーで暗号化して保存されます。",
|
||||
tsAdminSetKey: "API キーを設定・変更",
|
||||
tsAdminRemoveKey: "API キーを削除",
|
||||
tsAdminKeepKey: "API キーを維持",
|
||||
tsAdminActionSaved: "TeamSpeak の操作が完了しました。",
|
||||
tsAdminServerSettings: "サーバー設定",
|
||||
tsAdminWelcome: "ウェルカムメッセージ",
|
||||
tsAdminSlots: "最大接続数",
|
||||
tsAdminCreateChannel: "チャンネル作成",
|
||||
tsAdminRenameChannel: "チャンネル名を変更",
|
||||
tsAdminDeleteChannel: "チャンネル削除",
|
||||
tsAdminParent: "親チャンネル",
|
||||
tsAdminRoot: "最上位",
|
||||
tsAdminDescription: "チャンネル説明",
|
||||
tsAdminPermanent: "永続チャンネル",
|
||||
tsAdminMove: "メンバーを移動",
|
||||
tsAdminKick: "サーバーから退出させる",
|
||||
tsAdminBan: "ID を禁止",
|
||||
tsAdminGroupAction: "サーバーグループ割当",
|
||||
tsAdminGroup: "サーバーグループ",
|
||||
tsAdminRemoveGroup: "グループから削除",
|
||||
tsAdminReason: "理由",
|
||||
tsAdminBanDuration: "禁止期間(秒、0 は無期限)",
|
||||
tsAdminBanHelp: "共通のゲートウェイ IP を使う他のユーザーに影響しないよう、ID を禁止します。",
|
||||
tsAdminBans: "禁止一覧",
|
||||
tsAdminNoBans: "禁止はありません。",
|
||||
tsAdminRestricted: "この認証情報では一覧を取得できません。他の機能は利用できます。",
|
||||
tsAdminConfirm: "操作を確定",
|
||||
tsAdminCancel: "キャンセル",
|
||||
tsAdminDeleteHelp: "選択したチャンネルを削除します。メンバーまたは子チャンネルがある場合は拒否されます。",
|
||||
tsAdminActionHelp: "操作は下の TeamSpeak 対象に直ちに適用されます。内容を確認してください。",
|
||||
tsAdminUrlError: "認証情報、クエリ、フラグメントを含まない HTTP/HTTPS WebQuery URL を入力してください。",
|
||||
tsAdminKeyError: "WebQuery 管理を有効にする前に API キーを保存してください。",
|
||||
tsAdminHostError: "Query ホストが無効です。ポートは別に入力してください。",
|
||||
tsAdminServerIdError: "仮想サーバー ID が無効です。0 で自動選択します。",
|
||||
tsAdminPermissionError: "TeamSpeak が操作を拒否しました。Query 権限または API キーのスコープを確認してください。",
|
||||
tsAdminAuthError: "Query 認証情報が無効か、API キーでこの仮想サーバーにアクセスできません。",
|
||||
tsAdminActionError: "TeamSpeak の操作に失敗しました。更新して入力とサーバー権限を確認してください。",
|
||||
tsAdminClientChanged: "メンバーが退出したか ID が変わりました。更新して選択し直してください。",
|
||||
tsAdminConfigChanged: "管理接続または固定サーバー設定が変わりました。更新してください。",
|
||||
tsAdminPartialError: "ID の禁止は作成されましたが、退出処理に失敗しました。更新して確認し、再送信しないでください。",
|
||||
tsAdminRateError: "TeamSpeak の頻度制限で拒否されました。しばらく待って手動で再試行してください。",
|
||||
tsAdminTlsError: "WebQuery の HTTPS 証明書が信頼されていないか期限切れです。証明書またはゲートウェイの信頼済み CA を設定してください。",
|
||||
tsAdminActionSuccessEvent: "TeamSpeak 管理操作に成功",
|
||||
tsAdminActionFailureEvent: "TeamSpeak 管理操作に失敗",
|
||||
tsAdminActionPartialEvent: "TeamSpeak 管理操作が一部完了",
|
||||
} as const satisfies Record<keyof typeof zh, string>;
|
||||
|
||||
export const tsAdminCopy = { zh, en, de, ru, ja };
|
||||
@@ -1,5 +1,6 @@
|
||||
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput } from "../../../src/shared/admin-inputs.js";
|
||||
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
|
||||
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
|
||||
|
||||
export class AdminApiError extends Error {
|
||||
constructor(readonly code: string, readonly status = 0, message = code) {
|
||||
@@ -106,6 +107,10 @@ export function createAdminApi(options: AdminApiOptions) {
|
||||
overview: (signal?: AbortSignal) => request("/overview", adminResponses.overview, "GET", undefined, true, signal),
|
||||
settings: (signal?: AbortSignal) => request("/server", adminResponses.settings, "GET", undefined, true, signal),
|
||||
saveSettings: (body: AdminSettingsInput, signal?: AbortSignal) => request("/server", adminResponses.savedSettings, "PUT", body, true, signal),
|
||||
tsAdminSettings: (signal?: AbortSignal) => request("/ts-admin/settings", adminResponses.tsAdminSettings, "GET", undefined, true, signal),
|
||||
saveTsAdminSettings: (body: TsAdminSettingsInput, signal?: AbortSignal) => request("/ts-admin/settings", adminResponses.savedTsAdminSettings, "PUT", body, true, signal),
|
||||
tsAdminOverview: (signal?: AbortSignal) => request("/ts-admin/overview", adminResponses.tsAdminOverview, "POST", {}, true, signal),
|
||||
tsAdminAction: (body: TsAdminActionRequest, signal?: AbortSignal) => request("/ts-admin/action", adminResponses.ok, "POST", body, true, signal),
|
||||
probe: (body: Pick<AdminSettingsInput, "target" | "serverPassword" | "passwordAction">, signal?: AbortSignal) => request("/server/test", adminResponses.probe, "POST", body, true, signal),
|
||||
sessions: (signal?: AbortSignal) => request("/sessions", adminResponses.sessions, "GET", undefined, true, signal),
|
||||
terminateSession: (id: string, signal?: AbortSignal) => request(`/sessions/${encodeURIComponent(id)}/terminate`, adminResponses.ok, "POST", {}, true, signal),
|
||||
@@ -116,6 +121,8 @@ export function createAdminApi(options: AdminApiOptions) {
|
||||
logs: (signal?: AbortSignal) => request("/logs?limit=100", adminResponses.logs, "GET", undefined, true, signal),
|
||||
audit: (signal?: AbortSignal) => request("/audit?limit=50", adminResponses.audit, "GET", undefined, true, signal),
|
||||
skins: (signal?: AbortSignal) => request("/skins", adminResponses.skins, "GET", undefined, true, signal),
|
||||
skinStore: (refresh = false, signal?: AbortSignal) => request(refresh ? "/skin-store/refresh" : "/skin-store", adminResponses.skinStore, refresh ? "POST" : "GET", refresh ? {} : undefined, true, signal),
|
||||
installStoreSkin: (body: SkinStoreInstallInput, signal?: AbortSignal) => request("/skin-store/install", adminResponses.uploadedSkin, "POST", body, true, signal),
|
||||
setDefaultSkin: (id: string, signal?: AbortSignal) => request("/skins/default", adminResponses.defaultSkin, "PUT", { id }, true, signal),
|
||||
setSkinEnabled: (id: string, enabled: boolean, signal?: AbortSignal) => request(`/skins/${encodeURIComponent(id)}/enabled`, adminResponses.updatedSkin, "PUT", { enabled }, true, signal),
|
||||
deleteSkin: (id: string, signal?: AbortSignal) => request(`/skins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", {}, true, signal),
|
||||
|
||||
@@ -46,7 +46,7 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
|
||||
{
|
||||
id: BUILTIN_KAAK_SKIN_ID,
|
||||
name: "KAAK",
|
||||
version: "3.1.121",
|
||||
version: "3.1.122",
|
||||
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.",
|
||||
|
||||
@@ -486,7 +486,7 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" });
|
||||
const skin = await importSkinPack(file);
|
||||
assert.equal(skin.id, "community.kaak-voice");
|
||||
assert.equal(skin.version, "3.1.121");
|
||||
assert.equal(skin.version, "3.1.122");
|
||||
assert.equal(BUILTIN_SKIN_CATALOG.find((entry) => entry.id === skin.id)?.version, skin.version);
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
const baseMessages = skin.contentData?.locales["zh-CN"]?.messages ?? {};
|
||||
@@ -671,7 +671,7 @@ test("the distributable KAAK package provides full home and voice surfaces", asy
|
||||
assert.ok(skin.css.includes("data-session-connected=\"true\""));
|
||||
assert.ok(skin.css.includes("[data-ws-plugin-part=\"kaak-workspace.workspace\"][data-session-connected=\"true\"]:not([data-mobile-channels=\"true\"])"));
|
||||
assert.ok(skin.css.includes("[data-ws-plugin-part=\"kaak-workspace\"][data-ws-plugin-surface=\"voice\"]:has([data-ws-plugin-part=\"kaak-workspace.chat-panel-toggle\"][aria-expanded=\"false\"])"));
|
||||
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.kaak-voice"\]\s+\[data-ws-plugin-part="kaak-workspace"\]\[data-ws-plugin-surface="voice"\]\s*\{[\s\S]*?height: 100dvh;/, "the voice surface owns the KAAK grid and viewport sizing");
|
||||
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.kaak-voice"\]\s+\[data-ws-plugin-part="kaak-workspace"\]\[data-ws-plugin-surface="voice"\]\s*\{[^}]*height: calc\(var\(--ws-viewport-height, 100dvh\) \/ var\(--ui-scale, 1\)\);[^}]*max-height: calc\(var\(--ws-viewport-height, 100dvh\) \/ var\(--ui-scale, 1\)\);/, "the voice surface compensates application zoom so the bottom dock stays within the viewport");
|
||||
assert.doesNotMatch(skin.css, /\[data-ws-plugin-part="kaak-workspace"\](?!\[data-ws-plugin-surface="voice"\])/, "KAAK workspace selectors must anchor to the voice surface root, not generic child nodes");
|
||||
assert.ok(skin.css.includes("mobile-room-return"));
|
||||
assert.ok(skin.css.includes('[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"]'), "the room menu stays hidden on the channel tree page");
|
||||
@@ -936,6 +936,40 @@ test("the full voice surface example packages share-aware members and host-owned
|
||||
assert.ok(skin.css.includes("@media (max-width: 800px)"));
|
||||
});
|
||||
|
||||
test("the Discord Voice package imports portable home and voice surfaces", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/discord-voice.wskin", import.meta.url));
|
||||
const file = new File([archive], "discord-voice.wskin", { type: "application/octet-stream" });
|
||||
const skin = await importSkinPack(file);
|
||||
assert.equal(skin.id, "community.discord-voice");
|
||||
assert.equal(skin.packageType, "open-skin");
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
assert.deepEqual(skin.pluginData?.components.map(({ id, page, mode }) => [id, page, mode]), [
|
||||
["discord-home", "home", "surface"],
|
||||
["discord-workspace", "voice", "surface"],
|
||||
]);
|
||||
const voice = skin.pluginData?.components.find((component) => component.page === "voice");
|
||||
assert.ok(voice?.permissions.includes("ui.surface.replace"));
|
||||
assert.ok(voice?.permissions.includes("session.channels.read"));
|
||||
assert.ok(voice?.permissions.includes("session.members.read"));
|
||||
assert.ok(voice?.permissions.includes("chat.channel.send"));
|
||||
assert.ok(voice?.permissions.includes("audio.microphone.control"));
|
||||
assert.ok(voice?.permissions.includes("voice.screenShare.control"));
|
||||
assert.equal(voice?.actions["copy-invite-link"]?.type, "session.copyInviteLink");
|
||||
assert.equal(skin.runtimePlugins?.plugins.length ?? 0, 0, "the open skin contains no executable plugin code");
|
||||
const baseMessageKeys = Object.keys(skin.contentData?.locales.en?.messages ?? {}).sort();
|
||||
for (const locale of ["zh-CN", "de", "ru", "ja"]) {
|
||||
assert.deepEqual(
|
||||
Object.keys(skin.contentData?.locales[locale]?.messages ?? {}).sort(),
|
||||
baseMessageKeys,
|
||||
`Discord Voice provides complete skin copy for ${locale}`,
|
||||
);
|
||||
}
|
||||
assert.ok(skin.css.includes("--skin-discord-bg-guilds"));
|
||||
assert.doesNotMatch(skin.css, /\.ws-skin-root\[data-ws-skin="community\.discord-voice"\]\s+(?:strong|time)\b/, "host chat text styles stay scoped to public chat parts");
|
||||
assert.doesNotMatch(skin.css, /(?:^|[\s,])\.message-(?:meta|row|body|bubble|composer)\b/, "the package does not depend on private chat CSS classes");
|
||||
assert.ok(skin.css.includes("@media (max-width: 760px)"));
|
||||
});
|
||||
|
||||
test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspace", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/harbor-voice.wskin", import.meta.url));
|
||||
const file = new File([archive], "harbor-voice.wskin", { type: "application/octet-stream" });
|
||||
|
||||
@@ -3349,6 +3349,41 @@
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
|
||||
:deep(.skin-library-tabs) {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 5px;
|
||||
border: 1px solid var(--admin-border);
|
||||
border-radius: 12px;
|
||||
width: fit-content;
|
||||
}
|
||||
:deep(.skin-library-tabs button) {
|
||||
min-height: 42px;
|
||||
padding: 8px 18px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--admin-muted);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
:deep(.skin-library-tabs button[aria-current="page"]) {
|
||||
background: var(--admin-raised);
|
||||
color: var(--admin-accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
:deep(.skin-store) { display: grid; gap: 18px; min-width: 0; }
|
||||
:deep(.skin-store-heading) { display: flex; align-items: start; justify-content: space-between; flex-wrap: wrap; gap: 14px; }
|
||||
:deep(.skin-store-heading h3) { margin: 0 0 6px; }
|
||||
:deep(.skin-store-heading p), :deep(.skin-store-source) { margin: 0; color: var(--admin-muted); line-height: 1.6; overflow-wrap: anywhere; }
|
||||
:deep(.skin-store-source a) { color: var(--admin-accent); }
|
||||
:deep(.skin-library-card.skin-store-card) { display: flex; flex-direction: column; }
|
||||
:deep(.skin-store > .alert) { display: flex; align-items: flex-start; gap: 10px; }
|
||||
:deep(.skin-store > .alert > svg) { flex: 0 0 auto; }
|
||||
:deep(.skin-store-card .skin-library-copy) { flex: 1; }
|
||||
:deep(.skin-store-card .skin-library-actions) { margin-top: auto; padding-top: 14px; }
|
||||
:deep(.skin-store-warning) { color: var(--admin-muted); }
|
||||
:deep(.skin-library-page) {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
@@ -3654,6 +3689,150 @@
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-page) {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-credentials),
|
||||
:deep(.ts-admin-live) {
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-form) {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-enable) {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-enable input) {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: 2px 0 0;
|
||||
accent-color: #07877e;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-enable span) {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-fields) {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2,minmax(0,1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-fields label),
|
||||
:deep(.ts-admin-password-row label) {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 6px;
|
||||
color: var(--admin-muted,#687a74);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-fields input),
|
||||
:deep(.ts-admin-password-row input) {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 40px;
|
||||
padding: 0 11px;
|
||||
color: var(--admin-text,#263a35);
|
||||
background: var(--admin-surface,#fff);
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-fields input[readonly]) {
|
||||
opacity: .72;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-password-row) {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0,1fr) auto auto;
|
||||
align-items: end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-password-row button) {
|
||||
min-height: 38px;
|
||||
padding: 0 12px;
|
||||
color: var(--admin-text,#263a35);
|
||||
background: var(--admin-surface,#fff);
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 9px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-password-row button.active) {
|
||||
color: #087d70;
|
||||
border-color: #0f9a8b;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-password-row button.danger) {
|
||||
color: #b73838;
|
||||
border-color: #e5aaaa;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-actions) {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-metrics) {
|
||||
grid-template-columns: repeat(3,minmax(0,1fr));
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-metrics article) {
|
||||
padding: 14px;
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-tables) {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2,minmax(0,1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-tables .operation-card) {
|
||||
min-width: 0;
|
||||
height: auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-tables .table-wrap) {
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
:deep(.ts-admin-page .alert.success) {
|
||||
color: #087d70;
|
||||
background: #e9f8f2;
|
||||
border: 1px solid #b5e7d8;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
:deep(.ts-admin-tables) { grid-template-columns: minmax(0,1fr); }
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
:deep(.ts-admin-fields),
|
||||
:deep(.ts-admin-metrics) { grid-template-columns: minmax(0,1fr); }
|
||||
:deep(.ts-admin-password-row) { grid-template-columns: minmax(0,1fr) minmax(0,auto); }
|
||||
:deep(.ts-admin-password-row label) { grid-column: 1/-1; }
|
||||
}
|
||||
|
||||
:deep(.operations-page .operation-empty) {
|
||||
min-height: 84px;
|
||||
}
|
||||
@@ -3741,3 +3920,171 @@
|
||||
grid-template-columns: minmax(0,1fr);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.ts-admin-form fieldset) {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 14px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
:deep(.ts-admin-fields select),
|
||||
:deep(.ts-admin-fields textarea) {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 10px 11px;
|
||||
color: var(--admin-text,#263a35);
|
||||
background: var(--admin-surface,#fff);
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 9px;
|
||||
font: inherit;
|
||||
}
|
||||
:deep(.ts-admin-fields textarea) { resize: vertical; }
|
||||
:deep(.ts-admin-wide) { grid-column: 1/-1; }
|
||||
:deep(.ts-admin-toolbar),
|
||||
:deep(.ts-admin-row-actions) { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
:deep(.ts-admin-toolbar) { margin: 12px 0; }
|
||||
:deep(.ts-admin-row-actions button) {
|
||||
padding: 5px 8px;
|
||||
color: var(--admin-text,#263a35);
|
||||
background: var(--admin-surface,#fff);
|
||||
border: 1px solid var(--admin-border,#dce7e3);
|
||||
border-radius: 7px;
|
||||
font: inherit;
|
||||
white-space: normal;
|
||||
cursor: pointer;
|
||||
}
|
||||
:deep(.ts-admin-row-actions button.danger) { color: #c04444; }
|
||||
:deep(.ts-admin-page button:disabled) { opacity: .5; cursor: wait; }
|
||||
:deep(.ts-admin-page td small) { display: block; opacity: .65; }
|
||||
:deep(.ts-admin-page td) { overflow-wrap: anywhere; }
|
||||
:deep(.ts-admin-selected-target) { font-size: 16px; font-weight: 700; overflow-wrap: anywhere; }
|
||||
:deep(.ts-admin-editor) { margin: 14px 0; padding: 16px; border-color: var(--admin-accent,#07877e); scroll-margin-top: 16px; }
|
||||
:deep(.ts-admin-live > .operation-card) { margin-top: 14px; }
|
||||
@media (max-width: 1100px) { :deep(.ts-admin-tables) { grid-template-columns: minmax(0,1fr); } }
|
||||
|
||||
/* Administration is grouped by the system it controls. */
|
||||
.admin-sidebar .admin-primary-nav { gap: 24px; min-height: 0; overflow-y: auto; }
|
||||
.admin-nav-group { display: grid; gap: 5px; min-width: 0; }
|
||||
.admin-nav-heading { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; padding: 0 12px 7px; color: #92b9b2; font-size: 10px; font-weight: 700; letter-spacing: .04em; }
|
||||
.admin-sidebar nav a { min-width: 0; overflow-wrap: anywhere; line-height: 1.5; }
|
||||
.admin-sidebar nav a .ui-icon { flex: none; }
|
||||
:deep(.admin-optional) { display: inline-flex; align-items: center; width: fit-content; padding: 3px 8px; border: 1px solid var(--admin-border); border-radius: 999px; color: var(--admin-muted); background: var(--admin-raised); font-size: 10px; font-weight: 600; line-height: 1.4; white-space: nowrap; }
|
||||
.admin-nav-heading .admin-optional { padding: 2px 6px; color: #c1d8d3; background: #174b45; border-color: #32645c; font-size: 9px; }
|
||||
:deep(.page-content) { max-width: 1500px; margin-inline: auto; }
|
||||
:deep(.page-heading) { gap: 18px; }
|
||||
:deep(.page-heading p) { max-width: 72ch; line-height: 1.65; }
|
||||
:deep(.page-heading > button) { flex: none; }
|
||||
:deep(.admin-scope-banner) { display: flex; align-items: flex-start; gap: 12px; margin: 0 0 20px; padding: 14px 17px; border: 1px solid var(--admin-border); border-radius: 12px; background: var(--admin-accent-soft); color: var(--admin-accent); }
|
||||
:deep(.admin-scope-banner > .ui-icon) { flex: none; margin-top: 2px; }
|
||||
:deep(.admin-scope-banner strong) { font-size: 12px; }
|
||||
:deep(.admin-scope-banner p) { margin: 4px 0 0; color: var(--admin-muted); font-size: 11px; line-height: 1.65; }
|
||||
:deep(.admin-section-nav) { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 20px; padding: 5px; border: 1px solid var(--admin-border); border-radius: 12px; background: var(--admin-raised); }
|
||||
:deep(.admin-section-nav > button) { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 38px; padding: 9px 15px; border: 1px solid transparent; border-radius: 9px; color: var(--admin-muted); background: transparent; font: inherit; font-size: 12px; font-weight: 700; line-height: 1.4; cursor: pointer; }
|
||||
:deep(.admin-section-nav > button:hover) { color: var(--admin-text); background: var(--admin-surface); }
|
||||
:deep(.admin-section-nav > button[aria-current="page"]) { color: var(--admin-accent); background: var(--admin-surface); border-color: var(--admin-border); box-shadow: 0 2px 5px #00000008; }
|
||||
:deep(.admin-tab-count) { padding: 2px 7px; border-radius: 6px; color: var(--admin-accent); background: var(--admin-accent-soft); font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
:deep(.admin-section-nav > button:focus-visible),
|
||||
:deep(.ts-admin-credentials > summary:focus-visible),
|
||||
.admin-sidebar a:focus-visible,
|
||||
:deep(.admin-domain-links > a:focus-visible),
|
||||
:deep(.admin-domain-entry:focus-visible) { outline: 3px solid var(--admin-accent); outline-offset: 2px; }
|
||||
:deep(.admin-card-heading) { margin-bottom: 18px; }
|
||||
:deep(.admin-card-heading h3) { margin: 0; color: var(--admin-text); font-size: 15px; }
|
||||
:deep(.admin-card-heading p),
|
||||
:deep(.admin-save-scope) { margin: 7px 0 0; color: var(--admin-muted); font-size: 11px; line-height: 1.7; }
|
||||
:deep(.admin-save-scope) { display: flex; align-items: flex-start; gap: 8px; margin-top: 18px; }
|
||||
:deep(.admin-save-scope .ui-icon) { flex: none; margin-top: 2px; }
|
||||
:deep(.server-page .admin-setting-card) { padding: 20px; }
|
||||
:deep(.admin-setting-card .access-mode-fieldset > legend) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
:deep(.admin-settings-section) { margin-top: 0; }
|
||||
:deep(.operations-page) { display: block; width: 100%; padding: clamp(18px,2vw,32px) clamp(18px,2.4vw,44px) 34px; }
|
||||
:deep(.operations-page .page-heading) { margin-bottom: 22px; }
|
||||
:deep(.admin-operations-section) { min-width: 0; }
|
||||
:deep(.admin-operations-section .table-wrap) { max-height: 520px; overflow: auto; }
|
||||
:deep(.admin-operations-section .invite-list) { max-height: 450px; overflow-y: auto; }
|
||||
:deep(.admin-operations-section .system-notice) { margin-top: 16px; }
|
||||
:deep(.admin-domain-grid) { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 14px; }
|
||||
:deep(.admin-domain-card) { display: flex; min-width: 0; flex-direction: column; }
|
||||
:deep(.admin-domain-card > header) { margin-bottom: 14px; }
|
||||
:deep(.admin-domain-card h3) { display: flex; align-items: center; flex-wrap: wrap; gap: 9px; }
|
||||
:deep(.admin-domain-card p) { max-width: 65ch; line-height: 1.7; }
|
||||
:deep(.admin-domain-links) { display: grid; gap: 7px; margin-top: auto; }
|
||||
:deep(.admin-domain-links > a) { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border: 1px solid var(--admin-border); border-radius: 9px; color: var(--admin-text); background: var(--admin-raised); text-decoration: none; font-size: 12px; font-weight: 600; }
|
||||
:deep(.admin-domain-links > a:hover) { color: var(--admin-accent); border-color: var(--admin-accent); }
|
||||
:deep(.admin-capability-list) { display: flex; flex-wrap: wrap; gap: 6px; margin: 2px 0 20px; }
|
||||
:deep(.admin-capability-list > span) { padding: 5px 9px; border-radius: 6px; background: var(--admin-raised); color: var(--admin-muted); font-size: 11px; }
|
||||
:deep(.admin-domain-entry) { display: flex; align-items: center; align-self: flex-start; gap: 8px; margin-top: auto; color: var(--admin-accent); font-size: 12px; font-weight: 700; text-decoration: none; }
|
||||
:deep(.ts-admin-page) { display: block; }
|
||||
:deep(.ts-admin-page > .page-heading) { margin-bottom: 22px; }
|
||||
:deep(.ts-admin-page > .alert),
|
||||
:deep(.ts-admin-page > .operation-card) { margin-bottom: 16px; }
|
||||
:deep(.admin-ts-setup) { display: flex; align-items: center; gap: 16px; padding: 20px; }
|
||||
:deep(.admin-ts-setup > .ui-icon) { flex: none; color: var(--admin-accent); }
|
||||
:deep(.admin-ts-setup > div) { flex: 1; min-width: 0; }
|
||||
:deep(.admin-ts-setup h3) { margin: 0; font-size: 15px; }
|
||||
:deep(.admin-ts-setup p) { margin: 7px 0 0; color: var(--admin-muted); font-size: 12px; line-height: 1.7; }
|
||||
:deep(.admin-ts-setup > button) { flex: none; }
|
||||
:deep(.ts-admin-credentials) { padding: 0; }
|
||||
:deep(.ts-admin-credentials > summary) { display: flex; align-items: center; gap: 12px; min-height: 76px; padding: 17px 20px; border-radius: 12px; list-style: none; cursor: pointer; }
|
||||
:deep(.ts-admin-credentials > summary::-webkit-details-marker) { display: none; }
|
||||
:deep(.ts-admin-credentials > summary > .ui-icon) { flex: none; color: var(--admin-muted); }
|
||||
:deep(.ts-admin-credentials[open] > summary > .ui-icon) { transform: rotate(90deg); }
|
||||
:deep(.ts-admin-credentials > summary > div) { display: grid; flex: 1; gap: 5px; min-width: 0; }
|
||||
:deep(.ts-admin-credentials > summary strong) { font-size: 14px; }
|
||||
:deep(.ts-admin-credentials > summary small) { color: var(--admin-muted); font-size: 11px; }
|
||||
:deep(.admin-connection-body) { padding: 0 20px 20px; border-top: 1px solid var(--admin-border); }
|
||||
:deep(.admin-connection-body > .field-help) { margin: 15px 0; }
|
||||
:deep(.admin-ts-section) { min-width: 0; margin-top: 18px; }
|
||||
:deep(.admin-ts-section > .operation-card) { padding: 0; border: 0; box-shadow: none; }
|
||||
:deep(.admin-ts-section .table-wrap) { max-height: 520px; overflow: auto; }
|
||||
:deep(.ts-admin-live > .admin-section-nav) { margin-top: 20px; }
|
||||
:deep(.admin-fixed-notice) { align-items: flex-start; gap: 12px; }
|
||||
:deep(.admin-fixed-notice p) { margin-top: 0; }
|
||||
:deep(.admin-fixed-notice a) { color: var(--admin-accent); font-weight: 700; }
|
||||
:deep(.ts-admin-page button:disabled) { cursor: not-allowed; }
|
||||
:deep(.ts-admin-page .alert.success) { color: var(--admin-accent); background: var(--admin-accent-soft); border-color: var(--admin-border); }
|
||||
@media (max-width:1100px) {
|
||||
:deep(.admin-domain-grid) { grid-template-columns: minmax(0,1fr); }
|
||||
}
|
||||
@media (max-width:850px) {
|
||||
.admin-sidebar .admin-primary-nav { grid-template-columns: minmax(0,1fr); gap: 12px; overflow: visible; }
|
||||
.admin-nav-group { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 5px; }
|
||||
.admin-nav-heading { grid-column: 1/-1; padding: 0 8px 3px; }
|
||||
.admin-nav-group + .admin-nav-group { padding-top: 12px; border-top: 1px solid #ffffff20; }
|
||||
.admin-root .admin-sidebar nav a { justify-content: flex-start; gap: 8px; padding: 9px; font-size: 11px; }
|
||||
.admin-sidebar nav a .ui-icon { width: 17px; height: 17px; }
|
||||
:deep(.page-content) { max-width: none; }
|
||||
:deep(.operations-page) { padding: 20px clamp(14px,3vw,28px) 28px; }
|
||||
}
|
||||
@media (max-width:560px) {
|
||||
:deep(.page-heading) { flex-wrap: wrap; gap: 12px; }
|
||||
:deep(.admin-section-nav) { gap: 4px; padding: 4px; }
|
||||
:deep(.admin-section-nav > button) { flex: 1 1 auto; padding: 9px 11px; font-size: 11px; }
|
||||
:deep(.admin-ts-setup) { flex-wrap: wrap; align-items: flex-start; }
|
||||
:deep(.admin-ts-setup > button) { margin-left: 42px; max-width: calc(100% - 42px); white-space: normal; }
|
||||
:deep(.server-page .admin-setting-card) { padding: 16px; }
|
||||
:deep(.ts-admin-credentials > summary) { padding: 16px; flex-wrap: wrap; }
|
||||
:deep(.admin-connection-body) { padding: 0 16px 16px; }
|
||||
}
|
||||
|
||||
:deep(.admin-ts-section .table-wrap) { width: 100%; margin: 0; border: 1px solid var(--admin-border); border-radius: 10px; }
|
||||
:deep(.admin-ts-section table) { min-width: 720px; }
|
||||
:deep(.ts-admin-row-actions) { min-width: 210px; }
|
||||
:deep(.ts-admin-row-actions button) { flex: 0 0 auto; white-space: nowrap; }
|
||||
|
||||
:deep(.admin-ts-section table) { table-layout: fixed; }
|
||||
:deep(.admin-ts-section th:last-child) { width: 240px; }
|
||||
:deep(.admin-ts-section th),
|
||||
:deep(.admin-ts-section td) { white-space: normal; overflow-wrap: anywhere; }
|
||||
:deep(.admin-ts-section .table-wrap:focus-visible) { outline: 3px solid var(--admin-accent); outline-offset: 2px; }
|
||||
|
||||
.admin-root :deep(.alert.info) { color: var(--admin-accent); background: var(--admin-accent-soft); border-color: var(--admin-border); }
|
||||
.admin-root :deep(.diagnostics-card .text-link),
|
||||
:deep(.ts-admin-password-row button.active) { color: var(--admin-accent); }
|
||||
:deep(.ts-admin-row-actions button.danger),
|
||||
:deep(.ts-admin-password-row button.danger) { color: color-mix(in srgb,#df5b50 70%,var(--admin-text)); }
|
||||
|
||||
.admin-root :deep(.operation-card header > strong) { color: var(--admin-accent); }
|
||||
:deep(.ts-admin-credentials > summary .state-pill) { color: var(--admin-accent); background: var(--admin-accent-soft); }
|
||||
@@ -7388,15 +7388,23 @@
|
||||
}
|
||||
|
||||
:deep(.screen-share-player:fullscreen) {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: var(--surface-0);
|
||||
background: #000;
|
||||
}
|
||||
|
||||
:deep(.screen-share-player:fullscreen .screen-share-player-stage) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
aspect-ratio: auto;
|
||||
}
|
||||
|
||||
+55
-37
@@ -144,37 +144,19 @@
|
||||
><strong>WebSpeak</strong><small>{{ tr("adminConsole") }}</small></div
|
||||
></div
|
||||
>
|
||||
<nav
|
||||
><RouterLink
|
||||
to="/admin"
|
||||
exact-active-class="active"
|
||||
><Icon
|
||||
name="activity"
|
||||
:size="18"
|
||||
/>{{ tr("overview") }}</RouterLink
|
||||
><RouterLink
|
||||
to="/admin/server"
|
||||
active-class="active"
|
||||
><Icon
|
||||
name="server"
|
||||
:size="18"
|
||||
/>{{ tr("server") }}</RouterLink
|
||||
><RouterLink
|
||||
to="/admin/operations"
|
||||
active-class="active"
|
||||
><Icon
|
||||
name="users"
|
||||
:size="18"
|
||||
/>{{ tr("operations") }}</RouterLink
|
||||
><RouterLink
|
||||
to="/admin/skins"
|
||||
active-class="active"
|
||||
><Icon
|
||||
name="compass"
|
||||
:size="18"
|
||||
/>{{ tr("skinLibrary") }}</RouterLink
|
||||
></nav
|
||||
>
|
||||
<nav :aria-label="tr('adminConsole')" class="admin-primary-nav">
|
||||
<div class="admin-nav-group">
|
||||
<span class="admin-nav-heading">{{ tr('adminWsGroup') }}</span>
|
||||
<RouterLink to="/admin" exact-active-class="active"><Icon name="activity" :size="18" />{{ tr('overview') }}</RouterLink>
|
||||
<RouterLink to="/admin/server" active-class="active"><Icon name="server" :size="18" />{{ tr('adminInstanceSettings') }}</RouterLink>
|
||||
<RouterLink to="/admin/operations" active-class="active"><Icon name="users" :size="18" />{{ tr('adminInstanceOperations') }}</RouterLink>
|
||||
<RouterLink to="/admin/skins" active-class="active"><Icon name="compass" :size="18" />{{ tr('skinLibrary') }}</RouterLink>
|
||||
</div>
|
||||
<div class="admin-nav-group">
|
||||
<span class="admin-nav-heading">{{ tr('adminTsGroup') }}<span class="admin-optional">{{ tr('adminOptional') }}</span></span>
|
||||
<RouterLink to="/admin/ts-admin" active-class="active"><Icon name="shield" :size="18" />{{ tr('tsAdminTitle') }}</RouterLink>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="sidebar-bottom"
|
||||
><a
|
||||
href="/"
|
||||
@@ -202,7 +184,7 @@
|
||||
>
|
||||
<header class="admin-topbar">
|
||||
<div class="admin-page-title"
|
||||
><small>{{ tr("adminConsole") }}</small
|
||||
><small>{{ currentScope }}</small
|
||||
><h1>{{ currentPageTitle }}</h1></div
|
||||
>
|
||||
<div class="admin-tools">
|
||||
@@ -243,6 +225,7 @@
|
||||
<AdminServerSettings
|
||||
v-if="route.path === '/admin/server'"
|
||||
:model="serverSettings"
|
||||
:initial-section="initialSection"
|
||||
:i18n="i18n"
|
||||
v-model:welcome-language="welcomeLanguage"
|
||||
@webrtc-toggle="handleWebRtcToggle"
|
||||
@@ -250,6 +233,7 @@
|
||||
<AdminOperations
|
||||
v-else-if="route.path === '/admin/operations'"
|
||||
:model="adminOperations"
|
||||
:initial-section="initialSection"
|
||||
:i18n="i18n"
|
||||
/>
|
||||
<AdminSkins
|
||||
@@ -257,6 +241,13 @@
|
||||
:model="adminSkins"
|
||||
:i18n="i18n"
|
||||
/>
|
||||
<AdminTsAdmin
|
||||
v-else-if="route.path === '/admin/ts-admin'"
|
||||
:model="adminTsAdmin"
|
||||
:i18n="i18n"
|
||||
:target-address="savedTsTarget.address"
|
||||
:target-port="savedTsTarget.port"
|
||||
/>
|
||||
|
||||
<section
|
||||
v-else
|
||||
@@ -275,8 +266,8 @@
|
||||
<div class="hero-status"
|
||||
><div
|
||||
><small>{{ tr("systemStatus") }}</small
|
||||
><h2>{{ tr("everythingRunning") }}</h2
|
||||
><p>{{ tr("overviewLead") }}</p></div
|
||||
><h2>{{ tr("adminWsOverviewTitle") }}</h2
|
||||
><p>{{ tr("adminWsOverviewLead") }}</p></div
|
||||
><span class="status-badge"><i></i>{{ tr("running") }}</span></div
|
||||
>
|
||||
<div class="metric-grid"
|
||||
@@ -306,6 +297,21 @@
|
||||
><em>{{ tr("peakSessions", { count: overview.sessions.peak }) }}</em></article
|
||||
></div
|
||||
>
|
||||
<div class="admin-domain-grid">
|
||||
<article class="overview-card admin-domain-card">
|
||||
<header><div><h3><Icon name="waveform" :size="20" />{{ tr('adminWsGroup') }}</h3><p>{{ tr('adminWsManageLead') }}</p></div></header>
|
||||
<div class="admin-domain-links">
|
||||
<RouterLink to="/admin/server"><Icon name="server" :size="17" />{{ tr('adminInstanceSettings') }}</RouterLink>
|
||||
<RouterLink to="/admin/operations"><Icon name="users" :size="17" />{{ tr('adminInstanceOperations') }}</RouterLink>
|
||||
<RouterLink to="/admin/skins"><Icon name="compass" :size="17" />{{ tr('skinLibrary') }}</RouterLink>
|
||||
</div>
|
||||
</article>
|
||||
<article class="overview-card admin-domain-card">
|
||||
<header><div><h3><Icon name="shield" :size="20" />{{ tr('adminTsGroup') }}<span class="admin-optional">{{ tr('adminOptional') }}</span></h3><p>{{ tr('adminTsManageLead') }}</p></div></header>
|
||||
<div class="admin-capability-list"><span>{{ tr('tsAdminServerSettings') }}</span><span>{{ tr('tsAdminChannels') }}</span><span>{{ tr('tsAdminClients') }}</span><span>{{ tr('tsAdminBans') }}</span></div>
|
||||
<RouterLink to="/admin/ts-admin" class="admin-domain-entry">{{ tr('adminTsEntry') }}<Icon name="chevron-right" :size="16" /></RouterLink>
|
||||
</article>
|
||||
</div>
|
||||
<div class="overview-columns"
|
||||
><article class="overview-card target-health-card"
|
||||
><header
|
||||
@@ -393,11 +399,14 @@ import Icon from "../components/Icon.vue";
|
||||
import AdminServerSettings from "../components/admin/AdminServerSettings.vue";
|
||||
import AdminOperations from "../components/admin/AdminOperations.vue";
|
||||
import AdminSkins from "../components/admin/AdminSkins.vue";
|
||||
import AdminTsAdmin from "../components/admin/AdminTsAdmin.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import { createAdminRequests } from "../services/admin-requests.js";
|
||||
import { useAdminServerSettings } from "../composables/useAdminServerSettings.js";
|
||||
import { useAdminOperations } from "../composables/useAdminOperations.js";
|
||||
import { useAdminSkins } from "../composables/useAdminSkins.js";
|
||||
import { useAdminTsAdmin } from "../composables/useAdminTsAdmin.js";
|
||||
import { splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import type { SiteLanguage } from "../../../src/site-copy.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
@@ -438,14 +447,19 @@ const emptyOverview = () => ({ gateway: { version: "", uptimeSeconds: 0 }, teamS
|
||||
const overview = reactive(emptyOverview());
|
||||
const webrtcPortNoticeOpen = ref(false);
|
||||
const serverSettings = useAdminServerSettings({ api: adminApi, errorMessage, errorText, refreshOverview: loadOverview });
|
||||
const { serverForm, loadServerSettings } = serverSettings;
|
||||
const { serverForm, savedSettings, loadServerSettings } = serverSettings;
|
||||
const savedTsTarget = computed(() => splitTeamSpeakTarget(savedSettings.value?.target));
|
||||
const initialSection = computed(() => typeof route.query.section === "string" ? route.query.section : undefined);
|
||||
const currentScope = computed(() => route.path === "/admin/ts-admin" ? tr("adminTsGroup") : tr("adminWsGroup"));
|
||||
const adminOperations = useAdminOperations({ api: adminApi, errorMessage, errorText, tr, refreshOverview: loadOverview });
|
||||
const { loadOperations } = adminOperations;
|
||||
const adminSkins = useAdminSkins({ api: adminApi, tr });
|
||||
const { loadSkinCatalog } = adminSkins;
|
||||
const adminTsAdmin = useAdminTsAdmin({ api: adminApi, errorMessage, errorText, tr });
|
||||
const { loadSettings: loadTsAdminSettings } = adminTsAdmin;
|
||||
|
||||
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : route.path === "/admin/skins" ? tr('skinLibrary') : tr('overview'));
|
||||
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('adminInstanceSettings') : route.path === "/admin/operations" ? tr('adminInstanceOperations') : route.path === "/admin/skins" ? tr('skinLibrary') : route.path === "/admin/ts-admin" ? tr('tsAdminTitle') : tr('overview'));
|
||||
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
|
||||
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
|
||||
|
||||
@@ -457,9 +471,11 @@ watch(() => route.path, (path, previous) => {
|
||||
if (previous === "/admin/server") serverSettings.cancelRequests();
|
||||
if (previous === "/admin/operations") adminOperations.cancelRequests();
|
||||
if (previous === "/admin/skins") adminSkins.cancelRequests();
|
||||
if (previous === "/admin/ts-admin") adminTsAdmin.cancelRequests();
|
||||
if (screen.value !== "admin" || loading.value || submitting.value || loggingOut.value) return;
|
||||
if (path === "/admin/operations") void loadOperations();
|
||||
else if (path === "/admin/skins") void loadSkinCatalog();
|
||||
else if (path === "/admin/ts-admin") void loadTsAdminSettings();
|
||||
else if (path === "/admin") void loadOverview();
|
||||
});
|
||||
|
||||
@@ -469,12 +485,13 @@ function cancelPendingWork() {
|
||||
serverSettings.cancelRequests();
|
||||
adminOperations.cancelRequests();
|
||||
adminSkins.cancelRequests();
|
||||
adminTsAdmin.cancelRequests();
|
||||
loading.value = false;
|
||||
submitting.value = false;
|
||||
loggingOut.value = false;
|
||||
}
|
||||
function resetPrivateState() {
|
||||
serverSettings.reset(); adminOperations.reset(); adminSkins.reset();
|
||||
serverSettings.reset(); adminOperations.reset(); adminSkins.reset(); adminTsAdmin.reset();
|
||||
Object.assign(overview, emptyOverview());
|
||||
loginPassword.value = ""; newPassword.value = ""; confirmNewPassword.value = "";
|
||||
errorMessage.value = "";
|
||||
@@ -488,6 +505,7 @@ async function loadAdminData(request: { isCurrent(): boolean }) {
|
||||
if (!request.isCurrent()) return;
|
||||
if (route.path === "/admin/operations") await loadOperations();
|
||||
else if (route.path === "/admin/skins") await loadSkinCatalog();
|
||||
else if (route.path === "/admin/ts-admin") await loadTsAdminSettings();
|
||||
}
|
||||
async function loadAdminView() {
|
||||
const request = pageRequests.begin("auth");
|
||||
|
||||
@@ -62,9 +62,11 @@ export function createVoiceConnection(options: ConnectionOptions) {
|
||||
options.onFailure(failure);
|
||||
}
|
||||
|
||||
function openSocket(record: Attempt, ticket: string): void {
|
||||
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const socket = new WebSocket(`${protocol}//${location.host}/ws/voice?ticket=${encodeURIComponent(ticket)}`);
|
||||
function openSocket(record: Attempt, ticket: string, voiceEndpoint?: string): void {
|
||||
let socketUrl: string;
|
||||
try { socketUrl = buildVoiceSocketUrl(ticket, voiceEndpoint); }
|
||||
catch (cause) { fail(record, { code: "VOICE_GATEWAY_UNAVAILABLE", cause }); return; }
|
||||
const socket = new WebSocket(socketUrl);
|
||||
record.socket = socket;
|
||||
socket.binaryType = "arraybuffer";
|
||||
options.onSocket(socket);
|
||||
@@ -112,7 +114,7 @@ export function createVoiceConnection(options: ConnectionOptions) {
|
||||
// TeamSpeak handshake, which has its own gateway connection policy.
|
||||
clearDeadline(record);
|
||||
record.controller = null;
|
||||
openSocket(record, result.ticket);
|
||||
openSocket(record, result.ticket, typeof result.voiceEndpoint === "string" ? result.voiceEndpoint : undefined);
|
||||
} catch (cause) {
|
||||
fail(record, { code: "REQUEST_FAILED", cause });
|
||||
}
|
||||
@@ -130,3 +132,16 @@ export function createVoiceConnection(options: ConnectionOptions) {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildVoiceSocketUrl(ticket: string, endpoint?: string): string {
|
||||
const securePage = location.protocol === "https:";
|
||||
const base = endpoint ? new URL(endpoint) : new URL(`${securePage ? "https:" : "http:"}//${location.host}`);
|
||||
if ((base.protocol !== "https:" && base.protocol !== "http:") || base.username || base.password
|
||||
|| base.pathname !== "/" || base.search || base.hash || securePage && base.protocol !== "https:") {
|
||||
throw new Error("Invalid voice gateway endpoint");
|
||||
}
|
||||
base.protocol = base.protocol === "https:" ? "wss:" : "ws:";
|
||||
base.pathname = "/ws/voice";
|
||||
base.search = `?ticket=${encodeURIComponent(ticket)}`;
|
||||
return base.toString();
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import { AdminSessionStore } from "../../src/admin/admin-session.js";
|
||||
import { createAdminRouter } from "../../src/admin/admin-router.js";
|
||||
import { createAdminApi } from "../src/services/admin-api.js";
|
||||
import { adminResponses } from "../../src/shared/admin-responses.js";
|
||||
import type { QueryClient, QueryClientOptions } from "@honeybbq/teamspeak/query";
|
||||
import { decryptSecret } from "../../src/security/secret-crypto.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
@@ -21,7 +23,7 @@ test("schema 7 upgrades preserve the previously unused public host and initializ
|
||||
const original = new WebSpeakDatabase(filename);
|
||||
original.close();
|
||||
const legacy = new DatabaseSync(filename);
|
||||
legacy.exec("ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; PRAGMA user_version = 7;");
|
||||
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; ALTER TABLE settings DROP COLUMN webrtc_ipv6_enabled; ALTER TABLE settings DROP COLUMN webrtc_stun_server; PRAGMA user_version = 7;");
|
||||
legacy.prepare("UPDATE settings SET webrtc_public_host = ?").run("media.example.com");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(filename);
|
||||
@@ -45,7 +47,34 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.ok(directory.includes("webspeak-admin-api-"));
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
const service = new AdminService(database, Buffer.alloc(32, 7), logger, join(directory, "absent-config.json"), undefined, "test-version");
|
||||
let mismatchHostKey = true;
|
||||
const queryFactory = (queryOptions: QueryClientOptions) => ({
|
||||
async connect() {
|
||||
if (queryOptions.transport.kind !== "ssh") throw new Error("expected SSH transport");
|
||||
queryOptions.transport.hostKey({
|
||||
host: "127.0.0.1", port: queryOptions.transport.port ?? 10022, keyType: "ssh-ed25519",
|
||||
key: new Uint8Array(), fingerprint: `SHA256:${(mismatchHostKey ? "B" : "A").repeat(43)}`,
|
||||
});
|
||||
},
|
||||
async disconnect() {},
|
||||
serverVersion: "6.0.0-beta-test",
|
||||
serverFamily: "ts6",
|
||||
async send(request: { command: string }) {
|
||||
if (request.command === "serverinfo") return [{ virtualserver_name: "Test TeamSpeak" }];
|
||||
if (request.command === "channellist") return [{
|
||||
cid: "1", cpid: "0", channel_name: "Lobby", channel_flag_password: "0", channel_flag_default: "1",
|
||||
channel_flag_permanent: "1", channel_flag_semi_permanent: "0", channel_codec: "4", channel_codec_quality: "6",
|
||||
channel_maxclients: "-1", channel_maxfamilyclients: "-1", total_clients: "1", total_clients_family: "1",
|
||||
channel_needed_talk_power: "0", channel_order: "0", channel_icon_id: "0",
|
||||
}];
|
||||
if (request.command === "clientlist") return [{
|
||||
clid: "42", client_nickname: "Guest", client_unique_identifier: "", cid: "1", client_type: "0",
|
||||
client_servergroups: "6,7", client_channel_group_id: "1", client_away: "0", client_is_recording: "0", client_is_talker: "0",
|
||||
}];
|
||||
throw new Error(`Unexpected ServerQuery command ${request.command}`);
|
||||
},
|
||||
}) as unknown as QueryClient;
|
||||
const service = new AdminService(database, Buffer.alloc(32, 7), logger, join(directory, "absent-config.json"), undefined, "test-version", queryFactory);
|
||||
await service.initialize();
|
||||
await service.changePassword("test-only-admin-password");
|
||||
const app = express();
|
||||
@@ -69,9 +98,15 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
return response;
|
||||
} });
|
||||
assert.equal((await api.session()).authenticated, false);
|
||||
const actionPath = `${origin}/api/admin/ts-admin/action`;
|
||||
assert.equal((await fetch(actionPath, { method: "POST", headers: { origin, "content-type": "application/json" }, body: '{}' })).status, 401);
|
||||
csrf = (await api.login("admin", "test-only-admin-password")).csrfToken;
|
||||
assert.equal((await api.session()).authenticated, true);
|
||||
assert.equal((await fetch(actionPath, { method: "POST", headers: { origin, cookie, "content-type": "application/json" }, body: '{}' })).status, 403);
|
||||
assert.equal((await fetch(actionPath, { method: "POST", headers: { origin: "https://untrusted.example", cookie, "x-csrf-token": csrf, "content-type": "application/json" }, body: '{}' })).status, 403);
|
||||
assert.equal((await api.overview()).gateway.version, "test-version");
|
||||
const tsAdminInitial = await api.tsAdminSettings();
|
||||
assert.deepEqual({ fixedMode: tsAdminInitial.fixedMode, enabled: tsAdminInitial.enabled, hasPassword: tsAdminInitial.hasPassword }, { fixedMode: true, enabled: false, hasPassword: false });
|
||||
const original = await api.settings();
|
||||
assert.equal(original.webRtcPublicHost, "");
|
||||
assert.equal(original.webRtcIpv6Enabled, false);
|
||||
@@ -105,6 +140,38 @@ test("browser admin API consumes the actual HTTP router and preserves keep/repla
|
||||
assert.equal(saved.settings.relayNodes[0].hasToken, passwordAction !== "remove");
|
||||
assert.equal(service.getAccelerationRelayOptions()[0]?.token, passwordAction === "remove" ? undefined : "test-relay-token");
|
||||
}
|
||||
const verifiedFingerprint = `SHA256:${"A".repeat(43)}`;
|
||||
const tsAdminSaved = await api.saveTsAdminSettings({
|
||||
enabled: true, transport: "ssh", queryPort: 10022, username: "query-admin", passwordAction: "replace",
|
||||
password: "query-secret-test", hostKeyFingerprint: verifiedFingerprint,
|
||||
});
|
||||
assert.equal(tsAdminSaved.settings.hasPassword, true);
|
||||
assert.equal(tsAdminSaved.settings.hostKeyFingerprint, verifiedFingerprint);
|
||||
assert.equal(JSON.stringify(tsAdminSaved).includes("query-secret-test"), false);
|
||||
assert.notEqual(database.getTsAdminSettings().passwordEncrypted, "query-secret-test");
|
||||
assert.equal(decryptSecret(database.getTsAdminSettings().passwordEncrypted, Buffer.alloc(32, 7), "webspeak:ts-admin-query-password:v1"), "query-secret-test");
|
||||
assert.throws(() => decryptSecret(database.getTsAdminSettings().passwordEncrypted, Buffer.alloc(32, 7)));
|
||||
assert.deepEqual(adminResponses.tsAdminSettings({ ...service.getTsAdminSettings(), password: "query-secret-test" }), service.getTsAdminSettings());
|
||||
await assert.rejects(api.tsAdminOverview(), (error: any) => error.code === "TS_ADMIN_HOST_KEY_MISMATCH");
|
||||
mismatchHostKey = false;
|
||||
const tsAdminOverview = await api.tsAdminOverview();
|
||||
assert.equal(tsAdminOverview.serverName, "Test TeamSpeak");
|
||||
assert.equal(tsAdminOverview.serverFamily, "ts6");
|
||||
assert.equal(tsAdminOverview.channels[0].name, "Lobby");
|
||||
assert.equal(tsAdminOverview.clients[0].nickname, "Guest");
|
||||
assert.deepEqual(tsAdminOverview.clients[0].serverGroups, ["6", "7"]);
|
||||
await assert.rejects(api.tsAdminAction({ configurationRevision: tsAdminOverview.configurationRevision, operation: { action: "channel.delete", channelId: "0" } }), (error: any) => error.code === "INVALID_TS_ADMIN_ACTION");
|
||||
await assert.rejects(api.tsAdminAction({ configurationRevision: tsAdminOverview.configurationRevision, operation: { action: "client.kick", clientId: 42, clientUid: "stale", reason: "" } }), (error: any) => error.code === "TS_ADMIN_CLIENT_CHANGED");
|
||||
mismatchHostKey = true;
|
||||
await assert.rejects(api.tsAdminOverview(), (error: any) => error.code === "TS_ADMIN_HOST_KEY_MISMATCH");
|
||||
assert.equal((await api.overview()).gateway.version, "test-version", "WebSpeak management does not depend on TS management connectivity");
|
||||
assert.equal((await api.settings()).accessMode, "fixed");
|
||||
const settingsWithOpenMode = service.getAdminSettings();
|
||||
await api.saveSettings({ ...settingsWithOpenMode, accessMode: "open" });
|
||||
assert.equal((await api.tsAdminSettings()).fixedMode, false);
|
||||
assert.equal((await api.tsAdminSettings()).enabled, false, "switching to open mode disables the TeamSpeak admin panel");
|
||||
await assert.rejects(api.tsAdminOverview(), (error: any) => error.code === "TS_ADMIN_FIXED_MODE_REQUIRED");
|
||||
await assert.rejects(api.saveTsAdminSettings({ enabled: true, queryPort: 10022, username: "query-admin", hostKeyFingerprint: verifiedFingerprint }), (error: any) => error.code === "TS_ADMIN_FIXED_MODE_REQUIRED");
|
||||
const settings = service.getAdminSettings();
|
||||
assert.deepEqual(adminResponses.settings({ ...settings, passwordAction: "remove", serverPassword: "injected" }), settings);
|
||||
const created = await api.createInvite({ channel: "Lobby", expiresInHours: 1, maxUses: 1 });
|
||||
|
||||
@@ -34,12 +34,20 @@ const overview = { gateway: { status: "running", version: "test", uptimeSeconds:
|
||||
teamSpeak: { target: "voice.example:9987", status: "unknown", lastTestAt: null, latencyMs: null, lastError: null },
|
||||
sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [], legacyConfigImported: false };
|
||||
const session = nickname => ({ id: nickname, nickname, target: "voice.example:9987", state: "connected", createdAt: "2026-10-01T00:00:00Z", ageSeconds: 0, tsClientId: 1, channelId: "1", memberCount: 1 });
|
||||
const tsSettings = (extra = {}) => ({ enabled: true, fixedMode: true, transport: "web", queryHost: "", webQueryUrl: "https://query.example", serverId: 1,
|
||||
configurationRevision: "reviewed-configuration",
|
||||
queryPort: 10022, username: "", hasPassword: false, hasApiKey: true, hostKeyFingerprint: "", updatedAt: "2026-10-01T00:00:00Z", ...extra });
|
||||
const tsOverview = () => ({ configurationRevision: "reviewed-configuration", serverName: "TS fixture", serverVersion: "6.0.0", serverFamily: "ts6", welcomeMessage: "Welcome", maxClients: 32, uptimeSeconds: 1,
|
||||
channelCount: 1, clientCount: 1, channels: [{ id: "1", parentID: "0", name: "Lobby", description: "", totalClients: 1, hasPassword: false }],
|
||||
clients: [{ id: 42, uid: "selected-uid", nickname: "Selected user", channelID: "1", serverGroups: ["6"], away: false, inputMuted: false, outputMuted: false }],
|
||||
groups: [{ id: "6", name: "Member" }], bans: [], groupsAvailable: true, bansAvailable: true, observedAt: "2026-10-01T00:00:00Z" });
|
||||
const defaults = path => ({
|
||||
"/session": { authenticated: true, mustChangePassword: false, csrfToken: "test-csrf" },
|
||||
"/server": settings(), "/overview": overview, "/sessions": { sessions: [] }, "/invites": { invites: [] },
|
||||
"/diagnostics": { gateway: { version: "test", node: "test", platform: "test", arch: "test" }, database: { schemaVersion: 1 }, sessions: { created: 0 } },
|
||||
"/logs?limit=100": { available: false, entries: [], sessions: [] }, "/audit?limit=50": { events: [] },
|
||||
"/skins": { skins: [], defaultSkinId: "builtin.light" },
|
||||
"/ts-admin/settings": tsSettings(), "/ts-admin/overview": tsOverview(),
|
||||
})[path];
|
||||
|
||||
before(async () => {
|
||||
@@ -385,6 +393,75 @@ test("skin mutations are serialized and failure restores the last saved default"
|
||||
assert.ok(skinsModel.skinManagerError);
|
||||
});
|
||||
|
||||
const storeFixture = () => ({ repository: "https://github.com/Huddle-Up-Forge/webspeak-skins", appVersion: "0.2.8", fetchedAt: 1,
|
||||
entries: [{ id: "store-test", repository: "https://github.com/example/skin", revision: "a".repeat(64), compatible: true, error: null,
|
||||
metadata: { schemaVersion: 1, id: "store-test", name: "Fixture", version: "1.0.0", author: "Fixture", license: "MIT", description: "Fixture", minAppVersion: "0.2.8", package: { path: "skin.wskin", ref: "v1.0.0", sha256: "b".repeat(64) } } }] });
|
||||
|
||||
test("skin store is loaded lazily and a failed refresh preserves its previous catalog", async () => {
|
||||
let reads = 0;
|
||||
handler = path => path === "/skin-store" ? (++reads, Promise.resolve(json(storeFixture()))) : Promise.resolve(json(defaults(path)));
|
||||
await mount("/admin/skins");
|
||||
assert.equal(reads, 0);
|
||||
skinsModel.selectSkinTab("store"); await nextTurn();
|
||||
assert.equal(reads, 1);
|
||||
assert.equal(skinsModel.storeCatalog.entries[0].id, "store-test");
|
||||
handler = path => Promise.resolve(json(path === "/skin-store/refresh" ? { code: "SKIN_STORE_UNAVAILABLE" } : defaults(path), path === "/skin-store/refresh" ? 502 : 200));
|
||||
await skinsModel.loadSkinStore(true);
|
||||
assert.equal(skinsModel.storeCatalog.entries.length, 1);
|
||||
assert.ok(skinsModel.storeError);
|
||||
});
|
||||
|
||||
test("leaving skins discards a late store catalog and logout clears store state", async () => {
|
||||
await mount("/admin/skins");
|
||||
const catalog = deferred();
|
||||
handler = path => path === "/skin-store" ? catalog.promise : Promise.resolve(json(defaults(path)));
|
||||
const pending = skinsModel.loadSkinStore();
|
||||
await router.push("/admin/server"); await nextTurn();
|
||||
catalog.resolve(json(storeFixture())); await pending;
|
||||
assert.equal(skinsModel.storeCatalog, null);
|
||||
assert.equal(skinsModel.storeLoading, false);
|
||||
skinsModel.storeCatalog = storeFixture();
|
||||
skinsModel.reset();
|
||||
assert.equal(skinsModel.storeCatalog, null);
|
||||
});
|
||||
|
||||
test("refreshing the store also reloads packages changed by another administrator", async () => {
|
||||
await mount("/admin/skins");
|
||||
handler = path => Promise.resolve(json(path === "/skin-store/refresh" ? storeFixture()
|
||||
: path === "/skins" ? { skins: [{ ...manifestForStoreTest(), version: "1.1.0", enabled: false }], defaultSkinId: "builtin.light" } : defaults(path)));
|
||||
await skinsModel.loadSkinStore(true);
|
||||
assert.equal(skinsModel.skinEntries.find(skin => skin.id === "store-test").version, "1.1.0");
|
||||
assert.equal(skinsModel.installedStoreSkin(storeFixture().entries[0]).enabled, false);
|
||||
assert.equal(skinsModel.storeVersionOrder(storeFixture().entries[0]), -1);
|
||||
});
|
||||
|
||||
test("store install submits the reviewed revision once and reloads the instance catalog", async () => {
|
||||
await mount("/admin/skins");
|
||||
const install = deferred(); let writes = 0, submitted;
|
||||
handler = (path, init) => path === "/skin-store/install" ? (++writes, submitted = JSON.parse(init.body), install.promise) : Promise.resolve(json(defaults(path)));
|
||||
const entry = storeFixture().entries[0];
|
||||
const pending = skinsModel.installStoreSkin(entry);
|
||||
await skinsModel.installStoreSkin(entry);
|
||||
await skinsModel.saveSkinDefault();
|
||||
assert.equal(writes, 1);
|
||||
assert.deepEqual(submitted, { id: entry.id, revision: entry.revision, installedVersion: null });
|
||||
assert.equal(skinsModel.skinBusy, true);
|
||||
install.resolve(json({ ok: true, skin: { ...manifestForStoreTest(), enabled: true } }));
|
||||
await pending;
|
||||
assert.equal(skinsModel.skinBusy, false);
|
||||
assert.ok(skinsModel.skinManagerNotice);
|
||||
});
|
||||
function manifestForStoreTest() { return { id: "store-test", name: "Fixture", version: "1.0.0", author: "Fixture", license: "MIT", minAppVersion: "0.2.8", installedAt: 1 }; }
|
||||
|
||||
test("all store translations are explicit in each supported language", async () => {
|
||||
const { skinStoreCopy } = await vite.ssrLoadModule("/src/i18n/skin-store.ts");
|
||||
const keys = Object.keys(skinStoreCopy.zh).sort();
|
||||
for (const language of ["en", "de", "ru", "ja"]) {
|
||||
assert.deepEqual(Object.keys(skinStoreCopy[language]).sort(), keys);
|
||||
for (const key of keys) assert.ok(skinStoreCopy[language][key].trim());
|
||||
}
|
||||
});
|
||||
|
||||
test("a settings response cannot restore probe metadata after the draft password changes", async () => {
|
||||
await mount();
|
||||
const save = deferred();
|
||||
@@ -422,3 +499,219 @@ test("duplicate invite revocation sends one mutation", async () => {
|
||||
await Promise.all([pending, duplicate]);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("TS management saves keep newer credential edits and invalidate pending overview reads", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin), oldOverview = deferred(), save = deferred();
|
||||
handler = (path, init) => path === "/ts-admin/overview" ? oldOverview.promise : path === "/ts-admin/settings" && init.method === "PUT" ? save.promise : Promise.resolve(json(defaults(path)));
|
||||
const reading = model.connectAndRefresh();
|
||||
model.form.apiKeyAction = "replace"; model.form.apiKey = "submitted-key";
|
||||
const saving = model.saveSettings();
|
||||
model.form.apiKey = "newer-draft-key";
|
||||
save.resolve(json({ ok: true, settings: tsSettings({ hasApiKey: true }) }));
|
||||
await saving;
|
||||
oldOverview.resolve(json(tsOverview())); await reading;
|
||||
assert.equal(model.form.apiKey, "newer-draft-key");
|
||||
assert.equal(model.form.apiKeyAction, "replace");
|
||||
assert.equal(model.overview, null);
|
||||
assert.equal(model.connecting, false); assert.equal(model.saving, false);
|
||||
handler = () => Promise.resolve(json({ ok: true, settings: tsSettings({ hasApiKey: true }) }));
|
||||
await model.saveSettings();
|
||||
assert.equal(model.form.apiKey, ""); assert.equal(model.form.apiKeyAction, "keep");
|
||||
});
|
||||
|
||||
test("TS mutations send the selected UID once and a failed refresh never retries a completed write", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin);
|
||||
await model.connectAndRefresh();
|
||||
model.beginAction("client.kick", model.overview.clients[0]);
|
||||
model.editor.reason = "Test reason";
|
||||
const response = deferred(); let writes = 0;
|
||||
handler = (path, init) => {
|
||||
if (path === "/ts-admin/action") {
|
||||
writes++;
|
||||
assert.deepEqual(JSON.parse(init.body), { configurationRevision: "reviewed-configuration", operation: { action: "client.kick", clientId: 42, clientUid: "selected-uid", reason: "Test reason" } });
|
||||
return response.promise;
|
||||
}
|
||||
if (path === "/ts-admin/overview") return Promise.resolve(json({ code: "TS_ADMIN_CONNECTION_FAILED" }, 400));
|
||||
return Promise.resolve(json(defaults(path)));
|
||||
};
|
||||
const pending = model.runAction(); await model.runAction();
|
||||
response.resolve(json({ ok: true })); await pending;
|
||||
assert.equal(writes, 1); assert.equal(model.acting, false); assert.equal(model.editor.action, "");
|
||||
assert.ok(model.noticeMessage); assert.ok(state.errorMessage);
|
||||
assert.equal(model.overview, null);
|
||||
});
|
||||
|
||||
test("leaving TS management discards a late response and logout clears saved credential drafts", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin), read = deferred();
|
||||
handler = path => path === "/ts-admin/overview" ? read.promise : Promise.resolve(json(path === "/logout" ? { ok: true } : defaults(path)));
|
||||
const pending = model.connectAndRefresh();
|
||||
await router.push("/admin"); await nextTurn();
|
||||
read.resolve(json(tsOverview())); await pending;
|
||||
assert.equal(model.overview, null); assert.equal(model.connecting, false);
|
||||
model.form.apiKey = "private-key-draft"; model.form.password = "private-password-draft";
|
||||
await state.logout();
|
||||
assert.equal(model.form.apiKey, ""); assert.equal(model.form.password, ""); assert.equal(model.settings.hasApiKey, false);
|
||||
});
|
||||
|
||||
test("TS administration actually renders transport forms, operations and all five translations", async () => {
|
||||
const { createSSRApp } = await import("vue");
|
||||
const { renderToString } = await import("vue/server-renderer");
|
||||
const { default: Component } = await vite.ssrLoadModule("/src/components/admin/AdminTsAdmin.vue");
|
||||
await mount("/admin/ts-admin");
|
||||
const model = state.adminTsAdmin, readable = reactive(model);
|
||||
await readable.connectAndRefresh();
|
||||
for (const language of ["zh", "en", "de", "ru", "ja"]) {
|
||||
state.language = language;
|
||||
const html = await renderToString(createSSRApp(Component, { model, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
|
||||
assert.ok(html.includes("WebQuery")); assert.ok(html.includes("https://query.example"));
|
||||
assert.ok(html.includes("Selected user")); assert.ok(html.includes("Lobby"));
|
||||
assert.ok(!html.includes("undefined"));
|
||||
}
|
||||
readable.form.transport = "ssh";
|
||||
let html = await renderToString(createSSRApp(Component, { model, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
|
||||
assert.ok(html.includes("SHA256:")); assert.ok(!html.includes('type="url"'));
|
||||
readable.form.transport = "web";
|
||||
await nextTurn();
|
||||
readable.beginAction("client.move", readable.overview.clients[0]);
|
||||
html = await renderToString(createSSRApp(Component, { model, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
|
||||
assert.ok(html.includes('class="operation-card ts-admin-editor"')); assert.ok(html.includes("Selected user"));
|
||||
});
|
||||
|
||||
|
||||
test("WebSpeak routes work in open and fixed modes without any TS management request", async () => {
|
||||
for (const accessMode of ["open", "fixed"]) {
|
||||
const paths = [];
|
||||
handler = (path, init) => {
|
||||
paths.push(path);
|
||||
assert.ok(!path.startsWith("/ts-admin/"), "WebSpeak pages must not depend on Query availability");
|
||||
return Promise.resolve(json(path === "/server" ? init.method === "PUT" ? { ok: true, settings: settings({ accessMode }) } : settings({ accessMode }) : defaults(path)));
|
||||
};
|
||||
await mount("/admin");
|
||||
for (const route of ["/admin/server", "/admin/operations", "/admin/skins", "/admin"]) {
|
||||
await router.push(route); await nextTurn();
|
||||
}
|
||||
serverModel.serverForm.siteName = "Saved without Query";
|
||||
await serverModel.saveServerSettings();
|
||||
assert.equal(state.errorMessage, "");
|
||||
assert.ok(paths.includes("/sessions")); assert.ok(paths.includes("/skins"));
|
||||
app.unmount(); app = null;
|
||||
}
|
||||
});
|
||||
|
||||
test("TS target presentation uses saved settings rather than an unsaved WebSpeak draft", async () => {
|
||||
await mount("/admin/server");
|
||||
serverModel.serverForm.address = "unsaved.example";
|
||||
serverModel.serverForm.port = "9999";
|
||||
serverModel.serverForm.accessMode = "open";
|
||||
await router.push("/admin/ts-admin"); await nextTurn();
|
||||
assert.deepEqual(state.savedTsTarget, { address: "voice.example", port: "9987" });
|
||||
assert.equal(serverModel.savedSettings.accessMode, "fixed");
|
||||
assert.equal(serverModel.serverForm.address, "unsaved.example");
|
||||
handler = (path, init) => Promise.resolve(json(path === "/server" && init.method === "PUT"
|
||||
? { ok: true, settings: settings({ target: "new-saved.example:9990", accessMode: "open" }) } : defaults(path)));
|
||||
await serverModel.saveServerSettings();
|
||||
assert.deepEqual(state.savedTsTarget, { address: "new-saved.example", port: "9990" });
|
||||
assert.equal(serverModel.savedSettings.accessMode, "open");
|
||||
serverModel.reset();
|
||||
assert.equal(serverModel.savedSettings, null);
|
||||
});
|
||||
|
||||
test("TS management is optional and opening its page never connects automatically", async () => {
|
||||
const paths = [];
|
||||
handler = path => {
|
||||
paths.push(path);
|
||||
assert.notEqual(path, "/ts-admin/overview");
|
||||
return Promise.resolve(json(path === "/ts-admin/settings" ? tsSettings({ enabled: false }) : defaults(path)));
|
||||
};
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin);
|
||||
assert.ok(paths.includes("/ts-admin/settings"));
|
||||
await model.connectAndRefresh();
|
||||
assert.equal(model.overview, null);
|
||||
await router.push("/admin/operations"); await nextTurn();
|
||||
assert.equal(state.errorMessage, "");
|
||||
});
|
||||
|
||||
test("unsaved TS connection changes block both reads and writes until saved", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin);
|
||||
await model.connectAndRefresh();
|
||||
model.beginAction("client.kick", model.overview.clients[0]);
|
||||
model.form.webQueryUrl = "https://replacement.example";
|
||||
let calls = 0;
|
||||
handler = (path, init) => { calls++; return Promise.resolve(json(path === "/ts-admin/settings" && init.method === "PUT"
|
||||
? { ok: true, settings: tsSettings({ webQueryUrl: "https://replacement.example", configurationRevision: "replacement" }) } : defaults(path))); };
|
||||
assert.equal(model.settingsDirty, true);
|
||||
await model.connectAndRefresh(); await model.runAction();
|
||||
assert.equal(calls, 0);
|
||||
await model.saveSettings();
|
||||
assert.equal(calls, 1); assert.equal(model.settingsDirty, false);
|
||||
assert.equal(model.overview, null); assert.equal(model.editor.action, "");
|
||||
});
|
||||
|
||||
test("a changed saved TS connection discards an old overview and pending read", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin), oldRead = deferred();
|
||||
await model.connectAndRefresh(); model.beginAction("channel.update", model.overview.channels[0]);
|
||||
handler = path => path === "/ts-admin/overview" ? oldRead.promise : Promise.resolve(json(tsSettings({ configurationRevision: "new-connection" })));
|
||||
const pending = model.connectAndRefresh();
|
||||
await model.loadSettings();
|
||||
assert.equal(model.overview, null); assert.equal(model.editor.action, "");
|
||||
oldRead.resolve(json(tsOverview())); await pending;
|
||||
assert.equal(model.overview, null); assert.equal(model.connecting, false);
|
||||
});
|
||||
|
||||
test("settings and operations render explicit localized sections with valid deep links", async () => {
|
||||
const { createSSRApp } = await import("vue");
|
||||
const { renderToString } = await import("vue/server-renderer");
|
||||
const { default: Settings } = await vite.ssrLoadModule("/src/components/admin/AdminServerSettings.vue");
|
||||
const { default: Operations } = await vite.ssrLoadModule("/src/components/admin/AdminOperations.vue");
|
||||
const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
|
||||
await mount("/admin/server?section=site");
|
||||
assert.equal(state.initialSection, "site");
|
||||
for (const language of ["zh", "en", "de", "ru", "ja"]) {
|
||||
state.language = language;
|
||||
const translations = adminOrganizationCopy[language];
|
||||
assert.deepEqual(Object.keys(translations).sort(), Object.keys(adminOrganizationCopy.zh).sort());
|
||||
const settingsHtml = await renderToString(createSSRApp(Settings, { model: state.serverSettings, i18n: state.i18n, initialSection: "site", welcomeLanguage: "zh" }));
|
||||
assert.ok(settingsHtml.includes(translations.adminSiteAnnouncement));
|
||||
assert.ok(settingsHtml.includes('data-admin-section="site"'));
|
||||
assert.ok(!settingsHtml.includes("undefined"));
|
||||
const operationsHtml = await renderToString(createSSRApp(Operations, { model: state.adminOperations, i18n: state.i18n, initialSection: "maintenance" }));
|
||||
assert.ok(operationsHtml.includes(translations.adminBrowserSessionsLead));
|
||||
assert.ok(operationsHtml.includes('data-admin-section="maintenance"'));
|
||||
assert.ok(!operationsHtml.includes("undefined"));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test("loading saved custom Query ports never treats them as unsaved transport defaults", async () => {
|
||||
for (const [transport, queryPort] of [["ssh", 10011], ["tcp", 10022]]) {
|
||||
handler = path => Promise.resolve(json(path === "/ts-admin/settings" ? tsSettings({ transport, queryPort, username: "serveradmin", hasPassword: true }) : defaults(path)));
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin);
|
||||
assert.equal(model.form.queryPort, String(queryPort));
|
||||
assert.equal(model.settingsDirty, false);
|
||||
await model.connectAndRefresh();
|
||||
assert.ok(model.overview);
|
||||
app.unmount(); app = null;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test("a pending TS settings load preserves the port selected for a newer transport draft", async () => {
|
||||
await mount("/admin/ts-admin");
|
||||
const model = reactive(state.adminTsAdmin), read = deferred();
|
||||
handler = () => read.promise;
|
||||
const pending = model.loadSettings();
|
||||
model.form.transport = "ssh";
|
||||
read.resolve(json(tsSettings({ queryPort: 10011 })));
|
||||
await pending;
|
||||
assert.equal(model.settings.queryPort, 10011);
|
||||
assert.equal(model.form.transport, "ssh");
|
||||
assert.equal(model.form.queryPort, "10022");
|
||||
assert.equal(model.settingsDirty, true);
|
||||
});
|
||||
@@ -48,6 +48,8 @@ test("screen-share player fills the content width, limits height, and letterboxe
|
||||
const playerRule = css.match(/:deep\(\.screen-share-player\)\s*\{([^}]*)\}/)?.[1] ?? "";
|
||||
const stageRule = css.match(/:deep\(\.screen-share-player-stage\)\s*\{([^}]*)\}/)?.[1] ?? "";
|
||||
const videoRule = css.match(/:deep\(\.screen-share-player-video\)\s*\{([^}]*)\}/)?.[1] ?? "";
|
||||
const fullscreenRule = css.match(/:deep\(\.screen-share-player:fullscreen\)\s*\{([^}]*)\}/)?.[1] ?? "";
|
||||
const fullscreenStageRule = css.match(/:deep\(\.screen-share-player:fullscreen \.screen-share-player-stage\)\s*\{([^}]*)\}/)?.[1] ?? "";
|
||||
assert.match(playerRule, /width:\s*100%/);
|
||||
assert.doesNotMatch(playerRule, /width:\s*fit-content/);
|
||||
assert.match(stageRule, /width:\s*100%/);
|
||||
@@ -55,6 +57,14 @@ test("screen-share player fills the content width, limits height, and letterboxe
|
||||
assert.match(stageRule, /background:\s*#000/);
|
||||
assert.match(videoRule, /object-fit:\s*contain/);
|
||||
assert.match(videoRule, /background:\s*#000/);
|
||||
assert.match(fullscreenRule, /position:\s*fixed/);
|
||||
assert.match(fullscreenRule, /inset:\s*0/);
|
||||
assert.match(fullscreenRule, /height:\s*100dvh/);
|
||||
assert.match(fullscreenRule, /background:\s*#000/);
|
||||
assert.match(fullscreenStageRule, /height:\s*100%/);
|
||||
assert.match(fullscreenStageRule, /min-height:\s*0/);
|
||||
assert.match(component, /document\.addEventListener\("fullscreenchange", updateStageSize\)/);
|
||||
assert.match(component, /document\.fullscreenElement === player/);
|
||||
assert.doesNotMatch(component, /video\.video(?:Width|Height)/, "source dimensions must not resize the player stage");
|
||||
assert.doesNotMatch(component, /ResizeObserver/, "player sizing must not create a resize-feedback loop while video starts");
|
||||
assert.match(component, /if \(playerElement\.value === next\) return;/, "stable function refs must not rewrite player styles on every render");
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import test from "node:test";
|
||||
import express from "express";
|
||||
import { zipSync, strToU8 } from "fflate";
|
||||
import { SkinRegistry, SkinRegistryError } from "../../src/admin/skin-registry.js";
|
||||
import { SkinStore } from "../../src/admin/skin-store.js";
|
||||
import { createAdminRouter } from "../../src/admin/admin-router.js";
|
||||
import { AdminSessionStore } from "../../src/admin/admin-session.js";
|
||||
import type { AdminService } from "../../src/admin/admin-service.js";
|
||||
import type { Logger } from "../../src/logger.js";
|
||||
import { SKIN_STORE_INDEX_URL, compareSkinVersions } from "../../src/shared/skin-store.js";
|
||||
import { createAdminApi } from "../src/services/admin-api.js";
|
||||
|
||||
const repository = "https://github.com/example/skin";
|
||||
const raw = "https://raw.githubusercontent.com/example/skin";
|
||||
const manifest = { schemaVersion: 1, id: "community.store-test", name: "Store fixture", version: "1.0.0", author: "Fixture", license: "MIT", minAppVersion: "0.2.8", entry: "skin.css" };
|
||||
function fixture() {
|
||||
let version = "1.0.0";
|
||||
const archive = () => Buffer.from(zipSync({ "manifest.json": strToU8(JSON.stringify({ ...manifest, version })), "skin.css": strToU8('[data-ws-part="voice.member"] { color: teal; }') }));
|
||||
const metadata = () => ({ ...manifest, version, description: "Fixture description", package: { ref: `v${version}`, path: "skin.wskin", sha256: createHash("sha256").update(archive()).digest("hex") } });
|
||||
const index = { schemaVersion: 1, skins: [{ id: manifest.id, repository }] };
|
||||
const overrides = new Map<string, () => Response>();
|
||||
const calls: string[] = [];
|
||||
const fetcher: typeof fetch = async (url, init) => {
|
||||
const path = String(url); calls.push(path);
|
||||
assert.equal(init?.redirect, "error");
|
||||
assert.equal(init?.credentials, "omit");
|
||||
if (overrides.has(path)) return overrides.get(path)!();
|
||||
if (path === SKIN_STORE_INDEX_URL) return Response.json(index);
|
||||
if (path === `${raw}/HEAD/skin.json`) return Response.json(metadata());
|
||||
if (path === `${raw}/v${version}/skin.wskin`) return new Response(archive());
|
||||
throw new Error("Unexpected outbound URL");
|
||||
};
|
||||
return { archive, metadata, index, calls, overrides, fetcher, setVersion(value: string) { version = value; } };
|
||||
}
|
||||
const errorCode = (expected: string) => (error: unknown) => error instanceof SkinRegistryError && error.code === expected;
|
||||
async function registry(t: test.TestContext) {
|
||||
const directory = await mkdtemp(join(tmpdir(), "webspeak-store-test-"));
|
||||
t.after(async () => {
|
||||
assert.equal(dirname(resolve(directory)), resolve(tmpdir()));
|
||||
assert.ok(directory.includes("webspeak-store-test-"));
|
||||
await rm(directory, { force: true, recursive: true });
|
||||
});
|
||||
return new SkinRegistry(directory);
|
||||
}
|
||||
test("store installs exact verified packages and preserves enabled/default state on update", async t => {
|
||||
const f = fixture(), store = new SkinStore("0.2.8", f.fetcher), skins = await registry(t);
|
||||
const entry = (await store.list()).entries[0];
|
||||
assert.equal(entry.compatible, true);
|
||||
const input = { id: entry.id, revision: entry.revision, installedVersion: null };
|
||||
await store.install(skins, input);
|
||||
assert.deepEqual(await skins.readArchive(entry.id), f.archive());
|
||||
await skins.setDefaultSkin(entry.id);
|
||||
f.setVersion("1.1.0");
|
||||
const updated = (await store.list(true)).entries[0];
|
||||
await store.install(skins, { ...input, revision: updated.revision, installedVersion: "1.0.0" });
|
||||
assert.equal(await skins.getDefaultSkinId(), entry.id);
|
||||
await skins.setEnabled(entry.id, false);
|
||||
f.setVersion("1.2.0");
|
||||
const next = (await store.list(true)).entries[0];
|
||||
await store.install(skins, { ...input, revision: next.revision, installedVersion: "1.1.0" });
|
||||
assert.equal((await skins.list())[0].enabled, false);
|
||||
assert.equal(await skins.getDefaultSkinId(), "builtin.light");
|
||||
});
|
||||
test("store blocks changed catalogs, concurrent replacements, downgrades and incompatible apps", async t => {
|
||||
const f = fixture(), store = new SkinStore("0.2.8", f.fetcher), skins = await registry(t);
|
||||
const entry = (await store.list()).entries[0];
|
||||
const input = { id: entry.id, revision: entry.revision, installedVersion: null };
|
||||
f.setVersion("1.1.0");
|
||||
await assert.rejects(store.install(skins, input), errorCode("SKIN_STORE_CHANGED"));
|
||||
f.setVersion("1.0.0");
|
||||
await skins.save(f.archive(), entry.id);
|
||||
await assert.rejects(store.install(skins, input), errorCode("SKIN_STORE_INSTALLED_CHANGED"));
|
||||
await assert.rejects(store.install(skins, { ...input, installedVersion: "1.0.0" }), errorCode("SKIN_STORE_NOT_NEWER"));
|
||||
const old = new SkinStore("0.2.7", f.fetcher);
|
||||
assert.equal((await old.list()).entries[0].compatible, false);
|
||||
await assert.rejects(old.install(skins, input), errorCode("SKIN_STORE_INCOMPATIBLE"));
|
||||
assert.equal((await skins.list())[0].version, "1.0.0");
|
||||
});
|
||||
test("store rejects unsafe repositories, malformed/duplicate indexes and isolates a failed repository", async () => {
|
||||
for (const unsafe of ["http://github.com/a/b", "https://github.com.evil/a/b", "https://github.com/a/b?url=http://127.0.0.1", "https://user:pass@github.com/a/b", "https://github.com/a/..", "https://127.0.0.1/a/b"]) {
|
||||
const f = fixture(); f.index.skins[0].repository = unsafe;
|
||||
await assert.rejects(new SkinStore("0.2.8", f.fetcher).list(), errorCode("SKIN_STORE_INVALID"));
|
||||
assert.deepEqual(f.calls, [SKIN_STORE_INDEX_URL]);
|
||||
}
|
||||
const f = fixture(); f.index.skins.push({ ...f.index.skins[0] });
|
||||
await assert.rejects(new SkinStore("0.2.8", f.fetcher).list(), errorCode("SKIN_STORE_INVALID"));
|
||||
f.index.skins.pop();
|
||||
f.overrides.set(`${raw}/HEAD/skin.json`, () => new Response(null, { status: 404 }));
|
||||
const result = await new SkinStore("0.2.8", f.fetcher).list();
|
||||
assert.equal(result.entries[0].metadata, null);
|
||||
assert.equal(result.entries[0].error, "SKIN_STORE_UNAVAILABLE");
|
||||
});
|
||||
test("store bounds downloads and validates checksum, package identity and metadata before saving", async t => {
|
||||
const f = fixture(), store = new SkinStore("0.2.8", f.fetcher), skins = await registry(t);
|
||||
const entry = (await store.list()).entries[0], input = { id: entry.id, revision: entry.revision, installedVersion: null };
|
||||
const packageUrl = `${raw}/v1.0.0/skin.wskin`;
|
||||
f.overrides.set(packageUrl, () => new Response("wrong bytes"));
|
||||
await assert.rejects(store.install(skins, input), errorCode("SKIN_STORE_CHECKSUM"));
|
||||
f.overrides.set(packageUrl, () => new Response("x", { headers: { "content-length": String(21 * 1024 * 1024) } }));
|
||||
await assert.rejects(store.install(skins, input), errorCode("SKIN_STORE_TOO_LARGE"));
|
||||
f.overrides.delete(packageUrl);
|
||||
f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ ...f.metadata(), name: "Different display name" }));
|
||||
const mismatch = (await store.list(true)).entries[0];
|
||||
await assert.rejects(store.install(skins, { ...input, revision: mismatch.revision }), errorCode("SKIN_STORE_PACKAGE_MISMATCH"));
|
||||
f.overrides.set(`${raw}/HEAD/skin.json`, () => Response.json({ ...f.metadata(), package: { ...f.metadata().package, path: "../private.wskin" } }));
|
||||
assert.equal((await store.list(true)).entries[0].error, "SKIN_STORE_INVALID");
|
||||
assert.deepEqual(await skins.list(), []);
|
||||
f.overrides.set(SKIN_STORE_INDEX_URL, () => new Response("x".repeat(129 * 1024)));
|
||||
await assert.rejects(store.list(true), errorCode("SKIN_STORE_TOO_LARGE"));
|
||||
});
|
||||
test("catalog reads coalesce/cache and a failed refresh cannot erase the cached catalog", async () => {
|
||||
const f = fixture(), store = new SkinStore("0.2.8", f.fetcher);
|
||||
await Promise.all([store.list(), store.list()]);
|
||||
await store.list();
|
||||
assert.equal(f.calls.filter(url => url === SKIN_STORE_INDEX_URL).length, 1);
|
||||
f.overrides.set(SKIN_STORE_INDEX_URL, () => new Response(null, { status: 503 }));
|
||||
await assert.rejects(store.list(true), errorCode("SKIN_STORE_UNAVAILABLE"));
|
||||
assert.equal((await store.list()).entries.length, 1);
|
||||
});
|
||||
test("semantic versions handle prereleases, build metadata and multi-digit components", () => {
|
||||
assert.equal(compareSkinVersions("1.10.0", "1.9.9"), 1);
|
||||
assert.equal(compareSkinVersions("1.0.0-beta.10", "1.0.0-beta.2"), 1);
|
||||
assert.equal(compareSkinVersions("1.0.0-beta", "1.0.0"), -1);
|
||||
assert.equal(compareSkinVersions("1.0.0+build", "1.0.0"), 0);
|
||||
});
|
||||
test("actual admin HTTP endpoints enforce authentication/CSRF and serialize competing installs", async t => {
|
||||
const f = fixture(), skins = await registry(t);
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
const service = { isInitialized: () => true, isPasswordChangeRequired: () => false, verifyPassword: async () => true, database: { addAudit() {} } } as unknown as AdminService;
|
||||
const app = express(); app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger, getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now(), version: "0.2.8", skinRegistry: skins, skinStore: new SkinStore("0.2.8", f.fetcher) }));
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
t.after(() => new Promise<void>(done => server.close(() => done())));
|
||||
await new Promise<void>(done => server.once("listening", done));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
let cookie = "", csrf = "";
|
||||
const api = createAdminApi({ csrfToken: () => csrf, fetch: async (path, init) => {
|
||||
const headers = new Headers(init?.headers); headers.set("origin", origin); if (cookie) headers.set("cookie", cookie);
|
||||
const response = await fetch(`${origin}${path}`, { ...init, headers });
|
||||
const session = response.headers.get("set-cookie"); if (session) cookie = session.split(";")[0]; return response;
|
||||
} });
|
||||
await assert.rejects(api.skinStore(), (e: any) => e.status === 401);
|
||||
csrf = (await api.login("admin", "test-only-password")).csrfToken;
|
||||
const entry = (await api.skinStore()).entries[0];
|
||||
const input = { id: entry.id, revision: entry.revision, installedVersion: null };
|
||||
for (const path of ["/skin-store/refresh", "/skin-store/install"]) {
|
||||
const response = await fetch(`${origin}/api/admin${path}`, { method: "POST", headers: { origin, cookie, "content-type": "application/json" }, body: JSON.stringify(input) });
|
||||
assert.equal(response.status, 403);
|
||||
}
|
||||
const outcomes = await Promise.allSettled([api.installStoreSkin(input), api.installStoreSkin(input)]);
|
||||
assert.equal(outcomes.filter(result => result.status === "fulfilled").length, 1);
|
||||
assert.equal(outcomes.filter(result => result.status === "rejected").length, 1);
|
||||
assert.equal((await api.skins()).skins[0].id, entry.id);
|
||||
await api.setSkinEnabled(entry.id, false);
|
||||
assert.equal((await skins.list())[0].enabled, false);
|
||||
await api.deleteSkin(entry.id);
|
||||
assert.equal((await api.skins()).skins.length, 0);
|
||||
});
|
||||
@@ -249,6 +249,25 @@ async function connect() {
|
||||
return socket;
|
||||
}
|
||||
|
||||
test("accelerated voice signaling connects directly to the configured relay gateway", async () => {
|
||||
globalThis.fetch = async url => {
|
||||
assert.equal(url, "/api/join-ticket", "the page and join-ticket API stay on the ingress gateway");
|
||||
return { ok: true, json: async () => ({ ticket: "relay-ticket", voiceEndpoint: "https://voice-de.example.com" }) };
|
||||
};
|
||||
voice.connect("voice.example:9987", "", "Visitor", "", "", false, "", true, "relay-de");
|
||||
await nextTurn();
|
||||
assert.equal(TestSocket.instances.at(-1)?.url, "wss://voice-de.example.com/ws/voice?ticket=relay-ticket");
|
||||
assert.equal(location.host, "gateway.example", "the browser address remains on the ingress gateway");
|
||||
});
|
||||
|
||||
test("secure pages reject insecure remote voice gateway endpoints", async () => {
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ticket: "relay-ticket", voiceEndpoint: "http://voice-de.example.com" }) });
|
||||
voice.connect("voice.example:9987", "", "Visitor", "", "", false, "", true, "relay-de");
|
||||
await nextTurn();
|
||||
assert.equal(TestSocket.instances.length, 0);
|
||||
assert.equal(voice.state.errorCode, "VOICE_GATEWAY_UNAVAILABLE");
|
||||
});
|
||||
|
||||
test("directory snapshots keep member names, flags and identity-scoped volume in sync", async () => {
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, members: [{ id: 7, uid: "old-user", nickname: "Before" }] });
|
||||
|
||||
Reference in new issue
Block a user