Compare commits

..
46 Commits
Author SHA1 Message Date
illusia 7cc43bb336 fix(mobile): align standalone version fallback with v0.3.0 2026-11-03 20:30:52 +08:00
illusia 42d15c6d32 release: prepare v0.3.0 2026-11-03 20:19:28 +08:00
illusia 360126b14f merge: retain master release and skin startup fixes 2026-11-03 20:13:42 +08:00
illusia 047a40ac4b merge: retain dev security fixes for the 0.3.0 release 2026-11-03 20:13:15 +08:00
illusia 3430a8a753 feat: add plugin application runtime and unified instance authorization 2026-11-03 20:13:01 +08:00
illusia 275e27c4ac fix(security): address PR 48 findings with bounded concurrent authentication
Classify IPv6 subnets numerically, reserve login capacity before hashing, bind authentication to credential revisions, revoke other sessions on password rotation, reuse trusted proxy client keys and bound PCM encoding by monotonic time. Credit ph1gros for the findings and proposed regression cases.
2026-10-26 10:28:45 +08:00
illusia 37f5b86b52 fix(skins): use build version during initial activation 2026-10-25 18:49:21 +08:00
illusia 8bca848c21 docs: refresh multilingual READMEs and organize project assets 2026-10-25 11:26:53 +08:00
illusia ce681f749d feat(plugins): add GitHub store and scoped collaborative panels 2026-10-25 01:42:41 +08:00
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
220 changed files with 15872 additions and 1789 deletions

No files matched your search

@@ -0,0 +1,32 @@
---
name: webspeak-plugin-development
description: Build, review and package WebSpeak API v2 functional applications with standard browser code and optional Node services, including GitHub distribution. Use for .wplugin applications rather than .wskin skins or their presentation components.
---
# WebSpeak Application Development
Read the current [application runtime guide](../../../docs/PLUGIN_DEVELOPMENT.md). In a standalone checkout, use `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/PLUGIN_DEVELOPMENT.md`. Require WebSpeak v0.3.0 or later for API v2. API v1 and its shared-room examples are removed.
Develop an independent application, not a list of host business RPC calls. Use ordinary HTML/CSS/JavaScript, browser APIs and optional Node services with author-defined routes, dependencies and state. The host provides authenticated context, configuration, package/lifecycle management and a separate origin. It supplies no room API or feature permission list. Keep application business logic in its package; a host defect or missing general runtime primitive is a separate host change.
Start with `docs/templates/plugin-app/` or the distribution repository's `template/`. Put frontend output under `client/` with relative assets and optional `.mjs/.cjs` activation code under `server/`. Include audited dependencies or bundle them; the host does not run package installers. Native dependencies must match target OS and Node ABI. Build with `node scripts/build-plugin.mjs SOURCE_DIR OUTPUT.wplugin`, or the standalone distribution builder, then import the actual output.
Use `webspeak.ready`, `getContext()`, `onContextChange()` and `signal` for generic context; implement functionality through native browser/Node code. Scope provides admission and a grouping key, not synchronization. Server logic must enforce scope and business access. Prefer host-verified `req.webspeak` over browser-supplied identities or channels. Temporary runtime URLs are credentials: do not persist, broadcast or log them. Backend private configuration is encrypted at rest and omitted from admin reads; public configuration is user-visible.
Treat applications as trusted code. Node services have the WebSpeak OS account's privileges; process separation and heap limits are not a hostile-code sandbox. Frontends use a separate origin with standard browser capabilities. Browser permission, secure-context, user-gesture, CORS and network requirements apply. The shared application origin does not isolate mutually hostile plugins. Explain these boundaries accurately and review dependencies rather than inventing host feature permissions.
Provide responsive light/dark styles and suitable language handling using context. Keep UI in the application panel without relying on skin DOM. Clean timers, subscriptions, media and sockets on exit/revocation. Persist backend state in `dataDir`, never extracted code directories. Implement concurrency and atomic writes appropriate to the application.
Verify import, trust, enable, update, failure/restart, custom routes, persistence and revocation. Collaborative apps need two real browser participants and late-join/concurrent-change/channel-boundary/disconnect tests. Distinguish mocked HTTP, actual processes, browser interactions and independent networks. Claim only demonstrated capabilities. Keep credentials and diagnostics out of artifacts.
For distribution use schema v2 catalog entries, matching manifest, raw-package SHA-256 and fixed refs. Publishing and deployment follow the user's task authorization; this skill does not itself authorize either.
## Floating host workspace
The host owns a skin-independent draggable launcher, application library and non-modal app window. Do not add launch controls to a particular skin or inspect its DOM. Apps render their responsive light/dark UI inside the supplied iframe; the host supplies dragging, minimize/maximize/restore and close controls. The host window uses the standard `color-scheme` for its light/dark fallback without inheriting skin component styles. Do not duplicate host window chrome or block the workspace with a page-wide modal backdrop.
Minimizing or switching to the library retains the same iframe and app session. Transfers and playback must survive those actions. Closing the window, replacing the active app or host context revocation ends that session; only one frontend app is currently hosted at a time. Do not equate a hidden iframe with app exit. Verify resize, narrow screens, theme changes, minimize/resume without reload and close/revocation cleanup. Keep the user-facing window focused on functionality and actionable status; omit repeated runtime/permission disclaimers. Administrator trust and security review remain part of enablement.
## Instance authorization
The public host asks once per browser origin for third-party skins and functional applications together. No decision or refusal allows only Day, Night and ILLUSIA; KAAK also requires consent. The last item in the skin menu reopens this setting. Revocation must close/revoke the active frontend application while preserving independently enabled backend services. Do not add per-app copies of the same host authorization prompt, bypass the host gate or confuse this user decision with administrator package trust or browser-native permission prompts.
@@ -0,0 +1,4 @@
interface:
display_name: "WebSpeak Plugin Development"
short_description: "Build portable WebSpeak functional plugins"
default_prompt: "Use $webspeak-plugin-development to build and verify a portable WebSpeak plugin."
@@ -29,3 +29,7 @@ Develop the skin as a portable `.wskin` package. A skin task should not require
- `docs/SKIN_DEVELOPMENT.md` — the single current reference for skin formats, runtime APIs, permissions, data, actions, CSS hooks, security, and QA.
- `docs/examples/ILLUSIA-VOICE.md` and `docs/examples/OPEN-VOICE-SURFACE.md` — full skin and surface examples.
## Instance authorization
WebSpeak v0.3.0 replaces per-skin consent dialogs with one origin-scoped user decision covering third-party skins and functional apps. Without consent only the fixed official Day, Night and ILLUSIA skins are available; bundled KAAK also requires consent. The host skin switcher owns the final authorization item. Packages must not duplicate or bypass it. Revocation must cancel pending activation, remove third-party CSS/components and stop workers. Continue enforcing manifest permissions, credential redaction, trusted action validation and package digests internally; one-time consent does not extend the public API. See the current guide for release compatibility.
+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.3.0
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 3042/tcp 39087/udp 40000-40099/udp
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ["node", "scripts/docker-healthcheck.mjs"]
+114 -68
View File
@@ -1,99 +1,145 @@
<a id="readme-top"></a>
<div align="center">
<a id="readme-top"></a>
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak"><img src="./docs/assets/webspeak-banner.png" alt="WebSpeak — TeamSpeak in your browser" width="100%" /></a>
<h1>WebSpeak</h1>
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
[![Latest Release](https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?sort=semver&display_name=tag&style=flat-square&color=0f766e)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
[![Docker Image](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml/badge.svg?branch=master)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
[![License](https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square)](./LICENSE)
[![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/)
[![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)
<p><strong>打开浏览器,就能加入你的 TeamSpeak。</strong></p>
<p>A self-hosted browser voice client for TeamSpeak 3 &amp; TeamSpeak 6.</p>
<p>
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
<a href="./docs/README.en.md">English documentation</a> ·
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
<a href="./docs/README.ru.md">Русская документация</a> ·
<a href="./docs/README.ja.md">日本語ドキュメント</a>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?sort=semver&amp;display_name=tag&amp;style=flat-square&amp;color=0f766e" alt="Latest release" /></a>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/ci.yml"><img src="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/ci.yml/badge.svg?branch=master" alt="CI — master" /></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers"><img src="https://img.shields.io/github/stars/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;logo=github&amp;color=0f766e" alt="GitHub stars" /></a>
</p>
<p>
<a href="./docs/README.zh-CN.md">简体中文</a> · <a href="./docs/README.en.md">English</a> · <a href="./docs/README.de.md">Deutsch</a> · <a href="./docs/README.ru.md">Русский</a> · <a href="./docs/README.ja.md">日本語</a>
</p>
<p>
<a href="#live-demo">在线演示 · Live demo</a> · <a href="#quick-start">快速部署 · Quick start</a> · <a href="#documentation">文档 · Docs</a> · <a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues">反馈 · Issues</a>
</p>
</div>
## 项目简介 · Overview
当前版本 / Current version: **[v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
| 逻辑 | 中文 | English |
| --- | --- | --- |
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
## 关于 WebSpeak · Overview
WebSpeak 将 TeamSpeak 3 / TeamSpeak 6 带到浏览器:无需安装桌面客户端,即可加入语音频道、发送消息和分享屏幕。你可以自行部署网关,并通过网页后台管理服务器、访问策略、皮肤和运行数据。
Join voice channels, chat and share your screen from a browser. Deploy your own gateway and keep control of your TeamSpeak targets, access policy, skins and data through the web administration console.
| 能力 · Capability | 说明 · Highlights |
| --- | --- |
| 🎙️ 语音 · Voice | Opus、可选 WebRTC、WebSocket 回退、降噪与成员音量 / Opus, optional WebRTC, fallback, noise suppression and per-member volume |
| 💬 频道与聊天 · Channels & chat | 实时频道树、成员状态、私聊与本地历史 / Live channel tree, member state, private chat and local history |
| 🖥️ 屏幕共享 · Screen sharing | 浏览器之间及与受支持的 TS6 客户端互通 / Between browsers and supported native TS6 clients |
| 🎨 皮肤 · Skins | `.wskin` 外观、布局和小组件,支持 GitHub 分发 / Portable appearance, layouts and widgets, distributed through GitHub |
| 🛠️ 管理 · Administration | 目标、邀请、中继、备份和可选 TS 管理 / Targets, invites, relays, backups and optional TS management |
| 🌍 自托管 · Self-hosting | 五种语言、响应式界面、多架构部署 / Five languages, responsive layouts and multi-architecture deployment |
<a id="live-demo"></a>
## 在线演示 · Live demo
| 节点 · Region | 地址 · Address |
| --- | --- |
| 上海 · Shanghai | [shanghai.webspeak.online](https://shanghai.webspeak.online) |
| 香港 · Hong Kong | [webspeak.online](https://webspeak.online) |
![WebSpeak 语音工作区 · Voice workspace](./docs/screenshots/webspeak-zh.png)
<details>
<summary>更多界面与语言 · More screenshots & languages</summary>
- [简体中文](./docs/README.zh-CN.md#screenshots) · [English](./docs/README.en.md#screenshots) · [Deutsch](./docs/README.de.md#screenshots) · [Русский](./docs/README.ru.md#screenshots) · [日本語](./docs/README.ja.md#screenshots)
- 日间、夜间、ILLUSIA、KAAK 与社区皮肤 / Day, Night, ILLUSIA, KAAK and community skins
</details>
<a id="quick-start"></a>
## 快速部署 · Quick start
在 Linux Docker 主机上运行 / On a Linux Docker host:
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
1. 打开 `http://127.0.0.1:3040/admin`,使用 `admin` / `admin` 登录并设置至少 12 位新密码。Open the console, sign in and replace the default password.
2. 配置 TeamSpeak 目标和访问模式;公网使用 HTTPS。Set the TeamSpeak target and access mode; use HTTPS for public access.
3. 启用 WebRTC 时放行配置的 UDP 范围,默认 `40000–40099`。Allow the configured UDP range when enabling WebRTC.
数据保存在 `webspeak-data` volume,升级时保留它。以上 Compose 使用主机网络;Windows 服务端可选择[发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。完整说明:[中文部署指南](./docs/README.zh-CN.md#deployment) · [English deployment guide](./docs/README.en.md#deployment)。
Data persists in the `webspeak-data` volume. The Compose file uses host networking. Windows x64 and Linux x64/ARM64 release packages include the runtime; Docker images support amd64/arm64.
<a id="documentation"></a>
## 文档 · Documentation
- [简体中文](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.zh-CN.md)
- [English](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.en.md)
- [Deutsch](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.de.md)
- [Русский](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ru.md)
- [日本語](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/README.ja.md)
- [皮肤开发指南 / Skin development guide](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/docs/SKIN_DEVELOPMENT.md)
- [皮肤开发 Agent Skill / Skin Development Agent Skill](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/.agents/skills/webspeak-skin-development/SKILL.md)
- [简体中文](./docs/README.zh-CN.md)
- [English](./docs/README.en.md)
- [Deutsch](./docs/README.de.md)
- [Русский](./docs/README.ru.md)
- [日本語](./docs/README.ja.md)
- [皮肤开发指南 / Skin development guide](./docs/SKIN_DEVELOPMENT.md)
- [皮肤开发 Agent Skill / Skin Development Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
## 扩展生态 · Extensions
| 类型 · Type | 入口 · Resources |
| --- | --- |
| 皮肤包 · Skin packages | [皮肤索引 · Catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice) |
| 功能插件 · Functional plugins | [应用目录与开发起点 · Catalog & application starter](https://github.com/Huddle-Up-Forge/webspeak-plugin) · [开发指南 · Guide](./docs/PLUGIN_DEVELOPMENT.md) · [Agent Skill](./.agents/skills/webspeak-plugin-development/SKILL.md) |
皮肤包负责界面、布局及其附属小组件;功能插件使用标准浏览器环境和可选 Node 后端,自行实现业务功能。功能插件 API v2 已包含在 v0.3.0 中,提供独立于皮肤的悬浮应用入口。
Skins own appearance, layout and attached widgets. Functional plugin API v2 is included in v0.3.0 with a skin-independent floating application workspace.
## 社区 · Community
<div align="center">
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ 群 · QQ group `869500475`](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
</a>
<details>
<summary>QQ群二维码 · QQ group QR code</summary>
**QQ群 / QQ group:`869500475`**
<p align="center"><a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475"><img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ group 869500475" width="260" /></a></p>
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
</details>
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
### 相关项目 · Related projects
</div>
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — 面向 TeamSpeak 3/6 的音乐机器人,支持网易云音乐、QQ 音乐、Bilibili 和 Web 控制台。A TeamSpeak music bot with Netease Cloud Music, QQ Music, Bilibili and a web console.
## 友链项目 · Friend projects
## 贡献者 · Contributors
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
感谢协议 SDK 作者、代码与文档贡献者,以及独立皮肤的原始作者。Thanks to the SDK author, code and documentation contributors, and original skin authors.
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
<details>
<summary>查看贡献说明 · View contribution credits</summary>
## Contributors · 贡献者
感谢通过 PR 改进 WebSpeak 的贡献者。以下按 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) 修正缩放、浮动布局和首页脚注。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
- [ph1gros](https://github.com/ph1gros) — 在 [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 中报告并提供公开目标 IPv6 校验、管理员认证与会话、代理限流和 PCM 上行边界的安全审查、补丁及回归测试;相关问题由项目在 `dev` 分支重新实现并修复。Security findings, proposed fixes and regression tests; reimplemented on `dev`.
- [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 · Лицензия · ライセンス
</details>
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
## 许可证 · License
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
WebSpeak 使用 [AGPL-3.0-only](./LICENSE) 发布。第三方依赖的许可与归属见各自项目。
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
WebSpeak is distributed under [AGPL-3.0-only](./LICENSE). Third-party dependencies retain their respective licenses and attribution.
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
<details>
<summary>Star History</summary>
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&amp;Date"><img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&amp;type=Date" alt="WebSpeak star history" width="100%" /></a>
## Star History
</details>
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
</a>
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
<p align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></p>
+152
View File
@@ -0,0 +1,152 @@
# WebSpeak 功能应用开发 / Functional application development
WebSpeak **v0.3.0** 使用应用运行时 **API v2**。`.wplugin` 与 `.wskin` 完全独立;旧 API v1、共享房间协议及其两个示例已移除,不兼容旧包。
插件是作者自己的应用:标准 HTML/CSS/JavaScript 前端,加上可选的 Node 后端。可以使用框架、浏览器原生 API、自己的 HTTP/WebSocket 协议、网络客户端和数据模型。宿主不提供按音乐、文件、视频等功能划分的业务 API,也不提供 `room.read/write` 或下载权限表。浏览器原有的安全上下文、用户手势、权限许可、跨域及网络可达性要求仍然适用。
## 管理与部署
管理员在 `/admin/plugins` 从 GitHub 安装或导入包,审核代码和依赖,配置作用域,勾选信任后启用。每次安装、更新均撤销信任并禁用,需要重新审核。审核是人工准入流程,校验包哈希不等于审核代码。写操作继续使用管理员认证、同源检查、CSRF 和审计。
**信任边界:** 前端运行在独立源,和工作台 DOM 分离,使用真实浏览器环境。Node 后端运行于独立子进程,拥有 WebSpeak 服务账户的操作系统权限,能够访问该账户可访问的网络和文件。独立进程、目录和 JS 堆上限用于生命周期与故障控制,不是恶意代码安全沙箱。仅安装审核且信任的应用。
运行时默认监听 `0.0.0.0:3042`:
| 环境变量 | 用途 |
| --- | --- |
| `WEBSPEAK_PLUGIN_PORT` | 应用端口,默认 3042 |
| `WEBSPEAK_PLUGIN_HOST` | 监听地址,默认 0.0.0.0 |
| `WEBSPEAK_PLUGIN_PUBLIC_ORIGIN` | 初始公开源,例如 `https://apps.example.com` |
本地工作台为 `127.0.0.1` 时自动使用 `localhost:3042`,反向亦然,以保持源分离。公网部署必须给应用配置独立 HTTPS 源,在管理页“应用运行时”保存;该设置优先于环境变量。代理应将该源的全部路径转发至应用端口,支持 WebSocket 升级和 SSE 长连接,关闭 SSE 缓冲。不要让代理记录 `/apps/…` 中的访问凭证,也不要与主站共用域 Cookie。
```caddyfile
apps.example.com {
reverse_proxy 127.0.0.1:3042
}
```
容器需映射应用端口,或让代理接入相同容器网络。端口/监听地址改变需重启;公开源可在后台更新,会撤销已有应用会话。主站直接使用 TLS 时,运行端口使用相同证书;TLS 在代理终止时,上游使用 HTTP。监听失败会保留主站和语音服务,后台显示不可用,修复后需重启。配置为主站自身源时拒绝打开应用。
## 作用域与身份
`server`:管理员配置允许的实际 TS `host:port`,用户按真实 TS 目标和频道获得作用域标识。`instance`:当前语音网关的已连接用户获得同一实例标识。作用域负责宿主准入和提供上下文,**不会替作者创建共享房间或自动同步数据**。应用后端应按 `request.webspeak.scope.key` 分组,并自行实现业务授权和同步。
TS 目标由实际语音连接解析,插件不能自报身份或频道。目标支持 `host:port`、`host#port`、`[IPv6]:port`,保存时规范化;SRV/Nickname 场景应核对实际目标。服务器范围切换频道后需重开;实例范围的频道变更通过上下文更新。断开、重连、更新、禁用、重启、配置修改或卸载会撤销旧凭证并关闭连接。服务端可以在没有打开面板时执行后台任务,直到禁用或停止。
入口属于实际语音网关;浏览器直连另一中继网关时,在那个网关安装配置。原生 TS 客户端不会执行网页应用,不同网关不会自动共享状态。作者可自行实现跨实例服务。
## 包格式与构建
复制 [通用起点](templates/plugin-app/manifest.json),修改 ID、元数据和业务代码。它只展示上下文及自定义计数路由,不是商店预装插件。
```text
my-app/
manifest.json
client/index.html
client/main.js
client/style.css
server/main.mjs # 可选
server/node_modules/ # 可选,已审核的运行依赖
```
```json
{
"apiVersion": 2,
"id": "community.my-app",
"name": "My application",
"version": "1.0.0",
"author": "Author",
"license": "MIT",
"description": "An independently implemented application",
"scopes": ["server", "instance"],
"client": { "entry": "client/index.html" },
"server": { "entry": "server/main.mjs" }
}
```
纯前端应用删除 `server` 声明。前端框架产物放入 `client/`,静态引用使用相对路径,不能假设根路径为 `/`。后端入口支持 `.mjs/.cjs`,依赖放在 `server/` 内或打包为自包含文件。宿主不会执行 `npm install`、安装脚本或原生编译;原生依赖需匹配目标 Node ABI/操作系统,不一定跨平台。运行环境为宿主 Node,当前项目要求 Node 22 或更高。
```sh
node scripts/build-plugin.mjs docs/templates/plugin-app /tmp/application.wplugin
```
构建器是独立 Node 脚本,可复制到插件仓库,无需导入 WebSpeak 源码。`.wplugin` 是 UTF-8 JSON:`{manifest,files}`;`files` 是路径到 `{encoding:"utf8"|"base64",data:string}` 的映射。支持普通 `client/`、`server/` 文件;禁止越界路径、符号链接、Windows 设备名、大小写冲突及文件/目录别名。入口必须是 UTF-8。封装上限 48 MiB、解码内容 32 MiB、单文件 16 MiB、4096 个文件,安装上限 50 个。宿主导入时完整校验。
## 浏览器上下文
宿主在入口 HTML 注入外部脚本,在应用模块运行前提供:
```js
const context = await window.webspeak.ready;
const unsubscribe = webspeak.onContextChange(next => render(next));
const latest = webspeak.getContext();
const response = await fetch(context.serverUrl + '/my-route', {
method: 'POST', body: JSON.stringify({anything: 'defined by the application'}),
signal: webspeak.signal
});
const socket = new WebSocket(context.socketUrl + '/my-socket');
```
| 上下文字段 | 内容 |
| --- | --- |
| `apiVersion` | 2 |
| `plugin` | manifest |
| `self` | 当前公开 `id/nickname/uid?` |
| `connection` | 真实 `target/channelId` 和当前频道公开 `members`(`id/nickname/uid?`) |
| `scope` | `{type:"server"|"instance",key:string}`;分组标识不能直接当文件路径 |
| `config` | 管理员公开 JSON,所有参与者可读 |
| `theme/language` | `light/dark` 和 `zh/en/de/ru/ja`,同步到 `<html data-theme>` 与 `lang` |
| `appId` | 本次打开的公开标识,不是长期身份或认证凭据 |
| `serverUrl/socketUrl` | 此会话的后端 HTTP/WS 根;纯前端为 `null` |
| `contextUrl` | 此会话最新上下文地址 |
运行时 URL 含临时凭证,不应持久化、广播或记录。`webspeak.signal` 在撤销或退出时中止,仍需清理自己的定时器、网络、媒体和订阅。应用应提供两种基础配色及适合的语言回退。
用原生 `fetch`、`WebSocket`、`RTCPeerConnection`、文件选择/下载、IndexedDB、Canvas 等编写功能。独立源存储遵循原生规则;同一运行源的应用共享该源存储,请按插件 ID 命名,不能把此设计当作互不信任插件间的隔离。服务端持久化使用 `dataDir`。
关闭面板会销毁 iframe 并取消未完成的打开操作。宿主每秒检查会话有效性,撤销后终止 HTTP、SSE、WS 和旧页面。控制平面只传上下文与生命周期;业务数据使用独立应用服务,不经过语音 WebSocket。
## 可选 Node 后端
```js
export default async function activate({ dataDir, config, publicConfig, events, signal, log }) {
return {
handle(req, res) {
// req.webspeak is verified by the host; req.url is your own route.
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({participant: req.webspeak.self.id}));
},
upgrade(req, socket, head) { /* your WebSocket protocol */ },
async stop() { /* flush data and release resources */ }
};
}
```
也可直接返回 `(req,res)=>…`。这是 Node 原生请求/响应,可适配 Express、WS 等库。`req.webspeak` 含 `apiVersion/appId/self/connection/scope`,不含临时 URL 或管理凭据;服务端 `connection` 只有目标和频道。代理剥离主站 Cookie、Authorization 和伪造的 `x-webspeak-*` 头;应用自行认证可使用自定义头或自己的外部服务。后端不会收到主站管理员/Query 密钥,除非管理员主动在插件配置中提供。
`dataDir` 为本插件持久目录,更新/重启/卸载保留。代码提取目录会清理,不可持久化。包文件没有可执行位;额外子程序需作者自行处理权限和平台。Node 网络、文件、子程序和第三方服务同样属于审核范围。
`config` 是后端私密 JSON,`publicConfig` 是公开 JSON。私密配置在管理页仅显示是否已保存,支持保留/替换/删除,用实例主密钥加密存储;启用的 Node 代码获得明文。它不是针对恶意插件的秘密保险箱。不要把私密配置写入响应或日志。
`events` 为 Node `EventEmitter`:`participantJoined/contextChanged` 提供服务端公开上下文,`participantLeft` 为 `{appId,selfId,scopeKey}`。加入指打开应用面板,不是全体 TS 成员。`signal` 在停止时中止;`log(level,message)` 提供限流日志,宿主当前以 debug 级别记录。
每个后端一个进程,默认最多 8 个;启动超时 10 秒、停止宽限 2 秒、JS 堆上限 256 MiB(不是总 RSS 限额)。失败显示错误、撤销会话,可手动重启,无无限重试。每个语音连接最多 8 个打开会话,全局 800 个,每会话最多 32 条代理连接及 4 条上下文 SSE。普通 HTTP 空闲超时 120 秒,无上下文 SSE 且 90 秒无活动的会话回收。作者负责消息大小、业务授权、并发、存储一致性和依赖资源用量。
## 分发与验证
[分发仓库](https://github.com/Huddle-Up-Forge/webspeak-plugin) 目录为 `{"schemaVersion":2,"plugins":[{"id":"community.my-app","repository":"https://github.com/OWNER/REPO","metadataPath":"plugin.json"}]}`。插件仓库 `plugin.json` 包含同一 `manifest` 和 `package:{ref,path,sha256}`。`ref` 使用固定提交/不可变标签,`path` 指向已提交包,SHA-256 为包原始字节哈希。宿主限制 GitHub 内容来源、核验哈希与 manifest;目录或安装修订改变会拒绝覆盖,需重新加载。空目录不默认安装插件。
验证实际构建包的导入、审核、启用、自定义 HTTP/WS、依赖加载、持久化和关闭/断线/禁用/更新撤销;检查明暗、语言、窄屏。协作另测两位真实参与者及并发/离开/重连。区分模拟身份、真实 TS、浏览器交互与跨网络证据。宿主回归:`npm run verify`。
## 悬浮应用窗口 / Floating application workspace
功能插件入口由宿主的独立悬浮层提供,不属于默认主题或任何皮肤插槽。入口可拖动,避免遮挡工作台控件。应用库和应用内容使用非模态窗口:打开后仍可操作工作台;标题栏可拖动,支持最小化、最大化、还原和关闭,小屏幕自动限制在可视区域内。宿主窗口优先读取标准 `color-scheme` 来选择日间/夜间配色,不继承皮肤组件样式。
最小化、切换到应用库、再返回当前应用均保留同一个 iframe 与会话,传输、播放等任务不会因收起窗口而重置。关闭窗口、切换至另一个应用或语音会话撤销时,宿主结束当前应用会话。当前同时承载一个前端应用;不要把窗口最小化当成退出事件。
应用只负责 iframe 内部内容,使用自身响应式日间/夜间样式和上下文中的主题、语言。不读取或改写皮肤 DOM,不绘制覆盖宿主的全屏遮罩,不自行重复宿主的标题栏、最小化和关闭按钮。需要自有导航时可在内容区实现。应用界面优先显示功能与实际状态,不重复运行环境、权限或免责说明;管理员启用时的信任与权限信息保留在管理流程中。
## 实例级用户授权
首次访问时,宿主统一征求第三方皮肤与功能应用的使用授权;决定按浏览器源保存,不迁移旧的逐皮肤授权。拒绝或未选择时,只显示日间、夜间、ILLUSIA 三款官方皮肤,KAAK 和功能应用入口均隐藏。皮肤菜单最后的“授权”可随时更改。撤回会关闭 iframe 并撤销当前打开操作/应用会话,不停止管理员启用的全实例后台服务。应用不得以入口以外的方式绕过宿主授权,也无需重复询问同一份宿主上下文授权;相机、麦克风等浏览器原生许可仍由浏览器处理。
+317 -119
View File
@@ -1,62 +1,182 @@
# WebSpeak · Deutsch
<a id="readme-top"></a>
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
<div align="center">
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
<h1>WebSpeak · Deutsch</h1>
<p><strong>Deiner TeamSpeak-Community im Browser beitreten.</strong></p>
<p><a href="../README.md">Projektstartseite</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
<p>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;color=0f766e" alt="Release" /></a>
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
</p>
</div>
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.
WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer verwenden Sprache, Chat und Bildschirmfreigabe im Browser; Betreiber verwalten Zielserver, Zugriff und Daten über die Webkonsole.
Aktuelle Version: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
Stabile Version: [Hinweise zu v0.3.0](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Mit Plugin-API v2, schwebenden Anwendungen und gemeinsamer Instanzberechtigung.
[Live-Demo](#demo) · [Funktionen](#features) · [Screenshots](#screenshots) · [Bereitstellung](#deployment) · [Verwaltung](#administration) · [Erweiterte Einstellungen](#advanced) · [Skins & Plugins](#extensions) · [Problemlösung](#troubleshooting) · [Änderungsprotokoll](#changelog)
<a id="demo"></a>
## Live-Demo
Adresse: <https://webspeak.online>
- [Shanghai · shanghai.webspeak.online](https://shanghai.webspeak.online)
- [Hongkong · webspeak.online](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.
Willkommensseite und Sprachbereich direkt ausprobieren. Netzwerk, Auslastung und Verfügbarkeit der Demo-Knoten können schwanken.
## ✨ Funktionen
<a id="features"></a>
## Funktionen
| Funktion | Beschreibung |
| --- | --- |
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele, widerrufbare Einladungen sowie Import, Konvertierung, Prüfung und Export von TeamSpeak-3-Identitäten. |
| Administration | Ziele, Zugriff, öffentliche Medienadresse, IPv6-Kandidaten, Sprach-STUN, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
| Projektstruktur | In 0.2.6 wurden Sprach-Gateway, Sitzungsereignisse, Audio und Bildschirmfreigabe in Module aufgeteilt; Sprach- und Admin-Oberflächen in Komponenten, Composables und Dienste zerlegt und um Lebenszyklus- und Wiederverbindungstests ergänzt. |
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
| Selbsthosting | Daten bleiben beim Betreiber; 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. |
| Echtzeit-Sprache | Opus, optionales WebRTC und WebSocket-Fallback; Stummschaltung, VOX, Geräteauswahl, Browser-Geräuschunterdrückung und Lautstärke je Mitglied. |
| Kanäle & Nachrichten | Kanalbaum und TeamSpeak-Trenner, Mitgliedsstatus, Kanalwechsel, Kanal-/Server-/Privatchat, Anstupsen, Flüstern und lokaler Chatverlauf. |
| Bildschirm & Audio | Bildschirmfreigabe zwischen Browsern und unterstützten nativen TeamSpeak-6-Clients mit Qualitäts-, Bitraten- und Statistikoptionen; Fenster-/Tab-Audio auf dem Desktop. |
| Identität & Verbindungen | Gespeicherte Identitäten, TS3-Identitätsimport/-export, Favoriten und Verlauf, SRV-/Nickname-Auflösung, IPv4/IPv6 und Einladungen. |
| Instanzverwaltung | Feste oder offene Ziele, Zugriffsregeln, Einladungen, Sitzungen, Logs, Diagnosen, Backups und optionale TeamSpeak-Verwaltung. |
| Skins & Oberfläche | Tag, Nacht, ILLUSIA und KAAK, `.wskin`-Pakete über GitHub, fünf Sprachen und responsive Ansichten. |
| Verteilte Sprache | Der Browser verbindet sich direkt mit dem gewählten Relay-Sprach-Gateway; die URL der Eingangsinstanz bleibt erhalten. |
| Bereitstellung | Docker amd64/arm64, Serverpakete für Windows x64 und Linux x64/ARM64 sowie Android-Vorschau-APKs. |
## 🖼️ Screenshots
### TeamSpeak-Versionskompatibilität
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
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.0-beta.23` [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak richtet sich an TeamSpeak 3 und 6.
<a id="screenshots"></a>
## Screenshots
![WebSpeak · Sprachbereich](./screenshots/webspeak-de.png)
<details>
<summary>Willkommensseite, Audiosteuerung und Mitgliedermenü anzeigen</summary>
### Willkommensseite
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
### Sprachbereich
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
![WebSpeak · Willkommensseite](./screenshots/webspeak-de-home.png)
### Audiosteuerung
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
![WebSpeak · Audiosteuerung](./screenshots/webspeak-de-audio.png)
### Mitgliedermenü
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
![WebSpeak · Mitgliedermenü](./screenshots/webspeak-de-menu.png)
## 🧩 Erweiterte Funktionen
</details>
<a id="deployment"></a>
## Bereitstellung & erste Konfiguration
Die Compose-Konfiguration verwendet `network_mode: host` für Linux-Docker-Hosts. Für einen Windows-Server das Release-Paket verwenden.
| Methode | Geeignet für | Umgebung |
| --- | --- | --- |
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.12+, Git und native Build-Werkzeuge |
### Docker Compose (empfohlen)
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
```bash
docker compose ps
docker compose logs -f webspeak
```
Upgrade:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
### Release-Paket
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
### Aus dem Quellcode
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
### Erste Konfiguration
1. `http://<dein-host>:3040/admin` öffnen.
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
### HTTPS & persistente Daten
Öffentliche Webseite und WebSocket über HTTPS bereitstellen. Beispielsweise die eigene Domain auf den Host zeigen lassen und Caddy als Reverse Proxy einrichten:
```caddyfile
webspeak.example.com {
reverse_proxy 127.0.0.1:3040
}
```
Die Beispieldomain durch die eigene ersetzen. Ein erreichbarer Reverse Proxy oder Tunnel garantiert keine UDP-Medienverbindung; siehe [Erweiterte Einstellungen](#advanced). Release- und Quellcode-Installationen verwenden `data/`, Docker das Volume `webspeak-data`. Bei Backup und Umzug `webspeak.db` und den zugehörigen `master.key` gemeinsam aufbewahren.
<a id="administration"></a>
## Administration
Unter `/admin` werden Server, Zugriff, WebRTC, Relays, Einladungen, aktive Sitzungen, Logs und Backups verwaltet. Der Skin-Store liegt unter `/admin/skins`, der Store für funktionale Plugins unter `/admin/plugins`.
### 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.
<a id="advanced"></a>
## Erweiterte Einstellungen
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
### 1. WebRTC-Sprache mit niedriger Latenz
### WebRTC-Sprache mit niedriger Latenz
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
@@ -67,6 +187,14 @@ WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
### Sprach-WebRTC hinter Reverse Proxy oder TCP-Tunnel
Unter **Server → Erweiterte Einstellungen** die **öffentliche Medienadresse** als per UDP erreichbare IP oder Domain des Sprach-Gateways eintragen, ohne Schema, Pfad oder Port. Sie ersetzt die aus dem Webseitenaufruf abgeleitete Adresse. Ein Proxy-Hostname ist nicht automatisch eine erreichbare Medienadresse.
**IPv6-Kandidaten** sind optional und behalten IPv4 bei; IPv6-Routing und Firewall müssen passen. Als **Sprach-STUN** kann `stun:turn.teamspeak.com:3478` eingetragen werden. Browser und Gateway verwenden dann denselben Dienst. Leer behält das bisherige Verhalten bei: STUN des Gateway-SDKs, kein Browser-STUN. Zulässig sind IPv4-erreichbare UDP-STUN-Domains oder IPv4-Adressen, keine IPv6-Literale oder TURN-Zugangsdaten.
Speichern und neu verbinden. Den gesamten UDP-Portbereich öffnen und bei statischer Weiterleitung die Portnummern erhalten. STUN findet Adressabbildungen, leitet aber keine Audiodaten weiter. Ein reiner TCP-Tunnel ohne nutzbaren UDP-/IPv6-Pfad führt weiter zum kompatiblen Transport.
### ICE-Kandidaten für Bildschirmfreigabe
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
@@ -81,11 +209,14 @@ Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niem
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
### 2. Relay-Modus
### Relay-Modus
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder Administrationsseite. Sie akzeptiert nur Gateway-Sitzungen mit passendem Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
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.
<details>
<summary>Start- und Konfigurationsbeispiele für Relays anzeigen</summary>
#### Aus dem Quellcode starten
@@ -93,7 +224,7 @@ 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 rebuild @discordjs/opus --foreground-scripts
npm run build
WEBSPEAK_MODE=relay \
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
@@ -137,26 +268,147 @@ 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.
### 3. Abhängigkeiten und Hinweise zur Herkunft
</details>
### Abhängigkeiten und Hinweise zur Herkunft
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
- TeamSpeak verwendet das Upstream-Paket [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) `@honeybbq/teamspeak@1.0.0-beta.23`; ein eigener SDK-Fork muss nicht gebaut werden.
## 🧾 Änderungsprotokoll
<a id="extensions"></a>
## Skins & funktionale Plugins
### Skin-Pakete `.wskin`
Skins gestalten Aussehen, Layout und zugehörige Widgets. Administratoren installieren, aktivieren und wählen den Standard-Skin. Autoren verwenden öffentliche Schnittstellen ohne Änderungen am WebSpeak-Quellcode.
[Entwicklungsleitfaden](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin-Katalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord-Voice-Beispiel](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
### Funktionale Plugins `.wplugin`
Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und optionalen Node-Backends, eigenen Routen, Daten und Zusammenarbeit. Administratoren prüfen Code und Abhängigkeiten vor der Aktivierung; Updates erfordern erneutes Vertrauen. Anwendungen unterstützen TS-Server- oder Instanz-Bereiche und eine separate Origin. API v2 ist ab v0.3.0 enthalten.
[Entwicklungsleitfaden](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Verteilungskatalog & Beispiel](https://github.com/Huddle-Up-Forge/webspeak-plugin)
<a id="troubleshooting"></a>
## Problemlösung
| Symptom | Prüfen |
| --- | --- |
| WebRTC fällt trotz Aktivierung zurück | Fehlercode im Sprachstatus, HTTPS, vollständigen UDP-Portbereich und öffentliche Medienadresse prüfen. Ein TCP-Tunnel transportiert diese UDP-Medien nicht. |
| Ziel wird als lokale Adresse blockiert | Der offene Modus beschränkt Loopback-/Privatadressen. Für einen TS-Server auf demselben Host den administrativ konfigurierten festen Servermodus verwenden. |
| Bildschirmfreigabe läuft ab oder bleibt schwarz | Sie verwendet eine eigene WebRTC-Verbindung. Aushandlung, ICE und Codec-Statistik prüfen; verbundenes Sprach-WebRTC bestätigt nicht die Bildschirmverbindung. |
| Daten fehlen oder lassen sich nach dem Update nicht entschlüsseln | Dasselbe Datenverzeichnis bzw. Volume mit passendem `master.key` verwenden. Nicht mit `docker compose down -v` aktualisieren. |
### ⚠️ Voraussetzungen und Hinweise
| Bereich | Hinweis |
| --- | --- |
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
| Sitzungslimit | Bis zu 100 aktive Browser-Sitzungen pro Instanz; dies ist ein Anwendungslimit, keine Leistungszusage oder TS-Lizenzgrenze. |
<a id="changelog"></a>
## Änderungsprotokoll
<a id="latest-release-notes"></a>
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Plugin-Anwendungen
- Plugin-API v2 für eigenständige Browser-Anwendungen und optionale Node-Backends mit eigenen Routen, Zuständen, Kommunikationswegen und Funktionen.
- Installation über den GitHub-Store oder lokale `.wplugin`-Pakete. Administratoren verwalten öffentliche/private Konfigurationen, prüfen und aktivieren Anwendungen; Updates erfordern erneutes Vertrauen.
- Ein vom Design unabhängiger schwebender Einstieg und eine Anwendungsbibliothek. Fenster lassen sich verschieben, skalieren, minimieren, maximieren und wiederherstellen; Minimieren oder der Wechsel zur Bibliothek lädt die Anwendung nicht neu.
- Anwendungsvorlage, Entwicklungsanleitung und Agent Skill; P2P-Dateiübertragung und gemeinsames Videoschauen werden in eigenen Repositories verteilt.
#### Designs und Berechtigung
- Beim ersten Besuch wird gemeinsam nach der Berechtigung für Designs und Plugins dieser Instanz gefragt; Verbindungszugangsdaten sind ausgeschlossen. Der letzte Eintrag im Designmenü öffnet diese Einstellung erneut.
- Ohne Zustimmung bleiben nur Tag, Nacht und ILLUSIA verfügbar. KAAK, andere Designs und der Plugin-Einstieg werden ausgeblendet. Ein Widerruf stellt ein integriertes Design wieder her, bricht laufende Ladevorgänge ab und beendet zugehörige Komponenten und Anwendungsseiten.
- Manifest-Berechtigungen, Datenprojektion, Paketprüfsummen und Prüfungen von Host-Aktionen bleiben erhalten. Die Prüfung durch den Administrator gilt weiterhin separat.
#### Korrekturen und Aktualisierungen
- Native TS-Clients beantworteten reine Videoangebote bei Fenster-, Bildschirm- oder Freigaben ohne Ton nicht. Die erforderliche Audiosektion wird jetzt ausgehandelt, ohne ein Mikrofon aufzunehmen oder Ton zu erzeugen. Fenster- und Bildschirmvideo wurden im Benutzertest bestätigt.
- SDK auf `@honeybbq/teamspeak@1.0.0-beta.23` aktualisiert; optionale Mitgliedsfelder werden berücksichtigt und leere Pakete am Sprachende übersprungen.
- Upstream-Korrekturen für TSDNS, Query-Wiederholungen nach Flooding, Dateiübertragungen und Verbindungsabbau übernommen.
- Korrekturen für IPv6-Zielprüfung, begrenzte parallele Anmeldungen, Sitzungswiderruf nach Passwortwechsel, vertrauenswürdige Proxys und PCM-Uplink-Schutz übernommen.
- Der Kaltstart von Designs verwendet weiterhin die tatsächliche Build-Version. Desktop, Web und Android verwenden eine einheitliche Anwendungsversion.
#### Aktualisierung
- Plugin-API v2 ist nicht mit v1-Paketen kompatibel. Ersatzanwendungen aktualisieren, prüfen und aktivieren.
- Öffentliche Plugins benötigen einen separaten HTTPS-Ursprung, der im Administrationsbereich konfiguriert und an den Laufzeitport (Standard `3042`) weitergeleitet wird. Hauptseite und Anwendungen dürfen keinen Ursprung teilen.
- Die Instanzberechtigung muss neu gewählt werden; frühere Einzelberechtigungen gelten nicht als Zustimmung.
### [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.
<details>
<summary>v0.2.8 und frühere Versionen anzeigen</summary>
### [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
@@ -233,87 +485,33 @@ WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansich
Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung.
</details>
## 🚀 Bereitstellung
<a id="contributors"></a>
| Methode | Geeignet für | Umgebung |
| --- | --- | --- |
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
## Mitwirkende & Herkunft
### Docker Compose (empfohlen)
<details>
<summary>Upstream-Autoren und PR-Beiträge anzeigen</summary>
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
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.
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
```bash
docker compose ps
docker compose logs -f webspeak
```
Upgrade:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
### Release-Paket
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
### Aus dem Quellcode
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
### Erste Konfiguration
1. `http://<dein-host>:3040/admin` öffnen.
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
## ⚠️ Voraussetzungen und Hinweise
| Bereich | Hinweis |
| --- | --- |
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
## Kürzlich zusammengeführte 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.
- [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.
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) meldete Sicherheitsprobleme und lieferte Korrekturvorschläge sowie Regressionstests für IPv6-Zielprüfung, Admin-Anmeldung und Sitzungen, Proxy-Ratenlimits und PCM-Uplink. Der ursprüngliche Patch wurde nicht direkt übernommen; die Korrekturen wurden auf `dev` neu implementiert.
- [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.
</details>
## Community & verwandte Projekte
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ-Gruppe 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot): TeamSpeak-Musikbot mit plattformübergreifender Wiedergabe und Webkonsole.
## Lizenz
WebSpeak wird unter [AGPL-3.0-only](../LICENSE) veröffentlicht. Lizenzen und Herkunft von Abhängigkeiten stehen in den jeweiligen Upstream-Projekten.
<p align="right"><a href="#readme-top">Nach oben ↑</a></p>
+309 -121
View File
@@ -1,64 +1,182 @@
# WebSpeak · English
<a id="readme-top"></a>
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
<div align="center">
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
<h1>WebSpeak · English</h1>
<p><strong>Join your TeamSpeak community from a browser.</strong></p>
<p><a href="../README.md">Project home</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
<p>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;color=0f766e" alt="Release" /></a>
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
</p>
</div>
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.
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors join voice, chat and screen sharing in a browser; operators manage target servers, access policy and data through the administration console.
Latest release: [read the 0.2.7 changelog on this page](#latest-release-notes).
Stable release: [v0.3.0 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Includes plugin API v2, floating applications and unified instance authorization.
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](#demo) · [Features](#features) · [Screenshots](#screenshots) · [Deployment](#deployment) · [Administration](#administration) · [Advanced settings](#advanced) · [Skins & plugins](#extensions) · [Troubleshooting](#troubleshooting) · [Changelog](#changelog)
<a id="demo"></a>
## Live demo
URL: <https://webspeak.online>
- [Shanghai · shanghai.webspeak.online](https://shanghai.webspeak.online)
- [Hong Kong · webspeak.online](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.
Try the welcome page and voice workspace. Network conditions, load and availability vary between demo nodes.
## ✨ Features
<a id="features"></a>
| Capability | Description |
## Features
| Capability | What it provides |
| --- | --- |
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
| Identity and access | Remembered identity, visitor-defined targets, revocable expiring invite links, and TeamSpeak 3 identity import, conversion, validation, and export. |
| Administration | Manage targets, access policy, public media address, IPv6 candidates, voice STUN, relays, invites, sessions, logs, diagnostics, and backups. |
| Engineering structure | In 0.2.6, gateway voice, session events, audio, and screen-share coordination were split into modules; frontend voice and admin pages were decomposed into components, composables, and services, with lifecycle and reconnect tests. |
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
| Self-hosting | Data stays with the operator; packages include Windows x64 and Linux x64/ARM64, Docker supports amd64/arm64, and Android APKs target arm64-v8a, armeabi-v7a, and x86_64. |
| Realtime voice | Opus, optional WebRTC and WebSocket fallback; mute, VOX, device selection, browser noise suppression and per-member volume. |
| Channels & messaging | Channel tree and TeamSpeak spacers, member state, channel switching, channel/server/private chat, pokes, whispers and local chat history. |
| Screen & audio sharing | Screen sharing between browsers and supported native TeamSpeak 6 clients, with quality, bitrate and statistics controls; desktop window or tab audio sharing. |
| Identity & connections | Remembered identities, TS3 identity import/export, favorites and history, SRV and Nickname resolution, IPv4/IPv6 and invitation links. |
| Instance administration | Fixed or open targets, access policy, invitations, sessions, logs, diagnostics, backups and optional TeamSpeak management connections. |
| Skins & interface | Day, Night, ILLUSIA and KAAK, plus GitHub distribution of `.wskin` packages, five interface languages and responsive layouts. |
| Distributed voice | Browsers connect directly to the selected relay voice gateway while the page stays on the ingress instance URL. |
| Deployment | Docker amd64/arm64, Windows x64 and Linux x64/ARM64 server packages, plus Android preview APKs. |
## 🖼️ Screenshots
### TeamSpeak version compatibility
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
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.0-beta.23` SDK; WebSpeak targets TeamSpeak 3 and TeamSpeak 6.
<a id="screenshots"></a>
## Screenshots
![WebSpeak · Voice workspace](./screenshots/webspeak-en.png)
<details>
<summary>Show the welcome page, audio controls and member menu</summary>
### Welcome page
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
### Voice workspace
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
![WebSpeak · Welcome page](./screenshots/webspeak-en-home.png)
### Audio controls
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
![WebSpeak · Audio controls](./screenshots/webspeak-en-audio.png)
### Member menu
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
![WebSpeak · Member menu](./screenshots/webspeak-en-menu.png)
## 🧩 Advanced features
</details>
<a id="deployment"></a>
## Deployment & first-time setup
The Compose configuration uses `network_mode: host` and targets Linux Docker hosts. Use the release package for a Windows server.
| Method | Best for | Environment |
| --- | --- | --- |
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
| From source | Development, debugging, and customization | Node.js 22.12+, Git, and native build tools |
### Docker Compose (recommended)
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
```bash
docker compose ps
docker compose logs -f webspeak
```
Upgrade:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
Do not run `docker compose down -v`; it removes the database and administrator settings.
### Release package
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
### From source
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
### First-time setup
1. Open `http://<your-host>:3040/admin`.
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
### HTTPS & persistent data
Expose the public page and WebSocket over HTTPS. For example, point your hostname to the host and configure Caddy to reverse-proxy WebSpeak:
```caddyfile
webspeak.example.com {
reverse_proxy 127.0.0.1:3040
}
```
Replace the example hostname with your own. A working reverse proxy or Tunnel does not make WebRTC UDP media reachable; see [Advanced settings](#advanced). Release/source installs use `data/`, while Docker uses the `webspeak-data` volume. Keep `webspeak.db` and its matching `master.key` together when backing up or moving an instance.
<a id="administration"></a>
## Administration
Open `/admin` to manage servers and access, WebRTC and relays, invitations, active sessions, logs and backups. The skin store is at `/admin/skins`; the functional plugin store is at `/admin/plugins`.
### 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.
<a id="advanced"></a>
## Advanced settings
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
### 1. WebRTC low-latency voice
### WebRTC low-latency voice
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
@@ -91,11 +209,14 @@ With TURN configured, media may use that external TURN service but never the Web
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
### 2. Relay mode
### Relay mode
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
A relay instance is a dedicated forwarding service with no visitor page or administration console. It accepts only gateway sessions with a matching token. Use a random token of at least 16 characters.
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.
<details>
<summary>Show relay startup and configuration examples</summary>
#### Run from source
@@ -103,7 +224,7 @@ 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 rebuild @discordjs/opus --foreground-scripts
npm run build
WEBSPEAK_MODE=relay \
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
@@ -147,26 +268,147 @@ 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.
### 3. Dependencies and attribution
</details>
### Dependencies and attribution
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
- TeamSpeak connectivity uses the upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) package `@honeybbq/teamspeak@1.0.0-beta.23`; a project SDK fork build is not required.
## 🧾 Changelog
<a id="extensions"></a>
## Skins & functional plugins
### Skin packages `.wskin`
Skins own appearance, layout and their attached widgets. Administrators install, enable and choose the default skin. Authors use the public contract without changing WebSpeak source code.
[Development guide](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Skin catalog](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice example](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
### Functional plugins `.wplugin`
Functional plugins are independent applications using standard browser capabilities and optional Node backends with their own routes, state and collaboration. Administrators review code and dependencies before enabling; updates require renewed trust. Applications support TS server or instance scope and run on a separate origin. API v2 is included starting with v0.3.0.
[Development guide](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Distribution catalog & example](https://github.com/Huddle-Up-Forge/webspeak-plugin)
<a id="troubleshooting"></a>
## Troubleshooting
| Symptom | What to check |
| --- | --- |
| WebRTC falls back after being enabled | Check the voice-status error code, HTTPS, the complete UDP firewall range and the public media address. A TCP Tunnel does not carry this UDP media path. |
| A target is blocked as a local address | Open mode restricts loopback/private targets. Use the administrator-configured fixed-server mode for a co-located TS server; visitor-defined targets need a reachable address. |
| Screen sharing times out or stays black | Screen sharing has a separate WebRTC connection. Inspect its negotiation, ICE and codec statistics; connected voice WebRTC does not prove screen-media reachability. |
| Data is missing or cannot be decrypted after upgrading | Reuse the data directory or volume and its matching `master.key`. Do not upgrade with `docker compose down -v`. |
### ⚠️ Requirements and notes
| Area | Requirement or note |
| --- | --- |
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
| Session limit | One instance admits up to 100 active browser sessions; this is an application limit, not a performance guarantee or TS license allowance. |
<a id="changelog"></a>
## Changelog
<a id="latest-release-notes"></a>
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Plugin applications
- Release plugin API v2 for independent browser applications and optional Node backends, with author-defined routes, state, communication and business logic.
- Install applications from the GitHub store or local `.wplugin` packages. Administrators manage public/private configuration, review and enable applications; updates require renewed trust.
- Add a skin-independent floating launcher and application library. Windows support dragging, resizing, minimize, maximize and restore; minimizing or returning to the library keeps the active application loaded.
- Provide an application template, development guide and Agent Skill. P2P file transfer and Watch Together are distributed from separate repositories.
#### Skins and authorization
- Ask once on first entry for this instance’s third-party skins and plugins together, excluding connection credentials. The final Authorization item in the skin menu allows changes at any time.
- Without consent, offer only Day, Night and ILLUSIA; hide KAAK, other third-party skins and plugin access. Revocation restores a built-in skin, cancels pending loads and stops related components and application pages.
- Retain manifest permissions, data projection, package digests and host action checks. Administrator application review and trust remain independent.
#### Fixes and upgrades
- Fix native TS clients not answering video-only offers when sharing an application window, the entire screen or without shared audio. Negotiate the required audio section without capturing a microphone or fabricating shared sound. Window and full-screen video were confirmed by user retesting.
- Upgrade to `@honeybbq/teamspeak@1.0.0-beta.23`, handle optional member fields and skip empty audio packets that mark the end of speech.
- Include upstream TSDNS resolution, Query flooding retries, file transfer and disconnect cleanup fixes.
- Include IPv6 target validation, bounded concurrent login, password-change session revocation, trusted-proxy rate limiting and PCM uplink protection fixes.
- Retain and verify the skin cold-start fix that uses the real build version. Align application versions across desktop, web and Android.
#### Upgrading
- Plugin API v2 is incompatible with API v1 packages. Update, review and enable replacement applications.
- Public plugin deployment requires a separate HTTPS application origin configured in administration and proxied to the runtime port (default `3042`). The application and main site must not share an origin.
- Users must make a new instance authorization choice; old per-skin approvals do not imply consent.
### [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.
<details>
<summary>Show v0.2.8 and earlier releases</summary>
### [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
@@ -243,87 +485,33 @@ Fixed WebRTC and channel chat and refined administration, logs, and mobile layou
Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering.
</details>
## 🚀 Deployment
<a id="contributors"></a>
| Method | Best for | Environment |
| --- | --- | --- |
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
## Contributors & attribution
### Docker Compose (recommended)
<details>
<summary>Show upstream authors and PR contributions</summary>
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
This list acknowledges the upstream SDK author, contributions through merged GitHub PRs, and original work adapted into independently distributed skin packages.
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
```bash
docker compose ps
docker compose logs -f webspeak
```
Upgrade:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
Do not run `docker compose down -v`; it removes the database and administrator settings.
### Release package
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
### From source
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
### First-time setup
1. Open `http://<your-host>:3040/admin`.
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
## ⚠️ Requirements and notes
| Area | Requirement or note |
| --- | --- |
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
| Session limit | One instance accepts up to 100 active browser sessions. |
## Recent contributors
- 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.
- [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.
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) reported security issues and supplied proposed fixes and regression tests for open-target IPv6 validation, admin authentication/sessions, proxy-aware limits and PCM uplink boundaries. The original patch was not merged directly; the fixes were reimplemented on `dev`.
- [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).
</details>
## Community & related projects
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ group 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot): a TeamSpeak music bot with multi-platform playback and a web console.
## License
WebSpeak is distributed under [AGPL-3.0-only](../LICENSE). See each upstream project for third-party licenses and attribution.
<p align="right"><a href="#readme-top">Back to top ↑</a></p>
+321 -77
View File
@@ -1,90 +1,85 @@
# WebSpeak · 日本語
<a id="readme-top"></a>
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
<div align="center">
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
<h1>WebSpeak · 日本語</h1>
<p><strong>ブラウザーから、いつもの TeamSpeak へ。</strong></p>
<p><a href="../README.md">プロジェクトトップ</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a></p>
<p>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;color=0f766e" alt="Release" /></a>
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
</p>
</div>
## プロジェクト概要
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
最新リリース:[v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7)。
安定版:[v0.3.0 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。API v2、フローティングアプリ、インスタンス単位の許可に対応。
| 観点 | 説明 |
| --- | --- |
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
[オンラインデモ](#demo) · [機能](#features) · [画面プレビュー](#screenshots) · [デプロイ](#deployment) · [管理](#administration) · [詳細設定](#advanced) · [スキンとプラグイン](#extensions) · [トラブル対処](#troubleshooting) · [更新履歴](#changelog)
<a id="demo"></a>
## オンラインデモ
アドレス: <https://webspeak.online>
- [上海 · shanghai.webspeak.online](https://shanghai.webspeak.online)
- [香港 · webspeak.online](https://webspeak.online)
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
ホームと音声ワークスペースを体験できます。デモのネットワーク、負荷、稼働状況は変動します。
## ✨ 機能
<a id="features"></a>
| 機能 | 説明 |
## 主な機能
| 機能 | 内容 |
| --- | --- |
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンクに加え、TeamSpeak 3 ID のインポート、変換、検証、エクスポート。 |
| 管理コンソール | 接続先、アクセス、公開メディアアドレス、IPv6 候補、音声 STUN、中継、招待、セッション、ログ、診断、バックアップ。 |
| プロジェクト構造 | 0.2.6 では音声ゲートウェイ、セッションイベント、音声処理、画面共有調整を分割し、音声・管理画面をコンポーネント、composable、サービスに整理しました。ライフサイクルと再接続のテストも追加しました。 |
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
| デプロイ | Windows x64、Linux x64/ARM64 パッケージ、Docker amd64/arm64、Android arm64-v8a・armeabi-v7a・x86_64 APK。 |
| リアルタイム音声 | Opus、任意の WebRTC、WebSocket へのフォールバック。ミュート、VOX、デバイス選択、ブラウザー側ノイズ抑制、メンバー別音量に対応。 |
| チャンネルとメッセージ | チャンネルツリーと TeamSpeak 区切り、メンバー状態、移動、チャンネル・サーバー・個人チャット、Poke、ささやき、ローカル履歴。 |
| 画面と音声の共有 | ブラウザー間および対応する TeamSpeak 6 クライアントとの画面共有。品質、ビットレート、統計を設定でき、デスクトップではウィンドウやタブの音声も共有可能。 |
| ID と接続 | ID 保持、TS3 ID インポート・エクスポート、お気に入りと履歴、SRV・Nickname 名前解決、IPv4/IPv6、招待リンク。 |
| インスタンス管理 | 固定・公開接続先、アクセス方針、招待、セッション、ログ、診断、バックアップ、任意の TeamSpeak 管理接続。 |
| スキンと画面 | 昼・夜・ILLUSIA・KAAK、GitHub 経由の `.wskin` 配布、5 言語、レスポンシブ表示。 |
| 分散音声 | ブラウザーが選択した中継の音声ゲートウェイに直接接続し、ページの URL は入口インスタンスのまま維持。 |
| デプロイ方法 | Docker amd64/arm64、Windows x64・Linux x64/ARM64 サーバーパッケージ、Android プレビュー APK。 |
## 🖼️ インターフェースのスクリーンショット
### TeamSpeak のバージョン互換性
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
音声接続には標準の TeamSpeak クライアントプロトコルを使い、Query の認証情報は不要です。任意の TS 管理機能では、別途 WebQuery / ServerQuery の認証情報を使用します。
- **TeamSpeak 3**: 先頭の `3.x` バージョンを使ってプロトコルを判定します。すべての旧バージョンを個別に検証しているわけではないため、古いサーバーは実際の環境で確認してください。
- **TeamSpeak 6**: 対応しています。TeamSpeak 6 ネイティブクライアントとの画面共有も可能です。
- **自動検出**: ゲートウェイはサーバーの `version` 応答を読み取り、接続診断に判定結果を記録します。
- ゲートウェイは上流 SDK `1.0.0-beta.23` の [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js) を使用し、WebSpeak は TeamSpeak 3 と 6 を対象とします。
<a id="screenshots"></a>
## 画面プレビュー
![WebSpeak · 音声ワークスペース](./screenshots/webspeak-ja.png)
<details>
<summary>ホーム、オーディオ設定、メンバーメニューを表示</summary>
### ホーム
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
### 音声ワークスペース
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
![WebSpeak · ホーム](./screenshots/webspeak-ja-home.png)
### オーディオ設定
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
![WebSpeak · オーディオ設定](./screenshots/webspeak-ja-audio.png)
### メンバーメニュー
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
![WebSpeak · メンバーメニュー](./screenshots/webspeak-ja-menu.png)
## 🧩 高度な機能
</details>
### WebRTC
<a id="deployment"></a>
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
## デプロイと初期設定
### 画面共有の ICE 候補
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
### クロスプラットフォーム P2P 画面共有
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
### 中継サーバー
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
## 🚀 デプロイ
Compose は `network_mode: host` を使う Linux Docker ホスト向けの構成です。Windows サーバーには Release パッケージを使用してください。
| 方法 | 用途 |
| --- | --- |
@@ -103,6 +98,19 @@ docker compose up -d
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
```bash
docker compose ps
docker compose logs -f webspeak
```
データを保持して更新:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
### Release パッケージ
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から `windows-x64.zip`、`linux-x64.tar.gz`、`linux-arm64.tar.gz` のいずれかを取得し、同梱ランチャーを実行します。Docker は amd64/arm64 に対応します。`arm64-v8a`、`armeabi-v7a`、`x86_64` の Android APK もあります。APK は手動インストールとテスト向けのデバッグ署名で、Google Play 用ではありません。実機 TeamSpeak 音声は未検証です。
@@ -110,18 +118,148 @@ docker compose up -d
### ソースから
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run web:build
npm run build
npm start
```
## ⚠️ 要件と注意
ビルドには Node.js `>=22.12`、Python、Make、C/C++ コンパイラーが必要です。
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
### 初期設定
1. `http://<your-host>:3040/admin` を開きます。
2. `admin` / `admin` でログインし、直ちに 12 文字以上の新しいパスワードに変更します。
3. **サーバー**で `voice.example.com#9987` などの接続先とアクセスモードを設定します。
4. 公開時は HTTPS を設定し、WebRTC 有効時は指定した UDP 範囲全体を許可します。
### HTTPS とデータ保持
公開ページと WebSocket は HTTPS で提供してください。例えば、自分のドメインをホストに向け、Caddy から WebSpeak へ転送します。
```caddyfile
webspeak.example.com {
reverse_proxy 127.0.0.1:3040
}
```
例のドメインは自分のものに置き換えてください。リバースプロキシや Tunnel でページが開けても、WebRTC の UDP が到達可能とは限りません。[詳細設定](#advanced)を確認してください。パッケージとソースは `data/`、Docker は `webspeak-data` volume を使用します。移行・バックアップ時は `webspeak.db` と対応する `master.key` を一緒に保存します。
<a id="administration"></a>
## 管理コンソール
`/admin` で接続先、アクセス、WebRTC、中継、招待、アクティブセッション、ログ、バックアップを管理します。スキンストアは `/admin/skins`、機能プラグインストアは `/admin/plugins` です。
### 任意の 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 を使う他のユーザーへの影響を避けます。
<a id="advanced"></a>
## 詳細設定
### WebRTC
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
### リバースプロキシ・TCP Tunnel 経由の音声 WebRTC
**サーバー → 詳細設定** の**公開メディアアドレス**には、UDP で到達可能な音声ゲートウェイの IP またはドメインを入力します。スキーム、パス、ポートは含めません。ページのリクエストから推測する接続先より優先され、プロキシのドメインが音声にも到達可能とは限りません。
**IPv6 候補**は任意で、IPv4 も維持します。IPv6 の経路とファイアウォール許可が必要です。**音声 STUN** に `stun:turn.teamspeak.com:3478` を設定すると、ブラウザーとゲートウェイが同じサービスを使います。空欄では従来どおり、ゲートウェイのライブラリ内蔵 STUN を使い、ブラウザーには設定しません。IPv4 で到達可能な UDP STUN ドメイン・IPv4 アドレスに対応し、IPv6 リテラルや TURN 認証情報は指定できません。
保存後に再接続してください。UDP 範囲全体を許可し、固定ポート転送では番号を維持します。STUN はアドレスを検出するだけで音声を中継しません。利用可能な UDP/IPv6 経路のない TCP Tunnel だけでは、互換転送に戻ります。
### 画面共有の ICE 候補
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
### クロスプラットフォーム P2P 画面共有
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
### 中継サーバー
入口ゲートウェイが署名付きの一度限りのチケットを発行し、ブラウザーは中継の音声ゲートウェイに直接接続します。中継が TeamSpeak に接続し、ページの URL はそのままです。中継ノードはホームや管理コンソールを提供しません。
<details>
<summary>中継の起動と設定</summary>
```bash
docker run -d --name webspeak-relay --restart unless-stopped --network host \
-e WEBSPEAK_MODE=relay \
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
-e WEBSPEAK_RELAY_PORT='39087' \
-e WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST='relay.example.com' \
ghcr.io/echosixhiya/webspeak:latest
```
共通トークンはランダムな 16 文字以上にします。音声ゲートウェイは `127.0.0.1:3041` で待ち受けるため、Caddy などで HTTPS/WSS ドメインから転送します。
```caddyfile
relay.example.com {
reverse_proxy 127.0.0.1:3041
}
```
入口側の**サーバー → 中継**で、名前、UDP 接続先 `relay.example.com#39087`、音声接続先 `https://relay.example.com`、同じトークンを設定して保存します。ユーザーは直接接続か中継を選べます。UDP `39087` と WebRTC の `40000–40099` を許可してください。公開メディアアドレスは HTTP プロキシではなく、中継に直接到達できる必要があります。
ソースや Release パッケージでも同じ環境変数を指定します。ビルド後は `node dist/index.js`、パッケージでは `./runtime/node ./dist/index.js`(Windows:`.\runtime\node.exe .\dist\index.js`)で起動します。
</details>
### 依存ライブラリ
中継は WebSpeak に組み込まれ、Node.js 標準ライブラリを使います。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`、TeamSpeak は上流 [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js) の `@honeybbq/teamspeak@1.0.0-beta.23` を使用し、fork のビルドは不要です。
<a id="extensions"></a>
## スキンと機能プラグイン
### スキンパッケージ `.wskin`
スキンは外観、配置、付属ウィジェットを扱います。管理者がインストール、有効化、デフォルト選択を行い、開発者は WebSpeak のソースを変更せず公開 API で制作します。
[開発ガイド](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [スキン一覧](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice サンプル](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
### 機能プラグイン `.wplugin`
機能プラグインは標準ブラウザー機能と任意の Node バックエンドを使う独立アプリです。ルート、状態、共同作業は作者が実装します。管理者はコードと依存関係を審査して有効化し、更新後は再び信頼を確認します。TS サーバーまたはインスタンス範囲に対応し、別オリジンで動作します。API v2 は v0.3.0 から利用できます。
[開発ガイド](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [配布一覧とサンプル](https://github.com/Huddle-Up-Forge/webspeak-plugin)
<a id="troubleshooting"></a>
## トラブル対処
| 症状 | 確認する内容 |
| --- | --- |
| WebRTC を有効にしてもフォールバックする | 音声状態のエラーコード、HTTPS、UDP 範囲全体、公開メディアアドレスを確認します。TCP Tunnel はこの UDP メディア経路を転送しません。 |
| ローカルアドレス保護で接続先が拒否される | 公開モードはループバック・プライベートアドレスを制限します。同じホストの TS には、管理者が設定する固定サーバーモードを使います。 |
| 画面共有がタイムアウトする・黒いまま | 画面共有は独立した WebRTC 接続です。共有統計のネゴシエーション、ICE、コーデックを確認します。音声の接続成功だけでは画面の到達性を確認できません。 |
| 更新後にデータがない・復号できない | 元のデータディレクトリまたは volume と対応する `master.key` を使います。`docker compose down -v` で更新しないでください。 |
### ⚠️ 要件と注意
- ソースからのビルドには Node.js `>=22.12` が必要です。Docker と Release には必要な実行環境が含まれます。
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
@@ -129,16 +267,83 @@ npm start
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
- BGM共有はデスクトップのみで、WebRTC が必要です。
## コミュニティと関連プロジェクト
- WebRTC の初期範囲は UDP `40000–40099` です。全体を許可し、変更前に WebRTC を無効化して保存します。
- アプリケーションの上限は 1 インスタンス 100 ブラウザーセッションです。性能保証や TS ライセンス上限を示すものではありません。
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
<a id="changelog"></a>
## 🧾 更新履歴
## 更新履歴
<a id="latest-release-notes"></a>
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### プラグインアプリ
- 独立したブラウザアプリと任意の Node バックエンドに対応するプラグイン API v2 を公開。作者がルート、状態、通信、機能を実装できます。
- GitHub ストアまたはローカルの `.wplugin` からインストール。管理者が公開・非公開設定を管理し、確認して有効化します。更新後は再度信頼の確認が必要です。
- スキンに依存しないフローティング起動ボタンとアプリライブラリを追加。ウィンドウの移動、サイズ変更、最小化、最大化、復元に対応し、最小化やライブラリへの移動でもアプリを再読み込みしません。
- アプリテンプレート、開発ガイド、Agent Skill を提供。P2P ファイル転送と動画の同時視聴は独立リポジトリで配布します。
#### スキンと許可
- 初回アクセス時に、インスタンスのサードパーティ製スキンとプラグインをまとめて確認します。接続用の認証情報は含みません。スキンメニュー末尾の「許可」から変更できます。
- 同意しない場合は昼・夜・ILLUSIA のみ利用でき、KAAK、その他のスキン、プラグイン入口は非表示になります。許可を取り消すと内蔵スキンに戻り、読み込み処理、関連コンポーネント、アプリページを停止します。
- マニフェストの権限、データ投影、ファイルハッシュ、ホスト操作の検証は維持します。管理者による確認と信頼は別途必要です。
#### 修正と更新
- ウィンドウ、画面全体、音声なしの共有で、映像のみの offer にネイティブ TS クライアントが応答しない問題を修正。必要な音声セクションを交渉しますが、マイクの収録や音声の生成は行いません。ウィンドウと画面全体での表示はユーザーの再テストで確認済みです。
- SDK を `@honeybbq/teamspeak@1.0.0-beta.23` に更新。省略可能なメンバーフィールドに対応し、発話終了を表す空の音声パケットを除外します。
- upstream の TSDNS、Query の制限時リトライ、ファイル転送、切断処理の修正を取り込みました。
- IPv6 の接続先検証、並列ログイン制限、パスワード変更時のセッション失効、信頼済みプロキシの制限、PCM 送信保護を修正しました。
- スキンの初回読み込みに実際のビルドバージョンを使用する修正を維持。デスクトップ、Web、Android のアプリバージョンを統一しました。
#### アップグレード
- API v2 は v1 のプラグインと互換性がありません。対応アプリへ更新し、確認後に有効化してください。
- 公開環境のプラグインには、管理画面で設定した独立 HTTPS オリジンと実行ポート(既定 `3042`)へのプロキシが必要です。メインサイトと同じオリジンは使用できません。
- インスタンス単位の許可を改めて選択してください。旧スキン単位の許可は同意として引き継がれません。
### [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 のクローズは、報告された問題の修正完了を意味しません。
<details>
<summary>v0.2.8 以前の履歴を表示</summary>
### [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
#### より開かれたスキンシステム
@@ -195,14 +400,53 @@ npm start
Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。
### [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) · 2026-09-06
ドイツ語、Telegram、ネットワーク統計、全体音量を追加し、BGM 音量の変動を修正しました。
### [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) · 2026-09-04
ウィンドウ・タブ音声の共有、ID 保持の案内、サイトアイコンを追加し、WebRTC のメンバー別音量を修正しました。
### [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) · 2026-09-04
ID 保存処理を修正し、テーマ切り替えを改善しました。
### [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) · 2026-09-03
WebRTC とチャンネルチャットを修正し、管理画面、ログ、モバイル配置を改善しました。
### [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) · 2026-09-03
内蔵 WebRTC を追加し、TeamSpeak SDK を移行しました。メンバー同期と音声バッファーを改善しました。
</details>
<a id="contributors"></a>
## 貢献者と主な貢献
<details>
<summary>上流作者と PR の貢献を表示</summary>
上流 SDK の作者、マージ済みの GitHub PR、および独立配布のスキンパッケージへ移植された原作の貢献を記載しています。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上流 SDK [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) の作者。WebSpeak の TeamSpeak プロトコル通信を支えるクライアントライブラリを提供。
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) で IPv6 接続先検証、管理者認証とセッション、プロキシ配下の制限、PCM 送信境界の問題を報告し、修正案と回帰テストを提供。元のパッチは直接マージせず、`dev` で改めて修正を実装しました。
- [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 の登録済みニックネーム接続と接続先の保持に対応し、[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)へ移植。
</details>
## コミュニティと関連プロジェクト
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ グループ 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot):複数サービスの再生と Web コンソールに対応した TeamSpeak 音楽ボット。
## ライセンス
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
WebSpeak は [AGPL-3.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) で拡大縮小、フローティングレイアウト、ホームのフッターを修正。
- [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 の登録済みニックネームによる接続に対応し、設定・お気に入り・招待リンクにニックネームの接続先を保持。
<p align="right"><a href="#readme-top">先頭へ ↑</a></p>
+320 -76
View File
@@ -1,90 +1,85 @@
# WebSpeak · Русский
<a id="readme-top"></a>
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
<div align="center">
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
<h1>WebSpeak · Русский</h1>
<p><strong>Ваше сообщество TeamSpeak — прямо в браузере.</strong></p>
<p><a href="../README.md">Главная проекта</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ja.md">日本語</a></p>
<p>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;color=0f766e" alt="Release" /></a>
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
</p>
</div>
## О проекте
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
Последний выпуск: [v0.2.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.7).
Стабильный выпуск: [изменения v0.3.0](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). API v2, плавающие приложения и единое разрешение для экземпляра.
| Логика | Описание |
| --- | --- |
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
[Онлайн-демо](#demo) · [Возможности](#features) · [Скриншоты](#screenshots) · [Развёртывание](#deployment) · [Управление](#administration) · [Расширенные настройки](#advanced) · [Скины и плагины](#extensions) · [Решение проблем](#troubleshooting) · [История изменений](#changelog)
<a id="demo"></a>
## Онлайн-демо
Адрес: <https://webspeak.online>
- [Шанхай · shanghai.webspeak.online](https://shanghai.webspeak.online)
- [Гонконг · webspeak.online](https://webspeak.online)
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
Попробуйте главную страницу и голосовое пространство. Сеть, нагрузка и доступность демонстрационных узлов могут меняться.
## ✨ Возможности
<a id="features"></a>
## Возможности
| Возможность | Описание |
| --- | --- |
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
| Идентичность и доступ | Сохранение идентичности, собственные цели, приглашения с ограничением срока и числа использований, а также импорт, преобразование, проверка и экспорт идентификаторов TeamSpeak 3. |
| Панель администратора | Цели, доступ, публичный адрес медиа, IPv6-кандидаты, голосовой STUN, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
| Структура проекта | В 0.2.6 голосовой шлюз, события сессий, аудио и координация демонстрации разделены на модули; голосовые и административные страницы — на компоненты, composables и сервисы. Добавлены тесты жизненного цикла и переподключения. |
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
| Развёртывание | Пакеты Windows x64 и Linux x64/ARM64, Docker amd64/arm64, Android APK для arm64-v8a, armeabi-v7a и x86_64. |
| Голос | Opus, необязательный WebRTC и резервный WebSocket; отключение микрофона, VOX, выбор устройств, шумоподавление в браузере и громкость участников. |
| Каналы и сообщения | Дерево и разделители каналов TeamSpeak, состояние участников, переходы, чат канала/сервера/личный чат, толчки, шёпот и локальная история. |
| Экран и аудио | Обмен экраном между браузерами и поддерживаемыми нативными клиентами TeamSpeak 6, настройки качества, битрейта и статистика; звук окна или вкладки на компьютере. |
| Идентичность и подключения | Сохранение идентичности, импорт/экспорт TS3, избранное и история, разрешение SRV и Nickname, IPv4/IPv6 и приглашения. |
| Управление экземпляром | Фиксированные или открытые цели, доступ, приглашения, сессии, журналы, диагностика, резервные копии и необязательное управление TeamSpeak. |
| Скины и интерфейс | Дневная, ночная, ILLUSIA и KAAK, пакеты `.wskin` через GitHub, пять языков и адаптивная вёрстка. |
| Распределённый голос | Браузер подключается напрямую к выбранному голосовому ретранслятору, сохраняя URL входного экземпляра. |
| Развёртывание | Docker amd64/arm64, серверные пакеты Windows x64 и Linux x64/ARM64, а также предварительные Android APK. |
## 🖼️ Скриншоты интерфейса
### Совместимость версий TeamSpeak
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
Голосовые соединения используют стандартный клиентский протокол TeamSpeak и не требуют учётных данных Query. Необязательное управление TS использует отдельные данные WebQuery / ServerQuery.
- **TeamSpeak 3**: определение распознаёт ведущую версию `3.x`. Старые версии сервера следует проверять отдельно в конкретной среде: не каждая историческая версия тестировалась независимо.
- **TeamSpeak 6**: поддерживается, включая демонстрацию экрана с нативными клиентами TeamSpeak 6.
- **Автоопределение**: шлюз читает ответ сервера `version` и записывает распознанный протокол в диагностику подключения.
- Шлюз использует upstream SDK `1.0.0-beta.23` [`@honeybbq/teamspeak`](https://github.com/HoneyBBQ/teamspeak-js); WebSpeak рассчитан на TeamSpeak 3 и 6.
<a id="screenshots"></a>
## Скриншоты
![WebSpeak · Голосовое пространство](./screenshots/webspeak-ru.png)
<details>
<summary>Показать главную страницу, настройки аудио и меню участника</summary>
### Главная страница
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
### Голосовое пространство
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
![WebSpeak · Главная страница](./screenshots/webspeak-ru-home.png)
### Настройки аудио
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
![WebSpeak · Настройки аудио](./screenshots/webspeak-ru-audio.png)
### Меню участника
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
![WebSpeak · Меню участника](./screenshots/webspeak-ru-menu.png)
## 🧩 Расширенные функции
</details>
### WebRTC
<a id="deployment"></a>
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
## Развёртывание и первый запуск
### ICE для демонстрации экрана
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
### Кроссплатформенная P2P-трансляция экрана
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
### Ретрансляторы
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
## 🚀 Развертывание
Compose использует `network_mode: host` и рассчитан на Linux-хосты Docker. Для сервера Windows используйте пакет Release.
| Способ | Подходит для |
| --- | --- |
@@ -103,6 +98,19 @@ docker compose up -d
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
```bash
docker compose ps
docker compose logs -f webspeak
```
Обновление с сохранением данных:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
### Пакет Release
Скачайте подходящий пакет `windows-x64.zip`, `linux-x64.tar.gz` или `linux-arm64.tar.gz` из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) и запустите приложенный скрипт. Docker поддерживает amd64/arm64. Также доступны Android APK для `arm64-v8a`, `armeabi-v7a` и `x86_64`; они подписаны отладочным ключом для ручной установки и тестирования, а не для Google Play. Голос TeamSpeak на реальных устройствах пока не проверен.
@@ -110,18 +118,148 @@ docker compose up -d
### Из исходников
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run web:build
npm run build
npm start
```
## ⚠️ Требования и замечания
Для сборки нужны Node.js `>=22.12`, Python, Make и компилятор C/C++.
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
### Первый запуск
1. Откройте `http://<your-host>:3040/admin`.
2. Войдите с `admin` / `admin` и сразу задайте новый пароль длиной не менее 12 символов.
3. В разделе **Сервер** настройте цель, например `voice.example.com#9987`, и режим доступа.
4. Для публичного доступа настройте HTTPS; при включении WebRTC откройте весь указанный диапазон UDP.
### HTTPS и постоянные данные
Публичную страницу и WebSocket следует предоставлять по HTTPS. Например, направьте свой домен на хост и настройте Caddy как обратный прокси:
```caddyfile
webspeak.example.com {
reverse_proxy 127.0.0.1:3040
}
```
Замените домен примера своим. Рабочий обратный прокси или Tunnel не гарантирует доступность UDP-медиа; см. [расширенные настройки](#advanced). Пакеты и исходники используют `data/`, Docker — volume `webspeak-data`. При переносе и резервном копировании сохраняйте вместе `webspeak.db` и соответствующий `master.key`.
<a id="administration"></a>
## Панель администратора
Откройте `/admin` для управления серверами, доступом, WebRTC, ретрансляторами, приглашениями, активными сессиями, журналами и резервными копиями. Магазин скинов: `/admin/skins`; магазин функциональных плагинов: `/admin/plugins`.
### Необязательное управление 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 шлюза.
<a id="advanced"></a>
## Расширенные настройки
### WebRTC
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
### Голосовой WebRTC за обратным прокси или TCP Tunnel
В **Сервер → Расширенные настройки** задайте **публичный адрес медиа**: доступный по UDP IP или домен голосового шлюза без схемы, пути и порта. Он заменяет адрес, определяемый по запросу страницы. Домен прокси не обязательно доступен для медиатрафика.
**IPv6-кандидаты** включаются отдельно и сохраняют IPv4; необходимы маршрутизация IPv6 и правила firewall. В поле **голосовой STUN** можно указать `stun:turn.teamspeak.com:3478`: браузер и шлюз используют один сервис. Пустое поле сохраняет прежнее поведение: встроенный STUN библиотеки шлюза и отсутствие STUN в браузере. Поле принимает доступный по IPv4 UDP STUN с доменом или IPv4, но не IPv6-литералы и не учётные данные TURN.
Сохраните настройки и подключитесь заново. Откройте весь диапазон UDP и сохраняйте номера портов при статическом пробросе. STUN обнаруживает отображения адресов, но не ретранслирует звук. Один TCP Tunnel без доступного UDP/IPv6 не предотвращает переход на совместимый транспорт.
### ICE для демонстрации экрана
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
### Кроссплатформенная P2P-трансляция экрана
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
### Ретрансляторы
Входной шлюз выдаёт подписанный одноразовый билет, после чего браузер подключается прямо к голосовому шлюзу ретранслятора, а тот — к TeamSpeak. URL страницы остаётся прежним. Узел не предоставляет главную страницу и панель администратора.
<details>
<summary>Запуск и настройка ретранслятора</summary>
```bash
docker run -d --name webspeak-relay --restart unless-stopped --network host \
-e WEBSPEAK_MODE=relay \
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
-e WEBSPEAK_RELAY_PORT='39087' \
-e WEBSPEAK_RELAY_WEBRTC_PUBLIC_HOST='relay.example.com' \
ghcr.io/echosixhiya/webspeak:latest
```
Используйте случайный общий токен длиной не менее 16 символов. Голосовой шлюз слушает `127.0.0.1:3041`; направьте на него HTTPS/WSS-домен через Caddy:
```caddyfile
relay.example.com {
reverse_proxy 127.0.0.1:3041
}
```
В **Сервер → Ретрансляторы** входного экземпляра задайте имя, UDP-адрес `relay.example.com#39087`, голосовой адрес `https://relay.example.com` и тот же токен. После сохранения посетитель выбирает прямое подключение или узел. Откройте UDP `39087` и WebRTC `40000–40099`; публичный адрес медиа должен разрешаться непосредственно в доступный ретранслятор, а не в HTTP-прокси.
Для запуска из исходников или пакета задайте те же переменные. После сборки выполните `node dist/index.js`, а в пакете — `./runtime/node ./dist/index.js` (Windows: `.\runtime\node.exe .\dist\index.js`).
</details>
### Зависимости
Ретранслятор встроен в WebSpeak и использует стандартные библиотеки Node.js. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`. TeamSpeak использует upstream [HoneyBBQ/teamspeak-js](https://github.com/HoneyBBQ/teamspeak-js), пакет `@honeybbq/teamspeak@1.0.0-beta.23`; сборка форка не нужна.
<a id="extensions"></a>
## Скины и функциональные плагины
### Пакеты скинов `.wskin`
Скины задают оформление, компоновку и связанные виджеты. Администратор устанавливает, включает и выбирает скин по умолчанию. Авторы используют публичный интерфейс без изменения исходников WebSpeak.
[Руководство](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [Каталог скинов](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Пример Discord Voice](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
### Функциональные плагины `.wplugin`
Функциональные плагины — самостоятельные приложения с API браузера, необязательными сервисами Node, своими маршрутами, данными и совместной работой. Администратор проверяет код и зависимости перед включением; обновления требуют повторного доверия. Приложения работают на отдельном источнике в области TS-сервера или экземпляра. API v2 доступен начиная с v0.3.0.
[Руководство](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [Каталог распространения и пример](https://github.com/Huddle-Up-Forge/webspeak-plugin)
<a id="troubleshooting"></a>
## Решение проблем
| Проблема | Что проверить |
| --- | --- |
| WebRTC включён, но используется резервный транспорт | Код ошибки голосового статуса, HTTPS, весь диапазон UDP и публичный адрес медиа. TCP Tunnel не переносит этот UDP-трафик. |
| Цель заблокирована как локальный адрес | Открытый режим ограничивает loopback и частные адреса. Для TS на том же хосте используйте настроенный администратором режим фиксированного сервера. |
| Тайм-аут или чёрный экран трансляции | Экран использует отдельное WebRTC-соединение. Проверьте согласование, ICE и кодек в статистике трансляции; работающий голос не подтверждает доступность видео. |
| После обновления нет данных или они не расшифровываются | Используйте прежний каталог/volume и соответствующий `master.key`. Не обновляйте через `docker compose down -v`. |
### ⚠️ Требования и замечания
- Node.js `>=22.12` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
@@ -129,16 +267,83 @@ npm start
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
- Фоновая музыка доступна только на компьютере и требует WebRTC.
## Сообщество и проекты
- WebRTC использует UDP `40000–40099` по умолчанию; откройте весь диапазон. Для смены диапазона сначала выключите WebRTC и сохраните.
- Лимит приложения — 100 активных браузерных сессий на экземпляр; это не гарантия производительности и не лимит лицензии TS.
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
<a id="changelog"></a>
## 🧾 История изменений
## История изменений
<a id="latest-release-notes"></a>
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### Приложения-плагины
- Выпущен API v2 для самостоятельных браузерных приложений и необязательных Node-бэкендов со своими маршрутами, состоянием, обменом данными и логикой.
- Установка через магазин GitHub или локальные `.wplugin`. Администратор проверяет приложения, задаёт публичные/закрытые настройки и включает их; обновление требует повторного подтверждения доверия.
- Добавлены независимые от темы плавающий вход и библиотека приложений. Окна можно перемещать, изменять в размере, сворачивать и разворачивать; сворачивание и возврат в библиотеку не перезагружают приложение.
- Добавлены шаблон, руководство и Agent Skill. P2P-передача файлов и совместный просмотр видео распространяются в отдельных репозиториях.
#### Темы и разрешение
- При первом входе запрашивается единое разрешение для сторонних тем и плагинов экземпляра, без учётных данных подключения. Последний пункт меню тем позволяет изменить решение.
- Без согласия доступны только дневная, ночная и ILLUSIA; KAAK, другие сторонние темы и вход в плагины скрыты. Отзыв разрешения возвращает встроенную тему, отменяет загрузки и останавливает связанные компоненты и страницы приложений.
- Сохраняются права манифеста, фильтрация данных, проверка хешей и действий хоста. Проверка и доверие администратора остаются отдельными.
#### Исправления и обновления
- Исправлено отсутствие ответа нативного TS-клиента на offer только с видео при показе окна, всего экрана или без звука. Добавляется необходимая аудиосекция без захвата микрофона и создания звука. Пользователь подтвердил изображение при показе окна и экрана.
- SDK обновлён до `@honeybbq/teamspeak@1.0.0-beta.23`; учтены необязательные поля участников и пустые пакеты конца речи.
- Включены исправления TSDNS, повторов Query при ограничении частоты, передачи файлов и завершения соединений из upstream.
- Включены исправления проверки IPv6-целей, параллельных входов, отзыва сеансов после смены пароля, ограничений через доверенные прокси и защиты PCM-входа.
- Сохранено исправление первой загрузки темы с фактической версией сборки. Версии приложения для настольных платформ, веба и Android согласованы.
#### Обновление
- API v2 несовместим с пакетами v1. Обновите приложения, проверьте и включите их заново.
- Для публичных плагинов нужен отдельный HTTPS-origin, настроенный в панели администратора и направленный на порт среды выполнения (по умолчанию `3042`). Основной сайт и приложения не должны использовать один origin.
- Пользователю нужно заново выбрать разрешение для экземпляра; старые разрешения отдельных тем не считаются согласием.
### [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 не означает исправления описанных проблем.
<details>
<summary>Показать v0.2.8 и более ранние версии</summary>
### [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
#### Более открытая система скинов
@@ -195,14 +400,53 @@ npm start
Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг.
### [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) · 2026-09-06
Добавлены немецкий язык, Telegram, панель сетевой статистики и общая громкость; исправлены колебания громкости фоновой музыки.
### [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) · 2026-09-04
Добавлены передача звука окна/вкладки, напоминание о сохранении идентичности и значок сайта; исправлена индивидуальная громкость в WebRTC.
### [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) · 2026-09-04
Исправлено сохранение идентичности и улучшено переключение тем.
### [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) · 2026-09-03
Исправлены WebRTC и чат канала, улучшены панель управления, журналы и мобильная компоновка.
### [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) · 2026-09-03
Добавлен встроенный WebRTC, заменён TeamSpeak SDK, улучшены синхронизация участников и буферизация голоса.
</details>
<a id="contributors"></a>
## Участники и вклад в проект
<details>
<summary>Показать авторов SDK и вклад через PR</summary>
Список отмечает автора SDK, используемого в основе проекта, вклад через объединённые PR на GitHub и исходные работы, перенесённые в отдельно распространяемые пакеты скинов.
- [HoneyBBQ](https://github.com/HoneyBBQ) — Автор SDK [teamspeak-js (`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js), который предоставляет используемый WebSpeak клиент протокола TeamSpeak.
- [ph1gros](https://github.com/ph1gros) — В [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) сообщил о проблемах безопасности и предложил исправления с регрессионными тестами для проверки IPv6, входа и сессий администратора, лимитов за прокси и PCM-аудио. Исходный патч не объединён напрямую; исправления реализованы заново в `dev`.
- [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 с сохранением имени цели; [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).
</details>
## Сообщество и проекты
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ-группа 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот TeamSpeak с поддержкой разных платформ и веб-консолью.
## Лицензия
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
WebSpeak распространяется по [AGPL-3.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) исправил масштабирование, плавающую компоновку и нижний колонтитул главной страницы.
- [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 и сохранение имени цели в настройках, избранном и приглашениях.
<p align="right"><a href="#readme-top">Наверх ↑</a></p>
+311 -121
View File
@@ -1,64 +1,182 @@
# WebSpeak · 简体中文
<a id="readme-top"></a>
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
<div align="center">
<img src="./assets/webspeak-logo.png" alt="WebSpeak" width="88" />
<h1>WebSpeak · 简体中文</h1>
<p><strong>打开浏览器,就能加入你的 TeamSpeak。</strong></p>
<p><a href="../README.md">项目首页</a> · <a href="./README.en.md">English</a> · <a href="./README.de.md">Deutsch</a> · <a href="./README.ru.md">Русский</a> · <a href="./README.ja.md">日本語</a></p>
<p>
<a href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest"><img src="https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&amp;color=0f766e" alt="Release" /></a>
<a href="../LICENSE"><img src="https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square" alt="AGPL-3.0-only" /></a>
</p>
</div>
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
皮肤开发请从[当前皮肤开发指南](./SKIN_DEVELOPMENT.md)开始。它整合 `.wskin` 包格式、当前运行时接口、权限边界和制作验收流程。Agent 工作流见[WebSpeak Skin Development Skill](../.agents/skills/webspeak-skin-development/SKILL.md)。
稳定版:[v0.3.0 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)。包含功能插件 API v2、悬浮应用界面和实例统一授权。
## 在线 Demo
地址:<https://webspeak.online>
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
[在线演示](#demo) · [功能](#features) · [界面预览](#screenshots) · [部署](#deployment) · [管理](#administration) · [高级配置](#advanced) · [皮肤与插件](#extensions) · [常见问题](#troubleshooting) · [更新日志](#changelog)
最新版本:[查看本页的 0.2.7 更新日志](#latest-release-notes)。
<a id="demo"></a>
## ✨ 特性
## 在线演示
- [上海 · shanghai.webspeak.online](https://shanghai.webspeak.online)
- [香港 · webspeak.online](https://webspeak.online)
可直接体验欢迎页与语音工作区。演示节点的网络、负载和可用性会变化。
<a id="features"></a>
## 主要功能
| 能力 | 说明 |
| --- | --- |
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
| 身份与访问 | 支持身份保持、访客自定义目标、可撤销/可过期邀请链接,以及 TeamSpeak 3 身份导入、转换、校验与导出。 |
| 工程结构 | 0.2.6 将网关语音、会话事件、音频和屏幕共享拆分为独立模块;前端语音与管理页拆分为组件、composables 和服务,并补充生命周期与重连测试。 |
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
| 实时语音 | Opus 音频、可选 WebRTC、兼容 WebSocket 回退;支持闭麦、VOX、设备选择、浏览器降噪和成员独立音量。 |
| 频道与消息 | 频道树、TeamSpeak 频道分隔栏、成员状态、频道切换、频道/服务器/私聊消息、戳一戳、耳语及本地聊天历史。 |
| 屏幕与音频共享 | 浏览器之间及与受支持的 TeamSpeak 6 原生客户端共享屏幕;提供采集质量、码率和统计面板,桌面端还可分享窗口或标签页音频。 |
| 身份与连接 | 身份保持、TS3 身份导入/导出、收藏和历史连接、SRV 与 Nickname 地址解析、IPv4/IPv6 及邀请链接。 |
| 实例管理 | 固定或公开目标、访问策略、邀请、会话、日志、诊断、备份及可选的 TeamSpeak 管理连接。 |
| 皮肤与界面 | 日间、夜间、ILLUSIA 和 KAAK;可通过 GitHub 皮肤商店管理 `.wskin` 包,支持五种语言和响应式布局。 |
| 分布式语音 | 配置中继后,浏览器直接连接所选中继的语音网关,网页地址仍保留在入口实例。 |
| 部署方式 | Docker amd64/arm64、Windows x64 与 Linux x64/ARM64 发布包;另有 Android 预览 APK。 |
## 🖼️ 界面截图
### 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.0-beta.23` SDK;WebSpeak 面向 TeamSpeak 3 和 TeamSpeak 6。
<a id="screenshots"></a>
## 界面预览
![WebSpeak · 语音工作区](./screenshots/webspeak-zh.png)
<details>
<summary>展开欢迎页、音频设置与成员菜单</summary>
### 欢迎页
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
![WebSpeak · 欢迎页](./screenshots/webspeak-zh-home.png)
### 语音工作区
### 音频设置
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
### 音量控制
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
![WebSpeak · 音频设置](./screenshots/webspeak-zh-audio.png)
### 成员菜单
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
![WebSpeak · 成员菜单](./screenshots/webspeak-zh-menu.png)
## 🧩 高级功能
</details>
<a id="deployment"></a>
## 部署与首次配置
以下 Compose 配置使用 `network_mode: host`,适用于 Linux Docker 主机。Windows 服务端可使用发布包。
| 方案 | 适用场景 | 环境 |
| --- | --- | --- |
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
| 源码运行 | 开发、调试和二次开发 | Node.js 22.12+、Git 和本地编译工具 |
### Docker Compose(推荐)
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
```bash
docker compose ps
docker compose logs -f webspeak
```
升级:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
### 发布包
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
### 源码运行
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
### 首次配置
1. 打开 `http://<你的主机>:3040/admin`。
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
### HTTPS 与持久化
公网部署应通过 HTTPS 提供网页和 WebSocket。例如,将已解析到主机的域名配置到 Caddy,反向代理到 WebSpeak:
```caddyfile
webspeak.example.com {
reverse_proxy 127.0.0.1:3040
}
```
以上域名仅为配置示例,请替换成自己的域名。网页能通过反向代理或 Tunnel 打开,并不表示 WebRTC 的 UDP 媒体可达;相关配置见[高级配置](#advanced)。发布包和源码的数据默认位于 `data/`,Docker 位于 `webspeak-data` volume;备份和迁移时同时保留 `webspeak.db` 与 `master.key`。
<a id="administration"></a>
## 管理员控制台
实例配置位于 `/admin`:管理服务器与访问策略、WebRTC 与中继、邀请、活动会话、运行日志和备份。皮肤商店位于 `/admin/skins`;功能插件商店位于 `/admin/plugins`。
### 可选的 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 的其他用户。
<a id="advanced"></a>
## 高级配置
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
### 1. WebRTC 低延迟语音
### WebRTC 低延迟语音
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
@@ -93,11 +211,14 @@ WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
### 2. 中继模式
### 中继模式
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
中继实例同时运行 UDP 兼容转发和独立语音网关,不提供访客首页或管理员后台。网关收到用户的入场请求后,会用共享令牌签名并转交一次性语音票据;浏览器随后直接连接中继节点,语音网关再从中继节点连接 TeamSpeak。网页地址仍保持在入口网关,不需要跳转。令牌至少使用 16 个字符的随机值。
<details>
<summary>展开中继启动与配置示例</summary>
#### 源码启动
@@ -105,7 +226,7 @@ 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 rebuild @discordjs/opus --foreground-scripts
npm run build
WEBSPEAK_MODE=relay \
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
@@ -151,24 +272,147 @@ 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. 访客欢迎页即可选择直连或其中一个中继。
关闭并保存中继配置后,访客页面不会显示中继选项。
### 3. 依赖与归属
</details>
### 依赖与归属
- 中继服务是 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.23`,无需构建项目 SDK fork。
## 🧾 更新日志
<a id="extensions"></a>
## 皮肤与功能插件
### 皮肤包 `.wskin`
皮肤包负责外观、布局及其附属小组件。管理员可安装、启用和设置默认皮肤;开发时遵循公开接口,无需修改 WebSpeak 源码。
[开发指南](./SKIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-skin-development/SKILL.md) · [皮肤索引仓库](https://github.com/Huddle-Up-Forge/webspeak-skins) · [Discord Voice 示例](https://github.com/Huddle-Up-Forge/webspeak-skin-discord-voice)
### 功能插件 `.wplugin`
功能插件是独立应用,使用标准浏览器能力和可选 Node 后端,自行实现路由、状态与协作。管理员审核代码和依赖后启用;更新须重新信任。支持 TS 服务器或实例范围,运行于独立源。v0.3.0 起提供 API v2。
[开发指南](./PLUGIN_DEVELOPMENT.md) · [Agent Skill](../.agents/skills/webspeak-plugin-development/SKILL.md) · [分发索引与示例](https://github.com/Huddle-Up-Forge/webspeak-plugin)
<a id="troubleshooting"></a>
## 常见问题
| 现象 | 检查方向 |
| --- | --- |
| WebRTC 启用后仍回退 | 检查语音状态中的错误代码、HTTPS、整段 UDP 防火墙规则和公网媒体地址。TCP Tunnel 不能转发这条 UDP 媒体路径。 |
| 连接目标被本地地址保护拦截 | 公开模式限制回环和私网目标。连接同机 TS 时使用管理员配置的固定服务器模式;面向访客的目标应填实际可访问的地址。 |
| 屏幕共享超时或黑屏 | 屏幕共享使用独立的 WebRTC 连接;检查共享统计中的协商、ICE 和编码信息。语音 WebRTC 已连接不代表屏幕媒体可达。 |
| 升级后数据丢失或无法解密 | 复用原数据目录或 volume,并保留匹配的 `master.key`;不要用 `docker compose down -v` 升级。 |
### ⚠️ 要求和注意事项
| 项目 | 要求或注意事项 |
| --- | --- |
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
| 会话上限 | 单实例最多允许 100 个活动网页会话;这是应用准入上限,不是性能保证或 TS 许可证额度。 |
<a id="changelog"></a>
## 更新日志
<a id="latest-release-notes"></a>
### [v0.3.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.0) · 2026-11-03
#### 插件系统
- 发布功能插件 API v2:支持独立浏览器应用和可选 Node 后端,作者可自行实现路由、状态、通信和业务逻辑。
- 管理员可通过 GitHub 插件商店或本地 `.wplugin` 包安装应用,配置公开/私密设置并审核启用;更新后需要重新信任。
- 新增独立于皮肤的悬浮入口和应用库。插件窗口支持拖动、调整大小、最小化、最大化与还原,最小化或返回应用库不会重载当前应用。
- 提供应用模板、插件开发指南与 Agent Skill;P2P 文件传输和视频同看通过独立仓库分发。
#### 皮肤与授权
- 首次进入时统一确认当前实例第三方皮肤与插件的授权,不包含连接凭据;皮肤菜单末尾增加“授权”,可随时更改。
- 未同意时仅显示日间、夜间、ILLUSIA 三款官方皮肤,隐藏 KAAK 等其他皮肤及插件入口。撤回后切回内置皮肤、取消待完成加载并停止相关组件和插件页面。
- 保留皮肤清单权限、数据投影、文件摘要及宿主动作校验,管理员的应用审核与信任设置仍独立生效。
#### 修复与升级
- 修复窗口、整个屏幕及关闭共享音频时,TS 原生客户端不应答纯视频 offer 的问题:补充必要的音频协商段,不采集麦克风,也不伪造共享声音。窗口与全屏已由用户复测出画面。
- SDK 升级至 `@honeybbq/teamspeak@1.0.0-beta.23`,适配可选成员字段,并跳过代表说话结束的空音频数据包。
- 纳入上游 TSDNS 解析、查询限流重试、文件传输及断开连接清理等修复。
- 纳入 IPv6 目标校验、并发登录限制、改密后的会话撤销、可信代理限流与 PCM 上行保护修复。
- 保留并验证皮肤首次加载使用真实构建版本的修复,统一桌面、网页及 Android 的应用版本号。
#### 升级说明
- 插件 API v2 不兼容旧 API v1 应用包,请更新插件后重新审核并启用。
- 公网使用功能插件时,需要在管理员面板配置独立的 HTTPS 应用源并代理运行端口(默认 `3042`);主站与应用不能使用同一个源。
- 本次统一授权需要用户重新选择,旧的逐皮肤授权记录不会自动视为同意。
### [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 不代表相关问题已修复。
<details>
<summary>展开 v0.2.8 及更早版本</summary>
### [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
#### 更开放的皮肤系统
@@ -245,87 +489,33 @@ docker run -d --name webspeak-relay --restart unless-stopped --network host \
引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。
</details>
## 🚀 部署方案
<a id="contributors"></a>
| 方案 | 适用场景 | 环境 |
| --- | --- | --- |
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
## 贡献者与贡献来源
### Docker Compose(推荐)
<details>
<summary>查看上游作者与 PR 贡献说明</summary>
```bash
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
以下列出上游 SDK 作者、已合并的 GitHub PR,以及已移植为独立皮肤包的原始贡献。
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
```bash
docker compose ps
docker compose logs -f webspeak
```
升级:
```bash
git pull --ff-only
docker compose pull
docker compose up -d
```
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
### 发布包
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
### 源码运行
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
npm ci --ignore-scripts
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts
npm --prefix web ci
npm --prefix web run build
npm run build
npm start
```
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
### 首次配置
1. 打开 `http://<你的主机>:3040/admin`。
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
## ⚠️ 要求和注意事项
| 项目 | 要求或注意事项 |
| --- | --- |
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
## 近期合并贡献者
- 以下依据 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) 修正缩放、浮动布局和首页脚注。
- [HoneyBBQ](https://github.com/HoneyBBQ) — 上游 [teamspeak-js(`@honeybbq/teamspeak`)](https://github.com/HoneyBBQ/teamspeak-js) SDK 的作者,为 WebSpeak 提供底层 TeamSpeak 协议客户端能力。
- [ph1gros](https://github.com/ph1gros) — [PR #48](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/48) 提供公开目标 IPv6 校验、管理员认证与会话、代理限流及 PCM 上行边界的安全审查、补丁和回归测试;原补丁未直接合并,相关修复已在 `dev` 中重新实现。
- [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)。
</details>
## 社区与相关项目
[GitHub Issues](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues) · [QQ 群 869500475](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475) · [Telegram](https://t.me/+8qShpTcuN9A3MWY9)
[NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot):支持多平台点歌和 Web 控制台的 TeamSpeak 音乐机器人。
## 许可证
WebSpeak 按 [AGPL-3.0-only](../LICENSE) 发布。第三方依赖的许可与归属见各自项目。
<p align="right"><a href="#readme-top">返回顶部 ↑</a></p>
+68 -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.3.0 的唯一皮肤开发说明,整合原皮肤开发规范与开放皮肤系统规格。它覆盖仍受支持的 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",
@@ -464,3 +522,11 @@ CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删
自绘成员列表时,`session.members` 可读取 `screenSharing` 与 `screenShareStreamId`;这两个成员字段和 `screenShare.streams` 一样要求 `voice.screenShare.read`。用 `member.screenSharing` 显示共享标记,再将 `member.screenShareStreamId` 绑定到 `voice.joinScreenShare`(还需 `voice.screenShare.control`)即可让用户观看。未声明/未获共享读取权限的皮肤不会收到这两个字段;整页替换皮肤仍须在自己的成员列表中绘制标记或观看入口。
\n
## 实例级用户授权(v0.3.0)
用户首次访问公开页面时,由宿主统一询问是否允许当前实例的第三方皮肤和功能插件使用已公开的频道/成员/聊天等上下文;不包含连接凭据。不再逐个皮肤弹窗确认。选择按浏览器源(协议、域名、端口)保存,旧版本的逐包授权记录不会自动替代这次选择。管理员对应用的审核与信任仍单独保留。
未作选择或拒绝时,仅可使用固定三款官方皮肤:`builtin.light`、`builtin.dark`、`community.illusia-voice`;KAAK 即使随包分发也不在免授权名单中,其他第三方皮肤及功能插件入口隐藏。缓存、直接激活、进行中的加载也必须经过同一授权检查,不能仅过滤菜单。皮肤菜单末尾的“授权”可以随时修改选择。撤回时立即退回内置皮肤、停止第三方皮肤组件/worker,并关闭与撤销当前功能应用会话;服务端由管理员启用的后台应用不因此停机。
清单权限、数据投影、宿主动作校验和 Wasm 文件摘要校验继续保留,统一授权不是扩大皮肤 API 的理由。作者不应再自行增加重复授权弹窗。原文中的逐包授权记录与 SHA-256 绑定描述指内部校验记录,其创建必须在实例授权允许之后(或固定官方皮肤之内)。
File renamed without changes.
File renamed without changes.
File renamed without changes.
+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; }
}
+3
View File
@@ -0,0 +1,3 @@
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Application starter</title><link rel="stylesheet" href="./style.css"><script type="module" src="./main.js"></script></head>
<body><main><span class="eyebrow">WEBSPEAK · APPLICATION RUNTIME 2</span><h1 id="title"></h1><p id="intro"></p><section><div class="status"><i></i><span id="status"></span></div><dl><div><dt id="user-label"></dt><dd id="user"></dd></div><div><dt id="scope-label"></dt><dd id="scope"></dd></div></dl><button id="request" type="button"></button><output id="result" aria-live="polite"></output></section></main></body></html>
+12
View File
@@ -0,0 +1,12 @@
const host=window.webspeak;
let context=await host.ready;
const copy={
en:['Your application starts here','Standard browser APIs, your own routes and an optional Node backend.','Connected application context','Participant','Scope','Call my backend','Persisted requests','Frontend only'],
zh:['从这里构建你的应用','使用标准浏览器 API、自定义路由和可选的 Node 后端。','应用上下文已连接','参与者','作用域','调用自己的后端','已保存的请求次数','仅前端模式'],
de:['Hier beginnt deine Anwendung','Browser-APIs, eigene Routen und ein optionales Node-Backend.','Anwendungskontext verbunden','Teilnehmer','Bereich','Backend aufrufen','Gespeicherte Anfragen','Nur Frontend'],
ru:['Начните своё приложение здесь','API браузера, собственные маршруты и необязательный сервис Node.','Контекст приложения подключён','Участник','Область','Вызвать свой сервис','Сохранённые запросы','Только браузер'],
ja:['ここからアプリを作成','標準ブラウザー API、独自ルート、任意の Node バックエンド。','アプリの接続情報を取得済み','参加者','範囲','バックエンドを呼び出す','保存したリクエスト数','フロントエンドのみ']};
const element=id=>document.getElementById(id);
function render(){const t=copy[context.language]??copy.en;for(const [id,index]of [['title',0],['intro',1],['status',2],['user-label',3],['scope-label',4],['request',5]])element(id).textContent=t[index];element('user').textContent=context.self.nickname;element('scope').textContent=context.scope.type;element('request').disabled=!context.serverUrl;if(!context.serverUrl)element('result').textContent=t[7];}
host.onContextChange(next=>{context=next;render();});render();
element('request').addEventListener('click',async()=>{element('request').disabled=true;try{const response=await fetch(context.serverUrl+'/my-counter',{method:'POST',signal:host.signal});if(!response.ok)throw new Error(String(response.status));const result=await response.json();element('result').textContent=(copy[context.language]??copy.en)[6]+': '+result.count;}catch(error){element('result').textContent=error.message;}finally{element('request').disabled=!context.serverUrl;}});
+1
View File
@@ -0,0 +1 @@
:root{color-scheme:light;--bg:#f1f5f4;--surface:#fff;--text:#183d39;--muted:#5b7671;--border:#d4e3df;--accent:#126b60;--soft:#e8f4ef}html[data-theme=dark]{color-scheme:dark;--bg:#161c21;--surface:#202a30;--text:#e4efec;--muted:#9eb6b0;--border:#37474c;--accent:#8ee2be;--soft:#293e37}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.6 system-ui,sans-serif}main{max-width:800px;margin:0 auto;padding:clamp(24px,6vw,64px)}.eyebrow{color:var(--accent);font-size:11px;font-weight:750;letter-spacing:.14em}h1{font-size:clamp(25px,4vw,38px);letter-spacing:-.04em;line-height:1.2;margin:20px 0 14px}p{color:var(--muted);max-width:550px}section{margin-top:30px;padding:26px;border:1px solid var(--border);border-radius:18px;background:var(--surface)}.status{display:flex;align-items:center;gap:9px;font-size:12px;color:var(--accent)}.status i{width:8px;height:8px;border-radius:50%;background:var(--accent)}dl{display:flex;gap:32px;flex-wrap:wrap;margin:22px 0 30px}dt{font-size:12px;color:var(--muted)}dd{margin:4px 0 0;font-weight:650;overflow-wrap:anywhere}button{font:600 14px system-ui;padding:12px 18px;border-radius:10px;border:1px solid var(--border);color:var(--accent);background:var(--soft);cursor:pointer}button:disabled{opacity:.5;cursor:default}output{display:block;margin-top:16px;color:var(--muted);font-size:13px}
+19
View File
@@ -0,0 +1,19 @@
{
"apiVersion": 2,
"id": "community.application-starter",
"name": "Application starter",
"version": "1.0.0",
"author": "Your community",
"license": "AGPL-3.0-only",
"description": "A starting point for an independent browser application and optional Node service.",
"scopes": [
"server",
"instance"
],
"client": {
"entry": "client/index.html"
},
"server": {
"entry": "server/main.mjs"
}
}
+19
View File
@@ -0,0 +1,19 @@
import { readFile, writeFile, rename } from 'node:fs/promises';
import path from 'node:path';
// Ordinary trusted Node code: use your own modules, network clients and routes.
export default async function activate({ dataDir, signal }) {
const filename=path.join(dataDir,'counter.json');
let count=JSON.parse(await readFile(filename,'utf8').catch(()=> '0'));
let writes=Promise.resolve();
return {
async handle(request,response) {
if(request.method!=='POST'||new URL(request.url,'http://app.local').pathname!=='/my-counter'){response.writeHead(404);response.end();return;}
// req.webspeak is host-authenticated context; it is not supplied by the browser.
writes=writes.then(async()=>{count++;await writeFile(filename+'.tmp',JSON.stringify(count));await rename(filename+'.tmp',filename);});
try{await writes;response.setHeader('content-type','application/json');response.end(JSON.stringify({count,participant:request.webspeak.self.id}));}
catch{response.writeHead(500);response.end();}
},
async stop(){await writes.catch(()=>undefined);}
};
}
+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.
+23 -15
View File
@@ -1,14 +1,14 @@
{
"name": "webspeak-android-gateway",
"version": "0.0.0",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-android-gateway",
"version": "0.0.0",
"version": "0.3.0",
"dependencies": {
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
"@honeybbq/teamspeak": "1.0.0-beta.23",
"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.23",
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.23.tgz",
"integrity": "sha512-Y0fV4NOdvaU3Df4231XZkFOfSgm7G4xN50x5hglxVV+HtYlxx5sS+G3vAF0rvOcW80qUy20nfnD/Sxx+JgQ1TA==",
"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",
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "webspeak-android-gateway",
"version": "0.0.0",
"version": "0.3.0",
"private": true,
"type": "module",
"main": "index.cjs",
"dependencies": {
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
"@honeybbq/teamspeak": "1.0.0-beta.23",
"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.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "webspeak-webclient",
"version": "0.2.7",
"version": "0.3.0",
"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.23",
"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.23",
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.23.tgz",
"integrity": "sha512-Y0fV4NOdvaU3Df4231XZkFOfSgm7G4xN50x5hglxVV+HtYlxx5sS+G3vAF0rvOcW80qUy20nfnD/Sxx+JgQ1TA==",
"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",
+52 -51
View File
@@ -1,55 +1,56 @@
{
"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.3.0",
"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 src/admin/security-boundaries.test.ts src/domain/teamspeak-target.test.ts 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 src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.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",
"plugin:build": "node scripts/build-plugin.mjs"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@honeybbq/teamspeak": "1.0.0-beta.23",
"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 握手和断开:
+62 -30
View File
@@ -1,44 +1,73 @@
import { createSocket } from "node:dgram";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
import { BlockList, isIP, SocketAddress } from "node:net";
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
function endpointKey(address, port) {
return `${address}/${port}`;
}
function isPrivateAddress(host) {
const family = isIP(host);
if (family === 4) {
const octets = host.split(".").map(Number);
return octets[0] === 10
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|| octets[0] === 192 && octets[1] === 168
|| octets[0] === 127
|| octets[0] === 169 && octets[1] === 254
|| octets[0] === 0;
/**
* 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.
*/
const restrictedIpv6 = new BlockList();
for (const [network, prefix] of [
["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
["fec0::", 10], ["ff00::", 8],
]) restrictedIpv6.addSubnet(network, prefix, "ipv6");
export function isRestrictedAddress(host) {
if (host.includes("%")) return true;
const version = isIP(host);
if (version === 4) return isRestrictedIpv4(host);
if (version !== 6) return true;
const normalized = new SocketAddress({ address: host, family: "ipv6" }).address;
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");
return restrictedIpv6.check(normalized, "ipv6");
}
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 +100,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 +116,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,110 @@
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],
["0:0:0:0:0:ffff:808:808", false],
["2001:4860:0:0:0:0:0:8888", false],
["0:0:0:0:0:0:0:1", true],
["0::1", true],
["0:1234::1", true],
["0:0:0:0:0:0:0:0", true],
["::ffff:7f00:1", true],
["0::ffff:a00:1", true],
["::127.0.0.1", true],
["fe80::1%eth0", true],
["64:ff9b::808:808", true],
["64:ff9b:1:1234::1", true],
["64:ff9b:2::1", false],
["100::1", true],
["100:0:0:1::1", true],
["100:0:1::1", false],
["2001:0::1", true],
["2002:808:808::1", true],
["2001:0db8::1", true],
["2001:db9::1", false],
["3fff:fff::1", true],
["3fff:1000::1", 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`);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
const [input, output] = process.argv.slice(2);
if (!input || !output) throw new Error('Usage: node scripts/build-plugin.mjs APPLICATION_DIR OUTPUT.wplugin');
const root=path.resolve(input),manifest=JSON.parse(await readFile(path.join(root,'manifest.json'),'utf8'));
if(manifest.apiVersion!==2||manifest.permissions!==undefined)throw new Error('Application runtime v2 manifest required');
const validPath=value=>typeof value==='string'&&value.length<=500&&value.split('/').every(s=>/^[A-Za-z0-9._@+~-]+$/.test(s)&&!['.','..'].includes(s)&&!s.endsWith('.')&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(s));
const files=Object.create(null);let total=0;
async function collect(directory){
for(const entry of(await readdir(path.join(root,directory),{withFileTypes:true})).sort((a,b)=>a.name<b.name?-1:1)){
const name=directory+'/'+entry.name;if(!validPath(name)||entry.isSymbolicLink())throw new Error('Invalid package path: '+name);
if(entry.isDirectory())await collect(name);
else if(entry.isFile()){
const bytes=await readFile(path.join(root,name));total+=bytes.length;
if(bytes.length>16*1024*1024||total>32*1024*1024||Object.keys(files).length>=4096)throw new Error('Package size limit');
try{files[name]={encoding:'utf8',data:new TextDecoder('utf-8',{fatal:true}).decode(bytes)};}
catch{files[name]={encoding:'base64',data:bytes.toString('base64')};}
}else throw new Error('Only ordinary files are supported: '+name);
}
}
await collect('client');if(manifest.server)await collect('server');
if(!validPath(manifest.client?.entry)||!manifest.client.entry.startsWith('client/')||files[manifest.client.entry]?.encoding!=='utf8')throw new Error('Missing HTML client entry');
if(manifest.server&&(!validPath(manifest.server.entry)||!manifest.server.entry.startsWith('server/')||files[manifest.server.entry]?.encoding!=='utf8'))throw new Error('Missing bundled server entry');
const bytes=JSON.stringify({manifest,files});if(Buffer.byteLength(bytes)>48*1024*1024)throw new Error('Package size limit');
await writeFile(output,bytes);console.log(`${manifest.id} v${manifest.version} -> ${output}`);
+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";
}
}
+123 -16
View File
@@ -1,12 +1,17 @@
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";
import { createPluginAdminRouter } from "../plugins/admin-router.js";
import type { PluginRegistry } from "../plugins/registry.js";
import type { PluginStore } from "../plugins/store.js";
import type { PluginRuntime } from "../plugins/runtime.js";
export interface AdminConnectionRecord {
id: string;
@@ -36,13 +41,33 @@ export interface AdminRouterOptions {
version?: string;
logFile?: string;
skinRegistry?: SkinRegistry;
skinStore?: SkinStore;
pluginRegistry?: PluginRegistry;
pluginStore?: PluginStore;
pluginRuntime?: PluginRuntime;
startedAt: number;
clientIp?: (request: Request) => string;
}
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");
@@ -68,25 +93,29 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
const peer = request.socket.remoteAddress ?? "unknown";
const retryAfterMs = limiter.retryAfterMs(peer);
if (retryAfterMs > 0) {
response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
return;
}
const peer = options.clientIp?.(request) ?? request.socket.remoteAddress ?? "unknown";
const body = asRecord(request.body);
const username = readString(body, "username", 64).trim();
const password = readOptionalString(body, "password", 1024);
if (!await options.service.verifyPassword(username, password)) {
const delayMs = limiter.recordFailure(peer);
const reservation = limiter.reserve(peer);
if (!reservation.allowed) {
response.setHeader("Retry-After", String(Math.ceil(reservation.retryAfterMs / 1000)));
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs: reservation.retryAfterMs });
return;
}
const revision = options.service.credentialRevision;
let verified: boolean;
try { verified = await options.service.verifyPassword(username, password); }
catch (error) { reservation.finish("cancelled"); sendAdminError(response, error); return; }
if (!verified || revision !== options.service.credentialRevision) {
const delayMs = reservation.finish("failure");
await waitFor(delayMs);
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
logger.warn("Administrator login failed");
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
return;
}
limiter.recordSuccess(peer);
reservation.finish("success");
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
const session = options.sessions.create(response, isSecureRequest(request));
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
@@ -96,6 +125,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
try {
const body = asRecord(request.body);
await options.service.changePassword(readString(body, "newPassword", 1024));
options.sessions.revokeOthers(request);
response.json({ ok: true, mustChangePassword: false });
} catch (error: unknown) {
sendAdminError(response, error);
@@ -109,6 +139,10 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
});
router.use(requireAdmin(options.sessions, options.service));
router.use("/plugins", createPluginAdminRouter({ registry: options.pluginRegistry, store: options.pluginStore, runtime: options.pluginRuntime,
protect: [requireSameOrigin, requireCsrf(options.sessions)],
audit: (event, data) => options.service.database.addAudit(event, data),
}));
router.get("/overview", (_request, response) => {
response.json(options.service.getOverview(
@@ -122,6 +156,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 +189,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 +230,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 +248,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 +265,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 +530,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 +564,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";
}
@@ -702,7 +809,7 @@ function logLevelName(level: unknown): string {
function sendAdminError(response: Response, error: unknown): void {
if (error instanceof AdminInputError) {
response.status(400).json({ ok: false, code: error.code });
response.status(error.code === "AUTH_REQUIRED" ? 401 : 400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
+56 -13
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,9 @@ export interface ManagedInviteView {
type ProbeFunction = typeof probeTeamSpeak;
export class AdminService {
private readonly tsAdmin: TsAdminService;
private revision = 0;
get credentialRevision(): number { return this.revision; }
constructor(
readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
@@ -47,7 +54,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();
@@ -63,8 +76,9 @@ export class AdminService {
}
async verifyPassword(username: string, password: string): Promise<boolean> {
const revision = this.revision;
const credential = this.database.getAdminCredential();
return credential?.username === username && await verifyAdminPassword(password, credential);
return credential?.username === username && await verifyAdminPassword(password, credential) && revision === this.revision;
}
isPasswordChangeRequired(): boolean {
@@ -72,12 +86,15 @@ export class AdminService {
}
async changePassword(password: string): Promise<void> {
const revision = this.revision;
const credential = this.database.getAdminCredential();
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
const passwordError = validateAdminPassword(password);
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
if (revision !== this.revision) throw new AdminInputError("AUTH_REQUIRED", "Administrator credentials changed during the request");
this.database.updateAdminCredential(replacement);
this.revision++;
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
}
@@ -154,7 +171,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 +189,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 +332,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 +508,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 +526,7 @@ export class AdminService {
enabled: input.enabled === true,
host: target.host,
port: target.port,
voiceEndpoint,
tokenEncrypted,
createdAt: previous?.createdAt ?? now,
updatedAt: now,
@@ -513,12 +542,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 +563,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 +661,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";
}
}
+7
View File
@@ -50,6 +50,13 @@ export class AdminSessionStore {
clear(): void {
this.sessions.clear();
}
/** A credential change retains only the authenticated session that performed it. */
revokeOthers(request: Request): void {
const token = readCookie(request.headers.cookie, COOKIE_NAME);
const keep = token ? hashToken(token) : null;
for (const key of this.sessions.keys()) if (key !== keep) this.sessions.delete(key);
}
}
export function isSecureRequest(request: Request): boolean {
+32 -29
View File
@@ -1,51 +1,54 @@
import { performance } from "node:perf_hooks";
const WINDOW_MS = 5 * 60 * 1000;
const MAX_FAILURES = 5;
interface LoginAttempt {
failures: number;
pending: number;
firstFailureAt: number;
}
type Reservation = { allowed: false; retryAfterMs: number }
| { allowed: true; finish(result: "success" | "failure" | "cancelled"): number };
export class AdminLoginRateLimiter {
private readonly attempts = new Map<string, LoginAttempt>();
private pending = 0;
constructor(private readonly maxTrackedPeers = 1024) {}
constructor(private readonly maxTrackedPeers = 1024, private readonly maxConcurrentChecks = 8) {}
retryAfterMs(peer: string, now = Date.now()): number {
const attempt = this.attempts.get(peer);
if (!attempt) return 0;
if (now - attempt.firstFailureAt >= WINDOW_MS) {
this.attempts.delete(peer);
return 0;
}
if (attempt.failures < MAX_FAILURES) return 0;
return WINDOW_MS - (now - attempt.firstFailureAt);
}
recordFailure(peer: string, now = Date.now()): number {
/** Reserve before hashing; pending checks count against capacity, successes are not failures. */
reserve(peer: string, now = performance.now()): Reservation {
this.pruneExpired(now);
const current = this.attempts.get(peer);
if (!current) {
this.pruneExpired(now);
while (this.attempts.size >= this.maxTrackedPeers) {
const oldestPeer = this.attempts.keys().next().value;
if (!oldestPeer) break;
this.attempts.delete(oldestPeer);
}
if (current && current.failures + current.pending >= MAX_FAILURES) {
return { allowed: false, retryAfterMs: Math.max(1000, WINDOW_MS - (now - current.firstFailureAt)) };
}
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
? { failures: 1, firstFailureAt: now }
: { ...current, failures: current.failures + 1 };
if (this.pending >= this.maxConcurrentChecks || (!current && this.attempts.size >= this.maxTrackedPeers)) {
// Never evict another visitor's lockout or pending check to admit a new address.
return { allowed: false, retryAfterMs: 1000 };
}
const attempt = current ?? { failures: 0, pending: 0, firstFailureAt: now };
this.attempts.set(peer, attempt);
return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
}
recordSuccess(peer: string): void {
this.attempts.delete(peer);
attempt.pending++;
this.pending++;
let finished = false;
return { allowed: true, finish: result => {
if (finished) return 0;
finished = true;
this.pending--;
attempt.pending--;
if (result === "success") attempt.failures = 0;
else if (result === "failure") attempt.failures++;
if (!attempt.failures && !attempt.pending) this.attempts.delete(peer);
return result === "failure" ? Math.min(2000, 250 * 2 ** Math.min(3, attempt.failures - 1)) : 0;
} };
}
private pruneExpired(now: number): void {
for (const [peer, attempt] of this.attempts) {
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
if (!attempt.pending && now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
}
}
}
+189
View File
@@ -0,0 +1,189 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { createServer } from "node:net";
import express from "express";
import { AdminLoginRateLimiter } from "./login-rate-limit.js";
import { AdminService } from "./admin-service.js";
import { AdminSessionStore } from "./admin-session.js";
import { createAdminRouter } from "./admin-router.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { createWebServer } from "../server/server.js";
import { JoinTicketStore } from "../server/join-ticket.js";
import type { Logger } from "../logger.js";
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(yes => { resolve = yes; }); return { promise, resolve }; };
test("login reservations bound pending work, count only failures and preserve other lockouts", () => {
const limiter = new AdminLoginRateLimiter(2, 8);
const reserved = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
assert.ok(reserved.every(value => value.allowed));
assert.equal(limiter.reserve("a", 0).allowed, false);
for (const item of reserved) if (item.allowed) item.finish("failure");
const b = limiter.reserve("b", 0); assert.ok(b.allowed); b.finish("failure");
assert.equal(limiter.reserve("c", 0).allowed, false, "new IPs cannot evict an existing lockout");
assert.equal(limiter.reserve("a", 0).allowed, false);
assert.equal(limiter.reserve("a", 300_001).allowed, true);
const successes = new AdminLoginRateLimiter(1);
for (let i = 0; i < 20; i++) { const item = successes.reserve("a", 0); assert.ok(item.allowed); item.finish("success"); }
const cap = new AdminLoginRateLimiter(10, 2);
const first = cap.reserve("a", 0), second = cap.reserve("b", 0);
assert.ok(first.allowed && second.allowed);
assert.equal(cap.reserve("c", 0).allowed, false, "different IPs share the hash concurrency ceiling");
first.finish("cancelled"); first.finish("cancelled");
const third = cap.reserve("c", 0); assert.ok(third.allowed);
assert.equal(cap.reserve("d", 0).allowed, false, "finishing twice cannot release another request's slot");
second.finish("success"); third.finish("success");
});
test("a pending check cannot expire out of the reservation count", () => {
const limiter = new AdminLoginRateLimiter(1);
const checks = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
assert.ok(checks.every(item => item.allowed));
assert.equal(limiter.reserve("a", 400_000).allowed, false);
for (const item of checks) if (item.allowed) item.finish("cancelled");
assert.equal(limiter.reserve("b", 400_000).allowed, true);
});
test("a successful concurrent login cannot erase another request's reservation", () => {
const limiter = new AdminLoginRateLimiter(1);
const slow = limiter.reserve("a", 0), success = limiter.reserve("a", 0);
assert.ok(slow.allowed && success.allowed);
success.finish("success");
const additional = Array.from({ length: 4 }, () => limiter.reserve("a", 0));
assert.ok(additional.every(item => item.allowed));
assert.equal(limiter.reserve("a", 0).allowed, false);
slow.finish("failure");
assert.equal(limiter.reserve("a", 0).allowed, false);
});
async function availablePort() {
const server = createServer();
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address(); assert.ok(address && typeof address !== "string");
await new Promise<void>(resolve => server.close(() => resolve()));
return address.port;
}
for (const trusted of [true, false]) test(`HTTP login and join limits ${trusted ? "separate trusted proxy clients" : "ignore spoofed headers from an untrusted peer"}`, async t => {
let checks = 0;
const gate = deferred();
const service = { credentialRevision: 0, isInitialized: () => true,
verifyPassword: async () => { checks++; await gate.promise; return false; },
database: { addAudit() {} },
getConnectionPolicy: () => ({ accessMode: "fixed", defaultTarget: "8.8.8.8#9987", serverPassword: "" }),
isPasswordChangeRequired: () => false,
} as unknown as AdminService;
const port = await availablePort(), origin = `http://127.0.0.1:${port}`;
const gateway = createWebServer({ port, logger, adminService: service, voiceBridgeOptions: {
joinTickets: new JoinTicketStore(), trustedProxies: trusted ? ["127.0.0.1", "::1"] : ["192.0.2.1"],
} });
await gateway.start();
t.after(async () => { gate.resolve(); await gateway.stop(); });
const post = (route: string, client: string, body: unknown) => fetch(origin + route, {
method: "POST", headers: { origin, "content-type": "application/json", "x-forwarded-for": client }, body: JSON.stringify(body),
});
const a = "203.0.113.9", b = "198.51.100.4";
const logins = Array.from({ length: 12 }, () => post("/api/admin/login", a, { username: "admin", password: "bad" }));
const results = Promise.all(logins);
gate.resolve();
const responses = await results;
const statuses = responses.map(r => r.status);
assert.equal(checks, 5);
assert.equal(statuses.filter(s => s === 401).length, 5);
assert.equal(statuses.filter(s => s === 429).length, 7);
assert.ok(Number(responses.find(r => r.status === 429)!.headers.get("retry-after")) > 0);
assert.equal((await post("/api/admin/login", b, { username: "admin", password: "bad" })).status, trusted ? 401 : 429);
for (let i = 0; i < 30; i++) assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 201);
assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 429);
assert.equal((await post("/api/join-ticket", b, { nickname: "Test" })).status, trusted ? 201 : 429);
});
test("password-verifier exceptions release reservations without leaking their details", async t => {
const app = express(); app.use(express.json());
const service = { credentialRevision: 0, isInitialized: () => true,
verifyPassword: async () => { throw new Error("secret verifier failure detail"); },
} as unknown as AdminService;
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
const server = app.listen(0, "127.0.0.1");
await new Promise<void>(resolve => server.once("listening", resolve));
const address = server.address(); assert.ok(address && typeof address !== "string");
const origin = `http://127.0.0.1:${address.port}`;
t.after(async () => { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });
for (let i = 0; i < 10; i++) {
const response = await fetch(origin + "/api/admin/login", { method: "POST", headers: { origin, "content-type": "application/json" },
body: JSON.stringify({ username: "admin", password: "irrelevant" }) });
assert.equal(response.status, 500);
assert.deepEqual(await response.json(), { ok: false, code: "INTERNAL_ERROR" });
}
});
async function adminFixture(t: TestContext) {
const directory = await mkdtemp(path.join(tmpdir(), "webspeak-auth-race-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"));
await service.initialize(); // Intentionally keep the default password for the bootstrap race.
const app = express(); app.use(express.json());
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
const server = app.listen(0, "127.0.0.1");
await new Promise<void>(resolve => server.once("listening", resolve));
const address = server.address(); assert.ok(address && typeof address !== "string");
const origin = `http://127.0.0.1:${address.port}`;
t.after(async () => { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); database.close(); await rm(directory, { recursive: true }); });
const post = (route: string, body: unknown, cookie = "", csrf = "") => fetch(origin + "/api/admin" + route, {
method: "POST", headers: { origin, cookie, "content-type": "application/json", "x-csrf-token": csrf }, body: JSON.stringify(body),
});
const login = async (password: string) => {
const response = await post("/login", { username: "admin", password });
assert.equal(response.status, 200);
const body = await response.json() as { csrfToken: string };
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
};
const authenticated = async (cookie: string) => (await (await fetch(origin + "/api/admin/session", { headers: { cookie } })).json() as { authenticated: boolean }).authenticated;
return { service, database, post, login, authenticated };
}
test("password rotation revokes other default-password sessions and a login finishing after rotation", { timeout: 15_000 }, async t => {
const f = await adminFixture(t);
const current = await f.login("admin"), other = await f.login("admin");
const verified = deferred(), release = deferred();
const verify = f.service.verifyPassword.bind(f.service);
t.mock.method(f.service, "verifyPassword", async (username: string, password: string) => {
const result = await verify(username, password);
if (password === "admin") { verified.resolve(); await release.promise; }
return result;
});
const pending = f.post("/login", { username: "admin", password: "admin" });
await verified.promise;
try {
const changed = await f.post("/change-password", { newPassword: "new-password-for-test" }, current.cookie, current.csrf);
assert.equal(changed.status, 200);
assert.equal(await f.authenticated(current.cookie), true);
assert.equal(await f.authenticated(other.cookie), false);
} finally { release.resolve(); }
const stale = await pending;
assert.equal(stale.status, 401);
assert.equal(stale.headers.get("set-cookie"), null, "an old verification cannot mint a new session");
await f.login("new-password-for-test");
});
test("failed password updates keep other sessions and concurrent rotations cannot overwrite a winner", { timeout: 15_000 }, async t => {
const f = await adminFixture(t);
const current = await f.login("admin"), other = await f.login("admin");
assert.equal((await f.post("/change-password", { newPassword: "short" }, current.cookie, current.csrf)).status, 400);
assert.equal(await f.authenticated(other.cookie), true);
const results = await Promise.all([
f.post("/change-password", { newPassword: "first-possible-password" }, current.cookie, current.csrf),
f.post("/change-password", { newPassword: "second-possible-password" }, other.cookie, other.csrf),
]);
assert.deepEqual(results.map(r => r.status).sort(), [200, 401]);
const winner = results[0]!.status === 200 ? current : other;
const loser = winner === current ? other : current;
assert.equal(await f.authenticated(winner.cookie), true);
assert.equal(await f.authenticated(loser.cookie), false);
});
+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 ?? false, 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;
}
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { spawnSync } from "node:child_process";
test("protocol identifiers and favorite addresses keep ASCII casing under a Turkish locale", () => {
const child = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", `
import assert from 'node:assert/strict';
import { parseTeamSpeakTarget, teamSpeakTargetKey } from './src/domain/teamspeak-target.ts';
import { quickServerTargetsEqual, mergeQuickServers } from './web/src/services/quick-servers.ts';
import { normalizeTeamSpeakError } from './src/errors.ts';
// Windows ignores LANG for ICU's default locale; isolate the Turkish default in this child.
const localeLower = String.prototype.toLocaleLowerCase;
String.prototype.toLocaleLowerCase = function(...locales) {
return localeLower.call(this, ...(locales.length ? locales : ['tr']));
};
assert.equal('I'.toLocaleLowerCase(), 'ı', 'the child must actually run under Turkish casing');
const target = parseTeamSpeakTarget('VOICE.EXAMPLE.IO#9987');
assert.equal(target.host, 'voice.example.io');
assert.equal(teamSpeakTargetKey({host:'VOICE.EXAMPLE.IO',port:9987}), 'voice.example.io:9987');
assert.equal(quickServerTargetsEqual('VOICE.EXAMPLE.IO:9987', 'voice.example.io#9987'), true);
assert.equal(mergeQuickServers([{id:'a',label:'a',address:'VOICE.EXAMPLE.IO:9987'}],
[{id:'b',address:'voice.example.io:9987',lastConnectedAt:1}]).length, 1);
const upper=normalizeTeamSpeakError(new Error('INVALID IDENTITY'));
const lower=normalizeTeamSpeakError(new Error('invalid identity'));
assert.equal(upper.code, lower.code);
`], { env: { ...process.env, LANG: "tr_TR.UTF-8", LC_ALL: "tr_TR.UTF-8" }, encoding: "utf8" });
assert.equal(child.status, 0, child.stderr || child.stdout);
});
+2 -2
View File
@@ -72,11 +72,11 @@ export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
}
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
return formatTeamSpeakTarget(target).toLocaleLowerCase();
return formatTeamSpeakTarget(target).toLowerCase();
}
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
const host = hostValue.trim().toLocaleLowerCase();
const host = hostValue.trim().toLowerCase();
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
+3 -3
View File
@@ -186,7 +186,7 @@ function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnosti
*/
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
if (id === undefined || id === null) return null;
const text = String(id).trim().toLocaleLowerCase();
const text = String(id).trim().toLowerCase();
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
@@ -199,7 +199,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const diagnostics = collectDiagnostics(error);
const text = diagnosticText(error).toLocaleLowerCase();
const text = diagnosticText(error).toLowerCase();
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
// keyword heuristic below. The inline scan keeps the `id=515` shape
@@ -258,7 +258,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
// the class name before falling back to the message text.
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
const errorName = (diagnostics.name ?? "").toLowerCase();
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
}
+56 -4
View File
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { SkinRegistry } from "./admin/skin-registry.js";
import { PluginRegistry } from "./plugins/registry.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -45,6 +46,8 @@ async function main() {
await adminService.initialize();
removeObsoleteBootstrapFile();
const joinTickets = new JoinTicketStore();
const pluginRegistry = new PluginRegistry(path.join(DATA_DIR, "plugins"), masterSecret);
await pluginRegistry.initialize();
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
@@ -58,6 +61,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
@@ -69,6 +73,8 @@ async function main() {
},
adminService,
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
pluginRegistry,
pluginRuntime: { port: parsePort(process.env.WEBSPEAK_PLUGIN_PORT, 3042), host: process.env.WEBSPEAK_PLUGIN_HOST?.trim() || "0.0.0.0", publicOrigin: process.env.WEBSPEAK_PLUGIN_PUBLIC_ORIGIN?.trim() },
logger,
nextVisitorNumber: () => database.nextVisitorNumber(),
visitorCount: () => database.getVisitorCount(),
@@ -93,11 +99,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 +177,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();
+3 -3
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";
@@ -31,7 +31,7 @@ app.get("/api/health", (_request, response) => response.json({ status: "ok", eng
app.get("/api/public-config", (_request, response) => {
response.setHeader("Cache-Control", "no-store");
response.json({
version: process.env.WEBSPEAK_VERSION ?? "0.2.6",
version: process.env.WEBSPEAK_VERSION ?? "0.3.0",
initialized: true,
siteName: "WebSpeak",
welcomeText: DEFAULT_WELCOME_TEXTS.zh,
@@ -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;
`);
});
}
}
+66
View File
@@ -0,0 +1,66 @@
import express, { Router, type RequestHandler } from "express";
import { PluginRegistry } from "./registry.js";
import { PluginStore } from "./store.js";
import type { PluginRuntime } from "./runtime.js";
import { pluginAssert, pluginRecord, PluginError, parsePluginPackage } from "../shared/plugins.js";
export function createPluginAdminRouter(options: {
registry?: PluginRegistry; store?: PluginStore; runtime?: PluginRuntime; protect: RequestHandler[];
audit(event: string, data: { id: string; version?: string }): void;
}) {
const router = Router(), store = options.store ?? new PluginStore();
const writeGuard = Router(); writeGuard.use(...options.protect);
router.use((request, response, next) => {
if (request.method === "GET") return next();
// Reuse the admin session's same-origin and CSRF rules for every write.
writeGuard(request, response, next);
});
// The parent authenticates before parsing a potentially large application bundle.
router.use(express.json({limit:"50mb"}));
const registry = () => { pluginAssert(options.registry, "PLUGIN_STORAGE_UNAVAILABLE"); return options.registry; };
const project=(plugin:ReturnType<PluginRegistry["list"]>[number])=>({...plugin,runtime:options.runtime?.status(plugin.manifest.id)??{state:plugin.settings.enabled?(plugin.manifest.server?"stopped":"client"):"disabled"}});
router.get("/", (_request, response) => response.json({ plugins: registry().list().map(project) }));
router.get("/runtime",(_request,response)=>{pluginAssert(options.runtime,"PLUGIN_RUNTIME_UNAVAILABLE");response.json({runtime:options.runtime.settings()});});
router.put("/runtime",async(request,response)=>{
pluginAssert(options.runtime&&pluginRecord(request.body));const runtime=await options.runtime.configureOrigin(request.body.publicOrigin,request.body.revision);
options.audit("ADMIN_PLUGIN_RUNTIME_CONFIGURED",{id:"runtime"});response.json({runtime});
});
router.get("/store", async (_request, response) => { response.json(await store.list()); });
router.post("/store/install", async (request, response) => {
const plugin = await store.install(registry(), request.body);
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
response.status(201).json({ plugin:project(plugin) });
});
router.post("/upload", async (request, response) => {
pluginAssert(pluginRecord(request.body));
const expected = request.body.installedRevision;
pluginAssert(expected === null || typeof expected === "string");
const plugin = await registry().install(parsePluginPackage(request.body.package), expected);
options.audit("ADMIN_PLUGIN_INSTALLED", { id: plugin.manifest.id, version: plugin.manifest.version });
response.status(201).json({ plugin:project(plugin) });
});
router.put("/:id/settings", async (request, response) => {
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
const plugin = await registry().configure(String(request.params.id), request.body.settings, request.body.revision);
await options.runtime?.synchronize(plugin.manifest.id);
options.audit("ADMIN_PLUGIN_CONFIGURED", { id: plugin.manifest.id });
response.json({ plugin:project(plugin) });
});
router.post("/:id/restart",async(request,response)=>{
pluginAssert(options.runtime&&pluginRecord(request.body));const id=String(request.params.id),plugin=registry().policy(id);
pluginAssert(plugin,"PLUGIN_NOT_FOUND");pluginAssert(plugin.revision===request.body.revision,"PLUGIN_CHANGED");pluginAssert(plugin.settings.enabled&&plugin.settings.trusted,"PLUGIN_DISABLED");
await options.runtime.restart(id);options.audit("ADMIN_PLUGIN_RESTARTED",{id});response.json({plugin:project(plugin)});
});
router.delete("/:id", async (request, response) => {
pluginAssert(pluginRecord(request.body) && typeof request.body.revision === "string");
await registry().remove(String(request.params.id), request.body.revision);
await options.runtime?.synchronize(String(request.params.id));
options.audit("ADMIN_PLUGIN_REMOVED", { id: String(request.params.id) }); response.json({ ok: true });
});
router.use((error: unknown, _request: unknown, response: import("express").Response, _next: unknown) => {
const tooLarge=pluginRecord(error)&&error.type==="entity.too.large";
const code = tooLarge?"PLUGIN_TOO_LARGE":error instanceof PluginError ? error.code : "PLUGIN_FAILED";
response.status(tooLarge?413:code === "PLUGIN_STORE_UNAVAILABLE" ? 502 : code === "PLUGIN_NOT_FOUND" ? 404 : code === "PLUGIN_CHANGED" ? 409 : 400).json({ ok: false, code });
});
return router;
}
+65
View File
@@ -0,0 +1,65 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdtemp, rm, readFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { PluginRegistry } from './registry.js';
import { PluginProcess } from './process.js';
import { parsePluginPackage, parsePluginJson, pluginPath, pluginFileBytes, type PluginPackage, type PluginAppContext } from '../shared/plugins.js';
import { createLogger } from '../logger.js';
export const fixturePackage = (server?:string):PluginPackage => parsePluginPackage({manifest:{apiVersion:2,id:'test.application',name:'Application',version:'1.0.0',author:'Tests',license:'MIT',description:'Independent application fixture',scopes:['server','instance'],client:{entry:'client/index.html'},...(server?{server:{entry:'server/main.mjs'}}:{})},files:{'client/index.html':{encoding:'utf8',data:'<!doctype html><html><head></head><body><script type="module" src="./app.js"></script></body></html>'},'client/app.js':{encoding:'utf8',data:'document.body.dataset.ready="yes"'},...(server?{'server/main.mjs':{encoding:'utf8',data:server}}:{})}});
async function registry(t:test.TestContext){const directory=await mkdtemp(path.join(tmpdir(),'webspeak-app-v2-'));const cleanup:Array<()=>Promise<unknown>>=[];t.after(async()=>{for(const dispose of cleanup)await dispose();assert.equal(path.dirname(directory),tmpdir());await rm(directory,{recursive:true,force:true});});const value=new PluginRegistry(directory,Buffer.alloc(32,7));await value.initialize();return {value,directory,cleanup};}
test('v2 accepts ordinary application assets and rejects the obsolete room protocol',()=>{
const pack=fixturePackage();assert.equal(pack.manifest.apiVersion,2);assert.ok(pack.files['client/app.js']);
assert.throws(()=>parsePluginPackage({manifest:{...pack.manifest,apiVersion:1},html:'x',script:'x',styles:{light:'x',dark:'x'}}),/PLUGIN_API_UNSUPPORTED/);
assert.throws(()=>parsePluginPackage({...pack,manifest:{...pack.manifest,permissions:['room.read']}}),/PLUGIN_API_UNSUPPORTED/);
const binary=parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'AAEC/w=='}}});assert.deepEqual([...pluginFileBytes(binary.files['client/asset.bin'])],[0,1,2,255]);
assert.throws(()=>parsePluginPackage({...pack,files:{...pack.files,'client/asset.bin':{encoding:'base64',data:'!notbase64'}}}));
});
test('package paths reject traversal, Windows special names, case collisions and file-directory aliases',()=>{
for(const name of ['../a','client/../a','client/a\\b','client/CON.txt','client/aux','client/a.','/client/a'])assert.equal(pluginPath(name),false,name);
const pack=fixturePackage();
for(const files of [{...pack.files,'client/APP.js':{encoding:'utf8',data:'x'}},{...pack.files,'client/folder':{encoding:'utf8',data:'x'},'client/folder/file.js':{encoding:'utf8',data:'x'}}])assert.throws(()=>parsePluginPackage({...pack,files}));
assert.throws(()=>parsePluginJson(JSON.parse('{"__proto__":{"value":1}}')));assert.throws(()=>parsePluginJson({n:Infinity}));
});
test('install and update require explicit trust, encrypt private config and preserve CAS/persistence',async t=>{
const {value:r,directory}=await registry(t),pack=fixturePackage();const first=await r.install(pack,null);
assert.equal(first.settings.enabled,false);assert.equal(first.settings.trusted,false);
await assert.rejects(r.configure(pack.manifest.id,{enabled:true,trusted:false,scope:'instance',targets:[],config:{}},first.revision),/PLUGIN_TRUST_REQUIRED/);
const enabled=await r.configure(pack.manifest.id,{enabled:true,trusted:true,scope:'server',targets:['EXAMPLE.com#9987'],config:{public:'value'},serverConfigAction:'replace',serverConfig:{secret:'private-fixture-value'}},first.revision);
assert.deepEqual(enabled.settings.targets,['example.com:9987']);assert.equal(enabled.settings.hasServerConfig,true);assert.equal(JSON.stringify(enabled).includes('private-fixture-value'),false);
const record=await readFile(path.join(directory,'installed',pack.manifest.id+'.json'),'utf8');assert.equal(record.includes('private-fixture-value'),false);assert.deepEqual(r.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
await assert.rejects(r.configure(pack.manifest.id,enabled.settings,first.revision),/PLUGIN_CHANGED/);
const reloaded=new PluginRegistry(directory,Buffer.alloc(32,7));await reloaded.initialize();assert.deepEqual(reloaded.list(),r.list());assert.deepEqual(reloaded.serverConfig(pack.manifest.id),{secret:'private-fixture-value'});
const update=await r.install({...pack,manifest:{...pack.manifest,version:'1.1.0'}},enabled.revision);assert.equal(update.settings.enabled,false);assert.equal(update.settings.trusted,false);assert.equal(update.settings.hasServerConfig,true);
const cleared=await r.configure(pack.manifest.id,{...update.settings,serverConfigAction:'remove'},update.revision);assert.equal(cleared.settings.hasServerConfig,false);
await r.remove(pack.manifest.id,cleared.revision);assert.equal(r.list().length,0);
});
test('materialized applications contain their own files and package integrity is checked',async t=>{
const {value:r}=await registry(t),pack=fixturePackage();const installed=await r.install(pack,null);const directory=await r.materialize(pack.manifest.id,installed.revision);
assert.match(await readFile(path.join(directory,'client/index.html'),'utf8'),/type="module"/);
await assert.rejects(r.releaseCode(path.resolve(directory,'../../../../unrelated')),/PLUGIN_INVALID/);
await r.releaseCode(directory);await assert.rejects(readFile(path.join(directory,'client/index.html')));
});
test('a backend runs native Node filesystem and arbitrary HTTP handlers in an independent process',async t=>{
const {value:r,cleanup}=await registry(t);
const source=`import {writeFile,readFile} from 'node:fs/promises';import path from 'node:path';export default async ({dataDir,config})=>{let count=Number(await readFile(path.join(dataDir,'counter.txt'),'utf8').catch(()=>0));return {handle:async(req,res)=>{count++;await writeFile(path.join(dataDir,'counter.txt'),String(count));res.setHeader('content-type','application/json');res.end(JSON.stringify({path:req.url,user:req.webspeak.self.id,configured:config.secret==='private',count,pid:process.pid}));}};};`;
const pack=fixturePackage(source),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision),data=await r.dataDirectory(pack.manifest.id);
const processes:PluginProcess[]=[];cleanup.push(async()=>{await Promise.all(processes.map(p=>p.close()));});
const run=()=>{const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:data,config:{secret:'private'},publicConfig:{},logger:createLogger(),onExit:()=>{}});processes.push(child);return child;};
const child=run();await child.ready;assert.ok(child.child.pid&&child.child.pid!==process.pid);
const context={apiVersion:2,self:{id:'participant-a'},scope:{key:'instance'}} as PluginAppContext;
const request=()=>fetch(`http://127.0.0.1:${child.port}/author-defined/path`,{headers:{'x-webspeak-runtime':child.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});
assert.equal((await fetch(`http://127.0.0.1:${child.port}/author-defined/path`)).status,403);
const value=await(await request()).json();assert.equal(value.path,'/author-defined/path');assert.equal(value.user,'participant-a');assert.equal(value.configured,true);assert.equal(value.count,1);
await child.close();const replacement=run();await replacement.ready;
const next=await fetch(`http://127.0.0.1:${replacement.port}/another-route`,{headers:{'x-webspeak-runtime':replacement.token,'x-webspeak-context':Buffer.from(JSON.stringify(context),'utf8').toString('base64url')}});assert.equal((await next.json()).count,2);
});
test('a failed or hung plugin activation is bounded and does not execute in the gateway process',async t=>{
const {value:r,cleanup}=await registry(t),pack=fixturePackage('export default async()=>new Promise(()=>{});'),installed=await r.install(pack,null),code=await r.materialize(pack.manifest.id,installed.revision);
const child=new PluginProcess({entry:path.join(code,'server/main.mjs'),codeDirectory:code,dataDirectory:await r.dataDirectory(pack.manifest.id),config:{},publicConfig:{},logger:createLogger(),onExit:()=>{},startupMs:1000});
cleanup.push(()=>child.close());await assert.rejects(child.ready,/PLUGIN_START_TIMEOUT/);await child.close();assert.notEqual(child.child.exitCode,null);
});
+69
View File
@@ -0,0 +1,69 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import { PluginError, pluginRecord, type JsonValue } from "../shared/plugins.js";
export class PluginProcess {
readonly token = randomBytes(32).toString("base64url");
readonly child: ChildProcess;
readonly ready: Promise<number>;
readonly exited: Promise<void>;
port = 0;
private stopping = false;
private finished = false;
private closePromise?: Promise<void>;
constructor(options: {
entry: string; codeDirectory: string; dataDirectory: string; config: JsonValue; publicConfig: JsonValue;
logger: Logger; onExit(): void; startupMs?: number;
}) {
const typescript = import.meta.url.endsWith(".ts");
const worker = fileURLToPath(new URL(typescript ? "./worker.ts" : "./worker.js", import.meta.url));
const execArgv = [...(typescript ? ["--import", import.meta.resolve("tsx")] : []), "--max-old-space-size=256"];
// Separate process and reduced environment; reviewed backend code still has the OS user's permissions.
const env: NodeJS.ProcessEnv = {};
for (const key of ["PATH", "Path", "SystemRoot", "WINDIR", "TEMP", "TMP", "LANG", "NODE_EXTRA_CA_CERTS"]) if (process.env[key]) env[key] = process.env[key];
this.child = spawn(process.execPath, [...execArgv, worker], { cwd: options.codeDirectory, env, windowsHide: true, stdio: ["ignore", "ignore", "ignore", "ipc"] });
let resolveExit!: () => void;
this.exited = new Promise(resolve => { resolveExit = resolve; });
let resolveReady!: (port: number) => void, rejectReady!: (error: Error) => void;
this.ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
const timer = setTimeout(() => { rejectReady(new PluginError("PLUGIN_START_TIMEOUT")); void this.close(); }, options.startupMs ?? 10000);
let logWindow = Date.now(), logs = 0;
this.child.on("message", value => {
if (!pluginRecord(value) || this.stopping) return;
if (value.type === "ready" && Number.isInteger(value.port) && Number(value.port) > 0 && Number(value.port) <= 65535) {
clearTimeout(timer); this.port = Number(value.port); resolveReady(this.port);
} else if (value.type === "failed") {
clearTimeout(timer); rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close();
} else if (value.type === "log" && typeof value.message === "string") {
if (Date.now() - logWindow > 1000) { logWindow = Date.now(); logs = 0; }
if (++logs <= 20) options.logger.debug({ message: value.message.slice(0, 1000) }, "Plugin application log");
}
});
const finish = () => {
if (this.finished) return; this.finished = true; clearTimeout(timer);
rejectReady(new PluginError(this.stopping ? "PLUGIN_STOPPED" : "PLUGIN_PROCESS_EXITED"));
resolveExit(); if (!this.stopping) options.onExit();
};
this.child.once("error", finish); this.child.once("exit", finish);
this.child.send({ type: "initialize", entry: options.entry, dataDir: options.dataDirectory, config: options.config, publicConfig: options.publicConfig, token: this.token }, error => {
if (error) { rejectReady(new PluginError("PLUGIN_START_FAILED")); void this.close(); }
});
}
event(name: string, payload: unknown): void {
if (this.stopping || this.finished || !this.child.connected) return;
try { this.child.send({ type: "event", name, payload }, () => undefined); } catch { /* Retired worker. */ }
}
close(): Promise<void> {
if (this.closePromise) return this.closePromise;
this.stopping = true;
this.closePromise = (async () => {
if (this.finished) return;
if (this.child.connected) { try { this.child.send({ type: "stop" }, () => undefined); } catch {} }
const killer = setTimeout(() => this.child.kill("SIGKILL"), 2000);
try { await this.exited; } finally { clearTimeout(killer); }
})();
return this.closePromise;
}
}
+98
View File
@@ -0,0 +1,98 @@
import { mkdir, readFile, readdir, writeFile, rename, unlink, mkdtemp, rm } from "node:fs/promises";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
import { loadOrCreateMasterSecret } from "../security/master-secret.js";
import { parsePluginPackage, parsePluginManifest, parsePluginJson, pluginAssert, pluginId, pluginRecord, pluginFileBytes, PluginError, PLUGIN_LIMIT_BYTES,
type InstalledPlugin, type PluginPackage, type PluginSettings, type JsonValue } from "../shared/plugins.js";
interface StoredPlugin extends InstalledPlugin { schemaVersion: 2; packageDigest: string; serverConfigCiphertext: string }
export class PluginRegistry {
private readonly records = new Map<string, StoredPlugin>();
private queue: Promise<unknown> = Promise.resolve();
private readonly masterKey: Buffer;
readonly listeners = new Set<(id: string) => void>();
readonly directory: string;
constructor(directory: string, masterKey?: Buffer) {
this.directory = path.resolve(directory);
this.masterKey = masterKey ?? loadOrCreateMasterSecret(path.join(this.directory,"master.key"));
}
async initialize(): Promise<void> {
await mkdir(path.join(this.directory,"installed"),{recursive:true});
for (const file of await readdir(path.join(this.directory,"installed"))) {
if (!file.endsWith('.json')) continue;
try {
const bytes=await readFile(path.join(this.directory,"installed",file)); pluginAssert(bytes.length<=256*1024);
const v:unknown=JSON.parse(bytes.toString('utf8'));pluginAssert(pluginRecord(v)&&v.schemaVersion===2);
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
} catch { /* Invalid or obsolete packages are never executed. */ }
}
}
private public(record: StoredPlugin): InstalledPlugin {
return structuredClone({manifest:record.manifest,settings:record.settings,revision:record.revision,installedAt:record.installedAt});
}
list(): InstalledPlugin[] { return [...this.records.values()].map(record=>this.public(record)); }
policy(id: string): InstalledPlugin | undefined { const record=this.records.get(id);return record?this.public(record):undefined; }
private hash(record: Omit<StoredPlugin,'revision'> | StoredPlugin): string {
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
}
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
}
private readSecret(record: StoredPlugin): JsonValue {
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
return text?parsePluginJson(JSON.parse(text)):null;
}
serverConfig(id: string): JsonValue { const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');return this.readSecret(record); }
private mutate<T>(run:()=>Promise<T>):Promise<T>{const next=this.queue.then(run,run);this.queue=next.catch(()=>undefined);return next;}
private async commit(record:StoredPlugin):Promise<InstalledPlugin>{
record.revision=this.hash(record);const directory=path.join(this.directory,'installed'),temporary=path.join(directory,`.${randomUUID()}.tmp`);
try{await writeFile(temporary,JSON.stringify(record),{flag:'wx',mode:0o600});await rename(temporary,path.join(directory,`${record.manifest.id}.json`));}finally{await unlink(temporary).catch(()=>undefined);}
this.records.set(record.manifest.id,record);for(const listener of this.listeners){try{listener(record.manifest.id);}catch{}}
return this.public(record);
}
install(input:PluginPackage,expectedRevision:string|null):Promise<InstalledPlugin>{return this.mutate(async()=>{
const pack=parsePluginPackage(input),previous=this.records.get(pack.manifest.id);pluginAssert((previous?.revision??null)===expectedRevision,'PLUGIN_CHANGED');pluginAssert(previous||this.records.size<50,'PLUGIN_LIMIT');
const bytes=JSON.stringify(pack),digest=createHash('sha256').update(bytes).digest('hex'),directory=path.join(this.directory,'packages',pack.manifest.id);
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
const old=previous?.settings;
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
});}
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');pluginAssert(pluginRecord(input));
let secret=record.serverConfigCiphertext;const action=input.serverConfigAction??'keep';pluginAssert(['keep','replace','remove'].includes(String(action)));
if(action==='remove')secret='';else if(action==='replace')secret=encryptSecret(JSON.stringify(parsePluginJson(input.serverConfig)),this.masterKey,`webspeak:plugin-config:v2:${id}`);
const settings=this.settings(input,record.manifest,!!secret);return this.commit({...record,settings,serverConfigCiphertext:secret});
});}
async getPackage(id:string):Promise<PluginPackage>{
const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');
const bytes=await readFile(path.join(this.directory,'packages',id,`${record.packageDigest}.wplugin`));pluginAssert(bytes.length<=PLUGIN_LIMIT_BYTES,'PLUGIN_TOO_LARGE');
pluginAssert(createHash('sha256').update(bytes).digest('hex')===record.packageDigest,'PLUGIN_CHECKSUM');
const pack=parsePluginPackage(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)));pluginAssert(JSON.stringify(pack.manifest)===JSON.stringify(record.manifest),'PLUGIN_PACKAGE_MISMATCH');return pack;
}
async materialize(id:string,revision:string):Promise<string>{
const record=this.records.get(id);pluginAssert(record?.revision===revision,'PLUGIN_CHANGED');const pack=await this.getPackage(id);pluginAssert(this.records.get(id)?.revision===revision,'PLUGIN_CHANGED');
const parent=path.join(this.directory,'code',id);await mkdir(parent,{recursive:true});const root=await mkdtemp(path.join(parent,'run-'));
try{for(const [name,file]of Object.entries(pack.files)){const target=path.resolve(root,name);pluginAssert(target.startsWith(root+path.sep));await mkdir(path.dirname(target),{recursive:true});await writeFile(target,pluginFileBytes(file),{flag:'wx',mode:0o600});}return root;}
catch(error){await this.releaseCode(root);throw error;}
}
async releaseCode(directory:string):Promise<void>{
const root=path.resolve(this.directory,'code');pluginAssert(path.resolve(directory).startsWith(root+path.sep));await rm(directory,{recursive:true,force:true});
}
async dataDirectory(id:string):Promise<string>{pluginAssert(pluginId(id));const directory=path.join(this.directory,'data',id);await mkdir(directory,{recursive:true});return directory;}
remove(id:string,revision:string):Promise<void>{return this.mutate(async()=>{
pluginAssert(pluginId(id));const record=this.records.get(id);pluginAssert(record,'PLUGIN_NOT_FOUND');pluginAssert(record.revision===revision,'PLUGIN_CHANGED');
await unlink(path.join(this.directory,'installed',`${id}.json`));this.records.delete(id);for(const listener of this.listeners){try{listener(id);}catch{}}
});}
}
+34
View File
@@ -0,0 +1,34 @@
import { Router } from "express";
import { PluginRuntime } from "./runtime.js";
import { pluginAssert, PluginError, pluginRecord } from "../shared/plugins.js";
/** Control plane only. Application HTTP/WebSocket traffic lives on the independent origin. */
export function createPluginRuntimeRouter(runtime?: PluginRuntime) {
const router=Router();
router.use((_request,response,next)=>{
response.setHeader("access-control-allow-origin","*");
response.setHeader("access-control-allow-headers","authorization, content-type");
response.setHeader("access-control-allow-methods","GET, POST, PATCH, DELETE, OPTIONS");
response.setHeader("cache-control","no-store");next();
});
router.options(/.*/,(_request,response)=>{response.sendStatus(204);});
const token=(authorization:string|undefined)=>{pluginAssert(typeof authorization==="string"&&authorization.startsWith("Bearer "),"PLUGIN_NOT_CONNECTED");return authorization.slice(7);};
const service=()=>{pluginAssert(runtime,"PLUGIN_RUNTIME_UNAVAILABLE");return runtime;};
router.get("/",(request,response)=>{response.json({plugins:service().directory(token(request.header("authorization")))});});
router.post("/:id/open",async(request,response)=>{
const origin=request.header("origin")??`${request.protocol}://${request.header("host")}`;
response.status(201).json(await service().open(token(request.header("authorization")),String(request.params.id),request.body,origin));
});
router.delete("/opening/:id",(request,response)=>{service().cancelOpen(token(request.header("authorization")),String(request.params.id));response.json({ok:true});});
router.patch("/apps/:id",(request,response)=>{
pluginAssert(pluginRecord(request.body));service().appearance(String(request.params.id),token(request.header("authorization")),request.body);response.json({ok:true});
});
router.delete("/apps/:id",(request,response)=>{
const instance=service(),id=String(request.params.id);pluginAssert(instance.authorizeApp(id,token(request.header("authorization"))),"PLUGIN_NOT_OPEN");instance.closeApp(id);response.json({ok:true});
});
router.use((error:unknown,_request:unknown,response:import("express").Response,_next:unknown)=>{
const code=error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED";
response.status(code==="PLUGIN_NOT_CONNECTED"?401:code==="PLUGIN_NOT_FOUND"?404:code==="PLUGIN_RUNTIME_UNAVAILABLE"?503:403).json({ok:false,code});
});
return router;
}
+274
View File
@@ -0,0 +1,274 @@
import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse, type Server } from "node:http";
import { createServer as createHttpsServer, type ServerOptions } from "node:https";
import { readFile, writeFile, rename } from "node:fs/promises";
import { createReadStream } from "node:fs";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import path from "node:path";
import type { Socket } from "node:net";
import type { Logger } from "../logger.js";
import { PluginRegistry } from "./registry.js";
import { PluginProcess } from "./process.js";
import { PluginError, pluginAssert, pluginPath, pluginRecord, type InstalledPlugin, type PluginAppContext, type PluginAppLaunch, type PluginParticipant, type PluginRequestContext, type PluginRuntimeStatus } from "../shared/plugins.js";
interface ApplicationEntry { policy: InstalledPlugin; directory: string; assets: Set<string>; process?: PluginProcess; status: PluginRuntimeStatus; stale: boolean }
interface AppSession {
id: string; publicId: string; participantId: string; openKey: string; pluginId: string; revision: string; voiceToken: string; scopeKey: string;
theme: "light" | "dark"; language: PluginAppContext["language"]; origin: string; lastActivity: number; lastContext: string;
streams: Set<ServerResponse>; connections: Set<() => void>;
}
interface RuntimeOptions {
registry: PluginRegistry; participant(token: string): PluginParticipant | null; logger: Logger;
port?: number; host?: string; publicOrigin?: string; tls?: ServerOptions; maxWorkers?: number;
}
const contentTypes: Record<string, string> = { ".html":"text/html; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".css":"text/css; charset=utf-8", ".json":"application/json; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".gif":"image/gif", ".ico":"image/x-icon", ".woff":"font/woff", ".woff2":"font/woff2", ".wasm":"application/wasm", ".mp4":"video/mp4", ".webm":"video/webm" };
/** App traffic uses its own HTTP origin and child processes, never the voice WebSocket. */
export class PluginRuntime {
private readonly entries = new Map<string, ApplicationEntry>();
private readonly queues = new Map<string, Promise<unknown>>();
private readonly sessions = new Map<string, AppSession>();
private readonly openings = new Map<string, {cancelled:boolean; expires:number; appId?:string}>();
private readonly server: Server | ReturnType<typeof createHttpsServer>;
private readonly sockets = new Set<Socket>();
private timer?: ReturnType<typeof setInterval>;
private origin = "";
private listening = false;
private closed = false;
private configQueue: Promise<unknown> = Promise.resolve();
private readonly changed = (id: string) => {
this.revokePlugin(id, "PLUGIN_CHANGED");
const entry = this.entries.get(id); if (entry) { entry.stale = true; void entry.process?.close(); }
void this.synchronize(id).catch(() => undefined);
};
constructor(private readonly options: RuntimeOptions) {
this.server = options.tls ? createHttpsServer(options.tls, (req,res) => void this.handle(req,res)) : createServer((req,res) => void this.handle(req,res));
this.server.on("connection", socket => { this.sockets.add(socket); socket.once("close", () => this.sockets.delete(socket)); });
this.server.on("upgrade", (req,socket,head) => void this.upgrade(req,socket as Socket,head));
options.registry.listeners.add(this.changed);
}
get port(): number { const address=this.server.address(); return address&&typeof address!=="string"?address.port:0; }
settings() { return { publicOrigin:this.origin, port:this.port, available:this.listening, revision:createHash("sha256").update(this.origin).digest("hex") }; }
async configureOrigin(input: unknown, revision: unknown): Promise<ReturnType<PluginRuntime["settings"]>> {
const next=this.configQueue.then(async()=>{
pluginAssert(typeof input==="string"&&input.length<=300&&typeof revision==="string");
pluginAssert(revision===this.settings().revision,"PLUGIN_CHANGED");
const origin=normalizeOrigin(input);
const directory=this.options.registry.directory, temporary=path.join(directory,`.runtime-${randomUUID()}.tmp`);
await writeFile(temporary,JSON.stringify({publicOrigin:origin}),{flag:"wx",mode:0o600}); await rename(temporary,path.join(directory,"runtime.json"));
this.origin=origin;for(const app of [...this.sessions.values()])this.closeApp(app.id,"PLUGIN_CHANGED");return this.settings();
});this.configQueue=next.catch(()=>undefined);return next;
}
async start(): Promise<void> {
try { const value=JSON.parse(await readFile(path.join(this.options.registry.directory,"runtime.json"),"utf8"));this.origin=normalizeOrigin(value.publicOrigin); }
catch { this.origin=normalizeOrigin(this.options.publicOrigin??""); }
await new Promise<void>((resolve,reject)=>{
const failed=(error:Error)=>{this.server.off("listening",ready);reject(error);};
const ready=()=>{this.server.off("error",failed);this.listening=true;resolve();};
this.server.once("error",failed);this.server.once("listening",ready);this.server.listen(this.options.port??3042,this.options.host??"0.0.0.0");
});
this.timer=setInterval(()=>this.reconcileSessions(),1000);
// Applications may provide background integrations even without an open browser panel.
await Promise.allSettled(this.options.registry.list().filter(p=>p.settings.enabled).map(p=>this.synchronize(p.manifest.id)));
}
status(id: string): PluginRuntimeStatus {
const policy=this.options.registry.policy(id);if(!policy?.settings.enabled)return {state:"disabled"};
return this.entries.get(id)?.status??{state:policy.manifest.server?"stopped":"client"};
}
private async stopEntry(entry: ApplicationEntry): Promise<void> {
await entry.process?.close();if(entry.directory){await this.options.registry.releaseCode(entry.directory);entry.directory="";}
}
synchronize(id: string): Promise<void> {
const next=(this.queues.get(id)??Promise.resolve()).then(async()=>{
const policy=this.options.registry.policy(id),previous=this.entries.get(id);
if(previous&&!previous.stale&&previous.policy.revision===policy?.revision)return;
if(previous){await this.stopEntry(previous);this.entries.delete(id);}
if(this.closed||!policy?.settings.enabled||!policy.settings.trusted)return;
const entry:ApplicationEntry={policy,directory:"",assets:new Set(),status:{state:"starting"},stale:false};this.entries.set(id,entry);
try {
if(policy.manifest.server)pluginAssert([...this.entries.values()].filter(p=>p.policy.manifest.server&&["starting","running"].includes(p.status.state)).length<=(this.options.maxWorkers??8),"PLUGIN_WORKER_LIMIT");
entry.assets=new Set(Object.keys((await this.options.registry.getPackage(id)).files).filter(name=>name.startsWith("client/")));
entry.directory=await this.options.registry.materialize(id,policy.revision);
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
if(policy.manifest.server){
entry.process=new PluginProcess({entry:path.join(entry.directory,policy.manifest.server.entry),codeDirectory:entry.directory,dataDirectory:await this.options.registry.dataDirectory(id),config:this.options.registry.serverConfig(id),publicConfig:policy.settings.config,logger:this.options.logger.child({pluginId:id}),onExit:()=>{
if(this.entries.get(id)===entry&&!entry.stale&&!this.closed){entry.status={state:"failed",error:"PLUGIN_PROCESS_EXITED"};this.revokePlugin(id,"PLUGIN_PROCESS_EXITED");}
}});await entry.process.ready;
}
pluginAssert(!this.closed&&this.options.registry.policy(id)?.revision===policy.revision,"PLUGIN_CHANGED");
entry.status={state:policy.manifest.server?"running":"client"};
} catch(error) {
entry.status={state:"failed",error:error instanceof PluginError?error.code:"PLUGIN_START_FAILED"};
await this.stopEntry(entry);this.options.logger.warn({pluginId:id,code:entry.status.error},"Plugin application failed to start");
}
});this.queues.set(id,next.catch(()=>undefined));return next;
}
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
directory(voiceToken:string) {
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
}
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
if(policy.settings.scope==="instance")return "instance";
pluginAssert(policy.settings.targets.includes(participant.target),"PLUGIN_NOT_ALLOWED");return `${participant.target}#${participant.channelId}`;
}
private appOrigin(mainOrigin:string):string{
pluginAssert(this.listening,"PLUGIN_RUNTIME_UNAVAILABLE");
if(this.origin){pluginAssert(this.origin!==new URL(mainOrigin).origin,"PLUGIN_SEPARATE_ORIGIN_REQUIRED");return this.origin;}
const source=new URL(mainOrigin);pluginAssert(["127.0.0.1","localhost","[::1]"].includes(source.hostname),"PLUGIN_PUBLIC_ORIGIN_REQUIRED");
source.hostname=source.hostname==="localhost"?"127.0.0.1":"localhost";source.port=String(this.port);source.protocol=this.options.tls?"https:":"http:";return source.origin;
}
async open(voiceToken:string,id:string,input:unknown,mainOrigin:string):Promise<PluginAppLaunch>{
const participant=this.options.participant(voiceToken),policy=this.options.registry.policy(id);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");pluginAssert(policy,"PLUGIN_NOT_FOUND");
const preferences=pluginRecord(input)?input:{},openId=preferences.openId??randomUUID();
pluginAssert(typeof openId==="string"&&/^[a-zA-Z0-9-]{8,80}$/.test(openId));const openKey=voiceToken+":"+openId,previous=this.openings.get(openKey);
if(previous?.appId){const app=this.sessions.get(previous.appId);if(app&&this.validate(app)){pluginAssert(app.pluginId===id,"PLUGIN_OPEN_CONFLICT");return {id:app.id,url:`${app.origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};}}
pluginAssert(!previous,previous?.cancelled?"PLUGIN_CANCELLED":"PLUGIN_OPEN_PENDING");
pluginAssert([...this.openings.keys()].filter(key=>key.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
const operation={cancelled:false,expires:Date.now()+90000,appId:undefined as string|undefined};this.openings.set(openKey,operation);
const scopeKey=this.scopeKey(policy,participant),origin=this.appOrigin(mainOrigin);
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
await this.synchronize(id);const entry=this.entries.get(id);pluginAssert(entry&&["running","client"].includes(entry.status.state),entry?.status.error??"PLUGIN_RUNTIME_UNAVAILABLE");
pluginAssert(!operation.cancelled,"PLUGIN_CANCELLED");
const current=this.options.participant(voiceToken);pluginAssert(current&&this.options.registry.policy(id)?.revision===policy.revision&&this.scopeKey(policy,current)===scopeKey,"PLUGIN_CONTEXT_CHANGED");
pluginAssert([...this.sessions.values()].filter(app=>app.voiceToken===voiceToken).length<8&&this.sessions.size<800,"PLUGIN_LIMIT");
const app:AppSession={id:randomBytes(32).toString("base64url"),publicId:randomUUID(),participantId:current.id,openKey,pluginId:id,revision:policy.revision,voiceToken,scopeKey,origin,theme:preferences.theme==="dark"?"dark":"light",language:["zh","en","de","ru","ja"].includes(String(preferences.language))?preferences.language as PluginAppContext["language"]:"en",lastActivity:Date.now(),lastContext:"",streams:new Set(),connections:new Set()};
operation.appId=app.id;
this.sessions.set(app.id,app);entry.process?.event("participantJoined",this.requestContext(app,current));
return {id:app.id,url:`${origin}/apps/${app.id}/${policy.manifest.client.entry}`,manifest:policy.manifest};
}
authorizeApp(id:string,voiceToken:string):boolean{return this.sessions.get(id)?.voiceToken===voiceToken;}
cancelOpen(voiceToken:string,openId:string):void{
pluginAssert(/^[a-zA-Z0-9-]{8,80}$/.test(openId));const key=voiceToken+":"+openId,operation=this.openings.get(key);
if(operation){operation.cancelled=true;if(operation.appId)this.closeApp(operation.appId);return;}
pluginAssert(this.options.participant(voiceToken),"PLUGIN_NOT_CONNECTED");
pluginAssert([...this.openings.keys()].filter(item=>item.startsWith(voiceToken+":")).length<64&&this.openings.size<8192,"PLUGIN_LIMIT");
this.openings.set(key,{cancelled:true,expires:Date.now()+90000});
}
appearance(id:string,voiceToken:string,input:unknown):void{
pluginAssert(this.authorizeApp(id,voiceToken)&&pluginRecord(input),"PLUGIN_NOT_OPEN");const app=this.sessions.get(id)!;
if(input.theme==="light"||input.theme==="dark")app.theme=input.theme;
if(["zh","en","de","ru","ja"].includes(String(input.language)))app.language=input.language as PluginAppContext["language"];
this.publishContext(app);
}
closeApp(id:string,code="PLUGIN_CLOSED"):void{
const app=this.sessions.get(id);if(!app)return;this.sessions.delete(id);
const opening=this.openings.get(app.openKey);if(opening){opening.cancelled=true;opening.appId=undefined;opening.expires=Date.now()+90000;}
for(const response of app.streams){if(!response.destroyed)response.end(`event: closed\ndata: ${JSON.stringify({code})}\n\n`);}
for(const close of app.connections){try{close();}catch{}}
this.entries.get(app.pluginId)?.process?.event("participantLeft",{appId:app.publicId,selfId:app.participantId,scopeKey:app.scopeKey});
}
private revokePlugin(id:string,code:string):void{for(const app of [...this.sessions.values()])if(app.pluginId===id)this.closeApp(app.id,code);}
private context(app:AppSession,participant:PluginParticipant):PluginAppContext{
const policy=this.options.registry.policy(app.pluginId)!;
const base=`${app.origin}/apps/${app.id}`;
return {...this.requestContext(app,participant),plugin:policy.manifest,connection:{target:participant.target,channelId:participant.channelId,members:participant.members},config:policy.settings.config,theme:app.theme,language:app.language,
serverUrl:policy.manifest.server?`${base}/server`:null,socketUrl:policy.manifest.server?`${base.replace(/^http/,"ws")}/server`:null,contextUrl:`${base}/_runtime/context`};
}
private requestContext(app:AppSession,participant:PluginParticipant):PluginRequestContext{
return {apiVersion:2,appId:app.publicId,self:{id:participant.id,nickname:participant.nickname,...(participant.uid?{uid:participant.uid}:{})},connection:{target:participant.target,channelId:participant.channelId},scope:{type:this.options.registry.policy(app.pluginId)!.settings.scope,key:app.scopeKey}};
}
private validate(app:AppSession):PluginParticipant|null{
const policy=this.options.registry.policy(app.pluginId),participant=this.options.participant(app.voiceToken);
try{return policy&&policy.revision===app.revision&&participant&&this.scopeKey(policy,participant)===app.scopeKey?participant:null;}catch{return null;}
}
private publishContext(app:AppSession):void{
const participant=this.validate(app);if(!participant){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");return;}
const context=this.context(app,participant),json=JSON.stringify(context);
if(json!==app.lastContext){app.lastContext=json;for(const response of app.streams)if(!response.destroyed)response.write(`event: context\ndata: ${json}\n\n`);this.entries.get(app.pluginId)?.process?.event("contextChanged",{...this.requestContext(app,participant),connection:context.connection});}
}
private reconcileSessions():void{
for(const [key,operation]of this.openings)if(!operation.appId&&operation.expires<Date.now())this.openings.delete(key);
for(const app of [...this.sessions.values()]){
if(!this.validate(app)||(!app.streams.size&&Date.now()-app.lastActivity>90000)){this.closeApp(app.id,"PLUGIN_CONTEXT_CHANGED");continue;}
this.publishContext(app);for(const response of app.streams){if(response.destroyed)app.streams.delete(response);else if(response.writableLength>256*1024){response.destroy();app.streams.delete(response);}else response.write(": keepalive\n\n");}
}
}
private locate(request:IncomingMessage):{app:AppSession;route:string;query:string;participant:PluginParticipant}{
const url=new URL(request.url??"/","http://runtime.invalid"),match=/^\/apps\/([A-Za-z0-9_-]{43})\/(.*)$/.exec(url.pathname);
pluginAssert(match,"PLUGIN_NOT_OPEN");const app=this.sessions.get(match[1]);pluginAssert(app,"PLUGIN_NOT_OPEN");
const participant=this.validate(app);pluginAssert(participant,"PLUGIN_CONTEXT_CHANGED");app.lastActivity=Date.now();
return {app,route:decodeURIComponent(match[2]),query:url.search,participant};
}
private async handle(request:IncomingMessage,response:ServerResponse):Promise<void>{
response.setHeader("referrer-policy","no-referrer");response.setHeader("x-content-type-options","nosniff");response.setHeader("cache-control","no-store");
try{
const {app,route,query,participant}=this.locate(request),entry=this.entries.get(app.pluginId);pluginAssert(entry?.directory,"PLUGIN_RUNTIME_UNAVAILABLE");
if(route.startsWith("server/")||route==="server"){this.proxy(request,response,app,participant,"/"+route.slice(7)+query);return;}
pluginAssert(request.method==="GET"||request.method==="HEAD","PLUGIN_METHOD_NOT_ALLOWED");
if(route==="_runtime/context"){response.setHeader("content-type","application/json");response.end(JSON.stringify(this.context(app,participant)));return;}
if(route==="_runtime/events"){
pluginAssert(app.streams.size<4,"PLUGIN_LIMIT");response.writeHead(200,{"content-type":"text/event-stream","x-accel-buffering":"no"});response.flushHeaders();app.streams.add(response);
response.write(`event: context\ndata: ${JSON.stringify(this.context(app,participant))}\n\n`);response.once("close",()=>app.streams.delete(response));return;
}
if(route==="_runtime/sdk.js"){response.setHeader("content-type","text/javascript; charset=utf-8");response.end(applicationSdk(this.context(app,participant),`${app.origin}/apps/${app.id}/_runtime/events`,app.id));return;}
pluginAssert(route.startsWith("client/")&&pluginPath(route),"PLUGIN_ASSET_NOT_FOUND");
pluginAssert(this.validate(app)&&entry.assets.has(route),"PLUGIN_ASSET_NOT_FOUND");
const file=path.resolve(entry.directory,route);pluginAssert(file.startsWith(entry.directory+path.sep),"PLUGIN_ASSET_NOT_FOUND");
response.setHeader("content-type",contentTypes[path.extname(route)]??"application/octet-stream");
if(route===entry.policy.manifest.client.entry){
let html=await readFile(file,"utf8");pluginAssert(this.validate(app),"PLUGIN_CONTEXT_CHANGED");
const script=`<script src="/apps/${app.id}/_runtime/sdk.js"></script>`;
if(/<head(?:\s[^>]*)?>/i.test(html))html=html.replace(/<head(?:\s[^>]*)?>/i,head=>head+script);
else if(/<!doctype[^>]*>/i.test(html))html=html.replace(/<!doctype[^>]*>/i,doctype=>doctype+script);
else html=script+html;
response.end(request.method==="HEAD"?undefined:html);return;
}
if(request.method==="HEAD"){response.end();return;}
const stream=createReadStream(file);stream.once("error",()=>{if(!response.headersSent)response.writeHead(404);response.end();});response.once("close",()=>stream.destroy());stream.pipe(response);
}catch(error){if(!response.headersSent)response.writeHead(error instanceof PluginError&&error.code==="PLUGIN_ASSET_NOT_FOUND"?404:403,{"content-type":"application/json"});response.end(JSON.stringify({error:error instanceof PluginError?error.code:"PLUGIN_RUNTIME_FAILED"}));}
}
private headers(request:IncomingMessage,app:AppSession,participant:PluginParticipant):Record<string,string|string[]>{
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");
const headers:Record<string,string|string[]>={};
for(const [key,value]of Object.entries(request.headers))if(value!==undefined&&!['cookie','authorization','host','connection','proxy-authorization'].includes(key)&&!key.startsWith('x-webspeak-'))headers[key]=value;
const context=this.requestContext(app,participant);
headers['x-webspeak-runtime']=worker.token;headers['x-webspeak-context']=Buffer.from(JSON.stringify(context),'utf8').toString('base64url');return headers;
}
private proxy(request:IncomingMessage,response:ServerResponse,app:AppSession,participant:PluginParticipant,route:string):void{
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port,"PLUGIN_BACKEND_UNAVAILABLE");pluginAssert(app.connections.size<32,"PLUGIN_BUSY");
const upstream=httpRequest({hostname:"127.0.0.1",port:worker.port,path:route,method:request.method,headers:this.headers(request,app,participant)},incoming=>{
if(response.destroyed||!this.sessions.has(app.id)){incoming.destroy();return;}
const headers={...incoming.headers};delete headers['set-cookie'];response.writeHead(incoming.statusCode??502,headers);incoming.once('error',()=>response.destroy());incoming.pipe(response);
});
const close=()=>{upstream.destroy();if(!response.writableFinished)response.destroy();};app.connections.add(close);
upstream.setTimeout(120000,()=>upstream.destroy());upstream.once('error',()=>{if(!response.headersSent)response.writeHead(502,{'content-type':'application/json'});response.end('{"error":"PLUGIN_BACKEND_UNAVAILABLE"}');});
response.once('close',()=>{app.connections.delete(close);upstream.destroy();});request.once('aborted',close);request.pipe(upstream);
}
private async upgrade(request:IncomingMessage,socket:Socket,head:Buffer):Promise<void>{
try{
const {app,route,query,participant}=this.locate(request);pluginAssert(route==='server'||route.startsWith('server/'),"PLUGIN_NOT_ALLOWED");
const worker=this.entries.get(app.pluginId)?.process;pluginAssert(worker?.port&&app.connections.size<32,"PLUGIN_BACKEND_UNAVAILABLE");
const headers=this.headers(request,app,participant);headers.connection='Upgrade';headers.upgrade=String(request.headers.upgrade??'websocket');
const upstream=httpRequest({hostname:'127.0.0.1',port:worker.port,path:'/'+route.slice(7)+query,headers});
const close=()=>{upstream.destroy();socket.destroy();};app.connections.add(close);socket.once('close',()=>{app.connections.delete(close);upstream.destroy();});
upstream.once('upgrade',(response,peer,upstreamHead)=>{
socket.write(`HTTP/1.1 ${response.statusCode??101} Switching Protocols\r\n`);for(const [key,value]of Object.entries(response.headers))if(value!==undefined&&key!=='set-cookie')socket.write(`${key}: ${Array.isArray(value)?value.join(', '):value}\r\n`);socket.write('\r\n');
if(head.length)peer.write(head);if(upstreamHead.length)socket.write(upstreamHead);peer.pipe(socket);socket.pipe(peer);peer.once('error',()=>socket.destroy());socket.once('error',()=>peer.destroy());
app.connections.delete(close);const closePeer=()=>{peer.destroy();socket.destroy();};app.connections.add(closePeer);socket.once('close',()=>{app.connections.delete(closePeer);peer.destroy();});peer.once('close',()=>socket.destroy());
});
upstream.once('error',close);upstream.once('response',()=>close());upstream.end();
}catch{socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');}
}
async close():Promise<void>{
if(this.closed)return;this.closed=true;this.listening=false;clearInterval(this.timer);this.options.registry.listeners.delete(this.changed);
for(const app of [...this.sessions.values()])this.closeApp(app.id);
this.openings.clear();
await Promise.allSettled([...this.entries.values()].map(entry=>entry.process?.close()));
await Promise.allSettled(this.queues.values());await Promise.allSettled([...this.entries.values()].map(entry=>this.stopEntry(entry)));this.entries.clear();
for(const socket of this.sockets)socket.destroy();await new Promise<void>(resolve=>this.server.close(()=>resolve()));
}
}
function normalizeOrigin(value:unknown):string{
pluginAssert(typeof value==='string'&&value.length<=300);if(!value.trim())return '';
const url=new URL(value.trim());pluginAssert(['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash&&url.pathname==='/');
pluginAssert(url.protocol==='https:'||['localhost','127.0.0.1','[::1]'].includes(url.hostname),'PLUGIN_HTTPS_REQUIRED');return url.origin;
}
function applicationSdk(context:PluginAppContext,eventsUrl:string,id:string):string{
// No expression evaluator, business RPC, shared rooms, dependency loader, or network allowlist.
return `(()=>{let context=${JSON.stringify(context).replace(/</g,'\\u003c')};const listeners=new Set(),closed=new AbortController();document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;
const events=new EventSource(${JSON.stringify(eventsUrl)});events.addEventListener('context',event=>{try{context=JSON.parse(event.data);document.documentElement.dataset.theme=context.theme;document.documentElement.lang=context.language;for(const fn of listeners){try{fn(context)}catch{}}}catch{}});
events.addEventListener('closed',()=>{closed.abort();events.close();parent.postMessage({type:'webspeak-app-closed',id:${JSON.stringify(id)}},'*')});
window.webspeak=Object.freeze({apiVersion:2,ready:Promise.resolve(context),getContext:()=>context,onContextChange(fn){listeners.add(fn);return()=>listeners.delete(fn)},signal:closed.signal});
addEventListener('pagehide',()=>{closed.abort();events.close();listeners.clear()},{once:true});})();`;
}
+78
View File
@@ -0,0 +1,78 @@
import { createHash } from "node:crypto";
import { PluginRegistry } from "./registry.js";
import { PLUGIN_STORE_INDEX, PLUGIN_STORE_REPOSITORY, PLUGIN_LIMIT_BYTES, pluginAssert, pluginId, pluginRecord,
parsePluginManifest, parsePluginPackage, PluginError, type PluginCatalog, type PluginStoreEntry } from "../shared/plugins.js";
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
const SHA = /^[a-f0-9]{64}$/;
export class PluginStore {
constructor(private readonly fetcher: typeof fetch = fetch) {}
private async read(url: string, limit: number): Promise<Buffer> {
pluginAssert(new URL(url).origin === "https://raw.githubusercontent.com");
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000);
try {
const response = await this.fetcher(url, { signal: controller.signal, redirect: "error", credentials: "omit" });
pluginAssert(response.ok && response.body, "PLUGIN_STORE_UNAVAILABLE");
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(); throw new PluginError("PLUGIN_TOO_LARGE"); }
chunks.push(part.value);
}
} finally { reader.releaseLock(); }
return Buffer.concat(chunks, size);
} catch (error) { if (error instanceof PluginError) throw error; throw new PluginError("PLUGIN_STORE_UNAVAILABLE"); }
finally { clearTimeout(timer); }
}
private async json(url: string): Promise<unknown> {
try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await this.read(url, 128 * 1024))); }
catch (e) { if (e instanceof PluginError) throw e; throw new PluginError("PLUGIN_INVALID"); }
}
private async sources() {
const root = await this.json(PLUGIN_STORE_INDEX);
pluginAssert(pluginRecord(root) && root.schemaVersion === 2 && Array.isArray(root.plugins) && root.plugins.length <= 50,"PLUGIN_CATALOG_UNSUPPORTED");
const seen = new Set<string>();
return root.plugins.map(item => {
pluginAssert(pluginRecord(item) && pluginId(item.id) && !seen.has(item.id)); seen.add(item.id);
pluginAssert(typeof item.repository === "string" && /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}$/.test(item.repository) && !item.repository.endsWith(".git"));
const metadataPath = item.metadataPath ?? "plugin.json";
pluginAssert(typeof metadataPath === "string" && /^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.json$/.test(metadataPath) && metadataPath.length <= 160);
return { id: item.id, repository: item.repository, metadataPath };
});
}
private async metadata(source: { id: string; repository: string; metadataPath: string }) {
const rawBase = source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/");
const value = await this.json(`${rawBase}/HEAD/${source.metadataPath}`);
pluginAssert(pluginRecord(value) && pluginRecord(value.package));
const manifest = parsePluginManifest(value.manifest), pack = value.package;
pluginAssert(manifest.id === source.id && typeof pack.ref === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/.test(pack.ref));
pluginAssert(typeof pack.path === "string" && /^(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+\.wplugin$/.test(pack.path) && pack.path.length <= 160);
pluginAssert(typeof pack.sha256 === "string" && SHA.test(pack.sha256));
const descriptor = { ref: pack.ref, path: pack.path, sha256: pack.sha256 };
return { manifest, descriptor, revision: hash({ source, manifest, package: descriptor }), url: `${rawBase}/${pack.ref}/${pack.path}` };
}
async list(): Promise<PluginCatalog> {
const sources = await this.sources(), entries = new Array<PluginStoreEntry>(sources.length); let cursor = 0;
await Promise.all(Array.from({ length: Math.min(4, sources.length) }, async () => {
while (cursor < sources.length) { const i = cursor++, source = sources[i];
try { const meta = await this.metadata(source); entries[i] = { ...source, manifest: meta.manifest, revision: meta.revision, error: null }; }
catch (e) { entries[i] = { ...source, manifest: null, revision: "", error: e instanceof PluginError ? e.code : "PLUGIN_STORE_UNAVAILABLE" }; }
}
}));
return { repository: PLUGIN_STORE_REPOSITORY, entries };
}
async install(registry: PluginRegistry, input: unknown) {
pluginAssert(pluginRecord(input) && pluginId(input.id) && typeof input.revision === "string" && SHA.test(input.revision));
pluginAssert(input.installedRevision === null || typeof input.installedRevision === "string" && SHA.test(input.installedRevision));
const source = (await this.sources()).find(s => s.id === input.id); pluginAssert(source, "PLUGIN_NOT_FOUND");
const metadata = await this.metadata(source); pluginAssert(metadata.revision === input.revision, "PLUGIN_CHANGED");
const bytes = await this.read(metadata.url, PLUGIN_LIMIT_BYTES);
pluginAssert(createHash("sha256").update(bytes).digest("hex") === metadata.descriptor.sha256, "PLUGIN_CHECKSUM");
let value: unknown;
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new PluginError("PLUGIN_INVALID"); }
const pack = parsePluginPackage(value); pluginAssert(JSON.stringify(pack.manifest) === JSON.stringify(metadata.manifest), "PLUGIN_PACKAGE_MISMATCH");
return registry.install(pack, input.installedRevision as string | null);
}
}
+80
View File
@@ -0,0 +1,80 @@
/** Child-process entrypoint. Reviewed applications run normal Node.js, not a JS sandbox. */
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { type Socket } from "node:net";
import { EventEmitter } from "node:events";
import { pathToFileURL } from "node:url";
import type { JsonValue, PluginRequestContext } from "../shared/plugins.js";
interface RequestContext extends IncomingMessage { webspeak?: PluginRequestContext }
interface Application {
handle(request: RequestContext, response: ServerResponse): unknown;
upgrade?(request: RequestContext, socket: Socket, head: Buffer): unknown;
stop?(): unknown;
}
interface Initialization { type: "initialize"; entry: string; dataDir: string; config: JsonValue; publicConfig: JsonValue; token: string }
const events = new EventEmitter(), abort = new AbortController(), sockets = new Set<Socket>();
let application: Application | undefined, initialized = false, stopping = false, secret = "";
const server = createServer((request: RequestContext, response) => {
if (!authorize(request)) { response.writeHead(403).end(); return; }
Promise.resolve().then(() => application!.handle(request, response)).catch(() => {
if (!response.headersSent) response.writeHead(500, { "content-type": "application/json" });
if (!response.destroyed) response.end('{"error":"PLUGIN_HANDLER_FAILED"}');
});
});
function authorize(request: RequestContext): boolean {
if (!secret || request.headers["x-webspeak-runtime"] !== secret) return false;
delete request.headers["x-webspeak-runtime"];
try {
const context = JSON.parse(Buffer.from(String(request.headers["x-webspeak-context"]), "base64url").toString("utf8"));
if (context?.apiVersion !== 2 || !context.self?.id || !context.scope?.key) return false;
request.webspeak = context;
delete request.headers["x-webspeak-context"];
return true;
} catch { return false; }
}
server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); });
server.on("upgrade", (request: RequestContext, socket: Socket, head) => {
if (!authorize(request) || !application?.upgrade) { socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n"); return; }
Promise.resolve().then(() => application!.upgrade!(request, socket, head)).catch(() => socket.destroy());
});
server.on("error", () => { process.send?.({ type: "failed", code: "PLUGIN_LISTEN_FAILED" }); void stop(); });
async function initialize(value: Initialization): Promise<void> {
if (initialized) return;
initialized = true; secret = value.token;
try {
const module = await import(pathToFileURL(value.entry).href);
if (typeof module.default !== "function") throw new Error("Expected a default activation function");
const result = await module.default({
dataDir: value.dataDir, config: value.config, publicConfig: value.publicConfig, events, signal: abort.signal,
log(level: string, message: unknown) { process.send?.({ type: "log", level, message: String(message).slice(0, 1000) }); },
});
if (stopping) return;
application = typeof result === "function" ? { handle: result } : result;
if (!application || typeof application.handle !== "function") throw new Error("Expected a Node HTTP request handler");
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (address && typeof address !== "string") process.send?.({ type: "ready", port: address.port });
});
} catch { process.send?.({ type: "failed", code: "PLUGIN_START_FAILED" }); await stop(); }
}
async function stop(): Promise<void> {
if (stopping) return;
stopping = true; abort.abort();
for (const socket of sockets) socket.destroy();
server.close();
try { await application?.stop?.(); } catch { /* Disposal cannot keep the worker alive. */ }
events.removeAllListeners();
if (process.connected) process.disconnect();
process.exit(0);
}
process.on("message", (value: unknown) => {
if (!value || typeof value !== "object" || !("type" in value)) return;
if (value.type === "initialize") void initialize(value as Initialization);
else if (value.type === "stop") void stop();
else if (value.type === "event" && "name" in value && typeof value.name === "string" && !stopping) {
try { events.emit(value.name, "payload" in value ? value.payload : undefined); } catch { /* App event failure is local to this worker. */ }
}
});
process.once("disconnect", () => void stop());
process.once("SIGTERM", () => void stop());
process.once("SIGINT", () => void stop());
+19
View File
@@ -12,6 +12,25 @@ const resolved = (...addresses: string[]) => async () => addresses.map((address)
family: address.includes(":") ? 6 : 4,
}));
test("open targets classify equivalent IPv6 spellings and embedded IPv4 before DNS pinning", async () => {
const blocked = ["0:0:0:0:0:0:0:1", "0::1", "0:1234::1", "0:0:0:0:0:0:0:0", "0:0:0:0:0:ffff:a00:1",
"::ffff:7f00:1", "0::ffff:192.168.1.1", "0:0:0:0:0:0:7f00:1", "fe80::1%1",
"64:ff9b::808:808", "64:ff9b:1:abcd::1", "2002:0808:0808::1", "2001:0:4136:e378::1",
"0100:0000:0:0:ffff::1", "100:0:0:1::1", "2001:0db8::1", "3fff::1"];
for (const host of blocked) {
assert.equal(isRestrictedAddress(host), true, host);
await assert.rejects(resolveSafeOpenTarget({ host, port: 9987 }), { name: "UnsafeTeamSpeakTargetError" });
await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
resolveSrv: async () => [], lookup: resolved("8.8.8.8", host),
}), { name: "UnsafeTeamSpeakTargetError" });
}
for (const host of ["0:0:0:0:0:ffff:808:808", "::ffff:1.1.1.1", "2001:4860:0000:0:0:0:0:8888",
"64:ff9b:2::1", "100:0:1::1", "2001:db9::1", "2003::1"]) {
assert.equal(isRestrictedAddress(host), false, host);
assert.deepEqual(await resolveSafeOpenTarget({ host, port: 9987 }), { host, port: 9987 });
}
});
test("Mihomo fake-IP DNS answers remain connectable without allowing literal or mixed fake-IP targets", async () => {
const target = { host: "ts.twilightly.top", port: 9987 };
+14 -11
View File
@@ -1,4 +1,4 @@
import { isIP } from "node:net";
import { BlockList, isIP, SocketAddress } from "node:net";
import { lookup, resolveSrv } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
@@ -108,25 +108,28 @@ export async function isSafeOpenTargetForPrefill(
}
}
const restrictedIpv6 = new BlockList();
// Match address bits, not textual compression or the case/width of hex groups.
for (const [network, prefix] of [
["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
["fec0::", 10], ["ff00::", 8],
] as const) restrictedIpv6.addSubnet(network, prefix, "ipv6");
export function isRestrictedAddress(address: string): boolean {
// Scoped destinations refer to a gateway-local interface and are never public targets.
if (address.includes("%")) return true;
const version = isIP(address);
if (version === 4) return isRestrictedIpv4(address);
if (version !== 6) return true;
const normalized = address.toLocaleLowerCase();
if (normalized === "::" || normalized === "::1") return true;
const normalized = new SocketAddress({ address, family: "ipv6" }).address;
if (normalized.startsWith("::ffff:")) {
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
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;
return restrictedIpv6.check(normalized, "ipv6");
}
function isMihomoFakeIpv4(address: string): boolean {
+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) => {
+1 -1
View File
@@ -110,7 +110,7 @@ export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempt
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
const text = error instanceof Error ? error.message : String(error);
const lower = text.toLocaleLowerCase();
const lower = text.toLowerCase();
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
@@ -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");
}
}
+68 -14
View File
@@ -3,7 +3,7 @@ import { createServer as createHttpsServer } from "node:https";
import { createServer as createHttpServer } from "node:http";
import { readFileSync } from "node:fs";
import path from "node:path";
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
@@ -12,11 +12,15 @@ 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";
import type { PluginRegistry } from "../plugins/registry.js";
import { PluginRuntime } from "../plugins/runtime.js";
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
export interface WebServerOptions {
port: number;
@@ -27,6 +31,8 @@ export interface WebServerOptions {
voiceBridgeOptions: VoiceBridgeOptions;
adminService: AdminService;
skinRegistry?: SkinRegistry;
pluginRegistry?: PluginRegistry;
pluginRuntime?: { port?: number; host?: string; publicOrigin?: string; maxWorkers?: number };
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
@@ -54,11 +60,17 @@ export function createWebServer(options: WebServerOptions): WebServer {
server = createHttpServer(app);
}
app.use(express.json({ limit: "100kb" }));
const json = express.json({ limit: "100kb" });
app.use((request, response, next) => request.path.startsWith("/api/admin/plugins") ? next() : json(request, response, next));
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
const pluginRuntime = options.pluginRegistry ? new PluginRuntime({ registry: options.pluginRegistry, participant: token => voiceBridge.resolvePluginParticipant(token), logger,
...options.pluginRuntime, ...(options.certDir ? { tls: { cert: readFileSync(path.join(options.certDir,"cert.pem")), key: readFileSync(path.join(options.certDir,"key.pem")) } } : {}) }) : undefined;
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
const adminSessions = new AdminSessionStore();
const joinRateLimiter = new JoinRateLimiter();
const trustedProxies = createTrustedProxies(options.voiceBridgeOptions.trustedProxies);
const clientIp = (request: express.Request) => resolveClientIp(request, trustedProxies);
const startedAt = Date.now();
const healthHandler: express.RequestHandler = (_request, response) => {
@@ -159,7 +171,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
if (!joinRateLimiter.allow(clientIp(request))) {
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
return;
}
@@ -171,7 +183,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 +247,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 });
});
@@ -256,9 +284,12 @@ export function createWebServer(options: WebServerOptions): WebServer {
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
terminateSession: (id) => voiceBridge.terminateSession(id),
skinRegistry: options.skinRegistry,
pluginRegistry: options.pluginRegistry,
pluginRuntime,
version: options.version,
logFile: options.logFile,
startedAt,
clientIp,
}));
// Serve static frontend
@@ -272,15 +303,18 @@ export function createWebServer(options: WebServerOptions): WebServer {
voiceBridge.attach(server);
return {
start(): Promise<void> {
return new Promise((resolve) => {
server.listen(options.port, () => {
logger.info({ port: options.port }, "Web server started");
resolve();
});
async start(): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(options.port, () => { server.off("error", reject); logger.info({ port: options.port }, "Web server started"); resolve(); });
});
if (pluginRuntime) {
try { await pluginRuntime.start(); }
catch { logger.warn({code:"PLUGIN_RUNTIME_UNAVAILABLE"},"Plugin application origin could not start; voice and administration remain available"); }
}
},
async stop(): Promise<void> {
await pluginRuntime?.close();
await voiceBridge.shutdown();
adminSessions.clear();
return new Promise((resolve) => {
@@ -298,6 +332,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);
}
+73 -4
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,14 +32,48 @@ 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);
}, encoder, () => state.now, () => 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 flooding is bounded before encoding while real-time, jitter and recovery remain usable", t => {
const realtime = fixture();
for (let i = 0; i < 1_000; i++) { realtime.state.now = i * 20; realtime.transport.receivePcm(Buffer.alloc(1_920)); }
assert.equal(realtime.encoded.length, 1_000);
const flood = fixture();
t.mock.method(flood.encoder, "encode", () => { flood.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
for (let i = 0; i < 1_000; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
assert.ok(flood.encoded.length <= 50);
assert.equal(flood.audio.ingressDroppedFrames, 1_000 - flood.encoded.length);
assert.equal(flood.warnings.filter(w => w.code === "AUDIO_RATE_EXCEEDED").length, 1);
assert.equal(flood.notices.length, 0);
flood.state.now = 10_000;
const before = flood.forwarded.length;
for (let i = 0; i < 50; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
assert.equal(flood.forwarded.length - before, 50, "one-second backlog after a stall is allowed");
const recovered = flood.forwarded.length;
for (let i = 1; i <= 100; i++) { flood.state.now = 10_000 + i * 20; flood.transport.receivePcm(Buffer.alloc(1_920)); }
assert.equal(flood.forwarded.length - recovered, 100, "flood drops do not lock out subsequent real-time audio");
});
test("PCM budget uses a separate monotonic clock and cannot refill twice after a clock rollback", t => {
const f = fixture();
t.mock.method(f.encoder, "encode", () => { f.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
for (let i = 0; i < 50; i++) f.transport.receivePcm(Buffer.alloc(1_920));
f.state.now = -1_000;
f.transport.receivePcm(Buffer.alloc(1_920));
f.state.now = 0;
f.transport.receivePcm(Buffer.alloc(1_920));
assert.equal(f.encoded.length, 50);
f.state.now = 100;
for (let i = 0; i < 20; i++) f.transport.receivePcm(Buffer.alloc(1_920));
assert.equal(f.encoded.length, 56);
});
test("PCM framing preserves codec, whisper routing and timing counters", () => {
const f = fixture();
f.transport.receivePcm(Buffer.alloc(1_920));
@@ -49,19 +92,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() {} };
+74 -10
View File
@@ -1,4 +1,6 @@
import { WebSocket } from "ws";
import { performance } from "node:perf_hooks";
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 +9,12 @@ 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;
const PCM_BURST_FRAMES = 50; // One second of buffered 20 ms capture after a stall.
const PCM_FRAMES_PER_MS = 60 / 1_000; // 50 fps capture plus 20% scheduling headroom.
export interface VoiceEncoder {
encode(frame: Buffer): Buffer;
@@ -17,6 +25,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 +39,16 @@ 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;
private pcmTokens = PCM_BURST_FRAMES;
private pcmRefilledAt: number | null = null;
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now,
private readonly rateClock: () => number = performance.now.bind(performance)) {
this.encoder = encoder;
this.logger = options.logger ?? null;
}
private isCurrent(): boolean {
@@ -64,25 +80,72 @@ 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;
}
const now = this.rateClock();
if (this.pcmRefilledAt !== null) {
this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
}
this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
if (this.pcmTokens < 1) {
stats.ingressDroppedFrames++;
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
}
return;
}
this.pcmTokens--;
this.recordIngress();
const startedAt = this.clock();
let encoded: Buffer;
@@ -150,6 +213,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");
+1 -1
View File
@@ -99,7 +99,7 @@ export async function probeTeamSpeak(
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
if (error instanceof TeamSpeakProbeError) return error;
const normalized = normalizeTeamSpeakError(error);
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLowerCase();
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
}
+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) {
+160
View File
@@ -0,0 +1,160 @@
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, asClientDBID, 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), databaseID: asClientDBID(BigInt(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('partial SDK records preserve unknown status and channel descriptions without querying', async () => {
const { sdk, native } = fixture();
const { uid: _uid, serverGroups: _groups, isAway: _away, awayMessage: _message,
isInputMuted: _input, isOutputMuted: _output, isChannelCommander: _commander, ...partial } = member();
native.view.clients.set(partial.id, partial);
const { description: _description, ...room } = channel(); native.view.channels.set(room.id, room);
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: 'Member 1', uid: '', serverGroups: [], channelID: 1n, type: 0 }]);
assert.equal((await sdk.listDirectoryChannels())[0].description, undefined);
assert.equal(await sdk.getClientAvatarMetadata(1), null);
assert.deepEqual(native.queries, []);
});
test('SDK end-of-speech markers are not sent into the audio decoder or browser transport', () => {
const { sdk, native } = fixture(), received: unknown[] = [];
sdk.on('voiceData', frame => received.push(frame));
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data: new Uint8Array() });
assert.deepEqual(received, []);
const data = Uint8Array.of(1, 2);
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data });
assert.deepEqual(received, [{ clientId: 1, codec: 4, data }]);
});
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);
});
+342
View File
@@ -0,0 +1,342 @@
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) => {
// beta.20+ reports an empty payload for end-of-speech, not an Opus frame.
if (!isCurrent() || event.data.byteLength === 0) 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 } : {}),
};
}
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff. Show more