Compare commits

..
37 Commits
Author SHA1 Message Date
illusia dacc4a143f release: prepare v0.2.9 2026-10-24 18:28:03 +08:00
illusia d91e811ede Merge dev into master for v0.2.9 2026-10-24 18:24:04 +08:00
illusia b9fccb8757 feat(channels): render TeamSpeak spacers across skins 2026-10-24 18:16:01 +08:00
illusia 4bff2133b6 fix(admin): correct TeamSpeak member counts and action feedback 2026-10-24 18:16:00 +08:00
illusia 88439181ae fix(skins): sync Discord Voice 1.0.11 layout and controls 2026-10-24 18:16:00 +08:00
illusia 941cff30d7 docs: credit upstream SDK author and skin contributors 2026-10-24 18:15:59 +08:00
illusia 9c4a2c4a51 fix(kaak): identify project links in icon tooltips 2026-10-24 14:11:32 +08:00
illusia bb5905eb39 feat(kaak): add admin and community shortcuts to server rail 2026-10-24 14:03:27 +08:00
illusia 452e6f09ca feat(skins): add persistent voice workspace API and align KAAK 2026-10-24 13:30:50 +08:00
illusia 0af3236c30 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.
2026-10-24 12:52:59 +08:00
ILLUSIA c917692b61 Merge pull request #51 from yichen11818/codex/kook-connection-flow
fix(kook): KAAK首次连接后保留语音工作区
2026-10-21 16:39:05 +08:00
yumi bcecf4fed4 fix(kook): keep returning users in the voice workspace 2026-10-21 15:31:19 +08:00
illusia 32d84435ce fix(screen-share): correct fullscreen dimensions 2026-10-18 11:10:54 +08:00
illusia 180bfeb52f fix: harden TeamSpeak detection and clean up departed speakers 2026-10-17 14:55:25 +08:00
illusia 84bdf63514 fix: persist member volume preferences 2026-10-17 12:34:57 +08:00
illusia 54e154be1a release: prepare v0.2.8 2026-10-17 09:53:27 +08:00
illusia 4375f01d05 docs: add Shanghai and Hong Kong demo links 2026-10-16 22:55:29 +08:00
ILLUSIA 6f5f4c9f4d Merge pull request #38 from LainHE/fix/audio-frame-error-reporting-upstream
fix(audio): report discarded frames as route drops, not bad frames
2026-10-16 19:33:23 +08:00
ILLUSIA a9f5a47163 Merge pull request #35 from LainHE/fix/voice-session-connect-window-upstream
fix(voice): never swallow a TeamSpeak drop while the session is settling
2026-10-16 19:33:15 +08:00
ILLUSIA 6bf6544fd6 Merge pull request #37 from LainHE/fix/client-ip-trust-boundary-upstream
fix(voice): only believe forwarding headers from declared proxies
2026-10-16 19:33:07 +08:00
ILLUSIA 9c3b86dc7a Merge pull request #40 from LainHE/fix/webrtc-peer-rollback-upstream
fix(webrtc): roll back the peer when the mixer codec is unavailable
2026-10-16 19:31:00 +08:00
ILLUSIA 411ab57b63 Merge pull request #34 from LainHE/fix/screen-share-viewer-roster-upstream
fix(screen-share): resolve viewer avatars from client ids instead of the roster
2026-10-16 19:30:01 +08:00
ILLUSIA 4de532e56b Merge pull request #31 from LainHE/fix/acceleration-relay-ssrf-upstream
fix(acceleration-relay): 在 DNS 解析后校验目标地址,阻断 SSRF
2026-10-16 19:29:43 +08:00
LainHE e9cec18345 fix(voice): only believe forwarding headers from declared proxies
resolveClientIp() read X-Forwarded-For, then X-Real-IP, then the socket
address, taking whichever parsed first, with no notion of who wrote them.
Every visitor can set those headers on the WebSocket upgrade, so the address
recorded for a connection was chosen by the client rather than observed. It is
logged when the client starts connecting, when it reaches TeamSpeak and when
its session ends, and readConnectionHistory() turns those lines into the source
column of the admin connection log, so a visitor could put any address into the
audit trail.

Nothing else was affected: join, mobile and admin-login rate limiting key on
request.socket.remoteAddress, and the admin audit records no address at all, so
no admission or authentication decision depended on the forwarded value.

Forwarding headers are now read only when the peer that sent them is a declared
proxy. A trusted chain is walked from the hop nearest to us towards the client,
and the first address that is not a trusted proxy is reported, so a value a
client injects to the left of the entry its proxy appended is never recorded.
X-Real-IP is used only for a trusted peer that sent no chain, and never in
preference to one: a proxy appends its peer to X-Forwarded-For, whereas
X-Real-IP is only as good as the proxy configuration and can still carry a
client value if it is forwarded rather than overwritten.

Whoever we believe can choose what we record, so the default trusts loopback
alone. That keeps a reverse proxy on the same host working, including the
published host-network container. WEBSPEAK_TRUSTED_PROXIES takes IPs and CIDRs
for anything else; an invalid entry stops startup instead of silently narrowing
what is trusted.

Tests cover the direct-client case including the mapped IPv4 peer form, the
chain walk over IPv4 and IPv6, chains that are trusted end to end, X-Real-IP
gating, default loopback, CIDR and ::ffff: entries, and rejected
misconfiguration.
2026-10-16 17:48:09 +08:00
LainHE 82957832a5 fix(audio): report discarded frames as route drops, not bad frames
The browser uplink judged an incoming PCM frame before it resolved the audio
route, so a frame that arrived while the route was down was reported as
malformed. Every frame is discarded in that state whatever its size, which made
the error a misattribution and, worse, a spurious client-side failure: the
browser renders `error.code` as a session error, and that code can abort an
in-flight quick connect, because WebClient.vue fails the pending favorite
connection whenever a new error code appears.

Resolve the route first and only then judge the frame. The flow counters are
unchanged: a discarded frame increments `ingressDroppedFrames` exactly once
either way, so the teardown log and the client's `audioStatsProbe` still report
the same numbers, and a malformed frame still never reaches the encoder.

Repeated faults of one kind also produced one JSON error per frame. A client
streaming malformed frames made the server build and send a ~110 byte error for
every frame it received, for a payload that can be as small as a single byte,
while the browser only ever shows the first one: it writes the same error string
into the same state, and Vue does not re-render for an unchanged value.
Rate-limit the reports per fault code so that two different faults cannot hide
each other, and keep counting every discarded frame.

Route those faults to the logger as well. The outbound error is not logged
anywhere, so an operator had no way to notice a client that kept sending
malformed audio until the session was torn down and the full flow stats were
written at once. The warning is raised under the same rate limit, so a broken
client cannot turn it into a new log flood.

Tests: the route-first ordering and the per-code window each have a case that
fails without the change.
2026-10-16 16:42:28 +08:00
LainHE 5cf7331223 fix(webrtc): roll back the peer when the mixer codec is unavailable
`WebRtcAudioSession` builds its `RTCPeerConnection`, attaches the outgoing
track and adds the audio transceiver before it creates the mixer encoder. When
that encoder cannot be created the constructor stops the track and throws, but
it never closed the peer it had already built.

The caller cannot cover for it. `handleWebRtcOffer` assigns the factory result
to a local that starts as `null`:

    let peer: WebRtcAudioSession | null = null;
    ...
    peer = this.createWebRtcSession({ ... });

so a throwing constructor leaves `peer` at `null`, and the catch block's
`if (entry.webrtc === peer) entry.webrtc = null;` and `await peer?.close()` are
both no-ops. The peer was created, never closed, and no handle to it survived
the unwind.

The impact today is bounded, and the defect is the broken invariant rather than
a measured leak: the throw lands before ICE gathering starts, before
`scheduleAudioTick()` and `activityTimer` are installed, and werift's
constructor binds no socket or timer of its own, so the unreachable instance is
reclaimed by garbage collection. But an exception during construction must not
strand a half-built resource, and any acquisition added above that point would
turn this into a real leak.

Close the peer before propagating the failure:

  * `this.peer.close()` now runs before the throw, so the peer is released even
    though the caller never receives the session;
  * `createEncoder` becomes an injectable option on `WebRtcAudioSessionOptions`,
    mirroring `VoiceBridgeDependencies.createEncoder` and `createWebRtcSession`.
    Production still resolves to `new OpusEncoder(AUDIO_SAMPLE_RATE, 1)`, so
    behaviour is unchanged; the seam exists so the failure branch is reachable
    without a machine that happens to lack the native codec.

Covered by a regression test that injects a failing encoder and instruments
`RTCPeerConnection.prototype.close` to count the distinct peers closed during
construction. It reports 0 on the old code and 1 with the fix, in any
environment and with no dependency on native Opus.
2026-10-16 14:55:13 +08:00
LainHE 9873d27222 fix(voice): never swallow a TeamSpeak drop while the session is settling
The gateway only publishes `connected` once the directory snapshot lands in
`sendInitialState()`. Between authenticating and that point the session is in
`syncing` while `hasConnectedOnce` is still false. `onDisconnect` required both
`hasConnectedOnce` and `state === "connected"`, so a transport drop inside that
gap returned early and did nothing:

  * no `disconnected` frame for the browser,
  * no `scheduleReconnect`,
  * no peer/WeRTC rollback, no teardown.

The session stayed in `syncing` with the browser socket still open, the client
kept showing the connecting state forever, and nothing could recover it short
of the user closing the tab. `onKick` had the same gap via its own
`if (!hasConnectedOnce) return;` guard, so a kick or ban during the same window
was silently ignored while the gateway kept the dead session alive.

The window is not momentary. `tsClient.connect()` resolves even when the
directory reconciliation fails (the failure is logged and the explicit snapshot
emit is skipped), and `resetDirectoryForReconnect()` clears the snapshot on
every recovery, so each reconnect attempt opens the window again.

Treat the settling states (`authenticating`, `syncing`) as an explicit concept
and handle transport loss there:

  * a drop during the first connect is a connect failure, not an interruption:
    report `connectionFailed`, close with 4003 and tear the session down;
  * the same reporting is now shared by the rejected-`connect()` path through a
    single `failConnect` helper, so a transport that reports itself twice (a
    `disconnected` event plus a rejected connect) still fails exactly once;
  * a drop during a *reconnect* handshake returns the session to `reconnecting`
    and schedules another attempt instead of stalling in `syncing`;
  * a kick that lands before the session settles is reported and terminal.

A drop on an established session keeps the previous behaviour: `disconnected`
plus a scheduled reconnect.

Covered by three regression tests over the real WebSocket wiring with only the
external SDK stubbed: a drop before the directory sync, a kick in the same
window, and a drop during a reconnect handshake. All three hang on the old code.
2026-10-16 12:23:55 +08:00
LainHE 0ef9b84237 Merge remote-tracking branch 'upstream/master' into tmp-merge-check
# Conflicts:
#	package.json
#	src/server/acceleration-relay.test.ts
#	src/server/acceleration-relay.ts
2026-10-16 10:32:06 +08:00
LainHE bcc78177c2 fix(screen-share): keep the announced viewer count in step with the roster
Two smaller gaps left over from removing the inline avatars.

The announced viewerCount summed the viewer entry ids and the native viewer
ids, while the roster silently dropped ids whose participant had vanished
from the entry map. A client that disappears without passing through the
leave path therefore inflated the count for as long as the stream lived.
Prune those ids, and derive the count in the same call that builds the
roster so the two can no longer disagree.

The legacy inline-avatar path capped each entry at 128 KiB but placed no
bound on the roster total, which still allowed 64 x 128 KiB in a single
broadcast. Bound the total as well; entries past the budget fall back to
the client-side member lookup like any other viewer without an avatar.

Both behaviours are covered by new tests: a dropped entry no longer
inflates the count, and eight 128 KiB avatars are trimmed to the budget
(measured at 1048576 bytes without the bound).
2026-10-16 09:50:26 +08:00
LainHE bfa26da9eb fix(screen-share): resolve viewer avatars from client ids instead of the roster
The screen-share viewer roster embedded every viewer's avatar as a base64
data URL, and the gateway rebroadcast the whole roster to the channel on
every viewer join and leave. With the 64-viewer cap and the 128 KiB avatar
cap that is up to ~8 MB of JSON per event, multiplied by every member of
the channel -- even though the player renders at most five avatars and
every client already holds member avatars from the directory it received
through the connected and memberAvatar messages.

Send the TeamSpeak client id instead and resolve the avatar locally,
mirroring how a stream's ownerClientId already maps to a member card. This
removes the payload entirely rather than trimming it: the roster no longer
scales with avatar size at all.

The legacy inline avatar is still parsed so a newer client keeps working
against an older gateway, and a viewer missing from the local directory
degrades to the existing initial-based avatar fallback.

Verified by a regression test that gives every viewer a 128 KiB avatar and
asserts the roster stays under 16 KiB. Restoring the previous behaviour
makes that assertion fail at 1049182 bytes for eight viewers.
2026-10-16 09:47:01 +08:00
ILLUSIA 7715214f43 Merge pull request #33 from LainHE/fix/acceleration-relay-reconnect-upstream
fix(acceleration-relay): rebuild a self-closed tunnel on reconnect
2026-10-15 22:31:50 +08:00
ILLUSIA 69c2f4776e Merge pull request #32 from LainHE/fix/acceleration-relay-error-handling-upstream
fix(acceleration-relay): 修复 socket 错误监听器内 throw 导致进程崩溃
2026-10-15 22:31:22 +08:00
LainHE 7977572362 fix(acceleration-relay): rebuild a self-closed tunnel on reconnect
An acceleration tunnel can tear itself down on its own: a socket error, a relay
OPEN_ERR/CLOSE frame, or an open timeout runs closeSockets(), which closes both
UDP sockets and leaves every later sendFrame() a silent no-op.

TSClient kept the adapter bound to that tunnel's now-dead local port and only
rebuilt the transport when adapter or client were null. An auto-reconnect
therefore dialed a port nobody reads, and because a closed tunnel reports
nothing, the session could never recover and never surfaced an error either.

- expose isClosed() on AccelerationRelayClient so callers can distinguish a live
  tunnel from one that tore itself down
- drop a stale tunnel together with its adapter and SDK client before connect()
  decides whether to rebuild the transport, detaching first so a late
  "disconnected" from the retired client cannot re-enter the reconnect path
- cover the reconnect guard with regression tests in ts-client.test.ts

Verified: tsc clean; ts-client.test.ts 35/35 pass (incl. the two new guards).
2026-10-15 21:36:31 +08:00
LainHE 96f7fd6783 fix(acceleration-poc): align the relay's target guard with the gateway policy
The PoC relay carried its own copy of the restricted-address check and had
drifted well behind src/security/open-target-policy.ts: it missed multicast,
192.0.0.0/24 and the other special-use ranges, 198.18.0.0/15, the TEST-NET
blocks, fec0::/10, ff00::/8 and 2001:db8::/32. A relay started without
allowPrivate would therefore forward to addresses the gateway refuses, and
nothing exercised the guard, so the gap could not be noticed.

The relay must stay a plain .mjs file that the README documents copying to a
remote host without a build step, so it cannot import the TypeScript policy. The
predicate is mirrored instead and pinned by a parity test that fails the moment
the two classifications disagree.

The parity test lives beside the PoC rather than under src/: .dockerignore
excludes scripts/acceleration-poc from the Docker build context while the
Dockerfile runs `tsc` over src/**, so a copy in src/ would resolve locally and
still break the image build with TS2307.

- mirror isRestrictedAddress() exactly, including fail-closed handling of any
  input that is not a literal public address
- add scripts/acceleration-poc/target-guard-parity.test.mjs comparing both
  implementations across private, loopback, link-local, carrier-grade NAT,
  special-use, IPv6 and IPv4-mapped cases
- assert the guard in the PoC smoke run: a relay without allowPrivate must
  reject loopback, private and IPv4-mapped targets while still serving a public
  one, and the run now fails with the offending target instead of passing
  silently

Verified: tsc clean; `npm run build` and `npm run web:build` succeed with
scripts/acceleration-poc moved aside to reproduce the Docker build context; the
parity test fails when either side drifts; the smoke run reports ssrf_guard_ok
and ACCELERATION_POC_OK after the fix, and fails with a LEAK line per unblocked
target once the guard is weakened; the IPv6 smoke run still reports
IPV6_ACCELERATION_POC_OK.
2026-10-15 21:26:22 +08:00
LainHE 4816c7ea62 fix(acceleration-relay): validate resolved targets to close SSRF
The relay's private-target guard ran on the caller-supplied hostname while the
connection was made to the DNS-resolved address, so any hostname could reach
loopback or an internal host even with allowPrivate=false. IPv4-mapped IPv6
literals such as ::ffff:127.0.0.1 slipped through the IPv6 branch as well.

- reuse isRestrictedAddress() instead of the weaker local isPrivateAddress()
- resolve first, then reject when any resolved address is restricted, so a
  mixed public/private DNS answer cannot be used to reach an internal host
- release the freshly created session before rejecting a blocked target
- add an injectable lookupAddresses option for deterministic tests
- mirror the same resolve-then-validate ordering in the acceleration PoC relay
- add src/server/acceleration-relay.test.ts (6 tests) to the test script

Verified: tsc clean; the 6 new tests fail 4/6 before the fix and pass 6/6 after;
the acceleration PoC still reports ACCELERATION_POC_OK.
2026-10-15 16:34:07 +08:00
LainHE feb50d29c1 fix(acceleration-relay): report socket errors instead of throwing into the void
The relay's socket error listener ended with `throw error`. A listener that throws
escapes EventEmitter.emit, so it became an uncaught exception that terminated the
whole process. Because the throw also aborts the remaining listeners, it prevented
the startup promise from ever settling when the socket failed to bind.

- extract an idempotent shutdown() used by both close() and error handling
- reject the startup promise when the failure happens before listening, so a failed
  bind behaves like any other rejected startup rather than a process crash
- tear the relay down and report via a new onError callback once it is running
- release the socket and sweep interval on a synchronous bind failure, which never
  emits error at all
- add 3 regression tests covering bind failure, a surviving relay after a failed
  sibling startup, and idempotent close
- register the new test file in the npm test list so CI actually runs it

Verified: tsc --noEmit is clean and the 3 new tests pass. Before the fix the same
bind failure terminated the process with an uncaught EADDRINUSE instead of
rejecting the startup promise.
2026-10-15 16:20:19 +08:00
illusia 62af82f253 fix(kaak): keep voice dock controls inside panel 2026-10-14 17:06:44 +08:00
151 changed files with 11639 additions and 1161 deletions

No files matched your search

+22 -12
View File
@@ -9,7 +9,7 @@ on:
version:
description: Release version without the v prefix
required: true
default: 0.2.7
default: 0.2.9
type: string
permissions:
@@ -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
@@ -303,15 +299,29 @@ jobs:
cd release-assets
sha256sum * > SHA256SUMS.txt
- name: Publish GitHub release
env:
RELEASE_REF: ${{ github.ref_name }}
run: |
node --input-type=module <<'NODE'
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const tag = process.env.RELEASE_REF;
const languages = [['简体中文', 'zh-CN'], ['English', 'en'], ['Deutsch', 'de'], ['Русский', 'ru'], ['日本語', 'ja']];
const sections = languages.map(([label, locale]) => {
const source = readFileSync(`docs/README.${locale}.md`, 'utf8');
const start = source.indexOf(`### [${tag}](`);
if (start < 0) throw new Error(`Missing ${tag} release notes for ${locale}`);
const remaining = source.slice(start);
const next = remaining.indexOf('\n### [v', 1);
const notes = (next < 0 ? remaining : remaining.slice(0, next)).trim();
return `## ${label}\n\n${notes}\n\n[Project documentation](https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${tag}/docs/README.${locale}.md)`;
});
writeFileSync(join(process.env.RUNNER_TEMP, 'webspeak-release-notes.md'), sections.join('\n\n---\n\n') + '\n');
NODE
- name: Upload GitHub release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: WebSpeak ${{ github.ref_name }}
body: |
Release notes are maintained in each language's project documentation:
- [简体中文](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.zh-CN.md#latest-release-notes)
- [English](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.en.md#latest-release-notes)
- [Deutsch](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.de.md#latest-release-notes)
- [Русский](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ru.md#latest-release-notes)
- [日本語](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ja.md#latest-release-notes)
body_path: ${{ runner.temp }}/webspeak-release-notes.md
files: release-assets/*
-1
View File
@@ -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
+4 -2
View File
@@ -138,22 +138,24 @@ Settings responses merge against the submitted snapshot instead of replacing new
| Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings |
| `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` |
| `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup |
| `WEBSPEAK_TRUSTED_PROXIES` | Comma-separated IPs/CIDRs whose `X-Forwarded-For` may be believed; defaults to loopback so a same-host reverse proxy keeps working |
| Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings |
| Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state |
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
View File
@@ -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"]
+10 -4
View File
@@ -14,7 +14,7 @@
[![GitHub Stars](https://img.shields.io/github/stars/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&logo=github&color=0f766e)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
<br />
[![TeamSpeak](https://img.shields.io/badge/TeamSpeak-3%20%7C%206-2580C3?style=flat-square)](https://www.teamspeak.com/)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.5-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.12-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/)
[![Vue](https://img.shields.io/badge/Vue-3-42B883?style=flat-square&logo=vuedotjs&logoColor=white)](https://vuejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-6-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Docker](https://img.shields.io/badge/Docker-GHCR-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
@@ -36,6 +36,11 @@
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
## 在线演示 · Live Demo
- 上海节点 / Shanghai: <https://shanghai.webspeak.online>
- 香港节点 / Hong Kong: <https://webspeak.online>
## 文档 · Documentation
- [简体中文](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.zh-CN.md)
@@ -72,11 +77,12 @@ Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music
## Contributors · 贡献者
感谢通过 PR 改进 WebSpeak 的贡献者。以下按 GitHub 的合并记录列出。
感谢上游 SDK 作者及通过 PR 改进 WebSpeak 的贡献者。以下列出上游基础项目、已合并的 PR,以及已移植为独立皮肤包的原始贡献。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
## 许可证 · License · Lizenz · Лицензия · ライセンス
+79 -15
View File
@@ -4,19 +4,20 @@
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
Aktuelle Version: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
Aktuelle Version: [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9).
## Live-Demo
Adresse: <https://webspeak.online>
- Shanghai: <https://shanghai.webspeak.online>
- Hongkong: <https://webspeak.online>
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
Netzwerkbedingungen und Auslastung können bei beiden Demos schwanken; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
## ✨ Funktionen
| Funktion | Beschreibung |
| --- | --- |
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll anhand der gemeldeten Version automatisch. |
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
@@ -32,6 +33,26 @@ Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung kö
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
| Selbsthosting | Daten bleiben beim Betreiber; Pakete für Windows x64 und Linux x64/ARM64, Docker für amd64/arm64 und Android-APKs für arm64-v8a, armeabi-v7a und x86_64. |
## TeamSpeak-Versionskompatibilität
Sprachverbindungen verwenden das TeamSpeak-Clientprotokoll und benötigen keine Query-Zugangsdaten. Die optionale TS-Verwaltung verwendet eigene WebQuery-/ServerQuery-Zugangsdaten.
- **TeamSpeak 3**: Die Erkennung wertet die führende `3.x`-Versionsnummer aus. Ältere Serverversionen sollten in der jeweiligen Umgebung geprüft werden, da nicht jede historische Version separat getestet wurde.
- **TeamSpeak 6**: Unterstützt, einschließlich Bildschirmfreigabe mit nativen TeamSpeak-6-Clients.
- **Automatische Erkennung**: Das Gateway liest die `version`-Antwort des Servers und hält das erkannte Protokoll in der Verbindungsdiagnose fest.
- Das Gateway verwendet das Upstream-SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak richtet sich an TeamSpeak 3 und 6.
## Optionale TeamSpeak-Verwaltung
WebSpeak-Verwaltung und Sprachverbindungen sind davon unabhängig. Im Modus mit festem Server die TS-Verbindung unter `/admin/ts-admin` einrichten.
1. WebQuery auf dem TS-Server aktivieren und einen berechtigten TS-Administrator einen API-Schlüssel erstellen lassen. HTTP-/HTTPS-URL von WebQuery und Schlüssel eintragen. Gemeint ist der TS-Query-Dienst, nicht die WebSpeak-Webseite. Unterstützt werden TS3 ab 3.12 und TS6.
2. Virtuelle Server-ID `0` wählt anhand des festen Sprachports aus. Bei eingeschränkten Schlüsseln die freigegebene Server-ID eintragen. Änderungen erfordern einen schreibbaren Geltungsbereich und entsprechende TS-Rechte; Leseschlüssel dienen zur Anzeige.
3. Alternativ ServerQuery SSH oder bei TS3 ServerQuery TCP wählen. Query-Host (leer: festes Ziel), Query-Port, Benutzername und Passwort eintragen; SSH benötigt einen vertrauenswürdigen Hostschlüssel-Fingerabdruck. Dies ist kein SSH-Zugang zum Betriebssystem. TCP ist unverschlüsselt und nur für vertrauenswürdige Netze geeignet. HTTPS-Zertifikate müssen vom Gateway als vertrauenswürdig erkannt werden.
4. Speichern und verbinden oder aktualisieren. Verfügbar sind Servereinstellungen, Kanalverwaltung, Verschieben/Ausschließen/Sperren von Mitgliedern, Gruppenzuweisung und Entsperren. Aktionen benötigen Bestätigung und TS-Rechte; Listen werden manuell aktualisiert.
Zugangsdaten werden serverseitig verschlüsselt und nie von der API zurückgegeben. Datenbank und `master.key` gemeinsam sichern. Verbindungsfehler beeinflussen weder WebSpeak-Verwaltung noch Sprache. Sperren verwenden die Benutzer-UID, damit andere Nutzer derselben Gateway-IP nicht betroffen sind.
## 🖼️ Screenshots
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
@@ -85,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
@@ -93,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' \
@@ -137,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.
@@ -151,12 +179,47 @@ Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entf
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
- Die TeamSpeak-Verbindung verwendet das Upstream-SDK [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), veröffentlicht als `@honeybbq/teamspeak@1.0.0-beta.19`; der SDK-Fork des Projekts muss nicht mehr gebaut werden.
## 🧾 Änderungsprotokoll
<a id="latest-release-notes"></a>
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
#### Erweiterungen
- Umstellung auf das Upstream-SDK 1.0.0-beta.19. Normale Sprachverbindungen verwenden das Live-Clientverzeichnis ohne Query-Listenberechtigungen.
- Neuer GitHub-Skin-Store mit Installation, Updates und Freigabe pro Instanz. Discord Voice wird als eigenständiges standardkonformes `.wskin`-Beispiel verteilt.
- Optionale TS-Verwaltung im Modus mit festem Server: WebQuery-, TCP- oder SSH-Query-Zugangsdaten ermöglichen die Verwaltung von Server, Kanälen, Mitgliedern, Servergruppen und Sperren.
- Relays können einen direkten Sprachendpunkt für Browser bereitstellen und die Sprachsitzung übernehmen; eine zusätzliche Weiterleitung zwischen Gateways entfällt.
- Allgemeine Schnittstellen zum Beibehalten des Arbeitsbereichs und zur Wiederverbindung; KAAK nutzt diese und bietet Zugänge zur Administration, zum Projekt-GitHub und zur QQ-Gruppe.
- Unterstützung für TeamSpeak-Kanaltrenner mit Ausrichtung, Wiederholung, Leerzeilen und Standardlinien sowie öffentlichen Darstellungsdaten für Skins.
#### Fehlerbehebungen
- Vollbildgröße der Bildschirmfreigabe und Bereinigung von Status und Wiedergaberessourcen ausgeschiedener Mitglieder korrigiert.
- Erfolgreiche Sperren werden nicht mehr als Fehler gemeldet; Query-Verbindungen zählen nicht als Mitglieder, und das Kanalpasswort ist korrekt beschriftet.
- Berechtigungs-, Ratenlimit- und Zeitüberschreitungsfehler werden unterschieden. Schlägt nur die Aktualisierung nach einer erfolgreichen Aktion fehl, erscheint eine eigene Warnung gegen doppelte Ausführung.
- Verhindert, dass das SDK fehlgeschlagene HTTP-Antworten als erfolgreiche WebQuery-Ergebnisse behandelt; Layoutfehler auf der DC-Startseite, im Chat und bei schmalen Ansichten behoben.
#### Bekannte Probleme
- Die in [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) beschriebene Sicherheitsabsicherung ist nicht enthalten; das Schließen des PRs bedeutet nicht, dass die gemeldeten Probleme behoben sind.
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
#### Bildschirmfreigabe und Verbindungsstabilität
- Aushandlung und Verarbeitung der Videospur für Bildschirmfreigaben zwischen Browsern und nativen TeamSpeak-Clients korrigiert.
- Schnelle Kanalwechsel werden zuverlässiger verarbeitet, um inkonsistente Clientzustände zu vermeiden.
- Darstellungsfehler in einigen Skin-Komponenten und der KAAK-Übersetzung behoben.
#### Verbesserungen der Oberfläche
- Audiogerätenamen werden vollständig angezeigt und bei wenig Platz umgebrochen, damit lange Namen unterscheidbar bleiben.
- Unbeabsichtigte Textauswahl des Avatar-Platzhalters behoben.
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
#### Offeneres Skin-System
@@ -240,7 +303,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)
@@ -280,7 +343,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
@@ -311,9 +373,11 @@ Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
## Kürzlich zusammengeführte Beiträge
## Mitwirkende und Beiträge
- Die Liste folgt den GitHub-Merge-Einträgen.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) verbesserte Browser-Fehlermeldungen; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) korrigierte Skalierung, schwebendes Layout und Fußzeile der Startseite.
Diese Liste würdigt den Autor des zugrunde liegenden SDKs, Beiträge aus zusammengeführten GitHub-PRs sowie ursprüngliche Arbeiten, die in eigenständig verteilte Skin-Pakete übernommen wurden.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Autor des [teamspeak-js-SDKs (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), das den von WebSpeak verwendeten TeamSpeak-Protokollclient bereitstellt.
- [LainHE](https://github.com/LainHE) — [zusammengeführte PRs #2, #8, #28, #31–#35, #37, #38 und #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): Browser-Fehlerübersetzungen, Skalierung und Startseitenlayout, Bildschirmfreigabe-Bitrate und Zuschaueravatare, Relay-Zielprüfung und Wiederverbindung, vertrauenswürdige Proxys, Weitergabe von Verbindungsfehlern, Audio-Fehlermeldungen und Ressourcenfreigabe bei WebRTC-Fehlern.
- [TimmySheep](https://github.com/TimmySheep) — [zusammengeführte PRs #13 und #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep) zu vorhandenen TS6-Freigaben, Seitenverhältnis, mobiler Sprache/Bildschirm-Wachhalten/Skin-Menü, Kanaloptionen der Identität, PWA/Design, Chatverlauf, Mitglieder-Audiozuständen und Mikrofonberechtigungen.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele in Einstellungen, Favoriten und Einladungen.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) ermöglichte Verbindungen über registrierte TeamSpeak-Nicknames und bewahrte Nickname-Ziele; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) verbesserte das Beibehalten des KAAK-Arbeitsbereichs und die Wiederverbindung nach der ersten Verbindung. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) und [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) lieferten das ursprüngliche Design und die Implementierung des Discord-Skins (Commit-Autor **yumi**), die das WebSpeak-Projekt in einen [eigenständig verteilten `.wskin`-Skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) überführte.
+79 -15
View File
@@ -4,21 +4,22 @@
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
Latest release: [read the 0.2.7 changelog on this page](#latest-release-notes).
Latest release: [read the 0.2.9 changelog on this page](#latest-release-notes).
Skin authors should start with the [current skin development guide](./SKIN_DEVELOPMENT.md), which combines the `.wskin` package format, current runtime APIs, permission boundaries, and authoring workflow. The repository also includes the [WebSpeak skin development skill for agents](../.agents/skills/webspeak-skin-development/SKILL.md).
## Live demo
URL: <https://webspeak.online>
- Shanghai: <https://shanghai.webspeak.online>
- Hong Kong: <https://webspeak.online>
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
Network conditions and load may vary at either demo. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
## ✨ Features
| Capability | Description |
| --- | --- |
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6, automatically detecting the target protocol from the reported version. |
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
@@ -34,6 +35,26 @@ The public demo is hosted in Hong Kong and its network conditions and load may b
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
| Self-hosting | Data stays with the operator; packages include Windows x64 and Linux x64/ARM64, Docker supports amd64/arm64, and Android APKs target arm64-v8a, armeabi-v7a, and x86_64. |
## TeamSpeak version compatibility
Voice uses the standard TeamSpeak client protocol and needs no Query credentials. Optional TeamSpeak administration uses separate WebQuery / ServerQuery credentials.
- **TeamSpeak 3**: protocol detection recognizes the leading `3.x` version. Older server releases should be validated with the specific deployment because not every historical release has been independently tested.
- **TeamSpeak 6**: supported, including screen sharing with native TeamSpeak 6 clients.
- **Auto-detection**: the gateway reads the server's `version` response and records the detected protocol in connection diagnostics.
- The gateway uses the upstream [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK; WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
## Optional TeamSpeak administration
WebSpeak administration and visitor voice do not depend on this feature. In fixed-server mode, open `/admin/ts-admin` to configure the TS management connection.
1. Enable WebQuery on the TS server and have an authorized TS administrator create an API key. Enter the WebQuery HTTP/HTTPS URL and key. This is the TS Query endpoint, not the WebSpeak website. TS3 (3.12+) and TS6 are supported.
2. Virtual server ID `0` selects the fixed target's voice port. For a restricted key, enter its authorized server ID. Read-only keys support viewing; changes require writable scope and the corresponding TS permissions.
3. Alternatively, choose ServerQuery SSH, or ServerQuery TCP for TS3. Enter the Query host (blank uses the fixed target), Query port, username and password; SSH also requires a trusted host-key fingerprint. This is the TS Query service, not an operating-system SSH login. TCP is unencrypted and suitable only for trusted networks. HTTPS certificates must be trusted by the gateway.
4. Save and connect or refresh to inspect the server, channels, members, server groups and bans. Actions include server settings, channel creation/renaming/deletion, moving/kicking/banning members by identity, group assignment and removing bans. Actions require confirmation and TS permission checks; lists refresh manually.
Credentials are encrypted on the server and never returned by the API. Back up both the database and `master.key`. A failed management connection does not affect WebSpeak administration or ordinary voice. UID bans avoid banning other users sharing the gateway IP.
## 🖼️ Screenshots
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
@@ -95,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
@@ -103,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' \
@@ -147,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.
@@ -161,12 +189,47 @@ Disable and save the relay configuration to remove the relay option from the wel
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
- TeamSpeak connectivity uses upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), published as `@honeybbq/teamspeak@1.0.0-beta.19`; building the project's SDK fork is no longer required.
## 🧾 Changelog
<a id="latest-release-notes"></a>
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
#### Enhancements
- Migrated to upstream SDK 1.0.0-beta.19. Ordinary voice connections use the live client directory without Query list permissions.
- Added a GitHub skin store and instance-level installation, updates and availability controls. Discord Voice is distributed independently as a standard `.wskin` example.
- Added optional TS administration in fixed-instance mode, with WebQuery, TCP or SSH Query credentials for managing the server, channels, members, server groups and bans.
- Relays can advertise a direct browser voice endpoint and own the voice session, avoiding an extra gateway forwarding hop.
- Added generic persistent-workspace and reconnect APIs, adopted by KAAK alongside administrator, project GitHub and QQ group shortcuts.
- Added TeamSpeak channel spacers with alignment, repeated fill, blank rows and standard line patterns, including public presentation data for skins.
#### Fixes
- Fixed screen-share fullscreen sizing and cleanup of departed members' state and playback resources.
- Fixed successful bans being reported as failures, Query connections appearing in member counts and the channel-password label.
- Distinguished permission, rate-limit and timeout errors. A refresh failure after a successful action now has its own warning to prevent duplicate actions.
- Guarded against the SDK treating failed HTTP responses as successful WebQuery results, and fixed DC home, chat and narrow-screen control layouts.
#### Known issues
- The security hardening described in [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) is not included in this release; closing that PR does not mean the reported issues are fixed.
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
#### Screen sharing and connection reliability
- Fixed negotiation and video-track handling for screen sharing between browsers and native TeamSpeak clients.
- Improved handling of rapid channel switches to reduce inconsistent client state.
- Fixed content rendering in some skin components and localization in the KAAK skin.
#### Interface improvements
- Audio device names now display in full and wrap when space is limited, making long names easier to distinguish.
- Fixed avatar fallback text being selected unintentionally.
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
#### A more open skin system
@@ -250,7 +313,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)
@@ -290,7 +353,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
@@ -321,9 +383,11 @@ Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
| Session limit | One instance accepts up to 100 active browser sessions. |
## Recent contributors
## Contributors and contributions
- Listed from GitHub's merge records; the version summaries above describe only changes included in each release.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) improved browser error translations; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) fixed scaling, floating layout, and the homepage footer.
This list acknowledges the upstream SDK author, contributions through merged GitHub PRs, and original work adapted into independently distributed skin packages.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Author of the upstream [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK, which provides the TeamSpeak protocol client used by WebSpeak.
- [LainHE](https://github.com/LainHE) — [merged PRs #2, #8, #28, #31–#35, #37, #38 and #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE), covering browser error translations, scaling and home layout, screen-share bitrate and viewer avatars, relay target validation and recovery, trusted proxy handling, connection-failure propagation, audio fault reporting, and WebRTC failure cleanup.
- [TimmySheep](https://github.com/TimmySheep) — [merged PRs #13 and #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep), covering existing TS6 share discovery, share aspect ratio, mobile voice/wake/skin-menu behavior, identity channel options, PWA/theme work, chat history, member audio states, and microphone permission.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added connections through registered TeamSpeak nicknames and preserved nickname targets in settings, favorites, and invitations.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) added registered TeamSpeak nickname connections and preserved nickname targets; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) improved KAAK workspace retention and reconnection after the first connection. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) and [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) supplied the original Discord skin design and implementation (commit author **yumi**), later adapted by the WebSpeak project into an [independently distributed `.wskin` skin](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
+68 -11
View File
@@ -4,7 +4,7 @@
## プロジェクト概要
最新リリース:[v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7)。
最新リリース:[v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9)。
| 観点 | 説明 |
| --- | --- |
@@ -14,15 +14,16 @@
## オンラインデモ
アドレス: <https://webspeak.online>
- 上海: <https://shanghai.webspeak.online>
- 香港: <https://webspeak.online>
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
各デモのネットワークや負荷は変動する場合があります。遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
## ✨ 機能
| 機能 | 説明 |
| --- | --- |
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
| TeamSpeak | TeamSpeak 3 / 6 に対応し、サーバーのバージョンから対象プロトコルを自動検出します。 |
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
@@ -38,6 +39,26 @@
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
| デプロイ | Windows x64、Linux x64/ARM64 パッケージ、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 APK。 |
## TeamSpeak のバージョン互換性
音声接続には標準の TeamSpeak クライアントプロトコルを使い、Query の認証情報は不要です。任意の TS 管理機能では、別途 WebQuery / ServerQuery の認証情報を使用します。
- **TeamSpeak 3**: 先頭の `3.x` バージョンを使ってプロトコルを判定します。すべての旧バージョンを個別に検証しているわけではないため、古いサーバーは実際の環境で確認してください。
- **TeamSpeak 6**: 対応しています。TeamSpeak 6 ネイティブクライアントとの画面共有も可能です。
- **自動検出**: ゲートウェイはサーバーの `version` 応答を読み取り、接続診断に判定結果を記録します。
- ゲートウェイは上流 SDK 1.0 の [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) を使用し、WebSpeak は TeamSpeak 3 と 6 を対象とします。
## 任意の TeamSpeak 管理
WebSpeak 管理画面と音声接続は、この機能に依存しません。固定サーバーモードで `/admin/ts-admin` を開き、TS 管理用の接続を設定します。
1. TS サーバーで WebQuery を有効にし、権限のある TS 管理者に API キーを作成してもらいます。WebQuery の HTTP/HTTPS URL とキーを入力します。WebSpeak のサイトではなく、TS Query サービスの URL です。TS3(3.12 以降)と TS6 に対応します。
2. 仮想サーバー ID `0` は固定接続先の音声ポートから選択します。制限付きキーでは許可された ID を入力してください。読み取りキーでは閲覧ができ、変更には書き込み可能なスコープと対応する TS 権限が必要です。
3. ServerQuery SSH、または TS3 の ServerQuery TCP も選べます。Query ホスト(空欄は固定接続先)、ポート、ユーザー名、パスワードを入力し、SSH では信頼できるホストキーのフィンガープリントも指定します。OS への SSH ログインではありません。TCP は暗号化されないため信頼できるネットワークで使用します。HTTPS 証明書はゲートウェイで信頼されている必要があります。
4. 保存して接続または更新します。サーバー設定、チャンネル管理、メンバーの移動・退出・ID による BAN、グループ割り当て、BAN 解除に対応します。操作には確認が必要で、TS が権限を検証します。リストは手動更新します。
認証情報はサーバーで暗号化され、API から返されません。データベースと `master.key` を一緒にバックアップしてください。管理接続の失敗は WebSpeak 管理画面や音声に影響しません。UID による BAN で同じゲートウェイ IP を使う他のユーザーへの影響を避けます。
## 🖼️ インターフェースのスクリーンショット
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
@@ -82,7 +103,7 @@ TURN を設定した場合、メディアは外部 TURN サービスを経由す
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続は上流の [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) が公開する `@honeybbq/teamspeak@1.0.0-beta.19` を使用します。SDK フォークのビルドは不要になりました。
## 🚀 デプロイ
@@ -111,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
@@ -121,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 をリバースプロキシ経由で公開してください。
@@ -139,6 +159,41 @@ npm start
<a id="latest-release-notes"></a>
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
#### 機能追加
- 上流 SDK 1.0.0-beta.19 へ移行しました。通常の音声接続はクライアントのライブ一覧を使用し、Query の一覧取得権限を必要としません。
- GitHub スキンストアと、インスタンスごとのインストール、更新、有効化の管理を追加しました。Discord Voice は標準 `.wskin` の独立したサンプルとして配布します。
- 固定サーバーモードに任意の TS 管理パネルを追加しました。WebQuery、TCP または SSH Query の認証情報を設定し、サーバー、チャンネル、メンバー、サーバーグループ、BAN を管理できます。
- 中継ノードがブラウザー向けの音声接続先を公開し、音声セッションを担当できるようになりました。ゲートウェイ間の余分な転送を減らせます。
- ワークスペース保持と再接続の共通 API を追加し、KAAK に適用しました。管理画面、プロジェクトの GitHub、QQ グループへの入口も追加しました。
- TeamSpeak のチャンネル区切りに対応しました。配置、繰り返し、空白行、標準線種を扱い、表示データをスキンにも公開します。
#### 修正
- 画面共有の全画面サイズと、退出したメンバーの状態および再生リソースの解放を修正しました。
- BAN 成功時の誤った失敗表示、Query 接続の人数への混入、チャンネルパスワードのラベルを修正しました。
- 権限不足、レート制限、タイムアウトを区別します。操作成功後の更新だけが失敗した場合は別の警告を表示し、重複操作を防ぎます。
- SDK が失敗した HTTP 応答を WebQuery 成功とみなすことを防止し、DC のホーム、チャット、狭い画面の操作部品の配置を修正しました。
#### 既知の問題
- [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) のセキュリティ強化は本リリースに含まれません。PR のクローズは、報告された問題の修正完了を意味しません。
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
#### 画面共有と接続の安定性
- ブラウザーと TeamSpeak ネイティブクライアント間の画面共有で、接続ネゴシエーションと映像トラックの処理を修正しました。
- チャンネルをすばやく切り替えた際の処理を改善し、クライアント状態の不整合を減らしました。
- 一部スキンコンポーネントの内容表示と KAAK の多言語表示を修正しました。
#### インターフェースの改善
- 音声デバイス名を省略せず表示し、幅が足りない場合は折り返して、長い名前を判別しやすくしました。
- アバターの代替テキストが誤って選択される問題を修正しました。
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
#### より開かれたスキンシステム
@@ -200,9 +255,11 @@ Docker 起動を簡略化し、15秒の接続タイムアウトと継続的な
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
## 最近マージされた貢献
## 貢献者と主な貢献
- GitHub のマージ記録に基づく一覧です。上のバージョン概要には、各リリースに実際に含まれる変更のみを記載しています。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) でブラウザのエラー翻訳を改善し、[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) で拡大縮小、フローティングレイアウト、ホームのフッターを修正。
上流 SDK の作者、マージ済みの GitHub PR、および独立配布のスキンパッケージへ移植された原作の貢献を記載しています。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上流 SDK [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) の作者。WebSpeak の TeamSpeak プロトコル通信を支えるクライアントライブラリを提供。
- [LainHE](https://github.com/LainHE) — [マージ済み PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE)。ブラウザのエラー翻訳、拡大縮小とホームのレイアウト、画面共有のビットレートと視聴者アバター、中継先の検証と再接続、信頼済みプロキシの扱い、接続失敗の通知、音声エラー報告、WebRTC 失敗時のリソース解放を改善。
- [TimmySheep](https://github.com/TimmySheep) — [マージ済み PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep)。既存 TS6 共有の検出、画面比率、モバイル音声・画面点灯・スキンメニュー、ID のチャンネル設定、PWA/テーマ、チャット履歴、メンバー音声状態、マイク権限などに貢献。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネームによる接続に対応し、設定・お気に入り・招待リンクにニックネームの接続先を保持。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) で TeamSpeak の登録済みニックネーム接続と接続先の保持に対応し、[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) で初回接続後の KAAK ワークスペース保持と再接続を改善。[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) と [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) では Discord スキンの原作デザインと実装を提供(コミット名義 **yumi**)。その後、WebSpeak プロジェクトが[独立配布の `.wskin` スキン](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)へ移植。
+70 -11
View File
@@ -4,7 +4,7 @@
## О проекте
Последний выпуск: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
Последний выпуск: [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9).
| Логика | Описание |
| --- | --- |
@@ -14,15 +14,18 @@
## Онлайн-демо
Адрес: <https://webspeak.online>
Адреса:
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
- Шанхай: <https://shanghai.webspeak.online>
- Гонконг: <https://webspeak.online>
Сеть и нагрузка на обоих демо-серверах могут быть нестабильными. Задержки, разрывы или временная недоступность не характеризуют самостоятельное развертывание.
## ✨ Возможности
| Возможность | Описание |
| --- | --- |
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола по версии сервера. |
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
@@ -38,6 +41,26 @@
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
| Развёртывание | Пакеты Windows x64 и Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64. |
## Совместимость версий TeamSpeak
Голосовые соединения используют стандартный клиентский протокол TeamSpeak и не требуют учётных данных Query. Необязательное управление TS использует отдельные данные WebQuery / ServerQuery.
- **TeamSpeak 3**: определение распознаёт ведущую версию `3.x`. Старые версии сервера следует проверять отдельно в конкретной среде: не каждая историческая версия тестировалась независимо.
- **TeamSpeak 6**: поддерживается, включая демонстрацию экрана с нативными клиентами TeamSpeak 6.
- **Автоопределение**: шлюз читает ответ сервера `version` и записывает распознанный протокол в диагностику подключения.
- Шлюз использует upstream SDK 1.0 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak рассчитан на TeamSpeak 3 и 6.
## Необязательное управление TeamSpeak
Панель WebSpeak и голосовые соединения работают независимо от этой функции. В режиме фиксированного сервера откройте `/admin/ts-admin` для настройки управления TS.
1. Включите WebQuery на сервере TS и попросите уполномоченного администратора TS создать API-ключ. Укажите HTTP/HTTPS-адрес WebQuery и ключ. Это Query-служба TS, а не сайт WebSpeak. Поддерживаются TS3 начиная с 3.12 и TS6.
2. ID виртуального сервера `0` выбирает сервер по голосовому порту фиксированной цели. Для ограниченного ключа укажите разрешённый ID. Ключ чтения позволяет просматривать данные; изменения требуют области с правом записи и соответствующих прав TS.
3. Можно выбрать ServerQuery SSH или ServerQuery TCP для TS3. Укажите Query-хост (пустое поле использует фиксированную цель), порт, имя пользователя и пароль; SSH также требует доверенный отпечаток ключа хоста. Это не SSH-вход в операционную систему. TCP не шифруется и подходит только для доверенных сетей. HTTPS-сертификат должен быть доверенным для шлюза.
4. Сохраните и подключитесь или обновите данные. Доступны настройки сервера, управление каналами, перемещение/исключение/блокировка участников, назначение групп и снятие блокировок. Действия требуют подтверждения и проверяются TS; списки обновляются вручную.
Учётные данные хранятся на сервере в зашифрованном виде и не возвращаются API. Сохраняйте базу данных вместе с `master.key`. Ошибка управления не влияет на панель WebSpeak и голос. Блокировка по UID не затрагивает других пользователей с общим IP шлюза.
## 🖼️ Скриншоты интерфейса
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
@@ -82,7 +105,7 @@
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), пакет `@honeybbq/teamspeak@1.0.0-beta.19`. Сборка форка SDK больше не требуется.
## 🚀 Развертывание
@@ -111,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
@@ -121,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 через обратный прокси.
@@ -139,6 +161,41 @@ npm start
<a id="latest-release-notes"></a>
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
#### Новые возможности
- Переход на upstream SDK 1.0.0-beta.19. Обычные голосовые подключения используют актуальный каталог клиентов без разрешений Query на получение списков.
- Добавлен магазин скинов GitHub с установкой, обновлением и управлением доступностью для экземпляра. Discord Voice распространяется отдельно как стандартный пример `.wskin`.
- В режиме фиксированного сервера доступна необязательная панель TS: учётные данные WebQuery, TCP или SSH Query позволяют управлять сервером, каналами, участниками, серверными группами и блокировками.
- Ретрансляторы могут предоставлять браузеру прямую голосовую точку подключения и обслуживать голосовую сессию без лишнего перехода через основной шлюз.
- Добавлены общие интерфейсы сохранения рабочего пространства и переподключения; KAAK использует их и предлагает вход в администрирование, GitHub проекта и группу QQ.
- Поддержаны разделители каналов TeamSpeak: выравнивание, повторяемое заполнение, пустые строки и стандартные линии. Данные оформления доступны скинам.
#### Исправления
- Исправлены размер полноэкранного показа экрана и очистка состояния и ресурсов воспроизведения ушедших участников.
- Успешная блокировка больше не отображается как ошибка; Query-подключения исключены из числа участников, исправлена подпись пароля канала.
- Разделены ошибки разрешений, ограничения частоты и тайм-аута. Ошибка обновления после успешной операции показывается отдельно, чтобы избежать повторного выполнения.
- Добавлена защита от ошибочного распознавания SDK неуспешных HTTP-ответов как успешных результатов WebQuery; исправлена компоновка DC на главной странице, в чате и на узких экранах.
#### Известные проблемы
- Усиление безопасности из [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) не вошло в выпуск; закрытие PR не означает исправления описанных проблем.
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
#### Демонстрация экрана и стабильность соединения
- Исправлены согласование соединения и обработка видеопотока при демонстрации экрана между браузерами и нативными клиентами TeamSpeak.
- Улучшена обработка быстрых переключений каналов, чтобы избежать несогласованного состояния клиента.
- Исправлено отображение содержимого некоторых компонентов скинов и локализации KAAK.
#### Улучшения интерфейса
- Названия аудиоустройств теперь отображаются полностью и переносятся при нехватке места, чтобы длинные названия было легче различать.
- Исправлено случайное выделение текста-заглушки аватара.
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
#### Более открытая система скинов
@@ -200,9 +257,11 @@ npm start
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
## Недавно объединённые вклады
## Участники и вклад в проект
- Список составлен по записям о слиянии на GitHub; сводки выше описывают только изменения, вошедшие в соответствующий релиз.
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) улучшил переводы ошибок браузера; [PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) исправил масштабирование, плавающую компоновку и нижний колонтитул главной страницы.
Список отмечает автора SDK, используемого в основе проекта, вклад через объединённые PR на GitHub и исходные работы, перенесённые в отдельно распространяемые пакеты скинов.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Автор SDK [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), который предоставляет используемый WebSpeak клиент протокола TeamSpeak.
- [LainHE](https://github.com/LainHE) — [объединённые PR #2, #8, #28, #31–#35, #37, #38 и #40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE): переводы ошибок браузера, масштабирование и компоновка главной страницы, битрейт трансляции и аватары зрителей, проверка целей и восстановление ретранслятора, доверенные прокси, передача ошибок подключения, сообщения об ошибках аудио и освобождение ресурсов при сбоях WebRTC.
- [TimmySheep](https://github.com/TimmySheep) — [объединённые PR #13 и #15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep): обнаружение активных трансляций TS6, пропорции экрана, мобильное аудио/подсветка экрана/меню скинов, канал в настройках идентичности, PWA/темы, история чата, состояние аудио участников и разрешение микрофона.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak и сохранение имени цели в настройках, избранном и приглашениях.
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) добавил подключение по зарегистрированным именам TeamSpeak с сохранением имени цели; [PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) улучшил сохранение рабочего пространства KAAK и повторное подключение после первого соединения. [PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) и [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) содержали исходный дизайн и реализацию скина Discord (автор коммитов **yumi**), которые проект WebSpeak перенёс в [отдельно распространяемый скин `.wskin`](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice).
+80 -14
View File
@@ -8,17 +8,18 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
## 在线 Demo
地址:<https://webspeak.online>
- 上海节点:<https://shanghai.webspeak.online>
- 香港节点:<https://webspeak.online>
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
演示站点的网络和负载可能不稳定;延迟、断线或暂时不可用不代表自行部署后的实际表现。
最新版本:[查看本页的 0.2.7 更新日志](#latest-release-notes)。
最新版本:[查看本页的 0.2.9 更新日志](#latest-release-notes)。
## ✨ 特性
| 能力 | 说明 |
| --- | --- |
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并根据服务器报告的版本自动探测协议。 |
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
@@ -34,6 +35,26 @@ WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
## TeamSpeak 版本兼容性
语音连接使用标准 TeamSpeak 客户端协议,无需 Query 凭据。可选的 TS 管理功能使用独立的 WebQuery / ServerQuery 凭据。
- **TeamSpeak 3**:协议识别会读取版本号开头的 `3.x`。并非所有历史服务器版本都经过独立验证,部署旧版本时请针对实际服务器进行测试。
- **TeamSpeak 6**:支持,也支持与 TeamSpeak 6 原生客户端进行屏幕共享。
- **自动探测**:网关读取服务器的 `version` 响应并在连接诊断中记录识别到的协议。
- 网关使用上游 [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) 1.0 SDK;WebSpeak 面向 TeamSpeak 3 和 TeamSpeak 6。
## 可选的 TeamSpeak 管理
WebSpeak 后台和访客语音不依赖此功能。在固定服务器模式下,打开 `/admin/ts-admin`,可集中配置 TS 管理连接。
1. 在 TS 服务端启用 WebQuery,并由有权限的 TS 管理员创建 API Key。填写 WebQuery 的 HTTP/HTTPS 地址和 API Key;地址指向 TS Query 服务,而非 WebSpeak 网页。支持 TS3(3.12+)和 TS6。
2. 虚拟服务器 ID 填 `0` 时,按固定目标的语音端口选择;受限 Key 应填写其被授权的服务器 ID。只读 Key 可查看,修改需要可写作用域及相应的 TS 权限。
3. 也可选择 ServerQuery SSH 或 TS3 ServerQuery TCP,填写 Query 主机(留空沿用固定目标)、Query 端口、用户名和密码;SSH 还需要可信的主机密钥指纹。这是 TS 的 Query 服务,并非服务器操作系统的 SSH。TCP 不加密,仅适合可信网络;HTTPS 证书须受网关信任。
4. 保存后连接或刷新,可查看服务器、频道、成员、服务器组和封禁,执行服务器设置、频道创建/重命名/删除、成员移动/移出/身份封禁、服务器组分配和解封。操作需确认,由 TS 核验权限;列表手动刷新。
凭据仅加密保存在服务端,接口不返回密码或 API Key;备份时同时保留数据库和 `master.key`。管理连接失败不影响 WebSpeak 后台和普通语音。封禁按 UID 创建,避免误封共用网关 IP 的其他用户。
## 🖼️ 界面截图
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
@@ -97,7 +118,7 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
中继实例同时运行 UDP 兼容转发和独立语音网关,不提供访客首页或管理员后台。网关收到用户的入场请求后,会用共享令牌签名并转交一次性语音票据;浏览器随后直接连接中继节点,语音网关再从中继节点连接 TeamSpeak。网页地址仍保持在入口网关,不需要跳转。令牌至少使用 16 个字符的随机值。
#### 源码启动
@@ -105,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' \
@@ -151,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. 访客欢迎页即可选择直连或其中一个中继。
关闭并保存中继配置后,访客页面不会显示中继选项。
@@ -163,12 +193,47 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
- TeamSpeak 协议使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork。
- TeamSpeak 协议使用上游 [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) 发布的 `@honeybbq/teamspeak@1.0.0-beta.19`,不再需要构建项目 SDK fork。
## 🧾 更新日志
<a id="latest-release-notes"></a>
### [v0.2.9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.9) · 2026-10-24
#### 功能增强
- 接入上游 SDK 1.0.0-beta.19,普通语音连接使用客户端实时目录,不再依赖 Query 列表权限。
- 管理员控制台新增 GitHub 皮肤商店,以及按实例管理、更新和启停皮肤的入口;Discord Voice 作为标准 `.wskin` 示例独立分发。
- 指定实例模式支持可选 TS 管理面板,可配置 WebQuery、TCP 或 SSH Query 凭据,管理服务器、频道、成员、服务器组和封禁。
- 中继可配置浏览器直连的语音入口,将语音会话交给中继节点处理,减少网关间的额外转发。
- 提供通用工作区保留与重连接口,KAAK 同步接入,并新增管理员、项目 GitHub 和 QQ 群入口。
- 支持 TeamSpeak 频道分隔栏,包括左中右对齐、重复填充、空白及标准线型;向皮肤开放格式化数据。
#### 问题修复
- 修复屏幕共享播放器的全屏尺寸,以及断线成员的状态、播放资源清理。
- 修复 TS 管理中封禁成功却报错、Query 连接混入成员统计和频道密码标签错误的问题。
- 区分权限、限流和超时提示;操作完成后的刷新失败单独提示,避免用户重复执行操作。
- 防止 SDK 将 HTTP 失败响应误判为 WebQuery 成功;修复 DC 首页、聊天区与窄屏控件布局。
#### 已知问题
- [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 记录的安全加固尚未纳入本版本,关闭该 PR 不代表相关问题已修复。
### [v0.2.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.8) · 2026-10-17
#### 屏幕共享与连接稳定性
- 修复网页与 TeamSpeak 原生客户端之间屏幕共享的协商和视频轨道处理问题。
- 改善快速切换频道时的队列处理,减少客户端状态错乱。
- 修复部分皮肤组件内容和 KAAK 皮肤多语言显示问题。
#### 界面改进
- 音频设备名称会完整显示;空间不足时自动换行,便于区分名称较长的设备。
- 修复头像占位文字被意外选中的问题。
### [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7) · 2026-10-13
#### 更开放的皮肤系统
@@ -252,7 +317,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(推荐)
@@ -292,7 +357,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
@@ -323,9 +387,11 @@ npm start
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
## 近期合并贡献者
## 贡献者与贡献来源
- 以下依据 GitHub 合并记录列出。
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2) 改进浏览器端报错翻译;[PR #8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/8) 修正缩放、浮动布局和首页脚注。
以下列出上游 SDK 作者、已合并的 GitHub PR,以及已移植为独立皮肤包的原始贡献。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
- [LainHE](https://github.com/LainHE) — [已合并 PR #2、#8、#28、#31–#35、#37、#38、#40](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ALainHE),涉及浏览器报错翻译、缩放与首页布局、屏幕共享码率与观看者头像、中继目标校验与异常重连、可信代理校验、连接失败传递、音频故障报告及 WebRTC 失败时的资源清理。
- [TimmySheep](https://github.com/TimmySheep) — [已合并 PR #13、#15–#24](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pulls?q=is%3Apr+is%3Amerged+author%3ATimmySheep),涉及 TS6 既有屏幕共享发现、屏幕比例、移动端语音/常亮/皮肤菜单、身份频道选项、PWA/主题、聊天历史、成员音频状态和麦克风权限等改进。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持通过 TeamSpeak 注册昵称连接,并在设置、收藏和邀请中保留昵称目标。
- [yichen11818](https://github.com/yichen11818) — [PR #25](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/25) 支持 TeamSpeak 注册昵称连接并保留昵称目标;[PR #51](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/51) 改进 KAAK 首次连接后的工作区保留与重连;[PR #27](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/27) 和 [PR #52](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/52) 提供 Discord 皮肤的原始设计与实现(提交署名 **yumi**),后由 WebSpeak 项目移植为[独立分发的 `.wskin` 皮肤](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)。
+60 -2
View File
@@ -1,6 +1,6 @@
# WebSpeak 0.2.7 皮肤系统开发指南
# WebSpeak 0.2.8 皮肤系统开发指南
本文是 WebSpeak 0.2.7 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
本文是 WebSpeak 0.2.8 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 v1/v2 兼容皮肤、v3 声明式开放皮肤和 v4 插件包,以及当前公开数据、宿主动作、授权、校验与开发流程。v4 有界 Wasm 已在生产构建开放;皮肤 JavaScript 仍只校验和缓存,不会执行。本文件是当前包格式和运行时接口的唯一文档来源。
## 目标:皮肤是可移植的外挂包
@@ -32,6 +32,58 @@ v3 保留安全的标准元素和属性白名单;组件可通过完整页面 s
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
### GitHub 皮肤商店分发
管理员在 `/admin/skins` 的“皮肤商店”页安装仓库分发的皮肤;“实例皮肤”页负责导入、启停、删除和设置默认值。安装和更新不改变默认皮肤,更新保留原启停状态。商店网络故障不会影响已安装皮肤。访客仍需自行批准皮肤组件权限,管理员安装不能替访客授权。
官方索引为 [Huddle-Up-Forge/webspeak-skins](https://github.com/Huddle-Up-Forge/webspeak-skins) 的 `master/index.json`。索引仅登记稳定的皮肤 ID 和公开 GitHub 仓库地址,不包含皮肤实现:
```json
{
"schemaVersion": 1,
"skins": [{
"id": "community.discord-voice",
"repository": "https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice"
}]
}
```
每个皮肤仓库的默认分支根目录提供 `skin.json`(位于 `.wskin` **之外**),例如:
```json
{
"schemaVersion": 1,
"id": "community.example-skin",
"name": "Example skin",
"version": "1.0.0",
"author": "Example author",
"license": "CC-BY-4.0",
"description": "A portable WebSpeak skin.",
"minAppVersion": "0.2.8",
"package": {
"ref": "v1.0.0",
"path": "example.wskin",
"sha256": "填写最终归档文件的 64 位小写 SHA-256"
}
}
```
`package.ref` 使用已发布 tag 或完整提交 SHA,`path` 指向该 ref 中的 `.wskin` 文件。推荐 tag 一经发布不再移动。`skin.json` 必须与归档清单的 ID、名称、版本、作者、许可证和最低应用版本一致。版本和最低应用版本使用语义化版本;`description` 必须是字符串,可以留空。仓库无需提供 GitHub 令牌,实例从 GitHub 的公开原始文件服务读取;不支持私有仓库、任意下载域名或重定向。
发布步骤:先构建并用客户端和服务端导入器验证最终归档;计算 SHA-256;提交源码、归档、许可证和 `skin.json`;为这个提交创建版本 tag;最后提交中央索引条目。后续更新只需在皮肤仓库发布新版本并更新默认分支的 `skin.json`,无需同步修改中央索引。安装时服务端重新检查索引及元数据,核对摘要并运行普通 `.wskin` 校验;校验失败不替换实例皮肤。同 ID 已安装且版本相同或更新时,不提供覆盖或降级操作。多个管理员同时修改实例皮肤时,过期的安装请求会被拒绝,需刷新后重试。
仓库地址限定为 `https://github.com/owner/repository`。索引最多 50 项;索引最大 128 KiB,单个 `skin.json` 最大 16 KiB,归档最大 20 MiB,下载有超时限制。商店不执行皮肤构建脚本,也不从仓库加载未打入归档的资源。
### 工作区接口 v1(WebSpeak 0.2.8 当前运行时)
v3/v4 开放皮肤可在 `manifest.json` 中声明 `"workspace": { "apiVersion": 1, "mode": "persistent" }`。未声明时保留原先的首页流程。该通用接口不识别皮肤 ID,也不授予额外网络或存储权限;皮肤包本身不能读写此偏好。旧运行时不认识该字段或权限时会拒绝导入,不能仅凭应用版本号认定支持;使用它的包需要 `minAppVersion: "0.2.8"` 及工作区接口 v1。
首次使用仍显示连接表单;只有成功连接才记录 `hasConnected`。旧的成功连接历史会迁移为已使用状态,只有昵称或失败尝试不算。启用此策略的皮肤在主动断开或刷新回访后仍进入工作区,但不会自动连接、采集麦克风或切换服务器。普通回访可由宿主恢复最近目标;显式邀请、目标或频道链接优先。切换到未声明策略的皮肤恢复其原有流程,清除本地数据会重置此记录。
可信控件 `voice.connection-status` 需要 `session.status.read` 与 `voice.connect`,显示本地化的连接/失败状态、可编辑昵称与重连按钮;忙碌时禁用重复提交,服务器密码和新增服务器对话框仍由宿主管理。公开部件为 `voice.connection-status`、`voice.connection-status.message`、`voice.connection-status.nickname`、`voice.connection-status.nickname.input`、`voice.connection-status.reconnect`。皮肤负责这些部件的位置、响应式布局和外观。
声明式动作 `voice.connect` 使用同名权限且不接受参数;它只在明确可信点击后连接宿主当前选定的目标,不能携带地址、密码、身份材料、邀请令牌或自动执行。服务器配置和身份未就绪、正在连接/重连、已经连接或对话框尚待处理时,宿主拒绝重复发起。它和既有的 `quickServers.switch`、服务器栏加号共用宿主连接流程;异步读取浏览器已保存密码不会被误判为连接失败。
## 包结构
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
@@ -137,6 +189,10 @@ components.json 顶层接受 schemaVersion 1、2 或 3 和 components 数组。s
申请 `session.channels.read` 的 `session.channels` 列表还提供 `memberCount`、两位数显示用的 `memberCountLabel`、`maxClients` 和 `maxClientsLimited`。后两个字段仅在 TeamSpeak 返回有效上限数据时出现;`maxClientsLimited: false` 表示频道不限人数。它们与频道树一起属于公开只读数据,不会授予服务器写入能力。
频道显示接口增补(0.2.8):同一权限下新增 `displayName`、`isSpacer`、`spacerAlignment` 与 `spacerStyle`,声明式 v3 和 Wasm v4 均可读取。`name` 始终保留服务器原名,`displayName` 仅对永久、顶层且名称以 `[spacer…]`、`[lspacer…]`、`[cspacer…]`、`[rspacer…]` 或 `[*spacer…]` 开头的频道移除前缀(大小写不敏感,省略或自定义标识均可)。分隔栏的 `spacerAlignment` 为 `left`、`center`、`right` 或 `repeat`;`spacerStyle` 为 `text`、`solid`、`dashed`、`dotted`、`dash-dot` 或 `dash-dot-dot`,五种线型对应 `___`、`---`、`...`、`-.-`、`-..`。普通频道的 `displayName` 等于 `name`、`isSpacer: false`、两个格式字段为空字符串。旧运行时可能不含新增字段;兼容包应回退到 `name`,不能只凭相同的 0.2.8 版本号推断字段存在。分隔栏仍为真实 TS 频道,不增加加入限制,不隐藏其中的成员或子频道;管理编辑继续使用原名。
宿主 `voice.channel-tree` 与 `voice.channel-panel` 自动使用上述显示规则;分隔栏隐藏普通频道图标和人数,不显示空成员提示。新增稳定部件 `voice.channel-spacer`,提供 `data-alignment` 与 `data-spacer-style` 属性;频道树行 `voice.channel-tree.row` 和成员面板标题 `voice.channel-group.heading` 在分隔栏上提供 `data-spacer="true"`。颜色和字体继承皮肤,文字及重复填充在可用宽度内裁剪,空文本保留分隔间距。皮肤无需新增权限或修改传输逻辑。
```json
{
"schemaVersion": 2,
@@ -261,6 +317,8 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
声明式 `components.json` 也可以显示皮肤自己的多语言文案。文本节点、字符串属性,以及组件 `name` / `accessibleName` 可使用 `{{skin.messages.<key>}}` 绑定。WebSpeak 会把皮肤 `content.json` 中 `defaultLocale`、当前语言代码和完整语言代码的 `messages` 合并到 `skin.messages`,当前语言内容覆盖默认文案;这个绑定适用于首页、语音页和 Demo 页的声明式组件。没有匹配的 key 会显示为空字符串,因此组件引用的 key 应在默认语言中提供。该本地化路径只提供皮肤包自身的文案,不会扩展 Wasm 插件的权限化运行时数据。
```json
{
"defaultLocale": "en",
+21
View File
@@ -0,0 +1,21 @@
# Discord Voice skin
This example turns the Discord-inspired voice interface into a portable WebSpeak `open-skin` v3 package. Its page structure is declared in `components.json`; its palette and layout are in `skin.css`; localized skin copy lives in `content.json`.
The independent distribution repository is [Huddle-Up-Forge/webspeak-skin-discord-voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice). It is the first entry in the [WebSpeak skin store index](https://github.com/Huddle-Up-Forge/webspeak-skins). Administrators can install it from **Skins → Skin store**, then manage availability and the instance default under **Instance skins**. Version 1.0.11 requires WebSpeak 0.2.8 with the current public skin API.
The package uses WebSpeak's public TeamSpeak widgets for channel navigation, member cards, chat, audio controls, screen sharing, performance status, server switching and invite links. That keeps connection logic and trusted actions in WebSpeak while the skin controls the visible layout. The Discord visual language and color palette are retained, while host-owned controls keep their supported behavior and accessibility.
The skin requires explicit approval to replace the home and voice pages. It does not include JavaScript, depend on Vue internals, or change WebSpeak runtime code. It can be imported from `/admin/skins` as an ordinary `.wskin` package.
- Source: [discord-voice](./discord-voice/)
- Package: [discord-voice.wskin](./discord-voice.wskin)
- Format and runtime contract: [skin development guide](../SKIN_DEVELOPMENT.md)
Build the package from the repository root with:
```powershell
node web/scripts/build-discord-voice-skin.mjs
```
Native fullscreen and the bespoke screen-share settings shortcut from the built-in Vue version are not part of the current public skin API. The standard package keeps screen sharing reachable through WebSpeak's trusted screen-share controls and uses the standard audio settings panel.
+8 -2
View File
@@ -14,7 +14,7 @@ While the WebSpeak performance card is sampling, its refresh icon spins to show
KAAK is a schema v3 open-skin package with full connection and voice-workspace surfaces. Its desktop voice page follows KOOK's proportions: an 86px server rail with 58px icons and 18px vertical spacing, a 290px channel pane, a 40px top bar, a central participant stage, right-side chat attached to the current voice channel, and a lower-left voice dock. The server rail uses KOOK's rounded-square silhouette, a 2px green active outline and left-edge marker, with neutral fallback tiles and the muted purple active tile from the reference. The identity tile stays pinned at the bottom with a 54px circular monogram and connection-aware online dot; the server list scrolls when the window is short. The host provides a stable color-tone value derived only from the privacy-safe label, but the rail keeps the KOOK neutral tile treatment rather than exposing those tones. The KOOK voice room is the point-to-point visual reference: composition, member presentation, styling, and motion should be compared directly, rather than treating matching component types or approximate placement as sufficient. The left tree contains the TeamSpeak voice channels only; KOOK's separate text-channel group is outside this pass because TeamSpeak has no equivalent channel type. The current voice channel's text chat remains on the right. Closing it hides the entire panel, expands the participant stage, and leaves a reopen button in the stage heading; this happens without leaving the voice room. Its header uses the `#` channel mark and an unobtrusive close control; the composer sits at the bottom edge. Messages use author monograms, a separate identity/time line, and readable message text. The central stage uses WebSpeak's reusable member-card widget so available TeamSpeak profile avatars appear inside KAAK's participant tiles; the tiles use a wide 1.82:1 layout with a responsive grid to match KOOK's participant presentation. Member names stay hidden at rest while chat is open and fade upward into the lower-left label on hover; they remain visible while chat is collapsed. KAAK's CSS adds hover depth and a smoothly transitioning speaking ring driven by live voice state. Active screen shares appear on member cards with a live badge and a themed watch action; the share player remains a WebSpeak host component. The dock retains WebSpeak's trusted connection-quality, audio, and disconnect controls. Input/output volume buttons open hover or keyboard-focus panels with live numeric levels; sliders use a skin-colored progress track, a distinct thumb, and visible focus feedback. Audio input and output devices use a reusable keyboard-accessible picker with a scrollable option list, selected/highlighted states, and an animated chevron; KAAK styles the trigger and open list. The connection surface, voice workspace, and audio settings share KOOK's PingFang SC-first font stack; audio settings use 16px/600 section headings and observed 14px/400 field labels. Audio sliders use a 16px thumb with hover/focus feedback. The performance card opens with a short entrance motion and readable network/audio metrics. No real device, volume, or microphone state is changed during visual checks. The roster shows connected TeamSpeak clients only; it does not invent an offline list. Channel selection is single-click; joining is double-click. The narrow layout keeps the host's mobile controls available while retaining readable member tiles.
The single TeamSpeak voice-channel group in the left tree collapses and expands with a short two-way height and fade transition like KOOK's voice group; the separate KOOK text-channel group remains outside this pass. A first click selects a channel and reveals a brief “双击加入” hint; the hint disappears on the active room. The current voice-room heading keeps the channel name and live member count visible above the participant stage while the attached chat is expanded, matching KOOK's room view. Member cards expose WebSpeak's trusted member-actions menu from a small hover or keyboard-focus control; desktop cards also open it on right-click, and touch layouts keep the control visible. KAAK gives the host menu KOOK's compact dark panel, separated volume section, and highlighted action rows while keeping WebSpeak's own individual-volume slider and member actions; it does not add KOOK menu actions or skin-side audio logic.
The single TeamSpeak voice-channel group in the left tree collapses and expands with a short two-way height and fade transition like KOOK's voice group; the separate KOOK text-channel group remains outside this pass. A first click selects a channel and reveals a brief “双击加入” hint; the hint disappears on the active room. The current voice-room heading keeps the channel name and live member count visible above the participant stage while the attached chat is expanded, matching KOOK's room view. Member cards expose WebSpeak's trusted member-actions menu from a small hover or keyboard-focus control; desktop cards also open it on right-click, and touch layouts keep the control visible. KAAK gives the host menu KOOK's compact dark panel, separated volume section, and highlighted action rows while keeping WebSpeak's own individual-volume slider and member actions; it does not add KOOK menu actions or skin-side audio logic. While a screen-share peer is active, the voice-status panel also displays its browser-side video codec and transport statistics.
The design target is the voice-client portion of KOOK, as requested by the project owner. It does not include discovery, companion/party, event, store, advertising, administrator, or other service-operator pages. It does not add a KOOK account flow, direct messages, server administration, or channels absent from the connected TeamSpeak server. The voice performance card also closes on outside click or Escape; Escape returns focus to its trigger, and its entrance/exit motion respects reduced-motion preferences.
@@ -28,9 +28,15 @@ The existing WebSpeak noise-suppression switch is available in the audio setting
The owner authorized inspection of the first two voice rooms in the KOOK server. Both rooms were entered and viewed; the microphone remained off and no message was sent. The in-room view confirmed a single large participant tile in the center, a separate right-side panel for the active voice channel's text chat, a narrow server rail, grouped voice channels, and a compact voice-control dock near the lower left. The chat was empty, so no message contents were recorded. Server/room identifiers and member names were not recorded.
## Returning to the workspace
KAAK 3.1.127 requires WebSpeak 0.2.8 with workspace API v1. Its manifest opts into the generic persistent workspace policy: first-time visitors keep the connection home until a successful voice connection; returning visitors and disconnected users retain the workspace and server rail. Restoring the workspace never starts a connection or captures the microphone. The host restores the recent target only for ordinary visits, preserving explicit invitation and target links. Clearing browser data resets this history.
The permission-gated `voice.connection-status` host widget provides the connection state, nickname and explicit reconnect button beside server navigation at desktop and narrow widths. Open-mode server switching and adding servers reuse the host connection flow, including saved-password lookup and trusted password prompts; fixed mode retains its restrictions. All KAAK layout and styling remain in the package.
## Components and permissions
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. The performance panel hides only share transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK 3.1.78 keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
The connection page and voice workspace are full-page declarative surfaces in [components.json](./kaak-voice/components.json). The voice surface requests only the capabilities it uses: visible server shortcuts, channel and member data, cached profile-avatar display inside the trusted member-card widget, channel joining, channel chat, voice status, microphone/output controls, whisper controls, disconnect, and screen-share status/read/control. Its member-card widget explicitly enables share status and watch actions; the KAAK dock uses the host's screen-share control. When a screen-share peer is active, the performance panel shows browser-side video codec and transport metrics. The host renders trusted connection, language, skin, and audio controls. KAAK keeps the shared-screen player inside the central voice-stage column with an explicit responsive height, so the player cannot collapse when the host applies its inline video sizing; member cards scroll in the remaining area. The full source image remains visible with black letterboxing. Server and channel password prompts use the compact dark KAAK dialog style while retaining WebSpeak's trusted password, error, cancel, and retry behavior. It rechecks permissions and connection state when each action runs; approval is local to this skin version and can be revoked from the host access control.
The server header uses the live, privacy-filtered TeamSpeak server label and a trusted `voice.server-switcher` menu backed by favorites and recent connections. Its click handler reuses WebSpeak's existing connection flow with an opaque local ID; addresses and credentials never enter skin data. The left panel uses the trusted `voice.channel-tree` widget to retain TeamSpeak channel nesting, member counts and capacity, available avatars, and mute/speaking/away states. Expanding a branch is local UI state, a single click selects a channel, and double-click joins it. With `memberActions` enabled, right-clicking another member row opens WebSpeak's existing host-owned action menu. With `memberDragDrop` enabled, another member can be dragged onto a different channel row; the member row and target channel receive visual feedback, and the host reuses its existing move-client operation. Both options default off for other skins. The skin does not add KOOK's separate text-channel list.
Binary file not shown.
+451
View File
@@ -0,0 +1,451 @@
{
"schemaVersion": 3,
"components": [
{
"id": "discord-home",
"name": "{{skin.messages.homeComponentName}}",
"page": "home",
"mode": "surface",
"accessibleName": "{{skin.messages.homeAccessibleName}}",
"permissions": ["ui.surface.replace", "session.status.read"],
"actions": {},
"root": {
"tag": "main",
"part": "home",
"className": "join-page",
"children": [
{
"tag": "header",
"part": "home-header",
"className": "join-header",
"children": [
{
"tag": "div",
"className": "brand-lockup",
"children": [
{ "tag": "span", "className": "dc-brand-mark", "children": [{ "text": "W" }] },
{
"tag": "div",
"children": [
{ "tag": "strong", "children": [{ "text": "WebSpeak" }] },
{ "tag": "small", "children": [{ "text": "{{skin.messages.tagline}}" }] }
]
}
]
},
{
"tag": "div",
"part": "home-header-tools",
"className": "join-header-tools",
"children": [
{ "widget": "home.social-links", "part": "social-links" },
{ "tag": "div", "className": "workspace-skin-switcher", "children": [{ "widget": "app.skin-switcher", "part": "skin-switcher" }] },
{ "tag": "div", "className": "workspace-language", "children": [{ "widget": "app.language-switcher", "part": "language-switcher" }] }
]
}
]
},
{
"tag": "main",
"part": "home-content",
"className": "join-content",
"children": [
{
"tag": "section",
"part": "home-hero",
"className": "join-copy",
"children": [
{
"tag": "div",
"part": "home-hero-eyebrow",
"className": "eyebrow",
"children": [
{ "tag": "span", "className": "eyebrow-dot" },
{ "text": "{{skin.messages.eyebrow}}" }
]
},
{
"tag": "h1",
"part": "home-hero-title",
"children": [
{ "text": "{{skin.messages.heroTitle}}" },
{ "tag": "em", "children": [{ "text": "{{skin.messages.heroAccent}}" }] }
]
},
{
"tag": "p",
"part": "home-hero-description",
"className": "join-description",
"children": [{ "text": "{{skin.messages.heroDescription}}" }]
},
{
"tag": "div",
"part": "home-features",
"className": "promise-list",
"children": [
{
"tag": "div",
"part": "home-feature",
"className": "promise-item",
"children": [
{ "tag": "span", "className": "promise-icon mint", "children": [{ "text": "01" }] },
{ "tag": "span", "children": [
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureOneTitle}}" }] },
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureOneBody}}" }] }
] }
]
},
{
"tag": "div",
"part": "home-feature",
"className": "promise-item",
"children": [
{ "tag": "span", "className": "promise-icon sand", "children": [{ "text": "02" }] },
{ "tag": "span", "children": [
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureTwoTitle}}" }] },
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureTwoBody}}" }] }
] }
]
},
{
"tag": "div",
"part": "home-feature",
"className": "promise-item",
"children": [
{ "tag": "span", "className": "promise-icon mint", "children": [{ "text": "03" }] },
{ "tag": "span", "children": [
{ "tag": "b", "children": [{ "text": "{{skin.messages.featureThreeTitle}}" }] },
{ "tag": "small", "children": [{ "text": "{{skin.messages.featureThreeBody}}" }] }
] }
]
}
]
},
{ "tag": "div", "className": "dc-visitor-slot", "children": [{ "widget": "home.visitor-count", "part": "visitor-count" }] },
{ "tag": "div", "className": "announcement-wrap", "children": [{ "widget": "home.server-announcement", "part": "announcement" }] }
]
},
{
"tag": "section",
"part": "home-join-card",
"className": "join-card",
"children": [
{ "tag": "div", "className": "join-card-effects", "attributes": { "aria-hidden": "true" }, "children": [
{ "tag": "span", "className": "join-card-waveform", "children": [
{ "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }, { "tag": "i" }
] },
{ "tag": "span", "className": "join-card-sonar", "children": [{ "tag": "i" }, { "tag": "i" }, { "tag": "i" }] }
] },
{ "tag": "h2", "part": "home-join-title", "children": [{ "text": "{{skin.messages.connectTitle}}" }] },
{ "tag": "p", "part": "home-join-description", "className": "card-lead", "children": [{ "text": "{{skin.messages.connectDescription}}" }] },
{ "widget": "home.connection-status", "part": "connection-status" },
{ "widget": "home.connection-form", "part": "connection-form" },
{ "tag": "p", "part": "home-security-note", "className": "join-meta", "children": [{ "text": "{{skin.messages.securityNote}}" }] }
]
}
]
},
{
"tag": "footer",
"part": "home-footer",
"className": "join-footer",
"children": [
{ "tag": "span", "children": [{ "text": "WebSpeak" }] },
{ "tag": "span", "className": "footer-separator", "children": [{ "text": "·" }] },
{ "tag": "span", "children": [{ "text": "TeamSpeak" }] },
{ "tag": "span", "className": "footer-spacer" },
{ "tag": "span", "children": [{ "text": "{{skin.messages.footerNote}}" }] }
]
}
]
}
},
{
"id": "discord-workspace",
"name": "{{skin.messages.voiceComponentName}}",
"page": "voice",
"mode": "surface",
"accessibleName": "{{skin.messages.voiceAccessibleName}}",
"stateScope": "session.status.channelId",
"permissions": [
"ui.surface.replace",
"session.status.read",
"session.invite.copy",
"session.channels.read",
"session.members.read",
"session.memberAvatars.read",
"session.channel.join",
"servers.quickList.read",
"servers.quickList.switch",
"chat.channel.read",
"chat.channel.send",
"audio.status.read",
"audio.microphone.control",
"audio.output.control",
"audio.settings.open",
"voice.disconnect",
"voice.screenShare.status.read",
"voice.screenShare.read",
"voice.screenShare.control",
"voice.whisper.status.read",
"voice.whisper.control"
],
"actions": {
"switch-server": { "type": "quickServers.switch", "args": { "quickServerId": "{{server.id}}" } },
"copy-invite-link": { "type": "session.copyInviteLink", "args": {} },
"stop-screen-share": { "type": "voice.stopScreenShare", "args": {} },
"toggle-accompaniment": { "type": "audio.toggleAccompaniment", "args": {} },
"open-audio-settings": { "type": "audio.openSettings", "args": {} },
"toggle-chat": { "type": "ui.toggleState", "args": { "key": "chatopen" } }
},
"state": { "chatopen": true },
"root": {
"tag": "main",
"part": "voice-shell",
"className": "app-shell discord-app-shell",
"children": [
{
"tag": "nav",
"part": "server-rail",
"className": "dc-rail",
"attributes": { "aria-label": "{{skin.messages.serverRailLabel}}" },
"children": [
{
"tag": "div",
"className": "dc-rail-list",
"children": [
{
"tag": "div",
"part": "quick-server-item",
"className": "dc-rail-item",
"repeat": { "path": "servers.quickList", "as": "server" },
"children": [
{ "tag": "span", "className": "dc-rail-pill", "attributes": { "aria-hidden": "true" } },
{
"tag": "button",
"part": "quick-server",
"className": "dc-rail-icon dc-rail-server",
"attributes": {
"type": "button",
"aria-label": "{{skin.messages.switchServer}} {{server.label}}",
"aria-pressed": "{{server.current}}",
"aria-disabled": "{{server.switchRestricted}}",
"title": "{{server.switchTitle}}"
},
"events": { "click": "switch-server" },
"children": [{ "tag": "span", "className": "dc-rail-avatar", "children": [{ "text": "{{server.monogram}}" }] }]
},
{ "tag": "span", "className": "dc-rail-tooltip", "attributes": { "role": "tooltip" }, "children": [{ "tag": "strong", "children": [{ "text": "{{server.label}}" }] }] },
{ "tag": "span", "className": "dc-rail-fav", "when": { "path": "server.favorite", "equals": true }, "attributes": { "aria-label": "{{skin.messages.favoriteServer}}" }, "children": [{ "text": "★" }] }
]
}
]
}
]
},
{
"tag": "aside",
"part": "member-panel",
"className": "dc-sidebar",
"children": [
{
"tag": "header",
"className": "dc-server-header",
"children": [
{ "tag": "strong", "children": [{ "text": "{{session.status.serverLabel}}" }] },
{
"tag": "button",
"part": "invite-copy",
"className": "dc-header-icon",
"attributes": { "type": "button", "aria-label": "{{skin.messages.copyInvite}}", "title": "{{skin.messages.copyInvite}}" },
"events": { "click": "copy-invite-link" },
"children": [{ "text": "↗" }]
}
]
},
{
"tag": "div",
"className": "dc-sidebar-scroll",
"children": [
{ "tag": "div", "className": "dc-category", "children": [{ "text": "{{skin.messages.voiceChannels}}" }] },
{ "tag": "div", "className": "dc-channel-list", "children": [{ "widget": "voice.channel-tree", "part": "channel-tree", "options": { "layout": "server-sidebar", "memberActions": true, "memberDragDrop": true } }] }
]
},
{
"tag": "section",
"part": "connected-status",
"className": "dc-connected",
"when": { "path": "session.status.connected", "equals": true },
"children": [
{
"tag": "div",
"className": "dc-connected-row",
"children": [
{ "tag": "div", "className": "dc-connected-copy", "children": [
{ "tag": "strong", "children": [{ "text": "{{skin.messages.voiceConnected}}" }] },
{ "tag": "small", "children": [{ "text": "{{session.status.channelName}}" }] }
] },
{ "tag": "div", "className": "dc-performance", "children": [{ "widget": "voice.performance-panel", "part": "performance-panel" }] }
]
},
{ "tag": "div", "className": "dc-connected-actions", "children": [{ "widget": "voice.connection-controls", "part": "connection-controls" }] }
]
},
{
"tag": "div",
"part": "audio-dock",
"className": "dc-user-bar",
"children": [
{ "tag": "div", "className": "dc-user-info", "children": [
{ "tag": "span", "className": "dc-user-avatar", "children": [{ "tag": "i", "children": [{ "text": "{{session.status.userName}}" }] }] },
{ "tag": "span", "className": "dc-user-text", "children": [{ "tag": "strong", "children": [{ "text": "{{session.status.userName}}" }] }, { "tag": "small", "children": [{ "text": "{{skin.messages.online}}" }] }] }
] },
{ "tag": "div", "className": "dc-user-actions", "children": [
{ "widget": "voice.audio-controls", "part": "audio-controls" },
{
"tag": "button",
"part": "mobile-audio-settings",
"className": "dc-mobile-audio-settings",
"attributes": { "type": "button", "aria-label": "{{skin.messages.audioSettings}}", "title": "{{skin.messages.audioSettings}}" },
"events": { "click": "open-audio-settings" },
"children": [{
"tag": "svg",
"attributes": { "width": 20, "height": 20, "viewbox": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke-width": 1.8, "stroke-linecap": "round", "aria-hidden": "true" },
"children": [
{ "tag": "path", "attributes": { "d": "M4 6h4m4 0h8M4 12h8m4 0h4M4 18h2m4 0h10" } },
{ "tag": "circle", "attributes": { "cx": 10, "cy": 6, "r": 2 } },
{ "tag": "circle", "attributes": { "cx": 14, "cy": 12, "r": 2 } },
{ "tag": "circle", "attributes": { "cx": 8, "cy": 18, "r": 2 } }
]
}]
}
] }
]
}
]
},
{
"tag": "section",
"part": "workspace",
"className": "dc-stage",
"children": [
{
"tag": "header",
"part": "voice-header",
"className": "dc-stage-header",
"children": [
{ "tag": "div", "className": "dc-stage-title", "children": [{ "tag": "h2", "children": [{ "text": "{{session.status.channelName}}" }] }] },
{
"tag": "div",
"part": "header-actions",
"className": "dc-stage-header-actions",
"children": [
{ "tag": "div", "className": "workspace-skin-switcher", "children": [{ "widget": "app.skin-switcher", "part": "skin-switcher" }] },
{ "tag": "div", "className": "workspace-language", "children": [{ "widget": "app.language-switcher", "part": "language-switcher" }] },
{
"tag": "button",
"part": "chat-toggle",
"className": "dc-stage-icon",
"attributes": { "type": "button", "aria-expanded": "{{state.chatopen}}", "aria-label": "{{skin.messages.toggleChat}}", "title": "{{skin.messages.toggleChat}}" },
"events": { "click": "toggle-chat" },
"children": [{ "text": "#" }]
}
]
}
]
},
{ "tag": "div", "className": "dc-stage-notices" },
{
"tag": "div",
"part": "voice-activity",
"className": "dc-stage-canvas",
"children": [
{
"tag": "div",
"className": "dc-stage-grid",
"children": [
{ "widget": "voice.screen-share-player", "part": "screen-share-player" },
{ "widget": "voice.member-cards", "part": "member-cards", "options": { "screenShare": true, "memberActions": true } },
{
"tag": "button",
"part": "invite-tile",
"className": "dc-invite-tile",
"attributes": { "type": "button", "aria-label": "{{skin.messages.invitePeople}}" },
"events": { "click": "copy-invite-link" },
"children": [{ "tag": "strong", "children": [{ "text": "{{skin.messages.invitePeople}}" }] }]
}
]
},
{ "widget": "voice.whisper-controls", "part": "whisper-controls" }
]
},
{
"tag": "footer",
"className": "dc-stage-controls",
"attributes": { "aria-label": "{{skin.messages.voiceControls}}" },
"children": [
{ "tag": "div", "className": "dc-stage-controls-side" },
{
"tag": "div",
"className": "dc-stage-controls-main",
"children": [
{
"tag": "div",
"className": "dc-stage-pill",
"children": [
{ "widget": "voice.screen-share-start", "part": "screen-share-start", "when": { "path": "screenShare.status.active", "equals": false } },
{
"tag": "button",
"part": "screen-share-stop",
"className": "dc-stage-btn",
"when": { "path": "screenShare.status.active", "equals": true },
"attributes": { "type": "button", "aria-pressed": "true", "aria-label": "{{skin.messages.stopScreenShare}}", "title": "{{skin.messages.stopScreenShare}}" },
"events": { "click": "stop-screen-share" },
"children": [{ "text": "▣" }]
},
{
"tag": "button",
"part": "accompaniment-toggle",
"className": "dc-stage-btn",
"attributes": { "type": "button", "aria-label": "{{skin.messages.toggleAccompaniment}}", "title": "{{skin.messages.toggleAccompaniment}}" },
"events": { "click": "toggle-accompaniment" },
"children": [{ "text": "♫" }]
}
]
}
]
},
{ "tag": "div", "className": "dc-stage-controls-side end" }
]
}
]
},
{
"tag": "aside",
"part": "chat-panel",
"className": "dc-chat",
"when": { "path": "state.chatopen", "equals": true },
"children": [
{
"tag": "header",
"className": "dc-chat-header",
"children": [
{ "tag": "div", "className": "dc-chat-title", "children": [{ "tag": "strong", "children": [{ "text": "{{session.status.channelName}}" }] }] },
{
"tag": "button",
"part": "chat-close",
"className": "dc-stage-icon",
"attributes": { "type": "button", "aria-label": "{{skin.messages.closeChat}}", "title": "{{skin.messages.closeChat}}" },
"events": { "click": "toggle-chat" },
"children": [{ "text": "×" }]
}
]
},
{ "widget": "voice.chat-panel", "part": "chat", "className": "dc-chat-body" }
]
}
]
}
}
]
}
+190
View File
@@ -0,0 +1,190 @@
{
"defaultLocale": "en",
"locales": {
"en": {
"messages": {
"homeComponentName": "Discord-style connection home",
"homeAccessibleName": "Discord-style WebSpeak connection page",
"voiceComponentName": "Discord-style voice workspace",
"voiceAccessibleName": "Discord-style WebSpeak voice workspace",
"tagline": "YOUR VOICE, EVERYWHERE.",
"eyebrow": "VOICE, TOGETHER",
"heroTitle": "Your people.",
"heroAccent": "Your voice.",
"heroDescription": "Join your TeamSpeak community from the browser, with the controls you already know.",
"featureOneTitle": "No client install",
"featureOneBody": "Connect directly from your browser.",
"featureTwoTitle": "Low-latency voice",
"featureTwoBody": "Use browser audio with your TeamSpeak server.",
"featureThreeTitle": "One familiar space",
"featureThreeBody": "Keep channels, members and chat together.",
"connectTitle": "Connect to a TeamSpeak server",
"connectDescription": "Enter a server address to join voice.",
"securityNote": "Your connection and identity stay under WebSpeak's control.",
"footerNote": "Voice in your browser",
"serverRailLabel": "Saved and recent servers",
"switchServer": "Switch to",
"favoriteServer": "Saved server",
"copyInvite": "Copy invite link",
"voiceChannels": "VOICE CHANNELS",
"voiceConnected": "VOICE CONNECTED",
"online": "Online",
"audioSettings": "Audio settings",
"toggleChat": "Toggle channel chat",
"invitePeople": "Invite people",
"closeChat": "Close chat",
"voiceControls": "Voice controls",
"stopScreenShare": "Stop screen sharing",
"toggleAccompaniment": "Toggle accompaniment"
}
},
"zh-CN": {
"messages": {
"homeComponentName": "Discord 风格连接首页",
"homeAccessibleName": "Discord 风格 WebSpeak 连接页",
"voiceComponentName": "Discord 风格语音工作区",
"voiceAccessibleName": "Discord 风格 WebSpeak 语音工作区",
"tagline": "你的声音,随时随地。",
"eyebrow": "一起语音",
"heroTitle": "和熟悉的人,",
"heroAccent": "畅快交流。",
"heroDescription": "在浏览器中加入你的 TeamSpeak 社区,使用熟悉的语音控制。",
"featureOneTitle": "无需安装客户端",
"featureOneBody": "直接从浏览器连接。",
"featureTwoTitle": "低延迟语音",
"featureTwoBody": "通过浏览器连接 TeamSpeak 服务器。",
"featureThreeTitle": "熟悉的语音空间",
"featureThreeBody": "频道、成员和聊天一目了然。",
"connectTitle": "连接 TeamSpeak 服务器",
"connectDescription": "填写服务器地址即可加入语音。",
"securityNote": "连接和身份信息由 WebSpeak 安全管理。",
"footerNote": "在浏览器中语音聊天",
"serverRailLabel": "收藏和最近连接的服务器",
"switchServer": "切换到",
"favoriteServer": "已收藏的服务器",
"copyInvite": "复制邀请链接",
"voiceChannels": "语音频道",
"voiceConnected": "语音已连接",
"online": "在线",
"audioSettings": "音频设置",
"toggleChat": "打开或关闭频道聊天",
"invitePeople": "邀请成员",
"closeChat": "关闭聊天",
"voiceControls": "语音控制",
"stopScreenShare": "停止屏幕共享",
"toggleAccompaniment": "切换伴奏"
}
},
"de": {
"messages": {
"homeComponentName": "Discord-inspirierte Verbindungsseite",
"homeAccessibleName": "Discord-inspirierte WebSpeak-Verbindungsseite",
"voiceComponentName": "Discord-inspirierter Sprachbereich",
"voiceAccessibleName": "Discord-inspirierter WebSpeak-Sprachbereich",
"tagline": "DEINE STIMME, ÜBERALL.",
"eyebrow": "ZUSAMMEN SPRECHEN",
"heroTitle": "Deine Leute.",
"heroAccent": "Deine Stimme.",
"heroDescription": "Tritt deiner TeamSpeak-Community direkt im Browser bei.",
"featureOneTitle": "Keine Installation",
"featureOneBody": "Verbinde dich direkt im Browser.",
"featureTwoTitle": "Sprachkommunikation mit geringer Latenz",
"featureTwoBody": "Nutze Browser-Audio mit deinem TeamSpeak-Server.",
"featureThreeTitle": "Ein vertrauter Bereich",
"featureThreeBody": "Kanäle, Mitglieder und Chat an einem Ort.",
"connectTitle": "Mit einem TeamSpeak-Server verbinden",
"connectDescription": "Gib die Serveradresse ein, um beizutreten.",
"securityNote": "WebSpeak schützt deine Verbindung und Identität.",
"footerNote": "Sprache im Browser",
"serverRailLabel": "Gespeicherte und zuletzt verwendete Server",
"switchServer": "Wechseln zu",
"favoriteServer": "Gespeicherter Server",
"copyInvite": "Einladungslink kopieren",
"voiceChannels": "SPRACHKANÄLE",
"voiceConnected": "SPRACHE VERBUNDEN",
"online": "Online",
"audioSettings": "Audioeinstellungen",
"toggleChat": "Kanalchat umschalten",
"invitePeople": "Mitglieder einladen",
"closeChat": "Chat schließen",
"voiceControls": "Sprachsteuerung",
"stopScreenShare": "Bildschirmfreigabe beenden",
"toggleAccompaniment": "Begleitung umschalten"
}
},
"ru": {
"messages": {
"homeComponentName": "Главная WebSpeak в стиле Discord",
"homeAccessibleName": "Страница подключения WebSpeak в стиле Discord",
"voiceComponentName": "Голосовое пространство в стиле Discord",
"voiceAccessibleName": "Голосовое пространство WebSpeak в стиле Discord",
"tagline": "ТВОЙ ГОЛОС — ВЕЗДЕ.",
"eyebrow": "ОБЩАЙТЕСЬ ВМЕСТЕ",
"heroTitle": "Твои друзья.",
"heroAccent": "Твой голос.",
"heroDescription": "Подключайтесь к сообществу TeamSpeak прямо в браузере.",
"featureOneTitle": "Без установки клиента",
"featureOneBody": "Подключайтесь прямо из браузера.",
"featureTwoTitle": "Голос с низкой задержкой",
"featureTwoBody": "Используйте браузерное аудио с сервером TeamSpeak.",
"featureThreeTitle": "Привычное пространство",
"featureThreeBody": "Каналы, участники и чат в одном месте.",
"connectTitle": "Подключиться к серверу TeamSpeak",
"connectDescription": "Введите адрес сервера, чтобы подключиться.",
"securityNote": "WebSpeak защищает подключение и данные личности.",
"footerNote": "Голосовое общение в браузере",
"serverRailLabel": "Избранные и недавние серверы",
"switchServer": "Переключиться на",
"favoriteServer": "Сохранённый сервер",
"copyInvite": "Скопировать ссылку-приглашение",
"voiceChannels": "ГОЛОСОВЫЕ КАНАЛЫ",
"voiceConnected": "ГОЛОС ПОДКЛЮЧЁН",
"online": "В сети",
"audioSettings": "Настройки звука",
"toggleChat": "Показать или скрыть чат канала",
"invitePeople": "Пригласить участников",
"closeChat": "Закрыть чат",
"voiceControls": "Управление голосом",
"stopScreenShare": "Остановить показ экрана",
"toggleAccompaniment": "Переключить сопровождение"
}
},
"ja": {
"messages": {
"homeComponentName": "Discord 風の接続ホーム",
"homeAccessibleName": "Discord 風 WebSpeak 接続ページ",
"voiceComponentName": "Discord 風のボイスワークスペース",
"voiceAccessibleName": "Discord 風 WebSpeak ボイスワークスペース",
"tagline": "あなたの声を、どこでも。",
"eyebrow": "一緒にボイスチャット",
"heroTitle": "仲間と、",
"heroAccent": "声をつなごう。",
"heroDescription": "ブラウザーから TeamSpeak コミュニティに参加できます。",
"featureOneTitle": "クライアント不要",
"featureOneBody": "ブラウザーから直接接続。",
"featureTwoTitle": "低遅延の音声",
"featureTwoBody": "TeamSpeak サーバーでブラウザー音声を利用。",
"featureThreeTitle": "使い慣れた空間",
"featureThreeBody": "チャンネル、メンバー、チャットをまとめて表示。",
"connectTitle": "TeamSpeak サーバーに接続",
"connectDescription": "サーバーアドレスを入力して参加します。",
"securityNote": "接続と ID 情報は WebSpeak が安全に管理します。",
"footerNote": "ブラウザーでボイスチャット",
"serverRailLabel": "保存済み・最近のサーバー",
"switchServer": "切り替え先",
"favoriteServer": "保存済みサーバー",
"copyInvite": "招待リンクをコピー",
"voiceChannels": "ボイスチャンネル",
"voiceConnected": "ボイス接続中",
"online": "オンライン",
"audioSettings": "音声設定",
"toggleChat": "チャンネルチャットの表示切替",
"invitePeople": "メンバーを招待",
"closeChat": "チャットを閉じる",
"voiceControls": "ボイスコントロール",
"stopScreenShare": "画面共有を停止",
"toggleAccompaniment": "伴奏を切り替え"
}
}
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"schemaVersion": 3,
"packageType": "open-skin",
"id": "community.discord-voice",
"name": "Discord Voice",
"version": "1.0.11",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A Discord-inspired dark voice workspace built with WebSpeak's portable open-skin interface.",
"entry": "skin.css",
"components": "components.json",
"content": "content.json",
"minAppVersion": "0.2.8"
}
File diff suppressed because it is too large. Load diff
Binary file not shown.
+91 -84
View File
@@ -3,10 +3,10 @@
"components": [
{
"id": "kaak-home",
"name": "KAAK connection home",
"name": "{{skin.messages.kaakHomeComponentName}}",
"page": "home",
"mode": "surface",
"accessibleName": "KAAK 连接页 / Connection page",
"accessibleName": "{{skin.messages.kaakHomeAccessibleName}}",
"permissions": [
"ui.surface.replace",
"session.status.read"
@@ -49,7 +49,7 @@
"part": "slogan",
"children": [
{
"text": "YOUR VOICE, EVERYWHERE."
"text": "{{skin.messages.kaakTagline}}"
}
]
},
@@ -67,7 +67,7 @@
"attributes": {
"viewbox": "0 0 640 480",
"role": "img",
"aria-label": "WebSpeak voice connection illustration"
"aria-label": "{{skin.messages.kaakHomeIllustrationAlt}}"
},
"children": [
{
@@ -298,7 +298,7 @@
"part": "welcome-title",
"children": [
{
"text": "欢迎来到 WebSpeak"
"text": "{{skin.messages.kaakWelcomeTitle}}"
}
]
},
@@ -315,7 +315,7 @@
"part": "connection-title",
"children": [
{
"text": "连接 TeamSpeak 服务器"
"text": "{{skin.messages.kaakConnectTitle}}"
}
]
},
@@ -334,7 +334,7 @@
"part": "description",
"children": [
{
"text": "无需注册账号,填写服务器信息即可加入语音"
"text": "{{skin.messages.kaakConnectDescription}}"
}
]
},
@@ -347,7 +347,7 @@
"part": "note",
"children": [
{
"text": "浏览器直连 · 无需安装 TeamSpeak 客户端"
"text": "{{skin.messages.kaakBrowserDirect}}"
}
]
},
@@ -374,10 +374,10 @@
},
{
"id": "kaak-workspace",
"name": "KAAK voice workspace",
"name": "{{skin.messages.kaakVoiceComponentName}}",
"page": "voice",
"mode": "surface",
"accessibleName": "KAAK 语音工作区 / Voice workspace",
"accessibleName": "{{skin.messages.kaakVoiceAccessibleName}}",
"stateScope": "session.status.channelId",
"permissions": [
"ui.surface.replace",
@@ -395,6 +395,7 @@
"audio.microphone.control",
"audio.output.control",
"audio.settings.open",
"voice.connect",
"voice.disconnect",
"voice.screenShare.status.read",
"voice.screenShare.read",
@@ -480,7 +481,7 @@
"tag": "nav",
"part": "server-rail",
"attributes": {
"aria-label": "收藏与历史服务器 / Favorites and history"
"aria-label": "{{skin.messages.kaakFavoritesAndHistory}}"
},
"children": [
{
@@ -501,7 +502,8 @@
"attributes": {
"type": "button",
"aria-current": "{{server.current}}",
"aria-label": "切换到 {{server.label}}"
"aria-label": "{{server.switchTitle}}",
"title": "{{server.switchTitle}}"
},
"events": {
"click": "switch-server"
@@ -549,7 +551,7 @@
},
"children": [
{
"text": "收藏"
"text": "{{skin.messages.kaakFavorites}}"
}
]
},
@@ -562,7 +564,7 @@
},
"children": [
{
"text": "最近"
"text": "{{skin.messages.kaakRecent}}"
}
]
}
@@ -579,6 +581,10 @@
{
"widget": "app.language-switcher",
"part": "rail-language"
},
{
"widget": "home.social-links",
"part": "rail-links"
}
]
},
@@ -586,7 +592,7 @@
"tag": "header",
"part": "mobile-room-topbar",
"attributes": {
"aria-label": "语音房间控制"
"aria-label": "{{skin.messages.kaakVoiceRoomControls}}"
},
"children": [
{
@@ -594,7 +600,7 @@
"part": "mobile-room-back",
"attributes": {
"type": "button",
"aria-label": "返回频道树,不断开语音"
"aria-label": "{{skin.messages.kaakReturnChannelsNoDisconnect}}"
},
"events": {
"click": "toggle-mobile-page"
@@ -630,7 +636,7 @@
"part": "mobile-room-mode",
"children": [
{
"text": "语音感应"
"text": "{{skin.messages.kaakVoiceRoom}}"
}
]
},
@@ -640,7 +646,7 @@
"attributes": {
"type": "button",
"aria-expanded": "{{state.roommenu}}",
"aria-label": "更多语音功能"
"aria-label": "{{skin.messages.kaakMoreVoiceActions}}"
},
"events": {
"click": "toggle-room-menu"
@@ -706,7 +712,7 @@
},
"attributes": {
"role": "menu",
"aria-label": "更多语音功能"
"aria-label": "{{skin.messages.kaakMoreVoiceActions}}"
},
"children": [
{
@@ -715,14 +721,14 @@
"attributes": {
"type": "button",
"role": "menuitem",
"aria-label": "打开聊天记录"
"aria-label": "{{skin.messages.kaakOpenChatHistory}}"
},
"events": {
"click": "toggle-chat-panel"
},
"children": [
{
"text": "聊天记录"
"text": "{{skin.messages.kaakChatHistory}}"
}
]
},
@@ -732,14 +738,14 @@
"attributes": {
"type": "button",
"role": "menuitem",
"aria-label": "复制邀请链接 / Copy invite link"
"aria-label": "{{skin.messages.kaakCopyInviteLink}}"
},
"events": {
"click": "copy-invite-link"
},
"children": [
{
"text": "复制邀请链接 / Copy invite link"
"text": "{{skin.messages.kaakCopyInviteLink}}"
}
]
},
@@ -755,7 +761,7 @@
},
"children": [
{
"text": "关闭菜单"
"text": "{{skin.messages.kaakCloseMenu}}"
}
]
}
@@ -765,7 +771,7 @@
"tag": "section",
"part": "mobile-room-head",
"attributes": {
"aria-label": "当前语音频道"
"aria-label": "{{skin.messages.kaakCurrentVoiceChannel}}"
},
"children": [
{
@@ -814,7 +820,7 @@
"part": "mobile-room-connection-label",
"children": [
{
"text": "TeamSpeak · 已加入语音"
"text": "{{skin.messages.kaakVoiceConnected}}"
}
]
},
@@ -851,7 +857,7 @@
"tag": "aside",
"part": "channel-panel",
"attributes": {
"aria-label": "服务器频道 / Server channels"
"aria-label": "{{skin.messages.kaakServerChannels}}"
},
"children": [
{
@@ -862,11 +868,15 @@
"widget": "voice.server-banner",
"part": "server-banner"
},
{
"widget": "voice.connection-status",
"part": "connection-status"
},
{
"tag": "nav",
"part": "channel-list",
"attributes": {
"aria-label": "频道 / Channels"
"aria-label": "{{skin.messages.kaakChannels}}"
},
"children": [
{
@@ -875,7 +885,7 @@
"attributes": {
"type": "button",
"aria-expanded": "{{state.voicegroupopen}}",
"aria-label": "展开或收起语音分组 / Toggle voice group"
"aria-label": "{{skin.messages.kaakToggleVoiceGroup}}"
},
"events": {
"click": "toggle-voice-group"
@@ -898,7 +908,7 @@
"part": "voice-group-name",
"children": [
{
"text": "语音分组"
"text": "{{skin.messages.kaakVoiceGroup}}"
}
]
}
@@ -936,7 +946,7 @@
},
"attributes": {
"type": "button",
"aria-label": "返回当前语音房间"
"aria-label": "{{skin.messages.kaakReturnVoiceRoom}}"
},
"events": {
"click": "toggle-mobile-page"
@@ -959,7 +969,7 @@
"part": "mobile-room-return-copy",
"children": [
{
"text": "语音已连接 · 点击返回房间"
"text": "{{skin.messages.kaakReturnVoiceRoomConnected}}"
}
]
},
@@ -992,7 +1002,7 @@
"tag": "section",
"part": "conversation",
"attributes": {
"aria-label": "聊天 / Chat",
"aria-label": "{{skin.messages.kaakChat}}",
"data-chat-open": "{{chat.status.panelOpen}}"
},
"children": [
@@ -1015,7 +1025,7 @@
"attributes": {
"type": "button",
"aria-expanded": "{{chat.status.panelOpen}}",
"aria-label": "收起或展开聊天面板 / Toggle chat panel"
"aria-label": "{{skin.messages.kaakToggleChatPanel}}"
},
"events": {
"click": "toggle-chat-panel"
@@ -1065,7 +1075,7 @@
"tag": "aside",
"part": "voice-stage",
"attributes": {
"aria-label": "语音房间 / Voice room"
"aria-label": "{{skin.messages.kaakVoiceRoomAccessibleName}}"
},
"children": [
{
@@ -1089,7 +1099,7 @@
"part": "mobile-channel-back",
"attributes": {
"type": "button",
"aria-label": "返回频道树"
"aria-label": "{{skin.messages.kaakBackToChannels}}"
},
"events": {
"click": "toggle-mobile-page"
@@ -1125,7 +1135,7 @@
"tag": "span",
"part": "voice-stage-member-count",
"attributes": {
"aria-label": "频道成员数 / Channel member count"
"aria-label": "{{skin.messages.kaakChannelMemberCount}}"
},
"children": [
{
@@ -1152,8 +1162,8 @@
"className": "voice-stage-invite",
"attributes": {
"type": "button",
"aria-label": "复制邀请链接 / Copy invite link",
"title": "复制邀请链接 / Copy invite link"
"aria-label": "{{skin.messages.kaakCopyInviteLink}}",
"title": "{{skin.messages.kaakCopyInviteLink}}"
},
"events": {
"click": "copy-invite-link"
@@ -1200,7 +1210,7 @@
"attributes": {
"type": "button",
"aria-expanded": "{{chat.status.panelOpen}}",
"aria-label": "展开聊天面板 / Expand chat panel"
"aria-label": "{{skin.messages.kaakExpandChatPanel}}"
},
"events": {
"click": "toggle-chat-panel"
@@ -1233,7 +1243,7 @@
"tag": "footer",
"part": "voice-dock",
"attributes": {
"aria-label": "语音控制 / Voice controls"
"aria-label": "{{skin.messages.kaakVoiceControls}}"
},
"children": [
{
@@ -1260,24 +1270,21 @@
},
{
"widget": "voice.performance-panel",
"part": "performance-panel",
"options": {
"screenShare": false
}
"part": "performance-panel"
},
{
"tag": "button",
"part": "disconnect-control",
"attributes": {
"type": "button",
"aria-label": "断开语音"
"aria-label": "{{skin.messages.kaakDisconnectVoice}}"
},
"events": {
"click": "disconnect"
},
"children": [
{
"text": "离开"
"text": "{{skin.messages.kaakLeaveVoice}}"
}
]
}
@@ -1308,14 +1315,14 @@
},
"attributes": {
"type": "button",
"aria-label": "停止屏幕共享"
"aria-label": "{{skin.messages.kaakStopScreenShare}}"
},
"events": {
"click": "stop-screen-share"
},
"children": [
{
"text": "停止屏幕共享"
"text": "{{skin.messages.kaakStopScreenShare}}"
}
]
}
@@ -1327,7 +1334,7 @@
"className": "desktop-room-controls",
"attributes": {
"role": "toolbar",
"aria-label": "语音设置 / Audio controls"
"aria-label": "{{skin.messages.kaakAudioControls}}"
},
"children": [
{
@@ -1336,8 +1343,8 @@
"className": "desktop-room-control desktop-room-settings",
"attributes": {
"type": "button",
"aria-label": "语音设置 / Audio settings",
"title": "语音设置 / Audio settings"
"aria-label": "{{skin.messages.kaakAudioSettings}}",
"title": "{{skin.messages.kaakAudioSettings}}"
},
"events": {
"click": "open-audio-settings"
@@ -1377,7 +1384,7 @@
"className": "desktop-room-control-label",
"children": [
{
"text": "语音设置"
"text": "{{skin.messages.kaakAudioSettingsShort}}"
}
]
}
@@ -1389,8 +1396,8 @@
"className": "desktop-room-control desktop-room-noise-suppression",
"attributes": {
"type": "button",
"aria-label": "噪声抑制 / Noise suppression",
"title": "噪声抑制 / Noise suppression",
"aria-label": "{{skin.messages.kaakNoiseSuppression}}",
"title": "{{skin.messages.kaakNoiseSuppression}}",
"aria-pressed": "{{audio.status.noiseSuppressionEnabled}}"
},
"events": {
@@ -1440,8 +1447,8 @@
"className": "desktop-room-control desktop-room-microphone",
"attributes": {
"type": "button",
"aria-label": "麦克风 / Microphone",
"title": "麦克风 / Microphone",
"aria-label": "{{skin.messages.kaakMicrophone}}",
"title": "{{skin.messages.kaakMicrophone}}",
"aria-pressed": "{{audio.status.microphoneMuted}}"
},
"events": {
@@ -1507,8 +1514,8 @@
"className": "desktop-room-control desktop-room-output",
"attributes": {
"type": "button",
"aria-label": "扬声器静音 / Speaker mute",
"title": "扬声器静音 / Speaker mute",
"aria-label": "{{skin.messages.kaakSpeakerMute}}",
"title": "{{skin.messages.kaakSpeakerMute}}",
"aria-pressed": "{{audio.status.outputMuted}}"
},
"events": {
@@ -1566,8 +1573,8 @@
"className": "desktop-room-control desktop-room-accompaniment",
"attributes": {
"type": "button",
"aria-label": "伴奏 / Accompaniment",
"title": "伴奏 / Accompaniment",
"aria-label": "{{skin.messages.kaakAccompaniment}}",
"title": "{{skin.messages.kaakAccompaniment}}",
"aria-pressed": "{{audio.status.accompanimentActive}}"
},
"events": {
@@ -1625,7 +1632,7 @@
"className": "mobile-room-controls",
"attributes": {
"role": "toolbar",
"aria-label": "语音控制"
"aria-label": "{{skin.messages.kaakVoiceControls}}"
},
"children": [
{
@@ -1634,10 +1641,10 @@
"className": "mobile-room-control mobile-room-microphone",
"attributes": {
"type": "button",
"aria-label": "麦克风",
"aria-label": "{{skin.messages.kaakMicrophone}}",
"aria-pressed": "{{audio.status.microphoneMuted}}",
"data-muted": "{{audio.status.microphoneMuted}}",
"title": "麦克风"
"title": "{{skin.messages.kaakMicrophone}}"
},
"events": {
"click": "toggle-microphone"
@@ -1711,7 +1718,7 @@
},
"children": [
{
"text": "闭麦"
"text": "{{skin.messages.kaakMuteMicrophone}}"
}
]
},
@@ -1724,7 +1731,7 @@
},
"children": [
{
"text": "开麦"
"text": "{{skin.messages.kaakUnmuteMicrophone}}"
}
]
}
@@ -1736,10 +1743,10 @@
"className": "mobile-room-control mobile-room-deafen",
"attributes": {
"type": "button",
"aria-label": "耳机静音",
"aria-label": "{{skin.messages.kaakMuteOutput}}",
"aria-pressed": "{{audio.status.outputMuted}}",
"data-muted": "{{audio.status.outputMuted}}",
"title": "耳机静音"
"title": "{{skin.messages.kaakMuteOutput}}"
},
"events": {
"click": "toggle-output-mute"
@@ -1799,7 +1806,7 @@
},
"children": [
{
"text": "静音"
"text": "{{skin.messages.kaakMute}}"
}
]
},
@@ -1812,7 +1819,7 @@
},
"children": [
{
"text": "恢复"
"text": "{{skin.messages.kaakUnmute}}"
}
]
}
@@ -1824,8 +1831,8 @@
"className": "mobile-room-control mobile-room-speaker",
"attributes": {
"type": "button",
"aria-label": "扬声器",
"title": "扬声器"
"aria-label": "{{skin.messages.kaakSpeaker}}",
"title": "{{skin.messages.kaakSpeaker}}"
},
"events": {
"click": "open-audio-settings"
@@ -1867,7 +1874,7 @@
"className": "mobile-room-control-caption",
"children": [
{
"text": "扬声器"
"text": "{{skin.messages.kaakSpeaker}}"
}
]
}
@@ -1883,8 +1890,8 @@
},
"attributes": {
"type": "button",
"aria-label": "屏幕共享",
"title": "屏幕共享",
"aria-label": "{{skin.messages.kaakScreenShare}}",
"title": "{{skin.messages.kaakScreenShare}}",
"aria-pressed": false
},
"events": {
@@ -1937,7 +1944,7 @@
"className": "mobile-room-control-caption",
"children": [
{
"text": "屏幕共享"
"text": "{{skin.messages.kaakScreenShare}}"
}
]
}
@@ -1953,8 +1960,8 @@
},
"attributes": {
"type": "button",
"aria-label": "停止屏幕共享",
"title": "停止屏幕共享",
"aria-label": "{{skin.messages.kaakStopScreenShare}}",
"title": "{{skin.messages.kaakStopScreenShare}}",
"aria-pressed": true
},
"events": {
@@ -2007,7 +2014,7 @@
"className": "mobile-room-control-caption",
"children": [
{
"text": "屏幕共享"
"text": "{{skin.messages.kaakScreenShare}}"
}
]
}
@@ -2019,8 +2026,8 @@
"className": "mobile-room-control mobile-room-exit",
"attributes": {
"type": "button",
"aria-label": "退出",
"title": "退出"
"aria-label": "{{skin.messages.kaakLeaveVoice}}",
"title": "{{skin.messages.kaakLeaveVoice}}"
},
"events": {
"click": "disconnect"
@@ -2062,7 +2069,7 @@
"className": "mobile-room-control-caption",
"children": [
{
"text": "退出"
"text": "{{skin.messages.kaakLeaveVoice}}"
}
]
}
@@ -2080,7 +2087,7 @@
},
"attributes": {
"role": "group",
"aria-label": "当前 TeamSpeak 身份"
"aria-label": "{{skin.messages.kaakCurrentIdentity}}"
},
"children": [
{
@@ -2099,7 +2106,7 @@
},
"attributes": {
"role": "img",
"aria-label": "在线"
"aria-label": "{{skin.messages.kaakOnline}}"
}
}
]
+335 -5
View File
@@ -1,10 +1,340 @@
{
"defaultLocale": "zh-CN",
"locales": {
"zh-CN": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "确定" } },
"en": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Confirm" } },
"de": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Bestätigen" } },
"ru": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "Подтвердить" } },
"ja": { "home": { "brandName": "KAAK" }, "messages": { "passwordDialogConfirm": "確定" } }
"zh-CN": {
"home": {
"brandName": "KAAK"
},
"messages": {
"passwordDialogConfirm": "确定",
"kaakHomeComponentName": "KAAK 首页",
"kaakVoiceComponentName": "KAAK 语音工作区",
"kaakHomeAccessibleName": "KAAK 连接页",
"kaakVoiceAccessibleName": "KAAK 语音工作区",
"kaakTagline": "你的声音,随时随地。",
"kaakHomeIllustrationAlt": "WebSpeak 语音连接插图",
"kaakWelcomeTitle": "欢迎来到 WebSpeak",
"kaakConnectTitle": "连接 TeamSpeak 服务器",
"kaakConnectDescription": "无需注册账号,填写服务器信息即可加入语音",
"kaakBrowserDirect": "浏览器直连 · 无需安装 TeamSpeak 客户端",
"kaakFavoritesAndHistory": "收藏与最近服务器",
"kaakFavorites": "收藏",
"kaakRecent": "最近",
"kaakVoiceRoomControls": "语音房间控制",
"kaakReturnChannelsNoDisconnect": "返回频道树,不断开语音",
"kaakVoiceRoom": "语音房间",
"kaakMoreVoiceActions": "更多语音功能",
"kaakOpenChatHistory": "打开聊天记录",
"kaakChatHistory": "聊天记录",
"kaakCopyInviteLink": "复制邀请链接",
"kaakCloseMenu": "关闭菜单",
"kaakCurrentVoiceChannel": "当前语音频道",
"kaakVoiceConnected": "TeamSpeak · 已加入语音",
"kaakServerChannels": "服务器频道",
"kaakChannels": "频道",
"kaakToggleVoiceGroup": "展开或收起语音分组",
"kaakVoiceGroup": "语音分组",
"kaakReturnVoiceRoom": "返回当前语音房间",
"kaakReturnVoiceRoomConnected": "语音已连接 · 点击返回房间",
"kaakChat": "聊天",
"kaakToggleChatPanel": "收起或展开聊天面板",
"kaakVoiceRoomAccessibleName": "语音房间",
"kaakBackToChannels": "返回频道列表",
"kaakChannelMemberCount": "频道成员数",
"kaakExpandChatPanel": "展开聊天面板",
"kaakVoiceControls": "语音控制",
"kaakDisconnectVoice": "断开语音",
"kaakStopScreenShare": "停止屏幕共享",
"kaakAudioControls": "语音设置",
"kaakAudioSettings": "语音设置",
"kaakAudioSettingsShort": "语音设置",
"kaakNoiseSuppression": "噪声抑制",
"kaakMicrophone": "麦克风",
"kaakSpeakerMute": "扬声器静音",
"kaakAccompaniment": "伴奏",
"kaakMuteMicrophone": "闭麦",
"kaakUnmuteMicrophone": "开麦",
"kaakMuteOutput": "耳机静音",
"kaakMute": "静音",
"kaakUnmute": "恢复",
"kaakSpeaker": "扬声器",
"kaakScreenShare": "屏幕共享",
"kaakLeaveVoice": "退出",
"kaakCurrentIdentity": "当前 TeamSpeak 身份",
"kaakOnline": "在线",
"githubRepository": "Webspeak项目Github",
"qqGroup": "WebSpeak项目QQ群",
"adminConsole": "管理控制台",
"communityLinks": "社区与管理入口"
}
},
"en": {
"home": {
"brandName": "KAAK"
},
"messages": {
"passwordDialogConfirm": "Confirm",
"kaakHomeComponentName": "KAAK connection home",
"kaakVoiceComponentName": "KAAK voice workspace",
"kaakHomeAccessibleName": "KAAK connection page",
"kaakVoiceAccessibleName": "KAAK voice workspace",
"kaakTagline": "YOUR VOICE, EVERYWHERE.",
"kaakHomeIllustrationAlt": "WebSpeak voice connection illustration",
"kaakWelcomeTitle": "Welcome to WebSpeak",
"kaakConnectTitle": "Connect to a TeamSpeak server",
"kaakConnectDescription": "No account required. Enter the server details to join voice.",
"kaakBrowserDirect": "Connect directly in your browser · No TeamSpeak client needed",
"kaakFavoritesAndHistory": "Favorites and recent servers",
"kaakFavorites": "Favorites",
"kaakRecent": "Recent",
"kaakVoiceRoomControls": "Voice room controls",
"kaakReturnChannelsNoDisconnect": "Return to channels without disconnecting",
"kaakVoiceRoom": "Voice room",
"kaakMoreVoiceActions": "More voice actions",
"kaakOpenChatHistory": "Open chat history",
"kaakChatHistory": "Chat history",
"kaakCopyInviteLink": "Copy invite link",
"kaakCloseMenu": "Close menu",
"kaakCurrentVoiceChannel": "Current voice channel",
"kaakVoiceConnected": "TeamSpeak · Voice connected",
"kaakServerChannels": "Server channels",
"kaakChannels": "Channels",
"kaakToggleVoiceGroup": "Expand or collapse voice group",
"kaakVoiceGroup": "Voice group",
"kaakReturnVoiceRoom": "Return to the current voice room",
"kaakReturnVoiceRoomConnected": "Voice connected · Click to return to the room",
"kaakChat": "Chat",
"kaakToggleChatPanel": "Collapse or expand chat panel",
"kaakVoiceRoomAccessibleName": "Voice room",
"kaakBackToChannels": "Back to channel list",
"kaakChannelMemberCount": "Channel member count",
"kaakExpandChatPanel": "Expand chat panel",
"kaakVoiceControls": "Voice controls",
"kaakDisconnectVoice": "Disconnect voice",
"kaakStopScreenShare": "Stop screen sharing",
"kaakAudioControls": "Audio controls",
"kaakAudioSettings": "Audio settings",
"kaakAudioSettingsShort": "Audio settings",
"kaakNoiseSuppression": "Noise suppression",
"kaakMicrophone": "Microphone",
"kaakSpeakerMute": "Mute speakers",
"kaakAccompaniment": "Accompaniment",
"kaakMuteMicrophone": "Mute microphone",
"kaakUnmuteMicrophone": "Unmute microphone",
"kaakMuteOutput": "Mute output",
"kaakMute": "Mute",
"kaakUnmute": "Unmute",
"kaakSpeaker": "Speaker",
"kaakScreenShare": "Screen share",
"kaakLeaveVoice": "Leave",
"kaakCurrentIdentity": "Current TeamSpeak identity",
"kaakOnline": "Online",
"githubRepository": "WebSpeak project GitHub",
"qqGroup": "WebSpeak project QQ group",
"adminConsole": "Admin console",
"communityLinks": "Community and administration"
}
},
"de": {
"home": {
"brandName": "KAAK"
},
"messages": {
"passwordDialogConfirm": "Bestätigen",
"kaakHomeComponentName": "KAAK-Verbindungsseite",
"kaakVoiceComponentName": "KAAK-Sprachbereich",
"kaakHomeAccessibleName": "KAAK-Verbindungsseite",
"kaakVoiceAccessibleName": "KAAK-Sprachbereich",
"kaakTagline": "DEINE STIMME. ÜBERALL.",
"kaakHomeIllustrationAlt": "Illustration zur WebSpeak-Sprachverbindung",
"kaakWelcomeTitle": "Willkommen bei WebSpeak",
"kaakConnectTitle": "Mit einem TeamSpeak-Server verbinden",
"kaakConnectDescription": "Kein Konto nötig. Gib die Serverdaten ein, um dem Sprachkanal beizutreten.",
"kaakBrowserDirect": "Direkt im Browser · Kein TeamSpeak-Client erforderlich",
"kaakFavoritesAndHistory": "Favoriten und zuletzt verwendete Server",
"kaakFavorites": "Favoriten",
"kaakRecent": "Zuletzt",
"kaakVoiceRoomControls": "Sprachraum-Steuerung",
"kaakReturnChannelsNoDisconnect": "Zurück zu den Kanälen, ohne die Verbindung zu trennen",
"kaakVoiceRoom": "Sprachraum",
"kaakMoreVoiceActions": "Weitere Sprachaktionen",
"kaakOpenChatHistory": "Chatverlauf öffnen",
"kaakChatHistory": "Chatverlauf",
"kaakCopyInviteLink": "Einladungslink kopieren",
"kaakCloseMenu": "Menü schließen",
"kaakCurrentVoiceChannel": "Aktueller Sprachkanal",
"kaakVoiceConnected": "TeamSpeak · Sprachkanal beigetreten",
"kaakServerChannels": "Serverkanäle",
"kaakChannels": "Kanäle",
"kaakToggleVoiceGroup": "Sprachgruppe ein- oder ausklappen",
"kaakVoiceGroup": "Sprachgruppe",
"kaakReturnVoiceRoom": "Zum aktuellen Sprachraum zurückkehren",
"kaakReturnVoiceRoomConnected": "Sprachverbindung aktiv · Klicken, um zum Raum zurückzukehren",
"kaakChat": "Chat",
"kaakToggleChatPanel": "Chatbereich ein- oder ausklappen",
"kaakVoiceRoomAccessibleName": "Sprachraum",
"kaakBackToChannels": "Zur Kanalliste",
"kaakChannelMemberCount": "Anzahl der Kanalmitglieder",
"kaakExpandChatPanel": "Chatbereich erweitern",
"kaakVoiceControls": "Sprachsteuerung",
"kaakDisconnectVoice": "Sprachverbindung trennen",
"kaakStopScreenShare": "Bildschirmfreigabe beenden",
"kaakAudioControls": "Audio-Steuerung",
"kaakAudioSettings": "Audioeinstellungen",
"kaakAudioSettingsShort": "Audioeinstellungen",
"kaakNoiseSuppression": "Rauschunterdrückung",
"kaakMicrophone": "Mikrofon",
"kaakSpeakerMute": "Lautsprecher stummschalten",
"kaakAccompaniment": "Begleitton",
"kaakMuteMicrophone": "Mikrofon stummschalten",
"kaakUnmuteMicrophone": "Mikrofon einschalten",
"kaakMuteOutput": "Ausgabe stummschalten",
"kaakMute": "Stumm",
"kaakUnmute": "Ton einschalten",
"kaakSpeaker": "Lautsprecher",
"kaakScreenShare": "Bildschirm teilen",
"kaakLeaveVoice": "Verlassen",
"kaakCurrentIdentity": "Aktuelle TeamSpeak-Identität",
"kaakOnline": "Online",
"githubRepository": "GitHub-Repository des WebSpeak-Projekts",
"qqGroup": "QQ-Gruppe des WebSpeak-Projekts",
"adminConsole": "Administrationskonsole",
"communityLinks": "Community und Verwaltung"
}
},
"ru": {
"home": {
"brandName": "KAAK"
},
"messages": {
"passwordDialogConfirm": "Подтвердить",
"kaakHomeComponentName": "Страница подключения KAAK",
"kaakVoiceComponentName": "Голосовое пространство KAAK",
"kaakHomeAccessibleName": "Страница подключения KAAK",
"kaakVoiceAccessibleName": "Голосовое пространство KAAK",
"kaakTagline": "ТВОЙ ГОЛОС — ВЕЗДЕ.",
"kaakHomeIllustrationAlt": "Иллюстрация голосового подключения WebSpeak",
"kaakWelcomeTitle": "Добро пожаловать в WebSpeak",
"kaakConnectTitle": "Подключение к серверу TeamSpeak",
"kaakConnectDescription": "Аккаунт не нужен. Укажите данные сервера, чтобы подключиться к голосовому каналу.",
"kaakBrowserDirect": "Прямое подключение в браузере · Клиент TeamSpeak не нужен",
"kaakFavoritesAndHistory": "Избранные и недавние серверы",
"kaakFavorites": "Избранное",
"kaakRecent": "Недавние",
"kaakVoiceRoomControls": "Управление голосовой комнатой",
"kaakReturnChannelsNoDisconnect": "Вернуться к каналам без отключения",
"kaakVoiceRoom": "Голосовая комната",
"kaakMoreVoiceActions": "Дополнительные голосовые действия",
"kaakOpenChatHistory": "Открыть историю чата",
"kaakChatHistory": "История чата",
"kaakCopyInviteLink": "Скопировать ссылку-приглашение",
"kaakCloseMenu": "Закрыть меню",
"kaakCurrentVoiceChannel": "Текущий голосовой канал",
"kaakVoiceConnected": "TeamSpeak · Подключён к голосовому каналу",
"kaakServerChannels": "Каналы сервера",
"kaakChannels": "Каналы",
"kaakToggleVoiceGroup": "Развернуть или свернуть группу",
"kaakVoiceGroup": "Голосовая группа",
"kaakReturnVoiceRoom": "Вернуться в текущую голосовую комнату",
"kaakReturnVoiceRoomConnected": "Подключено · Нажмите, чтобы вернуться в комнату",
"kaakChat": "Чат",
"kaakToggleChatPanel": "Свернуть или развернуть панель чата",
"kaakVoiceRoomAccessibleName": "Голосовая комната",
"kaakBackToChannels": "Вернуться к списку каналов",
"kaakChannelMemberCount": "Количество участников канала",
"kaakExpandChatPanel": "Развернуть панель чата",
"kaakVoiceControls": "Голосовое управление",
"kaakDisconnectVoice": "Отключиться от голосового канала",
"kaakStopScreenShare": "Остановить демонстрацию экрана",
"kaakAudioControls": "Управление звуком",
"kaakAudioSettings": "Настройки звука",
"kaakAudioSettingsShort": "Настройки звука",
"kaakNoiseSuppression": "Шумоподавление",
"kaakMicrophone": "Микрофон",
"kaakSpeakerMute": "Отключить звук динамиков",
"kaakAccompaniment": "Сопровождение",
"kaakMuteMicrophone": "Выключить микрофон",
"kaakUnmuteMicrophone": "Включить микрофон",
"kaakMuteOutput": "Отключить звук",
"kaakMute": "Без звука",
"kaakUnmute": "Включить звук",
"kaakSpeaker": "Динамик",
"kaakScreenShare": "Демонстрация экрана",
"kaakLeaveVoice": "Выйти",
"kaakCurrentIdentity": "Текущая личность TeamSpeak",
"kaakOnline": "В сети",
"githubRepository": "GitHub проекта WebSpeak",
"qqGroup": "Группа QQ проекта WebSpeak",
"adminConsole": "Панель администратора",
"communityLinks": "Сообщество и управление"
}
},
"ja": {
"home": {
"brandName": "KAAK"
},
"messages": {
"passwordDialogConfirm": "確定",
"kaakHomeComponentName": "KAAK 接続ページ",
"kaakVoiceComponentName": "KAAK 音声ワークスペース",
"kaakHomeAccessibleName": "KAAK 接続ページ",
"kaakVoiceAccessibleName": "KAAK 音声ワークスペース",
"kaakTagline": "あなたの声を、どこでも。",
"kaakHomeIllustrationAlt": "WebSpeak 音声接続のイラスト",
"kaakWelcomeTitle": "WebSpeak へようこそ",
"kaakConnectTitle": "TeamSpeak サーバーに接続",
"kaakConnectDescription": "アカウント登録は不要です。サーバー情報を入力して音声に参加できます。",
"kaakBrowserDirect": "ブラウザーから直接接続 · TeamSpeak クライアント不要",
"kaakFavoritesAndHistory": "お気に入りと最近使ったサーバー",
"kaakFavorites": "お気に入り",
"kaakRecent": "最近",
"kaakVoiceRoomControls": "音声ルーム操作",
"kaakReturnChannelsNoDisconnect": "切断せずにチャンネル一覧へ戻る",
"kaakVoiceRoom": "音声ルーム",
"kaakMoreVoiceActions": "その他の音声操作",
"kaakOpenChatHistory": "チャット履歴を開く",
"kaakChatHistory": "チャット履歴",
"kaakCopyInviteLink": "招待リンクをコピー",
"kaakCloseMenu": "メニューを閉じる",
"kaakCurrentVoiceChannel": "現在の音声チャンネル",
"kaakVoiceConnected": "TeamSpeak · 音声に接続中",
"kaakServerChannels": "サーバーチャンネル",
"kaakChannels": "チャンネル",
"kaakToggleVoiceGroup": "音声グループを展開/折りたたむ",
"kaakVoiceGroup": "音声グループ",
"kaakReturnVoiceRoom": "現在の音声ルームに戻る",
"kaakReturnVoiceRoomConnected": "音声接続中 · タップしてルームに戻る",
"kaakChat": "チャット",
"kaakToggleChatPanel": "チャットパネルを折りたたむ/展開",
"kaakVoiceRoomAccessibleName": "音声ルーム",
"kaakBackToChannels": "チャンネル一覧に戻る",
"kaakChannelMemberCount": "チャンネルの参加者数",
"kaakExpandChatPanel": "チャットパネルを展開",
"kaakVoiceControls": "音声コントロール",
"kaakDisconnectVoice": "音声接続を切断",
"kaakStopScreenShare": "画面共有を停止",
"kaakAudioControls": "音声コントロール",
"kaakAudioSettings": "音声設定",
"kaakAudioSettingsShort": "音声設定",
"kaakNoiseSuppression": "ノイズ抑制",
"kaakMicrophone": "マイク",
"kaakSpeakerMute": "スピーカーをミュート",
"kaakAccompaniment": "伴奏音声",
"kaakMuteMicrophone": "マイクをミュート",
"kaakUnmuteMicrophone": "マイクのミュートを解除",
"kaakMuteOutput": "出力をミュート",
"kaakMute": "ミュート",
"kaakUnmute": "ミュート解除",
"kaakSpeaker": "スピーカー",
"kaakScreenShare": "画面共有",
"kaakLeaveVoice": "退出",
"kaakCurrentIdentity": "現在の TeamSpeak ID",
"kaakOnline": "オンライン",
"githubRepository": "WebSpeak プロジェクトの GitHub",
"qqGroup": "WebSpeak プロジェクトの QQ グループ",
"adminConsole": "管理コンソール",
"communityLinks": "コミュニティと管理"
}
}
}
}
+6 -2
View File
@@ -3,12 +3,16 @@
"packageType": "open-skin",
"id": "community.kaak-voice",
"name": "KAAK",
"version": "3.1.115",
"version": "3.1.127",
"author": "WebSpeak Project",
"license": "AGPL-3.0-only",
"description": "A KOOK-inspired WebSpeak skin with a split-screen connection home, searchable server header, TeamSpeak banner, nested channel members, unified chat with local history, and a compact audio dock.",
"entry": "skin.css",
"components": "components.json",
"content": "content.json",
"minAppVersion": "0.2.7"
"minAppVersion": "0.2.8",
"workspace": {
"apiVersion": 1,
"mode": "persistent"
}
}
+188 -13
View File
@@ -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);
@@ -2341,22 +2343,26 @@
cursor: pointer;
}
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control-icon { display: block; flex: 0 0 auto; width: 18px; height: 18px; }
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] {
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] {
display: flex;
grid-column: 1;
grid-row: 2;
align-items: center;
justify-content: flex-start;
justify-self: stretch;
box-sizing: border-box;
gap: 8px;
width: auto;
width: 100%;
max-width: 100%;
min-width: 0;
padding: 0 7px;
margin: 0;
padding: 0;
color: #b5c6d8;
font-size: 12px;
font-weight: 500;
line-height: 1;
}
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-icon {
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-icon {
display: block;
flex: 0 0 15px;
width: 15px;
@@ -2368,7 +2374,7 @@
transform: none;
vertical-align: middle;
}
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-label { display: block; line-height: 16px; white-space: nowrap; }
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"] .desktop-room-control-label { display: block; min-width: 0; overflow: hidden; line-height: 16px; text-overflow: ellipsis; white-space: nowrap; }
[data-ws-plugin-part="kaak-workspace.desktop-room-noise-suppression"] { grid-column: 2; grid-row: 2; color: #fff; background: #6cbf00; }
[data-ws-plugin-part="kaak-workspace.desktop-room-microphone"] { grid-column: 3; grid-row: 2; }
[data-ws-plugin-part="kaak-workspace.desktop-room-output"] { grid-column: 4; grid-row: 2; }
@@ -2386,8 +2392,8 @@
}
[data-ws-plugin-part="kaak-workspace.desktop-room-noise-suppression"][aria-pressed="true"] { color: #fff; background: #6cbf00; }
[data-ws-plugin-part="kaak-workspace.desktop-room-accompaniment"][aria-pressed="true"] { background: #477f00; box-shadow: inset 0 0 0 1px #9be031; }
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:hover,
[data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:focus-visible { color: #eff0f3; background: #303238; }
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:hover,
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] [data-ws-plugin-part="kaak-workspace.desktop-room-settings"]:focus-visible { color: #eff0f3; background: #303238; }
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control:hover,
[data-ws-plugin-part="kaak-workspace.desktop-room-controls"] .desktop-room-control:focus-visible { color: #eff0f3; background: #303238; outline: none; }
[data-ws-plugin-part="kaak-workspace.desktop-room-accompaniment"]:hover,
@@ -3043,13 +3049,15 @@
min-height: 40px;
}
[data-ws-part="voice.audio-settings"] .settings-select-option {
height: 32px;
height: auto;
min-height: 32px;
margin-bottom: 2px;
padding-inline: 8px;
padding: 6px 8px;
color: #e6eaf0;
font-size: 14px;
line-height: 32px;
line-height: 1.45;
overflow-wrap: anywhere;
white-space: normal;
border-radius: 8px;
}
[data-ws-part="voice.audio-settings"] .settings-select-option:last-child { margin-bottom: 0; }
@@ -4506,8 +4514,6 @@
[data-ws-plugin-part="kaak-workspace.conversation-heading"] { min-height: 48px; margin: 0; }
[data-ws-plugin-part="kaak-workspace.chat-panel-toggle"] { pointer-events: auto; }
[data-ws-plugin-part="kaak-workspace.chat-panel"] { min-height: 0; overflow: hidden; }
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"]:not([data-mobile-channels="true"])[data-chat-open="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"] { display: none; }
/* The legacy collapsed-chat rule places the room in grid column 2. Keep the
connected narrow room in its single-column layout in either chat state. */
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"]:has(
@@ -4528,3 +4534,172 @@
[data-ws-plugin-part="kaak-workspace.member-cards"] .voice-card { min-height: 116px; height: 116px; }
[data-ws-plugin-part="kaak-workspace.member-cards"] .voice-avatar { width: 60px; height: 60px; }
}
/* Keep the compact chat on the content side of the persistent server rail.
The room controls remain available after chat is closed, and the rail stays
interactive while the chat page is open. */
@media (max-width: 820px) {
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
position: fixed;
z-index: 50;
inset: 0 0 0 86px;
pointer-events: auto;
}
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
display: none;
pointer-events: none;
}
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"][data-mobile-channels="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"],
[data-ws-plugin-part="kaak-workspace.workspace"][data-session-connected="true"]:not([data-mobile-channels="true"])[data-chat-open="true"] [data-ws-plugin-part="kaak-workspace.mobile-room-menu"] {
display: none;
pointer-events: none;
}
[data-ws-part="app"]:has([data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"]) .modal-backdrop:has([data-ws-part="voice.audio-settings"]) {
z-index: 1000;
}
}
@media (max-width: 360px) {
[data-ws-plugin-part="kaak-workspace"][data-ws-plugin-surface="voice"] [data-ws-plugin-part="kaak-workspace.conversation"][data-chat-open="true"] {
inset-inline-start: 70px;
}
}
/* Workspace API v1: reconnect stays beside server navigation on every width. */
[data-ws-plugin-part="kaak-workspace.connection-status"] {
flex: 0 0 auto;
min-width: 0;
margin: 10px 8px;
}
[data-ws-plugin-part="kaak-workspace.connection-status"]:not(:has([data-ws-part="voice.connection-status"])) { display: none; }
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status"] {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 12px;
width: 100%;
min-width: 0;
margin: 0;
padding: 16px;
border: 1px solid var(--skin-kaak-border);
border-radius: 12px;
color: var(--skin-kaak-text);
background: var(--skin-kaak-raised);
box-shadow: none;
font-family: var(--skin-kaak-font);
}
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status.message"] {
flex: 0 0 auto;
margin: 0;
color: var(--skin-kaak-muted);
font-size: 13px;
line-height: 1.5;
overflow-wrap: anywhere;
}
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-state="failed"] [data-ws-part="voice.connection-status.message"] { color: #ffaaaa; }
[data-ws-plugin-part="kaak-workspace.connection-status"] [data-ws-part="voice.connection-status.nickname"] {
display: grid;
gap: 6px;
min-width: 0;
width: 100%;
color: var(--skin-kaak-muted);
font-size: 12px;
}
[data-ws-plugin-part="kaak-workspace.connection-status"] input {
width: 100%;
min-width: 0;
min-height: 44px;
padding: 9px 10px;
border: 1px solid #4b4e55;
border-radius: 7px;
color: var(--skin-kaak-text);
background: var(--skin-kaak-panel);
font: inherit;
font-size: 14px;
}
[data-ws-plugin-part="kaak-workspace.connection-status"] button {
justify-content: center;
min-width: 0;
min-height: 44px;
padding: 10px 12px;
border-radius: 7px;
color: #152000;
background: var(--skin-kaak-accent);
font: inherit;
font-weight: 700;
white-space: normal;
overflow-wrap: anywhere;
}
[data-ws-plugin-part="kaak-workspace.connection-status"] button:hover:not(:disabled) { background: var(--skin-kaak-accent-hover); }
[data-ws-plugin-part="kaak-workspace.connection-status"] input:focus-visible,
[data-ws-plugin-part="kaak-workspace.connection-status"] button:focus-visible { outline: 2px solid #a8ed50; outline-offset: 3px; }
@media (max-width: 820px) {
[data-ws-plugin-part="kaak-workspace.connection-status"] { margin: 10px 4px; }
}
/* Shared public links: management follows Add; community links finish the rail. */
[data-ws-plugin-part="kaak-workspace.server-rail"] {
gap: 10px;
overflow-x: hidden;
overflow-y: auto;
}
[data-ws-plugin-part="kaak-workspace.server-list"] { min-height: 58px; }
[data-ws-plugin-part="kaak-workspace.rail-links"],
[data-ws-plugin-part="kaak-workspace.rail-links"] [data-ws-part="home.social-links"] { display: contents; }
[data-ws-plugin-part="kaak-workspace.rail-links"] a {
position: relative;
display: grid;
flex: 0 0 44px;
place-items: center;
box-sizing: border-box;
width: 44px;
height: 44px;
min-width: 44px;
min-height: 44px;
padding: 0;
border: 1px solid transparent;
border-radius: 14px;
color: #b7bbc4;
background: transparent;
text-decoration: none;
transition: color .15s ease, background-color .15s ease, border-color .15s ease;
}
[data-ws-plugin-part="kaak-workspace.rail-links"] a .ui-icon { display: block; width: 22px; height: 22px; flex: 0 0 auto; }
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href="/admin"] {
order: 3;
flex-basis: 58px;
width: 58px;
height: 58px;
border-color: #3d4048;
border-radius: 18px;
color: #d1d5dc;
background: var(--skin-kaak-rail-item-bg);
}
[data-ws-plugin-part="kaak-workspace.rail-skin"] { order: 4; }
[data-ws-plugin-part="kaak-workspace.rail-language"] { order: 5; }
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href*="github.com/"] { order: 6; }
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href*="qm.qq.com/"] { order: 7; }
[data-ws-plugin-part="kaak-workspace.rail-links"] a:hover,
[data-ws-plugin-part="kaak-workspace.rail-links"] a:focus-visible {
border-color: #699b32;
color: #a8ed50;
background: #2b3524;
}
[data-ws-plugin-part="kaak-workspace.rail-links"] a:focus-visible { outline: 2px solid #a8ed50; outline-offset: 3px; }
@media (max-height: 620px) {
[data-ws-plugin-part="kaak-workspace.server-rail"] { gap: 8px; padding-top: 10px; padding-bottom: max(82px, env(safe-area-inset-bottom)); }
[data-ws-plugin-part="kaak-workspace.server-add"],
[data-ws-plugin-part="kaak-workspace.rail-links"] a[href="/admin"],
[data-ws-plugin-part="kaak-workspace.rail-skin"],
[data-ws-plugin-part="kaak-workspace.rail-language"] { flex: 0 0 44px; width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-switcher,
[data-ws-plugin-part="kaak-workspace.rail-skin"] .skin-trigger,
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-switcher,
[data-ws-plugin-part="kaak-workspace.rail-language"] .language-trigger { width: 44px; height: 44px; min-height: 44px; border-radius: 14px; }
}
@media (prefers-reduced-motion: reduce) {
[data-ws-plugin-part="kaak-workspace.rail-links"] a { transition: none; }
}
+2 -3
View File
@@ -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.
+21 -13
View File
@@ -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
View File
@@ -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",
+97 -15
View File
@@ -1,21 +1,22 @@
{
"name": "webspeak-webclient",
"version": "0.2.7",
"version": "0.2.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.2.7",
"version": "0.2.9",
"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",
+51 -51
View File
@@ -1,55 +1,55 @@
{
"name": "webspeak-webclient",
"version": "0.2.7",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
"engines": {
"node": ">=22.5.0"
},
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
"verify": "npm test && npm run build && npm run web:build",
{
"name": "webspeak-webclient",
"version": "0.2.9",
"private": true,
"license": "AGPL-3.0-only",
"type": "module",
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
"engines": {
"node": ">=22.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/skin-store.test.ts src/admin/ts-admin-service.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts",
"verify": "npm test && npm run build && npm run web:build",
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
"skin:kaak:build": "node web/scripts/build-kaak-voice-skin.mjs",
"skin:illusia:build": "node web/scripts/build-illusia-voice-skin.mjs",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "npm --prefix web run build",
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
"prepare:sdk": "node scripts/prepare-sdk.mjs",
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
"acceleration:relay": "node dist/relay.js"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#758a0d7d9120b0f5777d9451fb6b134f0b606f65",
"express": "^5.2.1",
"pino": "^10.3.1",
"postcss": "^8.5.29",
"postcss-selector-parser": "^7.1.6",
"postcss-value-parser": "^4.2.0",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
"@types/express": "^5.0.3",
"@types/node": "^22.15.0",
"@types/ws": "^8.18.1",
"tsx": "^4.21.0",
"typescript": "^6.0.2"
},
"overrides": {
"body-parser": "^2.3.0",
"esbuild": "^0.28.2",
"tar": "^7.5.22"
}
}
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "npm --prefix web run build",
"skin:wasm:build": "node scripts/build-skin-wasm-interpreter.mjs",
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
"acceleration:relay": "node dist/relay.js"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@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"
},
"devDependencies": {
"@types/express": "^5.0.3",
"@types/node": "^22.15.0",
"@types/ws": "^8.18.1",
"tsx": "^4.21.0",
"typescript": "^6.0.2"
},
"overrides": {
"body-parser": "^2.3.0",
"esbuild": "^0.28.2",
"tar": "^7.5.22"
}
}
+14 -1
View File
@@ -9,6 +9,7 @@
- 双向 UDP 数据报转发,并保持数据包边界;
- 会话之间按随机 ID 隔离;
- 错误密钥不能建立会话;
- 未开启 `allowPrivate` 时,解析到非公网地址的目标一律被拒绝;
- 不修改系统路由,因此不是 VPN。
## 本地冒烟
@@ -19,7 +20,13 @@
npm run acceleration:poc
```
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。除吞吐与错误密钥外,该冒烟还会用一个独立的 `allowPrivate: false` 中继断言私网目标防护生效:
```text
ssrf_guard_ok=true blocked=5/5 public_target_allowed=true
```
任一被禁目标未被拦截、或公网目标被误拦,都会输出 `LEAK` / 失败。
IPv6 回环验证:
@@ -27,6 +34,12 @@ IPv6 回环验证:
npm run acceleration:ipv6-smoke
```
## 私网目标防护与主程序保持一致
中继的 `isRestrictedAddress()` 是 `src/security/open-target-policy.ts` 中同名函数的镜像。PoC 必须是可直接拷贝到远端运行的 `.mjs` 文件,不能 import 主程序的 TypeScript 模块,因此这段判断是**有意重复**的。`scripts/acceleration-poc/target-guard-parity.test.mjs` 会逐条比对两边的分类结果,任何一侧改动而另一侧未同步都会让 CI 失败。
该测试放在 PoC 目录内而非 `src/` 下:`.dockerignore` 把 `scripts/acceleration-poc` 排除在 Docker 构建上下文之外,而 Dockerfile 会对 `src/**` 执行 `tsc`,因此 `src/` 下任何 import 该目录的文件都会让镜像构建以 TS2307 失败。
## 通过隧道连接指定 TeamSpeak
必须先将下方示例域名替换为你获准测试的 TeamSpeak 地址;脚本不内置真实服务器默认值。下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
+60 -29
View File
@@ -7,38 +7,66 @@ function endpointKey(address, port) {
return `${address}/${port}`;
}
function isPrivateAddress(host) {
const family = isIP(host);
if (family === 4) {
const octets = host.split(".").map(Number);
return octets[0] === 10
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|| octets[0] === 192 && octets[1] === 168
|| octets[0] === 127
|| octets[0] === 169 && octets[1] === 254
|| octets[0] === 0;
/**
* Mirror of `isRestrictedAddress()` in `src/security/open-target-policy.ts`.
*
* The PoC ships as a plain `.mjs` file that the README documents copying to a
* remote host without a build step, so it cannot import the TypeScript policy.
* The logic is duplicated rather than shared, and
* `scripts/acceleration-poc/target-guard-parity.test.mjs` fails the moment the two
* classifications disagree, so drift is caught in CI instead of in production.
*
* Keep this an exact mirror: fail closed on anything that is not a literal
* public address.
*/
export function isRestrictedAddress(host) {
const version = isIP(host);
if (version === 4) return isRestrictedIpv4(host);
if (version !== 6) return true;
const normalized = host.toLowerCase();
if (normalized === "::" || normalized === "::1") return true;
if (normalized.startsWith("::ffff:")) {
// IPv4-mapped addresses must be unwrapped before the IPv4 rules apply:
// ::ffff:10.0.0.1 is private traffic in IPv6 clothing.
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
if (family === 6) {
const normalized = host.toLowerCase();
return normalized === "::1"
|| normalized === "::"
|| normalized.startsWith("fc")
|| normalized.startsWith("fd")
|| normalized.startsWith("fe8")
|| normalized.startsWith("fe9")
|| normalized.startsWith("fea")
|| normalized.startsWith("feb");
}
return host === "localhost" || host.endsWith(".localhost");
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
if (normalized.startsWith("2001:db8:")) return true; // documentation range
return false;
}
function isRestrictedIpv4(host) {
const parts = host.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
const [a, b, c] = parts;
return a === 0
|| a === 10
|| a === 127
|| (a === 100 && b >= 64 && b <= 127)
|| (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 0)
|| (a === 192 && b === 168)
|| (a === 198 && (b === 18 || b === 19))
|| (a === 198 && b === 51 && c === 100)
|| (a === 203 && b === 0 && c === 113)
|| a >= 224;
}
async function resolveTarget(host) {
const family = isIP(host);
if (family) return { host, family };
if (family) return { host, family, resolved: [host] };
const records = await lookup(host, { all: true, verbatim: true });
const record = records.find((item) => item.family === 4) ?? records[0];
if (!record) throw new Error("TARGET_DNS_EMPTY");
return { host: record.address, family: record.family };
return { host: record.address, family: record.family, resolved: records.map((item) => item.address) };
}
export async function createRelayServer({
@@ -71,11 +99,6 @@ export async function createRelayServer({
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) {
return;
}
if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) {
const error = { code: "PRIVATE_TARGET_BLOCKED" };
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
return;
}
const existing = sessions.get(frame.sessionId);
if (existing) cleanup(existing);
@@ -92,6 +115,14 @@ export async function createRelayServer({
try {
const target = await resolveTarget(request.targetHost);
// Validate the resolved addresses, not the caller-supplied name: a DNS
// answer can point any hostname at loopback or an internal address.
if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) {
const error = { code: "PRIVATE_TARGET_BLOCKED" };
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
cleanup(session);
return;
}
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
session.targetSocket = targetSocket;
targetSocket.on("message", (payload) => {
+2 -2
View File
@@ -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));
+58 -1
View File
@@ -51,6 +51,59 @@ async function run() {
rejectedBadToken = true;
}
// SSRF guard: a relay started without allowPrivate must refuse every request
// that resolves to a non-public address, and must still serve public ones.
// Asserting only the happy path would let the private-address guard regress
// unnoticed, since the throughput relay above runs with allowPrivate: true.
const guardedRelay = await createRelayServer({
host: "127.0.0.1",
port: 0,
token: TOKEN,
allowPrivate: false,
});
const blockedTargets = ["127.0.0.1", "10.0.0.1", "169.254.169.254", "192.168.1.1", "::ffff:127.0.0.1"];
const blockedResults = [];
for (const targetHost of blockedTargets) {
let allowed = false;
try {
const tunnel = await createRelayClient({
relayHost: "127.0.0.1",
relayPort: guardedRelay.port,
targetHost,
targetPort: 9987,
token: TOKEN,
timeoutMs: 1_000,
});
tunnel.close();
allowed = true;
} catch (error) {
// The relay answers OPEN_ERR(PRIVATE_TARGET_BLOCKED); any other failure
// (timeout, bad token) would not prove the guard fired.
allowed = !(error instanceof Error && error.message === "PRIVATE_TARGET_BLOCKED");
}
blockedResults.push({ targetHost, blocked: !allowed });
}
let publicTargetAllowed = false;
try {
const tunnel = await createRelayClient({
relayHost: "127.0.0.1",
relayPort: guardedRelay.port,
targetHost: "8.8.8.8",
targetPort: 9987,
token: TOKEN,
timeoutMs: 2_000,
});
publicTargetAllowed = true;
tunnel.close();
} catch {
publicTargetAllowed = false;
}
guardedRelay.close();
const guardFailures = blockedResults.filter((entry) => !entry.blocked);
const ssrfGuardOk = guardFailures.length === 0 && publicTargetAllowed;
const sender = createSocket("udp4");
await bind(sender);
const pending = new Map();
@@ -90,7 +143,11 @@ async function run() {
console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`);
console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`);
console.log(`bad_token_rejected=${rejectedBadToken}`);
if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED");
console.log(`ssrf_guard_ok=${ssrfGuardOk} blocked=${blockedResults.filter((entry) => entry.blocked).length}/${blockedResults.length} public_target_allowed=${publicTargetAllowed}`);
for (const entry of blockedResults) {
if (!entry.blocked) console.log(` LEAK: ${entry.targetHost} was not blocked by the private-target guard`);
}
if (received !== PACKET_COUNT || !rejectedBadToken || !ssrfGuardOk) throw new Error("ACCELERATION_POC_FAILED");
console.log("ACCELERATION_POC_OK");
}
@@ -0,0 +1,88 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRestrictedAddress } from "../../src/security/open-target-policy.js";
import { isRestrictedAddress as isPocRestrictedAddress } from "./relay-server.mjs";
/**
* The acceleration PoC relay keeps its own copy of the restricted-address
* predicate because it is a standalone `.mjs` file that the README documents
* copying to a remote host without a build step, so it cannot import the
* gateway's TypeScript module. Duplication is only safe while the two stay
* identical: these cases pin both classifications to the same answer, so a
* change to either side without the other fails here instead of silently
* widening the PoC's SSRF boundary.
*
* This test lives beside the PoC because `.dockerignore` excludes
* `scripts/acceleration-poc` from the Docker build context while the Dockerfile
* runs `tsc` over `src/**`; a copy under `src/` would make the image build fail
* with TS2307.
*/
const CASES = [
// Public addresses that must stay reachable.
["8.8.8.8", false],
["1.1.1.1", false],
["172.32.0.1", false],
["100.128.0.1", false],
["2001:4860:4860::8888", false],
["2606:4700:4700::1111", false],
// Private, loopback and link-local.
["10.0.0.1", true],
["172.16.0.1", true],
["172.31.255.255", true],
["192.168.1.1", true],
["127.0.0.1", true],
["169.254.169.254", true],
["0.0.0.0", true],
["0.1.2.3", true],
// Carrier-grade NAT.
["100.64.0.1", true],
["100.127.255.255", true],
// Special-use ranges: the PoC's first implementation missed every one of these.
["192.0.0.1", true],
["192.0.2.5", true],
["198.18.0.1", true],
["198.19.5.5", true],
["198.51.100.7", true],
["203.0.113.9", true],
["224.0.0.1", true],
["239.1.1.1", true],
["255.255.255.255", true],
// IPv6 loopback, unspecified, unique-local, link-local, site-local, multicast.
["::1", true],
["::", true],
["fc00::1", true],
["fd12::1", true],
["fe80::1", true],
["fec0::1", true],
["ff02::1", true],
["2001:db8::1", true],
// IPv4-mapped forms must unwrap before the IPv4 rules apply.
["::ffff:127.0.0.1", true],
["::ffff:10.0.0.1", true],
["::ffff:8.8.8.8", false],
// Anything that is not a literal address fails closed.
["localhost", true],
["public.example.invalid", true],
["", true],
];
test("the acceleration PoC relay classifies restricted addresses exactly like the gateway policy", () => {
const mismatches = [];
for (const [address, expected] of CASES) {
const policy = isRestrictedAddress(address);
const poc = isPocRestrictedAddress(address);
assert.equal(policy, expected, `gateway policy disagrees with the pinned expectation for ${address}`);
if (poc !== policy) {
mismatches.push(`${address}: policy=${policy} poc=${poc}`);
}
}
assert.deepEqual(mismatches, [], "the PoC relay's restricted-address guard drifted from the gateway policy");
});
test("the acceleration PoC relay fails closed on a non-literal address", () => {
// `isIP()` returns 0 for a hostname, so the guard must not treat an
// unresolved name as public just because it is not a literal address.
for (const hostname of ["localhost", "internal.example.invalid", "attacker.example.invalid", ""]) {
assert.equal(isPocRestrictedAddress(hostname), true, `${hostname} must fail closed`);
}
});
+3 -7
View File
@@ -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) => {
-48
View File
@@ -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 });
}
+6
View File
@@ -0,0 +1,6 @@
export class AdminInputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "AdminInputError";
}
}
+95 -5
View File
@@ -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
View File
@@ -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";
}
}
+8 -3
View File
@@ -1,3 +1,4 @@
import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../shared/skin-workspace.js";
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
import { compileSkinCss, SkinCssValidationError, type SkinCssSchemaVersion } from "../shared/skin-css.js";
import { parseSkinLayoutJson } from "../shared/skin-layout.js";
@@ -58,6 +59,7 @@ type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" |
content?: string;
components?: string;
plugins?: string;
workspace?: SkinWorkspacePolicy;
preview?: string;
};
@@ -214,7 +216,7 @@ async function writeAtomicJson(filename: string, value: unknown): Promise<void>
}
}
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
const entries = inspectArchive(bytes);
const regularEntries = entries.filter((entry) => !entry.isDirectory);
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
@@ -472,7 +474,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion >= 2) {
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); }
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); }
if (schemaVersion === 4) fields.add("plugins");
const unknown = Object.keys(value).find((key) => !fields.has(key));
if (unknown) throw new SkinRegistryError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
@@ -482,6 +484,9 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
return item.trim();
};
let workspace: SkinWorkspacePolicy | undefined;
try { workspace = parseSkinWorkspacePolicy(value.workspace, schemaVersion); }
catch (error) { throw new SkinRegistryError(error instanceof Error ? error.message : "Invalid workspace policy.", "SKIN_MANIFEST_INVALID"); }
const id = read("id", 80);
if (!isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion === 2 && (value.packageType !== "layout-skin" || !Array.isArray(value.permissions) || value.permissions.length !== 0)) {
@@ -507,7 +512,7 @@ function parseManifest(bytes: Buffer): ParsedSkinManifest {
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
const description = readOptional("description", 400);
return { schemaVersion, ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
return { schemaVersion, ...(workspace ? { workspace } : {}), ...(schemaVersion === 2 ? { packageType: "layout-skin" as const } : schemaVersion >= 3 ? { packageType: "open-skin" as const } : {}), id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(layout ? { layout } : {}), ...(content ? { content } : {}), ...(components ? { components } : {}), ...(plugins ? { plugins } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
}
function singleRootPrefix(paths: string[]): string {
+142
View File
@@ -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);
}
}
+324
View File
@@ -0,0 +1,324 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { createServer } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { QueryClient, type QueryClientOptions } from "@honeybbq/teamspeak/query";
import { WebSpeakDatabase } from "../persistence/database.js";
import { decryptSecret } from "../security/secret-crypto.js";
import type { TsAdminAction } from "../shared/admin-inputs.js";
import type { Logger } from "../logger.js";
import { TsAdminService } from "./ts-admin-service.js";
import { webQueryFetch } from "./webquery-fetch.js";
const uid = "a-real-voice-identity=";
const channel = { cid: "1", cpid: "0", channel_name: "Lobby", total_clients: "1", channel_flag_password: "0" };
const member = { clid: "42", client_database_id: "77", client_unique_identifier: uid, client_nickname: "Guest", cid: "1", client_type: "0", client_servergroups: "6,7" };
type Reply = { body: Record<string, string>[]; status: { code: number; message: string } };
const ok = (body: Reply["body"] = []): Reply => ({ body, status: { code: 0, message: "ok" } });
const denied = (): Reply => ({ body: [], status: { code: 2568, message: "insufficient permissions: secret-value-must-not-escape" } });
function deferred() { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done; }); return { resolve, promise }; }
const hasCode = (code: string) => (error: any) => error.code === code && error.message === code;
/** Real published QueryClient + WebQuery transport, with a disposable HTTP server. */
async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
const directory = mkdtempSync(join(tmpdir(), "webspeak-ts-admin-"));
const database = new WebSpeakDatabase(join(directory, "test.sqlite"));
const master = Buffer.alloc(32, 5), logs: unknown[] = [];
const logger: Logger = { debug() {}, info() {}, error() {}, warn(...args: unknown[]) { logs.push(args); }, child() { return this; } };
const policy = { mode: "fixed" as "fixed" | "open", target: "127.0.0.1:9987" };
const calls: Array<{ path: string; command: string; params: Record<string, string>; key: string }> = [];
const clients: QueryClient[] = [];
const clientOptions: QueryClientOptions[] = [];
let httpStatus = 200;
let httpCommand: string | undefined;
let jsonErrors = false;
let reply: (command: string, params: Record<string, string>) => Reply | Promise<Reply> = command => {
switch (command) {
case "version": return ok([{ version: family === "ts3" ? "3.13.7" : "6.0.0-beta13" }]);
case "whoami": return ok([{ client_id: "99" }]);
case "serverinfo": return ok([{ virtualserver_name: "Test TeamSpeak", virtualserver_welcomemessage: "Welcome", virtualserver_maxclients: "32", virtualserver_uptime: "123" }]);
case "channellist": return ok([channel]);
case "clientlist": return ok([member]);
case "servergrouplist": return ok([{ sgid: "6", name: "Member", type: "1" }, { sgid: "1", name: "Query template", type: "0" }]);
case "banlist": return ok([{ banid: "8", uid, lastnickname: "Guest", reason: "Test", duration: "3600", created: "1700000000" }]);
case "channelcreate": return ok([{ cid: "2" }]);
case "banadd": return ok([{ banid: "9" }]);
default: return ok();
}
};
const server = createServer(async (req, res) => {
let body = "";
for await (const chunk of req) body += String(chunk);
const path = req.url!, command = path.split("/").at(-1)!;
const params = JSON.parse(body || "{}");
calls.push({ path, command, params, key: String(req.headers["x-api-key"]) });
const answer = await reply(command, params);
res.setHeader("content-type", "application/json");
res.statusCode = httpCommand === undefined || httpCommand === command ? httpStatus : 200;
res.end(res.statusCode === 200 || jsonErrors ? JSON.stringify(answer) : "Access denied");
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address(); assert.ok(address && typeof address !== "string");
const service = new TsAdminService(database, master, logger, () => policy, options => {
clientOptions.push(options);
const client = new QueryClient(options); clients.push(client); return client;
});
const settings = { enabled: true, transport: "web" as const, queryPort: 10022, queryHost: "", username: "", hostKeyFingerprint: "",
webQueryUrl: `http://127.0.0.1:${address.port}/query`, serverId: 7, apiKey: "secret-local-fixture-api-key", apiKeyAction: "replace" as const };
service.save(settings);
t.after(async () => {
await Promise.all(clients.map(client => client.disconnect()));
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
database.close(); rmSync(directory, { recursive: true, force: true });
});
return { service, database, master, settings, calls, policy, logs, clientOptions,
action: (operation: unknown) => service.action({ operation, configurationRevision: service.settings().configurationRevision }),
set httpStatus(value: number) { httpStatus = value; },
set httpCommand(value: string) { httpCommand = value; },
set jsonErrors(value: boolean) { jsonErrors = value; },
get reply() { return reply; }, set reply(value) { reply = value; } };
}
for (const family of ["ts3", "ts6"] as const) test(`WebQuery ${family} selects the virtual server, parses typed data and sends no login or notifications`, async t => {
const f = await fixture(t, family);
const result = await f.service.overview();
assert.equal(result.serverFamily, family); assert.equal(result.serverName, "Test TeamSpeak");
assert.equal(result.welcomeMessage, "Welcome"); assert.equal(result.maxClients, 32);
assert.equal(result.channels[0].id, "1"); assert.equal(result.clients[0].uid, uid);
assert.deepEqual(result.groups, [{ id: "6", name: "Member" }]);
assert.equal(result.bans[0].durationSeconds, 3600);
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/") && call.key === f.settings.apiKey));
assert.ok(!f.calls.some(call => /login|notify|clientupdate/.test(call.command)));
assert.equal(f.clientOptions[0].events, undefined, "WebQuery rejects even an explicit events:false option");
assert.equal(f.clientOptions[0].reconnect, undefined);
f.service.save({ ...f.settings, serverId: 0, apiKeyAction: "keep", apiKey: undefined });
f.calls.length = 0;
await f.service.overview();
assert.ok(f.calls.every(call => call.path.startsWith("/query/byport/9987/")));
});
test("Query credentials are encrypted separately, projected out, and keep/remove is explicit", async t => {
const f = await fixture(t);
f.service.save({ ...f.settings, passwordAction: "replace", password: "local-query-password" });
const stored = f.database.getTsAdminSettings();
assert.notEqual(stored.apiKeyEncrypted, f.settings.apiKey);
assert.equal(decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-webquery-api-key:v1"), f.settings.apiKey);
assert.equal(decryptSecret(stored.passwordEncrypted, f.master, "webspeak:ts-admin-query-password:v1"), "local-query-password");
assert.throws(() => decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-query-password:v1"));
const shown = f.service.settings();
assert.equal(shown.hasApiKey, true); assert.equal(shown.hasPassword, true);
assert.ok(!("apiKeyEncrypted" in shown) && !("passwordEncrypted" in shown));
f.service.save({ ...f.settings, apiKey: "ignored", apiKeyAction: "keep" });
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted);
assert.throws(() => f.service.save({ ...f.settings, apiKeyAction: "remove" }), hasCode("INVALID_TS_ADMIN_API_KEY"));
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted, "invalid settings must be atomic");
f.service.save({ ...f.settings, enabled: false, apiKeyAction: "remove", passwordAction: "remove" });
assert.equal(f.service.settings().hasApiKey, false);
assert.equal(f.service.settings().hasPassword, false);
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_NOT_CONFIGURED"));
assert.equal(f.calls.length, 0);
});
test("invalid endpoints and selectors are rejected without changing stored settings", async t => {
const f = await fixture(t), stored = f.database.getTsAdminSettings();
for (const webQueryUrl of ["file:///etc/passwd", "https://user:password@example.com", "https://example.com?api_key=secret", "https://example.com/#fragment", "no-url"]) {
assert.throws(() => f.service.save({ ...f.settings, webQueryUrl }), hasCode("INVALID_TS_ADMIN_URL"));
}
for (const serverId of [-1, 1.2, 4_294_967_296]) assert.throws(() => f.service.save({ ...f.settings, serverId }), hasCode("INVALID_TS_ADMIN_SERVER_ID"));
assert.throws(() => f.service.save({ ...f.settings, queryHost: "host:10022" }), hasCode("INVALID_TS_ADMIN_HOST"));
assert.deepEqual(f.database.getTsAdminSettings(), stored);
f.policy.mode = "open";
assert.throws(() => f.service.save(f.settings), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
});
test("limited list permissions preserve the rest of the overview and error details stay private", async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => ["servergrouplist", "banlist"].includes(command) ? denied() : original(command, params);
const result = await f.service.overview();
assert.equal(result.groupsAvailable, false); assert.equal(result.bansAvailable, false);
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED"); assert.equal(result.bansErrorCode, "TS_ADMIN_PERMISSION_DENIED");
assert.equal(result.channels.length, 1); assert.equal(result.clients.length, 1);
f.reply = (command, params) => command === "serverinfo" ? denied() : original(command, params);
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_PERMISSION_DENIED"));
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
assert.ok(!JSON.stringify(f.logs).includes(f.settings.apiKey));
});
test("Query connections never appear in member lists or channel and server member counts", async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => {
if (command === "clientlist") return ok([member, { ...member, clid: "99", client_type: "1", client_nickname: "serveradmin" }]);
if (command === "channellist") return ok([{ ...channel, total_clients: "2" }, { ...channel, cid: "2", channel_name: "Empty" }]);
return original(command, params);
};
const result = await f.service.overview();
assert.equal(result.clientCount, 1); assert.deepEqual(result.clients.map(entry => entry.id), [42]);
assert.deepEqual(result.channels.map(entry => entry.totalClients), [1, 0]);
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, clid: "99", client_type: "1" }]) : original(command, params);
const empty = await f.service.overview();
assert.equal(empty.clientCount, 0); assert.deepEqual(empty.clients, []); assert.equal(empty.channels[0].totalClients, 0);
});
for (const [code, expected] of [[524, "TS_ADMIN_RATE_LIMITED"], [2568, "TS_ADMIN_PERMISSION_DENIED"], [1538, "TS_ADMIN_READ_FAILED"]] as const) {
test(`optional list error ${code} retains its cause rather than inventing a permission failure`, async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => command === "servergrouplist" ? { body: [], status: { code, message: "private-error-detail" } } : original(command, params);
const result = await f.service.overview();
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
assert.equal(result.bansAvailable, true); assert.equal(result.bansErrorCode, null);
assert.equal(result.clients.length, 1); assert.ok(!JSON.stringify(result).includes("private-error-detail"));
});
}
for (const state of ["disconnected", "reused-id"] as const) test(`a successful UID ban with ${state} does not kick another connection or report partial failure`, async t => {
const f = await fixture(t), original = f.reply;
let banned = false;
f.reply = (command, params) => {
if (command === "banadd") banned = true;
if (command === "clientlist" && banned) return ok(state === "disconnected" ? [] : [{ ...member, client_unique_identifier: "replacement-identity=" }]);
return original(command, params);
};
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
assert.ok(!f.calls.some(call => call.command === "clientkick"));
assert.ok(!f.database.recentAudit(50).some(entry => entry.event === "TS_ADMIN_ACTION_PARTIAL"));
});
test("a banned client leaving between the fresh identity check and kick is successful", async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => command === "clientkick" ? { body: [], status: { code: 512, message: "invalid clientID" } } : original(command, params);
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
});
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [408, "TS_ADMIN_TIMEOUT"], [504, "TS_ADMIN_TIMEOUT"]] as const) test(`HTTP ${status} has a specific safe Query failure`, async t => {
const f = await fixture(t);
f.httpStatus = status;
await assert.rejects(f.service.overview(), hasCode(expected));
});
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [503, "TS_ADMIN_READ_FAILED"]] as const) test(`HTTP ${status} cannot become a successful list through a JSON status.code=0 body`, async t => {
const f = await fixture(t);
f.httpStatus = status; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
const result = await f.service.overview();
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
assert.equal(result.bansAvailable, true); assert.equal(result.clientCount, 1);
});
test("HTTP errors carrying genuine TS permission errors keep the SDK error classification", async t => {
const f = await fixture(t), original = f.reply;
f.httpStatus = 403; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
f.reply = (command, params) => command === "servergrouplist" ? denied() : original(command, params);
const result = await f.service.overview();
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED");
});
test("administrator actions use typed SDK commands, escaping and UID-only bans", async t => {
const f = await fixture(t);
const actions: TsAdminAction[] = [
{ action: "server.update", name: "A | name", welcomeMessage: "Hello\nworld", maxClients: 48 },
{ action: "channel.create", name: "Channel | special", parentId: "1", description: "Line1\nLine2", permanent: true, password: "test password" },
{ action: "channel.update", channelId: "2", name: "New name" },
{ action: "channel.delete", channelId: "2" },
{ action: "client.move", clientId: 42, clientUid: uid, channelId: "1" },
{ action: "client.kick", clientId: 42, clientUid: uid, reason: "Test reason" },
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: false },
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: true },
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID ban", durationSeconds: 3600 },
{ action: "ban.delete", banId: "9" },
];
for (const action of actions) assert.deepEqual(await f.action(action), { ok: true });
const command = (name: string) => f.calls.find(call => call.command === name)!.params;
assert.deepEqual(command("serveredit"), { virtualserver_name: "A | name", virtualserver_welcomemessage: "Hello\nworld", virtualserver_maxclients: "48" });
assert.equal(command("channelcreate").channel_description, "Line1\nLine2");
assert.equal(command("channelcreate").channel_password, "test password");
assert.deepEqual(command("channeledit"), { cid: "2", channel_name: "New name" }, "rename must preserve unread channel metadata");
assert.equal(command("channeldelete").force, "0");
assert.deepEqual(command("clientmove"), { clid: "42", cid: "1" });
assert.equal(command("clientkick").reasonid, "5");
assert.deepEqual(command("servergroupaddclient"), { sgid: "6", cldbid: "77" });
assert.deepEqual(command("servergroupdelclient"), { sgid: "6", cldbid: "77" });
assert.deepEqual(command("banadd"), { uid, time: "3600", banreason: "UID ban" });
assert.equal(command("bandel").banid, "9");
});
test("stale client identities never receive a mutation, and failed writes are not retried", async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, client_unique_identifier: "replacement-identity=" }]) : original(command, params);
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_CLIENT_CHANGED"));
assert.ok(!f.calls.some(call => call.command === "clientkick"));
f.reply = (command, params) => command === "clientkick" ? denied() : original(command, params);
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_PERMISSION_DENIED"));
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
await assert.rejects(f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: 0 }), hasCode("TS_ADMIN_PARTIAL_SUCCESS"));
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
assert.equal(f.calls.find(call => call.command === "banadd")!.params.time, undefined, "permanent UID ban has no expiry");
});
test("configuration changes cancel in-flight and queued writes instead of targeting another server", async t => {
const f = await fixture(t), original = f.reply, entered = deferred(), release = deferred();
f.reply = async (command, params) => {
if (command === "clientlist") { entered.resolve(); await release.promise; }
return original(command, params);
};
const first = f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" });
const queued = f.action({ action: "channel.delete", channelId: "1" });
const firstCheck = assert.rejects(first, hasCode("TS_ADMIN_CONFIG_CHANGED"));
const queuedCheck = assert.rejects(queued, hasCode("TS_ADMIN_CONFIG_CHANGED"));
await entered.promise;
f.service.save({ ...f.settings, serverId: 8 });
release.resolve();
await Promise.all([firstCheck, queuedCheck]);
assert.ok(!f.calls.some(call => ["clientkick", "channeldelete"].includes(call.command)));
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/")));
f.reply = original;
assert.deepEqual(await f.action({ action: "channel.delete", channelId: "2" }), { ok: true }, "failed queue entries must not block later work");
});
test("an old browser snapshot cannot mutate a newly configured management server", async t => {
const f = await fixture(t);
const snapshot = await f.service.overview();
const operation: TsAdminAction = { action: "channel.delete", channelId: "1" };
f.service.save({ ...f.settings, serverId: 8 });
f.calls.length = 0;
assert.throws(() => f.service.action({ operation, configurationRevision: snapshot.configurationRevision }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
assert.throws(() => f.service.action({ operation }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
assert.equal(f.calls.length, 0, "stale UI must fail before connecting to the new server");
});
test("administrator command whitelist rejects arbitrary commands and invalid object identifiers", async t => {
const f = await fixture(t);
for (const action of [null, [], { action: "serverstop" }, { action: "channel.delete", channelId: "0" },
{ action: "channel.delete", channelId: "1|serverstop" }, { action: "channel.delete", channelId: "18446744073709551616" },
{ action: "client.kick", clientId: 42, clientUid: "", reason: "" },
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: -1 },
{ action: "server.update", name: "", welcomeMessage: "", maxClients: 32 },
]) assert.throws(() => f.action(action), hasCode("INVALID_TS_ADMIN_ACTION"));
assert.equal(f.calls.length, 0);
});
test("WebQuery HTTP and TS API-key authentication failures have a useful safe error", async t => {
const f = await fixture(t);
for (const status of [401, 403]) {
f.httpStatus = status;
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
}
f.httpStatus = 200;
f.reply = () => ({ body: [], status: { code: 5122, message: "invalid API key: secret-value-must-not-escape" } });
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
});
test("disposing an administrator request cancels its underlying WebQuery HTTP request", async t => {
const f = await fixture(t), entered = deferred(), release = deferred(), controller = new AbortController();
f.reply = async () => { entered.resolve(); await release.promise; return ok(); };
const pending = webQueryFetch(controller.signal)(`${f.settings.webQueryUrl}/7/version`, { method: "POST", body: "{}" });
const check = assert.rejects(pending, (error: any) => error.name === "AbortError");
await entered.promise;
controller.abort(); await check;
release.resolve();
});
+302
View File
@@ -0,0 +1,302 @@
import { isIP } from "node:net";
import { createHash } from "node:crypto";
import {
addBan, addClientToServerGroup, asBanID, asChannelID, asClientID, asServerGroupID,
createChannel, deleteBan, deleteChannel, editChannel, editServer, getServerInfo, kickClient,
listBans, listChannels, listClients, listServerGroups, moveClient, Reason,
removeClientFromServerGroup, ServerError, ErrorCode, CommandTimeoutError, type CommandOptions,
} from "@honeybbq/teamspeak";
import { QueryClient, WebQueryHttpError, type QueryClientOptions } from "@honeybbq/teamspeak/query";
import type { Logger } from "../logger.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
import type { TsAdminAction, TsAdminSettingsInput } from "../shared/admin-inputs.js";
import { resolveTeamSpeakTarget } from "../server/teamspeak-alias.js";
import { AdminInputError } from "./admin-errors.js";
import { webQueryFetch } from "./webquery-fetch.js";
const PASSWORD_PURPOSE = "webspeak:ts-admin-query-password:v1";
const API_KEY_PURPOSE = "webspeak:ts-admin-webquery-api-key:v1";
export type TsAdminQueryClientFactory = (options: QueryClientOptions) => QueryClient;
type Policy = { mode: "fixed" | "open"; target: string };
/** Optional administrator access. Guest voice and WebSpeak management never use these credentials. */
export class TsAdminService {
private actions: Promise<unknown> = Promise.resolve();
constructor(
private readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
private readonly logger: Logger,
private readonly policy: () => Policy,
private readonly createClient: TsAdminQueryClientFactory = options => new QueryClient(options),
) {}
settings() {
const { passwordEncrypted, apiKeyEncrypted, ...settings } = this.database.getTsAdminSettings();
return { ...settings, configurationRevision: this.configuration(), fixedMode: this.policy().mode === "fixed", hasPassword: Boolean(passwordEncrypted), hasApiKey: Boolean(apiKeyEncrypted) };
}
save(input: TsAdminSettingsInput): void {
this.assertFixed();
const current = this.database.getTsAdminSettings();
const transport = input.transport ?? current.transport;
if (!["web", "ssh", "tcp"].includes(transport) || typeof input.enabled !== "boolean") fail("INVALID_TS_ADMIN_SETTINGS");
const queryPort = input.queryPort;
if (!Number.isInteger(queryPort) || queryPort < 1 || queryPort > 65535) fail("INVALID_TS_ADMIN_QUERY_PORT");
const username = text(input.username, 128).trim();
const hostKeyFingerprint = text(input.hostKeyFingerprint, 128).trim();
const queryHost = text(input.queryHost ?? current.queryHost, 253).trim();
if (queryHost && !isIP(queryHost) && !/^(?=.{1,253}$)[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i.test(queryHost)) fail("INVALID_TS_ADMIN_HOST");
let webQueryUrl = text(input.webQueryUrl ?? current.webQueryUrl, 2048).trim();
if (webQueryUrl) {
try {
const url = new URL(webQueryUrl);
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash) throw new Error();
webQueryUrl = url.toString().replace(/\/+$/, "");
} catch { fail("INVALID_TS_ADMIN_URL"); }
}
const serverId = input.serverId ?? current.serverId;
if (!Number.isSafeInteger(serverId) || serverId < 0 || serverId > 4_294_967_295) fail("INVALID_TS_ADMIN_SERVER_ID");
const passwordEncrypted = this.secret(input.password, input.passwordAction, current.passwordEncrypted, PASSWORD_PURPOSE, 1024);
const apiKeyEncrypted = this.secret(input.apiKey, input.apiKeyAction, current.apiKeyEncrypted, API_KEY_PURPOSE, 4096);
if (input.enabled) {
if (transport === "web") {
if (!webQueryUrl) fail("INVALID_TS_ADMIN_URL");
if (!apiKeyEncrypted) fail("INVALID_TS_ADMIN_API_KEY");
} else {
if (!username) fail("INVALID_TS_ADMIN_USERNAME");
if (!passwordEncrypted) fail("INVALID_TS_ADMIN_PASSWORD");
if (transport === "ssh" && !/^SHA256:[A-Za-z0-9+/]{43}$/.test(hostKeyFingerprint)) fail("INVALID_TS_ADMIN_HOST_KEY");
}
}
this.database.updateTsAdminSettings({ enabled: input.enabled, transport, queryHost, queryPort, username,
passwordEncrypted, apiKeyEncrypted, webQueryUrl, serverId, hostKeyFingerprint });
}
async overview() {
return this.withClient(async (client, options, assertCurrent) => {
const [server, channels, clients] = await Promise.all([
getServerInfo(client, options), listChannels(client, options),
listClients(client, { ...options, uid: true, away: true, voice: true, groups: true }),
]);
const [groups, bans] = await Promise.allSettled([listServerGroups(client, options), listBans(client, options)]);
assertCurrent();
const voiceClients = clients.filter(entry => entry.type === 0);
const channelMembers = new Map<string, number>();
for (const entry of voiceClients) {
const id = String(entry.channelID);
channelMembers.set(id, (channelMembers.get(id) ?? 0) + 1);
}
this.database.addAudit("TS_ADMIN_OVERVIEW_READ", { channels: channels.length, clients: voiceClients.length });
return {
configurationRevision: this.configuration(),
serverName: server.virtualserver_name ?? "", serverVersion: client.serverVersion, serverFamily: client.serverFamily,
welcomeMessage: server.virtualserver_welcomemessage ?? "", maxClients: numeric(server.virtualserver_maxclients),
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: voiceClients.length,
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
description: channel.description, totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
serverGroups: entry.serverGroups.map(String), away: entry.isAway, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
groups: groups.status === "fulfilled" ? groups.value.filter(group => group.type === 1).map(group => ({ id: String(group.id), name: group.name })) : [],
bans: bans.status === "fulfilled" ? bans.value.map(ban => ({ id: String(ban.id), name: ban.name || ban.lastNickname,
uid: ban.uid, reason: ban.reason, durationSeconds: ban.durationMs / 1000, createdAt: ban.createdAt?.toISOString() ?? null })) : [],
groupsAvailable: groups.status === "fulfilled", bansAvailable: bans.status === "fulfilled",
groupsErrorCode: groups.status === "fulfilled" ? null : classifyError(groups.reason, "TS_ADMIN_READ_FAILED"),
bansErrorCode: bans.status === "fulfilled" ? null : classifyError(bans.reason, "TS_ADMIN_READ_FAILED"),
observedAt: new Date().toISOString(),
};
}, undefined, "TS_ADMIN_READ_FAILED");
}
/** Serialize writes, then revalidate live client identities immediately before changing them. */
action(raw: unknown): Promise<{ ok: true }> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
const request = raw as Record<string, unknown>;
const action = readAction(request.operation);
// Bind queued work to the configuration the administrator reviewed.
const expected = this.configuration();
if (request.configurationRevision !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
const operation = this.actions.then(() => this.withClient(async (client, options, assertCurrent) => {
assertCurrent();
switch (action.action) {
case "server.update":
await editServer(client, { virtualserver_name: action.name, virtualserver_welcomemessage: action.welcomeMessage,
virtualserver_maxclients: String(action.maxClients) }, options); break;
case "channel.create":
await createChannel(client, { name: action.name, parentID: asChannelID(BigInt(action.parentId)),
description: action.description, isPermanent: action.permanent, password: action.password }, options); break;
case "channel.update":
await editChannel(client, asChannelID(BigInt(action.channelId)), { name: action.name }, options); break;
case "channel.delete":
await deleteChannel(client, asChannelID(BigInt(action.channelId)), { ...options, force: false }); break;
case "ban.delete":
await deleteBan(client, asBanID(BigInt(action.banId)), options); break;
default: {
const current = (await listClients(client, { ...options, uid: true, groups: true })).find(entry => Number(entry.id) === action.clientId);
if (!current || !current.uid || current.uid !== action.clientUid || current.type !== 0) fail("TS_ADMIN_CLIENT_CHANGED");
assertCurrent();
if (action.action === "client.move") await moveClient(client, current.id, asChannelID(BigInt(action.channelId)), options);
else if (action.action === "client.kick") await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason });
else if (action.action === "client.group") {
if (!current.databaseID) fail("TS_ADMIN_CLIENT_CHANGED");
const change = action.remove ? removeClientFromServerGroup : addClientToServerGroup;
await change(client, asServerGroupID(BigInt(action.groupId)), current.databaseID, options);
} else {
// Banning the gateway's IP would disconnect unrelated WebSpeak users.
await addBan(client, { uid: current.uid, reason: action.reason, durationMs: action.durationSeconds * 1000 }, options);
try {
assertCurrent();
// TS may disconnect the banned identity itself. Never kick a replacement that reused its ID.
const remaining = (await listClients(client, { ...options, uid: true })).find(entry => entry.id === current.id);
assertCurrent();
if (remaining?.uid === current.uid && remaining.type === 0) {
try { await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason }); }
catch (error) {
// The same client can leave between the fresh list and the kick.
if (!(error instanceof ServerError && error.code === ErrorCode.ClientInvalidID)) throw error;
}
}
}
catch { this.database.addAudit("TS_ADMIN_ACTION_PARTIAL", { action: action.action }); fail("TS_ADMIN_PARTIAL_SUCCESS"); }
}
}
}
this.database.addAudit("TS_ADMIN_ACTION_SUCCEEDED", { action: action.action });
return { ok: true as const };
}, expected)).catch(error => {
this.database.addAudit("TS_ADMIN_ACTION_FAILED", { action: action.action });
throw error;
});
this.actions = operation.catch(() => undefined);
return operation;
}
private configuration(): string {
return createHash("sha256").update(JSON.stringify([this.policy(), this.database.getTsAdminSettings()])).digest("hex");
}
private async withClient<T>(run: (client: QueryClient, options: CommandOptions, assertCurrent: () => void) => Promise<T>, expected?: string, failureCode = "TS_ADMIN_OPERATION_FAILED"): Promise<T> {
this.assertFixed();
if (expected !== undefined && this.configuration() !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
const settings = this.database.getTsAdminSettings();
if (!settings.enabled) fail("TS_ADMIN_NOT_CONFIGURED");
const policy = this.policy();
const captured = JSON.stringify(settings);
const assertCurrent = () => {
this.assertFixed();
if (this.policy().target !== policy.target || JSON.stringify(this.database.getTsAdminSettings()) !== captured) fail("TS_ADMIN_CONFIG_CHANGED");
};
let target: { host: string; port: number } | undefined;
if (!settings.serverId || settings.transport !== "web" && !settings.queryHost) {
try { target = await resolveTeamSpeakTarget(policy.target); } catch { fail("TS_ADMIN_TARGET_UNAVAILABLE"); }
}
const lifetime = new AbortController();
let transport: QueryClientOptions["transport"];
if (settings.transport === "web") {
if (!settings.webQueryUrl || !settings.apiKeyEncrypted) fail("TS_ADMIN_NOT_CONFIGURED");
transport = { kind: "web", url: settings.webQueryUrl, apiKey: this.decrypt(settings.apiKeyEncrypted, API_KEY_PURPOSE), fetch: webQueryFetch(lifetime.signal) };
} else {
if (!settings.passwordEncrypted || !settings.username) fail("TS_ADMIN_NOT_CONFIGURED");
const host = settings.queryHost || target!.host;
const password = this.decrypt(settings.passwordEncrypted, PASSWORD_PURPOSE);
transport = settings.transport === "tcp"
? { kind: "tcp", host, port: settings.queryPort, login: { name: settings.username, password } }
: { kind: "ssh", host, port: settings.queryPort, username: settings.username, password, hostKey: key => {
if (key.fingerprint !== settings.hostKeyFingerprint) fail("TS_ADMIN_HOST_KEY_MISMATCH");
} };
}
assertCurrent();
let client: QueryClient | undefined;
let connected = false;
try {
client = this.createClient({ transport, server: settings.serverId ? { id: settings.serverId } : { port: target!.port },
nickname: "WebSpeak Admin", ...(settings.transport === "web" ? {} : { events: false }) });
const signal = AbortSignal.timeout(20_000);
await client.connect({ signal }); connected = true; assertCurrent();
return await run(client, { signal, timeoutMs: 8_000 }, assertCurrent);
} catch (error) {
if (error instanceof AdminInputError) throw error;
const code = classifyError(error, connected ? failureCode : "TS_ADMIN_CONNECTION_FAILED");
this.logger.warn({ code, transport: settings.transport }, "TeamSpeak administrator request failed");
return fail(code);
} finally {
lifetime.abort();
try { await client?.disconnect(); } catch { /* no connection can outlive its request */ }
}
}
private assertFixed(): void { if (this.policy().mode !== "fixed") fail("TS_ADMIN_FIXED_MODE_REQUIRED"); }
private decrypt(value: string, purpose: string): string {
try { return decryptSecret(value, this.masterSecret, purpose); } catch { fail("TS_ADMIN_CREDENTIALS_UNAVAILABLE"); }
}
private secret(value: string | undefined, action: "keep" | "replace" | "remove" | undefined, current: string | null, purpose: string, max: number): string | null {
if (action === "remove") return null;
if (action === "replace" || action === undefined && value !== undefined) {
const secret = text(value ?? "", max);
return secret ? encryptSecret(secret, this.masterSecret, purpose) : null;
}
if (action !== undefined && action !== "keep") fail("INVALID_TS_ADMIN_SETTINGS");
return current;
}
}
function fail(code: string): never { throw new AdminInputError(code, code); }
function text(value: unknown, max: number, required = false): string {
if (typeof value !== "string" || value.length > max || /[\0]/.test(value) || required && !value.trim()) fail("INVALID_TS_ADMIN_ACTION");
return value;
}
function numeric(value: string | undefined): number { const n = Number(value); return Number.isFinite(n) && n >= 0 ? n : 0; }
function id(value: unknown, zero = false): string {
const v = text(value, 20, true);
if (!/^\d+$/.test(v) || BigInt(v) > 18_446_744_073_709_551_615n || !zero && BigInt(v) === 0n) fail("INVALID_TS_ADMIN_ACTION");
return v;
}
function readAction(raw: unknown): TsAdminAction {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
const r = raw as Record<string, unknown>;
const action = r.action;
if (action === "server.update") {
if (!Number.isInteger(r.maxClients) || Number(r.maxClients) < 1 || Number(r.maxClients) > 65535) fail("INVALID_TS_ADMIN_ACTION");
return { action, name: text(r.name, 64, true), welcomeMessage: text(r.welcomeMessage, 4096), maxClients: Number(r.maxClients) };
}
if (action === "channel.create") {
if (typeof r.permanent !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
return { action, name: text(r.name, 40, true), parentId: id(r.parentId, true), description: text(r.description, 8192),
permanent: r.permanent, ...(r.password === undefined ? {} : { password: text(r.password, 512) }) };
}
if (action === "channel.update") return { action, channelId: id(r.channelId), name: text(r.name, 40, true) };
if (action === "channel.delete") return { action, channelId: id(r.channelId) };
if (action === "ban.delete") return { action, banId: id(r.banId) };
if (!Number.isInteger(r.clientId) || Number(r.clientId) < 1 || Number(r.clientId) > 65535) fail("INVALID_TS_ADMIN_ACTION");
const member = { clientId: Number(r.clientId), clientUid: text(r.clientUid, 128, true) };
if (action === "client.move") return { action, ...member, channelId: id(r.channelId) };
if (action === "client.kick") return { action, ...member, reason: text(r.reason, 200) };
if (action === "client.group") {
if (typeof r.remove !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
return { action, ...member, groupId: id(r.groupId), remove: r.remove };
}
if (action === "client.ban") {
if (!Number.isSafeInteger(r.durationSeconds) || Number(r.durationSeconds) < 0 || Number(r.durationSeconds) > 31_536_000) fail("INVALID_TS_ADMIN_ACTION");
return { action, ...member, reason: text(r.reason, 200), durationSeconds: Number(r.durationSeconds) };
}
fail("INVALID_TS_ADMIN_ACTION");
}
function classifyError(error: unknown, fallback: string): string {
const seen = new Set<unknown>();
while (error instanceof Error && !seen.has(error)) {
seen.add(error);
if (error.message === "TS_ADMIN_HOST_KEY_MISMATCH") return error.message;
if (error instanceof WebQueryHttpError && [401, 403].includes(error.status)) return "TS_ADMIN_AUTH_FAILED";
if (error instanceof WebQueryHttpError && error.status === 429) return "TS_ADMIN_RATE_LIMITED";
if (error instanceof CommandTimeoutError || ["TimeoutError", "AbortError"].includes(error.name)
|| error instanceof WebQueryHttpError && [408, 504].includes(error.status)) return "TS_ADMIN_TIMEOUT";
if (error instanceof ServerError) {
if ([2568, 2569, 2570, 5120].includes(error.code)) return "TS_ADMIN_PERMISSION_DENIED";
if ([520, 5122, 5124].includes(error.code)) return "TS_ADMIN_AUTH_FAILED";
if (error.code === 524) return "TS_ADMIN_RATE_LIMITED";
}
if (/CERT|SELF_SIGNED|UNABLE_TO_VERIFY/i.test(String((error as NodeJS.ErrnoException).code ?? ""))) return "TS_ADMIN_TLS_FAILED";
error = error.cause;
}
return fallback;
}
+40
View File
@@ -0,0 +1,40 @@
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
import { WebQueryHttpError } from "@honeybbq/teamspeak/query";
/** Keep the SDK's WebQuery protocol, but bound HTTP requests to this admin operation.
* Node's global fetch blocks WebQuery's default port 10080. */
export function webQueryFetch(lifetime: AbortSignal): typeof fetch {
return ((url: string, init: RequestInit) => new Promise<Response>((resolve, reject) => {
const request = new URL(url).protocol === "https:" ? httpsRequest : httpRequest;
const req = request(url, {
method: init.method, headers: init.headers as Record<string, string>,
signal: AbortSignal.any([lifetime, AbortSignal.timeout(8_000)]),
}, res => {
const chunks: Buffer[] = [];
let size = 0;
res.on("data", (chunk: Buffer) => {
size += chunk.length;
if (size > 8 * 1024 * 1024) { res.destroy(new Error("WebQuery response too large")); return; }
chunks.push(chunk);
});
res.on("error", reject);
res.on("end", () => {
const body = Buffer.concat(chunks), status = res.statusCode ?? 502;
if (status < 200 || status >= 300) {
// SDK beta.19 accepts status.code=0 even on HTTP failures. Keep genuine TS errors,
// but never turn a proxy's failed HTTP response into a successful empty result.
let tsError = false;
try {
const code: unknown = JSON.parse(body.toString("utf8"))?.status?.code;
tsError = typeof code === "number" && Number.isSafeInteger(code) && code > 0;
} catch { /* HTTP status is authoritative when no TS error is present. */ }
if (!tsError) { reject(new WebQueryHttpError(status, res.statusMessage ?? "")); return; }
}
resolve(new Response(body, { status, statusText: res.statusMessage ?? "" }));
});
});
req.on("error", reject);
req.end(init.body as string);
})) as typeof fetch;
}
+51 -4
View File
@@ -58,6 +58,7 @@ async function main() {
certDir: hasCert ? CERT_DIR : undefined,
voiceBridgeOptions: {
joinTickets,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
webRtc: () => adminService.getWebRtcAudioOptions(),
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
// The public gateway only uses the relay configuration explicitly
@@ -93,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);
@@ -130,6 +172,11 @@ function parseBoolean(value: string | undefined): boolean {
return value === "1" || value?.toLowerCase() === "true";
}
function readTrustedProxies(value: string | undefined): string[] | undefined {
const entries = value?.split(/[\s,]+/).filter(Boolean) ?? [];
return entries.length ? entries : undefined;
}
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
const raw = value?.trim();
if (!raw) return normalizeScreenShareIceServers();
+2 -2
View File
@@ -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.
+53
View File
@@ -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
View File
@@ -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;
`);
});
}
}
+5 -5
View File
@@ -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")),
+177
View File
@@ -0,0 +1,177 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createHmac } from "node:crypto";
import { createSocket, type Socket } from "node:dgram";
import { createAccelerationRelayServer } from "./acceleration-relay.js";
const TOKEN = "test-acceleration-relay-token";
const MAGIC = Buffer.from("WSAT");
const HEADER_SIZE = 34;
const enum FrameType { OPEN = 1, OPEN_OK = 2, OPEN_ERR = 3 }
function encodeFrame(type: FrameType, sessionId: number, payload: Buffer): Buffer {
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
MAGIC.copy(frame, 0);
frame[4] = 1;
frame[5] = type;
frame.writeUInt32BE(sessionId >>> 0, 8);
frame.writeUInt32BE(1, 12);
frame.writeUInt16BE(payload.length, 16);
createHmac("sha256", Buffer.from(TOKEN, "utf8"))
.update(frame.subarray(0, 18)).update(payload)
.digest().subarray(0, 16).copy(frame, 18);
payload.copy(frame, HEADER_SIZE);
return frame;
}
function decodeFrame(packet: Buffer): { type: number; sessionId: number; payload: Buffer } | null {
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== 1) return null;
const length = packet.readUInt16BE(16);
if (packet.length !== HEADER_SIZE + length) return null;
return { type: packet[5]!, sessionId: packet.readUInt32BE(8), payload: packet.subarray(HEADER_SIZE) };
}
const resolved = (...addresses: string[]) => async () => addresses.map((address) => ({
address,
family: address.includes(":") ? 6 : 4,
}));
/** Send one OPEN and resolve with the relay's first reply. */
function openTarget(server: { host: string; port: number }, targetHost: string, targetPort = 9987): Promise<{ type: number; code?: string }> {
const client = createSocket("udp4");
const sessionId = 0x5a5a0001;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
client.close();
reject(new Error("The relay did not answer the OPEN frame"));
}, 3_000);
client.on("message", (packet) => {
const frame = decodeFrame(packet);
if (!frame || frame.sessionId !== sessionId) return;
clearTimeout(timer);
let code: string | undefined;
try { code = (JSON.parse(frame.payload.toString("utf8")) as { code?: string }).code; } catch { code = undefined; }
client.close();
resolve({ type: frame.type, code });
});
const payload = Buffer.from(JSON.stringify({ targetHost, targetPort }), "utf8");
client.send(encodeFrame(FrameType.OPEN, sessionId, payload), server.port, server.host);
});
}
async function startRelay(options: { allowPrivate?: boolean; lookupAddresses?: () => Promise<{ address: string; family: number }[]> } = {}) {
return await createAccelerationRelayServer({ host: "127.0.0.1", port: 0, token: TOKEN, ...options });
}
test("a hostname that resolves to loopback is blocked by the resolved-address check", async () => {
const server = await startRelay({ lookupAddresses: resolved("127.0.0.1") });
try {
// Regression: the name itself is not an IP literal, so a string-only check
// used to pass and the relay then connected to the resolved loopback address.
const reply = await openTarget(server, "attacker.example.invalid");
assert.equal(reply.type, FrameType.OPEN_ERR);
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED");
} finally {
server.close();
}
});
test("IPv4-mapped IPv6 literals cannot bypass the private-address check", async () => {
for (const target of ["::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:169.254.169.254"]) {
const server = await startRelay({});
try {
const reply = await openTarget(server, target);
assert.equal(reply.type, FrameType.OPEN_ERR, `${target} should be blocked`);
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`);
} finally {
server.close();
}
}
});
test("private and special-use literals stay blocked", async () => {
for (const target of ["10.0.0.5", "172.16.0.1", "192.168.1.1", "127.0.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1"]) {
const server = await startRelay({});
try {
const reply = await openTarget(server, target);
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`);
} finally {
server.close();
}
}
});
test("a mixed public/private DNS answer is rejected instead of using the public record", async () => {
const server = await startRelay({ lookupAddresses: resolved("8.8.8.8", "192.168.1.10") });
try {
const reply = await openTarget(server, "mixed.example.invalid");
assert.equal(reply.type, FrameType.OPEN_ERR);
assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED");
} finally {
server.close();
}
});
test("allowPrivate keeps the private-target escape hatch working", async () => {
const listener = createSocket("udp4");
await new Promise<void>((resolve) => listener.bind(0, "127.0.0.1", resolve));
const port = (listener.address() as { port: number }).port;
const server = await startRelay({ allowPrivate: true });
try {
const reply = await openTarget(server, "127.0.0.1", port);
assert.equal(reply.type, FrameType.OPEN_OK);
} finally {
server.close();
listener.close();
}
});
test("a public target still opens a relay session", async () => {
// UDP connect() only sets the default destination, so a public address opens
// the session without sending traffic or needing a real listener.
const server = await startRelay({});
try {
const reply = await openTarget(server, "8.8.8.8");
assert.equal(reply.type, FrameType.OPEN_OK);
} finally {
server.close();
}
});
test("a bind failure rejects startup instead of throwing out of the error listener", async () => {
// Regression: the socket error listener ended with `throw error`, which escaped
// EventEmitter.emit, became an uncaught exception, and killed the process. It
// also aborted the remaining listeners, so this call never settled at all.
const server = await startRelay({});
try {
await assert.rejects(
() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }),
(error: NodeJS.ErrnoException) => error.code === "EADDRINUSE",
);
} finally {
server.close();
}
});
test("a failed startup leaves the surviving relay serving traffic", async () => {
// The thrown error used to take the whole process down with it; the relay that
// did bind must stay usable.
const server = await startRelay({});
try {
await assert.rejects(() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }));
const reply = await openTarget(server, "8.8.8.8");
assert.equal(reply.type, FrameType.OPEN_OK);
} finally {
server.close();
}
});
test("closing a relay is idempotent after a failed sibling startup", async () => {
const server = await startRelay({});
// A failed startup already tore its own socket down, so nothing leaks and the
// surviving relay still closes cleanly when close() runs more than once.
const failed = await createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }).catch(() => null);
assert.equal(failed, null);
server.close();
server.close();
});
+82 -42
View File
@@ -2,6 +2,7 @@ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { createSocket } from "node:dgram";
import { isIP } from "node:net";
import { lookup } from "node:dns/promises";
import { isRestrictedAddress } from "../security/open-target-policy.js";
const MAGIC = Buffer.from("WSAT");
const VERSION = 1;
@@ -29,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 {
@@ -36,10 +39,20 @@ export interface AccelerationTarget {
port: number;
}
type AddressLookup = (hostname: string) => Promise<{ address: string; family: number }[]>;
export interface AccelerationRelayClient {
readonly localHost: string;
readonly localPort: number;
readonly sessionId: number;
/**
* True once the tunnel has torn itself down, whether by {@link close} or on
* its own after a socket error, a relay OPEN_ERR/CLOSE frame, or an open
* timeout. Callers that route a transport through this tunnel must watch this
* flag: after it flips, every sendFrame() call is a silent no-op and both UDP
* sockets are closed, so the tunnel can never recover on its own.
*/
isClosed(): boolean;
close(): void;
}
@@ -150,6 +163,7 @@ export async function createAccelerationRelayClient(
localHost: "127.0.0.1",
localPort: typeof address === "object" ? address.port : 0,
sessionId,
isClosed: (): boolean => closed,
close(): void {
if (!closed && ready) {
try { sendFrame(FrameType.CLOSE); } catch { /* best effort */ }
@@ -165,17 +179,24 @@ export async function createAccelerationRelayServer({
token,
allowPrivate = false,
idleTimeoutMs = 30_000,
lookupAddresses = (hostname) => lookup(hostname, { all: true, verbatim: true }),
onError = (error) => { console.error(`[acceleration-relay] socket error: ${error.message}`); },
}: {
host?: string;
port?: number;
token: string;
allowPrivate?: boolean;
idleTimeoutMs?: number;
lookupAddresses?: AddressLookup;
onError?: (error: Error) => void;
}): Promise<{ host: string; port: number; close(): void }> {
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
const sessions = new Map<number, RelaySession>();
let closed = false;
let started = false;
let sweep: ReturnType<typeof setInterval> | null = null;
let rejectStartup: ((error: Error) => void) | null = null;
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
if (closed) return;
@@ -188,12 +209,37 @@ export async function createAccelerationRelayServer({
session.targetSocket?.close();
};
const shutdown = (): void => {
if (closed) return;
closed = true;
if (sweep) clearInterval(sweep);
sweep = null;
for (const session of sessions.values()) cleanup(session);
try { socket.close(); } catch { /* never bound, or already closed */ }
};
// A listener throwing here is an uncaught exception: it escapes EventEmitter.emit
// and terminates the whole process, and because the throw aborts the remaining
// listeners it also stops the startup promise below from ever settling. Report the
// failure instead — a startup error rejects the returned promise, a later one tears
// the relay down — so callers can handle it rather than crash.
socket.on("error", (error) => {
if (!started) {
const reject = rejectStartup;
rejectStartup = null;
shutdown();
reject?.(asError(error));
return;
}
shutdown();
onError(asError(error));
});
socket.on("message", (packet, rinfo) => {
const frame = decodeFrame(packet);
if (!frame || !verifyFrame(frame, token)) return;
const client = { address: rinfo.address, port: rinfo.port };
if (frame.type === FrameType.OPEN) {
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup);
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup, lookupAddresses);
return;
}
const session = sessions.get(frame.sessionId);
@@ -203,35 +249,35 @@ export async function createAccelerationRelayServer({
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
});
socket.on("error", (error) => {
for (const session of sessions.values()) cleanup(session);
if (!closed) throw error;
});
const sweep = setInterval(() => {
sweep = setInterval(() => {
const now = Date.now();
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
sweep.unref?.();
await new Promise<void>((resolve, reject) => {
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
const onListening = () => { socket.off("error", onError); resolve(); };
socket.once("error", onError);
socket.once("listening", onListening);
socket.bind({ address: host, port });
});
try {
await new Promise<void>((resolve, reject) => {
rejectStartup = reject;
socket.once("listening", () => {
started = true;
rejectStartup = null;
resolve();
});
socket.bind({ address: host, port });
});
} catch (error) {
// A synchronous bind failure (for example an unusable address) never emits
// "error", so release the socket and the sweep interval here too.
rejectStartup = null;
shutdown();
throw error;
}
const address = socket.address();
return {
host,
port: typeof address === "object" ? address.port : port,
close(): void {
if (closed) return;
closed = true;
clearInterval(sweep);
for (const session of sessions.values()) cleanup(session);
socket.close();
},
close: shutdown,
};
}
@@ -253,20 +299,27 @@ async function openRelaySession(
allowPrivate: boolean,
send: (session: RelaySession, type: FrameType, payload?: Buffer) => void,
cleanup: (session: RelaySession) => void,
lookupAddresses: AddressLookup,
): Promise<void> {
const request = parseJson(frame.payload);
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return;
const targetPort = request.targetPort as number;
if (!allowPrivate && isPrivateAddress(request.targetHost)) {
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
return;
}
const previous = sessions.get(frame.sessionId);
if (previous) cleanup(previous);
const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false };
sessions.set(session.id, session);
try {
const target = await resolveTarget(request.targetHost);
const target = await resolveTarget(request.targetHost, lookupAddresses);
// The private-target check must run on the resolved addresses, never on the
// caller-supplied name: a DNS answer can map any hostname onto loopback or
// an internal address after a string-only check has already passed. Every
// address in the answer set is checked so a mixed public/private response
// cannot be used to reach an internal host.
if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) {
cleanup(session);
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
return;
}
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
session.targetSocket = targetSocket;
targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); });
@@ -341,26 +394,13 @@ function parseJson(payload: Buffer): Record<string, unknown> | null {
} catch { return null; }
}
function isPrivateAddress(host: string): boolean {
async function resolveTarget(host: string, lookupAddresses: AddressLookup): Promise<{ host: string; family: number; resolved: string[] }> {
const family = isIP(host);
if (family === 4) {
const parts = host.split(".").map(Number);
return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0;
}
if (family === 6) {
const normalized = host.toLocaleLowerCase();
return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
}
return host === "localhost" || host.endsWith(".localhost");
}
async function resolveTarget(host: string): Promise<{ host: string; family: number }> {
const family = isIP(host);
if (family) return { host, family };
const records = await lookup(host, { all: true, verbatim: true });
if (family) return { host, family, resolved: [host] };
const records = await lookupAddresses(host);
const record = records.find((item) => item.family === 4) ?? records[0];
if (!record) throw new Error("TARGET_DNS_EMPTY");
return { host: record.address, family: record.family };
return { host: record.address, family: record.family, resolved: records.map((item) => item.address) };
}
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
+10 -1
View File
@@ -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)));
+4 -1
View File
@@ -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);
+14
View File
@@ -9,6 +9,20 @@ const directory = (): TSDirectorySnapshot => ({
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
});
test("permanent channel flags survive the gateway wire, without guessing omitted flags", () => {
const source = directory();
source.channels[0] = { ...source.channels[0], name: "[cspacer0]Section", isPermanent: true };
source.channels[1] = { ...source.channels[1], isPermanent: false };
const channels = mapChannelTree(source);
const message = parseServerMessage(JSON.parse(JSON.stringify({ type: "channelList", channels })));
assert.ok(message?.type === "channelList");
assert.equal(message.channels[0].name, "[cspacer0]Section");
assert.equal(message.channels[0].isPermanent, true);
assert.equal(message.channels[1].isPermanent, false);
assert.equal(Object.hasOwn(mapChannelTree(directory())[0], "isPermanent"), false);
assert.equal(parseServerMessage({ type: "channelList", channels: [{ ...channels[0], isPermanent: "true" }] }), null);
});
test("self restoration uses the connected channel before a snapshot or requested channel", () => {
const source = directory();
const result = normalizeDirectorySnapshot(source, 2, 18446744073709551615n, "Self", "Lobby");
+1
View File
@@ -12,6 +12,7 @@ export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new
? { maxClients: channel.maxClients, maxClientsLimited: channel.maxClientsLimited }
: {}),
...(typeof channel.passwordProtected === "boolean" ? { passwordProtected: channel.passwordProtected } : {}),
...(typeof channel.isPermanent === "boolean" ? { isPermanent: channel.isPermanent } : {}),
members: snapshot.clients
.filter((client) => client.channelID === channel.id)
.map((client) => {
@@ -0,0 +1,97 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { createServer as createPortProbe } from "node:net";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { AdminService, type AdminSettingsInput } from "../admin/admin-service.js";
import type { Logger } from "../logger.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { JoinTicketStore } from "./join-ticket.js";
import { createWebServer } from "./server.js";
import { createVoiceGatewayServer } from "./voice-gateway.js";
const noop = () => {};
const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child: () => logger };
test("ingress keeps the page origin and delegates the voice ticket to the selected relay", async (context) => {
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-relay-delegation-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const relayPort = await availablePort();
const ingressPort = await availablePort();
const relayToken = "integration-test-relay-token";
const relayEndpoint = `http://127.0.0.1:${relayPort}`;
const relay = createVoiceGatewayServer({
host: "127.0.0.1",
port: relayPort,
sharedToken: relayToken,
logger,
webRtc: { enabled: false },
});
const service = new AdminService(
database,
Buffer.alloc(32, 7),
logger,
path.join(directory, "missing-config.json"),
async () => ({ ok: true, protocol: "ts3", latencyMs: 1, serverName: "Test", requiresPassword: false }),
);
const localTickets = new JoinTicketStore();
const ingress = createWebServer({
port: ingressPort,
adminService: service,
voiceBridgeOptions: { joinTickets: localTickets, acceleration: () => service.getAccelerationRelayOptions() },
logger,
});
context.after(async () => {
await ingress.stop();
await relay.stop();
database.close();
await rm(directory, { recursive: true, force: true });
});
await service.initialize();
const settings: AdminSettingsInput = {
target: "203.0.113.20#9987",
accessMode: "fixed",
siteName: "WebSpeak",
welcomeText: "",
webRtcEnabled: false,
relayNodes: [{
id: "de-relay",
name: "Germany relay",
target: "relay.example.com#39087",
voiceEndpoint: relayEndpoint,
enabled: true,
token: relayToken,
tokenAction: "replace",
}],
};
service.updateSettings(settings);
await relay.start();
await ingress.start();
const origin = `http://127.0.0.1:${ingressPort}`;
const response = await fetch(`${origin}/api/join-ticket`, {
method: "POST",
headers: { origin, "content-type": "application/json" },
body: JSON.stringify({ nickname: "Tester", accelerated: true }),
});
assert.equal(response.status, 201);
assert.equal(response.headers.get("cache-control"), "no-store");
const result = await response.json() as { ticket?: string; voiceEndpoint?: string };
assert.ok(result.ticket);
assert.equal(result.voiceEndpoint, relayEndpoint);
assert.equal(localTickets.consume(result.ticket!), null);
});
async function availablePort(): Promise<number> {
const socket = createPortProbe();
await new Promise<void>((resolve, reject) => {
socket.once("error", reject);
socket.listen(0, "127.0.0.1", resolve);
});
const address = socket.address();
assert.ok(address && typeof address !== "string");
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
return address.port;
}
+112 -2
View File
@@ -4,16 +4,26 @@ import { setImmediate as nextTurn } from "node:timers/promises";
import { ScreenShareCoordinator, type ScreenShareParticipant } from "./screen-share-coordinator.js";
import { parseServerMessage, type ServerMessage } from "../shared/server-messages.js";
import type { ScreenShareClientMessage } from "../shared/screen-share.js";
import type { Logger } from "../logger.js";
function fixture() {
const entries = new Map<string, ScreenShareParticipant>();
const messages: Array<{ to: string; message: ServerMessage }> = [];
const commands: Array<{ from: string; command: string }> = [];
const logs: Array<{ context: Record<string, unknown>; message: string }> = [];
const send = (to: string, message: ServerMessage) => {
assert.ok(parseServerMessage(JSON.parse(JSON.stringify(message))), `invalid message: ${message.type}`);
messages.push({ to, message });
return true;
};
const coordinator = new ScreenShareCoordinator(entries, send, { debug() {}, warn() {} });
const debug = ((contextOrMessage: Record<string, unknown> | string, message?: string) => {
logs.push({ context: typeof contextOrMessage === "string" ? {} : contextOrMessage, message: message ?? contextOrMessage.toString() });
}) as Logger["debug"];
const info = ((contextOrMessage: Record<string, unknown> | string, message?: string) => {
logs.push({ context: typeof contextOrMessage === "string" ? {} : contextOrMessage, message: message ?? contextOrMessage.toString() });
}) as Logger["info"];
const warn = (() => {}) as Logger["warn"];
const coordinator = new ScreenShareCoordinator(entries, send, { debug, info, warn });
function participant(id: string, clientId: number, channel = 1n, host = "first.example") {
const entry: ScreenShareParticipant = {
id, nickname: id, screenPeerId: `peer-${id}`, target: { host, port: 9987 }, members: new Map([[clientId, {}]]),
@@ -41,7 +51,7 @@ function fixture() {
assert.ok(share);
return share.streamId;
}
return { entries, messages, commands, coordinator, participant, handle, list, start };
return { entries, messages, commands, logs, coordinator, participant, handle, list, start };
}
test("sharing is isolated by server and channel, and only its owner can stop it", () => {
@@ -80,6 +90,43 @@ test("signaling permits owner-viewer pairs but rejects viewer-to-viewer injectio
assert.equal(f.messages.at(-1)?.message.type, "screenShareSignal");
});
test("screen-share diagnostics trace the native viewer handshake without logging SDP or ICE contents", async () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
f.coordinator.handleNotification(owner, { name: "notifystreamstarted", params: { id: "ts-stream-1", clid: "1" } });
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "wrong-stream", clid: "17" } });
f.coordinator.handleNotification(owner, { name: "notifyjoinstreamrequest", params: { id: "ts-stream-1", clid: "17" } });
assert.ok(f.messages.some(({ to, message }) => to === owner.id && message.type === "screenShareNativeViewerJoined"));
f.handle(owner, {
type: "screenShareSignal",
streamId,
targetPeerId: "ts-viewer-17",
signal: { kind: "offer", sdp: "private-sdp-marker" },
});
f.coordinator.handleNotification(owner, {
name: "notifystreamsignaling",
params: { id: "ts-stream-1", clid: "17", json: JSON.stringify({ cmd: "answer", args: { answer: "private-answer-marker" } }) },
});
f.coordinator.handleNotification(owner, {
name: "notifystreamsignaling",
params: { id: "ts-stream-1", clid: "17", json: JSON.stringify({ cmd: "iceCandidate", args: { sdp: "private-candidate-marker", mid: "video", mLine: 0 } }) },
});
await nextTurn();
assert.ok(f.logs.some(({ message }) => message === "TeamSpeak screen-share join request did not match an active browser stream"));
assert.ok(f.logs.some(({ message }) => message === "Forwarded TeamSpeak screen-share join request to browser owner"));
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded browser screen-share signaling to TeamSpeak viewer" && context.signalKind === "offer"));
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded TeamSpeak screen-share signaling to browser owner" && context.signalKind === "answer"));
assert.ok(f.logs.some(({ message, context }) => message === "Forwarded TeamSpeak screen-share signaling to browser owner" && context.signalKind === "iceCandidate"));
const serializedLogs = JSON.stringify(f.logs);
assert.equal(serializedLogs.includes("private-sdp-marker"), false);
assert.equal(serializedLogs.includes("private-answer-marker"), false);
assert.equal(serializedLogs.includes("private-candidate-marker"), false);
});
test("another member moving channels cannot stop the owner's share or evict its viewer", () => {
const f = fixture();
const owner = f.participant("owner", 1);
@@ -357,3 +404,66 @@ test("native removal notification and acknowledgement publish only one viewer-le
assert.equal(f.list(owner)[0]?.viewerCount, 0);
assert.equal(f.messages.filter(({ message }) => message.type === "screenShareViewerLeft").length, 1);
});
test("the viewer roster references members by client id instead of inlining avatars", () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
// Give every viewer the largest avatar the gateway will still accept.
const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`;
const viewers = Array.from({ length: 8 }, (_, index) => {
const clientId = index + 2;
const viewer = f.participant(`viewer-${index}`, clientId);
const member = viewer.members.get(clientId);
assert.ok(member);
member.avatar = avatar;
f.handle(viewer, { type: "screenShareJoin", streamId });
return { viewer, clientId };
});
const roster = f.messages
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
.at(-1)?.message;
assert.ok(roster?.type === "screenShareViewerCount");
const rosterViewers = roster.viewers ?? [];
assert.equal(rosterViewers.length, viewers.length);
// Eight 128 KiB avatars would be ~1 MB. The roster is rebroadcast to the whole
// channel on every join/leave, so it must not scale with avatar size at all.
const bytes = Buffer.byteLength(JSON.stringify(roster));
assert.ok(bytes < 16 * 1024, `roster payload must stay small regardless of avatars, got ${bytes} bytes`);
assert.deepEqual(
rosterViewers.map(viewer => viewer.clientId).sort((left, right) => left! - right!),
viewers.map(({ clientId }) => clientId).sort((left, right) => left - right),
"each roster entry must carry the TeamSpeak client id so the client can resolve the avatar locally",
);
for (const viewer of rosterViewers) {
assert.equal("avatar" in viewer, false, "the roster must not inline avatars");
}
});
test("a viewer whose entry disappeared no longer inflates the announced count", () => {
const f = fixture();
const owner = f.participant("owner", 1);
const streamId = f.start(owner);
const live = f.participant("live", 2);
const gone = f.participant("gone", 3);
f.handle(live, { type: "screenShareJoin", streamId });
f.handle(gone, { type: "screenShareJoin", streamId });
const before = f.messages
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
.at(-1)?.message;
assert.ok(before?.type === "screenShareViewerCount");
assert.equal(before.viewerCount, 2);
// The entry disappears without passing through the coordinator's leave path.
f.entries.delete(gone.id);
const later = f.participant("later", 4);
f.handle(later, { type: "screenShareJoin", streamId });
const after = f.messages
.filter(({ to, message }) => to === owner.id && message.type === "screenShareViewerCount")
.at(-1)?.message;
assert.ok(after?.type === "screenShareViewerCount");
assert.equal(after.viewers?.length, 2, "only viewers that still exist are listed");
assert.equal(after.viewerCount, 2, "the announced count must match the listed viewers");
});
+267 -22
View File
@@ -46,8 +46,8 @@ export class ScreenShareCoordinator {
constructor(
private readonly entries: ReadonlyMap<string, ScreenShareParticipant>,
private readonly sendToEntry: (entryId: string, message: ServerMessage) => void,
private readonly logger: Pick<Logger, "debug" | "warn">,
private readonly sendToEntry: (entryId: string, message: ServerMessage) => boolean,
private readonly logger: Pick<Logger, "debug" | "info" | "warn">,
) {}
handleMessage(
@@ -84,6 +84,13 @@ export class ScreenShareCoordinator {
nativeViewerClids: new Set(),
};
this.screenStreams.set(screenStreamKey(stream.targetKey, stream.streamId), stream);
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
ownerClientId: stream.ownerClientId ?? null,
channelId: String(stream.channelId),
}, "Started browser screen-share stream and requested TeamSpeak publication");
sendJson({ type: "screenShareStarted", requestId: message.requestId, stream: this.describeScreenStream(stream), owner: true });
this.broadcastScreenMessage(stream, {
type: "screenShareStarted",
@@ -96,10 +103,30 @@ export class ScreenShareCoordinator {
const stream = this.screenStreams.get(screenStreamKey(teamSpeakTargetKey(entry.target), message.streamId));
if (!stream) {
if (message.type === "screenShareSignal") {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: message.streamId,
targetPeerId: message.targetPeerId,
signalKind: message.signal.kind,
}, "Dropped screen-share signaling for an unknown stream");
}
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_NOT_FOUND", message: "屏幕共享已结束或不存在" });
return;
}
if (stream.targetKey !== teamSpeakTargetKey(entry.target) || stream.channelId !== entry.tsClient.getChannelId()) {
if (message.type === "screenShareSignal") {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
targetPeerId: message.targetPeerId,
signalKind: message.signal.kind,
sameTarget: stream.targetKey === teamSpeakTargetKey(entry.target),
sameChannel: stream.channelId === entry.tsClient.getChannelId(),
}, "Dropped screen-share signaling because the stream target changed");
}
sendJson({ type: "screenShareError", requestId: "requestId" in message ? message.requestId : undefined, code: "SCREEN_SHARE_TARGET_MISMATCH", message: "屏幕共享不属于当前服务器或频道" });
return;
}
@@ -233,11 +260,20 @@ export class ScreenShareCoordinator {
.filter((entry): entry is ScreenShareParticipant => Boolean(entry))
.slice(0, 64)
.map((entry) => {
const avatar = entry.members.get(entry.tsClient.getClientId())?.avatar;
// Send the client id, not the avatar: receivers already hold member
// avatars from the directory, and this roster is rebroadcast to the
// whole channel on every join and leave. Inlining avatars here scales
// with (viewers x avatar size x channel members) per event.
let clientId: number | undefined;
try {
clientId = entry.tsClient.getClientId();
} catch {
clientId = undefined;
}
return {
peerId: entry.screenPeerId,
nickname: entry.nickname,
...(avatar && avatar.length <= 128 * 1024 ? { avatar } : {}),
...(typeof clientId === "number" && clientId > 0 ? { clientId } : {}),
};
});
}
@@ -246,15 +282,29 @@ export class ScreenShareCoordinator {
return {
type: "screenShareViewerCount",
streamId: stream.streamId,
viewerCount: stream.viewerCount,
// Derive the count from the same call as the roster so the announced
// number can never disagree with the entries actually listed.
viewerCount: this.screenShareViewerCount(stream),
viewers: this.describeScreenViewers(stream),
};
}
private screenShareViewerCount(stream: ScreenStreamRecord): number {
this.pruneStaleViewers(stream);
return stream.viewerEntryIds.size + stream.nativeViewerClids.size;
}
/**
* Drop viewer entries whose participant is gone. A client can disappear from
* the entry map without passing through the leave path, and a lingering id
* inflates the announced count while the roster silently omits it.
*/
private pruneStaleViewers(stream: ScreenStreamRecord): void {
for (const entryId of [...stream.viewerEntryIds.keys()]) {
if (!this.entries.has(entryId)) stream.viewerEntryIds.delete(entryId);
}
}
private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void {
for (const candidate of this.entries.values()) {
if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue;
@@ -314,6 +364,14 @@ export class ScreenShareCoordinator {
signal: ScreenSharePeerSignal,
sendJson: (message: ServerMessage) => void,
): void {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
targetPeerId,
source: stream.source,
signalKind: signal.kind,
}, "Received browser screen-share signaling");
if (stream.source === "teamspeak") {
if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) {
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FORBIDDEN", message: "无权发送该屏幕共享信令" });
@@ -341,6 +399,14 @@ export class ScreenShareCoordinator {
json: JSON.stringify(payload),
})).catch((error: unknown) => {
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
this.logger.warn({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
targetPeerId,
signalKind: signal.kind,
errorName: error instanceof Error ? error.name : "unknown",
}, "Could not forward browser screen-share signaling to TeamSpeak source");
});
return;
}
@@ -349,6 +415,16 @@ export class ScreenShareCoordinator {
const viewerClid = parseNativeViewerPeerId(targetPeerId);
const publisher = stream.teamSpeakPublisherEntryId ? this.entries.get(stream.teamSpeakPublisherEntryId) : undefined;
if (!viewerClid || !publisher || !stream.teamSpeakStreamId || !stream.nativeViewerClids.has(viewerClid)) {
this.logger.info({
entryId: entry.id,
streamId: stream.streamId,
teamSpeakStreamId: stream.teamSpeakStreamId,
targetPeerId,
viewerClid: viewerClid ?? null,
publisherAvailable: Boolean(publisher),
viewerRegistered: viewerClid ? stream.nativeViewerClids.has(viewerClid) : false,
signalKind: signal.kind,
}, "Dropped browser screen-share signaling because the TeamSpeak viewer was not ready");
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_PEER_NOT_FOUND", message: "TeamSpeak 观看者已离开" });
return;
}
@@ -394,8 +470,23 @@ export class ScreenShareCoordinator {
} else {
return;
}
void publisher.tsClient.sendProtocolCommand(command).catch((error: unknown) => {
const signalContext = {
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
teamSpeakStreamId: stream.teamSpeakStreamId,
viewerClid,
signalKind: signal.kind,
};
this.logger.info(signalContext, "Forwarding browser screen-share signaling to TeamSpeak viewer");
void publisher.tsClient.sendProtocolCommand(command).then(() => {
this.logger.info(signalContext, "Forwarded browser screen-share signaling to TeamSpeak viewer");
}).catch((error: unknown) => {
sendJson({ type: "screenShareError", code: "SCREEN_SHARE_SIGNAL_FAILED", message: error instanceof Error ? error.message : "屏幕共享信令发送失败" });
this.logger.warn({
...signalContext,
errorName: error instanceof Error ? error.name : "unknown",
}, "Could not forward browser screen-share signaling to TeamSpeak viewer");
});
return;
}
@@ -433,6 +524,11 @@ export class ScreenShareCoordinator {
viewer_limit: "0",
audio: stream.audio ? "1" : "0",
}));
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
}, "TeamSpeak accepted browser screen-share publication request");
} catch (error: unknown) {
this.logger.warn({
target: formatTeamSpeakTarget(entry.target),
@@ -532,33 +628,81 @@ export class ScreenShareCoordinator {
}
handleNotification(entry: ScreenShareParticipant, notification: TSRawNotification): void {
if (this.entries.get(entry.id) !== entry) return;
if (this.entries.get(entry.id) !== entry) {
if (["notifyjoinstreamrequest", "notifystreamstarted", "notifystreaminfo", "notifyrespondjoinstreamrequest", "notifystreamsignaling"].includes(notification.name)) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
}, "Ignored screen-share notification from a stale TeamSpeak connection");
}
return;
}
const params = notification.params;
if (notification.name === "notifyjoinstreamrequest") {
const streamId = params.id || params.stream_id;
const viewerClientId = parseNumber(params.clid);
if (!streamId || !viewerClientId) return;
if (!streamId || !viewerClientId) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
hasStreamId: Boolean(streamId),
hasViewerClientId: Boolean(viewerClientId),
}, "Ignored TeamSpeak screen-share join request with incomplete identifiers");
return;
}
const targetKey = teamSpeakTargetKey(entry.target);
const stream = [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
const activeBrowserStreams = [...this.screenStreams.values()].filter((candidate) => candidate.targetKey === targetKey
&& candidate.source === "browser"
&& candidate.teamSpeakPublisherEntryId === entry.id
&& candidate.teamSpeakStreamId === streamId);
if (!stream) return;
&& candidate.teamSpeakPublisherEntryId === entry.id);
const stream = activeBrowserStreams.find((candidate) => candidate.teamSpeakStreamId === streamId);
if (!stream) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
teamSpeakStreamId: streamId,
viewerClientId,
activeBrowserStreamIds: activeBrowserStreams.map((candidate) => candidate.teamSpeakStreamId ?? null),
}, "TeamSpeak screen-share join request did not match an active browser stream");
return;
}
const alreadyRegistered = stream.nativeViewerClids.has(viewerClientId);
stream.nativeViewerClids.add(viewerClientId);
stream.viewerCount = this.screenShareViewerCount(stream);
this.sendToEntry(stream.ownerEntryId, {
const deliveredToBrowser = this.sendToEntry(stream.ownerEntryId, {
type: "screenShareNativeViewerJoined",
streamId: stream.streamId,
viewerPeerId: nativeViewerPeerId(viewerClientId),
viewerClientId,
});
this.logger.info({
entryId: entry.id,
ownerEntryId: stream.ownerEntryId,
target: formatTeamSpeakTarget(entry.target),
streamId: stream.streamId,
teamSpeakStreamId: streamId,
viewerClientId,
duplicateRequest: alreadyRegistered,
deliveredToBrowser,
}, deliveredToBrowser
? "Forwarded TeamSpeak screen-share join request to browser owner"
: "Could not forward TeamSpeak screen-share join request because browser WebSocket is unavailable");
this.broadcastScreenMessage(stream, this.screenShareViewerCountMessage(stream));
return;
}
if (notification.name === "notifystreamstarted" || notification.name === "notifystreaminfo") {
const streamId = params.id || params.stream_id;
const sourceClientId = parseNumber(params.clid);
if (!streamId || !sourceClientId) return;
if (!streamId || !sourceClientId) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
hasStreamId: Boolean(streamId),
hasSourceClientId: Boolean(sourceClientId),
}, "Ignored TeamSpeak screen-stream notification with incomplete identifiers");
return;
}
const targetKey = teamSpeakTargetKey(entry.target);
const publisherEntry = [...this.entries.values()].find((candidate) => candidate.target
&& teamSpeakTargetKey(candidate.target) === targetKey
@@ -571,9 +715,26 @@ export class ScreenShareCoordinator {
: undefined;
if (browserStream) {
browserStream.teamSpeakStreamId = streamId;
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId: browserStream.streamId,
teamSpeakStreamId: streamId,
sourceClientId,
}, "Linked TeamSpeak publication to browser screen-share stream");
return;
}
if (publisherEntry) {
this.logger.info({
entryId: entry.id,
publisherEntryId: publisherEntry.id,
target: formatTeamSpeakTarget(entry.target),
teamSpeakStreamId: streamId,
sourceClientId,
activeBrowserStreamIds: [...this.screenStreams.values()]
.filter((candidate) => candidate.targetKey === targetKey && candidate.source === "browser" && candidate.teamSpeakPublisherEntryId === publisherEntry.id)
.map((candidate) => candidate.teamSpeakStreamId ?? null),
}, "TeamSpeak screen-stream notification did not match the browser publisher stream");
// A delayed setup acknowledgement can arrive after the browser stopped.
// A gateway-owned publication is never a second native source.
void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined);
@@ -678,7 +839,15 @@ export class ScreenShareCoordinator {
}
if (notification.name === "notifyrespondjoinstreamrequest" || notification.name === "notifystreamsignaling") {
const streamId = params.id || params.stream_id;
if (!streamId) return;
if (!streamId) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
hasStreamId: false,
}, "Ignored TeamSpeak screen-share signaling without a stream id");
return;
}
const targetKey = teamSpeakTargetKey(entry.target);
const browserStream = notification.name === "notifystreamsignaling"
? [...this.screenStreams.values()].find((candidate) => candidate.targetKey === targetKey
@@ -688,28 +857,104 @@ export class ScreenShareCoordinator {
: undefined;
if (browserStream) {
const viewerClientId = parseNumber(params.clid);
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) return;
if (!viewerClientId || !browserStream.nativeViewerClids.has(viewerClientId)) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
viewerClientId: viewerClientId ?? null,
viewerRegistered: viewerClientId ? browserStream.nativeViewerClids.has(viewerClientId) : false,
}, "Ignored TeamSpeak signaling for an unregistered browser-share viewer");
return;
}
const payload = parseStreamSignalPayload(params.json || params.data || "");
if (!payload) return;
if (!payload) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
viewerClientId,
hasSignalPayload: Boolean(params.json || params.data),
}, "Ignored unparseable TeamSpeak browser-share signaling payload");
return;
}
const signal = toBrowserScreenSignal(payload);
if (!signal) return;
this.sendToEntry(browserStream.ownerEntryId, {
if (!signal) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
viewerClientId,
signalKind: payload.cmd,
}, "Ignored unsupported TeamSpeak browser-share signaling kind");
return;
}
const deliveredToBrowser = this.sendToEntry(browserStream.ownerEntryId, {
type: "screenShareSignal",
streamId: browserStream.streamId,
fromPeerId: nativeViewerPeerId(viewerClientId),
signal,
});
this.logger.info({
entryId: entry.id,
ownerEntryId: browserStream.ownerEntryId,
target: formatTeamSpeakTarget(entry.target),
streamId: browserStream.streamId,
teamSpeakStreamId: streamId,
viewerClientId,
signalKind: signal.kind,
deliveredToBrowser,
}, deliveredToBrowser
? "Forwarded TeamSpeak screen-share signaling to browser owner"
: "Could not forward TeamSpeak screen-share signaling because browser WebSocket is unavailable");
return;
}
const stream = this.screenStreams.get(screenStreamKey(targetKey, streamId));
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) return;
if (!stream || stream.source !== "teamspeak" || !stream.viewerEntryIds.has(entry.id)) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
knownStreamSource: stream?.source ?? null,
viewerJoined: stream?.viewerEntryIds.has(entry.id) ?? false,
}, "Ignored TeamSpeak signaling that did not match an active native stream viewer");
return;
}
const payload = notification.name === "notifyrespondjoinstreamrequest"
? { cmd: "offer", args: { offer: params.offer || "" } }
: parseStreamSignalPayload(params.json || params.data || "");
if (!payload) return;
if (!payload) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
hasSignalPayload: Boolean(params.json || params.data || params.offer),
}, "Ignored unparseable TeamSpeak native-share signaling payload");
return;
}
const signal = toBrowserScreenSignal(payload);
if (!signal) return;
if (!signal) {
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
notification: notification.name,
teamSpeakStreamId: streamId,
signalKind: payload.cmd,
}, "Ignored unsupported TeamSpeak native-share signaling kind");
return;
}
this.sendToEntry(entry.id, { type: "screenShareSignal", streamId, fromPeerId: stream.ownerPeerId, signal });
this.logger.info({
entryId: entry.id,
target: formatTeamSpeakTarget(entry.target),
streamId,
signalKind: signal.kind,
}, "Forwarded TeamSpeak native-share signaling to browser viewer");
}
}
+41 -4
View File
@@ -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);
}
+38 -3
View File
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { SessionAudioTransport } from "./session-audio.js";
import { createAudioFlowStats } from "./audio-stats.js";
import type { Logger as LoggerType } from "../logger.js";
import type { ServerMessage } from "../shared/server-messages.js";
import type { TSVoiceData } from "./ts-client.js";
@@ -13,6 +14,14 @@ function fixture() {
const encoded: Buffer[] = [];
const forwarded: Array<{ data: Buffer; codec: number; targets?: number[] }> = [];
const notices: ServerMessage[] = [];
const warnings: Array<Record<string, unknown>> = [];
const logger: LoggerType = {
debug: () => {},
info: () => {},
error: () => {},
warn: (objOrMsg: Record<string, unknown> | string) => { if (typeof objOrMsg !== "string") warnings.push(objOrMsg); },
child: () => logger,
};
const socket = { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send: (packet: Buffer) => { packets.push(packet); } };
const client = {
sendVoice: (data: Buffer, codec: number) => { forwarded.push({ data, codec }); },
@@ -23,12 +32,12 @@ function fixture() {
dispose() { state.disposed++; },
};
const transport = new SessionAudioTransport({
audio, socket, client, isCurrent: () => state.current, isReady: () => state.ready,
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
sendJson: message => { notices.push(message); },
}, encoder, () => state.now);
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, remote };
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
}
test("PCM framing preserves codec, whisper routing and timing counters", () => {
@@ -49,19 +58,45 @@ test("PCM framing preserves codec, whisper routing and timing counters", () => {
test("invalid PCM is rejected and reconnecting sessions do not encode audio", () => {
const f = fixture();
f.transport.receivePcm(Buffer.alloc(1_919));
f.state.now = 5_000;
f.transport.receivePcm(Buffer.alloc(1_921));
assert.equal(f.notices.length, 2);
assert.deepEqual(f.notices[0], { type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
assert.deepEqual(f.notices[1], f.notices[0]);
f.state.ready = false;
f.state.now = 10_000;
f.transport.receivePcm(Buffer.alloc(1_919));
assert.equal(f.notices.length, 2, "a frame the route discards must not be reported as malformed");
assert.equal(f.warnings.length, 2, "a frame the route discards must not reach the operator log");
f.transport.receivePcm(Buffer.alloc(1_920));
f.transport.receiveWebRtc(Buffer.from([1]), 4);
f.transport.receiveTeamSpeak(f.remote());
assert.equal(f.audio.ingressDroppedFrames, 3);
assert.equal(f.audio.ingressDroppedFrames, 4);
assert.equal(f.encoded.length, 0);
assert.equal(f.forwarded.length, 0);
assert.equal(f.packets.length, 0);
});
test("repeated malformed frames are counted in full but reported once per window", () => {
const f = fixture();
for (const now of [0, 1, 4_999, 5_000]) { f.state.now = now; f.transport.receivePcm(Buffer.alloc(1_919)); }
assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters");
assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame");
assert.deepEqual(f.warnings, [
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 },
], "operators get the same rate-limited view through the logger");
});
test("an encoder failure and a malformed frame do not suppress each other", t => {
const f = fixture();
t.mock.method(f.encoder, "encode", () => { throw new Error("Codec failed"); });
f.transport.receivePcm(Buffer.alloc(1_919));
f.transport.receivePcm(Buffer.alloc(1_920));
assert.deepEqual(f.notices.map(message => message.type), ["error", "audioError"]);
t.mock.restoreAll();
});
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
const f = fixture();
f.state.peer = { pushTeamSpeakVoice() {} };
+54 -9
View File
@@ -1,4 +1,5 @@
import { WebSocket } from "ws";
import type { Logger as LoggerType } from "../logger.js";
import type { ServerMessage } from "../shared/server-messages.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { TSClient, TSVoiceData } from "./ts-client.js";
@@ -7,6 +8,10 @@ import type { WebRtcAudioSession } from "./webrtc-audio.js";
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
// Keep the established byte guard; the browser also bounds playback by time.
const MAX_BUFFERED_BYTES = 4_096;
// A client that keeps sending bad audio must not turn into one JSON error per
// frame: the reply is roughly 100x the offending payload, and the browser only
// ever shows the first one because it writes the same error string.
const AUDIO_ISSUE_REPORT_MS = 5_000;
export interface VoiceEncoder {
encode(frame: Buffer): Buffer;
@@ -17,6 +22,8 @@ export interface SessionAudioOptions {
audio: AudioFlowStats;
socket: Pick<WebSocket, "readyState" | "bufferedAmount"> & { send(packet: Buffer): void };
client: Pick<TSClient, "sendVoice" | "sendWhisper">;
/** Optional: audio faults are also surfaced here so operators can see them. */
logger?: LoggerType;
isCurrent(): boolean;
isReady(): boolean;
selfId(): number;
@@ -29,10 +36,13 @@ export interface SessionAudioOptions {
export class SessionAudioTransport {
private encoder: VoiceEncoder | null;
private closed = false;
private warnedAt: number | null = null;
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
private readonly reportedAt = new Map<string, number>();
private readonly logger: LoggerType | null;
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
this.encoder = encoder;
this.logger = options.logger ?? null;
}
private isCurrent(): boolean {
@@ -64,25 +74,59 @@ export class SessionAudioTransport {
}
}
private reportEncoderFailure(): void {
/**
* Decide whether an audio fault is worth reporting right now. Repeated faults
* of the same kind collapse into one report per window. Codes are tracked
* separately so that one fault cannot hide a different one, which a single
* shared window would do.
*
* The browser only renders the first error string of a run, so dropping the
* repeats costs the user nothing; what it saves is the server-side cost, which
* is proportional to however fast the client streams bad frames.
*/
private shouldReportAudioIssue(code: string): boolean {
const now = this.clock();
if (this.warnedAt !== null && now - this.warnedAt < 5_000) return;
this.warnedAt = now;
const last = this.reportedAt.get(code);
if (last !== undefined && now - last < AUDIO_ISSUE_REPORT_MS) return false;
this.reportedAt.set(code, now);
return true;
}
private reportEncoderFailure(): void {
if (!this.shouldReportAudioIssue("AUDIO_ENCODER_UNAVAILABLE")) return;
this.logger?.warn({ code: "AUDIO_ENCODER_UNAVAILABLE" }, "Opus encoder unavailable for the browser uplink");
try {
this.options.sendJson({ type: "audioError", code: "AUDIO_ENCODER_UNAVAILABLE", detail: "Opus encoder unavailable" });
} catch { /* the socket may have closed while reporting the failure */ }
}
private reportInvalidFrame(length: number): void {
if (!this.shouldReportAudioIssue("INVALID_AUDIO_FRAME")) return;
// Log the faults that the browser is told about: the outbound error is not
// logged anywhere, so without this an operator has no way to notice a client
// that keeps sending malformed audio until the session is torn down.
this.logger?.warn(
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames },
"Discarded malformed browser audio frame",
);
try {
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
} catch { /* the socket may have closed while reporting the failure */ }
}
receivePcm(frame: Buffer): void {
if (!this.isCurrent()) return;
const stats = this.options.audio;
if (frame.length !== AUDIO_FRAME_BYTES) {
stats.ingressDroppedFrames++;
this.options.sendJson({ type: "error", error: { code: "INVALID_AUDIO_FRAME", message: "音频帧格式无效", recoverable: false } });
return;
}
// Resolve the route before judging the frame. A frame that arrives while the
// route is down is discarded whatever its size, so calling it malformed would
// misattribute the drop and raise a spurious client error in the browser.
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
if (frame.length !== AUDIO_FRAME_BYTES) {
stats.ingressDroppedFrames++;
this.reportInvalidFrame(frame.length);
return;
}
this.recordIngress();
const startedAt = this.clock();
let encoded: Buffer;
@@ -150,6 +194,7 @@ export class SessionAudioTransport {
close(): void {
if (this.closed) return;
this.closed = true;
this.reportedAt.clear();
const encoder = this.encoder;
this.encoder = null;
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
+1 -1
View File
@@ -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 -1
View File
@@ -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";
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { detectTeamSpeakProtocol } from "./teamspeak-adapter.js";
test("detects TeamSpeak 3 from the leading version number", () => {
assert.equal(detectTeamSpeakProtocol("3.13.7 build=1645123456 platform=Linux"), "ts3");
assert.equal(detectTeamSpeakProtocol("3.0.0"), "ts3");
});
test("does not misclassify a TeamSpeak 3 minor as TeamSpeak 6", () => {
assert.equal(detectTeamSpeakProtocol("3.6.7 build=1645123456 platform=Linux"), "ts3");
assert.equal(detectTeamSpeakProtocol("3.6.0"), "ts3");
assert.equal(detectTeamSpeakProtocol("3.16.0"), "ts3");
});
test("detects TeamSpeak 6 from the leading version number or product name", () => {
assert.equal(detectTeamSpeakProtocol("6.0.0-beta.1"), "ts6");
assert.equal(detectTeamSpeakProtocol("6.2.0"), "ts6");
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6.0.0"), "ts6");
assert.equal(detectTeamSpeakProtocol("TeamSpeak 3 Server 3.13.7"), "ts3");
});
test("returns null for unknown or unsupported version formats", () => {
assert.equal(detectTeamSpeakProtocol(""), null);
assert.equal(detectTeamSpeakProtocol("build=1645123456 platform=Linux"), null);
assert.equal(detectTeamSpeakProtocol("5.0.0-beta"), null);
assert.equal(detectTeamSpeakProtocol("7.0.0"), null);
});
+18 -31
View File
@@ -1,10 +1,5 @@
import {
Client as TeamSpeakClient,
generateIdentity,
type ClientOptions,
type Identity,
} from "@echosixhiya/teamspeak-client";
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
import { generateIdentitySync } from "@honeybbq/teamspeak/client";
import { TeamSpeakSdkClient, type Identity, type TeamSpeakClientOptions } from "./teamspeak-sdk.js";
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
@@ -75,7 +70,7 @@ export interface TeamSpeakAdapterOptions {
* successfully observed server generation for later connections.
*/
export class TeamSpeakAdapter {
readonly client: TeamSpeakClient;
readonly client: TeamSpeakSdkClient;
readonly identity: Identity;
private detectedProtocol: TeamSpeakProtocol | null = null;
@@ -84,9 +79,8 @@ export class TeamSpeakAdapter {
private readonly logger: Logger,
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
) {
this.identity = options.identity ?? generateIdentity(8);
const clientOptions: ClientOptions = {
resolver: new WebSpeakTeamSpeakResolver(),
this.identity = options.identity ?? generateIdentitySync(8);
const clientOptions: TeamSpeakClientOptions = {
serverPassword: options.serverPassword,
defaultChannel: options.defaultChannel,
defaultChannelPassword: options.channelPassword,
@@ -97,7 +91,7 @@ export class TeamSpeakAdapter {
error: (msg: string) => this.logger.error(msg),
},
};
this.client = new TeamSpeakClient(
this.client = new TeamSpeakSdkClient(
this.identity,
formatTeamSpeakTarget(options.target),
options.nickname,
@@ -112,14 +106,14 @@ export class TeamSpeakAdapter {
const cachedProtocol = this.protocolCache.get(this.target);
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
try {
await this.client.connect();
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
await this.client.connect({ signal: AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS) });
} catch (error: unknown) {
await this.client.disconnect().catch(() => undefined);
throw normalizeTeamSpeakError(error);
}
const observedProtocol = await this.detectProtocol();
const family = this.client.serverFamily;
const observedProtocol = family === "ts3" || family === "ts6" ? family : null;
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
}
@@ -136,24 +130,17 @@ export class TeamSpeakAdapter {
}
}
private async detectProtocol(): Promise<TeamSpeakProtocol | null> {
try {
const rows = await this.client.execCommandWithResponse("version", 3000);
const versionText = rows
.flatMap((row) => Object.values(row))
.filter((value): value is string => typeof value === "string")
.join(" ");
return detectTeamSpeakProtocol(versionText);
} catch {
// Version discovery is an optimization; connection success is enough to proceed.
return null;
}
}
}
export function detectTeamSpeakProtocol(versionText: string): TeamSpeakProtocol | null {
const text = versionText.trim().toLocaleLowerCase();
if (/teamspeak\s*6|(?:^|\D)6\.\d+/.test(text)) return "ts6";
if (/teamspeak\s*3|(?:^|\D)3\.\d+/.test(text)) return "ts3";
const text = versionText.trim().toLowerCase();
// The `version` command starts with the server version, optionally preceded
// by the product name. Match only that leading major version: scanning the
// whole string mistakes TeamSpeak 3.6.7 for TeamSpeak 6.
const match = /^(?:teamspeak\s*)?(\d+)/.exec(text);
if (!match) return null;
const major = Number(match[1]);
if (major === 6) return "ts6";
if (major === 3) return "ts3";
return null;
}
@@ -130,11 +130,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
});
database.close();
const legacy = new DatabaseSync(file);
legacy.exec("ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
legacy.close();
const migrated = new WebSpeakDatabase(file);
try {
assert.equal(migrated.schemaVersion, 9);
assert.equal(migrated.schemaVersion, 12);
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
assert.equal(migrated.getSettings().tsTarget, null);
const invite = migrated.consumeManagedInvite("legacy-token");
+39 -67
View File
@@ -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);
});
+2 -85
View File
@@ -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) {
+138
View File
@@ -0,0 +1,138 @@
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import { setImmediate as nextTurn } from "node:timers/promises";
import test from "node:test";
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
const identity = generateIdentitySync(8);
const uid = "AAAAAAAAAAAAAAAAAAAAAAAAAAA=";
function channel(id = 1): Channel {
return { id: asChannelID(BigInt(id)), parentID: asChannelID(0n), order: asChannelID(0n), name: "Lobby",
description: "", hasPassword: true, isPermanent: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
}
function member(id = 1): ClientEntry {
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
}
function fixture() {
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
const native = Object.assign(new EventEmitter(), {
view: {
status: "live", revision: 1,
channels: new Map([[asChannelID(1n), channel()]]),
clients: new Map([[asClientID(1), member()]]),
serverName: "Shanghai", serverIconID: undefined, serverBannerImageURL: "https://example.invalid/banner",
server: { virtualserver_welcomemessage: "Welcome" },
whenReady: async (_options?: { signal?: AbortSignal }) => {},
},
serverCapabilities: { family: "ts6", welcomeMessage: "Old welcome" },
queries: [] as string[],
async exec(command: string) { this.queries.push(command); throw new Error("insufficient client permissions (code 2568)"); },
});
const state = sdk as unknown as { sdkClient: Client | null; attachUpstreamEvents(client: Client): void };
state.sdkClient = native as unknown as Client;
state.attachUpstreamEvents(native as unknown as Client);
return { sdk, native, state };
}
test("ordinary-client directories and avatar metadata use the live view without list permissions", async () => {
const { sdk, native } = fixture();
assert.deepEqual(await sdk.listDirectoryChannels(), [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "",
passwordProtected: true, isPermanent: true, maxClients: 12, maxClientsLimited: true }]);
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: "Member 1", uid, channelID: 1n, type: 0,
serverGroups: [], away: true, awayMessage: "Away", inputMuted: true, outputMuted: false, channelCommander: true }]);
assert.deepEqual(await sdk.getClientAvatarMetadata(1), { uid, cacheKey: "avatar-hash", path: `/${avatarFileName(uid)}` });
assert.equal(await sdk.getClientAvatarMetadata(2), null);
assert.deepEqual(sdk.serverInfo, { name: "Shanghai", iconId: null, hostBannerGfxUrl: "https://example.invalid/banner", welcomeMessage: "Welcome" });
assert.equal(sdk.serverFamily, "ts6");
assert.deepEqual(native.queries, []);
});
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
const { sdk, native } = fixture();
const snapshots: DirectorySnapshot[] = [];
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
native.emit("viewReady");
native.emit("viewChanged");
assert.equal(snapshots.length, 1, "an unchanged revision does not duplicate the directory");
assert.equal(snapshots[0]?.complete, true);
native.view.clients.clear();
native.view.channels.set(asChannelID(1n), { ...channel(), name: "Renamed", hasPassword: false, isPermanent: false, maxClients: 20 });
native.view.revision++;
native.emit("viewChanged");
assert.equal(snapshots.at(-1)?.channels[0]?.name, "Renamed");
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, false);
assert.equal(snapshots[0]?.channels[0]?.isPermanent, true);
assert.equal(snapshots.at(-1)?.channels[0]?.isPermanent, false);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 20);
assert.deepEqual(snapshots.at(-1)?.clients, []);
assert.equal(snapshots[0]?.clients.length, 1, "earlier snapshots stay independent");
native.view.status = "stale";
native.view.revision++;
native.emit("viewChanged");
assert.equal(snapshots.length, 2, "a stale view cannot initialize a session");
});
test("member status changes use the SDK's current record and retired views cannot publish", async () => {
const { sdk, native, state } = fixture();
const updates: unknown[] = [];
const snapshots: unknown[] = [];
sdk.on("clientUpdated", update => updates.push(update));
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
native.view.clients.set(asClientID(1), { ...member(), isInputMuted: false, isOutputMuted: true, isAway: false });
native.emit("clientUpdated", { clientID: asClientID(1), changes: { isInputMuted: false } });
assert.equal((updates[0] as { info: { inputMuted: boolean } }).info.inputMuted, false);
assert.equal((updates[0] as { info: { outputMuted: boolean } }).info.outputMuted, true);
state.sdkClient = null;
native.emit("viewChanged");
native.emit("clientUpdated", { clientID: asClientID(1) });
assert.equal(updates.length, 1);
assert.equal(snapshots.length, 0);
state.sdkClient = native as unknown as Client;
native.view.status = "stale";
await assert.rejects(sdk.listDirectoryChannels(), /view is not ready/);
});
test("connect waits for the welcome view and propagates its connection deadline", async t => {
const { native } = fixture();
native.view.status = "loading";
let welcome!: () => void;
let observedSignal: AbortSignal | undefined;
native.view.whenReady = options => {
observedSignal = options?.signal;
return new Promise<void>(resolve => { welcome = resolve; });
};
t.mock.method(Client.prototype, "connect", async () => {});
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
const controller = new AbortController();
let connected = false;
const snapshots: DirectorySnapshot[] = [];
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
const pending = sdk.connect({ signal: controller.signal }).then(() => { connected = true; });
await nextTurn();
assert.equal(connected, false, "handshake success alone is not a usable directory");
assert.equal(observedSignal, controller.signal);
native.view.status = "live";
welcome();
await pending;
assert.equal(connected, true);
assert.equal(snapshots.length, 1);
assert.equal(snapshots[0]?.clients[0]?.id, 1);
});
test("an interrupted welcome rejects connect instead of leaving initialization pending", async t => {
const { native } = fixture();
const failure = new Error("welcome connection deadline");
native.view.status = "loading";
native.view.whenReady = async options => { options?.signal?.throwIfAborted(); };
t.mock.method(Client.prototype, "connect", async () => {});
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
await assert.rejects(sdk.connect({ signal: AbortSignal.abort(failure) }), error => error === failure);
});
+341
View File
@@ -0,0 +1,341 @@
import { EventEmitter } from "node:events";
import type { Writable } from "node:stream";
import {
asChannelID,
asClientID,
avatarFileName,
initFileDownload,
moveClient,
pokeClient,
sendChannelMessage,
sendPrivateMessage,
sendServerMessage,
type Channel,
type ClientEntry,
type Codec,
type CommandExecutor,
type FileDownloadInfo,
type ServerFamily,
} from "@honeybbq/teamspeak";
import { Client, type ClientOptions, type Identity } from "@honeybbq/teamspeak/client";
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
export type { Identity };
export type TeamSpeakClientOptions = Pick<ClientOptions, "serverPassword" | "defaultChannel" | "defaultChannelPassword" | "logger">;
export interface ClientInfo {
id: number;
nickname: string;
uid: string;
serverGroups: string[];
channelID: bigint;
type: number;
}
export interface DirectoryClientInfo extends ClientInfo {
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
export interface DirectoryChannelInfo {
id: bigint;
parentID: bigint;
order: bigint;
name: string;
description: string;
passwordProtected?: boolean;
isPermanent?: boolean;
maxClients?: number;
maxClientsLimited?: boolean;
}
export interface DirectorySnapshot {
channels: DirectoryChannelInfo[];
clients: DirectoryClientInfo[];
/** The SDK's live view replaces the visible roster, including unsubscribed clients. */
complete?: boolean;
}
export interface RawNotification {
name: string;
params: Record<string, string>;
}
export interface VoiceData {
clientId: number;
codec: number;
data: Uint8Array;
}
export interface TextMessage {
invokerName: string;
invokerUID: string;
message: string;
invokerGroups: readonly bigint[] | undefined;
targetMode: number;
targetID: bigint;
invokerID: number;
}
export interface ServerInfo {
name: string;
iconId: number | null;
hostBannerGfxUrl: string | null;
welcomeMessage: string;
}
/**
* A narrow compatibility boundary for WebSpeak's old fork-specific SDK events.
* Wire I/O and command execution are provided by the upstream 1.0 client; this
* class only translates names and shapes that WebSpeak already consumes.
*/
export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor {
private sdkClient: Client | null = null;
private directoryRevision = -1;
constructor(
private readonly identity: Identity,
private readonly address: string,
private readonly nickname: string,
private readonly options: TeamSpeakClientOptions,
) {
super();
}
get status(): string | number {
return this.sdkClient?.status ?? 0;
}
get serverInfo(): ServerInfo | null {
const client = this.sdkClient;
return client
? {
name: client.view.serverName,
iconId: client.view.serverIconID ?? null,
hostBannerGfxUrl: client.view.serverBannerImageURL ?? null,
welcomeMessage: client.view.server.virtualserver_welcomemessage ?? client.serverCapabilities.welcomeMessage,
}
: null;
}
get serverFamily(): ServerFamily {
return this.sdkClient?.serverCapabilities.family ?? "unknown";
}
async connect(options: { signal?: AbortSignal } = {}): Promise<void> {
this.directoryRevision = -1;
const target = parseTeamSpeakTarget(this.address);
const localAlias = await resolveLocalTeamSpeakAlias(target.host, { signal: options.signal });
const address = localAlias ? formatTeamSpeakTarget({ host: localAlias, port: target.port }) : this.address;
const client = new Client(this.identity, address, this.nickname, {
...this.options,
// Preserve TeamSpeak nickname addresses. The upstream resolver bounds
// the full SRV/TSDNS/nickname lookup and falls back to the given address.
nicknameLookup: true,
});
this.sdkClient = client;
this.attachUpstreamEvents(client);
await client.connect(options);
// connect() accepts the session before the welcome directory is complete.
// Share its cancellation/deadline instead of waiting forever for a snapshot.
await client.view.whenReady(options);
this.publishDirectory(client);
}
async disconnect(): Promise<void> {
await this.sdkClient?.disconnect();
}
async send(request: Parameters<CommandExecutor["send"]>[0], options?: Parameters<CommandExecutor["send"]>[1]) {
return this.requireClient().send(request, options);
}
async exec(command: string, options?: { signal?: AbortSignal; timeoutMs?: number }) {
return this.requireClient().exec(command, options);
}
clientID(): number {
return Number(this.sdkClient?.clientID ?? 0);
}
channelID(): bigint {
return this.sdkClient?.channelID ?? 0n;
}
async execCommand(command: string, timeoutMs?: number): Promise<void> {
await this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
}
async execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]> {
return this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
}
sendVoice(data: Uint8Array, codec: number): void {
this.requireClient().sendVoice(data, codec as Codec);
}
sendWhisper(data: Uint8Array, clientIds: number[], codec: number): void {
this.requireClient().sendWhisper(data, { clients: clientIds.map(asClientID) }, codec as Codec);
}
async fileTransferInitDownload(channelID: bigint, path: string, password: string): Promise<FileDownloadInfo> {
return initFileDownload(this, asChannelID(channelID), path, { password });
}
async downloadFileData(host: string, info: FileDownloadInfo, destination: Writable): Promise<void> {
await this.requireClient().downloadFileData(host, info, destination);
}
async listDirectoryChannels(): Promise<DirectoryChannelInfo[]> {
return this.readDirectory().channels;
}
async listDirectoryClients(): Promise<DirectoryClientInfo[]> {
return this.readDirectory().clients;
}
async getClientAvatarMetadata(clientId: number): Promise<{ uid: string; cacheKey: string; path: string } | null> {
const info = this.requireClient().view.clients.get(asClientID(clientId));
if (!info?.uid || !info.avatar) return null;
return { uid: info.uid, cacheKey: info.avatar, path: `/${avatarFileName(info.uid)}` };
}
private readDirectory(): DirectorySnapshot {
const view = this.requireClient().view;
if (view.status !== "live") throw new Error("TeamSpeak directory view is not ready");
return {
channels: [...view.channels.values()].map(toDirectoryChannel),
clients: [...view.clients.values()].map(toDirectoryClient),
complete: true,
};
}
private publishDirectory(client: Client): void {
if (this.sdkClient !== client || client.view.status !== "live" || client.view.revision === this.directoryRevision) return;
this.directoryRevision = client.view.revision;
this.emit("directorySnapshot", this.readDirectory());
}
private requireClient(): Client {
if (!this.sdkClient) throw new Error("TeamSpeak session is not ready");
return this.sdkClient;
}
private attachUpstreamEvents(client: Client): void {
const isCurrent = () => this.sdkClient === client;
client.on("viewReady", () => this.publishDirectory(client));
client.on("viewChanged", () => this.publishDirectory(client));
client.on("voiceData", (event) => {
if (!isCurrent()) return;
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
});
client.on("textMessage", (event) => {
if (!isCurrent()) return;
this.emit("textMessage", {
...event,
invokerGroups: event.invokerGroups,
targetID: BigInt(event.targetID),
invokerID: Number(event.invokerID),
} satisfies TextMessage);
});
client.on("poked", (event) => { if (isCurrent()) this.emit("poked", event); });
client.on("clientEnter", (event) => {
if (!isCurrent()) return;
this.emit("clientEnter", toDirectoryClient(event));
});
client.on("clientUpdated", (event) => {
if (!isCurrent()) return;
const info = client.view.clients.get(event.clientID);
if (info) this.emit("clientUpdated", { info: toDirectoryClient(info) });
});
client.on("clientLeave", (event) => {
if (!isCurrent()) return;
const id = Number(event.clientID);
this.emit("clientLeave", {
id,
reasonID: event.reason,
reasonMsg: event.reasonMessage,
targetID: id,
});
});
client.on("clientMoved", (event) => {
if (!isCurrent()) return;
const id = Number(event.clientID);
this.emit("clientMoved", {
id,
targetChannelID: BigInt(event.targetChannelID),
reasonID: event.reason,
invokerID: Number(event.invokerID),
invokerUID: event.invokerUID,
invokerName: event.invokerName,
});
});
client.on("kicked", (event) => { if (isCurrent()) this.emit("kicked", event.reasonMessage); });
client.on("disconnected", (event) => { if (isCurrent()) this.emit("disconnected", event.error); });
client.on("notification", (event) => {
if (!isCurrent()) return;
const notification = { name: event.name, params: { ...event.params } } satisfies RawNotification;
this.emit("rawNotification", notification);
});
}
}
export async function listChannelsCompat(client: TeamSpeakSdkClient): Promise<DirectoryChannelInfo[]> {
return client.listDirectoryChannels();
}
export async function listClientsCompat(client: TeamSpeakSdkClient): Promise<DirectoryClientInfo[]> {
return client.listDirectoryClients();
}
export async function moveClientCompat(client: TeamSpeakSdkClient, clientId: number, channelId: bigint, password?: string): Promise<void> {
await moveClient(client, asClientID(clientId), asChannelID(channelId), { password });
}
export async function sendTextMessageCompat(client: TeamSpeakSdkClient, mode: number, targetId: bigint, message: string): Promise<void> {
if (mode === 1) await sendPrivateMessage(client, asClientID(Number(targetId)), message);
else if (mode === 2) await sendChannelMessage(client, message);
else await sendServerMessage(client, message);
}
export async function pokeCompat(client: TeamSpeakSdkClient, clientId: number, message: string): Promise<void> {
await pokeClient(client, asClientID(clientId), message);
}
export type { Channel, ClientEntry };
function toDirectoryChannel(channel: Channel): DirectoryChannelInfo {
return {
id: BigInt(channel.id),
parentID: BigInt(channel.parentID),
order: BigInt(channel.order),
name: channel.name,
description: channel.description,
passwordProtected: channel.hasPassword,
...(typeof channel.isPermanent === "boolean" ? { isPermanent: channel.isPermanent } : {}),
...(Number.isInteger(channel.maxClients) && channel.maxClients >= 0 && channel.maxClients <= 65_535
&& typeof channel.isMaxClientsUnlimited === "boolean"
? { maxClients: channel.maxClients, maxClientsLimited: !channel.isMaxClientsUnlimited }
: {}),
};
}
function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
return {
id: Number(entry.id),
nickname: entry.nickname,
uid: entry.uid,
serverGroups: entry.serverGroups.map(String),
channelID: BigInt(entry.channelID),
type: entry.type,
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
...(entry.awayMessage !== undefined ? { awayMessage: entry.awayMessage } : {}),
...(entry.isInputMuted !== undefined ? { inputMuted: entry.isInputMuted } : {}),
...(entry.isOutputMuted !== undefined ? { outputMuted: entry.isOutputMuted } : {}),
...(entry.isChannelCommander !== undefined ? { channelCommander: entry.isChannelCommander } : {}),
};
}
+116
View File
@@ -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>();
@@ -108,6 +151,35 @@ test("server icons use the TeamSpeak file transfer path and enforce the download
assert.equal(f.sdk.downloaded, 1);
});
test("rapid channel switches wait for each TeamSpeak acknowledgement", async () => {
const f = fixture();
const firstAck = deferred<void>();
const switchCommands: string[] = [];
let activeSwitches = 0;
let maxActiveSwitches = 0;
f.sdk.inputUpdate = async command => {
if (!command.startsWith("clientmove ")) return;
switchCommands.push(command);
activeSwitches += 1;
maxActiveSwitches = Math.max(maxActiveSwitches, activeSwitches);
if (switchCommands.length === 1) await firstAck.promise;
activeSwitches -= 1;
};
const first = f.client.switchChannel(10n);
const second = f.client.switchChannel(20n);
await nextTurn();
assert.equal(switchCommands.length, 1, "the second clientmove waits until the first is acknowledged");
assert.equal(maxActiveSwitches, 1, "only one channel move can be active on the session");
firstAck.resolve();
await Promise.all([first, second]);
assert.equal(switchCommands.length, 2);
assert.match(switchCommands[0], /cid=10(?:\s|$)/);
assert.match(switchCommands[1], /cid=20(?:\s|$)/);
assert.equal(maxActiveSwitches, 1);
});
test("stream cleanup flood retries back off and stop after two retries", async t => {
const f = fixture();
t.mock.timers.enable({ apis: ["setTimeout"] });
@@ -410,3 +482,47 @@ for (const [name, payload] of retiredEvents) {
assert.equal(observed.length, 1);
});
}
interface RelayFixtureState {
accelerationClient: { isClosed(): boolean; close(): void } | null;
adapter: { disconnect(): Promise<void> } | null;
client: SdkStub | null;
dropStaleAccelerationTransport(): void;
}
function relayFixture(tunnelClosed: boolean) {
const client = new TSClient({
target: { host: "voice.example.invalid", port: 9987 },
nickname: "Test",
acceleration: { relayHost: "127.0.0.1", relayPort: 39087, token: "test-acceleration-relay-token" },
}, pino({ enabled: false }));
let disconnectCalls = 0;
let closeCalls = 0;
const state = client as unknown as RelayFixtureState;
state.accelerationClient = {
isClosed: () => tunnelClosed,
close: () => { closeCalls++; },
};
state.adapter = { disconnect: async () => { disconnectCalls++; } };
state.client = new SdkStub();
return { client, state, counts: () => ({ disconnectCalls, closeCalls }) };
}
test("a self-closed relay tunnel is dropped with its adapter so connect() rebuilds both", () => {
// Regression: reconnecting reused the adapter bound to the dead tunnel's local
// port. Every frame the tunnel sent was a silent no-op, so auto-reconnect
// could never recover and nothing reported an error.
const f = relayFixture(true);
f.state.dropStaleAccelerationTransport();
assert.equal(f.state.accelerationClient, null, "the dead tunnel must not be reused");
assert.equal(f.state.adapter, null, "the adapter bound to the dead local port must be dropped");
assert.equal(f.state.client, null, "the SDK client for the dead transport must be dropped");
});
test("a live relay tunnel survives the reconnect guard untouched", () => {
const f = relayFixture(false);
f.state.dropStaleAccelerationTransport();
assert.notEqual(f.state.accelerationClient, null, "an open tunnel stays usable");
assert.notEqual(f.state.adapter, null, "an open tunnel's adapter stays usable");
assert.notEqual(f.state.client, null, "an open tunnel's SDK client stays usable");
});
+89 -82
View File
@@ -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;
@@ -112,6 +116,7 @@ export class TSClient extends EventEmitter {
private inputState = { muted: false, accompaniment: false };
private syncedInputMuted: boolean | null = null;
private inputStateQueue: Promise<void> = Promise.resolve();
private channelSwitchQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
@@ -124,7 +129,26 @@ 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);
}
/**
* Discards an acceleration tunnel that closed itself (socket error, relay
* OPEN_ERR/CLOSE, or open timeout) together with the adapter and SDK client
* bound to its now-dead local port, so the next connect() builds all three
* from scratch. A closed tunnel silently drops every frame, so reusing the
* adapter would make reconnection fail forever without an error.
*/
private dropStaleAccelerationTransport(): void {
if (!this.accelerationClient?.isClosed()) return;
const staleAdapter = this.adapter;
// Detach before teardown: every SDK listener bails when it no longer owns
// this.client, so a late "disconnected" from the stale transport cannot
// re-enter connect() through the reconnect path.
this.accelerationClient = null;
this.adapter = null;
this.client = null;
try { void staleAdapter?.disconnect().catch(() => undefined); } catch { /* already gone */ }
}
async connect(): Promise<void> {
@@ -135,6 +159,12 @@ export class TSClient extends EventEmitter {
this.selfLeaveReasonId = null;
this.channelCapacities.clear();
this.channelPasswordProtection.clear();
// A relay tunnel that tore itself down (socket error, OPEN_ERR/CLOSE frame,
// open timeout) reports nothing and no-ops every send, while adapter and
// client still look reusable. Reconnecting through the dead local port would
// silently fail forever, so drop the whole stack and let the block below
// build a fresh tunnel plus adapter.
this.dropStaleAccelerationTransport();
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
if (this.options.acceleration && !this.accelerationClient) {
@@ -173,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) {
@@ -258,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.
@@ -271,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;
@@ -354,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", {
@@ -364,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(),
});
@@ -528,9 +520,24 @@ export class TSClient extends EventEmitter {
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
if (!this.client || !this.connected) return;
await tsClientMove(this.client, this.clientId, channelId, password);
this.preferredChannelId = channelId;
const client = this.client;
if (!client) throw new Error("TeamSpeak session is not ready");
const clientId = this.clientId;
const generation = this.connectionGeneration;
const isCurrent = () => client !== null && this.client === client && this.connected && this.connectionGeneration === generation;
const move = async () => {
if (!isCurrent()) throw new Error("TeamSpeak session is not ready");
await tsClientMove(client, clientId, channelId, password);
if (!isCurrent()) throw new Error("TeamSpeak session changed while switching channels");
this.preferredChannelId = channelId;
};
// Rapid clicks used to issue overlapping clientmove commands. The SDK and
// TeamSpeak server both treat these as stateful session operations, so wait
// for each acknowledgement before sending the next move.
const operation = this.channelSwitchQueue.then(move, move);
this.channelSwitchQueue = operation.catch(() => undefined);
return operation;
}
/** Move another visible TeamSpeak client; the server enforces both move powers. */
@@ -584,7 +591,7 @@ export class TSClient extends EventEmitter {
}
getIdentityString(): string {
return this.identity.toString();
return this.identity.export();
}
getChannelId(): bigint {
+130 -1
View File
@@ -79,12 +79,32 @@ 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 };
}
function messageTypes(messages: Array<{ data: Buffer; binary: boolean }>): string[] {
return messages
.filter(message => !message.binary)
.map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
}
function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, type: string): Promise<T> {
return new Promise(resolve => {
socket.on("message", (data, binary) => {
if (binary) return;
const message = JSON.parse(data.toString()) as { type?: string };
if (message.type === type) resolve(message as unknown as T);
});
});
}
// The native Opus codec is unavailable in some environments. These tests only
// exercise gateway wiring, so the encoder is stubbed out.
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
test("a TeamSpeak constructor failure releases the admitted gateway slot", { timeout: 5_000 }, async t => {
const f = await fixture(t, { createTeamSpeakClient() { throw new Error("Identity initialization failed"); } });
if (f.socket.readyState !== WebSocket.CLOSED) await once(f.socket, "close");
@@ -127,6 +147,77 @@ test("server identity lookup waits until the directory sync publishes the connec
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
createEncoder: stubEncoder,
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
});
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
// The session is past authentication, but `connected` was never published.
assert.deepEqual(messageTypes(f.messages), []);
const failure = waitForMessage<{ code: string }>(f.socket, "connectionFailed");
f.sdk.emit("disconnected");
assert.ok((await failure).code.length > 0);
await nextTurn();
assert.equal(f.bridge.getActiveCount(), 0);
});
test("a kick before the directory sync is reported instead of leaving the session alive", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
createEncoder: stubEncoder,
configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; },
});
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
assert.deepEqual(messageTypes(f.messages), []);
const failure = waitForMessage<{ code: string; detail?: string }>(f.socket, "connectionFailed");
f.sdk.emit("kicked", normalizeTeamSpeakKickedReason("Removed by operator", 4));
const message = await failure;
assert.equal(message.code, "KICKED");
assert.match(message.detail ?? "", /Removed by operator/);
await nextTurn();
assert.equal(f.bridge.getActiveCount(), 0);
});
test("a drop during a reconnect handshake resumes recovery instead of stalling in syncing", { timeout: 15_000 }, async t => {
const f = await fixture(t, {
createEncoder: stubEncoder,
configureSdk(sdk) {
let connects = 0;
sdk.connect = async () => {
sdk.connectCalls += 1;
sdk.disconnected = false;
connects += 1;
// Only the first handshake publishes the directory, so the reconnect
// attempt parks in `syncing` the way a slow server would.
if (connects === 1) sdk.emit("directorySnapshot", sdk.directory);
};
},
});
assert.ok(messageTypes(f.messages).includes("connected"));
const firstReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
f.sdk.emit("disconnected");
assert.equal((await firstReconnect).attempt, 1);
// Wait for the retry handshake to reach `syncing` without republishing `connected`.
while (f.sdk.connectCalls < 2) await nextTurn();
await nextTurn();
await nextTurn();
assert.ok(!messageTypes(f.messages).includes("reconnected"));
const secondReconnect = waitForMessage<{ attempt: number }>(f.socket, "reconnecting");
f.sdk.emit("disconnected");
assert.equal((await secondReconnect).attempt, 2);
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
const encoder = new OpusEncoder(48000, 1);
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
@@ -213,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);
+105 -1
View File
@@ -1,8 +1,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import type { IncomingMessage } from "node:http";
import pino from "pino";
import { VoiceBridge } from "./voice-bridge.js";
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
import { JoinTicketStore } from "./join-ticket.js";
import { createAudioFlowStats } from "./audio-stats.js";
import { SessionAudioTransport } from "./session-audio.js";
@@ -163,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]> = [];
@@ -222,3 +233,96 @@ test("an unset media override still uses a literal request host", async () => {
await f.offer("legacy");
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
});
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
}
test("a direct client cannot choose the address recorded for it", () => {
const trusted = createTrustedProxies(["127.0.0.1"]);
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7");
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-real-ip": "203.0.113.9" }), trusted), "192.0.2.7");
assert.equal(
resolveClientIp(ipRequest("::ffff:192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted),
"192.0.2.7",
"an IPv4 peer arrives in mapped form and is still the address we must record",
);
});
test("a trusted proxy chain is read from our side towards the client", () => {
const trusted = createTrustedProxies(["127.0.0.1", "::1", "10.0.0.0/8", "2001:db8::/32"]);
// The proxy appended the peer it accepted, so a value the client injected to
// its left is never the address we record.
assert.equal(
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 198.51.100.4" }), trusted),
"198.51.100.4",
);
// Both hops are trusted, so keep walking towards the client.
assert.equal(
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 10.1.2.3" }), trusted),
"203.0.113.9",
);
// The same walk over IPv6: a trusted hop, then the client.
assert.equal(
resolveClientIp(ipRequest("::1", { "x-forwarded-for": "2001:db9::9, 2001:db8::5" }), trusted),
"2001:db9::9",
);
});
test("X-Real-IP is used only for a trusted single-hop proxy", () => {
const trusted = createTrustedProxies(["127.0.0.1"]);
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "203.0.113.9" }), trusted), "203.0.113.9");
assert.equal(
resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "198.51.100.4", "x-forwarded-for": "203.0.113.9" }), trusted),
"203.0.113.9",
"the appended chain wins over the single-value header",
);
});
test("an all-trusted chain reports the furthest address instead of inventing one", () => {
const trusted = createTrustedProxies(["127.0.0.1"]);
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "127.0.0.1" }), trusted), "127.0.0.1");
assert.equal(resolveClientIp(ipRequest("127.0.0.1"), trusted), "127.0.0.1");
assert.equal(resolveClientIp(ipRequest(undefined), trusted), "unknown");
});
test("unparseable forwarding values are dropped rather than recorded", () => {
const trusted = createTrustedProxies(["127.0.0.1"]);
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip" }), trusted), "127.0.0.1");
assert.equal(
resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip, 203.0.113.9" }), trusted),
"203.0.113.9",
);
});
test("the default trust list is loopback only", () => {
const trusted = createTrustedProxies(undefined);
assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
assert.equal(resolveClientIp(ipRequest("::1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
// A bridge address belongs to a proxy we have not been told about, so its
// headers are ignored and the connection is logged from the proxy.
assert.equal(resolveClientIp(ipRequest("172.17.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "172.17.0.1");
});
test("a declared trusted proxy accepts CIDR and mapped forms", () => {
const cidr = createTrustedProxies(["10.0.0.0/8", "fd00::/8"]);
assert.equal(resolveClientIp(ipRequest("10.9.8.7", { "x-forwarded-for": "203.0.113.9" }), cidr), "203.0.113.9");
assert.equal(resolveClientIp(ipRequest("fd00::7", { "x-forwarded-for": "2001:db8::9" }), cidr), "2001:db8::9");
// Mapped entries are unwrapped, so they match both the plain and the
// mapped form of the same peer address.
const mapped = createTrustedProxies(["::ffff:192.0.2.1"]);
assert.equal(resolveClientIp(ipRequest("192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9");
assert.equal(resolveClientIp(ipRequest("::ffff:192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9");
});
test("an invalid trust list is rejected instead of silently ignored", () => {
for (const entry of ["not-an-ip", "10.0.0.0/33", "fd00::/129", "10.0.0.0/x", "10.0.0.0/-1"]) {
assert.throws(() => createTrustedProxies([entry]), /WEBSPEAK_TRUSTED_PROXIES/, entry);
}
});
test("trusting every address has to be asked for explicitly", () => {
const trusted = createTrustedProxies(["0.0.0.0/0", "::/0"]);
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9");
});
+223 -42
View File
@@ -11,8 +11,8 @@ import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { randomUUID } from "node:crypto";
import { isIP } from "node:net";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { BlockList, isIP } from "node:net";
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();
@@ -43,6 +54,10 @@ export interface VoiceBridgeOptions {
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
accelerationName?: string | (() => string | undefined);
// Addresses whose forwarding headers may be believed. Unset means loopback
// only, which covers a reverse proxy on the same host (including the
// published host-network container).
trustedProxies?: readonly string[];
}
interface VoiceBridgeDependencies {
@@ -82,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;
@@ -100,6 +117,7 @@ export class VoiceBridge {
private wss: WebSocketServer | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private logger: LoggerType;
private readonly trustedProxies: BlockList;
constructor(
private options: VoiceBridgeOptions,
@@ -108,9 +126,26 @@ export class VoiceBridge {
private readonly dependencies: VoiceBridgeDependencies = {},
) {
this.logger = logger.child({ component: "voice-bridge" });
this.trustedProxies = createTrustedProxies(options.trustedProxies);
this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => {
const entry = this.entries.get(entryId);
if (entry?.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify(message));
if (entry?.ws.readyState === WebSocket.OPEN) {
try {
entry.ws.send(JSON.stringify(message));
return true;
} catch (error: unknown) {
this.logger.warn({
entryId,
messageType: message.type,
errorName: error instanceof Error ? error.name : "unknown",
}, "Could not send screen-share message to browser");
return false;
}
}
if (message.type === "screenShareNativeViewerJoined" || (message.type === "screenShareSignal" && message.signal.kind !== "iceCandidate")) {
this.logger.info({ entryId, messageType: message.type, readyState: entry?.ws.readyState ?? null }, "Dropped screen-share message because browser WebSocket is unavailable");
}
return false;
}, this.logger);
}
@@ -135,11 +170,11 @@ export class VoiceBridge {
ws.close(4006, "ACCELERATION_UNAVAILABLE");
return;
}
const clientIp = resolveClientIp(req);
const clientIp = resolveClientIp(req, this.trustedProxies);
const webrtcPublicHost = resolveWebRtcPublicHost(req);
let identity;
try {
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.
@@ -213,6 +248,8 @@ export class VoiceBridge {
whisperTargetIds: new Set(),
whisperActive: false,
isAlive: true,
lastPongAt: Date.now(),
missedHeartbeats: 0,
reconnectTimer: null,
audio: createAudioFlowStats(),
webrtc: null,
@@ -229,6 +266,7 @@ export class VoiceBridge {
try {
entry.audioTransport = new SessionAudioTransport({
audio: entry.audio, socket: ws, client: tsClient,
logger: this.logger.child({ component: "session-audio", entryId }),
isCurrent: () => this.entries.get(entryId) === entry,
isReady: () => tsReady && session.state === "connected",
selfId: () => entry!.events?.selfId ?? 0,
@@ -245,6 +283,11 @@ export class VoiceBridge {
let initialStateSent = false;
let serverInfoGeneration = 0;
let hasConnectedOnce = false;
// `connected` is only published once the directory sync has landed (see
// `sendInitialState`), so the session can already be past authentication
// while `hasConnectedOnce` is still false. A transport drop inside that
// gap must be handled rather than swallowed.
const isSettling = () => session.state === "authenticating" || session.state === "syncing";
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
@@ -344,6 +387,28 @@ export class VoiceBridge {
void this.teardown(entryId, "teamSpeak-connect-failed");
};
const failConnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
// A dead transport can report itself twice -- once as a `disconnected`
// event and once as a rejected `connect()`. Report and tear down once.
if (session.state === "failed" || session.state === "disconnecting" || session.state === "idle") return;
if (entry!.reconnectTimer) {
clearTimeout(entry!.reconnectTimer);
entry!.reconnectTimer = null;
}
try {
session.transition("failed");
} catch { /* teardown below remains authoritative */ }
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
const failureDetail = publicFailureDetail(normalized);
entry!.connectionFailureCode = failureCode;
// Send the structured failure before closing. Some browsers and reverse
// proxies do not preserve a WebSocket close reason, which would
// otherwise collapse every failure into a generic message.
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
void this.teardown(entryId, "teamSpeak-connect-failed");
};
const scheduleReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError> | null) => {
if (session.state === "disconnecting" || session.state === "idle" || session.state === "failed") return;
if (!isRecoverable(normalized)) {
@@ -391,7 +456,6 @@ export class VoiceBridge {
} catch (error: unknown) {
const normalized = normalizeTeamSpeakError(error);
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
const failureDetail = publicFailureDetail(normalized);
entry!.connectionFailureCode = failureCode;
this.logger.warn({
code: failureCode,
@@ -403,15 +467,7 @@ export class VoiceBridge {
attempt: reconnectAttempt,
}, "TS connect failed");
if (!isReconnect) {
try {
if (session.state !== "disconnecting" && session.state !== "idle") session.transition("failed");
} catch { /* teardown below remains authoritative */ }
// Send the structured failure before closing. Some browsers and
// reverse proxies do not preserve a WebSocket close reason, which
// would otherwise collapse every failure into a generic message.
sendJson({ type: "connectionFailed", code: failureCode, ...(failureDetail ? { detail: failureDetail } : {}) });
if (ws.readyState === WebSocket.OPEN) ws.close(4003, failureCode);
void this.teardown(entryId, "teamSpeak-connect-failed");
failConnect(normalized);
return;
}
if (isReconnect && isRecoverable(normalized)) {
@@ -434,7 +490,7 @@ export class VoiceBridge {
sendJson, addEvent: addServerEvent, onDirectoryReady: sendInitialState,
onClientLeave: id => {
this.screenShares.onClientLeave(entry!, id);
entry!.webrtc?.setMemberVolume(id, 1);
entry!.webrtc?.removeClient(id);
},
onClientMove: (id, channelId) => this.screenShares.onClientMove(entry!, id, channelId),
onNotification: notification => this.screenShares.handleNotification(entry!, notification),
@@ -445,7 +501,11 @@ export class VoiceBridge {
onKick: kick => {
// A transport drop may arrive first and already start recovery. A
// subsequent kick is still terminal and must cancel that recovery.
if (!hasConnectedOnce) return;
// A kick that lands before the session ever settled in (during the
// first connect or a reconnect handshake) is terminal too: without
// this the client would sit on the connecting screen while the
// gateway kept the dead session alive.
if (!hasConnectedOnce && !isSettling()) return;
resetDirectoryForReconnect();
const failureCode = clientConnectionFailureCode(kick, serverPassword);
const failureDetail = publicFailureDetail(kick);
@@ -455,17 +515,48 @@ export class VoiceBridge {
void this.teardown(entryId, "teamSpeak-kicked");
},
onDisconnect: error => {
if (!hasConnectedOnce || session.state !== "connected") return;
const normalized = error ? normalizeTeamSpeakError(error) : null;
if (isSettling()) {
// `connected` was never published, so there is no live session to
// interrupt -- but staying in `syncing` would leave the client on
// the connecting screen with no recovery scheduled.
if (!hasConnectedOnce) {
this.logger.warn({
entryId,
normalizedCode: normalized?.code,
...(normalized ? { failureDetail: describeTeamSpeakError(normalized) } : {}),
}, "TeamSpeak connection lost before the session became usable");
failConnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during startup")));
return;
}
// A reconnect attempt dropped mid-handshake. Detach the dead
// transport and fall back into the recovery loop rather than
// stalling in `syncing`.
resetDirectoryForReconnect();
try {
session.transition("reconnecting");
} catch {
failReconnect(normalized ?? normalizeTeamSpeakError(new Error("TeamSpeak connection lost during reconnect")));
return;
}
scheduleReconnect(normalized);
return;
}
if (session.state !== "connected") return;
this.screenShares.removePeer(entryId);
resetDirectoryForReconnect();
const normalized = error ? normalizeTeamSpeakError(error) : null;
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
},
});
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) {
@@ -517,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");
});
@@ -641,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 },
@@ -649,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 {
@@ -774,28 +893,90 @@ 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;
}
return undefined;
}
function resolveClientIp(request: IncomingMessage): string {
const candidates = [
firstHeader(request.headers["x-forwarded-for"])?.split(",", 1)[0],
firstHeader(request.headers["x-real-ip"]),
request.socket.remoteAddress,
];
for (const candidate of candidates) {
const normalized = normalizeClientIp(candidate);
if (normalized) return normalized;
// A reverse proxy on the same host reaches us over loopback, which is also what
// the published host-network container sees. Anything else has to be declared,
// because whoever we believe can choose the address we record.
const DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"];
/** Build the matcher that decides whether forwarding headers may be believed. */
export function createTrustedProxies(entries: readonly string[] | undefined): BlockList {
const list = new BlockList();
const effective = entries?.length ? entries : DEFAULT_TRUSTED_PROXIES;
for (const entry of effective) {
const trimmed = entry.trim();
if (!trimmed) continue;
const separator = trimmed.indexOf("/");
const address = normalizeClientIp(separator === -1 ? trimmed : trimmed.slice(0, separator));
const family = address ? isIP(address) : 0;
if (!address || (family !== 4 && family !== 6)) {
throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES entry: ${entry}`);
}
if (separator === -1) {
list.addAddress(address, family === 4 ? "ipv4" : "ipv6");
continue;
}
const prefixText = trimmed.slice(separator + 1);
const prefix = Number(prefixText);
if (!/^\d+$/.test(prefixText) || prefix > (family === 4 ? 32 : 128)) {
throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES prefix: ${entry}`);
}
list.addSubnet(address, prefix, family === 4 ? "ipv4" : "ipv6");
}
return "unknown";
return list;
}
function isTrustedProxy(address: string, trustedProxies: BlockList): boolean {
const family = isIP(address);
if (family !== 4 && family !== 6) return false;
return trustedProxies.check(address, family === 4 ? "ipv4" : "ipv6");
}
/**
* Address to record for a connection. Each proxy appends the peer it accepted,
* so the chain is read from the hop nearest to us towards the client, and the
* first address we do not trust is the client. Forwarding headers received
* directly from an untrusted peer are ignored entirely: that peer can write
* anything, and whatever we return is shown as the source in the admin
* connection log.
*/
export function resolveClientIp(request: IncomingMessage, trustedProxies: BlockList): string {
const direct = normalizeClientIp(request.socket.remoteAddress);
if (!direct || !isTrustedProxy(direct, trustedProxies)) return direct ?? "unknown";
const forwarded = firstHeader(request.headers["x-forwarded-for"]);
const hops: string[] = [];
if (forwarded) {
for (const candidate of forwarded.split(",")) {
const hop = normalizeClientIp(candidate);
if (hop) hops.push(hop);
}
hops.reverse();
}
for (const hop of hops) {
if (!isTrustedProxy(hop, trustedProxies)) return hop;
}
if (!hops.length) {
// A single-hop proxy may be configured to send only X-Real-IP.
const realIp = normalizeClientIp(firstHeader(request.headers["x-real-ip"]));
if (realIp && !isTrustedProxy(realIp, trustedProxies)) return realIp;
}
// Every address we can see belongs to a proxy we trust. Report the furthest
// one instead of inventing a client address that was never forwarded.
return hops.length ? hops[hops.length - 1]! : direct;
}
function normalizeClientIp(value: string | undefined): string | undefined {
+47
View File
@@ -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);
});
+111
View File
@@ -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);
}
+49
View File
@@ -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);
});
+91
View File
@@ -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());
});
},
};
}
+60
View File
@@ -173,3 +173,63 @@ test("a rejected peer shutdown is shared without repeating partial cleanup", asy
assert.deepEqual(f.released, ["decoder-1", "decoder-2", "encoder", "track", "peer"]);
assert.equal(f.resources.decoderByClient.size, 0);
});
test("an unavailable mixer encoder closes the half-built peer before the constructor throws", () => {
// The constructor never returns when the codec is missing, so the caller's
// `peer?.close()` is a no-op. Instrument the prototype to observe that the
// rollback happens inside the constructor instead. Count distinct peers:
// werift re-enters close() on the same instance while tearing ICE down.
const originalClose = RTCPeerConnection.prototype.close;
const closedPeers = new Set<RTCPeerConnection>();
RTCPeerConnection.prototype.close = function patchedClose(this: RTCPeerConnection): Promise<void> {
closedPeers.add(this);
return originalClose.call(this);
};
try {
assert.throws(
() => new WebRtcAudioSession({
connectionId: "encoder-unavailable",
logger: pino({ enabled: false }),
createEncoder: () => { throw new Error("Opus codec is unavailable"); },
onVoiceFrame() {},
onVoiceActivity() {},
}),
/WebRTC Opus codec is unavailable/,
);
} finally {
RTCPeerConnection.prototype.close = originalClose;
}
assert.equal(closedPeers.size, 1, "the constructor must roll back the peer it already created");
});
test("removeClient releases only the leaving speaker's decoder and buffered state", () => {
const f = fixture();
f.resources.pendingFrames.set(2, []);
f.resources.memberVolumes.set(2, 0.5);
f.resources.partialPcmByClient.set(2, Buffer.alloc(2));
f.resources.activeSpeakerIds.add(2);
f.session.removeClient(1);
assert.deepEqual(f.released, ["decoder-1"]);
assert.equal(f.resources.decoderByClient.has(1), false);
assert.equal(f.resources.pendingFrames.has(1), false);
assert.equal(f.resources.partialPcmByClient.has(1), false);
assert.equal(f.resources.memberVolumes.has(1), false);
assert.equal(f.resources.activeSpeakerIds.has(1), false);
assert.equal(f.resources.decoderByClient.has(2), true);
assert.equal(f.resources.pendingFrames.has(2), true);
assert.equal(f.resources.partialPcmByClient.has(2), true);
assert.equal(f.resources.memberVolumes.has(2), true);
assert.equal(f.resources.activeSpeakerIds.has(2), true);
});
test("removeClient is idempotent and tolerates a throwing decoder disposal", () => {
const f = fixture();
f.session.removeClient(1);
f.session.removeClient(1);
assert.deepEqual(f.released, ["decoder-1"]);
assert.equal(f.resources.decoderByClient.has(1), false);
});
+24 -2
View File
@@ -41,6 +41,9 @@ export interface WebRtcAudioOptions {
udpPortRange?: [number, number];
}
/** The mixer only encodes; per-speaker decoders are created separately below. */
type MixerEncoder = Pick<OpusEncoder, "encode" | "dispose">;
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicAddresses?: string[];
@@ -49,6 +52,8 @@ export interface WebRtcAudioSessionOptions {
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
/** Mirrors `VoiceBridgeDependencies.createEncoder`; production uses `@discordjs/opus`. */
createEncoder?: () => MixerEncoder;
microphoneMuted?: boolean;
accompanimentActive?: boolean;
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
@@ -104,7 +109,7 @@ export class WebRtcAudioSession {
private readonly opusPayloadTypes = new Set<number>();
private audioTimer: ReturnType<typeof setTimeout> | null = null;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: OpusEncoder | null;
private encoder: MixerEncoder | null;
private sequenceNumber = randomInt(0, 65_536);
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
@@ -193,14 +198,19 @@ export class WebRtcAudioSession {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
try {
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
this.encoder = createEncoder();
} catch (error: unknown) {
this.encoder = null;
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
}
if (!this.encoder) {
// The constructor never returns, so the caller cannot clean up after us:
// its `peer` handle stays null and `peer?.close()` is a no-op. Roll the
// half-built peer back here instead of stranding it on the floor.
this.outgoingTrack.stop();
void this.peer.close().catch(() => { /* rollback is best effort */ });
throw new Error("WebRTC Opus codec is unavailable");
}
@@ -431,6 +441,18 @@ export class WebRtcAudioSession {
else this.memberVolumes.set(clientId, normalized);
}
removeClient(clientId: number): void {
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) return;
this.pendingFrames.delete(clientId);
this.partialPcmByClient.delete(clientId);
this.memberVolumes.delete(clientId);
this.activeSpeakerIds.delete(clientId);
const decoder = this.decoderByClient.get(clientId);
if (!decoder) return;
this.decoderByClient.delete(clientId);
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
}
private calculateRms(pcm: Buffer): number {
let sum = 0;
let samples = 0;
+35
View File
@@ -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;
}
+33 -1
View File
@@ -23,7 +23,7 @@ function object<T extends Record<string, Reader>>(fields: T): AdminResponseReade
}
const auditEvent = object({ event: text, createdAt: text });
const relayNode = object({ id: text, name: text, enabled: boolean, target: text, hasToken: boolean });
const relayNode = object({ id: text, name: text, enabled: boolean, target: text, voiceEndpoint: text, hasToken: boolean });
const welcomeTexts = object({ zh: text, en: text, de: text, ru: text, ja: text });
const settings = object({
target: text, hasPassword: boolean, accessMode: choice("fixed", "open"), siteName: text,
@@ -64,6 +64,34 @@ const skin = object({
description: optional(text), previewUrl: optional(text), previewMimeType: optional(text),
builtIn: optional(boolean), enabled: optional(boolean), previewKind: optional(choice("day", "night", "illusia")),
});
const storeMetadata = object({
schemaVersion: value => value === 1 ? 1 as const : invalid(),
id: text, name: text, version: text, author: text, license: text, description: text, minAppVersion: text,
package: object({ ref: text, path: text, sha256: text }),
});
const skinStore = object({
repository: text, appVersion: text, fetchedAt: number,
entries: array(object({ id: text, repository: text, metadata: nullable(storeMetadata), revision: text, compatible: boolean, error: nullable(text) })),
});
const tsAdminSettings = object({
configurationRevision: text,
fixedMode: boolean, enabled: boolean, queryPort: number, username: text,
transport: choice("web", "ssh", "tcp"), queryHost: text, webQueryUrl: text, serverId: number, hasApiKey: boolean,
hasPassword: boolean, hostKeyFingerprint: text, updatedAt: text,
});
const tsAdminOverview = object({
configurationRevision: text,
serverName: text, serverVersion: text, serverFamily: choice("ts3", "ts6", "unknown"),
channelCount: number, clientCount: number,
welcomeMessage: text, maxClients: number, uptimeSeconds: number,
channels: array(object({ id: text, parentID: text, name: text, description: text, totalClients: number, hasPassword: boolean })),
clients: array(object({ id: number, uid: text, nickname: text, channelID: text, serverGroups: array(text), away: boolean, inputMuted: boolean, outputMuted: boolean })),
groups: array(object({ id: text, name: text })), groupsAvailable: boolean, bansAvailable: boolean,
groupsErrorCode: optional(nullable(text)), bansErrorCode: optional(nullable(text)),
bans: array(object({ id: text, name: text, uid: text, reason: text, durationSeconds: number, createdAt: nullable(text) })),
observedAt: text,
});
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
export const adminResponses = {
@@ -87,6 +115,10 @@ export const adminResponses = {
database: object({ schemaVersion: number }), sessions: object({ created: number }),
}),
skins: object({ skins: array(skin), defaultSkinId: text }),
skinStore,
tsAdminSettings,
savedTsAdminSettings,
tsAdminOverview,
defaultSkin: object({ ok: choice(true), defaultSkinId: text }),
updatedSkin: object({ ok: choice(true), skin, defaultSkinId: text }),
uploadedSkin: object({ ok: choice(true), skin }),
+25
View File
@@ -0,0 +1,25 @@
import type { ChannelInfo } from "./voice-models.js";
export interface ChannelSpacer {
text: string;
alignment: "left" | "center" | "right" | "repeat";
style: "text" | "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot";
}
const LINE_STYLES: Readonly<Record<string, ChannelSpacer["style"]>> = {
"___": "solid", "---": "dashed", "...": "dotted", "-.-": "dash-dot", "-..": "dash-dot-dot",
};
/** Spacers are a presentation convention for permanent, root-level TS channels. */
export function getChannelSpacer(channel: Pick<ChannelInfo, "name" | "parentID" | "isPermanent">): ChannelSpacer | null {
if (channel.parentID !== "0" || channel.isPermanent !== true) return null;
const match = /^\[([clr*]?)spacer[^\]\r\n]*\]([\s\S]*)$/i.exec(channel.name);
if (!match) return null;
const text = match[2];
const alignment = ({ c: "center", r: "right", "*": "repeat" } as const)[match[1].toLowerCase() as "c" | "r" | "*"] ?? "left";
return { text, alignment, style: Object.hasOwn(LINE_STYLES, text) ? LINE_STYLES[text] : "text" };
}
export function channelDisplayName(channel: Pick<ChannelInfo, "name" | "parentID" | "isPermanent">): string {
return getChannelSpacer(channel)?.text ?? channel.name;
}
+18
View File
@@ -78,9 +78,27 @@ export type ScreenSharePeerSignal =
kind: "close";
};
/**
* Ceiling on the total inline avatar bytes a client accepts from a legacy
* gateway for one viewer roster. Current gateways send client ids instead of
* avatars, so this bounds only the compatibility path; a per-entry limit alone
* would still admit 64 x 128 KiB in a single broadcast.
*/
export const SCREEN_SHARE_LEGACY_AVATAR_BUDGET = 256 * 1024;
export interface ScreenShareViewerDescription {
peerId: string;
nickname: string;
/**
* TeamSpeak client id. The gateway sends this instead of an inline avatar so
* a receiving client can resolve the avatar it already holds for that member
* from the directory, rather than the roster carrying the image again.
*/
clientId?: number;
/**
* Legacy inline avatar. Current gateways do not set this; it is still parsed
* so a newer web client keeps rendering avatars against an older gateway.
*/
avatar?: string;
}
+48
View File
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseServerMessage, parseScreenShareStream, parseVoiceAudioBridgeStats, type ServerMessage } from "./server-messages.js";
import { SCREEN_SHARE_LEGACY_AVATAR_BUDGET } from "./screen-share.js";
const stream = {
streamId: "stream-1", source: "browser" as const, ownerPeerId: "owner", ownerClientId: 1,
@@ -101,3 +102,50 @@ test("legacy screen streams receive defaults and untrusted viewer data is bounde
assert.equal(message.streams[0]?.viewers[0]?.nickname.length, 120);
assert.equal(parseScreenShareStream({ streamId: "s", ownerPeerId: [] }), null);
});
test("screen share viewers carry a client id and still accept a legacy inline avatar", () => {
const message = parseServerMessage({
type: "screenShareList",
streams: [{
streamId: "s", ownerPeerId: "owner",
viewers: [
{ peerId: "v1", nickname: "One", clientId: 42 },
{ peerId: "v2", nickname: "Two", avatar: "data:image/png;base64,AAAA" },
{ peerId: "v3", nickname: "Three", clientId: -1 },
{ peerId: "v4", nickname: "Four", clientId: 70_000 },
],
}],
});
assert.ok(message?.type === "screenShareList");
const viewers = message.streams[0]?.viewers ?? [];
assert.equal(viewers.length, 4);
assert.equal(viewers[0]?.clientId, 42);
assert.equal("avatar" in viewers[0]!, false);
// An older gateway still inlines the avatar; keep honouring it.
assert.equal(viewers[1]?.avatar, "data:image/png;base64,AAAA");
assert.equal(viewers[1]?.clientId, undefined);
// Out-of-range ids are dropped rather than forwarded.
assert.equal(viewers[2]?.clientId, undefined);
assert.equal(viewers[3]?.clientId, undefined);
});
test("legacy inline avatars are bounded in total, not merely per entry", () => {
const avatar = `data:image/png;base64,${"A".repeat(128 * 1024 - 22)}`;
const message = parseServerMessage({
type: "screenShareList",
streams: [{
streamId: "s", ownerPeerId: "owner",
viewers: Array.from({ length: 8 }, (_, index) => ({ peerId: `v${index}`, nickname: `n${index}`, avatar })),
}],
});
assert.ok(message?.type === "screenShareList");
const viewers = message.streams[0]?.viewers ?? [];
assert.equal(viewers.length, 8, "entries are kept even when their avatar is dropped");
const accepted = viewers.reduce((total, viewer) => total + (viewer.avatar?.length ?? 0), 0);
assert.ok(
accepted <= SCREEN_SHARE_LEGACY_AVATAR_BUDGET,
`accepted avatar bytes must stay within the roster budget, got ${accepted}`,
);
assert.ok(accepted > 0, "the legacy path still renders the leading avatars");
assert.ok(viewers.some(viewer => viewer.avatar === undefined), "entries past the budget must fall back to a local lookup");
});
+17 -5
View File
@@ -1,5 +1,5 @@
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
import { normalizeScreenShareIceServers, parseScreenShareSignal, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
import { normalizeVoiceStunServer } from "./voice-ice.js";
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
@@ -73,6 +73,7 @@ function channel(value: unknown): value is ChannelInfo {
&& optional(value.maxClients, maximum => finite(maximum) && Number.isInteger(maximum) && maximum >= 0 && maximum <= 65_535)
&& optional(value.maxClientsLimited, boolean)
&& optional(value.passwordProtected, boolean)
&& optional(value.isPermanent, boolean)
&& (value.maxClients === undefined) === (value.maxClientsLimited === undefined)
&& optional(value.members, members => arrayOf(members, member));
}
@@ -100,11 +101,22 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat
export function parseScreenShareViewers(raw: unknown): ScreenShareViewerDescription[] {
if (!Array.isArray(raw)) return [];
let avatarBudget = SCREEN_SHARE_LEGACY_AVATAR_BUDGET;
return raw.filter((viewer): viewer is RecordValue & { peerId: string; nickname: string } => isRecord(viewer) && text(viewer.peerId) && text(viewer.nickname))
.slice(0, 64).map(viewer => ({
peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120),
...(text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 ? { avatar: viewer.avatar } : {}),
}));
.slice(0, 64).map(viewer => {
// Client ids replaced inline avatars, so this only serves older gateways.
// Bound the roster's total avatar bytes, not just each entry: the
// per-entry cap alone still allows 64 x 128 KiB per broadcast.
const avatar = text(viewer.avatar) && viewer.avatar.length <= 128 * 1024 && viewer.avatar.length <= avatarBudget
? viewer.avatar
: undefined;
if (avatar) avatarBudget -= avatar.length;
return {
peerId: viewer.peerId.slice(0, 128), nickname: viewer.nickname.slice(0, 120),
...(clientId(viewer.clientId) ? { clientId: viewer.clientId } : {}),
...(avatar ? { avatar } : {}),
};
});
}
/** Defaults preserve stream descriptions sent by older gateway versions. */
+6
View File
@@ -192,6 +192,7 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.breadcrumbs",
"voice.channel-group",
"voice.channel-group.heading",
"voice.channel-spacer",
"voice.channel-group.members",
"voice.channel-tree.avatar",
"voice.channel-tree.branch",
@@ -239,6 +240,10 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.chat.tab",
"voice.chat.tabs",
"voice.connection-status",
"voice.connection-status.message",
"voice.connection-status.nickname",
"voice.connection-status.nickname.input",
"voice.connection-status.reconnect",
"voice.content",
"voice.context-menu",
"voice.context-menu-backdrop",
@@ -370,6 +375,7 @@ const ACTION_PART_IDS = new Set([
"voice.channel-tree.expander", "voice.channel-tree.row", "demo.skin-switcher", "demo.language-switcher",
]);
const INTERACTIVE_PART_IDS = new Set([
"voice.connection-status.nickname.input", "voice.connection-status.reconnect",
"demo.action.poke", "demo.action.reconnect", "demo.action.speaking", "demo.channel.select",
"demo.chat.input", "demo.chat.send", "demo.chat.tab", "demo.home-link", "demo.poke.dismiss",
"demo.reconnect.restore", "home.connect", "home.favorite-toggle", "home.identity-export.button",
+19
View File
@@ -147,6 +147,25 @@ test("server list skins may display only the host-provided TeamSpeak icon image"
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
});
test("skin-owned localization messages are available without adding host permissions", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].name = "{{skin.messages.demo.title}}";
document.components[0].accessibleName = "{{skin.messages.accessibleName}}";
document.components[0].permissions = [];
document.components[0].actions = {};
document.components[0].root = {
tag: "section",
attributes: { "aria-label": "{{skin.messages.demo.accessibility.label}}" },
children: [{ text: "{{skin.messages.demo.greeting}}" }],
};
const component = parseSkinPluginDocument(document).components[0];
assert.equal(component.name, "{{skin.messages.demo.title}}");
assert.equal(component.accessibleName, "{{skin.messages.accessibleName}}");
assert.equal(component.root.children?.[0].text, "{{skin.messages.demo.greeting}}");
});
test("chat panel visibility is host-controlled and its toggle requires chat access", () => {
const document = validDocument();
document.schemaVersion = 3;
+15 -8
View File
@@ -32,6 +32,7 @@ export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({
"audio.settings.open": Object.freeze({ policyVersion: 1, description: "Open WebSpeak's trusted audio device and processing settings." }),
"voice.presence.write": Object.freeze({ policyVersion: 1, description: "Set the user's own away status through the connected TeamSpeak session." }),
"voice.whisper.control": Object.freeze({ policyVersion: 1, description: "Enable or disable the user's existing TeamSpeak whisper target selection." }),
"voice.connect": Object.freeze({ policyVersion: 1, description: "Connect to the host-selected TeamSpeak target after an explicit user action; the skin cannot provide addresses or credentials." }),
"voice.disconnect": Object.freeze({ policyVersion: 1, description: "Disconnect the user's current TeamSpeak voice session." }),
"voice.whisper.status.read": Object.freeze({ policyVersion: 1, description: "Read whether whisper is active and how many existing targets are selected." }),
"voice.screenShare.status.read": Object.freeze({ policyVersion: 1, description: "Read the user's own screen-share state." }),
@@ -63,6 +64,7 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
"voice.screen-share-start",
"voice.whisper-controls",
"voice.performance-panel",
"voice.connection-status",
"voice.connection-controls",
"voice.disconnect-control",
] as const);
@@ -90,6 +92,7 @@ export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostW
"voice.server-banner": widgetPermissions("session.status.read"),
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
"voice.connection-status": widgetPermissions("session.status.read", "voice.connect"),
"voice.connection-controls": widgetPermissions("voice.disconnect"),
"voice.disconnect-control": widgetPermissions("voice.disconnect"),
"voice.member-cards": widgetPermissions("session.members.read", "session.memberAvatars.read", "voice.screenShare.read", "voice.screenShare.control"),
@@ -123,7 +126,7 @@ export type SkinPluginAction =
| "voice.joinChannel" | "favorites.switch" | "quickServers.switch" | "chat.sendMessage" | "chat.togglePanel"
| "voice.toggleMicrophone" | "voice.toggleOutputMute" | "voice.setOutputVolume" | "audio.openSettings"
| "audio.toggleNoiseSuppression" | "audio.toggleAccompaniment"
| "voice.disconnect" | "voice.setAway" | "voice.setWhisperActive"
| "voice.connect" | "voice.disconnect" | "voice.setAway" | "voice.setWhisperActive"
| "voice.startScreenShare" | "voice.stopScreenShare" | "voice.joinScreenShare" | "voice.leaveScreenShare";
export interface SkinPluginActionDefinition {
@@ -204,11 +207,11 @@ const V3_EVENTS = new Set<string>([
const PASSIVE_EVENTS = new Set<string>(["focus", "blur", "pointerenter", "pointerleave", "dragstart", "dragover"]);
const ACTIONS = new Set<string>([
"ui.setState", "ui.toggleState", "session.copyInviteLink", "voice.joinChannel", "favorites.switch", "quickServers.switch", "chat.sendMessage", "chat.togglePanel",
"voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway", "voice.setWhisperActive",
"voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.connect", "voice.disconnect", "voice.setAway", "voice.setWhisperActive",
"voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
]);
const V3_ACTIONS = new Set<string>([
"ui.toggleState", "session.copyInviteLink", "chat.togglePanel", "voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.disconnect", "voice.setAway",
"ui.toggleState", "session.copyInviteLink", "chat.togglePanel", "voice.toggleMicrophone", "voice.toggleOutputMute", "voice.setOutputVolume", "audio.openSettings", "audio.toggleNoiseSuppression", "audio.toggleAccompaniment", "voice.connect", "voice.disconnect", "voice.setAway",
"voice.setWhisperActive", "voice.startScreenShare", "voice.stopScreenShare", "voice.joinScreenShare", "voice.leaveScreenShare",
]);
const PERMISSIONS = new Set<string>(Object.keys(SKIN_PLUGIN_PERMISSIONS));
@@ -228,6 +231,7 @@ const ACTION_ARGS: Record<SkinPluginAction, ReadonlySet<string>> = {
"audio.openSettings": new Set([]),
"audio.toggleNoiseSuppression": new Set([]),
"audio.toggleAccompaniment": new Set([]),
"voice.connect": new Set([]),
"voice.disconnect": new Set([]),
"voice.setAway": new Set(["away", "message"]),
"voice.setWhisperActive": new Set(["active"]),
@@ -251,6 +255,7 @@ const ACTION_PERMISSION: Record<SkinPluginAction, SkinPluginPermission | null> =
"audio.openSettings": "audio.settings.open",
"audio.toggleNoiseSuppression": "audio.microphone.control",
"audio.toggleAccompaniment": "audio.output.control",
"voice.connect": "voice.connect",
"voice.disconnect": "voice.disconnect",
"voice.setAway": "voice.presence.write",
"voice.setWhisperActive": "voice.whisper.control",
@@ -271,7 +276,7 @@ const COLLECTION_PERMISSION: Record<string, SkinPluginPermission> = {
"screenShare.streams": "voice.screenShare.read",
};
const COLLECTION_FIELDS: Record<string, ReadonlySet<string>> = {
"session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
"session.channels": new Set(["id", "name", "displayName", "isSpacer", "spacerAlignment", "spacerStyle", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
"session.members": new Set(["id", "name", "avatarInitial", "channelId", "status", "speaking", "self", "screenSharing", "screenShareStreamId"]),
"favorites.items": new Set(["id", "label", "current", "kind"]),
"servers.quickList": new Set(["id", "label", "monogram", "icon", "tone", "current", "switchRestricted", "switchTitle", "kind", "favorite"]),
@@ -327,10 +332,12 @@ function bindingPermissions(value: string, aliases: ReadonlyMap<string, string>,
const found = new Set<SkinPluginPermission>();
for (const match of value.matchAll(/\{\{\s*([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g)) {
const path = match[1].split(".");
if (path[0] === "state") {
if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key.");
continue;
}
if (path[0] === "state") {
if (path.length !== 2 || !stateKeys.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A state binding must reference a declared local state key.");
continue;
}
if (path[0] === "skin" && path[1] === "locale" && path.length === 2) continue;
if (path[0] === "skin" && path[1] === "messages" && path.length >= 3) continue;
const aliasCollection = aliases.get(path[0]);
if (aliasCollection) {
if (path.length !== 2 || !COLLECTION_FIELDS[aliasCollection]?.has(path[1])) fail("SKIN_PLUGIN_BINDING_INVALID", "A repeated item binding references an unsupported public field.");
@@ -5,6 +5,15 @@ import {
SKIN_RUNTIME_PLUGIN_CONTEXT_LIMIT_BYTES,
} from "./skin-runtime-plugin-context.js";
test("channel spacer metadata is available to custom skins only with channel read permission", () => {
const item = { id: "4", name: "[cspacer0]Section", displayName: "Section", isSpacer: true, spacerAlignment: "center", spacerStyle: "text", secret: "hidden" };
const context = { session: { channels: [item] } };
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext([], context))), {});
assert.deepEqual(JSON.parse(JSON.stringify(projectSkinRuntimePluginContext(["session.channels.read"], context))), {
session: { channels: [{ id: "4", name: item.name, displayName: "Section", isSpacer: true, spacerAlignment: "center", spacerStyle: "text" }] },
});
});
test("runtime context exposes only fields covered by declared read permissions", () => {
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
session: {
+5 -2
View File
@@ -26,7 +26,7 @@ interface CollectionProjection {
}
const COLLECTIONS: readonly CollectionProjection[] = Object.freeze([
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "displayName", "isSpacer", "spacerAlignment", "spacerStyle", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
{
path: ["session", "members"],
permission: "session.members.read",
@@ -54,7 +54,7 @@ const CONTEXTS: readonly ContextProjection[] = Object.freeze([
{ path: ["screenShare", "status"], permission: "voice.screenShare.status.read", fields: new Set(["active", "starting", "viewing"]) },
]);
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "screenSharing", "audio", "microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive", "active", "starting", "viewing", "maxClientsLimited", "panelOpen"]);
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "screenSharing", "audio", "microphoneMuted", "outputMuted", "noiseSuppressionEnabled", "accompanimentActive", "active", "starting", "viewing", "maxClientsLimited", "panelOpen", "isSpacer"]);
const NUMBER_FIELDS = new Set(["depth", "memberCount", "targetCount", "ownerClientId", "viewerCount", "maxClients"]);
const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
id: 128,
@@ -63,6 +63,9 @@ const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
channelId: 128,
parentId: 128,
name: 160,
displayName: 160,
spacerAlignment: 8,
spacerStyle: 12,
label: 160,
channelName: 160,
userName: 160,
+66
View File
@@ -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;
}
+15
View File
@@ -0,0 +1,15 @@
/** Public workspace API v1. No skin IDs or connection credentials belong here. */
export interface SkinWorkspacePolicy {
apiVersion: 1;
mode: "persistent";
}
export function parseSkinWorkspacePolicy(value: unknown, schemaVersion: number): SkinWorkspacePolicy | undefined {
if (value === undefined) return undefined;
if (schemaVersion < 3 || !value || typeof value !== "object" || Array.isArray(value)) throw new Error("Workspace policy requires an open-skin package.");
const policy = value as Record<string, unknown>;
if (Object.keys(policy).some(key => key !== "apiVersion" && key !== "mode") || policy.apiVersion !== 1 || policy.mode !== "persistent") {
throw new Error("Unsupported workspace policy or API version.");
}
return { apiVersion: 1, mode: "persistent" };
}
+2
View File
@@ -25,6 +25,8 @@ export interface ChannelInfo {
maxClientsLimited?: boolean;
/** TeamSpeak's public channel flag; absent when the connected server omits it. */
passwordProtected?: boolean;
/** Required to recognize TeamSpeak's permanent, root-level spacer channels. */
isPermanent?: boolean;
members?: ChannelMember[];
}
+2 -2
View File
@@ -1,7 +1,7 @@
apply plugin: 'com.android.application'
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.2.6'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 206
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.2.9'
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 209
android {
namespace = "io.webspeak.client"
Binary file not shown.
+13
View File
@@ -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);
+31 -20
View File
@@ -180,10 +180,18 @@ export default defineComponent({
return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission;
}
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
const parts = normalized.split(".");
let value: unknown = parts[0] === "state" ? state : context;
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
const parts = normalized.split(".");
if (parts[0] === "skin" && parts[1] === "messages" && parts.length >= 3) {
const skin = context.skin;
if (!skin || typeof skin !== "object" || !("messages" in skin)) return undefined;
const messages = (skin as { messages?: unknown }).messages;
if (!messages || typeof messages !== "object") return undefined;
const key = parts.slice(2).join(".");
return Object.prototype.hasOwnProperty.call(messages, key) ? (messages as Record<string, unknown>)[key] : undefined;
}
let value: unknown = parts[0] === "state" ? state : context;
const start = parts[0] === "state" ? 1 : 0;
for (let index = start; index < parts.length; index += 1) {
if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined;
@@ -292,10 +300,10 @@ export default defineComponent({
if (!widget) return null;
return h("div", {
class: ["ws-plugin-host-widget", node.className],
"data-ws-plugin-widget": node.widget,
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
"data-ws-part": layoutPart(component, node, nodePath),
"aria-label": component.accessibleName,
"data-ws-plugin-widget": node.widget,
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
"data-ws-part": layoutPart(component, node, nodePath),
"aria-label": interpolate(component.accessibleName, context, state),
}, [widget(node.options)]);
}
if (!node.tag) {
@@ -430,17 +438,20 @@ export default defineComponent({
onUnmounted(() => assetUrls.clear());
return () => {
const nodes: VNodeChild[] = renderedComponents.value.map((component) => h("div", {
key: `${props.skinId}:${component.id}`,
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-plugin-name": component.name,
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
"aria-label": component.accessibleName,
}, [renderNode(component, component.root, props.data, localState(component, props.data), { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]));
const nodes: VNodeChild[] = renderedComponents.value.map((component) => {
const state = localState(component, props.data);
return h("div", {
key: `${props.skinId}:${component.id}`,
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-plugin-name": interpolate(component.name, props.data, state),
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
"aria-label": interpolate(component.accessibleName, props.data, state),
}, [renderNode(component, component.root, props.data, state, { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]);
});
const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0);
const showConsent = (PROMPT_FOR_SKIN_PERMISSIONS && pendingApproval.value.length > 0) || manageOpen.value;
const accessToggle = hasPermissions && editorMode.isEnabled.value ? h(Teleport, { to: "body" }, [h("button", {
@@ -474,7 +485,7 @@ export default defineComponent({
h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"),
h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."),
...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [
h("strong", null, component.name),
h("strong", null, interpolate(component.name, props.data, localState(component, props.data))),
h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))),
])),
h("p", { class: "ws-plugin-consent-note" }, "页面可以替换公开客户端外观;内置控件仍由 WebSpeak 处理。皮肤不能运行脚本、访问网络或存储,也不能读取连接地址、密码和身份材料。/ A surface can replace the public client UI while built-in controls remain host-owned. Skins cannot run code, access network or storage, or read connection targets, passwords, or identity material."),
+69 -78
View File
@@ -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 || "—" });
+65 -112
View File
@@ -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 }> = [
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff. Show more