Compare commits

...
84 Commits
Author SHA1 Message Date
illusia 694f864d36 fix: include ca certificates in docker build 2026-09-04 08:38:06 +08:00
illusia 512854ab9f fix: pin sdk lockfile for reproducible installs 2026-09-04 08:31:48 +08:00
illusia b298496911 fix: make sdk release preparation deterministic 2026-09-04 08:27:28 +08:00
illusia b6367e2645 release: prepare v0.1.5 2026-09-04 08:18:56 +08:00
illusia b0fa4bf5d0 fix: make theme toggle respond on first click 2026-09-04 08:05:19 +08:00
illusia cb3dbe4ca4 fix: preserve remembered browser identity on exit 2026-09-03 23:40:38 +08:00
illusia 96ba467d52 release: prepare v0.1.4 2026-09-03 17:07:35 +08:00
illusia 20fdcc7b1d fix: fit welcome header actions on narrow screens 2026-09-03 16:59:28 +08:00
illusia feea39a81c feat: add bilibili profile link 2026-09-03 16:57:35 +08:00
illusia 69d1653f99 feat: add home link to admin login 2026-09-03 16:53:39 +08:00
illusia a18a5b4920 fix: wrap long admin logs on desktop 2026-09-03 16:46:40 +08:00
illusia 343dd84132 fix: wrap long mobile admin logs 2026-09-03 16:44:52 +08:00
illusia a037962cc1 fix: let mobile admin pages scroll naturally 2026-09-03 16:40:22 +08:00
illusia 680ce246fd fix: compact server settings layout 2026-09-03 16:36:52 +08:00
illusia baa09ad38c feat: customize and lock WebRTC media ports 2026-09-03 16:28:49 +08:00
illusia 767bdea018 fix: show channel broadcast messages 2026-09-03 16:08:51 +08:00
illusia 83a8fd0d5a fix: enforce WebRTC microphone mute at gateway 2026-09-03 15:25:34 +08:00
illusia e14ddc9465 fix: filter silent WebRTC uplink frames 2026-09-03 15:16:20 +08:00
illusia 7feb97d77d fix: keep WebRTC playback on native media output 2026-09-03 14:52:59 +08:00
illusia 434360cda9 fix: recover WebRTC playback and speaker state 2026-09-03 14:45:44 +08:00
illusia d0a2e9edc0 fix: make WebRTC playback reliable 2026-09-03 14:28:47 +08:00
illusia 61f66ab319 docs: simplify user-facing README 2026-09-03 12:54:11 +08:00
illusia e79ad66e1f docs: document WebRTC public UDP setup 2026-09-03 11:59:03 +08:00
illusia 522fa8f409 fix: remove obsolete WebRTC error labels 2026-09-03 11:02:42 +08:00
illusia c7def28a8f feat: make WebRTC media service self-contained 2026-09-03 10:56:39 +08:00
illusia d6c8ccb73f fix(ui): remove real IP from WebRTC placeholder 2026-09-03 08:01:08 +08:00
illusia ab5851935c merge: admin-managed WebRTC settings 2026-09-03 07:52:21 +08:00
illusia 5c3d1b7e5d feat(admin): manage WebRTC settings from console 2026-09-03 07:52:13 +08:00
illusia ecff06e9a1 docs: record SDK migration in v0.1.3 2026-09-03 07:32:11 +08:00
illusia 9c3f09b55b merge: release v0.1.3 2026-09-03 07:28:29 +08:00
illusia b42c455e7f release: prepare v0.1.3 2026-09-03 07:28:14 +08:00
illusia 40ea30b9e2 fix(audio): cleanly fall back from WebRTC 2026-09-03 01:29:34 +08:00
illusia a4cf5b5359 fix(audio): use OpusEncoder decoder API 2026-09-03 01:23:34 +08:00
illusia 1d41d5a3e7 fix(audio): honor negotiated WebRTC Opus payload 2026-09-03 01:17:01 +08:00
illusia 46b190a913 fix(audio): avoid duplicate WebRTC playback 2026-09-03 01:02:18 +08:00
illusia 8abd2d6228 feat(audio): add experimental WebRTC transport 2026-09-03 00:47:51 +08:00
illusia 7ff6836a7e fix(audio): tighten gateway voice backpressure 2026-09-03 00:23:16 +08:00
illusia a6187c18af chore(audio): attribute egress frames by client 2026-09-03 00:19:45 +08:00
illusia 8ab2fbe8ea fix(audio): move capture framing to audio worklet 2026-09-03 00:13:48 +08:00
illusia 3e7674c94f chore(audio): capture sampled flow timing 2026-09-03 00:04:17 +08:00
illusia 30c0d09a33 chore(audio): include session flow counters in teardown 2026-09-03 00:01:50 +08:00
illusia d9904fa154 fix(audio): bound realtime voice buffering 2026-09-02 23:56:24 +08:00
illusia afbbd1e2d4 refactor: migrate to maintained TeamSpeak SDK 2026-09-02 23:27:32 +08:00
illusia adca8cc1db docs(deploy): standardize published Docker image flow 2026-09-02 16:26:20 +08:00
illusia 9788e7fa1c release: prepare v0.1.2 2026-09-02 16:11:59 +08:00
illusia 66da7efe4a fix(web): align settings icons on narrow screens 2026-09-02 15:48:39 +08:00
illusia 3fb7000d02 feat(web): add prominent GitHub repository link 2026-09-02 15:35:54 +08:00
illusia 03c95abcf7 docs(deploy): simplify Docker startup and document demo 2026-09-02 12:51:43 +08:00
illusia d2ffbee873 refactor(admin): hide protocol details from users 2026-09-02 10:38:46 +08:00
illusia 413dbaf3a8 docs: record microphone mute update 2026-09-02 08:01:08 +08:00
illusia 9187d2faed fix(web): replace browser ptt with microphone mute 2026-09-02 07:52:54 +08:00
illusia af85a73c7d feat(web): optimize mobile client experience 2026-09-02 06:23:07 +08:00
illusia b3ace7d7b6 release: consolidate final v0.1.1 documentation 2026-09-02 00:13:58 +08:00
illusia 49c8aee795 release: make v0.1.3 publishing reliable 2026-09-02 00:08:12 +08:00
illusia cd6dd69d9b release: prepare v0.1.2 docker and packages 2026-09-02 00:02:20 +08:00
illusia 325c907683 docs: add Chinese community section and release publishing 2026-09-01 23:58:21 +08:00
illusia 41666a5531 docs: separate bilingual navigation and dated changelog 2026-09-01 23:53:04 +08:00
illusia 0732e2df7d docs: align bilingual readme and changelog 2026-09-01 23:48:48 +08:00
illusia d7766497e8 fix complete directory sync for late web clients 2026-09-01 23:32:15 +08:00
illusia aa5c5e687f fix private chat disconnect and member menu 2026-09-01 23:23:47 +08:00
illusia 8a06382cec docs: remove implementation details from readme 2026-09-01 23:12:13 +08:00
illusia 1fe11850b7 docs: rewrite project readme 2026-09-01 23:02:43 +08:00
illusia a5a8648240 fix: keep admin lists inside their cards 2026-09-01 22:54:49 +08:00
illusia 81212b420b fix: keep page scrolling inside view containers 2026-09-01 22:26:32 +08:00
illusia 3ec9ab497a feat: split TeamSpeak address and port inputs 2026-09-01 22:12:37 +08:00
illusia bf1158aff2 fix: complete admin session translations 2026-09-01 21:47:32 +08:00
illusia a4cbcf536f feat: expose audit and update status in operations 2026-09-01 18:28:12 +08:00
illusia 797c5b118a fix: pass package version to admin overview 2026-09-01 18:26:06 +08:00
illusia 6337789afa chore: harden release operations and freeze docs 2026-09-01 18:24:09 +08:00
illusia 87fcd736be feat: add admin operations dashboard 2026-09-01 18:19:18 +08:00
illusia f5bd06fdaf feat: add managed invites and admin diagnostics backend 2026-09-01 18:16:22 +08:00
illusia 96ef77c789 feat: add real TeamSpeak whisper routing 2026-09-01 18:08:07 +08:00
illusia cab7707e51 feat: complete M008 web ux and demo 2026-09-01 17:54:51 +08:00
illusia 277fa9d8fe feat: complete M007 audio system 2026-09-01 17:41:12 +08:00
illusia 509dc038c1 M006: add scoped chat and client interactions 2026-09-01 17:32:00 +08:00
illusia 2f8301d188 M005: add local identity and preference persistence 2026-09-01 17:19:15 +08:00
illusia 3397e90749 M004: close Docker and deployment workflow 2026-09-01 17:02:54 +08:00
illusia 3cca211ae9 M003: add TeamSpeak reconnect recovery 2026-09-01 16:59:48 +08:00
illusia 8c7a940de5 M002: harden session lifecycle and directory sync 2026-09-01 16:52:26 +08:00
illusia 4a5d1ca0da Use admin default target on welcome page 2026-09-01 13:12:43 +08:00
illusia 7dcbcaae78 M001: replace bootstrap setup with forced password rotation 2026-09-01 13:09:51 +08:00
illusia 34ef16b737 chore: update frontend security dependencies 2026-09-01 08:07:27 +08:00
illusia 31f320d4c1 M001: add secure admin foundation 2026-09-01 08:00:24 +08:00
illusia 960be106bb M000: normalize configuration and TeamSpeak adapter 2026-08-31 20:14:08 +08:00
75 changed files with 9690 additions and 1380 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
.git
.github
.claude
node_modules
web/node_modules
dist
web/dist
data
certs
release-artifacts
*.tar.gz
*.tar.xz
claude.pem
config.json
*.log
+63 -16
View File
@@ -1,12 +1,15 @@
name: Build release assets
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
inputs:
version:
description: Release version without the v prefix
required: true
default: 0.1.0
default: 0.1.3
type: string
permissions:
@@ -26,12 +29,24 @@ jobs:
web/package-lock.json
- name: Build application
shell: pwsh
env:
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
$ErrorActionPreference = "Stop"
npm ci --no-audit --no-fund
$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
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$currentVersion = node -p "require('./package.json').version"
if ($currentVersion -ne $releaseVersion) {
npm version --no-git-tag-version $releaseVersion
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
npm --prefix web run build
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm run build
@@ -41,10 +56,11 @@ jobs:
- name: Package and smoke-test Windows x64
shell: pwsh
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
$ErrorActionPreference = "Stop"
$packageName = "webspeak-webclient-v$env:RELEASE_VERSION-windows-x64"
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
$packageName = "webspeak-webclient-v$releaseVersion-windows-x64"
$packageRoot = Join-Path $env:RUNNER_TEMP $packageName
$runtimeRoot = Split-Path -Parent (Get-Command node).Source
New-Item -ItemType Directory -Path $packageRoot | Out-Null
@@ -71,7 +87,7 @@ jobs:
$smokeRoot = Join-Path $env:RUNNER_TEMP ($packageName + "-smoke")
Copy-Item -Recurse -LiteralPath $packageRoot -Destination $smokeRoot
@{
port = 31440
port = 3040
tsHost = "203.0.113.10"
tsPort = 9987
tsServerPassword = ""
@@ -85,9 +101,9 @@ jobs:
$health = $null
for ($attempt = 0; $attempt -lt 30 -and -not $health; $attempt++) {
Start-Sleep -Milliseconds 500
try { $health = Invoke-RestMethod -Uri "http://127.0.0.1:31440/api/health" -TimeoutSec 2 } catch {}
try { $health = Invoke-RestMethod -Uri "http://127.0.0.1:3040/api/health" -TimeoutSec 2 } catch {}
}
if (-not $health -or $health.status -ne "ok" -or $health.version -ne $env:RELEASE_VERSION) {
if (-not $health -or $health.status -ne "ok" -or $health.version -ne $releaseVersion) {
throw "Windows release health check failed"
}
} finally {
@@ -97,7 +113,7 @@ jobs:
- uses: actions/upload-artifact@v4
with:
name: windows-x64
path: webspeak-webclient-v${{ inputs.version }}-windows-x64.zip
path: webspeak-webclient-v*-windows-x64.zip
if-no-files-found: error
compression-level: 0
@@ -113,19 +129,29 @@ jobs:
package-lock.json
web/package-lock.json
- name: Build application
env:
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
set -euo pipefail
npm ci --no-audit --no-fund
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")"
if [ "$current_version" != "$release_version" ]; then
npm version --no-git-tag-version "$release_version"
fi
npm --prefix web run build
npm run build
npm prune --omit=dev --no-audit --no-fund
- name: Package and smoke-test Linux x64
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
set -euo pipefail
package_name="webspeak-webclient-v${RELEASE_VERSION}-linux-x64"
release_version="${RELEASE_REF#v}"
package_name="webspeak-webclient-v${release_version}-linux-x64"
package_root="$RUNNER_TEMP/$package_name"
runtime_root="$(dirname "$(dirname "$(command -v node)")")"
mkdir -p "$package_root/web" "$package_root/runtime"
@@ -148,7 +174,7 @@ jobs:
cp -a "$package_root" "$smoke_root"
cat > "$smoke_root/config.json" <<'CONFIG'
{
"port": 31441,
"port": 3040,
"tsHost": "203.0.113.10",
"tsPort": 9987,
"tsServerPassword": "",
@@ -164,17 +190,38 @@ jobs:
trap 'kill "$app_pid" 2>/dev/null || true; wait "$app_pid" 2>/dev/null || true' EXIT
health=""
for _ in $(seq 1 30); do
health="$(curl -fsS --max-time 2 http://127.0.0.1:31441/api/health 2>/dev/null || true)"
if grep -q '"status":"ok"' <<<"$health" && grep -q "\"version\":\"$RELEASE_VERSION\"" <<<"$health"; then break; fi
health="$(curl -fsS --max-time 2 http://127.0.0.1:3040/api/health 2>/dev/null || true)"
if grep -q '"status":"ok"' <<<"$health" && grep -q "\"version\":\"$release_version\"" <<<"$health"; then break; fi
sleep 0.5
done
grep -q '"status":"ok"' <<<"$health"
grep -q "\"version\":\"$RELEASE_VERSION\"" <<<"$health"
grep -q "\"version\":\"$release_version\"" <<<"$health"
)
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
- uses: actions/upload-artifact@v4
with:
name: linux-x64
path: webspeak-webclient-v${{ inputs.version }}-linux-x64.tar.gz
path: webspeak-webclient-v*-linux-x64.tar.gz
if-no-files-found: error
compression-level: 0
publish-release:
if: startsWith(github.ref, 'refs/tags/v')
needs: [windows-x64, linux-x64]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Download deployment packages
uses: actions/download-artifact@v4
with:
pattern: '*-x64'
path: release-assets
merge-multiple: true
- name: Publish GitHub release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: WebSpeak ${{ github.ref_name }}
generate_release_notes: true
files: release-assets/*
+54
View File
@@ -0,0 +1,54 @@
name: Continuous integration
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22.22.2
cache: npm
cache-dependency-path: |
package-lock.json
web/package-lock.json
- 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
run: |
npm test
npm run build
npm --prefix web run build
docker-smoke:
needs: verify
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Build image
run: docker build --tag webspeak:ci .
- name: Run health smoke test
run: |
set -euo pipefail
docker run --detach --name webspeak-ci --publish 3040:3040 webspeak:ci
trap 'docker logs webspeak-ci; docker rm --force webspeak-ci' EXIT
for attempt in $(seq 1 30); do
if curl --fail --silent http://127.0.0.1:3040/health | grep -q '"status":"ok"'; then
exit 0
fi
sleep 2
done
exit 1
+45
View File
@@ -0,0 +1,45 @@
name: Publish Docker image
on:
push:
branches: [master]
tags: ["v*.*.*"]
workflow_dispatch:
permissions:
contents: read
packages: write
env:
IMAGE_NAME: ghcr.io/echosixhiya/webspeak
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=ref,event=tag
type=sha
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+118
View File
@@ -0,0 +1,118 @@
# Changelog
## [0.1.5] — 2026-09-04
### 中文
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
- 修复浏览器身份保存与退出后的保持逻辑。
### English
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
- Fixed browser identity persistence across exit and return.
All notable changes to WebSpeak are documented here. Versions follow SemVer.
## [0.1.4] — 2026-09-03
### 中文
- 修复 WebRTC 语音收发与发言状态同步。
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
- 优化管理员页面、运行日志换行和移动端顶部布局。
- 首页新增 Bilibili 入口,管理员登录页新增返回首页。
### English
- Fixed WebRTC voice transport and speaking-state synchronization.
- Fixed channel text messages between WebSpeak clients.
- Refined admin pages, log wrapping, and narrow-screen header layout.
- Added the Bilibili profile link and the admin-login home link.
## [0.1.3] — 2026-09-03
### Added
- Optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency.
- A self-contained WebRTC media service controlled by one administrator switch; the gateway derives the media host from the current WebSpeak address and owns a fixed UDP range.
- Migrated the TeamSpeak integration to the maintained `EchoSixHIYA/teamspeak-js` fork, including live directory snapshots and member/channel synchronization.
### Changed
- WebRTC audio uses negotiated Opus parameters and a bounded newest-frame mixer instead of allowing stale audio to accumulate.
- The browser keeps the WebSocket path available for signaling, control, and compatibility fallback; Docker Compose publishes the built-in `40000–40099/UDP` media range alongside the web port.
### Fixed
- Prevented duplicate playback when WebRTC and the WebSocket audio path overlap during negotiation or fallback.
- Made WebRTC teardown and fallback explicit so a failed negotiation does not leave a server-side media session behind.
- Corrected native Opus decoder usage and cleaned up negotiated payload handling for TeamSpeak-to-browser audio.
### Verification
- After allowing inbound `40000–40099/UDP` on the public WebSpeak host, two browser sessions were tested against the same TeamSpeak target with WebRTC enabled: audio frames flowed in both directions, packet drops remained at `0`, ingress frame gaps peaked at about `27 ms`, and egress gaps peaked at about `81–83 ms`.
- The measured WebRTC path stayed below the previous WebSocket jitter peaks of about `268–376 ms` in the same browser test setup; these figures describe the observed test path, not a universal latency guarantee.
## [0.1.2] — 2026-09-02
### Added
- Current-version badge and a direct changelog link on the welcome page, next to the prominent GitHub repository button.
- Mobile member actions through a three-dot menu, while desktop member actions remain available through the context menu.
### Changed
- Mobile and narrow-screen header controls now collapse longer labels into icons to preserve usable spacing.
- The welcome page and connected workspace now present the GitHub, version, changelog, admin, theme, language, exit, and microphone controls as a consistent responsive control group.
- The version shown on the welcome page is read from the gateway's public configuration so it stays aligned with the running backend.
- Consolidated the post-0.1.1 mobile voice controls, microphone mute replacement for focus-dependent PTT, automatic protocol detection, simplified Docker Compose startup, and live-demo documentation.
### Fixed
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
## [0.1.1] — 2026-09-02
### Added
- M009 admin operations dashboard for managed invites, active-session inspection, per-session termination, diagnostics, logs, audit access, diagnostic report download, and SQLite backup export.
- Persistent managed invites with expiry, optional maximum uses, revocation, hashed opaque tokens, and encrypted TeamSpeak credentials at rest.
- Mobile-aware invite joining through the `invite` URL parameter without placing a TeamSpeak password in the URL.
- M010 hardening for per-peer join-ticket rate limiting and bounded rotating runtime logs.
- Bilingual README documentation with parallel Chinese and English feature, deployment, security, and operations sections.
### Changed
- Database schema is now version 2 and migrates existing version 1 installations transactionally with a migration copy.
- Admin overview and diagnostics use the application package version instead of a hard-coded display value.
- The README architecture section now uses GitHub-native Markdown instead of a Mermaid rich-display block.
- The README badge set now uses stable static Shields badges without a repository-metadata 404 dependency.
- Version tags publish Windows/Linux deployment packages to GitHub Releases and publish the matching Docker image.
- Removed the focus-dependent normal browser Space-key PTT mode and replaced it with a one-click microphone mute/unmute control on desktop and mobile.
- Persisted the microphone mute state in browser preferences and suppresses upstream audio before it is sent to TeamSpeak while muted.
### Fixed
- Late WebSpeak browser sessions now reconcile and merge the complete TeamSpeak directory, so members who joined earlier remain visible.
- Private-message delivery no longer disconnects the browser session.
- Member actions are presented through the right-click context menu with hover feedback.
- Docker release builds copy the root `postinstall` patch script before running `npm ci`.
- Release builds skip `npm version` when the project version already matches the requested version, preventing false `Version not changed` failures.
### Verification
- `npm test` — 51 tests passed.
- `npm run build` — backend TypeScript build passed.
- `npm run web:build` — frontend production build passed.
- `npm audit --omit=dev --audit-level=high` — no high or critical vulnerabilities reported.
- Local `/demo` browser checks passed at the documented narrow and desktop widths; `/demo` does not connect to TeamSpeak.
Real TS3/TS6 interoperability, Android microphone behavior, multi-client smoke, and the 24-hour long-run gate require their respective test environments and are not claimed by this local release check.
## [0.1.0] — 2026-08-31
- First normalized release with the browser client, TeamSpeak 3 / 6 gateway, browser audio controls, access modes, administrator operations, and AGPL-3.0-only licensing.
+8 -5
View File
@@ -9,8 +9,8 @@ Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpea
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
```
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
@@ -30,16 +30,19 @@ src/
server/
server.ts # Express + HTTPS + WS setup
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
ts-client.ts # TS3Client wrapper around @honeybbq/teamspeak-client
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
```
## Key Technical Details
### Audio Pipeline
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
### CJS Interop
`@discordjs/opus` is CommonJS, loaded via:
+45
View File
@@ -0,0 +1,45 @@
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++ \
&& 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
COPY . .
RUN npm --prefix web run build \
&& npm run build \
&& npm prune --omit=dev \
&& rm -rf web/node_modules
FROM node:22-bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /data \
&& chown node:node /data
ENV NODE_ENV=production
ENV WEBSPEAK_DATA_DIR=/data
COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --from=build --chown=node:node /app/web/dist ./web/dist
USER node
VOLUME ["/data"]
EXPOSE 3040/tcp 40000-40099/udp
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"
CMD ["node", "dist/index.js"]
+303 -315
View File
@@ -1,354 +1,342 @@
<div align="center">
# WebSpeak
TeamSpeak 浏览器客户端:在服务器上运行 Node.js 服务,用户无需安装 TeamSpeak 客户端,即可通过浏览器加入语音频道。
**让 TeamSpeak 真正进入浏览器。**
[English](#english) · [中文](#中文) · [AGPL-3.0 License](LICENSE)
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
## English
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
WebSpeak is a self-hosted browser client and gateway for TeamSpeak 3 and TeamSpeak 6. Each browser session receives an independent TeamSpeak client that maintains its own visible channel/member directory and relays voice through WebSocket.
[![GitHub](https://img.shields.io/badge/GitHub-源代码-181717?style=for-the-badge&logo=github)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak)
[![Version](https://img.shields.io/badge/version-0.1.5-0f766e?style=flat-square)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5)
[![License](https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square)](LICENSE)
[![TeamSpeak](https://img.shields.io/badge/TeamSpeak-3%20%7C%206-0f766e?style=flat-square)](https://www.teamspeak.com/)
### Highlights
[中文](#中文) · [English](#english) · [更新日志](#更新日志--changelog) · [快速开始](#快速开始--quick-start) · [社区](#社区--community)
- Low-latency PCM/Opus voice relay
- VOX open microphone and Space-key push-to-talk modes
- Browser microphone enumeration and device switching
- Channel switching with a complete channel/member tree, including empty channels
- Per-member playback volume controls
- Speaking members are highlighted with a live green avatar border
- Text chat, invite-link sharing, and persistent Chinese/English UI switching
- No WebQuery/SSH Query dependency and no invite token
- Editable TeamSpeak server address and voice port on the web join screen
- No browser plugin or desktop TeamSpeak client required
### Requirements
- Linux server recommended; Windows is also supported
- Node.js 22 or newer
- A reachable TeamSpeak 3 or TeamSpeak 6 server
- A recent Chrome or Edge browser
- HTTPS in production: microphone access and WebCodecs require a secure context
### How it works
```text
Browser WebSpeak TeamSpeak
┌────────────────────┐ ┌──────────────────────┐ ┌──────────┐
│ Microphone → PCM │ ──────▶ │ Per-user voice client│ ──────▶ │ │
│ AudioDecoder │ ◀────── │ PCM ↔ Opus bridge │ ◀────── │ Server │
│ Vue web client │ ◀ JSON │ Live directory │ ◀────── │ │
└────────────────────┘ │ welcome snapshot + │ └──────────┘
│ live events │
└──────────────────────┘
```
### Quick start
#### 1. Install dependencies
```bash
# Native build tools are required by @discordjs/opus.
sudo apt-get update
sudo apt-get install -y build-essential python3
npm install
npm --prefix web install
```
On Windows, install Visual Studio Build Tools with **Desktop development with C++** before running `npm install`.
`npm install` runs the SDK patch automatically. It adds a `directorySnapshot` event to the installed protocol package so the gateway can use the same welcome data as a native client.
#### 2. Build
```bash
npm --prefix web run build
npm run build
```
The build output is written to `web/dist/` and `dist/`.
#### 3. Configure `config.json`
Copy `config.example.json` to `config.json` in the project root, then edit the values. Keep `config.json` private because it may contain TeamSpeak credentials.
```json
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
}
```
| Field | Description |
| --- | --- |
| `port` | Local HTTP/HTTPS port for WebSpeak. |
| `tsHost` | TeamSpeak server address. Use `127.0.0.1` when it runs on the same host. |
| `tsPort` | TeamSpeak voice port, commonly `9987`. |
| `tsServerPassword` | TeamSpeak server password, if required. |
| `tsServerProtocol` | `"ts3"` or `"ts6"`; omit it to use protocol detection. |
| `maxClients` | Maximum number of simultaneous browser sessions. |
| `trustProxy` | Set to `true` only when a trusted reverse proxy is in front of WebSpeak. |
The join page includes a **Setup guide** button. It generates a copyable `config.json` preview from the server address, voice port, protocol, WebSpeak port, and optional password entered in the page. A browser cannot write files on the server, so save the copied JSON as `config.json` in the project root and restart WebSpeak after changing it.
WebSpeak uses each user's regular TeamSpeak client connection for both voice and directory data. TeamSpeak sends the initial channel/member snapshot during the normal client welcome sequence; WebSpeak then subscribes that regular client to the complete channel tree, just as a native client does, and applies channel/member notifications immediately afterward. A member moving out of the current channel is retained and reassigned to the target channel instead of being mistaken for a server disconnect. WebSpeak does not start a maintenance client and does not call the permission-restricted `channellist` or `clientlist` commands. The visible result is the same view available to that TeamSpeak identity.
The connected layout keeps the member/channel tree on the left. During the first connection, WebSpeak uses the current channel ID from TeamSpeak's welcome sequence to place the web client in the actual default channel instead of a placeholder group. The small speaking indicator is status-only: it is not a mute control. The avatar border turns green while a voice packet is active, then fades after the stream becomes quiet.
#### 4. Enable HTTPS
WebSpeak automatically serves HTTPS when `certs/cert.pem` and `certs/key.pem` exist:
```bash
mkdir -p certs
openssl req -x509 -newkey rsa:2048 \
-keyout certs/key.pem \
-out certs/cert.pem \
-days 365 -nodes \
-subj "/CN=your-domain.example"
```
For public use, prefer a trusted certificate from Let's Encrypt or terminate TLS at Nginx. Do not commit private keys to Git.
#### 5. Start WebSpeak
```bash
node dist/index.js
```
Open:
```text
https://your-domain.example:3040/
```
Enter the TeamSpeak server address, voice port, and nickname on the page. The browser will request microphone permission. Open **Audio settings** to select a specific microphone, change input/output volume, or run the real microphone-level test.
The connected page keeps its controls in the header so the chat viewport remains unobstructed. Microphone mode selection (free microphone or push-to-talk) is available in **Audio settings**.
### Production deployment
Example systemd unit:
```ini
[Unit]
Description=WebSpeak TeamSpeak browser gateway
After=network.target
[Service]
Type=simple
User=teamspeak
WorkingDirectory=/opt/webspeak
ExecStart=/usr/bin/node /opt/webspeak/dist/index.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
```
Enable it with:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now webspeak.service
sudo systemctl status webspeak.service
```
If Nginx terminates HTTPS, leave `certs/` absent so WebSpeak listens over local HTTP, then proxy both normal traffic and WebSocket upgrades:
```nginx
server {
listen 443 ssl;
server_name ts.example.com;
ssl_certificate /etc/letsencrypt/live/ts.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/ts.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3040;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Set `trustProxy` to `true` only after verifying that the proxy is trusted and cannot be bypassed.
### Troubleshooting
| Symptom | Check |
| --- | --- |
| Microphone is unavailable | Use HTTPS, grant the browser microphone permission, and check the selected device in Audio settings. |
| Only the default microphone appears | Reload after granting permission; browser device labels are hidden until permission is granted. Disconnect/reconnect if the device was plugged in later. |
| Channel/member list is empty | Check the TeamSpeak address/voice port and `tsServerProtocol`. The directory is populated from the normal client welcome sequence. |
| The channel directory is still loading | Keep the page connected briefly while the welcome snapshot arrives. Later member and channel changes are pushed to the page automatically in real time. |
| The current user is missing | Keep the connection open until the TeamSpeak welcome snapshot arrives. WebSpeak uses the current channel ID to place the user in the default channel, then updates the tree from realtime member notifications. |
| Page loads without audio | Use a recent Chrome/Edge build, verify HTTPS, and check browser output volume. |
| `Cannot find module '@discordjs/opus'` | Install the native build prerequisites and run `npm install` again. |
| `EADDRINUSE` | Change `port` or stop the process already listening on that port. |
### Project layout
```text
src/
server/voice-bridge.ts WebSocket bridge and per-user voice clients
server/ts-client.ts TeamSpeak protocol adapter and live directory adapter
config.example.json Safe starting configuration; copy to config.json
scripts/
patch-teamspeak-sdk.mjs Preserve TeamSpeak welcome directory data
web/
src/views/WebClient.vue Browser UI and bilingual presentation
src/composables/useVoiceWebSocket.ts
Voice, chat, device and channel state
```
### Development
```bash
# Frontend hot reload
npm run web:dev
# Type-check and production-build frontend
npm --prefix web run build
# Type-check backend
npm run build
```
Contributions and issue reports are welcome. Please do not include `config.json`, certificates, private keys, or server logs in issues or pull requests.
### License
WebSpeak is released under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version as a network service, you must offer its users the corresponding source code as required by the license.
</div>
## 中文
WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端。服务运行在服务器上,用户无需安装 TeamSpeak 客户端,打开网页即可加入语音频道。每个网页用户拥有独立的 TeamSpeak 连接,并使用自己的可见频道和成员信息。
WebSpeak 是一个面向 TeamSpeak 服务器的浏览器客户端。部署一次,用户通过网页即可加入语音空间,不需要安装 TeamSpeak 桌面客户端。
### 主要功能
### 功能
- 低延迟 PCM/Opus 语音转发
- 自由麦(VOX)与空格键按键说话
- 枚举并切换浏览器真实麦克风设备
- 频道切换与完整频道/成员树,空频道也会显示
- 为每个成员单独调整播放音量
- 正在发言的成员头像实时显示绿色边框
- 文字聊天、邀请链接分享、中英文界面切换
- 不依赖 WebQuery/SSH Query,不使用邀请 token
- 网页端直接设置 TeamSpeak 地址和语音端口
- 不需要浏览器插件或桌面版 TeamSpeak 客户端
- 支持 TeamSpeak 3 和 TeamSpeak 6,自动识别协议。
- 浏览频道、在线成员和实时成员状态。
- 加入、切换频道,并显示成员所在频道。
- 频道文字聊天、服务器消息、私聊和戳一戳。
- 浏览器麦克风和扬声器选择、音量调节、输入电平和本地麦克风测试。
- 一键闭麦/开麦、VOX 语音激活、发言状态提示。
- 可选 WebRTC 低延迟语音,网络不支持时自动回退。
- 固定服务器、开放服务器和一次性邀请链接三种访问方式。
- 管理控制台:默认目标、邀请链接、在线会话、日志、诊断和数据库备份。
- 中英文界面、主题切换、桌面端和移动端适配。
- 移动端提供成员操作菜单,桌面端支持右键菜单。
### 环境要求
### 快速开始 · Quick Start
- 推荐 Linux 服务器,也支持 Windows
- Node.js 22 或更高版本
- 可访问的 TeamSpeak 3 或 TeamSpeak 6 服务器
- 较新的 Chrome 或 Edge 浏览器
- 生产环境使用 HTTPS;浏览器麦克风和 WebCodecs 都要求安全上下文
#### Docker Compose(推荐)
### 快速开始
要求:安装 Docker Engine 和 Docker Compose。
```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install -y build-essential python3
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
# 安装服务端和前端依赖
npm install
npm --prefix web install
打开 `http://你的服务器地址:3040/`,首次进入管理后台 `/admin` 使用:
# 构建前端和后端
```text
账号:admin
密码:admin
```
首次登录必须修改管理员密码。然后在管理控制台的“服务器”页面设置“默认 TeamSpeak 目标”,例如:
```text
203.0.113.10#9987
```
用户欢迎页没有邀请链接参数时,会自动使用管理员设置的默认目标。开放模式下,用户可以自行输入要连接的服务器地址和端口。
数据会保存在 Docker volume `webspeak-data` 中。升级时执行:
```bash
docker compose pull
docker compose up -d
```
不要使用 `docker compose down -v`,否则会删除数据库和管理员配置。
如需更换网页端口:
```bash
WEBSPEAK_PORT=3041 docker compose up -d
```
#### 源码运行
需要 Node.js `22.5.0` 或更高版本,以及 `@discordjs/opus` 所需的本地编译工具。
```bash
npm ci
npm --prefix web ci
npm --prefix web run build
npm run build
```
将项目根目录的 `config.example.json` 复制为 `config.json`,再按实际环境修改。`config.json` 可能包含服务器密码,请勿提交到 Git:
```json
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
}
```
关键配置:
- `tsHost`:TeamSpeak 地址;同机部署使用 `127.0.0.1`。
- `tsPort`:语音端口,通常为 `9987`。
- `tsServerProtocol`:填写 `"ts3"` 或 `"ts6"`,也可以省略并使用自动检测。
加入页面提供“配置引导”按钮,可以根据页面中填写的服务器地址、语音端口、协议、WebSpeak 端口和可选密码生成可复制的 `config.json` 预览。浏览器不能直接写入服务器文件,请将复制的内容保存到项目根目录的 `config.json`,再重启 WebSpeak。
WebSpeak 使用每个网页用户自己的普通 TeamSpeak 客户端连接获取语音和目录数据,不连接 WebQuery/SSH Query,也不启动维护客户端。TeamSpeak 会在普通客户端登录握手阶段下发频道和成员快照;随后 WebSpeak 会像原生客户端一样订阅完整频道树,并实时应用频道/成员通知。成员切换到其他频道时会被移动到目标频道,不再被误判为退出服务器。不会主动调用受权限限制的 `channellist` 或 `clientlist` 命令,显示内容与该 TeamSpeak 身份实际可见的内容一致。
进入后的成员/频道树位于页面左侧。首次进入时,WebSpeak 会使用 TeamSpeak 欢迎握手中返回的当前频道 ID,把自己放入实际所在的默认频道;不会把已进入默认频道的用户显示到错误的占位分组。“正在语音中”旁边不再使用没有功能的禁麦图标;它只是状态提示,真正发言时头像边框会实时变绿,停止发声后自动恢复。
配置好证书后启动:
```bash
node dist/index.js
```
访问:
服务默认监听 `3040` 端口。
```text
https://你的域名或IP:3040/
```
### WebRTC 低延迟语音
在页面中填写 TeamSpeak 地址、语音端口和昵称。首次使用时允许浏览器访问麦克风。进入语音空间后,打开“音频设置”即可选择具体麦克风、调整输入/输出音量并进行真实麦克风电平测试。
WebRTC 是可选功能,由 WebSpeak 自带,不需要额外部署媒体服务器。
连接后的控制项统一放在顶部,不再遮挡聊天区域;“自由麦”和“按键说话”可以在“音频设置”中切换。
1. 在管理后台打开“WebRTC 语音”。
2. 在部署主机所在云平台安全组或上游防火墙放行入站 UDP `40000–40099`。
3. 重新进入语音空间即可生效。
### HTTPS 与反向代理
如果项目根目录存在 `certs/cert.pem` 和 `certs/key.pem`,WebSpeak 会直接提供 HTTPS。公网部署建议使用 Let's Encrypt,或让 Nginx 终止 HTTPS 后反向代理到 `http://127.0.0.1:3040`,并转发 WebSocket 升级请求。使用可信反向代理时,将 `trustProxy` 设置为 `true`。
### 常见问题
- **无法使用麦克风**:确认使用 HTTPS、已经允许浏览器访问麦克风,并在“音频设置”中检查设备。
- **只能看到默认麦克风**:授权前浏览器会隐藏设备名称;授权后刷新页面,或重新连接一次。
- **频道/成员列表为空**:检查网页中的 TeamSpeak 地址、语音端口和协议设置;目录来自普通客户端登录握手数据。
- **频道/成员目录仍在加载**:保持页面连接,等待登录握手快照到达;之后成员和频道变化会自动实时推送到页面。
- **首次进入看不到自己**:保持连接直到 TeamSpeak 欢迎握手完成;WebSpeak 会根据当前频道 ID 将自己归入默认频道,并在频道成员变化时实时更新。
- **没有声音**:使用较新的 Chrome/Edge,通过 HTTPS 访问,并检查浏览器输出音量。
- **原生 Opus 模块安装失败**:安装 `build-essential python3` 后重新执行 `npm install`。
### 开发命令
Docker Compose 已自动发布 `40000–40099/UDP`,但无法替你修改云安全组。Ubuntu 使用 UFW 时可执行:
```bash
# 前端热更新
npm run web:dev
# 前端类型检查并构建
npm --prefix web run build
# 后端 TypeScript 构建
npm run build
sudo ufw allow 40000:40099/udp
```
请不要在 Issue 或 Pull Request 中提交 `config.json`、API 密钥、证书、私钥或服务器日志。
网页和 WSS 使用 TCP `80/443`。TeamSpeak 的 `9987` 只需要让 WebSpeak 主机能够访问目标 TeamSpeak,不需要在 WebSpeak 主机对公网开放。WebRTC 不支持或端口未放行时,客户端会自动使用兼容模式。
### 管理员设置
管理员可以在控制台中:
- 修改默认 TeamSpeak 目标和服务器密码。
- 选择固定目标或允许用户自定义目标。
- 创建、撤销和设置有效期的邀请链接。
- 查看在线会话、运行日志、诊断信息和审计记录。
- 下载诊断报告和 SQLite 数据库备份。
- 开启或关闭 WebRTC 低延迟语音。
### 浏览器要求
- 使用较新的 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。
- 使用麦克风需要浏览器权限;公网部署建议使用 HTTPS。
- 目标 TeamSpeak 服务器必须能被 WebSpeak 主机访问。
### 更新日志 · Changelog
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
#### 2026-09-04 · v0.1.5
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
- 修复浏览器身份保存与退出后的保持逻辑。
#### 2026-09-03 · v0.1.4
- 修复 WebRTC 语音收发与发言状态同步。
- 修复频道文字消息在 WebSpeak 客户端之间无法互收。
- 优化管理员页面、运行日志换行和移动端顶部布局;新增 Bilibili 入口及登录页返回首页。
#### 2026-09-03 · v0.1.3
- 增加可选 WebRTC 低延迟语音。
- 支持在管理员页面直接启用 WebRTC,无需额外媒体服务器。
- 更新 TeamSpeak 集成,改善频道、成员和实时状态同步。
- 优化语音缓冲和连接回退,减少网络抖动造成的延迟堆积。
- 公网部署放行 UDP `40000–40099` 后,双浏览器语音测试稳定运行,实测间隔峰值约 `27–83ms`。
#### 2026-09-02 · v0.1.2
- 大幅优化移动端界面和成员操作。
- 首页增加 GitHub、当前版本和更新日志入口。
- 修复设置按钮错位,优化窄屏布局和滚动体验。
- 增加 AudioWorklet、设备选择和更稳定的语音缓冲处理。
#### 2026-09-02 · v0.1.1
- 正式提供浏览器客户端、管理控制台、邀请链接和运维功能。
- 修复成员同步、私聊断开和频道显示问题。
- 增加中英文切换、默认目标、首次登录改密和一键闭麦。
- 发布 Windows、Linux 和 Docker 部署方式。
#### 2026-08-31 · v0.1.0
- 首个规范化版本。
### 社区 · Community
QQ群:`869500475`
加入 QQ 群获取使用帮助、版本更新和交流支持:
![WebSpeak 群聊二维码](group-chat.png)
### 许可证
本项目仅按 [GNU Affero General Public License v3.0](LICENSE)(`AGPL-3.0-only`)授权。如果你将修改版作为网络服务运行,必须按照许可证要求向服务用户提供对应源代码。
WebSpeak 使用 [GNU Affero General Public License v3.0](LICENSE) 发布。
如果 WebSpeak 对你有帮助,欢迎在 GitHub 点一个 Star。维护者:[EchoSixHIYA](https://github.com/EchoSixHIYA)。
## English
### 加入交流群
WebSpeak is a self-hosted browser client for TeamSpeak 3 and TeamSpeak 6. Deploy it once and let users join voice channels from a browser without installing the desktop TeamSpeak client.
扫描下方二维码加入群聊(群号:`869500475`):
**Live demo: [webspeak.example.invalid](https://webspeak.example.invalid)**
![WebSpeak 群聊二维码](group-chat.png)
### Features
- TeamSpeak 3 and TeamSpeak 6 support with automatic protocol detection.
- Live channel tree, online members, member locations, and status updates.
- Channel switching and member presence grouped under the correct channel.
- Channel text chat, server messages, private messages, and poke actions.
- Browser microphone and speaker selection, volume control, input level, and local microphone test.
- One-click microphone mute/unmute, VOX activation, and speaking indicators.
- Optional low-latency WebRTC audio with automatic compatibility fallback.
- Fixed targets, open targets, and expiring one-time invite links.
- Admin console for targets, invites, sessions, logs, diagnostics, and database backups.
- Chinese and English UI, theme switching, and responsive desktop/mobile layouts.
- Mobile member action menus and desktop context menus.
### Quick Start
#### Docker Compose (recommended)
Requirements: Docker Engine and Docker Compose.
```bash
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
cd WebSpeak-client-for-TeamSpeak
docker compose pull
docker compose up -d
```
Open `http://your-server:3040/`. On the first admin login at `/admin`, use:
```text
Username: admin
Password: admin
```
You must change the administrator password after the first login. Then configure the **Default TeamSpeak target** in the **Servers** page, for example:
```text
203.0.113.10#9987
```
If a welcome link does not contain an invite target, the default target is pre-filled automatically. In open mode, users may enter their own TeamSpeak address and port.
Data is stored in the `webspeak-data` Docker volume. To upgrade:
```bash
docker compose pull
docker compose up -d
```
Do not run `docker compose down -v`, because it removes the database and administrator settings.
To change the web host port:
```bash
WEBSPEAK_PORT=3041 docker compose up -d
```
#### Run from source
Requires Node.js `22.5.0` or newer and native build tools for `@discordjs/opus`.
```bash
npm ci
npm --prefix web ci
npm --prefix web run build
npm run build
node dist/index.js
```
The service listens on port `3040` by default.
### Low-latency WebRTC audio
WebRTC is optional and bundled with WebSpeak. No separate media server is required.
1. Enable **WebRTC audio** in the admin console.
2. Allow inbound UDP `40000–40099` in the cloud security group or upstream firewall for the WebSpeak host.
3. Re-enter the voice space to apply the setting.
Docker Compose publishes `40000–40099/UDP` automatically, but it cannot change a cloud security group. With Ubuntu UFW:
```bash
sudo ufw allow 40000:40099/udp
```
The web page and WSS signaling use TCP `80/443`. TeamSpeak port `9987` only needs to be reachable from WebSpeak to the target TeamSpeak server; it does not need to be exposed publicly on the WebSpeak host. If WebRTC is unavailable, the client automatically uses the compatibility mode.
### Administrator settings
The admin console can:
- Set the default TeamSpeak target and server password.
- Choose a fixed target or allow users to enter their own target.
- Create, revoke, expire, and limit invite links.
- View online sessions, runtime logs, diagnostics, and audit records.
- Download diagnostic reports and SQLite backups.
- Enable or disable low-latency WebRTC audio.
### Browser requirements
- A recent Chrome, Edge, or another modern browser with WebRTC support.
- Microphone permission is required for voice input; HTTPS is recommended for public deployments.
- The target TeamSpeak server must be reachable from the WebSpeak host.
### Changelog
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
#### 2026-09-04 · v0.1.5
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
- Fixed browser identity persistence across exit and return.
#### 2026-09-03 · v0.1.4
- Fixed WebRTC voice transport and speaking-state synchronization.
- Fixed channel text messages between WebSpeak clients.
- Refined admin pages, log wrapping, and narrow-screen header layout; added Bilibili and admin-login home links.
#### 2026-09-03 · v0.1.3
- Added optional low-latency WebRTC audio.
- Added an admin switch for WebRTC without requiring a separate media server.
- Updated TeamSpeak integration for better channel, member, and realtime status synchronization.
- Improved audio buffering and connection fallback to reduce delay growth during network jitter.
- After allowing inbound UDP `40000–40099`, a two-browser voice test ran reliably with observed peak gaps of about `27–83 ms`.
#### 2026-09-02 · v0.1.2
- Major mobile UI and member-action improvements.
- Added GitHub, current-version, and changelog entries to the welcome page.
- Fixed settings-button alignment and improved narrow-screen layout and scrolling.
- Added AudioWorklet, device selection, and more stable voice buffering.
#### 2026-09-02 · v0.1.1
- Official browser client, admin console, invite links, and operations tools.
- Fixed member synchronization, private-message disconnects, and channel display issues.
- Added Chinese/English switching, default targets, first-login password rotation, and one-click mute.
- Added Windows, Linux, and Docker deployment options.
#### 2026-08-31 · v0.1.0
- First normalized release.
### Community
QQ group: `869500475`
Join the group for support, release updates, and discussion:
![WebSpeak QQ group QR code](group-chat.png)
### License
WebSpeak is released under the [GNU Affero General Public License v3.0](LICENSE).
+1 -5
View File
@@ -1,9 +1,5 @@
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
"tsServerPassword": ""
}
+13
View File
@@ -0,0 +1,13 @@
services:
webspeak:
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
pull_policy: missing
restart: unless-stopped
ports:
- "${WEBSPEAK_PORT:-3040}:3040"
- "40000-40099:40000-40099/udp"
volumes:
- webspeak-data:/data
volumes:
webspeak-data:
+709 -206
View File
File diff suppressed because it is too large. Load diff
+14 -4
View File
@@ -1,23 +1,28 @@
{
"name": "webspeak-webclient",
"version": "0.1.0",
"version": "0.1.5",
"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": "tsx --test \"test/**/*.test.ts\"",
"start": "node dist/index.js",
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite build"
"web:build": "cd web && npx vite build",
"prepare:sdk": "node scripts/prepare-sdk.mjs"
},
"dependencies": {
"@discordjs/opus": "^0.10.0",
"@honeybbq/teamspeak-client": "^0.2.2",
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
@@ -26,5 +31,10 @@
"@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"
}
}
-148
View File
@@ -1,148 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
const marker = "webspeak-directory-snapshot";
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
if (packageJson.version !== "0.2.2") {
throw new Error(`Unsupported @honeybbq/teamspeak-client version: ${packageJson.version}`);
}
const cjsPath = path.join(packageRoot, "dist", "index.cjs");
const mjsPath = path.join(packageRoot, "dist", "index.mjs");
const [cjs, mjs] = await Promise.all([
readFile(cjsPath, "utf8"),
readFile(mjsPath, "utf8"),
]);
const patchedCjs = patchCjs(cjs);
const patchedMjs = patchMjs(mjs);
await Promise.all([
writeFile(cjsPath, patchedCjs, "utf8"),
writeFile(mjsPath, patchedMjs, "utf8"),
]);
function patchCjs(source) {
if (source.includes(marker)) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var K=class", `${helper}var K=class`);
// TS6 reports a client that moved out of our current view as
// notifyclientleftview with a non-zero ctid. Preserve that client and apply
// the target channel; ctid=0 is the actual server leave case.
const replacements = [
[
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t;return r!==0&&n.delete(r),{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t,o=A(e.params.ctid??``),s=o!==0n;if(r!==0)if(s){let e=n.get(r);e&&n.set(r,{...e,channelID:o})}else n.delete(r);return s?{kind:`clientMoved`,event:{id:r,targetChannelID:o,reasonID:i,invokerID:j(e.params.invokerid??``),invokerName:e.params.invokername??``,invokerUID:e.params.invokeruid??``}}:{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
],
[
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#q=new Map;#R=[];#L=!1;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
],
[
"case`voiceData`:this.#h.push(t);break;case`connected`:",
"case`voiceData`:this.#h.push(t);break;case`directorySnapshot`:this.#R.push(t);break;case`connected`:",
],
[
"this.#o.reset(),this.#s.reset(),this.#c.clear(),this.clid=0",
"this.#o.reset(),this.#s.reset(),this.#q.clear(),this.#c.clear(),this.#L=!1,this.clid=0",
],
[
"case`initserver`:w(this,t.params);break;case`error`:this.#A(t.params);break;default:{",
"case`initserver`:w(this,t.params);break;case`channellist`:{let e=webSpeakDirectoryChannel(t.params,a.i);e&&this.#q.set(e.id,e),this.#Y();break}case`channelclientlist`:{let e=webSpeakDirectoryClient(t.params,a.i);e&&this.#c.set(e.id,e),this.#Y();break}case`error`:this.#A(t.params);break;default:{",
],
[
"if(t.name.startsWith(`notify`)){let e=F(t,this.clid,this.#c,this.nickname);this.#j(e,t.params);return}",
"if(t.name.startsWith(`notify`)){let e=webSpeakDirectoryChannelNotification(t.name,t.params,a.i,this.#q),n=F(t,this.clid,this.#c,this.nickname);this.#j(n,t.params),e&&this.#Y();return}",
],
[
"case`clientEnter`:{let t=e.info;t.id!==0&&N(this.nickname,t.nickname)&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete()),this.#M(`clientEnter`,t);break}",
"case`clientEnter`:{let t=e.info,r=webSpeakDirectoryBigInt(arguments[1]?.cid??arguments[1]?.ctid??\"0\");r!==0n&&(t={...t,channelID:r},this.#c.set(t.id,t));let n=this.#c.get(t.id);n&&t.channelID===0n&&n.channelID!==0n&&(t={...t,channelID:n.channelID},this.#c.set(t.id,t));let i=t.id!==0&&N(this.nickname,t.nickname);i&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete(),this.#Y()),this.#M(`clientEnter`,t),!i&&this.#i===2&&this.#Y();break}",
],
[
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event);break;",
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),this.#i===2&&this.#Y(),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event),this.#i===2&&this.#Y();break;",
],
[
"#M(e,t){this.#S(t)}#N(e,t){",
"#Y(){if(this.#L)return;this.#L=!0,setImmediate(()=>{this.#L=!1;const e={channels:Array.from(this.#q.values()).map(e=>({...e})),clients:Array.from(this.#c.values()).map(e=>({...e,serverGroups:[...(e.serverGroups??[])]}))};for(const t of this.#R)setImmediate(()=>t(e))})}#M(e,t){this.#S(t)}#N(e,t){",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch CJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
function patchMjs(source) {
if (source.includes(marker)) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var k = class", `${helper}var k = class`);
// Keep the readable ESM build behavior identical to the minified CJS build.
const replacements = [
[
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t;\n\treturn r !== 0 && n.delete(r), {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t, targetChannelID = J(e.params.ctid ?? \"\"), moved = targetChannelID !== 0n;\n\tif (r !== 0) {\n\t\tif (moved) {\n\t\t\tconst current = n.get(r);\n\t\t\tif (current) n.set(r, { ...current, channelID: targetChannelID });\n\t\t} else {\n\t\t\tn.delete(r);\n\t\t}\n\t}\n\treturn moved ? {\n\t\tkind: \"clientMoved\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\ttargetChannelID,\n\t\t\treasonID: i,\n\t\t\tinvokerID: Y(e.params.invokerid ?? \"\"),\n\t\t\tinvokerName: e.params.invokername ?? \"\",\n\t\t\tinvokerUID: e.params.invokeruid ?? \"\"\n\t\t}\n\t} : {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
],
[
"\t#c = /* @__PURE__ */ new Map();\n\t#l = [];",
"\t#c = /* @__PURE__ */ new Map();\n\t#q = /* @__PURE__ */ new Map();\n\t#R = [];\n\t#L = false;\n\t#l = [];",
],
[
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"directorySnapshot\":\n\t\t\t\tthis.#R.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
],
[
"this.#o.reset(), this.#s.reset(), this.#c.clear(), this.clid = 0",
"this.#o.reset(), this.#s.reset(), this.#q.clear(), this.#c.clear(), this.#L = false, this.clid = 0",
],
[
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":",
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"channellist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryChannel(t.params, S);\n\t\t\t\t\tif (e) this.#q.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"channelclientlist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryClient(t.params, S);\n\t\t\t\t\tif (e) this.#c.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"error\":",
],
[
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tconst directoryChanged = webSpeakDirectoryChannelNotification(t.name, t.params, S, this.#q);\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\tif (directoryChanged) this.#Y();\n\t\t\t\treturn;\n\t\t\t}",
],
[
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tt.id !== 0 && Z(this.nickname, t.nickname) && (this.clid = t.id, this.handler.setClientID(t.id), this.#o.signalWelcomeComplete()), this.#M(\"clientEnter\", t);\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tconst rawChannelID = webSpeakDirectoryBigInt(arguments[1]?.cid ?? arguments[1]?.ctid ?? \"0\");\n\t\t\t\tif (rawChannelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: rawChannelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst cached = this.#c.get(t.id);\n\t\t\t\tif (cached && t.channelID === 0n && cached.channelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: cached.channelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst own = t.id !== 0 && Z(this.nickname, t.nickname);\n\t\t\t\tif (own) {\n\t\t\t\t\tthis.clid = t.id;\n\t\t\t\t\tthis.handler.setClientID(t.id);\n\t\t\t\t\tthis.#o.signalWelcomeComplete();\n\t\t\t\t\tthis.#Y();\n\t\t\t\t}\n\t\t\t\tthis.#M(\"clientEnter\", t);\n\t\t\t\tif (!own && this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;\n\t\t\t}",
],
[
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), this.#i === n.Connected && this.#Y(), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
],
[
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tbreak;",
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tif (this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;",
],
[
"\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
"\t#Y() {\n\t\tif (this.#L) return;\n\t\tthis.#L = true;\n\t\tsetImmediate(() => {\n\t\t\tthis.#L = false;\n\t\t\tconst e = {\n\t\t\t\tchannels: Array.from(this.#q.values()).map((item) => ({ ...item })),\n\t\t\t\tclients: Array.from(this.#c.values()).map((item) => ({ ...item, serverGroups: [...(item.serverGroups ?? [])] })),\n\t\t\t};\n\t\t\tfor (const handler of this.#R) setImmediate(() => handler(e));\n\t\t});\n\t}\n\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch MJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
+48
View File
@@ -0,0 +1,48 @@
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import process from "node:process";
const root = process.cwd();
const sdkPackage = "@echosixhiya/teamspeak-client";
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const dependency = packageJson.dependencies?.[sdkPackage];
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
if (!match) {
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
}
const [, repository, commit] = match;
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
try {
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
const runNpm = (args) => {
if (process.platform === "win32") {
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
} else {
execFileSync("npm", args, npmOptions);
}
};
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
runNpm(["run", "build"]);
const source = join(temporaryRoot, "dist");
if (!existsSync(join(source, "index.mjs"))) {
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
}
mkdirSync(dirname(destination), { recursive: true });
mkdirSync(destination, { recursive: true });
for (const entry of readdirSync(source)) {
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
}
console.log(`Prepared ${sdkPackage} from ${commit}`);
} finally {
rmSync(temporaryRoot, { recursive: true, force: true });
}
+436
View File
@@ -0,0 +1,436 @@
import { Router, type NextFunction, type Request, type Response } from "express";
import { existsSync, readFileSync } from "node:fs";
import type { Logger } from "../logger.js";
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
import { 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";
export interface AdminRouterOptions {
service: AdminService;
sessions: AdminSessionStore;
logger: Logger;
getActiveSessions(): number;
getPeakSessions(): number;
getCreatedSessions?: () => number;
getSessionSummaries?: () => AdminSessionSummary[];
terminateSession?: (id: string) => Promise<boolean>;
version?: string;
logFile?: string;
startedAt: number;
}
export function createAdminRouter(options: AdminRouterOptions): Router {
const router = Router();
const limiter = new AdminLoginRateLimiter();
const logger = options.logger.child({ component: "admin-api" });
router.use((_request, response, next) => {
response.setHeader("Cache-Control", "no-store");
next();
});
router.get("/status", (_request, response) => {
response.json({ initialized: options.service.isInitialized() });
});
router.get("/session", (request, response) => {
const session = options.sessions.get(request);
response.json({
initialized: options.service.isInitialized(),
authenticated: Boolean(session),
mustChangePassword: Boolean(session) && options.service.isPasswordChangeRequired(),
...(session ? { csrfToken: session.csrfToken, expiresAt: session.expiresAt } : {}),
});
});
router.post("/login", requireSameOrigin, async (request, response) => {
if (!options.service.isInitialized()) {
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 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);
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);
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() });
});
router.post("/change-password", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
const body = asRecord(request.body);
await options.service.changePassword(readString(body, "newPassword", 1024));
response.json({ ok: true, mustChangePassword: false });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/logout", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
options.sessions.destroy(request, response, isSecureRequest(request));
options.service.database.addAudit("ADMIN_LOGOUT");
response.json({ ok: true });
});
router.use(requireAdmin(options.sessions, options.service));
router.get("/overview", (_request, response) => {
response.json(options.service.getOverview(
options.getActiveSessions(),
options.getPeakSessions(),
options.startedAt,
));
});
router.get("/server", (_request, response) => {
response.json(options.service.getAdminSettings());
});
router.get("/sessions", (_request, response) => {
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
});
router.post("/sessions/:id/terminate", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!options.terminateSession || !id || !(await options.terminateSession(id))) {
response.status(404).json({ ok: false, code: "SESSION_NOT_FOUND" });
return;
}
options.service.database.addAudit("ADMIN_SESSION_TERMINATED", { id });
response.json({ ok: true });
});
router.get("/invites", (_request, response) => {
response.json({ invites: options.service.listManagedInvites() });
});
router.post("/invites", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
const body = asRecord(request.body);
const created = options.service.createManagedInvite({
channel: readOptionalString(body, "channel", 100),
expiresInHours: readOptionalNumber(body, "expiresInHours", 1),
maxUses: readOptionalNumber(body, "maxUses", 0),
});
response.status(201).json({ ok: true, ...created });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/invites/:id/revoke", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!id) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
if (!options.service.revokeManagedInvite(id)) {
response.status(404).json({ ok: false, code: "INVITE_NOT_FOUND" });
return;
}
response.json({ ok: true });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.get("/audit", (request, response) => {
response.json({ events: options.service.database.recentAudit(readLimit(request.query.limit, 50)) });
});
router.get("/logs", (request, response) => {
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
});
router.get("/diagnostics", (_request, response) => {
const overview = options.service.getOverview(
options.getActiveSessions(),
options.getPeakSessions(),
options.startedAt,
) as unknown as AdminOverview;
response.json({
generatedAt: new Date().toISOString(),
gateway: {
version: options.version ?? "0.1.0",
uptimeSeconds: overview.gateway.uptimeSeconds,
node: process.version,
platform: process.platform,
arch: process.arch,
},
sessions: {
active: options.getActiveSessions(),
peak: options.getPeakSessions(),
created: options.getCreatedSessions?.() ?? 0,
limit: 100,
},
teamSpeak: overview.teamSpeak,
database: { schemaVersion: options.service.database.schemaVersion },
logs: { available: Boolean(options.logFile && existsSync(options.logFile)) },
});
});
router.get("/diagnostics/report", (_request, response) => {
const overview = options.service.getOverview(
options.getActiveSessions(),
options.getPeakSessions(),
options.startedAt,
) as unknown as AdminOverview;
const report = {
generatedAt: new Date().toISOString(),
gateway: {
version: options.version ?? "0.1.0",
uptimeSeconds: overview.gateway.uptimeSeconds,
node: process.version,
platform: process.platform,
arch: process.arch,
},
sessions: {
active: options.getActiveSessions(),
peak: options.getPeakSessions(),
created: options.getCreatedSessions?.() ?? 0,
limit: 100,
},
teamSpeak: {
status: overview.teamSpeak.status,
lastTestAt: overview.teamSpeak.lastTestAt,
latencyMs: overview.teamSpeak.latencyMs,
lastError: overview.teamSpeak.lastError,
},
database: { schemaVersion: options.service.database.schemaVersion },
audit: options.service.database.recentAudit(50),
};
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.setHeader("Content-Disposition", `attachment; filename="webspeak-diagnostic-report.json"`);
response.send(JSON.stringify(report, null, 2));
});
router.get("/backup", (_request, response) => {
try {
const backup = options.service.database.exportBackup();
options.service.database.addAudit("ADMIN_BACKUP_EXPORTED");
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", `attachment; filename="webspeak-backup-${new Date().toISOString().slice(0, 10)}.db"`);
response.send(backup);
} catch {
response.status(500).json({ ok: false, code: "BACKUP_FAILED" });
}
});
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
response.json({ ok: true, settings: options.service.getAdminSettings() });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/server/test", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const body = asRecord(request.body);
const action = readPasswordAction(body.passwordAction);
const password = action === "remove"
? ""
: typeof body.serverPassword === "string"
? body.serverPassword.slice(0, 512)
: options.service.getConnectionPolicy().serverPassword;
await runProbe(options.service, response, readString(body, "target", 300), password, true);
});
router.post("/legacy-import/dismiss", requireSameOrigin, requireCsrf(options.sessions), (_request, response) => {
options.service.dismissLegacyImportNotice();
response.json({ ok: true });
});
router.use((error: unknown, _request: Request, response: Response, _next: NextFunction) => {
sendAdminError(response, error);
});
return router;
}
function requireAdmin(sessions: AdminSessionStore, service: AdminService) {
return (request: Request, response: Response, next: NextFunction): void => {
if (!sessions.get(request)) {
response.status(401).json({ ok: false, code: "AUTH_REQUIRED" });
return;
}
if (service.isPasswordChangeRequired()) {
response.status(403).json({ ok: false, code: "PASSWORD_CHANGE_REQUIRED" });
return;
}
next();
};
}
function requireCsrf(sessions: AdminSessionStore) {
return (request: Request, response: Response, next: NextFunction): void => {
const session = sessions.get(request);
const csrf = request.header("x-csrf-token");
if (!session || !csrf || csrf !== session.csrfToken) {
response.status(403).json({ ok: false, code: "CSRF_REJECTED" });
return;
}
next();
};
}
function requireSameOrigin(request: Request, response: Response, next: NextFunction): void {
if (!request.is("application/json")) {
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
return;
}
const origin = request.header("origin");
const host = request.header("host");
try {
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
} catch {
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
return;
}
next();
}
async function runProbe(
service: AdminService,
response: Response,
target: string,
password: string,
persistResult: boolean,
): Promise<void> {
try {
response.json(await service.testConnection(target, password, persistResult));
} catch (error: unknown) {
if (error instanceof TeamSpeakProbeError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
sendAdminError(response, error);
}
}
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
return {
target: readString(body, "target", 300),
serverPassword: typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : undefined,
passwordAction: readPasswordAction(body.passwordAction),
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
siteName: readString(body, "siteName", 80),
welcomeText: readOptionalString(body, "welcomeText", 500),
webRtcEnabled: body.webRtcEnabled === true,
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
};
}
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
return value === "replace" || value === "remove" ? value : "keep";
}
function asRecord(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new AdminInputError("INVALID_REQUEST", "Request body is invalid");
return value as Record<string, unknown>;
}
function readString(body: Record<string, unknown>, key: string, max: number): string {
if (typeof body[key] !== "string" || body[key].length > max) throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
return body[key];
}
function readOptionalInteger(body: Record<string, unknown>, key: string): number | undefined {
if (body[key] === undefined) return undefined;
if (typeof body[key] !== "number" || !Number.isSafeInteger(body[key])) {
throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
}
return body[key];
}
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
}
function readOptionalNumber(body: Record<string, unknown>, key: string, fallback: number): number {
return body[key] === undefined ? fallback : typeof body[key] === "number" ? body[key] : Number.NaN;
}
function readLimit(value: unknown, fallback: number): number {
const limit = typeof value === "string" ? Number(value) : fallback;
return Number.isFinite(limit) ? Math.max(1, Math.min(200, Math.floor(limit))) : fallback;
}
interface AdminLogEntry {
timestamp: string | null;
level: string;
message: string;
context: Record<string, string | number | boolean>;
}
function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEntry[] {
if (!logFile) return [];
try {
const lines = readFileSync(logFile, "utf8").split(/\r?\n/).filter(Boolean).slice(-limit);
return lines.map((line) => {
try {
const raw = JSON.parse(line) as Record<string, unknown>;
const context: Record<string, string | number | boolean> = {};
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "channel", "reconnect", "port"]) {
const value = raw[key];
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") context[key] = value;
}
return {
timestamp: typeof raw.time === "string" ? raw.time : null,
level: logLevelName(raw.level),
message: typeof raw.msg === "string" ? raw.msg : "",
context,
};
} catch {
return { timestamp: null, level: "INFO", message: line.slice(0, 1000), context: {} };
}
});
} catch {
return [];
}
}
interface AdminOverview {
gateway: { uptimeSeconds: number };
teamSpeak: {
target: string;
status: string;
lastTestAt: string | null;
latencyMs: number | null;
lastError: string | null;
};
}
function logLevelName(level: unknown): string {
if (level === 10) return "DEBUG";
if (level === 30) return "INFO";
if (level === 40) return "WARN";
if (level === 50) return "ERROR";
if (level === 60) return "FATAL";
return typeof level === "string" ? level.toUpperCase() : "INFO";
}
function sendAdminError(response: Response, error: unknown): void {
if (error instanceof AdminInputError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
}
+370
View File
@@ -0,0 +1,370 @@
import { createHash, randomBytes } from "node:crypto";
import { existsSync } from "node:fs";
import type { Logger } from "../logger.js";
import { loadConfig } from "../config.js";
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
export interface AdminSettingsInput {
target: string;
serverPassword?: string;
passwordAction?: "keep" | "replace" | "remove";
accessMode: AccessMode;
siteName: string;
welcomeText: string;
webRtcEnabled: boolean;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
}
export interface ConnectionPolicy {
defaultTarget: TeamSpeakTarget;
serverPassword: string;
accessMode: AccessMode;
}
export interface ManagedInviteInput {
channel: string;
expiresInHours: number;
maxUses: number;
}
export interface ManagedInviteView {
id: string;
target: string;
channel: string;
expiresAt: string;
maxUses: number;
useCount: number;
createdAt: string;
revokedAt: string | null;
status: "active" | "expired" | "exhausted" | "revoked";
}
type ProbeFunction = typeof probeTeamSpeak;
export class AdminService {
constructor(
readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
private readonly logger: Logger,
private readonly legacyConfigPath: string,
private readonly probe: ProbeFunction = probeTeamSpeak,
private readonly version = "0.1.0",
) {}
async initialize(): Promise<void> {
this.importLegacyConfigOnce();
if (!this.database.hasAdmin()) {
const credential = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
this.database.initializeAdmin(credential, this.toSettingsUpdate(this.database.getSettings()));
this.logger.warn("Default admin account created. Change the password on first login.");
}
}
isInitialized(): boolean {
return this.database.hasAdmin();
}
async verifyPassword(username: string, password: string): Promise<boolean> {
const credential = this.database.getAdminCredential();
return credential?.username === username && await verifyAdminPassword(password, credential);
}
isPasswordChangeRequired(): boolean {
return this.database.getAdminCredential()?.mustChangePassword === true;
}
async changePassword(password: string): Promise<void> {
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 });
this.database.updateAdminCredential(replacement);
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
}
getPublicConfig(): Record<string, unknown> {
const settings = this.database.getSettings();
return {
version: this.version,
initialized: this.isInitialized(),
siteName: settings.siteName,
welcomeText: settings.welcomeText,
accessMode: settings.accessMode,
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
};
}
getAdminSettings(): Record<string, unknown> {
const settings = this.database.getSettings();
return {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
hasPassword: Boolean(settings.tsPasswordEncrypted),
accessMode: settings.accessMode,
siteName: settings.siteName,
welcomeText: settings.welcomeText,
lastTestAt: settings.lastTestAt,
lastTestLatencyMs: settings.lastTestLatencyMs,
lastTestError: settings.lastTestError,
webRtcEnabled: settings.webRtcEnabled,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
internalPort: 3040,
updatedAt: settings.updatedAt,
};
}
getWebRtcAudioOptions(): WebRtcAudioOptions {
const settings = this.database.getSettings();
return {
enabled: settings.webRtcEnabled,
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
};
}
updateSettings(input: AdminSettingsInput): void {
const current = this.database.getSettings();
const settings = this.normalizeSettings(input, current);
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
this.database.updateSettings(settings);
if (targetChanged) this.database.clearConnectionTest();
}
getConnectionPolicy(): ConnectionPolicy {
const settings = this.database.getSettings();
let serverPassword = "";
try {
serverPassword = decryptSecret(settings.tsPasswordEncrypted, this.masterSecret);
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TeamSpeak password could not be decrypted");
}
return {
defaultTarget: { host: settings.tsHost, port: settings.tsPort },
serverPassword,
accessMode: settings.accessMode,
};
}
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<Omit<TeamSpeakProbeResult, "protocol">> {
let target: TeamSpeakTarget;
try {
target = parseTeamSpeakTarget(targetText);
} catch {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
try {
const result = await this.probe(target, password, this.logger);
if (persistResult) {
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
}
const { protocol: _protocol, ...publicResult } = result;
return publicResult;
} catch (error: unknown) {
const probeError = error instanceof TeamSpeakProbeError
? error
: new TeamSpeakProbeError("INTERNAL_ERROR", "Connection test failed", error);
if (persistResult) {
this.database.recordConnectionTest({ protocol: null, latencyMs: null, error: probeError.code });
this.database.addAudit("CONNECTION_TEST_FAILED", { code: probeError.code });
}
throw probeError;
}
}
getOverview(activeSessions: number, peakSessions: number, startedAt: number): Record<string, unknown> {
const settings = this.database.getSettings();
return {
gateway: {
status: "running",
version: this.version,
uptimeSeconds: Math.max(0, Math.floor((Date.now() - startedAt) / 1000)),
},
teamSpeak: {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
lastTestAt: settings.lastTestAt,
latencyMs: settings.lastTestLatencyMs,
lastError: settings.lastTestError,
},
sessions: { active: activeSessions, peak: peakSessions, limit: 100 },
recentEvents: this.database.recentAudit(),
legacyConfigImported: this.database.getMeta("legacy_import_notice_pending") === "1",
};
}
createManagedInvite(input: ManagedInviteInput): { invite: ManagedInviteView; token: string } {
const channel = input.channel.trim();
if (channel.length > 100) throw new AdminInputError("INVALID_INVITE_CHANNEL", "Invite channel cannot exceed 100 characters");
if (!Number.isFinite(input.expiresInHours) || input.expiresInHours < 1 || input.expiresInHours > 720) {
throw new AdminInputError("INVALID_INVITE_EXPIRY", "Invite expiry must be between 1 and 720 hours");
}
if (!Number.isInteger(input.maxUses) || input.maxUses < 0 || input.maxUses > 10000) {
throw new AdminInputError("INVALID_INVITE_USES", "Invite max uses must be between 0 and 10000");
}
const settings = this.database.getSettings();
const token = randomBytes(32).toString("base64url");
const record = this.database.createManagedInvite({
id: `invite-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`,
tokenHash: hashInviteToken(token),
targetHost: settings.tsHost,
targetPort: settings.tsPort,
serverPasswordEncrypted: settings.tsPasswordEncrypted,
channel,
expiresAt: new Date(Date.now() + input.expiresInHours * 60 * 60 * 1000).toISOString(),
maxUses: input.maxUses,
});
this.database.addAudit("INVITE_CREATED", { id: record.id, channel, maxUses: input.maxUses });
return { invite: this.toInviteView(record), token };
}
listManagedInvites(): ManagedInviteView[] {
return this.database.listManagedInvites().map((record) => this.toInviteView(record));
}
revokeManagedInvite(id: string): boolean {
if (!/^invite-[a-z0-9-]+$/i.test(id) || id.length > 100) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
const revoked = this.database.revokeManagedInvite(id);
if (revoked) this.database.addAudit("INVITE_REVOKED", { id });
return revoked;
}
consumeManagedInvite(token: string): { target: TeamSpeakTarget; serverPassword: string; channel: string } | null {
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
const record = this.database.consumeManagedInvite(hashInviteToken(token));
if (!record) return null;
let serverPassword = "";
try {
serverPassword = decryptSecret(record.serverPasswordEncrypted, this.masterSecret);
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error), inviteId: record.id }, "Managed invite password could not be decrypted");
}
this.database.addAudit("INVITE_CONSUMED", { id: record.id });
return { target: { host: record.targetHost, port: record.targetPort }, serverPassword, channel: record.channel };
}
dismissLegacyImportNotice(): void {
this.database.setMeta("legacy_import_notice_pending", "0");
}
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
let target: TeamSpeakTarget;
try {
target = parseTeamSpeakTarget(input.target);
} catch {
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
}
const siteName = input.siteName.trim();
const welcomeText = input.welcomeText.trim();
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
}
if (typeof input.webRtcEnabled !== "boolean") {
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
}
const webRtcUdpStart = input.webRtcUdpStart ?? current.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0];
const webRtcUdpEnd = input.webRtcUdpEnd ?? current.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1];
if (!Number.isInteger(webRtcUdpStart) || webRtcUdpStart < WEBRTC_UDP_PORT_MIN || webRtcUdpStart > WEBRTC_UDP_PORT_MAX) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must be between 1024 and 65535");
}
if (!Number.isInteger(webRtcUdpEnd) || webRtcUdpEnd < WEBRTC_UDP_PORT_MIN || webRtcUdpEnd > WEBRTC_UDP_PORT_MAX) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP end port must be between 1024 and 65535");
}
if (webRtcUdpStart > webRtcUdpEnd) {
throw new AdminInputError("INVALID_WEBRTC_PORT_RANGE", "WebRTC UDP start port must not exceed the end port");
}
if (current.webRtcEnabled && (webRtcUdpStart !== current.webRtcUdpStart || webRtcUdpEnd !== current.webRtcUdpEnd)) {
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
if (action === "remove") encryptedPassword = null;
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
return {
siteName,
welcomeText,
accessMode: input.accessMode,
tsHost: target.host,
tsPort: target.port,
tsPasswordEncrypted: encryptedPassword,
webRtcEnabled: input.webRtcEnabled,
webRtcUdpStart,
webRtcUdpEnd,
};
}
private toInviteView(record: ManagedInviteRecord): ManagedInviteView {
const now = Date.now();
const expired = Date.parse(record.expiresAt) <= now;
const exhausted = record.maxUses > 0 && record.useCount >= record.maxUses;
return {
id: record.id,
target: formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }),
channel: record.channel,
expiresAt: record.expiresAt,
maxUses: record.maxUses,
useCount: record.useCount,
createdAt: record.createdAt,
revokedAt: record.revokedAt,
status: record.revokedAt ? "revoked" : expired ? "expired" : exhausted ? "exhausted" : "active",
};
}
private toSettingsUpdate(settings: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
return {
siteName: settings.siteName,
welcomeText: settings.welcomeText,
accessMode: settings.accessMode,
tsHost: settings.tsHost,
tsPort: settings.tsPort,
tsPasswordEncrypted: settings.tsPasswordEncrypted,
webRtcEnabled: settings.webRtcEnabled,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
};
}
private importLegacyConfigOnce(): void {
if (this.database.getMeta("legacy_config_checked") === "1") return;
if (existsSync(this.legacyConfigPath)) {
const legacy = loadConfig(this.legacyConfigPath);
const current = this.database.getSettings();
this.database.updateSettings({
siteName: current.siteName,
welcomeText: current.welcomeText,
accessMode: current.accessMode,
tsHost: legacy.tsHost,
tsPort: legacy.tsPort,
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
webRtcEnabled: current.webRtcEnabled,
webRtcUdpStart: current.webRtcUdpStart,
webRtcUdpEnd: current.webRtcUdpEnd,
}, "LEGACY_CONFIG_IMPORTED");
this.database.setMeta("legacy_config_imported", "1");
this.database.setMeta("legacy_import_notice_pending", "1");
this.logger.info("Legacy config imported; WebSpeak settings are now managed from /admin");
}
this.database.setMeta("legacy_config_checked", "1");
}
}
function hashInviteToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
export class AdminInputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "AdminInputError";
}
}
+77
View File
@@ -0,0 +1,77 @@
import { createHash, randomBytes } from "node:crypto";
import type { Request, Response } from "express";
import type { TLSSocket } from "node:tls";
const COOKIE_NAME = "webspeak_admin";
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
interface AdminSession {
csrfToken: string;
expiresAt: number;
}
export class AdminSessionStore {
private readonly sessions = new Map<string, AdminSession>();
create(response: Response, secure: boolean, now = Date.now()): { csrfToken: string; expiresAt: number } {
const token = randomBytes(32).toString("base64url");
const csrfToken = randomBytes(24).toString("base64url");
const expiresAt = now + SESSION_TTL_MS;
this.sessions.set(hashToken(token), { csrfToken, expiresAt });
response.cookie(COOKIE_NAME, token, {
httpOnly: true,
sameSite: "strict",
secure,
path: "/",
maxAge: SESSION_TTL_MS,
});
return { csrfToken, expiresAt };
}
get(request: Request, now = Date.now()): AdminSession | null {
const token = readCookie(request.headers.cookie, COOKIE_NAME);
if (!token) return null;
const key = hashToken(token);
const session = this.sessions.get(key);
if (!session) return null;
if (session.expiresAt <= now) {
this.sessions.delete(key);
return null;
}
return session;
}
destroy(request: Request, response: Response, secure: boolean): void {
const token = readCookie(request.headers.cookie, COOKIE_NAME);
if (token) this.sessions.delete(hashToken(token));
response.clearCookie(COOKIE_NAME, { httpOnly: true, sameSite: "strict", secure, path: "/" });
}
clear(): void {
this.sessions.clear();
}
}
export function isSecureRequest(request: Request): boolean {
return (request.socket as TLSSocket).encrypted === true;
}
function hashToken(token: string): string {
return createHash("sha256").update(token).digest("base64url");
}
function readCookie(header: string | undefined, name: string): string | null {
if (!header) return null;
for (const part of header.split(";")) {
const separator = part.indexOf("=");
if (separator < 0) continue;
if (part.slice(0, separator).trim() === name) {
try {
return decodeURIComponent(part.slice(separator + 1).trim());
} catch {
return null;
}
}
}
return null;
}
+55
View File
@@ -0,0 +1,55 @@
const WINDOW_MS = 5 * 60 * 1000;
const MAX_FAILURES = 5;
interface LoginAttempt {
failures: number;
firstFailureAt: number;
}
export class AdminLoginRateLimiter {
private readonly attempts = new Map<string, LoginAttempt>();
constructor(private readonly maxTrackedPeers = 1024) {}
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 {
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);
}
}
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
? { failures: 1, firstFailureAt: now }
: { ...current, failures: current.failures + 1 };
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);
}
private pruneExpired(now: number): void {
for (const [peer, attempt] of this.attempts) {
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
}
}
}
export function waitFor(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+45 -36
View File
@@ -1,65 +1,74 @@
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import {
DEFAULT_TEAM_SPEAK_PORT,
parseTeamSpeakTargetParts,
} from "./domain/teamspeak-target.js";
/** The only TeamSpeak state still read from the legacy JSON config. */
export interface AppConfig {
/** HTTP server port */
port: number;
/** TeamSpeak server host */
tsHost: string;
/** TeamSpeak voice/UDP port */
tsPort: number;
/** TS server password (empty if none) */
tsServerPassword: string;
/** Force protocol: "ts3" | "ts6" | undefined for auto-detect */
tsServerProtocol?: "ts3" | "ts6";
/** Max concurrent web clients */
maxClients: number;
/** Trust X-Forwarded-* headers (for reverse proxy) */
trustProxy: boolean;
}
export function getDefaultConfig(): AppConfig {
return {
port: 3040,
tsHost: "127.0.0.1",
tsPort: 9987,
tsPort: DEFAULT_TEAM_SPEAK_PORT,
tsServerPassword: "",
tsServerProtocol: undefined,
maxClients: 20,
trustProxy: false,
};
}
/**
* Convert both the old JSON shape and the M000 shape into the normalized
* normalized legacy model. Deprecated fields are intentionally ignored and disappear
* when the migrated model is written back.
*/
export function migrateConfig(input: unknown): AppConfig {
const defaults = getDefaultConfig();
if (!isRecord(input)) return defaults;
const rawHost = typeof input.tsHost === "string" && input.tsHost.trim()
? input.tsHost.trim()
: defaults.tsHost;
const rawPort = input.tsPort === undefined ? undefined : input.tsPort;
let target;
try {
target = parseTeamSpeakTargetParts(rawHost, toPortValue(rawPort), defaults.tsPort);
} catch {
target = { host: defaults.tsHost, port: defaults.tsPort };
}
return {
tsHost: target.host,
tsPort: target.port,
tsServerPassword: typeof input.tsServerPassword === "string" ? input.tsServerPassword : defaults.tsServerPassword,
};
}
export function loadConfig(path: string): AppConfig {
const defaults = getDefaultConfig();
try {
const input = JSON.parse(readFileSync(path, "utf-8")) as Record<string, unknown>;
const positiveInt = (value: unknown, fallback: number) => {
const number = typeof value === "number" ? value : Number(value);
return Number.isInteger(number) && number > 0 ? number : fallback;
};
const protocol = input.tsServerProtocol === "ts3" || input.tsServerProtocol === "ts6"
? input.tsServerProtocol
: defaults.tsServerProtocol;
return {
port: positiveInt(input.port, defaults.port),
tsHost: typeof input.tsHost === "string" && input.tsHost.trim() ? input.tsHost.trim() : defaults.tsHost,
tsPort: positiveInt(input.tsPort, defaults.tsPort),
tsServerPassword: typeof input.tsServerPassword === "string" ? input.tsServerPassword : defaults.tsServerPassword,
tsServerProtocol: protocol,
maxClients: positiveInt(input.maxClients, defaults.maxClients),
trustProxy: typeof input.trustProxy === "boolean" ? input.trustProxy : defaults.trustProxy,
};
return migrateConfig(JSON.parse(readFileSync(path, "utf-8")) as unknown);
} catch {
return defaults;
return getDefaultConfig();
}
}
/** Write only the normalized legacy shape; this is the one-time legacy cleanup. */
export function saveConfig(path: string, config: AppConfig): void {
try {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(config, null, 2), "utf-8");
writeFileSync(path, JSON.stringify(migrateConfig(config), null, 2), "utf-8");
} catch {
// config.json may be read-only (e.g. running under systemd as non-root)
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function toPortValue(value: unknown): string | number | undefined {
return typeof value === "string" || typeof value === "number" ? value : undefined;
}
+9
View File
@@ -0,0 +1,9 @@
/** The HTTP port is part of the WebSpeak deployment contract. */
export const APP_PORT = 3040;
/** Hard safety ceiling for independently connected browser sessions. */
export const MAX_ACTIVE_SESSIONS = 100;
export function canAcceptSession(activeSessionCount: number): boolean {
return Number.isInteger(activeSessionCount) && activeSessionCount >= 0 && activeSessionCount < MAX_ACTIVE_SESSIONS;
}
+99
View File
@@ -0,0 +1,99 @@
export const DEFAULT_TEAM_SPEAK_PORT = 9987;
export interface TeamSpeakTarget {
host: string;
port: number;
}
export class InvalidTeamSpeakTargetError extends Error {
constructor(message = "Invalid TeamSpeak server address") {
super(message);
this.name = "InvalidTeamSpeakTargetError";
}
}
/** Parse a user-facing TeamSpeak target such as example.com:9988 or example.com#9988. */
export function parseTeamSpeakTarget(value: string, fallbackPort = DEFAULT_TEAM_SPEAK_PORT): TeamSpeakTarget {
const input = value.trim();
if (!input) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
const hash = input.indexOf("#");
if (hash >= 0) {
if (input.indexOf("#", hash + 1) >= 0) {
throw new InvalidTeamSpeakTargetError("TeamSpeak target has too many port separators");
}
const hashHost = input.slice(0, hash);
const host = hashHost.startsWith("[") && hashHost.endsWith("]") ? hashHost.slice(1, -1) : hashHost;
return createTarget(host, input.slice(hash + 1));
}
if (input.startsWith("[")) {
const closingBracket = input.indexOf("]");
if (closingBracket < 0) throw new InvalidTeamSpeakTargetError("IPv6 addresses must close with ]");
const host = input.slice(1, closingBracket);
const suffix = input.slice(closingBracket + 1);
if (suffix && !suffix.startsWith(":")) {
throw new InvalidTeamSpeakTargetError("Invalid port separator after IPv6 address");
}
return createTarget(host, suffix ? suffix.slice(1) : fallbackPort);
}
const colon = input.indexOf(":");
if (colon < 0) return createTarget(input, fallbackPort);
if (input.indexOf(":", colon + 1) >= 0) {
throw new InvalidTeamSpeakTargetError("IPv6 addresses must use bracket notation");
}
return createTarget(input.slice(0, colon), input.slice(colon + 1));
}
/** Parse the legacy split host/port fields while accepting a bracketed IPv6 host. */
export function parseTeamSpeakTargetParts(
hostValue: string,
portValue?: string | number,
fallbackPort = DEFAULT_TEAM_SPEAK_PORT,
): TeamSpeakTarget {
const host = hostValue.trim();
if (!host) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
if (portValue !== undefined && String(portValue).trim() !== "") {
const hostOnly = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
if (hostOnly.includes(":")) return createTarget(hostOnly, portValue);
if (host.includes(":")) {
throw new InvalidTeamSpeakTargetError("Use one TeamSpeak address field when specifying a port");
}
return createTarget(hostOnly, portValue);
}
return parseTeamSpeakTarget(host, fallbackPort);
}
export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
return target.host.includes(":") ? `[${target.host}]:${target.port}` : `${target.host}:${target.port}`;
}
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
return formatTeamSpeakTarget(target).toLocaleLowerCase();
}
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
const host = hostValue.trim().toLocaleLowerCase();
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
if (host.includes(":")) {
// A raw IPv6 host is valid only when it came from bracket notation.
if (!host.split(":").every((part) => /^[0-9a-f]*$/i.test(part))) {
throw new InvalidTeamSpeakTargetError("Invalid IPv6 server address");
}
} else if (!/^[a-z0-9._-]+$/i.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
const portText = String(portValue).trim();
if (!/^\d+$/.test(portText)) throw new InvalidTeamSpeakTargetError("TeamSpeak port must be a number");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new InvalidTeamSpeakTargetError("TeamSpeak port must be between 1 and 65535");
}
return { host, port };
}
+45
View File
@@ -0,0 +1,45 @@
export type WebSpeakErrorCode =
| "invalid_target"
| "unreachable"
| "timeout"
| "authentication_failed"
| "protocol_negotiation_failed"
| "server_full"
| "unknown";
export class WebSpeakError extends Error {
readonly code: WebSpeakErrorCode;
readonly retryable: boolean;
readonly cause?: unknown;
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown) {
super(message);
this.name = "WebSpeakError";
this.code = code;
this.retryable = retryable;
this.cause = cause;
}
}
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const candidate = error as { code?: unknown; message?: unknown } | null;
const code = typeof candidate?.code === "string" ? candidate.code : "";
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
const text = `${code} ${message}`.toLocaleLowerCase();
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error);
}
if (/timeout|timed out|ack timeout|idle timeout/.test(text)) {
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error);
}
if (/econnrefused|enotfound|ehostunreach|enetunreach|network|socket|dns/.test(text)) {
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error);
}
if (/protocol|handshake|crypto|init1/.test(text)) {
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error);
}
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
}
+48 -14
View File
@@ -1,40 +1,56 @@
import path from "node:path";
import { existsSync } from "node:fs";
import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { loadConfig, saveConfig } from "./config.js";
import { createLogger } from "./logger.js";
import { createWebServer } from "./server/server.js";
import { APP_PORT } from "./constants.js";
import { WebSpeakDatabase } from "./persistence/database.js";
import { loadOrCreateMasterSecret } from "./security/master-secret.js";
import { AdminService } from "./admin/admin-service.js";
import { JoinTicketStore } from "./server/join-ticket.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
const CONFIG_PATH = path.join(ROOT_DIR, "config.json");
const CERT_DIR = path.join(ROOT_DIR, "certs");
const DATA_DIR = path.join(ROOT_DIR, "data");
// Production images mount the persistent volume at /data. Source installs
// keep the historical project-local data directory unless overridden.
const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "data");
const LOG_DIR = path.join(DATA_DIR, "logs");
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
const APP_VERSION = readPackageVersion();
async function main() {
const config = loadConfig(CONFIG_PATH);
saveConfig(CONFIG_PATH, config);
const logger = createLogger(LOG_DIR);
const database = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
const masterSecret = loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key"));
const adminService = new AdminService(
database,
masterSecret,
logger,
CONFIG_PATH,
undefined,
APP_VERSION,
);
await adminService.initialize();
removeObsoleteBootstrapFile();
const joinTickets = new JoinTicketStore();
logger.info({ config }, "Starting WebSpeak server");
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
const webServer = createWebServer({
port: config.port,
trustProxy: config.trustProxy,
port: APP_PORT,
version: APP_VERSION,
logFile: path.join(LOG_DIR, "webspeak.log"),
staticDir: STATIC_DIR,
certDir: hasCert ? CERT_DIR : undefined,
voiceBridgeOptions: {
tsHost: config.tsHost,
tsPort: config.tsPort,
tsServerPassword: config.tsServerPassword,
tsServerProtocol: config.tsServerProtocol,
maxClients: config.maxClients,
joinTickets,
webRtc: () => adminService.getWebRtcAudioOptions(),
},
adminService,
logger,
});
@@ -44,12 +60,30 @@ async function main() {
const shutdown = async (signal: string) => {
logger.info({ signal }, "Shutting down");
await webServer.stop();
database.close();
process.exit(0);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
}
function readPackageVersion(): string {
try {
const packageJson = JSON.parse(readFileSync(path.join(ROOT_DIR, "package.json"), "utf8")) as { version?: unknown };
return typeof packageJson.version === "string" && packageJson.version ? packageJson.version : "0.1.0";
} catch {
return "0.1.0";
}
}
function removeObsoleteBootstrapFile(): void {
try {
unlinkSync(path.join(DATA_DIR, "bootstrap"));
} catch (error: unknown) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
}
}
main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
+55 -16
View File
@@ -1,5 +1,9 @@
import pino from "pino";
import { mkdirSync } from "node:fs";
import { appendFile, existsSync, mkdirSync, renameSync, statSync } from "node:fs";
import { Writable } from "node:stream";
const MAX_LOG_BYTES = 10 * 1024 * 1024;
const MAX_ROTATED_LOGS = 3;
export interface Logger {
debug(obj: Record<string, unknown>, msg: string): void;
@@ -14,23 +18,17 @@ export interface Logger {
}
export function createLogger(logDir?: string): Logger {
const targets: pino.TransportTargetOptions[] = [
{ target: "pino/file", options: { destination: 1 }, level: "info" },
];
if (logDir) {
mkdirSync(logDir, { recursive: true });
targets.push({
target: "pino/file",
options: { destination: `${logDir}/webspeak.log` },
level: "debug",
});
}
const baseLogger = pino({
const loggerOptions = {
level: "debug",
timestamp: pino.stdTimeFunctions.isoTime,
...(targets.length > 1 ? { transport: { targets } } : {}),
});
redact: {
paths: ["password", "*.password", "serverPassword", "*.serverPassword", "token", "*.token", "identity", "*.identity"],
censor: "[Redacted]",
},
};
const baseLogger = logDir
? createFileLogger(loggerOptions, `${logDir}/webspeak.log`)
: pino(loggerOptions, pino.destination(1));
function wrap(l: pino.Logger): Logger {
function doLog(
@@ -60,3 +58,44 @@ export function createLogger(logDir?: string): Logger {
return wrap(baseLogger);
}
function createFileLogger(options: { level: string; timestamp: typeof pino.stdTimeFunctions.isoTime }, logPath: string): pino.Logger {
mkdirSync(logPath.replace(/[\\/][^\\/]+$/, ""), { recursive: true });
return pino(options, pino.multistream([
{ level: "info", stream: process.stdout },
{ level: "debug", stream: new RotatingFileStream(logPath) },
]));
}
class RotatingFileStream extends Writable {
private bytes: number;
constructor(private readonly filePath: string) {
super();
this.bytes = existsSync(filePath) ? statSync(filePath).size : 0;
if (this.bytes >= MAX_LOG_BYTES) this.rotate();
}
override _write(chunk: unknown, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), encoding);
try {
if (this.bytes + buffer.length > MAX_LOG_BYTES) this.rotate();
appendFile(this.filePath, buffer, (error) => {
if (!error) this.bytes += buffer.length;
callback(error);
});
} catch (error: unknown) {
callback(error instanceof Error ? error : new Error(String(error)));
}
}
private rotate(): void {
for (let index = MAX_ROTATED_LOGS - 1; index >= 1; index--) {
const source = `${this.filePath}.${index}`;
const destination = `${this.filePath}.${index + 1}`;
if (existsSync(source)) renameSync(source, destination);
}
if (existsSync(this.filePath)) renameSync(this.filePath, `${this.filePath}.1`);
this.bytes = 0;
}
}
+436
View File
@@ -0,0 +1,436 @@
import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { dirname } from "node:path";
import { DatabaseSync } from "node:sqlite";
import type { AdminCredential } from "../security/admin-password.js";
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
export const DATABASE_SCHEMA_VERSION = 3;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
siteName: string;
welcomeText: string;
accessMode: AccessMode;
tsHost: string;
tsPort: number;
tsPasswordEncrypted: string | null;
detectedProtocol: TeamSpeakProtocol | null;
lastTestAt: string | null;
lastTestLatencyMs: number | null;
lastTestError: string | null;
webRtcEnabled: boolean;
webRtcUdpStart: number;
webRtcUdpEnd: number;
updatedAt: string;
}
export interface SettingsUpdate {
siteName: string;
welcomeText: string;
accessMode: AccessMode;
tsHost: string;
tsPort: number;
tsPasswordEncrypted: string | null;
webRtcEnabled: boolean;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
}
export interface ManagedInviteRecord {
id: string;
tokenHash: string;
targetHost: string;
targetPort: number;
serverPasswordEncrypted: string | null;
channel: string;
expiresAt: string;
maxUses: number;
useCount: number;
createdAt: string;
revokedAt: string | null;
}
interface ManagedInviteRow extends Record<string, unknown> {
id: string;
token_hash: string;
target_host: string;
target_port: number;
server_password_encrypted: string | null;
channel: string;
expires_at: string;
max_uses: number;
use_count: number;
created_at: string;
revoked_at: string | null;
}
interface SettingsRow extends Record<string, unknown> {
site_name: string;
welcome_text: string;
access_mode: string;
ts_host: string;
ts_port: number;
ts_password_encrypted: string | null;
detected_protocol: string | null;
last_test_at: string | null;
last_test_latency_ms: number | null;
last_test_error: string | null;
webrtc_enabled: number;
webrtc_public_host: string;
webrtc_udp_start: number;
webrtc_udp_end: number;
updated_at: string;
}
export class WebSpeakDatabase {
private readonly database: DatabaseSync;
constructor(private readonly path: string) {
mkdirSync(dirname(path), { recursive: true });
const existed = existsSync(path);
this.database = new DatabaseSync(path);
this.database.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL;");
this.migrate(existed);
}
close(): void {
this.database.close();
}
get schemaVersion(): number {
return Number((this.database.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
}
hasAdmin(): boolean {
return Boolean(this.database.prepare("SELECT 1 AS present FROM admin_credentials WHERE id = 1").get());
}
getAdminCredential(): AdminCredential | null {
const row = this.database.prepare("SELECT credential_json FROM admin_credentials WHERE id = 1").get() as { credential_json?: string } | undefined;
if (!row?.credential_json) return null;
const credential = JSON.parse(row.credential_json) as Partial<AdminCredential>;
return {
...credential,
version: 1,
username: typeof credential.username === "string" && credential.username ? credential.username : "admin",
mustChangePassword: credential.mustChangePassword === true,
} as AdminCredential;
}
initializeAdmin(credential: AdminCredential, settings: SettingsUpdate): void {
this.transaction(() => {
if (this.hasAdmin()) throw new Error("WebSpeak is already initialized");
const now = new Date().toISOString();
this.database.prepare(
"INSERT INTO admin_credentials (id, credential_json, created_at, updated_at) VALUES (1, ?, ?, ?)",
).run(JSON.stringify(credential), now, now);
this.writeSettings(settings, now);
this.insertAudit("ADMIN_INITIALIZED", { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
});
}
updateAdminCredential(credential: AdminCredential): void {
const now = new Date().toISOString();
this.database.prepare(
"UPDATE admin_credentials SET credential_json = ?, updated_at = ? WHERE id = 1",
).run(JSON.stringify(credential), now);
}
getSettings(): PersistedSettings {
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
return {
siteName: row.site_name,
welcomeText: row.welcome_text,
accessMode: row.access_mode === "open" ? "open" : "fixed",
tsHost: row.ts_host,
tsPort: row.ts_port,
tsPasswordEncrypted: row.ts_password_encrypted,
detectedProtocol: row.detected_protocol === "ts3" || row.detected_protocol === "ts6" ? row.detected_protocol : null,
lastTestAt: row.last_test_at,
lastTestLatencyMs: row.last_test_latency_ms,
lastTestError: row.last_test_error,
webRtcEnabled: row.webrtc_enabled === 1,
webRtcUdpStart: row.webrtc_udp_start,
webRtcUdpEnd: row.webrtc_udp_end,
updatedAt: row.updated_at,
};
}
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
const now = new Date().toISOString();
this.transaction(() => {
this.writeSettings(settings, now);
this.insertAudit(auditEvent, { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
});
}
recordConnectionTest(result: {
protocol: TeamSpeakProtocol | null;
latencyMs: number | null;
error: string | null;
}): void {
this.database.prepare(
`UPDATE settings
SET detected_protocol = ?, last_test_at = ?, last_test_latency_ms = ?, last_test_error = ?
WHERE id = 1`,
).run(result.protocol, new Date().toISOString(), result.latencyMs, result.error);
}
clearConnectionTest(): void {
this.database.exec(
"UPDATE settings SET detected_protocol = NULL, last_test_at = NULL, last_test_latency_ms = NULL, last_test_error = NULL WHERE id = 1",
);
}
createManagedInvite(record: Omit<ManagedInviteRecord, "createdAt" | "revokedAt" | "useCount">): ManagedInviteRecord {
const now = new Date().toISOString();
this.transaction(() => {
this.database.prepare(
`INSERT INTO managed_invites (
id, token_hash, target_host, target_port, server_password_encrypted,
channel, expires_at, max_uses, use_count, created_at, revoked_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NULL)`,
).run(
record.id,
record.tokenHash,
record.targetHost,
record.targetPort,
record.serverPasswordEncrypted,
record.channel,
record.expiresAt,
record.maxUses,
now,
);
});
return { ...record, useCount: 0, createdAt: now, revokedAt: null };
}
listManagedInvites(): ManagedInviteRecord[] {
const rows = this.database.prepare(
"SELECT * FROM managed_invites ORDER BY created_at DESC",
).all() as ManagedInviteRow[];
return rows.map(mapManagedInviteRow);
}
revokeManagedInvite(id: string): boolean {
const result = this.database.prepare(
"UPDATE managed_invites SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
).run(new Date().toISOString(), id) as { changes?: number | bigint };
return Number(result.changes ?? 0) === 1;
}
consumeManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
const nowIso = new Date(now).toISOString();
this.database.exec("BEGIN IMMEDIATE");
try {
const row = this.database.prepare(
`SELECT * FROM managed_invites
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > ?
AND (max_uses = 0 OR use_count < max_uses)`,
).get(tokenHash, nowIso) as ManagedInviteRow | undefined;
if (!row) {
this.database.exec("COMMIT");
return null;
}
const result = this.database.prepare(
`UPDATE managed_invites
SET use_count = use_count + 1
WHERE id = ? AND revoked_at IS NULL AND expires_at > ?
AND (max_uses = 0 OR use_count < max_uses)`,
).run(row.id, nowIso) as { changes?: number | bigint };
if (Number(result.changes ?? 0) !== 1) {
this.database.exec("COMMIT");
return null;
}
this.database.exec("COMMIT");
return { ...mapManagedInviteRow(row), useCount: row.use_count + 1 };
} catch (error) {
this.database.exec("ROLLBACK");
throw error;
}
}
exportBackup(): Buffer {
const exportPath = `${this.path}.export-${randomBytes(8).toString("hex")}.db`;
try {
const escapedPath = exportPath.replaceAll("'", "''");
this.database.exec(`VACUUM INTO '${escapedPath}'`);
return readFileSync(exportPath);
} finally {
try { unlinkSync(exportPath); } catch { /* best effort cleanup */ }
}
}
getMeta(key: string): string | null {
const row = this.database.prepare("SELECT value FROM metadata WHERE key = ?").get(key) as { value?: string } | undefined;
return row?.value ?? null;
}
setMeta(key: string, value: string): void {
this.database.prepare(
"INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
).run(key, value);
}
addAudit(event: string, details: Record<string, unknown> = {}): void {
this.insertAudit(event, details, new Date().toISOString());
}
recentAudit(limit = 8): Array<{ event: string; createdAt: string }> {
const normalizedLimit = Math.max(1, Math.min(50, Math.floor(limit)));
const rows = this.database.prepare(
"SELECT event, created_at FROM audit_events ORDER BY id DESC LIMIT ?",
).all(normalizedLimit) as Array<{ event: string; created_at: string }>;
return rows.map((row) => ({ event: row.event, createdAt: row.created_at }));
}
private migrate(existed: boolean): void {
let version = this.schemaVersion;
if (version > DATABASE_SCHEMA_VERSION) {
throw new Error(`Database schema ${version} is newer than this WebSpeak build`);
}
if (existed && version > 0) {
copyFileSync(this.path, `${this.path}.schema-${version}.bak`);
}
if (version === 0) {
this.transaction(() => {
this.database.exec(`
CREATE TABLE metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE admin_credentials (
id INTEGER PRIMARY KEY CHECK (id = 1),
credential_json TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
site_name TEXT NOT NULL,
welcome_text TEXT NOT NULL,
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')),
ts_host TEXT NOT NULL,
ts_port INTEGER NOT NULL CHECK (ts_port BETWEEN 1 AND 65535),
ts_password_encrypted TEXT,
detected_protocol TEXT CHECK (detected_protocol IS NULL OR detected_protocol IN ('ts3', 'ts6')),
last_test_at TEXT,
last_test_latency_ms INTEGER,
last_test_error TEXT,
updated_at TEXT NOT NULL
);
CREATE TABLE audit_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event TEXT NOT NULL,
details_json TEXT NOT NULL,
created_at TEXT NOT NULL
);
`);
const now = new Date().toISOString();
this.database.prepare(
`INSERT INTO settings (
id, site_name, welcome_text, access_mode, ts_host, ts_port,
ts_password_encrypted, detected_protocol, last_test_at,
last_test_latency_ms, last_test_error, updated_at
) VALUES (1, 'WebSpeak', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, ?)`,
).run(now);
this.database.exec("PRAGMA user_version = 1");
});
version = 1;
}
if (version === 1) {
this.transaction(() => {
this.database.exec(`
CREATE TABLE managed_invites (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
target_host TEXT NOT NULL,
target_port INTEGER NOT NULL CHECK (target_port BETWEEN 1 AND 65535),
server_password_encrypted TEXT,
channel TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL,
max_uses INTEGER NOT NULL CHECK (max_uses >= 0),
use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0),
created_at TEXT NOT NULL,
revoked_at TEXT
);
CREATE INDEX managed_invites_token_idx ON managed_invites(token_hash);
CREATE INDEX managed_invites_expiry_idx ON managed_invites(expires_at);
`);
this.database.exec("PRAGMA user_version = 2");
});
version = 2;
}
if (version === 2) {
this.transaction(() => {
this.database.exec(`
-- WebRTC media ports are stored with the administrator settings so the
-- same range is used by the gateway and shown in the admin console.
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535);
`);
this.database.exec("PRAGMA user_version = 3");
});
}
}
private writeSettings(settings: SettingsUpdate, now: string): void {
this.database.prepare(
`UPDATE settings SET
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
webrtc_udp_end = ?, updated_at = ?
WHERE id = 1`,
).run(
settings.siteName,
settings.welcomeText,
settings.accessMode,
settings.tsHost,
settings.tsPort,
settings.tsPasswordEncrypted,
settings.webRtcEnabled ? 1 : 0,
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
now,
);
}
private insertAudit(event: string, details: Record<string, unknown>, now: string): void {
this.database.prepare(
"INSERT INTO audit_events (event, details_json, created_at) VALUES (?, ?, ?)",
).run(event, JSON.stringify(details), now);
}
private transaction(action: () => void): void {
this.database.exec("BEGIN IMMEDIATE");
try {
action();
this.database.exec("COMMIT");
} catch (error) {
this.database.exec("ROLLBACK");
throw error;
}
}
}
function mapManagedInviteRow(row: ManagedInviteRow): ManagedInviteRecord {
return {
id: row.id,
tokenHash: row.token_hash,
targetHost: row.target_host,
targetPort: row.target_port,
serverPasswordEncrypted: row.server_password_encrypted,
channel: row.channel,
expiresAt: row.expires_at,
maxUses: row.max_uses,
useCount: row.use_count,
createdAt: row.created_at,
revokedAt: row.revoked_at,
};
}
+75
View File
@@ -0,0 +1,75 @@
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
const KEY_LENGTH = 64;
const SCRYPT_PARAMETERS = Object.freeze({ N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
export interface AdminCredential {
version: 1;
username: string;
mustChangePassword: boolean;
salt: string;
hash: string;
parameters: {
N: number;
r: number;
p: number;
};
}
export interface AdminPasswordOptions {
username?: string;
mustChangePassword?: boolean;
allowWeakPassword?: boolean;
}
export function validateAdminPassword(password: string): string | null {
if (password.length < 12) return "Admin password must contain at least 12 characters";
if (password.length > 1024) return "Admin password is too long";
return null;
}
export async function hashAdminPassword(password: string, options: AdminPasswordOptions = {}): Promise<AdminCredential> {
const validationError = options.allowWeakPassword ? null : validateAdminPassword(password);
if (validationError) throw new Error(validationError);
const salt = randomBytes(16);
const hash = await derive(password, salt, SCRYPT_PARAMETERS);
return {
version: 1,
username: options.username ?? "admin",
mustChangePassword: options.mustChangePassword ?? false,
salt: salt.toString("base64url"),
hash: hash.toString("base64url"),
parameters: {
N: SCRYPT_PARAMETERS.N,
r: SCRYPT_PARAMETERS.r,
p: SCRYPT_PARAMETERS.p,
},
};
}
export async function verifyAdminPassword(password: string, credential: AdminCredential): Promise<boolean> {
if (credential.version !== 1 || typeof password !== "string" || password.length > 1024) return false;
try {
const expected = Buffer.from(credential.hash, "base64url");
const actual = await derive(password, Buffer.from(credential.salt, "base64url"), {
...credential.parameters,
maxmem: 64 * 1024 * 1024,
});
return expected.length === actual.length && timingSafeEqual(expected, actual);
} catch {
return false;
}
}
async function derive(
password: string,
salt: Buffer,
parameters: { N: number; r: number; p: number; maxmem: number },
): Promise<Buffer> {
return new Promise((resolve, reject) => {
scrypt(password, salt, KEY_LENGTH, parameters, (error, result) => {
if (error) reject(error);
else resolve(Buffer.from(result));
});
});
}
+42
View File
@@ -0,0 +1,42 @@
import {
chmodSync,
closeSync,
mkdirSync,
openSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
import { randomBytes } from "node:crypto";
const MASTER_KEY_BYTES = 32;
/** Create or load the installation-local key used to protect secrets at rest. */
export function loadOrCreateMasterSecret(path: string): Buffer {
mkdirSync(dirname(path), { recursive: true });
try {
const descriptor = openSync(path, "wx", 0o600);
try {
writeFileSync(descriptor, randomBytes(MASTER_KEY_BYTES));
} finally {
closeSync(descriptor);
}
} catch (error: unknown) {
if (!isAlreadyExistsError(error)) throw error;
}
const key = readFileSync(path);
if (key.length !== MASTER_KEY_BYTES) {
throw new Error(`Invalid WebSpeak master secret: expected ${MASTER_KEY_BYTES} bytes`);
}
try {
chmodSync(path, 0o600);
} catch {
// Windows and some container filesystems do not expose POSIX permissions.
}
return key;
}
function isAlreadyExistsError(error: unknown): boolean {
return error instanceof Error && "code" in error && error.code === "EEXIST";
}
+68
View File
@@ -0,0 +1,68 @@
import { isIP } from "node:net";
import { lookup } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export class UnsafeTeamSpeakTargetError extends Error {
constructor(message = "This TeamSpeak target is not allowed in open mode") {
super(message);
this.name = "UnsafeTeamSpeakTargetError";
}
}
/** Resolve and reject addresses that could turn a public gateway into an internal network probe. */
export async function assertSafeOpenTarget(target: TeamSpeakTarget): Promise<void> {
await resolveSafeOpenTarget(target);
}
export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<TeamSpeakTarget> {
const literalVersion = isIP(target.host);
const addresses = literalVersion
? [{ address: target.host, family: literalVersion }]
: await lookup(target.host, { all: true, verbatim: true });
if (!addresses.length || addresses.some(({ address }) => isRestrictedAddress(address))) {
throw new UnsafeTeamSpeakTargetError();
}
// Use the address that was actually validated so a second DNS lookup cannot
// rebind the gateway connection to a private network.
return { host: addresses[0]!.address, port: target.port };
}
export function isRestrictedAddress(address: string): boolean {
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;
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;
}
function isRestrictedIpv4(address: string): boolean {
const parts = address.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
const [a, b] = parts as [number, number, number, number];
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 === 192 && b === 0 && parts[2] === 2)
|| (a === 198 && (b === 18 || b === 19))
|| (a === 198 && b === 51 && parts[2] === 100)
|| (a === 203 && b === 0 && parts[2] === 113)
|| a >= 224;
}
+36
View File
@@ -0,0 +1,36 @@
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHM = "aes-256-gcm";
const VERSION = "v1";
const AAD = Buffer.from("webspeak:teamspeak-password:v1", "utf8");
export function encryptSecret(value: string, masterKey: Buffer): string {
if (!value) return "";
assertMasterKey(masterKey);
const nonce = randomBytes(12);
const cipher = createCipheriv(ALGORITHM, masterKey, nonce);
cipher.setAAD(AAD);
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 {
if (!payload) return "";
assertMasterKey(masterKey);
const [version, nonceText, tagText, ciphertextText, ...extra] = payload.split(":");
if (version !== VERSION || !nonceText || !tagText || ciphertextText === undefined || extra.length) {
throw new Error("Unsupported encrypted secret format");
}
const decipher = createDecipheriv(ALGORITHM, masterKey, Buffer.from(nonceText, "base64url"));
decipher.setAAD(AAD);
decipher.setAuthTag(Buffer.from(tagText, "base64url"));
return Buffer.concat([
decipher.update(Buffer.from(ciphertextText, "base64url")),
decipher.final(),
]).toString("utf8");
}
function assertMasterKey(masterKey: Buffer): void {
if (masterKey.length !== 32) throw new Error("Invalid master key length");
}
+80
View File
@@ -0,0 +1,80 @@
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
import type { TSDirectorySnapshot } from "./ts-client.js";
type DirectoryDelta =
| { type: "clientEnter"; info: ClientInfo }
| { type: "clientLeave"; id: number }
| { type: "clientMoved"; id: number; channelID: bigint };
/**
* Merges staged welcome snapshots with events received while the snapshot is
* in flight. Some TS6 welcome data arrives in more than one partial snapshot,
* so a later snapshot must not hide clients that were present in an earlier
* one. Explicit leave events remain authoritative removals.
*/
export class DirectorySynchronizer {
private snapshot: TSDirectorySnapshot | null = null;
private clients = new Map<number, ClientInfo>();
private pending: DirectoryDelta[] = [];
get ready(): boolean {
return this.snapshot !== null;
}
applySnapshot(snapshot: TSDirectorySnapshot): void {
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
for (const client of snapshot.clients) {
const previous = this.clients.get(client.id);
this.clients.set(client.id, previous ? { ...previous, ...client } : client);
}
const pending = this.pending.splice(0);
for (const delta of pending) this.applyDelta(delta);
}
applyClientEnter(info: ClientInfo): void {
this.applyOrQueue({ type: "clientEnter", info });
}
applyClientLeave(id: number): void {
this.applyOrQueue({ type: "clientLeave", id });
}
applyClientMoved(id: number, channelID: bigint): void {
this.applyOrQueue({ type: "clientMoved", id, channelID });
}
getSnapshot(): TSDirectorySnapshot | null {
if (!this.snapshot) return null;
return {
channels: this.snapshot.channels.slice(),
clients: [...this.clients.values()],
};
}
clear(): void {
this.snapshot = null;
this.clients.clear();
this.pending = [];
}
private applyOrQueue(delta: DirectoryDelta): void {
if (!this.snapshot) {
if (this.pending.length < 4096) this.pending.push(delta);
return;
}
this.applyDelta(delta);
}
private applyDelta(delta: DirectoryDelta): void {
if (delta.type === "clientEnter") {
this.clients.set(delta.info.id, delta.info);
return;
}
if (delta.type === "clientLeave") {
this.clients.delete(delta.id);
return;
}
const current = this.clients.get(delta.id);
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
}
}
+37
View File
@@ -0,0 +1,37 @@
const WINDOW_MS = 60 * 1000;
const MAX_REQUESTS = 30;
interface PeerWindow {
startedAt: number;
requests: number;
}
/** Bounds opaque join-ticket creation so one peer cannot fill the in-memory store. */
export class JoinRateLimiter {
private readonly peers = new Map<string, PeerWindow>();
constructor(private readonly maxTrackedPeers = 2048) {}
allow(peer: string, now = Date.now()): boolean {
const current = this.peers.get(peer);
if (!current || now - current.startedAt >= WINDOW_MS) {
this.prune(now);
while (this.peers.size >= this.maxTrackedPeers) {
const oldest = this.peers.keys().next().value;
if (!oldest) break;
this.peers.delete(oldest);
}
this.peers.set(peer, { startedAt: now, requests: 1 });
return true;
}
if (current.requests >= MAX_REQUESTS) return false;
current.requests += 1;
return true;
}
private prune(now: number): void {
for (const [peer, window] of this.peers) {
if (now - window.startedAt >= WINDOW_MS) this.peers.delete(peer);
}
}
}
+47
View File
@@ -0,0 +1,47 @@
import { randomBytes } from "node:crypto";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface JoinTicketPayload {
target: TeamSpeakTarget;
serverPassword: string;
nickname: string;
channel?: string;
identity?: string;
rememberIdentity?: boolean;
}
interface StoredTicket {
payload: JoinTicketPayload;
expiresAt: number;
}
export class JoinTicketStore {
private readonly tickets = new Map<string, StoredTicket>();
constructor(private readonly ttlMs = 30_000, private readonly maxTickets = 256) {}
create(payload: JoinTicketPayload, now = Date.now()): string {
this.prune(now);
while (this.tickets.size >= this.maxTickets) {
const oldest = this.tickets.keys().next().value;
if (!oldest) break;
this.tickets.delete(oldest);
}
const token = randomBytes(24).toString("base64url");
this.tickets.set(token, { payload, expiresAt: now + this.ttlMs });
return token;
}
consume(token: string, now = Date.now()): JoinTicketPayload | null {
const stored = this.tickets.get(token);
this.tickets.delete(token);
if (!stored || stored.expiresAt <= now) return null;
return stored.payload;
}
private prune(now: number): void {
for (const [token, stored] of this.tickets) {
if (stored.expiresAt <= now) this.tickets.delete(token);
}
}
}
+19
View File
@@ -0,0 +1,19 @@
import type { WebSpeakError } from "../errors.js";
export const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 30_000] as const;
export const RECONNECT_WINDOW_MS = 5 * 60_000;
export function reconnectDelayMs(attempt: number, random = Math.random): number {
const safeAttempt = Math.max(1, Math.floor(attempt));
const base = RECONNECT_DELAYS_MS[Math.min(safeAttempt, RECONNECT_DELAYS_MS.length) - 1] ?? RECONNECT_DELAYS_MS.at(-1)!;
const jitter = Math.round(base * ((random() * 0.2) - 0.1));
return Math.max(250, base + jitter);
}
export function reconnectWindowOpen(startedAt: number, now = Date.now()): boolean {
return now - startedAt < RECONNECT_WINDOW_MS;
}
export function isRecoverable(error: WebSpeakError | null): boolean {
return error?.retryable ?? true;
}
+119 -20
View File
@@ -3,18 +3,24 @@ 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 { fileURLToPath } from "node:url";
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
import { createAdminRouter } from "../admin/admin-router.js";
import type { AdminService } from "../admin/admin-service.js";
import { AdminSessionStore } from "../admin/admin-session.js";
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { JoinRateLimiter } from "./join-rate-limit.js";
export interface WebServerOptions {
port: number;
trustProxy: boolean;
version?: string;
logFile?: string;
staticDir?: string;
certDir?: string; // path to cert.pem + key.pem for HTTPS
voiceBridgeOptions: VoiceBridgeOptions;
adminService: AdminService;
logger: Logger;
}
@@ -38,26 +44,106 @@ export function createWebServer(options: WebServerOptions): WebServer {
server = createHttpServer(app);
}
if (options.trustProxy) {
app.set("trust proxy", true);
}
app.use(express.json({ limit: "100kb" }));
app.get("/api/health", (_req, res) => {
res.json({ status: "ok", version: "0.1.0" });
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
const adminSessions = new AdminSessionStore();
const joinRateLimiter = new JoinRateLimiter();
const startedAt = Date.now();
const healthHandler: express.RequestHandler = (_request, response) => {
response.json({ status: "ok", version: options.version ?? "0.1.0" });
};
app.get("/health", healthHandler);
app.get("/api/health", healthHandler);
app.get("/api/public-config", (_request, response) => {
response.setHeader("Cache-Control", "no-store");
response.json(options.adminService.getPublicConfig());
});
// The browser needs the gateway's default target so a user can edit it in
// the join form. No credentials are exposed here.
app.get("/api/public-config", (_req, res) => {
res.json({
tsHost: options.voiceBridgeOptions.tsHost,
tsPort: options.voiceBridgeOptions.tsPort,
tsServerProtocol: options.voiceBridgeOptions.tsServerProtocol ?? null,
app.post("/api/join-ticket", async (request, response) => {
response.setHeader("Cache-Control", "no-store");
if (!request.is("application/json") || !isSameOrigin(request)) {
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
return;
}
if (!options.adminService.isInitialized()) {
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
return;
}
const body = isRecord(request.body) ? request.body : {};
const nickname = typeof body.nickname === "string" ? body.nickname.trim().slice(0, 30) : "";
const requestedChannel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
const inviteToken = typeof body.invite === "string" ? body.invite.trim().slice(0, 128) : "";
const requestedIdentity = typeof body.identity === "string" && body.identity.length <= 8192 ? body.identity : "";
let identity: string | undefined;
if (requestedIdentity) {
try {
identityFromString(requestedIdentity);
identity = requestedIdentity;
} catch {
// A stale/corrupt local identity must not block a normal ephemeral join.
}
}
if (!nickname) {
response.status(400).json({ ok: false, code: "INVALID_NICKNAME" });
return;
}
const policy = options.adminService.getConnectionPolicy();
const managedInvite = inviteToken ? options.adminService.consumeManagedInvite(inviteToken) : null;
if (inviteToken && !managedInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
return;
}
let target = managedInvite?.target ?? policy.defaultTarget;
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
const channel = requestedChannel || managedInvite?.channel || "";
if (!managedInvite) {
try {
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
target = parseTeamSpeakTarget(body.target);
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
if (!isDefault) {
target = await resolveSafeOpenTarget(target);
serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
}
}
} catch {
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
return;
}
}
const ticket = options.voiceBridgeOptions.joinTickets.create({
target,
serverPassword,
nickname,
...(channel ? { channel } : {}),
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
});
response.status(201).json({ ok: true, ticket });
});
app.use("/api/admin", createAdminRouter({
service: options.adminService,
sessions: adminSessions,
logger,
getActiveSessions: () => voiceBridge.getActiveCount(),
getPeakSessions: () => voiceBridge.getPeakCount(),
getCreatedSessions: () => voiceBridge.getCreatedCount(),
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
terminateSession: (id) => voiceBridge.terminateSession(id),
version: options.version,
logFile: options.logFile,
startedAt,
}));
// Serve static frontend
if (options.staticDir) {
app.use(express.static(options.staticDir));
@@ -66,8 +152,6 @@ export function createWebServer(options: WebServerOptions): WebServer {
});
}
// Voice bridge WebSocket at /ws/voice
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
voiceBridge.attach(server);
return {
@@ -80,10 +164,25 @@ export function createWebServer(options: WebServerOptions): WebServer {
});
},
async stop(): Promise<void> {
voiceBridge.shutdown();
await voiceBridge.shutdown();
adminSessions.clear();
return new Promise((resolve) => {
server.close(() => resolve());
});
},
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isSameOrigin(request: express.Request): boolean {
const origin = request.header("origin");
const host = request.header("host");
try {
return Boolean(origin && host && new URL(origin).host === host);
} catch {
return false;
}
}
+145
View File
@@ -0,0 +1,145 @@
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js";
export type ConnectionState =
| "idle"
| "connecting"
| "authenticating"
| "syncing"
| "connected"
| "interrupted"
| "reconnecting"
| "disconnecting"
| "failed";
export type SessionTeardownReason =
| "client-disconnect"
| "websocket-close"
| "websocket-error"
| "protocol-error"
| "teamSpeak-disconnect"
| "teamSpeak-connect-failed"
| "heartbeat-timeout"
| "admin-terminated"
| "gateway-shutdown";
const ALLOWED_TRANSITIONS: Record<ConnectionState, readonly ConnectionState[]> = {
idle: ["connecting", "disconnecting"],
connecting: ["authenticating", "reconnecting", "failed", "disconnecting"],
authenticating: ["syncing", "reconnecting", "failed", "disconnecting"],
syncing: ["connected", "reconnecting", "failed", "disconnecting"],
connected: ["interrupted", "failed", "disconnecting"],
interrupted: ["reconnecting", "failed", "disconnecting"],
reconnecting: ["connecting", "failed", "disconnecting"],
disconnecting: ["idle"],
failed: ["disconnecting", "idle"],
};
export class ConnectionStateMachine {
private current: ConnectionState = "idle";
get state(): ConnectionState {
return this.current;
}
transition(next: ConnectionState): void {
if (next === this.current) return;
if (!ALLOWED_TRANSITIONS[this.current].includes(next)) {
throw new Error(`Illegal connection state transition: ${this.current} -> ${next}`);
}
this.current = next;
}
}
export type SessionCleanup = (reason: SessionTeardownReason) => Promise<void>;
export class ManagedSession {
readonly createdAt = Date.now();
private readonly stateMachine = new ConnectionStateMachine();
private teardownPromise: Promise<void> | null = null;
constructor(
readonly id: string,
private readonly cleanup: SessionCleanup,
) {}
get state(): ConnectionState {
return this.stateMachine.state;
}
transition(next: ConnectionState): void {
this.stateMachine.transition(next);
}
async teardown(reason: SessionTeardownReason): Promise<void> {
if (this.teardownPromise) return this.teardownPromise;
this.teardownPromise = (async () => {
if (this.state !== "idle" && this.state !== "disconnecting") {
this.stateMachine.transition("disconnecting");
} else if (this.state === "idle") {
this.stateMachine.transition("disconnecting");
}
try {
await this.cleanup(reason);
} catch {
// Teardown is best effort and must not be interrupted by an already
// closed socket, TeamSpeak client, or codec resource.
} finally {
if (this.state === "disconnecting") this.stateMachine.transition("idle");
}
})();
return this.teardownPromise;
}
}
export class SessionManager {
private readonly sessions = new Map<string, ManagedSession>();
private accepting = true;
private peak = 0;
private created = 0;
admit(id: string, cleanup: SessionCleanup): ManagedSession | null {
if (!this.accepting || !canAcceptSession(this.sessions.size)) return null;
if (this.sessions.has(id)) throw new Error(`Session already exists: ${id}`);
const session = new ManagedSession(id, cleanup);
this.sessions.set(id, session);
this.created++;
this.peak = Math.max(this.peak, this.sessions.size);
return session;
}
get(id: string): ManagedSession | undefined {
return this.sessions.get(id);
}
get activeCount(): number {
return this.sessions.size;
}
get peakCount(): number {
return this.peak;
}
get createdCount(): number {
return this.created;
}
get isAccepting(): boolean {
return this.accepting;
}
async teardown(id: string, reason: SessionTeardownReason): Promise<void> {
const session = this.sessions.get(id);
if (!session) return;
await session.teardown(reason);
this.sessions.delete(id);
}
async shutdown(reason: SessionTeardownReason = "gateway-shutdown"): Promise<void> {
this.accepting = false;
await Promise.all([...this.sessions.keys()].map((id) => this.teardown(id, reason)));
}
get maxSessions(): number {
return MAX_ACTIVE_SESSIONS;
}
}
+154
View File
@@ -0,0 +1,154 @@
import {
Client as TeamSpeakClient,
generateIdentity,
type ClientOptions,
type Identity,
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
export type TeamSpeakProtocol = "ts3" | "ts6";
interface CacheEntry {
protocol: TeamSpeakProtocol;
lastSuccessfulAt: number;
}
/** Process-local optimization; protocol is never persisted as user config. */
export class EndpointProtocolCache {
private readonly entries = new Map<string, CacheEntry>();
constructor(
private readonly ttlMs = 30 * 60 * 1000,
private readonly maxEntries = 128,
) {}
get(target: TeamSpeakTarget, now = Date.now()): TeamSpeakProtocol | undefined {
const key = teamSpeakTargetKey(target);
const entry = this.entries.get(key);
if (!entry) return undefined;
if (now - entry.lastSuccessfulAt > this.ttlMs) {
this.entries.delete(key);
return undefined;
}
return entry.protocol;
}
set(target: TeamSpeakTarget, protocol: TeamSpeakProtocol, now = Date.now()): void {
const key = teamSpeakTargetKey(target);
this.entries.delete(key);
this.entries.set(key, { protocol, lastSuccessfulAt: now });
while (this.entries.size > this.maxEntries) {
const oldest = this.entries.keys().next().value;
if (oldest === undefined) break;
this.entries.delete(oldest);
}
}
clear(): void {
this.entries.clear();
}
get size(): number {
return this.entries.size;
}
}
export const endpointProtocolCache = new EndpointProtocolCache();
export interface TeamSpeakAdapterOptions {
target: TeamSpeakTarget;
nickname: string;
identity?: Identity;
serverPassword?: string;
defaultChannel?: string;
channelPassword?: string;
}
/**
* The SDK performs the wire-level TS3/TS6 negotiation itself. This adapter is
* the only application boundary that knows about that SDK and records the
* successfully observed server generation for later connections.
*/
export class TeamSpeakAdapter {
readonly client: TeamSpeakClient;
readonly identity: Identity;
private detectedProtocol: TeamSpeakProtocol | null = null;
constructor(
options: TeamSpeakAdapterOptions,
private readonly logger: Logger,
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
) {
this.identity = options.identity ?? generateIdentity(8);
const clientOptions: ClientOptions = {
serverPassword: options.serverPassword,
defaultChannel: options.defaultChannel,
defaultChannelPassword: options.channelPassword,
logger: {
debug: (msg: string) => this.logger.debug(msg),
info: (msg: string) => this.logger.info(msg),
warn: (msg: string) => this.logger.warn(msg),
error: (msg: string) => this.logger.error(msg),
},
};
this.client = new TeamSpeakClient(
this.identity,
formatTeamSpeakTarget(options.target),
options.nickname,
clientOptions,
);
this.target = options.target;
}
private readonly target: TeamSpeakTarget;
async connect(): Promise<void> {
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();
} catch (error: unknown) {
throw normalizeTeamSpeakError(error);
}
const observedProtocol = await this.detectProtocol();
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
}
get protocol(): TeamSpeakProtocol | null {
return this.detectedProtocol;
}
async disconnect(): Promise<void> {
try {
await this.client.disconnect();
} catch {
// Teardown must remain safe when the transport has already gone away.
}
}
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";
return null;
}
+105
View File
@@ -0,0 +1,105 @@
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
export type ProbeErrorCode =
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "TIMEOUT"
| "INVALID_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "INTERNAL_ERROR";
export interface TeamSpeakProbeResult {
ok: true;
protocol: TeamSpeakProtocol | null;
latencyMs: number;
serverName: string | null;
requiresPassword: boolean;
}
export class TeamSpeakProbeError extends Error {
constructor(readonly code: ProbeErrorCode, message: string, readonly cause?: unknown) {
super(message);
this.name = "TeamSpeakProbeError";
}
}
interface ProbeAdapter {
connect(): Promise<void>;
disconnect(): Promise<void>;
readonly protocol: TeamSpeakProtocol | null;
readonly client: {
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
};
}
export type ProbeAdapterFactory = (input: {
target: TeamSpeakTarget;
password: string;
logger: Logger;
}) => ProbeAdapter;
export async function probeTeamSpeak(
target: TeamSpeakTarget,
password: string,
logger: Logger,
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
): Promise<TeamSpeakProbeResult> {
const startedAt = Date.now();
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
try {
await adapter.connect();
let serverName: string | null = null;
try {
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
const first = rows[0] ?? {};
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
} catch {
// A connected server can restrict serverinfo; reachability is still proven.
}
return {
ok: true,
protocol: adapter.protocol,
latencyMs: Math.max(0, Date.now() - startedAt),
serverName,
requiresPassword: Boolean(password),
};
} catch (error: unknown) {
throw toProbeError(error);
} finally {
try {
await adapter.disconnect();
} catch (error: unknown) {
logger.warn({ err: extractErrorText(error) }, "TeamSpeak probe cleanup failed");
}
}
}
export function toProbeError(error: unknown): TeamSpeakProbeError {
if (error instanceof TeamSpeakProbeError) return error;
const normalized = normalizeTeamSpeakError(error);
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
}
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
invalid_target: "INTERNAL_ERROR",
unreachable: "UNREACHABLE",
timeout: "TIMEOUT",
authentication_failed: "INVALID_PASSWORD",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "SERVER_REJECTED",
};
return new TeamSpeakProbeError(mapping[normalized.code] ?? "INTERNAL_ERROR", normalized.message, error);
}
function extractErrorText(error: unknown): string {
if (!error || typeof error !== "object") return String(error ?? "");
const candidate = error as { code?: unknown; message?: unknown };
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
}
+185 -93
View File
@@ -1,23 +1,29 @@
import { EventEmitter } from "node:events";
import {
Client as TS3FullClient,
generateIdentity,
clientMove as tsClientMove,
listChannels as tsListChannels,
listClients as tsListClients,
poke as tsPoke,
sendTextMessage as tsSendTextMessage,
generateIdentity,
type Identity,
type VoiceData,
type ChannelInfo,
type ClientInfo,
} from "@honeybbq/teamspeak-client";
type DirectoryClientInfo,
type DirectorySnapshot,
type TextMessage,
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface TSClientOptions {
host: string;
port: number;
target: TeamSpeakTarget;
nickname: string;
serverPassword?: string;
serverProtocol?: "ts3" | "ts6";
defaultChannel?: string;
channelPassword?: string;
identity?: Identity;
}
export interface TSVoiceData {
@@ -26,45 +32,129 @@ export interface TSVoiceData {
data: Buffer;
}
export interface TSDirectorySnapshot {
channels: ChannelInfo[];
clients: ClientInfo[];
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryClient = DirectoryClientInfo;
export type TSChatScope = "channel" | "server" | "private";
export interface TSChatMessage {
invokerName: string;
invokerId: number;
invokerUid: string;
message: string;
targetMode: number;
targetId: bigint;
}
/**
* Keep the TeamSpeak target id when adapting SDK events for the gateway.
* Private-message events include a bigint targetID; dropping it makes the
* bridge dereference undefined while echoing the message to the browser.
*/
export function toTSChatMessage(msg: TextMessage): TSChatMessage {
return {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
targetId: msg.targetID,
};
}
export class TSClient extends EventEmitter {
private client: TS3FullClient | null = null;
private identity: Identity;
private adapter: TeamSpeakAdapter | null = null;
private logger: Logger;
private readonly identity: Identity;
private clientId = 0;
private connected = false;
private preferredChannelId = 0n;
constructor(
private options: TSClientOptions,
logger: Logger,
) {
constructor(private options: TSClientOptions, logger: Logger) {
super();
this.logger = logger.child({ nickname: options.nickname });
this.identity = generateIdentity(8);
this.identity = options.identity ?? generateIdentity(8);
}
async connect(): Promise<void> {
const addr = `${this.options.host}:${this.options.port}`;
if (!this.adapter || !this.client) {
this.adapter = new TeamSpeakAdapter({
target: this.options.target,
nickname: this.options.nickname,
identity: this.identity,
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
channelPassword: this.options.channelPassword,
}, this.logger);
this.client = this.adapter.client;
this.attachClientListeners(this.client);
}
const adapter = this.adapter;
const client = this.client;
this.logger.info({ addr }, "Connecting to TeamSpeak");
await adapter.connect();
this.client = new TS3FullClient(this.identity, addr, this.options.nickname, {
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
defaultChannelPassword: this.options.channelPassword,
logger: {
debug: (msg: string) => this.logger.debug(msg),
info: (msg: string) => this.logger.info(msg),
warn: (msg: string) => this.logger.warn(msg),
error: (msg: string) => this.logger.error(msg),
},
});
this.clientId = client.clientID();
try {
// A native TeamSpeak client subscribes to the complete channel tree
// after the welcome sequence. Without this command the server only
// exposes members in the current channel, so users disappear as soon as
// they move elsewhere even though both clients are on the same server.
await client.execCommand("channelsubscribeall", 5000);
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
}, "Could not subscribe to all TeamSpeak channels");
}
// Directory snapshots are dispatched through two setImmediate layers in
// the SDK. Let both flush before reconciling with a direct client-protocol
// snapshot so the gateway's first connected state contains every member.
await new Promise<void>((resolve) => setImmediate(resolve));
await new Promise<void>((resolve) => setImmediate(resolve));
this.client.on("voiceData", (data: VoiceData) => {
// TS6 can finish the welcome event stream before it has exposed every
// existing client to a newly connected session. Pull one authoritative
// snapshot through this same client protocol session so users who joined
// earlier are visible immediately as well. Realtime events continue to
// keep the snapshot current after this reconciliation.
try {
const [channels, clients] = await Promise.all([
tsListChannels(client),
tsListClients(client),
]);
this.emit("directorySnapshot", { channels, clients });
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
}, "Could not reconcile the TeamSpeak directory snapshot");
}
const connectedChannelId = client.channelID();
if (this.preferredChannelId === 0n) {
this.preferredChannelId = connectedChannelId;
} else if (connectedChannelId !== this.preferredChannelId) {
try {
await tsClientMove(client, this.clientId, this.preferredChannelId);
} catch (error: unknown) {
// The old channel may have been deleted or become inaccessible. The
// SDK has already left us in the server/default channel, which is the
// safe fallback required by the reconnect contract.
this.logger.info({
channelId: this.preferredChannelId.toString(),
err: error instanceof Error ? error.message : String(error),
}, "Previous TeamSpeak channel could not be restored");
this.preferredChannelId = client.channelID();
}
}
this.connected = true;
this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak");
this.emit("connected", this.clientId);
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
clientId: data.clientId,
codec: data.codec,
@@ -72,68 +162,43 @@ export class TSClient extends EventEmitter {
} as TSVoiceData);
});
// The SDK patch exposes the directory that TeamSpeak sends during the
// normal client welcome sequence. This is the same data a native client
// receives and does not require channellist/clientlist permissions.
(this.client as unknown as {
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
}).on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", snapshot);
});
this.client.on("textMessage", (msg) => {
this.emit("textMessage", {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
// The SDK exposes the directory that TeamSpeak sends during the normal
// client welcome sequence. The connect path also reconciles this event
// stream with a complete client-protocol snapshot.
client.on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
clients: snapshot.clients.slice(),
});
});
this.client.on("disconnected", (err) => {
client.on("textMessage", (msg) => {
this.emit("textMessage", toTSChatMessage(msg));
});
client.on("poked", (event) => {
this.emit("poked", event);
});
client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Disconnected from TS");
this.connected = false;
this.clientId = 0;
this.emit("disconnected");
this.emit("disconnected", err);
});
this.client.on("clientEnter", (info) => {
client.on("clientEnter", (info) => {
this.emit("clientEnter", info);
});
this.client.on("clientLeave", (info) => {
client.on("clientLeave", (info) => {
this.emit("clientLeave", info);
});
this.client.on("clientMoved", (info) => {
client.on("clientMoved", (info) => {
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
this.emit("clientMoved", info);
});
await this.client.connect();
await this.client.waitConnected();
this.clientId = this.client.clientID();
try {
// A native TeamSpeak client subscribes to the complete channel tree
// after the welcome sequence. Without this command the server only
// exposes members in the current channel, so users disappear as soon as
// they move elsewhere even though both clients are on the same server.
await this.client.execCommand("channelsubscribeall", 5000);
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
}, "Could not subscribe to all TeamSpeak channels");
}
// Directory snapshots are dispatched through two setImmediate layers in
// the SDK. Let both flush so the gateway's first connected state already
// contains members from every subscribed channel.
await new Promise<void>((resolve) => setImmediate(resolve));
await new Promise<void>((resolve) => setImmediate(resolve));
this.connected = true;
this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak");
this.emit("connected", this.clientId);
}
sendVoice(data: Buffer, codec: number = 4): void {
@@ -141,20 +206,34 @@ export class TSClient extends EventEmitter {
this.client.sendVoice(data, codec);
}
sendTextMessage(message: string): void {
// We use execCommand for simplicity — the client API has higher-level wrappers
sendWhisper(data: Buffer, clientIds: number[], codec: number = 4): void {
if (!this.client || !this.connected) return;
const escaped = message
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/");
this.client.execCommand(`sendtextmessage targetmode=2 target=0 msg=${escaped}`)
.catch((err: Error) => this.logger.error({ err }, "sendTextMessage failed"));
const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId());
if (!targets.length) throw new Error("Whisper requires at least one valid target");
this.client.sendWhisper(data, targets, codec);
}
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const targetMode = scope === "private" ? 1 : scope === "server" ? 3 : 2;
await tsSendTextMessage(this.client, targetMode, targetId, message);
}
async poke(clientId: number, message: string): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
await tsPoke(this.client, clientId, message);
}
async setAway(away: boolean, message = ""): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const escaped = escapeTeamSpeakValue(message);
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
if (!this.client) return;
if (!this.client || !this.connected) return;
await tsClientMove(this.client, this.clientId, channelId, password);
this.preferredChannelId = channelId;
}
getClientId(): number {
@@ -164,6 +243,14 @@ export class TSClient extends EventEmitter {
return this.client?.clientID() ?? this.clientId;
}
getProtocol(): TeamSpeakProtocol | null {
return this.adapter?.protocol ?? null;
}
getIdentityString(): string {
return this.identity.toString();
}
getChannelId(): bigint {
if (!this.client) return 0n;
const sdkClient = this.client as unknown as { channelID?: () => bigint };
@@ -176,14 +263,19 @@ export class TSClient extends EventEmitter {
async disconnect(): Promise<void> {
this.connected = false;
if (this.client) {
try {
await this.client.disconnect();
} catch {
// ignore
}
this.client = null;
}
if (this.adapter) await this.adapter.disconnect();
this.adapter = null;
this.client = null;
this.clientId = 0;
}
}
function escapeTeamSpeakValue(value: string): string {
return value
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r");
}
+804 -168
View File
File diff suppressed because it is too large. Load diff
+71
View File
@@ -0,0 +1,71 @@
export interface ClientCommand {
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted";
requestId?: string;
payload: Record<string, unknown>;
}
export type ClientCommandResult = ClientCommand | { error: { code: string; message: string } };
export function parseClientCommand(raw: string): ClientCommandResult {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
return { error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" } };
}
if (!isRecord(value) || typeof value.type !== "string") {
return { error: { code: "INVALID_MESSAGE", message: "消息类型不能为空" } };
}
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
if (!isRecord(value.payload)) {
return { error: { code: "INVALID_PAYLOAD", message: "消息参数无效" } };
}
if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
}
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendServerMessage" || value.type === "sendPrivateMessage") && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendPrivateMessage" || value.type === "poke") && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
}
if (value.type === "poke" && (typeof value.payload.message !== "string" || value.payload.message.length > 200)) {
return { error: { code: "INVALID_POKE_MESSAGE", message: "戳一戳消息无效" } };
}
if (value.type === "setAway" && (typeof value.payload.away !== "boolean" || (value.payload.message !== undefined && (typeof value.payload.message !== "string" || value.payload.message.length > 200)))) {
return { error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" } };
}
if (value.type === "setWhisperTargets") {
const targetIds = value.payload.targetIds;
if (!Array.isArray(targetIds) || targetIds.length > 8 || targetIds.some((clientId) => typeof clientId !== "number" || !Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) || new Set(targetIds).size !== targetIds.length) {
return { error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" } };
}
}
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
}
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
}
return {
type: value.type as ClientCommand["type"],
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
payload: value.payload,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+288
View File
@@ -0,0 +1,288 @@
import { randomInt } from "node:crypto";
import { createRequire } from "node:module";
import {
MediaStreamTrack,
RtpHeader,
RtpPacket,
RTCPeerConnection,
} from "werift";
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
OpusEncoder: new (sampleRate: number, channels: number) => {
decode(data: Buffer): Buffer;
encode(data: Buffer): Buffer;
};
};
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
// TeamSpeak and browsers can emit valid Opus comfort-noise/silence packets
// while a client is muted. Do not turn those packets into a false "speaking"
// indicator or forward them to TeamSpeak as if they were voice.
const MIN_SPEAKER_RMS = 160;
// WebRTC is served by the WebSpeak process itself. The default range is also
// published by the bundled Docker Compose file; advanced administrators can
// change it in the admin console before enabling WebRTC.
export interface WebRtcAudioOptions {
enabled: boolean;
udpPortRange?: [number, number];
}
export interface WebRtcSessionDescription {
type: "offer" | "answer";
sdp: string;
muted?: boolean;
}
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
microphoneMuted?: boolean;
onVoiceFrame: (data: Buffer) => void;
onVoiceActivity: (clientIds: number[]) => void;
}
/**
* One low-latency WebRTC audio session for one browser connection.
*
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
* audio track in this first transport, so this class mixes only the newest
* 20 ms frame from each active speaker and packetizes the result as RTP. The
* map is deliberately bounded to one frame per speaker; an old frame is
* replaced instead of becoming a playback queue.
*/
export class WebRtcAudioSession {
readonly peer: RTCPeerConnection;
private readonly logger: LoggerType;
private readonly onVoiceFrame: (data: Buffer) => void;
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
private readonly pendingFrames = new Map<number, Buffer>();
private readonly activeSpeakerIds = new Set<number>();
private readonly opusPayloadTypes = new Set<number>();
private readonly audioTimer: ReturnType<typeof setInterval>;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: { encode(data: Buffer): Buffer } | null;
private microphoneMuted: boolean;
private sequenceNumber = randomInt(0, 65_536);
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
private closed = false;
constructor(options: WebRtcAudioSessionOptions) {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
this.microphoneMuted = options.microphoneMuted === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
this.peer = new RTCPeerConnection({
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseTcp: false,
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
});
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
audio.onTrack.subscribe((track) => {
track.onReceiveRtp.subscribe((rtp) => {
if (this.closed || this.microphoneMuted || !this.opusPayloadTypes.has(rtp.header.payloadType)) return;
const payload = Buffer.from(rtp.payload);
// A disabled browser MediaStreamTrack normally still produces RTP
// comfort-noise packets. TeamSpeak treats any received voice packet
// as activity, so enforce mute/VAD at this gateway boundary instead
// of relying on the browser's local speaking indicator.
if (!this.hasVoiceEnergy(payload)) return;
this.onVoiceFrame(payload);
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
});
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
try {
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
// Use a separate stateful decoder for browser ingress. RTP payloads do
// not identify whether a packet contains microphone energy or DTX/CN
// audio, so the gateway must decode it before forwarding to TS.
this.ingressDecoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
} catch (error: unknown) {
this.encoder = null;
this.ingressDecoder = null;
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
}
if (!this.encoder || !this.ingressDecoder) {
this.outgoingTrack.stop();
throw new Error("WebRTC Opus codec is unavailable");
}
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
this.audioTimer.unref?.();
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
this.activityTimer.unref?.();
this.peer.onconnectionstatechange = () => {
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
};
}
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
if (this.closed) throw new Error("WebRTC session is closed");
this.setOpusPayloadTypes(offer.sdp);
await this.peer.setRemoteDescription(offer);
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
const description = this.peer.localDescription;
if (!description) throw new Error("WebRTC answer was not created");
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
return { type: description.type, sdp: description.sdp };
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || data.codec !== 4) return;
let decoder = this.decoderByClient.get(data.clientId);
if (!decoder) {
try {
// @discordjs/opus exposes decoding on OpusEncoder instances too;
// there is no separate OpusDecoder constructor in that package.
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
this.decoderByClient.set(data.clientId, decoder);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
return;
}
}
try {
const pcm = decoder.decode(data.data);
// Only advertise speaking after a valid TeamSpeak Opus frame has been
// decoded. Otherwise the UI can show activity while the mixer has no
// audio to send, which is especially confusing on the WebRTC path.
if (pcm.length < AUDIO_FRAME_BYTES) return;
let sum = 0;
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
const sample = pcm.readInt16LE(index);
sum += sample * sample;
}
if (Math.sqrt(sum / AUDIO_FRAME_SAMPLES) < MIN_SPEAKER_RMS) return;
this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
this.activeSpeakerIds.add(data.clientId);
} catch {
// A malformed or codec-transition packet is discarded without touching
// the peer connection. The next valid Opus frame can recover the stream.
}
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
clearInterval(this.audioTimer);
clearInterval(this.activityTimer);
this.pendingFrames.clear();
this.activeSpeakerIds.clear();
this.ingressDecoder = null;
this.decoderByClient.clear();
this.encoder = null;
this.outgoingTrack.stop();
await this.peer.close();
}
private flushAudio(): void {
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
let sourceCount = 0;
for (const pcm of this.pendingFrames.values()) {
sourceCount++;
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
}
this.pendingFrames.clear();
if (!sourceCount) return;
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
const scale = 1 / Math.sqrt(sourceCount);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale)));
pcm.writeInt16LE(sample, index * 2);
}
try {
const encoded = this.encoder.encode(pcm);
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
} catch {
// A peer closing concurrently may reject a packet; teardown owns the
// session lifecycle and no per-frame error needs to reach the logs.
}
}
private flushSpeakerActivity(): void {
if (this.closed || !this.activeSpeakerIds.size) return;
const ids = [...this.activeSpeakerIds];
this.activeSpeakerIds.clear();
this.onVoiceActivity(ids);
}
setMicrophoneMuted(muted: boolean): void {
this.microphoneMuted = muted;
}
private hasVoiceEnergy(data: Buffer): boolean {
const decoder = this.ingressDecoder;
if (!decoder) return false;
try {
const pcm = decoder.decode(data);
if (pcm.length < AUDIO_FRAME_BYTES) return false;
let sum = 0;
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
const sample = pcm.readInt16LE(index);
sum += sample * sample;
}
return Math.sqrt(sum / AUDIO_FRAME_SAMPLES) >= MIN_SPEAKER_RMS;
} catch {
// Malformed/transition packets are discarded without interrupting the
// rest of the peer. The next valid Opus packet can recover the decoder.
return false;
}
}
private setOpusPayloadTypes(sdp: string): void {
this.opusPayloadTypes.clear();
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
const payloadType = Number(match[1]);
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
this.opusPayloadTypes.add(payloadType);
this.outgoingPayloadType = payloadType;
}
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
}
}
+7
View File
@@ -0,0 +1,7 @@
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
// Kept as a public alias for callers that used the original fixed-range name.
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
export const WEBRTC_UDP_PORT_MIN = 1024;
export const WEBRTC_UDP_PORT_MAX = 65535;
+244
View File
@@ -0,0 +1,244 @@
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { createServer } from "node:http";
import test from "node:test";
import express from "express";
import { createAdminRouter } from "../src/admin/admin-router.js";
import { AdminService } from "../src/admin/admin-service.js";
import { AdminSessionStore } from "../src/admin/admin-session.js";
import { WebSpeakDatabase } from "../src/persistence/database.js";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { silentLogger } from "./helpers/logger.js";
test("admin API requires the default password to be changed before administration", async (context) => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-api-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
path.join(directory, "missing-config.json"),
async (_target, password) => ({ ok: true, protocol: "ts6", latencyMs: 7, serverName: "Mock Server", requiresPassword: Boolean(password) }),
);
await service.initialize();
const app = express();
app.use(express.json());
app.use("/api/admin", createAdminRouter({
service,
sessions: new AdminSessionStore(),
logger: silentLogger,
getActiveSessions: () => 2,
getPeakSessions: () => 4,
startedAt: Date.now() - 5000,
}));
const server = createServer(app);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
context.after(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
database.close();
});
const address = server.address();
assert.ok(address && typeof address === "object");
const origin = `http://127.0.0.1:${address.port}`;
const status = await request(origin, "/api/admin/status");
assert.equal(status.response.status, 200);
assert.equal(status.response.headers.get("cache-control"), "no-store");
assert.equal(status.body.initialized, true);
assert.equal("setupDefaults" in status.body, false);
const login = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "admin" },
});
assert.equal(login.response.status, 200);
assert.equal(login.body.mustChangePassword, true);
assert.equal(typeof login.body.csrfToken, "string");
const cookie = login.response.headers.get("set-cookie")?.split(";", 1)[0];
assert.ok(cookie?.startsWith("webspeak_admin="));
assert.match(login.response.headers.get("set-cookie") ?? "", /HttpOnly/i);
assert.match(login.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i);
const session = await request(origin, "/api/admin/session", { cookie });
assert.equal(session.body.authenticated, true);
assert.equal(session.body.mustChangePassword, true);
const blockedOverview = await request(origin, "/api/admin/overview", { cookie });
assert.equal(blockedOverview.response.status, 403);
assert.equal(blockedOverview.body.code, "PASSWORD_CHANGE_REQUIRED");
const shortPassword = await request(origin, "/api/admin/change-password", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { newPassword: "too-short" },
});
assert.equal(shortPassword.response.status, 400);
assert.equal(shortPassword.body.code, "INVALID_ADMIN_PASSWORD");
const changed = await request(origin, "/api/admin/change-password", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { newPassword: "integration-admin-password" },
});
assert.equal(changed.response.status, 200);
assert.equal(changed.body.mustChangePassword, false);
const updatedSession = await request(origin, "/api/admin/session", { cookie });
assert.equal(updatedSession.body.mustChangePassword, false);
const overview = await request(origin, "/api/admin/overview", { cookie });
assert.deepEqual(overview.body.sessions, { active: 2, peak: 4, limit: 100 });
const rejectedMutation = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
body: { target: "voice.example.com:9988", accessMode: "open", siteName: "Changed", welcomeText: "" },
});
assert.equal(rejectedMutation.response.status, 403);
assert.equal(rejectedMutation.body.code, "CSRF_REJECTED");
const saved = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
csrf: login.body.csrfToken,
body: {
target: "voice.example.com:9988",
passwordAction: "remove",
accessMode: "open",
siteName: "Changed",
welcomeText: "Open access",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
},
});
assert.equal(saved.body.ok, true);
assert.equal(saved.body.settings.accessMode, "open");
assert.equal(saved.body.settings.hasPassword, false);
assert.equal(saved.body.settings.webRtcEnabled, true);
assert.equal(saved.body.settings.webRtcUdpStart, 41000);
assert.equal(saved.body.settings.webRtcUdpEnd, 41099);
const lockedPorts = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
csrf: login.body.csrfToken,
body: {
target: "voice.example.com:9988",
passwordAction: "keep",
accessMode: "open",
siteName: "Changed",
welcomeText: "Open access",
webRtcEnabled: true,
webRtcUdpStart: 42000,
webRtcUdpEnd: 42099,
},
});
assert.equal(lockedPorts.response.status, 400);
assert.equal(lockedPorts.body.code, "WEBRTC_PORT_LOCKED");
const invite = await request(origin, "/api/admin/invites", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { channel: "Lobby", expiresInHours: 4, maxUses: 2 },
});
assert.equal(invite.response.status, 201);
assert.equal(invite.body.ok, true);
assert.match(invite.body.token, /^[A-Za-z0-9_-]{43}$/);
assert.equal(invite.body.invite.channel, "Lobby");
assert.equal("token" in invite.body.invite, false);
const invites = await request(origin, "/api/admin/invites", { cookie });
assert.equal(invites.body.invites.length, 1);
assert.equal(invites.body.invites[0].status, "active");
assert.equal(invites.body.invites[0].target, "voice.example.com:9988");
const sessions = await request(origin, "/api/admin/sessions", { cookie });
assert.deepEqual(sessions.body.sessions, []);
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
assert.equal(diagnostics.body.database.schemaVersion, 3);
assert.equal("target" in diagnostics.body.teamSpeak, true);
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
const report = await request(origin, "/api/admin/diagnostics/report", { cookie });
assert.equal(report.response.status, 200);
assert.match(report.response.headers.get("content-disposition") ?? "", /diagnostic-report\.json/);
assert.equal("target" in report.body.teamSpeak, false);
assert.equal("protocol" in report.body.teamSpeak, false);
assert.equal("serverPassword" in report.body, false);
const revoked = await request(origin, `/api/admin/invites/${encodeURIComponent(invite.body.invite.id)}/revoke`, {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: {},
});
assert.equal(revoked.body.ok, true);
const revokedList = await request(origin, "/api/admin/invites", { cookie });
assert.equal(revokedList.body.invites[0].status, "revoked");
const backup = await download(origin, "/api/admin/backup", cookie);
assert.equal(backup.response.status, 200);
assert.equal(backup.response.headers.get("content-type"), "application/octet-stream");
assert.ok(backup.bytes.length > 100);
assert.equal("serverPassword" in saved.body.settings, false);
const probe = await request(origin, "/api/admin/server/test", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { target: "voice.example.com:9988", passwordAction: "remove" },
});
assert.equal("protocol" in probe.body, false);
const settings = await request(origin, "/api/admin/server", { cookie });
assert.equal("detectedProtocol" in settings.body, false);
assert.equal(settings.body.lastTestLatencyMs, 7);
const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} });
assert.equal(logout.body.ok, true);
const denied = await request(origin, "/api/admin/overview", { cookie });
assert.equal(denied.response.status, 401);
const oldPassword = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "admin" },
});
assert.equal(oldPassword.response.status, 401);
const newPassword = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "integration-admin-password" },
});
assert.equal(newPassword.response.status, 200);
assert.equal(newPassword.body.mustChangePassword, false);
});
async function request(
origin: string,
pathname: string,
options: { method?: string; body?: unknown; cookie?: string; csrf?: string } = {},
): Promise<{ response: Response; body: any }> {
const method = options.method ?? "GET";
const response = await fetch(`${origin}${pathname}`, {
method,
headers: {
accept: "application/json",
...(method !== "GET" ? { "content-type": "application/json", origin } : {}),
...(options.cookie ? { cookie: options.cookie } : {}),
...(options.csrf ? { "x-csrf-token": options.csrf } : {}),
},
...(method !== "GET" ? { body: JSON.stringify(options.body ?? {}) } : {}),
});
return { response, body: await response.json() };
}
async function download(origin: string, pathname: string, cookie?: string): Promise<{ response: Response; bytes: Uint8Array }> {
const response = await fetch(`${origin}${pathname}`, {
headers: { accept: "application/octet-stream", ...(cookie ? { cookie } : {}) },
});
return { response, bytes: new Uint8Array(await response.arrayBuffer()) };
}
+128
View File
@@ -0,0 +1,128 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import { AdminService } from "../src/admin/admin-service.js";
import { WebSpeakDatabase } from "../src/persistence/database.js";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { silentLogger } from "./helpers/logger.js";
test("legacy config imports once, seeds the default admin, and allows password rotation", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-service-"));
const legacyPath = path.join(directory, "config.json");
const legacyText = JSON.stringify({
tsHost: "legacy.example.com",
tsPort: 9988,
tsServerPassword: "legacy-secret-value",
tsServerProtocol: "ts6",
maxClients: 9000,
port: 9999,
trustProxy: true,
}, null, 2);
writeFileSync(legacyPath, legacyText);
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
legacyPath,
async () => ({ ok: true, protocol: "ts6", latencyMs: 4, serverName: "Mock TS", requiresPassword: true }),
);
await service.initialize();
assert.equal(readFileSync(legacyPath, "utf8"), legacyText);
assert.equal(database.getSettings().tsHost, "legacy.example.com");
assert.equal(database.getSettings().tsPort, 9988);
assert.equal(service.getConnectionPolicy().serverPassword, "legacy-secret-value");
assert.equal(readFileSync(path.join(directory, "webspeak.db")).includes(Buffer.from("legacy-secret-value")), false);
assert.equal(service.isInitialized(), true);
assert.equal(await service.verifyPassword("admin", "admin"), true);
assert.equal(await service.verifyPassword("wrong-user", "admin"), false);
assert.equal(service.isPasswordChangeRequired(), true);
await service.changePassword("a-secure-admin-password");
assert.equal(await service.verifyPassword("admin", "a-secure-admin-password"), true);
assert.equal(await service.verifyPassword("admin", "admin"), false);
assert.equal(service.isPasswordChangeRequired(), false);
assert.equal(service.getPublicConfig().accessMode, "fixed");
assert.equal(service.getPublicConfig().target, "legacy.example.com:9988");
service.updateSettings({
target: "public.example.com:9987",
serverPassword: "replacement-secret",
passwordAction: "replace",
accessMode: "open",
siteName: "Open WebSpeak",
welcomeText: "Public gateway",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
});
const publicConfig = service.getPublicConfig();
assert.equal(publicConfig.target, "public.example.com:9987");
assert.equal(publicConfig.accessMode, "open");
assert.equal("serverPassword" in service.getAdminSettings(), false);
assert.equal(service.getAdminSettings().hasPassword, true);
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
assert.equal(service.getAdminSettings().webRtcEnabled, true);
assert.equal(service.getAdminSettings().webRtcUdpStart, 41000);
assert.equal(service.getAdminSettings().webRtcUdpEnd, 41099);
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, udpPortRange: [41000, 41099] });
assert.throws(() => service.updateSettings({
target: "public.example.com:9987",
accessMode: "open",
siteName: "Open WebSpeak",
welcomeText: "Public gateway",
webRtcEnabled: true,
webRtcUdpStart: 42000,
webRtcUdpEnd: 42099,
}), /Disable WebRTC/);
database.close();
});
test("managed invites are opaque, bounded, revocable, and included in database backups", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-invites-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
path.join(directory, "missing-config.json"),
);
await service.initialize();
const created = service.createManagedInvite({ channel: "Lobby", expiresInHours: 2, maxUses: 1 });
assert.match(created.token, /^[A-Za-z0-9_-]{43}$/);
assert.equal(created.invite.channel, "Lobby");
assert.equal(created.invite.status, "active");
assert.equal("token" in created.invite, false);
const consumed = service.consumeManagedInvite(created.token);
assert.deepEqual(consumed?.target, { host: "127.0.0.1", port: 9987 });
assert.equal(consumed?.channel, "Lobby");
assert.equal(service.consumeManagedInvite(created.token), null);
assert.equal(service.listManagedInvites()[0]?.status, "exhausted");
database.createManagedInvite({
id: "invite-expired-test",
tokenHash: "expired-token-hash",
targetHost: "127.0.0.1",
targetPort: 9987,
serverPasswordEncrypted: null,
channel: "Expired",
expiresAt: new Date(Date.now() - 1).toISOString(),
maxUses: 0,
});
assert.equal(database.consumeManagedInvite("expired-token-hash"), null);
const revocable = service.createManagedInvite({ channel: "Revocable", expiresInHours: 2, maxUses: 0 });
assert.equal(service.revokeManagedInvite(revocable.invite.id), true);
assert.equal(service.listManagedInvites().find((invite) => invite.id === revocable.invite.id)?.status, "revoked");
const backup = database.exportBackup();
assert.ok(backup.length > 100);
database.close();
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
assert.equal(reopened.schemaVersion, 3);
assert.equal(reopened.listManagedInvites().length, 3);
reopened.close();
});
+71
View File
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { migrateConfig, saveConfig } from "../src/config.js";
describe("legacy config migration", () => {
it("drops deprecated runtime controls while preserving the TeamSpeak target", () => {
assert.deepEqual(migrateConfig({
port: 3999,
tsHost: "TS.Example.COM",
tsPort: "9988",
tsServerPassword: "secret",
tsServerProtocol: "ts6",
maxClients: 3,
trustProxy: true,
}), {
tsHost: "ts.example.com",
tsPort: 9988,
tsServerPassword: "secret",
});
});
it("accepts a host with an embedded port during migration", () => {
assert.deepEqual(migrateConfig({ tsHost: "[2001:db8::1]:9988" }), {
tsHost: "2001:db8::1",
tsPort: 9988,
tsServerPassword: "",
});
});
it("accepts the address#port form during migration", () => {
assert.deepEqual(migrateConfig({ tsHost: "voice.example.com#9988" }), {
tsHost: "voice.example.com",
tsPort: 9988,
tsServerPassword: "",
});
});
it("falls back safely for malformed legacy targets", () => {
assert.deepEqual(migrateConfig({ tsHost: "bad host", tsPort: 0 }), {
tsHost: "127.0.0.1",
tsPort: 9987,
tsServerPassword: "",
});
});
it("writes the migrated shape without deprecated runtime controls", () => {
const directory = mkdtempSync(join(tmpdir(), "webspeak-m000-config-"));
const path = join(directory, "config.json");
try {
writeFileSync(path, JSON.stringify({
port: 3999,
tsHost: "example.com",
tsPort: 9988,
tsServerProtocol: "ts3",
maxClients: 2,
trustProxy: true,
}), "utf8");
saveConfig(path, migrateConfig(JSON.parse(readFileSync(path, "utf8"))));
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), {
tsHost: "example.com",
tsPort: 9988,
tsServerPassword: "",
});
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
});
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { ChannelInfo, ClientInfo } from "@echosixhiya/teamspeak-client";
import { DirectorySynchronizer } from "../src/server/directory-sync.js";
const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", };
const games: ChannelInfo = { id: 2n, parentID: 1n, name: "Games", description: "", };
function client(id: number, nickname: string, channelID: bigint): ClientInfo {
return { id, nickname, uid: `uid-${id}`, channelID, type: 1, serverGroups: [] };
}
test("directory synchronizer merges welcome events that arrive before the snapshot", () => {
const sync = new DirectorySynchronizer();
sync.applyClientEnter(client(7, "Alice", 1n));
sync.applyClientMoved(7, 2n);
sync.applySnapshot({ channels: [root, games], clients: [client(3, "Bob", 1n)] });
assert.equal(sync.ready, true);
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n], [7, 2n]]);
});
test("directory state and movement events remain isolated per session", () => {
const first = new DirectorySynchronizer();
const second = new DirectorySynchronizer();
const snapshot = { channels: [root, games], clients: [client(3, "Bob", 1n)] };
first.applySnapshot(snapshot);
second.applySnapshot(snapshot);
first.applyClientEnter(client(7, "Alice", 2n));
first.applyClientMoved(3, 2n);
first.applyClientLeave(7);
assert.deepEqual(first.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 2n]]);
assert.deepEqual(second.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n]]);
});
test("directory synchronizer keeps clients across staged partial snapshots", () => {
const sync = new DirectorySynchronizer();
const alice = client(7, "Alice", 1n);
const bob = client(8, "Bob", 1n);
sync.applySnapshot({ channels: [root], clients: [alice, bob] });
sync.applySnapshot({ channels: [root], clients: [bob] });
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [7, 8]);
sync.applyClientLeave(alice.id);
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [8]);
});
+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { normalizeTeamSpeakError } from "../src/errors.js";
describe("normalized connection errors", () => {
it("classifies authentication failures as non-retryable", () => {
const error = normalizeTeamSpeakError(new Error("invalid server password"));
assert.equal(error.code, "authentication_failed");
assert.equal(error.retryable, false);
});
it("classifies network and timeout failures", () => {
assert.equal(normalizeTeamSpeakError(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })).code, "unreachable");
assert.equal(normalizeTeamSpeakError(new Error("ack timeout")).code, "timeout");
});
});
+9
View File
@@ -0,0 +1,9 @@
import type { Logger } from "../../src/logger.js";
export const silentLogger: Logger = {
debug: () => undefined,
info: () => undefined,
warn: () => undefined,
error: () => undefined,
child: () => silentLogger,
};
+13
View File
@@ -0,0 +1,13 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JoinRateLimiter } from "../src/server/join-rate-limit.js";
test("join ticket creation is bounded per peer and resets after its window", () => {
const limiter = new JoinRateLimiter(2);
let now = 10_000;
for (let attempt = 0; attempt < 30; attempt++) assert.equal(limiter.allow("peer-a", now), true);
assert.equal(limiter.allow("peer-a", now), false);
assert.equal(limiter.allow("peer-b", now), true);
now += 60_000;
assert.equal(limiter.allow("peer-a", now), true);
});
+24
View File
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@echosixhiya/teamspeak-client";
import { JoinTicketStore } from "../src/server/join-ticket.js";
test("join tickets are opaque, one-time, and expire", () => {
const store = new JoinTicketStore(1000, 2);
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest" };
const token = store.create(payload, 100);
assert.equal(token.includes("secret"), false);
assert.deepEqual(store.consume(token, 101), payload);
assert.equal(store.consume(token, 102), null);
const expired = store.create(payload, 200);
assert.equal(store.consume(expired, 1201), null);
});
test("join tickets carry identity only in memory and never expose it in the opaque token", () => {
const store = new JoinTicketStore();
const identity = generateIdentity(8).toString();
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest", identity, rememberIdentity: true };
const token = store.create(payload);
assert.equal(token.includes(identity), false);
assert.deepEqual(store.consume(token), payload);
});
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../src/constants.js";
describe("session safety limit", () => {
it("uses the fixed 100-session product limit", () => {
assert.equal(MAX_ACTIVE_SESSIONS, 100);
assert.equal(canAcceptSession(99), true);
assert.equal(canAcceptSession(100), false);
assert.equal(canAcceptSession(101), false);
});
});
+20
View File
@@ -0,0 +1,20 @@
import assert from "node:assert/strict";
import test from "node:test";
import { AdminLoginRateLimiter } from "../src/admin/login-rate-limit.js";
test("admin login limiter blocks repeated failures for one peer", () => {
const limiter = new AdminLoginRateLimiter();
const start = 1_000_000;
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("peer-a", start + attempt);
assert.ok(limiter.retryAfterMs("peer-a", start + 5) > 0);
assert.equal(limiter.retryAfterMs("peer-a", start + 5 * 60 * 1000), 0);
});
test("admin login limiter evicts old peers when its bounded table is full", () => {
const limiter = new AdminLoginRateLimiter(2);
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("oldest", 10 + attempt);
limiter.recordFailure("second", 20);
limiter.recordFailure("newest", 30);
assert.equal(limiter.retryAfterMs("oldest", 31), 0);
assert.equal(limiter.retryAfterMs("second", 31), 0);
});
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRestrictedAddress, resolveSafeOpenTarget } from "../src/security/open-target-policy.js";
test("open mode blocks loopback, private, link-local, multicast and reserved ranges", () => {
for (const address of [
"0.0.0.0", "10.1.2.3", "100.64.0.1", "127.0.0.1", "169.254.1.2",
"172.16.0.1", "192.168.1.2", "224.0.0.1", "255.255.255.255",
"::", "::1", "::7f00:1", "fc00::1", "fe80::1", "fec0::1", "ff02::1", "2001:db8::1",
]) assert.equal(isRestrictedAddress(address), true, address);
assert.equal(isRestrictedAddress("8.8.8.8"), false);
assert.equal(isRestrictedAddress("2606:4700:4700::1111"), false);
});
test("validated literal target is returned for the actual connection", async () => {
assert.deepEqual(await resolveSafeOpenTarget({ host: "8.8.8.8", port: 9987 }), { host: "8.8.8.8", port: 9987 });
await assert.rejects(resolveSafeOpenTarget({ host: "127.0.0.1", port: 9987 }));
});
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import test from "node:test";
import { WebSpeakDatabase, DATABASE_SCHEMA_VERSION } from "../src/persistence/database.js";
import { hashAdminPassword } from "../src/security/admin-password.js";
test("SQLite persistence initializes schema and stores the single admin/settings model", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-"));
const dbPath = path.join(directory, "webspeak.db");
const database = new WebSpeakDatabase(dbPath);
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
assert.equal(database.hasAdmin(), false);
assert.equal(database.getSettings().accessMode, "fixed");
const credential = await hashAdminPassword("database-admin-password");
database.initializeAdmin(credential, {
siteName: "Private Voice",
welcomeText: "Welcome",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
});
assert.equal(database.hasAdmin(), true);
assert.equal(database.getAdminCredential()?.hash, credential.hash);
assert.deepEqual(database.getSettings(), {
siteName: "Private Voice",
welcomeText: "Welcome",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
detectedProtocol: null,
lastTestAt: null,
lastTestLatencyMs: null,
lastTestError: null,
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
updatedAt: database.getSettings().updatedAt,
});
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
database.close();
const reopened = new WebSpeakDatabase(dbPath);
assert.equal(reopened.hasAdmin(), true);
assert.equal(reopened.getSettings().siteName, "Private Voice");
reopened.close();
});
test("SQLite schema v1 upgrades to v3 with a migration copy", () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-"));
const dbPath = path.join(directory, "webspeak.db");
const legacy = new DatabaseSync(dbPath);
legacy.exec(`
CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE admin_credentials (id INTEGER PRIMARY KEY CHECK (id = 1), credential_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE settings (
id INTEGER PRIMARY KEY CHECK (id = 1), site_name TEXT NOT NULL, welcome_text TEXT NOT NULL,
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')), ts_host TEXT NOT NULL,
ts_port INTEGER NOT NULL, ts_password_encrypted TEXT, detected_protocol TEXT,
last_test_at TEXT, last_test_latency_ms INTEGER, last_test_error TEXT, updated_at TEXT NOT NULL
);
CREATE TABLE audit_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT NOT NULL, details_json TEXT NOT NULL, created_at TEXT NOT NULL);
INSERT INTO settings VALUES (1, 'Legacy', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, '2026-01-01T00:00:00.000Z');
PRAGMA user_version = 1;
`);
legacy.close();
const upgraded = new WebSpeakDatabase(dbPath);
assert.equal(upgraded.schemaVersion, 3);
assert.equal(upgraded.getSettings().webRtcEnabled, false);
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
assert.equal(upgraded.listManagedInvites().length, 0);
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
upgraded.close();
});
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import test from "node:test";
import { probeTeamSpeak, toProbeError } from "../src/server/teamspeak-probe.js";
import { silentLogger } from "./helpers/logger.js";
test("connection probe reports protocol/server and always tears down", async () => {
let disconnected = false;
const result = await probeTeamSpeak({ host: "example.com", port: 9987 }, "", silentLogger, () => ({
protocol: "ts6",
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Example TS" }] },
connect: async () => undefined,
disconnect: async () => { disconnected = true; },
}));
assert.equal(result.ok, true);
assert.equal(result.protocol, "ts6");
assert.equal(result.serverName, "Example TS");
assert.equal(disconnected, true);
});
test("connection probe normalizes DNS errors and tears down failures", async () => {
let disconnected = false;
await assert.rejects(
probeTeamSpeak({ host: "missing.invalid", port: 9987 }, "", silentLogger, () => ({
protocol: null,
client: { execCommandWithResponse: async () => [] },
connect: async () => { throw Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" }); },
disconnect: async () => { disconnected = true; },
})),
(error: unknown) => Boolean(error && typeof error === "object" && "code" in error && error.code === "HOST_NOT_FOUND"),
);
assert.equal(disconnected, true);
assert.equal(toProbeError(new Error("authentication invalid password")).code, "INVALID_PASSWORD");
});
test("connection probe keeps a successful result when cleanup reports an error", async () => {
const result = await probeTeamSpeak(
{ host: "voice.example.com", port: 9987 },
"",
silentLogger,
() => ({
protocol: "ts6",
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Cleanup Test" }] },
connect: async () => {},
disconnect: async () => { throw new Error("already disconnected"); },
}),
);
assert.equal(result.ok, true);
assert.equal(result.serverName, "Cleanup Test");
});
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { EndpointProtocolCache, detectTeamSpeakProtocol } from "../src/server/teamspeak-adapter.js";
describe("TeamSpeak protocol adapter", () => {
it("detects TS3 and TS6 from the normal version response", () => {
assert.equal(detectTeamSpeakProtocol("version=3.13.7 build=12345"), "ts3");
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6 version 6.0.0"), "ts6");
assert.equal(detectTeamSpeakProtocol("unknown"), null);
});
it("remembers a successful endpoint only for its bounded TTL", () => {
const cache = new EndpointProtocolCache(1000, 2);
const target = { host: "example.com", port: 9987 };
cache.set(target, "ts6", 1000);
assert.equal(cache.get(target, 1500), "ts6");
assert.equal(cache.get(target, 2001), undefined);
});
it("evicts the oldest endpoint when bounded", () => {
const cache = new EndpointProtocolCache(60_000, 2);
cache.set({ host: "one.example", port: 9987 }, "ts3", 1);
cache.set({ host: "two.example", port: 9987 }, "ts3", 2);
cache.set({ host: "three.example", port: 9987 }, "ts6", 3);
assert.equal(cache.size, 2);
assert.equal(cache.get({ host: "one.example", port: 9987 }, 4), undefined);
});
});
+19
View File
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import test from "node:test";
import { WebSpeakError } from "../src/errors.js";
import { RECONNECT_WINDOW_MS, isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "../src/server/reconnect-policy.js";
test("reconnect backoff follows the bounded policy and applies deterministic jitter", () => {
assert.deepEqual([1, 2, 3, 4, 5, 6, 8].map((attempt) => reconnectDelayMs(attempt, () => 0.5)), [1000, 2000, 4000, 8000, 15000, 30000, 30000]);
assert.equal(reconnectDelayMs(1, () => 0), 900);
assert.equal(reconnectDelayMs(1, () => 1), 1100);
assert.equal(reconnectDelayMs(0, () => 0.5), 1000);
});
test("reconnect eligibility distinguishes transient failures from authentication failures", () => {
assert.equal(isRecoverable(new WebSpeakError("unreachable", "offline", true)), true);
assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "bad password", false)), false);
assert.equal(isRecoverable(null), true);
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS - 1), true);
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS), false);
});
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { decryptSecret, encryptSecret } from "../src/security/secret-crypto.js";
import { hashAdminPassword, verifyAdminPassword } from "../src/security/admin-password.js";
test("master secret is stable and protects authenticated ciphertext", () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-secret-"));
const secretPath = path.join(directory, "master.key");
const first = loadOrCreateMasterSecret(secretPath);
const second = loadOrCreateMasterSecret(secretPath);
assert.equal(first.length, 32);
assert.deepEqual(first, second);
const encrypted = encryptSecret("never-store-this-password", first);
assert.equal(encrypted.includes("never-store-this-password"), false);
assert.equal(decryptSecret(encrypted, first), "never-store-this-password");
const [version, nonce, tag, ciphertext] = encrypted.split(":") as [string, string, string, string];
const tamperedTag = `${tag[0] === "A" ? "B" : "A"}${tag.slice(1)}`;
assert.throws(() => decryptSecret([version, nonce, tamperedTag, ciphertext].join(":"), first));
});
test("admin password uses a salted scrypt credential", async () => {
const first = await hashAdminPassword("a-long-admin-password");
const second = await hashAdminPassword("a-long-admin-password");
assert.notEqual(first.salt, second.salt);
assert.notEqual(first.hash, second.hash);
assert.equal(await verifyAdminPassword("a-long-admin-password", first), true);
assert.equal(await verifyAdminPassword("wrong-password-value", first), false);
assert.equal(JSON.stringify(first).includes("a-long-admin-password"), false);
const pending = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
assert.equal(pending.username, "admin");
assert.equal(pending.mustChangePassword, true);
});
+59
View File
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ConnectionStateMachine, SessionManager } from "../src/server/session-manager.js";
test("connection state machine accepts the normal lifecycle and rejects illegal jumps", () => {
const machine = new ConnectionStateMachine();
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("syncing");
machine.transition("connected");
machine.transition("interrupted");
machine.transition("reconnecting");
machine.transition("connecting");
assert.throws(() => machine.transition("connected"), /Illegal connection state transition/);
});
test("connection state machine can retry a transient authentication phase", () => {
const machine = new ConnectionStateMachine();
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("reconnecting");
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("syncing");
machine.transition("connected");
assert.equal(machine.state, "connected");
});
test("managed session teardown is idempotent and reaches idle even when cleanup fails", async () => {
const manager = new SessionManager();
let cleanupCalls = 0;
const session = manager.admit("session-a", async () => {
cleanupCalls++;
throw new Error("already closed");
});
assert.ok(session);
session.transition("connecting");
await Promise.all([session.teardown("websocket-close"), session.teardown("websocket-error")]);
assert.equal(cleanupCalls, 1);
assert.equal(session.state, "idle");
assert.equal(manager.activeCount, 1);
await manager.teardown("session-a", "websocket-close");
assert.equal(manager.activeCount, 0);
});
test("session manager admits 100 active sessions and rejects the 101st", async () => {
const manager = new SessionManager();
for (let index = 0; index < 100; index++) {
assert.ok(manager.admit(`session-${index}`, async () => undefined));
}
assert.equal(manager.activeCount, 100);
assert.equal(manager.admit("session-100", async () => undefined), null);
assert.equal(manager.peakCount, 100);
assert.equal(manager.createdCount, 100);
await manager.shutdown();
assert.equal(manager.activeCount, 0);
assert.equal(manager.isAccepting, false);
assert.equal(manager.admit("after-shutdown", async () => undefined), null);
});
+45
View File
@@ -0,0 +1,45 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
InvalidTeamSpeakTargetError,
formatTeamSpeakTarget,
parseTeamSpeakTarget,
parseTeamSpeakTargetParts,
teamSpeakTargetKey,
} from "../src/domain/teamspeak-target.js";
describe("TeamSpeak target parser", () => {
it("uses 9987 when the port is omitted", () => {
assert.deepEqual(parseTeamSpeakTarget("Example.COM"), { host: "example.com", port: 9987 });
});
it("parses a custom port", () => {
assert.deepEqual(parseTeamSpeakTarget("ts.example.com:9988"), { host: "ts.example.com", port: 9988 });
});
it("parses the address#port form used by the web fields", () => {
assert.deepEqual(parseTeamSpeakTarget("ts.example.com#9988"), { host: "ts.example.com", port: 9988 });
assert.deepEqual(parseTeamSpeakTarget("[2001:DB8::1]#9988"), { host: "2001:db8::1", port: 9988 });
});
it("supports bracketed IPv6", () => {
const target = parseTeamSpeakTarget("[2001:DB8::1]:9987");
assert.deepEqual(target, { host: "2001:db8::1", port: 9987 });
assert.equal(formatTeamSpeakTarget(target), "[2001:db8::1]:9987");
});
it("accepts legacy split fields", () => {
assert.deepEqual(parseTeamSpeakTargetParts("[::1]", "9988"), { host: "::1", port: 9988 });
assert.deepEqual(parseTeamSpeakTargetParts("ts.example.com", undefined), { host: "ts.example.com", port: 9987 });
});
it("rejects ambiguous raw IPv6 and invalid ports", () => {
assert.throws(() => parseTeamSpeakTarget("2001:db8::1"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:0"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:65536"), InvalidTeamSpeakTargetError);
});
it("creates a stable case-insensitive cache key", () => {
assert.equal(teamSpeakTargetKey({ host: "TS.Example.COM", port: 9987 }), "ts.example.com:9987");
});
});
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@echosixhiya/teamspeak-client";
import { parseTeamSpeakTarget } from "../src/domain/teamspeak-target.js";
import { TSClient, toTSChatMessage } from "../src/server/ts-client.js";
import { silentLogger } from "./helpers/logger.js";
test("TSClient keeps the supplied identity material for reconnects", () => {
const identity = generateIdentity(8);
const client = new TSClient({ target: parseTeamSpeakTarget("example.com:9987"), nickname: "Guest", identity }, silentLogger);
assert.equal(client.getIdentityString(), identity.toString());
});
test("TSClient preserves the TeamSpeak target id for private chat events", () => {
const message = toTSChatMessage({
invokerName: "Alice",
invokerUID: "uid-alice",
message: "hello",
invokerGroups: [],
targetMode: 1,
targetID: 42n,
invokerID: 7,
});
assert.equal(message.targetId, 42n);
assert.equal(message.invokerId, 7);
assert.equal(message.invokerUid, "uid-alice");
});
+85
View File
@@ -0,0 +1,85 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseClientCommand } from "../src/server/voice-protocol.js";
test("voice protocol accepts the versioned command payload", () => {
const command = parseClientCommand(JSON.stringify({
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
}));
assert.deepEqual(command, {
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
});
});
test("voice protocol rejects malformed and unsupported commands", () => {
assert.deepEqual(parseClientCommand("not-json"), {
error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" },
});
assert.equal("error" in parseClientCommand(JSON.stringify({ type: "unknown", payload: {} })), true);
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage" })), {
error: { code: "INVALID_PAYLOAD", message: "消息参数无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage", payload: { message: "x".repeat(501) } })), {
error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" },
});
});
test("voice protocol keeps chat scopes and status actions explicit", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), {
type: "sendPrivateMessage",
requestId: "pm-1",
payload: { clientId: 7, message: "hello" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), {
type: "setAway",
payload: { away: true, message: "back soon" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), {
type: "switchChannel",
payload: { channelId: "42", password: "secret" },
});
});
test("voice protocol rejects unsafe client and away payloads", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), {
error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), {
error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), {
error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" },
});
});
test("voice protocol validates whisper targets and its independent push state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", requestId: "whisper-1", payload: { targetIds: [7, 9] } })), {
type: "setWhisperTargets",
requestId: "whisper-1",
payload: { targetIds: [7, 9] },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: true } })), {
type: "setWhisperActive",
payload: { active: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", payload: { targetIds: [7, 7] } })), {
error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: "yes" } })), {
error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" },
});
});
test("voice protocol accepts and validates the microphone mute state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: true } })), {
type: "setMicrophoneMuted",
payload: { muted: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: "yes" } })), {
error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" },
});
});
+14 -18
View File
@@ -13,7 +13,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.3",
"typescript": "~5.7.0",
"vite": "^6.3.0",
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
}
},
@@ -1104,9 +1104,9 @@
}
},
"node_modules/brace-expansion": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
"integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1301,9 +1301,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"funding": [
{
"type": "github",
@@ -1343,7 +1343,6 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -1373,9 +1372,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"funding": [
{
"type": "opencollective",
@@ -1392,7 +1391,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -1504,7 +1503,6 @@
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -1514,12 +1512,11 @@
}
},
"node_modules/vite": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz",
"integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==",
"version": "6.4.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -1601,7 +1598,6 @@
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz",
"integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.34",
"@vue/compiler-sfc": "3.5.34",
+1 -1
View File
@@ -15,7 +15,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.3",
"typescript": "~5.7.0",
"vite": "^6.3.0",
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
}
}
+35
View File
@@ -0,0 +1,35 @@
const FRAME_SAMPLES = 960;
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
}
process(inputs, outputs) {
const input = inputs[0]?.[0];
const output = outputs[0]?.[0];
if (output) output.fill(0);
if (!input) return true;
let inputOffset = 0;
while (inputOffset < input.length) {
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
this.offset += count;
inputOffset += count;
if (this.offset !== FRAME_SAMPLES) continue;
let sum = 0;
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
const frame = this.frame;
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
}
return true;
}
}
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
+12 -1
View File
@@ -26,8 +26,8 @@
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
</template>
<template v-else-if="name === 'settings'">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-1.42 1.42-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V20h-2v-.09a1.7 1.7 0 0 0-1.03-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-1.42-1.42.06-.06A1.7 1.7 0 0 0 9.4 15a1.7 1.7 0 0 0-1.56-1.03H7v-2h.84A1.7 1.7 0 0 0 9.4 11a1.7 1.7 0 0 0-.34-1.88L9 9.06l1.42-1.42.06.06a1.7 1.7 0 0 0 1.88.34A1.7 1.7 0 0 0 13.39 6.5V6h2v.5a1.7 1.7 0 0 0 1.03 1.54 1.7 1.7 0 0 0 1.88-.34l.06-.06 1.42 1.42-.06.06A1.7 1.7 0 0 0 19.4 11a1.7 1.7 0 0 0 1.56 1.03H21v2h-.04A1.7 1.7 0 0 0 19.4 15Z" />
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
@@ -39,7 +39,12 @@
<path d="m16 16 4.5 4.5" />
</template>
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
<path v-else-if="name === 'clock'" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-14v5l3 2" />
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
<template v-else-if="name === 'info'">
<circle cx="12" cy="12" r="9" />
<path d="M12 10v6m0-9h.01" />
</template>
<template v-else-if="name === 'plus'">
<path d="M12 5v14M5 12h14" />
</template>
@@ -63,7 +68,13 @@
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
<template v-else-if="name === 'sun'">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
</template>
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
File diff suppressed because it is too large. Load diff
+6
View File
@@ -3,9 +3,15 @@ import { createPinia } from "pinia";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import WebClient from "./views/WebClient.vue";
import AdminView from "./views/AdminView.vue";
import DemoView from "./views/DemoView.vue";
import "./services/theme.js";
const routes = [
{ path: "/", name: "webclient", component: WebClient },
{ path: "/join", name: "join", component: WebClient },
{ path: "/demo", name: "demo", component: DemoView },
{ path: "/admin/:pathMatch(.*)*", name: "admin", component: AdminView },
];
const router = createRouter({
+255
View File
@@ -0,0 +1,255 @@
const DB_NAME = "webspeak-local";
const DB_VERSION = 1;
const CURRENT_IDENTITY_KEY = "current";
const PREFERENCES_KEY = "singleton";
export interface StoredIdentity {
id: string;
label?: string;
privateMaterial: string;
createdAt: number;
lastUsedAt: number;
}
export interface FavoriteServer {
id: string;
label: string;
address: string;
nickname?: string;
identityId?: string;
lastChannelHint?: { id?: string; name?: string };
}
export interface RecentServer {
id: string;
address: string;
nickname?: string;
identityId?: string;
lastConnectedAt: number;
lastChannelHint?: { id?: string; name?: string };
}
export interface LocalPreferences {
schemaVersion: 1;
locale?: "auto" | "zh-CN" | "en";
theme?: "system" | "light" | "dark";
microphoneMuted?: boolean;
voxThreshold?: number;
language?: "zh" | "en";
preferredInputDeviceId?: string;
preferredOutputDeviceId?: string;
inputGain?: number;
outputVolume?: number;
notificationVolume?: number;
lastNickname?: string;
inputDeviceId?: string;
volumesByUid?: Record<string, number>;
}
let databasePromise: Promise<IDBDatabase> | null = null;
export function isLocalPersistenceAvailable(): boolean {
return typeof indexedDB !== "undefined";
}
function openDatabase(): Promise<IDBDatabase> {
if (!isLocalPersistenceAvailable()) return Promise.reject(new Error("IndexedDB unavailable"));
if (databasePromise) return databasePromise;
databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error ?? new Error("Could not open local storage"));
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains("identities")) database.createObjectStore("identities", { keyPath: "id" });
if (!database.objectStoreNames.contains("preferences")) database.createObjectStore("preferences", { keyPath: "id" });
if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" });
if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" });
};
request.onsuccess = () => {
const database = request.result;
database.onversionchange = () => database.close();
resolve(database);
};
}).catch((error) => {
databasePromise = null;
throw error;
});
return databasePromise!;
}
async function request<T>(storeName: string, mode: IDBTransactionMode, action: (store: IDBObjectStore, resolve: (value: T) => void, reject: (reason?: unknown) => void) => void): Promise<T> {
const database = await openDatabase();
return new Promise<T>((resolve, reject) => {
const transaction = database.transaction(storeName, mode);
action(transaction.objectStore(storeName), resolve, reject);
transaction.onerror = () => reject(transaction.error ?? new Error("Local storage transaction failed"));
});
}
export async function loadStoredIdentity(): Promise<StoredIdentity | null> {
try {
return await request<StoredIdentity | null>("identities", "readonly", (store, resolve, reject) => {
const get = store.get(CURRENT_IDENTITY_KEY);
get.onsuccess = () => resolve((get.result as StoredIdentity | undefined) ?? null);
get.onerror = () => reject(get.error);
});
} catch {
return null;
}
}
export async function saveStoredIdentity(privateMaterial: string, label = "此设备"): Promise<boolean> {
try {
const existing = await loadStoredIdentity();
await request("identities", "readwrite", (store, resolve, reject) => {
const put = store.put({
id: CURRENT_IDENTITY_KEY,
label,
privateMaterial,
createdAt: existing?.createdAt ?? Date.now(),
lastUsedAt: Date.now(),
} satisfies StoredIdentity);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
return true;
} catch {
return false;
}
}
export async function removeStoredIdentity(): Promise<void> {
try {
await request("identities", "readwrite", (store, resolve, reject) => {
const remove = store.delete(CURRENT_IDENTITY_KEY);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Identity removal is best effort when browser storage is unavailable.
}
}
export async function loadLocalPreferences(): Promise<LocalPreferences> {
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
try {
const value = await request<(LocalPreferences & { id: string }) | null>("preferences", "readonly", (store, resolve, reject) => {
const get = store.get(PREFERENCES_KEY);
get.onsuccess = () => resolve((get.result as (LocalPreferences & { id: string }) | undefined) ?? null);
get.onerror = () => reject(get.error);
});
if (!value || value.schemaVersion !== 1) return defaults;
return { ...defaults, ...value, volumesByUid: { ...defaults.volumesByUid, ...value.volumesByUid } };
} catch {
return defaults;
}
}
export async function saveLocalPreferences(preferences: LocalPreferences): Promise<void> {
try {
const existing = await loadLocalPreferences();
await request("preferences", "readwrite", (store, resolve, reject) => {
const put = store.put({
...existing,
...preferences,
volumesByUid: { ...existing.volumesByUid, ...preferences.volumesByUid },
id: PREFERENCES_KEY,
});
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
} catch {
// Local preference persistence is optional and never blocks joining.
}
}
export async function listFavorites(): Promise<FavoriteServer[]> {
try {
return await request<FavoriteServer[]>("favorites", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve((get.result as FavoriteServer[]).sort((a, b) => a.label.localeCompare(b.label)));
get.onerror = () => reject(get.error);
});
} catch {
return [];
}
}
export async function saveFavorite(favorite: FavoriteServer): Promise<void> {
try {
await request("favorites", "readwrite", (store, resolve, reject) => {
const put = store.put(favorite);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
} catch {
// Favorites are an optional convenience.
}
}
export async function removeFavorite(id: string): Promise<void> {
try {
await request("favorites", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Favorites are an optional convenience.
}
}
export async function listRecentServers(): Promise<RecentServer[]> {
try {
const recent = await request<RecentServer[]>("recent", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve(get.result as RecentServer[]);
get.onerror = () => reject(get.error);
});
return recent.sort((a, b) => b.lastConnectedAt - a.lastConnectedAt).slice(0, 10);
} catch {
return [];
}
}
export async function recordRecentServer(server: RecentServer): Promise<void> {
try {
await request("recent", "readwrite", (store, resolve, reject) => {
const put = store.put(server);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
const all = await request<RecentServer[]>("recent", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve(get.result as RecentServer[]);
get.onerror = () => reject(get.error);
});
all.sort((a, b) => b.lastConnectedAt - a.lastConnectedAt);
for (const old of all.slice(10)) await removeRecentServer(old.id);
} catch {
// Recent servers are an optional convenience.
}
}
async function removeRecentServer(id: string): Promise<void> {
await request("recent", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
}
export async function clearLocalData(): Promise<void> {
try {
const database = await openDatabase();
await Promise.all(["identities", "preferences", "favorites", "recent"].map((storeName) => new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.objectStore(storeName).clear();
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error ?? new Error("Local storage clear failed"));
transaction.onabort = () => reject(transaction.error ?? new Error("Local storage clear aborted"));
})));
} catch {
// Clearing local data is best effort when storage is unavailable.
}
}
+56
View File
@@ -0,0 +1,56 @@
export const DEFAULT_TEAM_SPEAK_PORT = "9987";
export interface TeamSpeakTargetFields {
address: string;
port: string;
}
/** Split both the current canonical target and the legacy address#port form. */
export function splitTeamSpeakTarget(value: unknown, fallbackPort = DEFAULT_TEAM_SPEAK_PORT): TeamSpeakTargetFields {
const input = typeof value === "string" ? value.trim() : "";
if (!input) return { address: "", port: fallbackPort };
const hash = input.lastIndexOf("#");
if (hash > 0 && isPort(input.slice(hash + 1))) {
return { address: stripBrackets(input.slice(0, hash)), port: input.slice(hash + 1) };
}
if (input.startsWith("[")) {
const closingBracket = input.indexOf("]");
if (closingBracket > 0) {
const address = input.slice(1, closingBracket);
const suffix = input.slice(closingBracket + 1);
const port = suffix.startsWith(":") && isPort(suffix.slice(1)) ? suffix.slice(1) : fallbackPort;
return { address, port };
}
}
const colon = input.lastIndexOf(":");
if (colon > 0 && input.indexOf(":") === colon && isPort(input.slice(colon + 1))) {
return { address: input.slice(0, colon), port: input.slice(colon + 1) };
}
return { address: stripBrackets(input), port: fallbackPort };
}
/** Build the canonical API value from the two user-facing fields. */
export function combineTeamSpeakTarget(address: string, port: string): string {
const normalizedAddress = stripBrackets(address.trim());
const normalizedPort = port.trim() || DEFAULT_TEAM_SPEAK_PORT;
if (!normalizedAddress) return "";
return normalizedAddress.includes(":") ? `[${normalizedAddress}]:${normalizedPort}` : `${normalizedAddress}:${normalizedPort}`;
}
export function isValidTeamSpeakPort(value: string): boolean {
return isPort(value.trim());
}
function isPort(value: string): boolean {
if (!/^\d+$/.test(value)) return false;
const port = Number(value);
return Number.isInteger(port) && port >= 1 && port <= 65535;
}
function stripBrackets(value: string): string {
return value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
}
+32
View File
@@ -0,0 +1,32 @@
export type ThemeMode = "system" | "light" | "dark";
const THEME_KEY = "webspeak:theme";
export function getStoredTheme(): ThemeMode {
const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY);
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function applyTheme(theme: ThemeMode): void {
if (typeof document === "undefined") return;
document.documentElement.dataset.theme = theme;
}
export function saveTheme(theme: ThemeMode): void {
if (typeof localStorage !== "undefined") localStorage.setItem(THEME_KEY, theme);
applyTheme(theme);
}
export function isDarkTheme(theme: ThemeMode): boolean {
if (theme === "dark") return true;
if (theme === "light") return false;
return typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-color-scheme: dark)").matches
: false;
}
export function nextTheme(theme: ThemeMode): ThemeMode {
return isDarkTheme(theme) ? "light" : "dark";
}
applyTheme(getStoredTheme());
+677
View File
@@ -0,0 +1,677 @@
<template>
<div class="admin-root">
<div v-if="loading" class="center-card compact"><span class="spinner"></span><p>{{ tr('loading') }}</p></div>
<main v-else-if="screen === 'change-password'" class="login-page">
<section class="login-card">
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<header><h1>{{ tr('changePasswordTitle') }}</h1><p>{{ tr('changePasswordLead') }}</p></header>
<form @submit.prevent="changePassword"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('newPassword') }}</span><input v-model="newPassword" type="password" autocomplete="new-password" maxlength="1024" autofocus :placeholder="tr('passwordPlaceholder')" /></label><label><span>{{ tr('confirmPassword') }}</span><input v-model="confirmNewPassword" type="password" autocomplete="new-password" maxlength="1024" /></label><div class="strength"><i :style="{ width: `${passwordStrength}%` }"></i></div><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('savePassword') }}</button></form>
<p class="security-note">{{ tr('defaultCredentialNotice') }}</p><button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button>
</section>
</main>
<main v-else-if="screen === 'login'" class="login-page">
<section class="login-card">
<div class="admin-brand centered"><span><Icon name="waveform" :size="24" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<header><h1>{{ tr('welcomeAdmin') }}</h1><p>{{ tr('loginLead') }}</p></header>
<form @submit.prevent="login"><div v-if="errorMessage" class="alert error">{{ errorMessage }}</div><label><span>{{ tr('adminUsername') }}</span><input v-model.trim="loginUsername" autocomplete="username" autofocus /></label><label><span>{{ tr('adminPassword') }}</span><input v-model="loginPassword" type="password" autocomplete="current-password" /></label><button class="primary-button wide" :disabled="submitting" type="submit"><span v-if="submitting" class="spinner small"></span>{{ tr('login') }}</button></form>
<div class="login-actions"><RouterLink to="/" class="home-link"><Icon name="home" :size="15" />{{ tr('backHome') }}</RouterLink><button class="language-link" type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div>
</section>
</main>
<div v-else class="admin-shell">
<aside class="admin-sidebar">
<div class="admin-brand"><span><Icon name="waveform" :size="22" /></span><div><strong>WebSpeak</strong><small>{{ tr('adminConsole') }}</small></div></div>
<nav><RouterLink to="/admin" exact-active-class="active"><Icon name="activity" :size="18" />{{ tr('overview') }}</RouterLink><RouterLink to="/admin/server" active-class="active"><Icon name="server" :size="18" />{{ tr('server') }}</RouterLink><RouterLink to="/admin/operations" active-class="active"><Icon name="users" :size="18" />{{ tr('operations') }}</RouterLink></nav>
<div class="sidebar-bottom"><a href="/" target="_blank"><Icon name="share" :size="16" />{{ tr('openGuest') }}</a><button type="button" @click="logout"><Icon name="door" :size="16" />{{ tr('logout') }}</button></div>
</aside>
<main class="admin-main">
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" class="theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /><span>{{ themeLabel }}</span></button><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div></header>
<div v-if="errorMessage" class="alert error page-alert">{{ errorMessage }}</div>
<section v-if="route.path === '/admin/server'" class="page-content server-page">
<div class="page-heading"><div><h2>{{ tr('serverSettings') }}</h2><p>{{ tr('serverSettingsLead') }}</p></div><button class="primary-button" :disabled="submitting" @click="saveServerSettings">{{ submitting ? tr('saving') : tr('saveChanges') }}</button></div>
<div class="settings-grid">
<article class="settings-card"><h3>{{ tr('teamSpeakTarget') }}</h3><div class="target-fields"><label><span>{{ tr('serverAddress') }}</span><input v-model.trim="serverForm.address" :placeholder="tr('serverPlaceholder')" /></label><label><span>{{ tr('serverPort') }}</span><input v-model.trim="serverForm.port" inputmode="numeric" type="text" maxlength="5" :placeholder="tr('serverPortPlaceholder')" /></label></div><div class="password-row"><label><span>{{ tr('serverPassword') }}</span><input v-model="serverForm.serverPassword" type="password" autocomplete="off" :disabled="serverForm.passwordAction !== 'replace'" :placeholder="serverForm.hasPassword ? tr('passwordConfigured') : tr('optionalPassword')" /></label><div class="password-actions"><button type="button" :class="{ active: serverForm.passwordAction === 'replace' }" @click="serverForm.passwordAction = 'replace'">{{ tr('change') }}</button><button v-if="serverForm.hasPassword" type="button" :class="{ danger: serverForm.passwordAction === 'remove' }" @click="serverForm.passwordAction = 'remove'">{{ tr('remove') }}</button></div></div><button class="secondary-button" type="button" :disabled="testing" @click="testServerConnection"><span v-if="testing" class="spinner small"></span><Icon v-else name="activity" :size="17" />{{ testing ? tr('testing') : tr('testConnection') }}</button><div v-if="testResult" :class="['test-result', testResult.ok ? 'success' : 'error']"><Icon :name="testResult.ok ? 'check' : 'close'" :size="18" /><div><strong>{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}</strong><small>{{ testResultText }}</small></div></div></article>
<article class="settings-card"><h3>{{ tr('accessAndIdentity') }}</h3><fieldset><legend>{{ tr('accessMode') }}</legend><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="fixed" /><span><strong>{{ tr('fixedMode') }}</strong><small>{{ tr('fixedModeLead') }}</small></span></label><label class="choice"><input v-model="serverForm.accessMode" type="radio" value="open" /><span><strong>{{ tr('openMode') }}</strong><small>{{ tr('openModeLead') }}</small></span></label></fieldset><label><span>{{ tr('siteName') }}</span><input v-model.trim="serverForm.siteName" maxlength="80" /></label><label><span>{{ tr('welcomeText') }}</span><textarea v-model="serverForm.welcomeText" maxlength="500" rows="4"></textarea></label></article>
<article class="settings-card advanced-card"><div><h3>{{ tr('advancedSettings') }}</h3><p class="card-help">{{ tr('advancedSettingsLead') }}</p></div><label class="choice toggle-choice"><input v-model="serverForm.webRtcEnabled" type="checkbox" @change="handleWebRtcToggle" /><span><strong>{{ tr('webrtcEnabled') }}</strong><small>{{ tr('webrtcEnabledLead') }}</small></span></label><div class="webrtc-port-fields"><div class="port-fields-heading"><strong>{{ tr('webrtcPortRange') }}</strong><small>{{ tr('webrtcPortRangeLead') }}</small></div><div class="port-inputs"><label><span>{{ tr('webrtcPortStart') }}</span><input v-model.number="serverForm.webRtcUdpStart" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label><label><span>{{ tr('webrtcPortEnd') }}</span><input v-model.number="serverForm.webRtcUdpEnd" type="number" inputmode="numeric" min="1024" max="65535" :disabled="serverForm.webRtcEnabled" /></label></div></div><small class="field-help">{{ tr('webrtcApplyHint') }}</small></article>
</div>
<article class="readonly-card"><h3>{{ tr('runtimeFacts') }}</h3><dl><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(serverForm.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}</dd></div><div><dt>{{ tr('internalPort') }}</dt><dd>3040</dd></div></dl></article>
</section>
<section v-else-if="route.path === '/admin/operations'" class="page-content operations-page">
<div class="page-heading"><div><h2>{{ tr('operations') }}</h2><p>{{ tr('operationsLead') }}</p></div><button class="secondary-button" :disabled="operationsLoading" @click="loadOperations"><span v-if="operationsLoading" class="spinner small"></span><Icon v-else name="refresh" :size="17" />{{ tr('refresh') }}</button></div>
<div class="alert info system-notice"><Icon name="info" :size="16" /><span>{{ tr('updateNotice', { version: operations.diagnostics.version || '—' }) }}</span></div>
<div class="operations-grid operations-primary">
<article class="operation-card operation-wide"><header><div><h3>{{ tr('sessions') }}</h3><p>{{ tr('sessionsLead') }}</p></div><strong>{{ operations.sessions.length }}</strong></header><div v-if="operations.sessions.length" class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }}</th><th>{{ tr('sessionState') }}</th><th>{{ tr('age') }}</th><th>{{ tr('memberCount') }}</th><th></th></tr></thead><tbody><tr v-for="session in operations.sessions" :key="session.id"><td><strong>{{ session.nickname }}</strong><small>{{ session.target }}</small></td><td><span class="state-pill">{{ sessionStateLabel(session.state) }}</span></td><td>{{ formatAge(session.ageSeconds) }}</td><td>{{ session.memberCount }}</td><td><button class="danger-button" type="button" :disabled="terminatingSession === session.id" @click="terminateSession(session)">{{ terminatingSession === session.id ? tr('terminating') : tr('endSession') }}</button></td></tr></tbody></table></div><div v-else class="operation-empty"><Icon name="users" :size="22" /><span>{{ tr('sessionEmpty') }}</span></div></article>
<article class="operation-card"><header><div><h3>{{ tr('invites') }}</h3><p>{{ tr('invitesLead') }}</p></div></header><form class="invite-form" @submit.prevent="createInvite"><label><span>{{ tr('inviteChannel') }}</span><input v-model.trim="inviteForm.channel" maxlength="100" :placeholder="tr('inviteChannelPlaceholder')" /></label><div class="invite-form-grid"><label><span>{{ tr('expiresIn') }}</span><input v-model.number="inviteForm.expiresInHours" type="number" min="1" max="720" /></label><label><span>{{ tr('maxUses') }}</span><input v-model.number="inviteForm.maxUses" type="number" min="0" max="10000" /></label></div><small class="field-help">{{ tr('unlimitedUses') }}</small><button class="primary-button" type="submit" :disabled="submitting"><span v-if="submitting" class="spinner small"></span>{{ tr('createInvite') }}</button></form><div v-if="createdInvite" class="generated-invite"><strong>{{ tr('inviteCreated') }}</strong><div class="generated-link"><input :value="createdInvite.link" readonly /><button class="secondary-button" type="button" @click="copyInviteLink">{{ tr('copyLink') }}</button></div><small>{{ tr('inviteSecurity') }}</small></div><div v-if="operations.invites.length" class="invite-list"><div v-for="invite in operations.invites" :key="invite.id" class="invite-row"><div><strong>{{ invite.channel || tr('defaultChannel') }}</strong><small>{{ invite.target }} · {{ formatDate(invite.expiresAt) }}</small></div><div class="invite-row-meta"><span :class="['state-pill', invite.status]">{{ inviteStatusLabel(invite.status) }}</span><span>{{ invite.useCount }}/{{ invite.maxUses || '∞' }}</span><button v-if="invite.status === 'active'" class="text-danger" type="button" @click="revokeInvite(invite)">{{ tr('revoke') }}</button></div></div></div></article>
</div>
<div class="operations-grid lower-operations"><article class="operation-card diagnostics-card"><header><div><h3>{{ tr('diagnostics') }}</h3><p>{{ tr('diagnosticsLead') }}</p></div><a class="text-link" href="/api/admin/diagnostics/report">{{ tr('downloadReport') }}</a></header><dl class="diagnostic-list"><div><dt>{{ tr('version') }}</dt><dd>{{ operations.diagnostics.version || '—' }}</dd></div><div><dt>{{ tr('runtime') }}</dt><dd>{{ operations.diagnostics.node || '—' }}</dd></div><div><dt>{{ tr('platform') }}</dt><dd>{{ operations.diagnostics.platform || '—' }} / {{ operations.diagnostics.arch || '—' }}</dd></div><div><dt>{{ tr('databaseSchema') }}</dt><dd>v{{ operations.diagnostics.schemaVersion || '—' }}</dd></div><div><dt>{{ tr('createdSessions') }}</dt><dd>{{ operations.diagnostics.createdSessions }}</dd></div></dl><button class="secondary-button" type="button" @click="downloadBackup">{{ tr('exportBackup') }}</button></article><article class="operation-card logs-card"><header><div><h3>{{ tr('logViewer') }}</h3><p>{{ tr('logViewerLead') }}</p></div><span v-if="!operations.logs.available" class="muted-label">{{ tr('logsUnavailable') }}</span></header><div v-if="operations.logs.entries.length" class="log-list"><div v-for="(entry, index) in operations.logs.entries" :key="`${entry.timestamp}-${index}`" class="log-row"><span :class="['log-level', entry.level.toLowerCase()]">{{ entry.level }}</span><div><strong>{{ entry.message || '—' }}</strong><small>{{ formatDate(entry.timestamp) }}<template v-if="Object.keys(entry.context).length"> · {{ formatContext(entry.context) }}</template></small></div></div></div><div v-else class="operation-empty"><Icon name="activity" :size="22" /><span>{{ tr('noLogs') }}</span></div></article><article class="operation-card audit-card"><header><div><h3>{{ tr('audit') }}</h3><p>{{ tr('auditLead') }}</p></div></header><ul class="event-list"><li v-for="event in operations.audit" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!operations.audit.length" class="empty-event">{{ tr('auditEmpty') }}</li></ul></article></div>
</section>
<section v-else class="page-content overview-page">
<div v-if="overview.legacyConfigImported" class="alert info import-notice"><span>{{ tr('legacyImported') }}</span><button type="button" @click="dismissLegacyNotice">{{ tr('gotIt') }}</button></div>
<div class="hero-status"><div><small>{{ tr('systemStatus') }}</small><h2>{{ tr('everythingRunning') }}</h2><p>{{ tr('overviewLead') }}</p></div><span class="status-badge"><i></i>{{ tr('running') }}</span></div>
<div class="metric-grid"><article><span><Icon name="activity" :size="20" /></span><small>{{ tr('gateway') }}</small><strong>{{ overview.gateway.version || '—' }}</strong><em>{{ formatUptime(overview.gateway.uptimeSeconds) }}</em></article><article><span><Icon name="server" :size="20" /></span><small>{{ tr('teamSpeakTarget') }}</small><strong>{{ overview.teamSpeak.target || '—' }}</strong><em>{{ targetStatusText }}</em></article><article><span><Icon name="users" :size="20" /></span><small>{{ tr('activeSessions') }}</small><strong>{{ overview.sessions.active }} / {{ overview.sessions.limit }}</strong><em>{{ tr('peakSessions', { count: overview.sessions.peak }) }}</em></article></div>
<div class="overview-columns"><article class="overview-card target-health-card"><header><div><h3>{{ tr('targetHealth') }}</h3><p>{{ tr('targetHealthLead') }}</p></div><RouterLink to="/admin/server">{{ tr('manage') }}</RouterLink></header><dl><div><dt>{{ tr('status') }}</dt><dd><i :class="overview.teamSpeak.status"></i>{{ targetStatusText }}</dd></div><div><dt>{{ tr('lastTest') }}</dt><dd>{{ formatDate(overview.teamSpeak.lastTestAt) }}</dd></div><div><dt>{{ tr('latency') }}</dt><dd>{{ overview.teamSpeak.latencyMs == null ? '—' : `${overview.teamSpeak.latencyMs} ms` }}</dd></div></dl></article><article class="overview-card recent-events-card"><header><div><h3>{{ tr('recentEvents') }}</h3><p>{{ tr('recentEventsLead') }}</p></div></header><ul class="event-list"><li v-for="event in overview.recentEvents" :key="`${event.event}-${event.createdAt}`"><span><Icon name="check" :size="14" /></span><div><strong>{{ eventName(event.event) }}</strong><small>{{ formatDate(event.createdAt) }}</small></div></li><li v-if="!overview.recentEvents.length" class="empty-event">{{ tr('noRecentEvents') }}</li></ul></article></div>
</section>
<div v-if="webrtcPortNoticeOpen" class="modal-backdrop" @click.self="webrtcPortNoticeOpen = false"><section class="modal-card" role="dialog" aria-modal="true" :aria-label="tr('webrtcPortNoticeTitle')"><div class="modal-icon"><Icon name="info" :size="21" /></div><h2>{{ tr('webrtcPortNoticeTitle') }}</h2><p>{{ tr('webrtcPortNotice', { range: webrtcPortRangeText }) }}</p><button class="primary-button wide" type="button" @click="webrtcPortNoticeOpen = false">{{ tr('gotIt') }}</button></section></div>
</main>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import Icon from "../components/Icon.vue";
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
type Language = "zh" | "en";
type Screen = "login" | "change-password" | "admin";
type AccessMode = "fixed" | "open";
interface ProbeState { ok: boolean; latencyMs?: number; serverName?: string | null; code?: string }
const route = useRoute();
const router = useRouter();
const language = ref<Language>((localStorage.getItem("webspeak:language") as Language) || "zh");
const themeMode = ref<ThemeMode>(getStoredTheme());
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
applyTheme(themeMode.value);
const loading = ref(true);
const screen = ref<Screen>("login");
const csrfToken = ref("");
const submitting = ref(false);
const testing = ref(false);
const errorMessage = ref("");
const loginUsername = ref("admin");
const loginPassword = ref("");
const newPassword = ref("");
const confirmNewPassword = ref("");
const testResult = ref<ProbeState | null>(null);
const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", webRtcEnabled: false, webRtcUdpStart: 40000, webRtcUdpEnd: 40099, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null });
const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false });
interface AdminSession { id: string; nickname: string; target: string; state: string; createdAt: string; ageSeconds: number; tsClientId: number | null; channelId: string | null; memberCount: number }
interface ManagedInvite { id: string; target: string; channel: string; expiresAt: string; maxUses: number; useCount: number; createdAt: string; revokedAt: string | null; status: "active" | "expired" | "exhausted" | "revoked" }
interface AdminLog { timestamp: string | null; level: string; message: string; context: Record<string, string | number | boolean> }
const operationsLoading = ref(false);
const terminatingSession = ref("");
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const webrtcPortNoticeOpen = ref(false);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[], diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 }, logs: { available: false, entries: [] as AdminLog[] }, audit: [] as Array<{ event: string; createdAt: string }> });
const copy = {
zh: {
loading: "正在载入管理控制台…",
adminConsole: "管理控制台",
changePasswordTitle: "首次登录需要修改密码",
changePasswordLead: "默认密码仅用于首次登录。请设置一个至少 12 个字符的新管理员密码。",
savePassword: "保存新密码",
defaultCredentialNotice: "默认账号:admin,默认密码:admin。修改后旧密码将立即失效。",
adminUsername: "管理员账号",
newPassword: "新管理员密码",
passwordPlaceholder: "至少 12 个字符",
passwordHint: "建议使用长且唯一的密码。",
confirmPassword: "确认管理员密码",
languageSwitch: "English",
themeSystem: "跟随系统",
themeLight: "浅色主题",
themeDark: "深色主题",
switchToLightTheme: "切换到浅色主题",
switchToDarkTheme: "切换到深色主题",
welcomeAdmin: "欢迎回来",
loginLead: "输入管理员账号和密码以管理此 WebSpeak 实例。",
adminPassword: "管理员密码",
login: "登录",
backHome: "返回首页",
overview: "概览",
server: "服务器",
operations: "运维",
openGuest: "打开访客页面",
logout: "退出登录",
gatewayRunning: "网关运行中",
serverSettings: "服务器设置",
serverSettingsLead: "管理默认 TeamSpeak 目标、访问策略和访客页面内容。",
saving: "正在保存…",
saveChanges: "保存更改",
teamSpeakTarget: "默认 TeamSpeak 目标",
serverAddress: "TeamSpeak 服务器地址",
serverPlaceholder: "例如:ts.example.com 或 127.0.0.1",
serverPort: "语音端口",
serverPortPlaceholder: "9987",
serverHint: "请分别填写服务器地址和语音端口;IPv6 地址可直接填写,不需要方括号。",
serverPassword: "服务器密码",
optional: "可选",
optionalPassword: "无密码则留空",
passwordConfigured: "已配置密码(留空保持不变)",
change: "修改",
remove: "移除",
testConnection: "测试连接",
testing: "正在测试…",
connectionReady: "连接成功",
connectionFailed: "连接失败",
accessAndIdentity: "访问与站点信息",
advancedSettings: "高级参数",
advancedSettingsLead: "仅在需要时调整网关的高级传输参数。",
webrtcSettings: "WebRTC 语音",
webrtcLead: "由当前 WebSpeak 网关直接提供低延迟语音传输,无需配置其他服务器。",
webrtcEnabled: "启用 WebRTC",
webrtcEnabledLead: "浏览器和网络支持时使用实时语音通道,否则自动回退到兼容模式。",
webrtcPortRange: "WebRTC UDP 端口范围",
webrtcPortRangeLead: "请在 WebSpeak 所在主机的防火墙和安全组放行整个范围。",
webrtcPortStart: "起始端口",
webrtcPortEnd: "结束端口",
webrtcApplyHint: "端口范围仅可在 WebRTC 关闭时修改;开启后会锁定,保存后对新连接生效。",
webrtcPortNoticeTitle: "请先放行 WebRTC 端口",
webrtcPortNotice: "需要开启端口,范围是 {{range}}(UDP)。请先在主机防火墙、安全组和 Docker 端口映射中放行该范围。",
accessMode: "访客访问模式",
fixedMode: "仅限此 TeamSpeak 服务器",
fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。",
openMode: "允许访客输入其他服务器",
openModeLead: "访客可输入公网 TeamSpeak 地址;内网和保留地址会被阻止。",
siteName: "站点显示名称",
welcomeText: "欢迎文本",
runtimeFacts: "运行时信息",
lastTest: "最近测试",
latency: "延迟",
internalPort: "内部端口",
unknown: "未知",
legacyImported: "已导入旧 config.json。WebSpeak 现在由管理控制台管理,原文件不会再作为实时配置源。",
gotIt: "知道了",
systemStatus: "系统状态",
everythingRunning: "WebSpeak 正常运行",
overviewLead: "管理服务可用;TeamSpeak 可达性以最近一次连接测试为准。",
running: "运行中",
gateway: "网关",
activeSessions: "活动会话",
peakSessions: "本次启动峰值 {{count}}",
targetHealth: "目标状态",
targetHealthLead: "最近一次短连接测试的结果。",
manage: "管理",
status: "状态",
recentEvents: "最近事件",
recentEventsLead: "仅记录管理和系统事件,不包含聊天内容。",
noRecentEvents: "暂无事件",
reachable: "可连接",
unreachable: "不可连接",
notTested: "尚未测试",
setupPasswordsMismatch: "两次输入的密码不一致。",
setupPasswordShort: "管理员密码至少需要 12 个字符。",
invalidPassword: "管理员密码错误。",
rateLimited: "尝试次数过多,请稍后再试。",
requestFailed: "请求失败,请检查输入后重试。",
loginEvent: "管理员登录成功",
logoutEvent: "管理员退出登录",
settingsEvent: "服务器设置已更新",
initializedEvent: "默认管理员账号已创建",
importedEvent: "已导入旧配置",
testEvent: "连接测试完成",
operationsLead: "无需登录服务器终端即可完成日常维护和问题定位。",
refresh: "刷新",
sessions: "活动会话",
sessionsLead: "查看当前浏览器连接,并在必要时安全断开单个会话。",
sessionEmpty: "当前没有活动会话。",
nickname: "昵称",
sessionState: "状态",
age: "持续时间",
memberCount: "成员数",
endSession: "断开",
terminating: "断开中…",
sessionTerminated: "会话已断开。",
confirmTerminate: "确定断开「{{nickname}}」吗?",
invites: "受控邀请",
invitesLead: "创建可过期、可限次的邀请链接;链接中不包含服务器密码。",
inviteChannel: "目标频道",
inviteChannelPlaceholder: "留空使用默认频道",
expiresIn: "有效期(小时)",
maxUses: "最多使用次数",
unlimitedUses: "填写 0 表示不限次数。",
createInvite: "创建邀请链接",
inviteCreated: "邀请链接已创建",
inviteSecurity: "请立即复制并分享链接。出于安全原因,页面不会再次显示完整令牌。",
copyLink: "复制链接",
copiedLink: "邀请链接已复制。",
defaultChannel: "默认频道",
revoke: "撤销",
inviteRevoked: "邀请链接已撤销。",
confirmRevoke: "确定撤销这个邀请链接吗?",
active: "有效",
expired: "已过期",
exhausted: "已用尽",
revoked: "已撤销",
diagnostics: "诊断信息",
diagnosticsLead: "用于反馈问题的运行时摘要;导出的报告会自动脱敏。",
runtime: "运行时",
platform: "平台",
databaseSchema: "数据库版本",
createdSessions: "累计会话",
downloadReport: "下载诊断报告",
exportBackup: "导出数据库备份",
logViewer: "运行日志",
logViewerLead: "最近的网关日志,不包含聊天内容。",
logsUnavailable: "未配置日志文件",
noLogs: "暂无可查看日志。",
operationFailed: "运维操作失败,请稍后重试。",
updateNotice: "当前运行版本为 {{version}}。如需升级,请先导出备份,再按部署文档替换应用版本。",
version: "版本",
audit: "审计记录",
auditLead: "管理员和系统操作记录,不包含聊天内容或敏感值。",
auditEmpty: "暂无审计记录。",
},
en: {
loading: "Loading the admin console…",
adminConsole: "Admin Console",
changePasswordTitle: "Change the default password",
changePasswordLead: "The default password is for first sign-in only. Set a new admin password with at least 12 characters.",
savePassword: "Save new password",
defaultCredentialNotice: "Default account: admin. Default password: admin. The old password expires immediately after you save.",
adminUsername: "Admin username",
newPassword: "New admin password",
passwordPlaceholder: "At least 12 characters",
passwordHint: "Use a long, unique password.",
confirmPassword: "Confirm admin password",
languageSwitch: "中文",
themeSystem: "System theme",
themeLight: "Light theme",
themeDark: "Dark theme",
switchToLightTheme: "Switch to light theme",
switchToDarkTheme: "Switch to dark theme",
welcomeAdmin: "Welcome back",
loginLead: "Enter the admin account and password to manage this WebSpeak instance.",
adminPassword: "Admin password",
login: "Sign in",
backHome: "Back to home",
overview: "Overview",
server: "Server",
operations: "Operations",
openGuest: "Open guest page",
logout: "Log out",
gatewayRunning: "Gateway running",
serverSettings: "Server settings",
serverSettingsLead: "Manage the default TeamSpeak target, access policy, and guest-facing content.",
saving: "Saving…",
saveChanges: "Save changes",
teamSpeakTarget: "Default TeamSpeak target",
serverAddress: "TeamSpeak server address",
serverPlaceholder: "e.g. ts.example.com or 127.0.0.1",
serverPort: "Voice port",
serverPortPlaceholder: "9987",
serverHint: "Enter the server address and voice port separately. IPv6 addresses do not need brackets.",
serverPassword: "Server password",
optional: "Optional",
optionalPassword: "Leave blank when unused",
passwordConfigured: "Password configured (leave blank to keep it)",
change: "Change",
remove: "Remove",
testConnection: "Test connection",
testing: "Testing…",
connectionReady: "Connection ready",
connectionFailed: "Connection failed",
accessAndIdentity: "Access and site identity",
advancedSettings: "Advanced settings",
advancedSettingsLead: "Adjust gateway transport options only when needed.",
webrtcSettings: "WebRTC audio",
webrtcLead: "Low-latency voice is provided by this WebSpeak gateway; no extra server is required.",
webrtcEnabled: "Enable WebRTC",
webrtcEnabledLead: "Use realtime audio when supported; browsers and networks fall back automatically.",
webrtcPortRange: "WebRTC UDP port range",
webrtcPortRangeLead: "Allow the complete range through the host firewall and security group.",
webrtcPortStart: "Start port",
webrtcPortEnd: "End port",
webrtcApplyHint: "The range can only be edited while WebRTC is off. It is locked while enabled and applies to new connections after saving.",
webrtcPortNoticeTitle: "Allow WebRTC ports first",
webrtcPortNotice: "Ports must be opened: {{range}} (UDP). Allow this range in the host firewall, security group, and Docker port mapping first.",
accessMode: "Guest access mode",
fixedMode: "Only this TeamSpeak server",
fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.",
openMode: "Allow other TeamSpeak servers",
openModeLead: "Guests may enter public TeamSpeak addresses; private and reserved networks are blocked.",
siteName: "Site display name",
welcomeText: "Welcome text",
runtimeFacts: "Runtime facts",
lastTest: "Last test",
latency: "Latency",
internalPort: "Internal port",
unknown: "Unknown",
legacyImported: "Legacy config.json was imported. WebSpeak is now managed here and the old file is no longer a live configuration source.",
gotIt: "Got it",
systemStatus: "SYSTEM STATUS",
everythingRunning: "WebSpeak is running",
overviewLead: "The management service is available. TeamSpeak reachability reflects the latest connection test.",
running: "Running",
gateway: "Gateway",
activeSessions: "Active sessions",
peakSessions: "Peak this run: {{count}}",
targetHealth: "Target health",
targetHealthLead: "Result of the latest short-lived connection test.",
manage: "Manage",
status: "Status",
recentEvents: "Recent events",
recentEventsLead: "Only system and admin events are recorded; chat content is excluded.",
noRecentEvents: "No recent events",
reachable: "Reachable",
unreachable: "Unreachable",
notTested: "Not tested",
setupPasswordsMismatch: "The two passwords do not match.",
setupPasswordShort: "The admin password must be at least 12 characters.",
invalidPassword: "The admin password is incorrect.",
rateLimited: "Too many attempts. Try again later.",
requestFailed: "The request failed. Check the fields and try again.",
loginEvent: "Administrator signed in",
logoutEvent: "Administrator signed out",
settingsEvent: "Server settings changed",
initializedEvent: "Default administrator account created",
importedEvent: "Legacy configuration imported",
testEvent: "Connection test completed",
operationsLead: "Handle routine maintenance and troubleshooting without shell access.",
refresh: "Refresh",
sessions: "Active sessions",
sessionsLead: "Inspect browser connections and safely terminate an individual session when needed.",
sessionEmpty: "There are no active sessions.",
nickname: "Nickname",
sessionState: "State",
age: "Age",
memberCount: "Members",
endSession: "Terminate",
terminating: "Terminating…",
sessionTerminated: "Session terminated.",
confirmTerminate: "Terminate “{{nickname}}”?",
invites: "Managed invites",
invitesLead: "Create expiring, usage-limited invite links without putting the server password in the URL.",
inviteChannel: "Target channel",
inviteChannelPlaceholder: "Leave blank for the default channel",
expiresIn: "Expires in (hours)",
maxUses: "Maximum uses",
unlimitedUses: "Use 0 for unlimited uses.",
createInvite: "Create invite link",
inviteCreated: "Invite link created",
inviteSecurity: "Copy and share it now. For security, the full token will not be shown again.",
copyLink: "Copy link",
copiedLink: "Invite link copied.",
defaultChannel: "Default channel",
revoke: "Revoke",
inviteRevoked: "Invite link revoked.",
confirmRevoke: "Revoke this invite link?",
active: "Active",
expired: "Expired",
exhausted: "Exhausted",
revoked: "Revoked",
diagnostics: "Diagnostics",
diagnosticsLead: "Runtime facts for troubleshooting; downloaded reports are sanitized.",
runtime: "Runtime",
platform: "Platform",
databaseSchema: "Database schema",
createdSessions: "Sessions created",
downloadReport: "Download diagnostic report",
exportBackup: "Export database backup",
logViewer: "Runtime logs",
logViewerLead: "Recent gateway logs; chat content is not recorded.",
logsUnavailable: "Log file unavailable",
noLogs: "No logs are available.",
operationFailed: "The operation failed. Try again later.",
updateNotice: "Running version {{version}}. Export a backup before upgrading, then replace the application version using the deployment guide.",
version: "Version",
audit: "Audit trail",
auditLead: "Administrator and system actions; chat content and secrets are excluded.",
auditEmpty: "No audit events.",
},
} as const;
function tr(key: keyof typeof copy.zh, vars: Record<string, string | number> = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; }
const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0))));
const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : route.path === "/admin/operations" ? tr('operations') : tr('overview'));
const testResultText = computed(() => { if (!testResult.value) return ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].filter(Boolean).join(" · "); });
const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested'));
const webrtcPortRangeText = computed(() => `${serverForm.webRtcUdpStart}–${serverForm.webRtcUdpEnd}`);
onMounted(loadAdminView);
watch(() => [serverForm.address, serverForm.port, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; });
watch(() => route.path, () => { if (screen.value === "admin" && route.path === "/admin/operations") void loadOperations(); });
async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); if (route.path === "/admin/operations") await loadOperations(); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } }
async function login() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/login", "POST", { username: loginUsername.value, password: loginPassword.value }, false); csrfToken.value = String(result.csrfToken || ""); loginPassword.value = ""; if (result.mustChangePassword) { screen.value = "change-password"; await router.replace("/admin/change-password"); } else { screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } }
async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); }
async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: value.webRtcEnabled === true, webRtcUdpStart: Number(value.webRtcUdpStart || 40000), webRtcUdpEnd: Number(value.webRtcUdpEnd || 40099) }); }
async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } }
async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } }
async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('confirmRevoke'))) return; try { await sendJson(`/api/admin/invites/${encodeURIComponent(invite.id)}/revoke`, "POST", {}); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } }
function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); }
async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } }
async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: result.settings.webRtcEnabled === true, webRtcUdpStart: Number(result.settings.webRtcUdpStart || 40000), webRtcUdpEnd: Number(result.settings.webRtcUdpEnd || 40099) }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } }
function handleWebRtcToggle() { if (serverForm.webRtcEnabled) webrtcPortNoticeOpen.value = true; }
async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } }
function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, webRtcEnabled: serverForm.webRtcEnabled, webRtcUdpStart: serverForm.webRtcUdpStart, webRtcUdpEnd: serverForm.webRtcUdpEnd }; }
async function runTest(url: string, body: Record<string, unknown>) { testing.value = true; errorMessage.value = ""; testResult.value = null; try { testResult.value = await sendJson(url, "POST", body, url.includes("/server/test")); } catch (error) { testResult.value = { ok: false, code: (error as ApiError).code }; } finally { testing.value = false; } }
async function dismissLegacyNotice() { await sendJson("/api/admin/legacy-import/dismiss", "POST", {}); overview.legacyConfigImported = false; }
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
function cycleTheme() { themeMode.value = nextTheme(themeMode.value); saveTheme(themeMode.value); }
function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; }
function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return language.value === "zh" ? `已运行 ${hours} 小时 ${minutes} 分钟` : `Up ${hours}h ${minutes}m`; }
function formatAge(seconds: number) { if (seconds < 60) return language.value === "zh" ? `${seconds} 秒` : `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return language.value === "zh" ? `${minutes} 分钟` : `${minutes}m`; const hours = Math.floor(minutes / 60); return language.value === "zh" ? `${hours} 小时 ${minutes % 60} 分钟` : `${hours}h ${minutes % 60}m`; }
function sessionStateLabel(state: string) { const names: Record<string, { zh: string; en: string }> = { connecting: { zh: "连接中", en: "Connecting" }, authenticating: { zh: "认证中", en: "Authenticating" }, syncing: { zh: "同步中", en: "Syncing" }, connected: { zh: "已连接", en: "Connected" }, interrupted: { zh: "已中断", en: "Interrupted" }, reconnecting: { zh: "重连中", en: "Reconnecting" }, disconnecting: { zh: "断开中", en: "Disconnecting" }, failed: { zh: "失败", en: "Failed" }, idle: { zh: "空闲", en: "Idle" } }; return names[state]?.[language.value] ?? state; }
function inviteStatusLabel(status: ManagedInvite["status"]) { const names: Record<ManagedInvite["status"], keyof typeof copy.zh> = { active: "active", expired: "expired", exhausted: "exhausted", revoked: "revoked" }; return tr(names[status]); }
function formatContext(context: Record<string, string | number | boolean>) { return Object.entries(context).map(([key, value]) => `${key}=${value}`).join(" · "); }
function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : "Connection test failed"; const names: Record<string, keyof typeof copy.zh> = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); }
function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); if (code === "INVALID_WEBRTC_PORT_RANGE") return language.value === "zh" ? "WebRTC UDP 端口范围无效,请填写 1024–65535 且起始端口不能大于结束端口。" : "The WebRTC UDP port range is invalid. Use 1024–65535 with the start no greater than the end."; if (code === "WEBRTC_PORT_LOCKED") return language.value === "zh" ? "WebRTC 已开启,请先关闭并保存后再修改端口范围。" : "WebRTC is enabled. Turn it off and save before changing the port range."; const probe: Record<string, { zh: string; en: string }> = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); }
interface ApiError extends Error { code?: string }
async function getJson(url: string): Promise<any> { const response = await fetch(url, { headers: { accept: "application/json" } }); return parseResponse(response); }
async function sendJson(url: string, method: string, body: unknown, authenticated = true): Promise<any> { const response = await fetch(url, { method, headers: { "content-type": "application/json", accept: "application/json", ...(authenticated && csrfToken.value ? { "x-csrf-token": csrfToken.value } : {}) }, body: JSON.stringify(body) }); return parseResponse(response); }
async function parseResponse(response: Response) { const value = await response.json().catch(() => ({})); if (!response.ok) { const error = new Error(String(value.code || response.statusText)) as ApiError; error.code = String(value.code || "REQUEST_FAILED"); if (response.status === 401 && screen.value === "admin") { screen.value = "login"; void router.replace("/admin/login"); } throw error; } return value; }
</script>
<style scoped>
.intro-copy h1{font-size:clamp(38px,4.2vw,56px)!important;line-height:1.05!important;letter-spacing:-.055em!important}
.admin-topbar .theme-toggle{display:inline-flex;align-items:center;gap:6px}
:global(*){box-sizing:border-box}:global(body){margin:0;font-family:Inter,"Segoe UI","PingFang SC",sans-serif;color:#20302c;background:#f4f8f6}.admin-root{min-height:100dvh}.auth-layout{display:grid;min-height:100dvh;grid-template-columns:minmax(360px,.82fr) minmax(520px,1.18fr)}.auth-intro{display:flex;flex-direction:column;padding:48px clamp(38px,6vw,92px);color:#e8fffa;background:radial-gradient(circle at 20% 0,rgba(90,211,191,.28),transparent 32rem),#063f3b}.admin-brand{display:flex;align-items:center;gap:12px}.admin-brand>span{display:grid;place-items:center;width:42px;height:42px;color:#fff;background:#07877d;border-radius:12px;box-shadow:0 8px 22px rgba(0,0,0,.15)}.admin-brand strong,.admin-brand small{display:block}.admin-brand strong{font-size:20px;letter-spacing:-.04em}.admin-brand small{margin-top:3px;color:#9bc9c2;font-size:11px}.intro-copy{margin:auto 0 48px}.intro-copy i{color:#75e3d2;font-size:12px;font-style:normal;font-weight:800;letter-spacing:.12em}.intro-copy h1{max-width:540px;margin:16px 0;font-size:clamp(40px,5vw,66px);line-height:1.03;letter-spacing:-.065em}.intro-copy p{max-width:530px;color:#a9d0ca;font-size:16px;line-height:1.75}.step-list{display:grid;gap:10px}.step-list button{display:flex;align-items:center;gap:13px;width:100%;padding:13px;color:#89bbb4;text-align:left;background:transparent;border:1px solid transparent;border-radius:12px}.step-list button.active{color:#fff;background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.1)}.step-list button.done{color:#8ee4d7}.step-list button>span{display:grid;place-items:center;width:28px;height:28px;flex:none;border:1px solid currentColor;border-radius:50%;font-size:12px;font-weight:800}.step-list strong,.step-list small{display:block}.step-list strong{font-size:13px}.step-list small{margin-top:3px;font-size:10px;opacity:.75}.auth-panel{position:relative;display:grid;place-items:center;padding:80px 40px;background:radial-gradient(circle at 80% 10%,rgba(99,205,188,.15),transparent 25rem),#f5f9f7}.panel-tools{position:absolute;top:28px;right:34px}.panel-tools button,.language-link,.admin-topbar button{color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;padding:8px 12px;font-size:11px;font-weight:700;cursor:pointer}.setup-card,.login-card{width:min(560px,100%);padding:36px;background:#fff;border:1px solid #dfeae6;border-radius:20px;box-shadow:0 20px 55px rgba(27,69,61,.09)}.setup-card header small{color:#07877d;font-size:11px;font-weight:800;letter-spacing:.08em}.setup-card header h2,.login-card h1{margin:10px 0 7px;font-size:29px;letter-spacing:-.045em}.setup-card header p,.login-card header p{margin:0;color:#71817c;font-size:13px;line-height:1.6}.form-stack,.login-card form{display:grid;gap:17px;margin-top:27px}label>span,fieldset legend{display:block;margin-bottom:7px;color:#40514c;font-size:12px;font-weight:700}label em{color:#91a09c;font-size:10px;font-style:normal;font-weight:500}label small{display:block;margin-top:6px;color:#899792;font-size:10px;line-height:1.5}input,textarea{width:100%;padding:11px 12px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:13px;outline:none}input{height:43px}input:focus,textarea:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}textarea{resize:vertical}.strength{height:4px;overflow:hidden;background:#e7eeeb;border-radius:4px}.strength i{display:block;height:100%;background:linear-gradient(90deg,#e7a452,#50c5a2);transition:.2s}fieldset{display:grid;gap:9px;margin:0;padding:0;border:0}.choice{display:flex;align-items:flex-start;gap:10px;padding:13px;border:1px solid #dfe9e6;border-radius:10px;cursor:pointer}.choice:has(input:checked){border-color:#62bfb5;background:#eff8f6}.choice input{width:16px;height:16px;flex:none;margin:2px 0}.choice strong,.choice small{display:block}.choice strong{font-size:12px}.choice small{margin-top:4px;color:#7b8985;font-size:10px;line-height:1.45}.setup-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:28px;padding-top:20px;border-top:1px solid #edf1ef}.primary-button,.secondary-button,.text-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:42px;padding:0 18px;border:0;border-radius:9px;font-size:12px;font-weight:800;cursor:pointer}.primary-button{color:#fff;background:#087d74}.primary-button:hover{background:#056b63}.primary-button:disabled,.secondary-button:disabled{opacity:.55;cursor:not-allowed}.secondary-button{color:#08776e;background:#eaf6f3;border:1px solid #cfe9e3}.text-button{color:#687a74;background:transparent}.wide{width:100%}.spinner{display:inline-block;width:22px;height:22px;border:2px solid #cde6df;border-top-color:#087d74;border-radius:50%;animation:spin .7s linear infinite}.spinner.small{width:15px;height:15px;border-color:rgba(255,255,255,.35);border-top-color:currentColor}@keyframes spin{to{transform:rotate(360deg)}}.alert{padding:12px 14px;border-radius:9px;font-size:12px;linLine truncated
@media(max-width:850px){.auth-layout{display:block}.auth-intro{min-height:auto;padding:28px 24px}.intro-copy{margin:55px 0 35px}.step-list{display:none}.auth-panel{padding:35px 18px 60px}.panel-tools{top:18px;right:18px}.admin-shell{display:block}.admin-sidebar{position:static;width:100%;height:auto;flex-direction:row;align-items:center;padding:12px 16px}.admin-sidebar .admin-brand{padding:0}.admin-sidebar .admin-brand small{display:none}.admin-sidebar nav{display:flex;margin-left:auto}.admin-sidebar nav a{font-size:0}.admin-sidebar nav a .ui-icon{width:20px;height:20px}.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}.sidebar-bottom a{display:none}.sidebar-bottom button{font-size:0}.settings-grid,.overview-columns{grid-template-columns:1fr}.readonly-card dl{grid-template-columns:1fr 1fr}.admin-topbar{padding:0 18px}.page-content{width:min(100% - 28px,700px);padding-top:24px}.metric-grid{grid-template-columns:1fr}.hero-status{align-items:flex-start;gap:20px}.hero-status p{max-width:75%}}
@media(max-width:520px){.setup-card,.login-card{padding:25px 20px;border-radius:15px}.setup-card header h2{font-size:24px}.admin-topbar>div:last-child{font-size:0}.page-heading{gap:15px}.page-heading .primary-button{padding-inline:12px}.settings-card,.readonly-card,.overview-card{padding:18px}.readonly-card dl,.overview-card dl{grid-template-columns:1fr}.password-row{grid-template-columns:1fr}.password-actions{padding:0}.hero-status{padding:23px}.status-badge{display:none}}
.security-note{margin:18px 0 0;color:#879590;font-size:11px;line-height:1.5}
:global(:root[data-theme="dark"]) .admin-root, :global(:root[data-theme="dark"]) .login-page, :global(:root[data-theme="dark"]) .auth-panel { color: #e8f3f0; background: #101918; }
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .setup-card, :global(:root[data-theme="dark"]) .login-card, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card, :global(:root[data-theme="dark"]) input, :global(:root[data-theme="dark"]) textarea { color: #e8f3f0; background: #172321; border-color: #30413d; }
:global(:root[data-theme="dark"]) .admin-topbar, :global(:root[data-theme="dark"]) .settings-card, :global(:root[data-theme="dark"]) .readonly-card, :global(:root[data-theme="dark"]) .overview-card { border-color: #30413d; }
:global(:root[data-theme="dark"]) .admin-topbar h1, :global(:root[data-theme="dark"]) .page-heading h2, :global(:root[data-theme="dark"]) .settings-card h3, :global(:root[data-theme="dark"]) .readonly-card h3, :global(:root[data-theme="dark"]) .overview-card h3, :global(:root[data-theme="dark"]) .login-card h1 { color: #e8f3f0; }
:global(:root[data-theme="dark"]) .page-heading p, :global(:root[data-theme="dark"]) .admin-topbar small, :global(:root[data-theme="dark"]) label > span, :global(:root[data-theme="dark"]) .page-heading p { color: #9bb0aa; }
:global(:root[data-theme="dark"]) .metric-grid article, :global(:root[data-theme="dark"]) .readonly-card dl div, :global(:root[data-theme="dark"]) .overview-card dl div, :global(:root[data-theme="dark"]) .event-list li { background: #202f2c; border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .admin-root, :global(:root[data-theme="system"]) .login-page, :global(:root[data-theme="system"]) .auth-panel { color: #e8f3f0; background: #101918; } :global(:root[data-theme="system"]) .admin-topbar, :global(:root[data-theme="system"]) .setup-card, :global(:root[data-theme="system"]) .login-card, :global(:root[data-theme="system"]) .settings-card, :global(:root[data-theme="system"]) .readonly-card, :global(:root[data-theme="system"]) .overview-card { background: #172321; border-color: #30413d; } }
.operations-grid{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(340px,.88fr);gap:18px}.system-notice{display:flex;align-items:center;gap:8px;margin-bottom:18px}.operation-card{min-width:0;padding:22px;background:#fff;border:1px solid #dfe8e5;border-radius:14px}.operation-card header{display:flex;align-items:flex-start;justify-content:space-between;gap:15px}.operation-card h3{margin:0;font-size:15px}.operation-card header p{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.operation-card header>strong{color:#087d74;font-size:22px}.table-wrap{margin:18px -22px -22px;overflow:auto;border-top:1px solid #edf1ef}.table-wrap table{width:100%;min-width:600px;border-collapse:collapse;text-align:left}.table-wrap th,.table-wrap td{padding:12px 14px;border-bottom:1px solid #edf1ef;font-size:11px;white-space:nowrap}.table-wrap th{color:#83928d;font-size:10px;font-weight:700}.table-wrap td strong,.table-wrap td small{display:block}.table-wrap td small{margin-top:3px;color:#8a9994;font-size:9px}.state-pill{display:inline-flex;padding:4px 7px;color:#236c63;background:#e5f5f1;border-radius:99px;font-size:10px;font-weight:700}.state-pill.expired,.state-pill.exhausted,.state-pill.revoked{color:#8b6259;background:#f8ece9}.danger-button,.text-danger{color:#a34f48;background:#fff0ee;border:1px solid #f1d2cd;border-radius:7px;font-size:10px;font-weight:700;cursor:pointer}.danger-button{padding:7px 9px}.text-danger{padding:4px 7px;border:0}.danger-button:disabled{opacity:.55;cursor:wait}.operation-empty{display:grid;place-items:center;gap:8px;min-height:130px;color:#8b9994;text-align:center;font-size:11px}.operation-empty .ui-icon{color:#72afa7}.invite-form{display:grid;gap:14px;margin-top:18px}.invite-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}.field-help{margin-top:-8px;color:#899792;font-size:10px}.generated-invite{display:grid;gap:8px;margin-top:17px;padding:12px;color:#29685f;background:#eaf7f3;border-radius:9px}.generated-invite strong{font-size:11px}.generated-invite small{color:#648780;font-size:9px;line-height:1.45}.generated-link{display:flex;gap:6px}.generated-link input{height:36px;min-width:0;padding:8px;font-size:10px}.generated-link .secondary-button{min-height:36px;padding-inline:9px;white-space:nowrap;font-size:10px}.invite-list{display:grid;gap:9px;margin-top:18px;padding-top:15px;border-top:1px solid #edf1ef}.invite-row{display:flex;align-items:center;justify-content:space-between;gap:9px;padding:10px;background:#f6f9f8;border-radius:9px}.invite-row>div:first-child{min-width:0}.invite-row strong,.invite-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.invite-row strong{font-size:11px}.invite-row small{max-width:260px;margin-top:4px;color:#86958f;font-size:9px}.invite-row-meta{display:flex;align-items:center;gap:7px;flex:none;color:#70827b;font-size:9px}.lower-operations{margin-top:18px}.text-link{color:#087d74;font-size:10px;font-weight:700;text-decoration:none;white-space:nowrap}.diagnostic-list{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin:18px 0}.diagnostic-list div{padding:10px;background:#f6f9f8;border-radius:8px}.diagnostic-list dt{color:#8a9893;font-size:9px}.diagnostic-list dd{margin:4px 0 0;overflow:hidden;font-size:11px;font-weight:700;text-overflow:ellipsis;white-space:nowrap}.logs-card{display:flex;min-height:250px;flex-direction:column}.audit-card{min-height:250px}.muted-label{color:#9aa6a2;font-size:9px}.log-list{display:grid;gap:7px;max-height:280px;margin-top:16px;overflow:auto}.log-row{display:flex;align-items:flex-start;gap:8px;padding:8px;background:#f6f9f8;border-radius:7px}.log-row>div{min-width:0}.log-row strong,.log-row small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.log-row strong{font-size:10px}.log-row small{margin-top:4px;color:#899792;font-size:8px}.log-level{flex:none;padding:3px 5px;border-radius:4px;color:#356c62;background:#e3f3ef;font-size:8px;font-weight:800}.log-level.warn{color:#8b6a3e;background:#fbf1dc}.log-level.error,.log-level.fatal{color:#a34f48;background:#fff0ee}
:global(:root[data-theme="dark"]) .operation-card,:global(:root[data-theme="dark"]) .invite-row,:global(:root[data-theme="dark"]) .diagnostic-list div,:global(:root[data-theme="dark"]) .log-row{color:#e8f3f0;background:#202f2c;border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap{border-color:#30413d}:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td,:global(:root[data-theme="dark"]) .invite-list{border-color:#30413d}:global(:root[data-theme="dark"]) .operation-card header p,:global(:root[data-theme="dark"]) .table-wrap th,:global(:root[data-theme="dark"]) .table-wrap td small,:global(:root[data-theme="dark"]) .invite-row small{color:#9bb0aa}
@media(max-width:850px){.operations-grid{grid-template-columns:1fr}.operation-wide{overflow:hidden}}
@media(max-width:520px){.operation-card{padding:18px}.table-wrap{margin-left:-18px;margin-right:-18px;margin-bottom:-18px}.invite-form-grid,.diagnostic-list{grid-template-columns:1fr}.generated-link{display:grid}.invite-row{align-items:flex-start;flex-direction:column}.invite-row-meta{width:100%;justify-content:flex-end}.lower-operations{margin-top:14px}}
.target-fields{display:grid;grid-template-columns:minmax(0,1fr) 132px;gap:12px}
.webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px}
@media(max-width:520px){.target-fields{grid-template-columns:1fr}}
/* Keep administration inside the browser viewport. Long data sets scroll in
their own cards instead of pushing the whole page below the fold. */
.admin-shell{height:100dvh;min-height:100dvh;overflow:hidden}
.admin-main{min-height:0;display:flex;flex-direction:column;overflow:hidden}
.admin-topbar{flex:0 0 auto}
.page-content{flex:1 1 auto;min-height:0;overflow-y:auto}
.operations-page{display:flex;flex-direction:column;width:min(1400px,calc(100% - 48px));height:calc(100dvh - 82px);overflow:hidden;padding-top:28px;padding-bottom:18px}
.operations-page .page-heading{flex:0 0 auto;margin-bottom:16px}
.operations-page .system-notice{flex:0 0 auto;margin-bottom:12px}
.operations-page .operations-grid{min-width:0;min-height:0}
.operations-primary{flex:0 0 auto;grid-template-columns:minmax(0,1.2fr) minmax(360px,.8fr)}
.operations-primary>.operation-card{min-height:0;overflow:hidden}
.operations-primary .table-wrap{max-height:190px}
.operations-primary .invite-list{max-height:132px;overflow-y:auto}
.lower-operations{flex:1 1 0;grid-template-columns:minmax(210px,.9fr) minmax(0,1.1fr) minmax(210px,.9fr);margin-top:14px}
.lower-operations>.operation-card{min-height:0}
.diagnostics-card,.logs-card,.audit-card{overflow:hidden}
.diagnostics-card{display:flex;flex-direction:column;overflow-y:auto}
.diagnostics-card .secondary-button{margin-top:auto}
.logs-card,.audit-card{display:flex;flex-direction:column}
.logs-card .log-list,.audit-card .event-list{flex:1 1 0;min-height:0;max-height:none;overflow-y:auto}
@media(max-width:850px){
.admin-main{height:100%}
.operations-page{width:min(100% - 28px,700px);height:auto;min-height:calc(100dvh - 82px);overflow:visible}
.operations-page .lower-operations{flex:none}
}
/* Keep every admin surface inside the viewport. The page content and data
lists are the scroll containers, never the document body. */
:global(html),:global(body),:global(#app){width:100%;height:100dvh;min-height:0;max-height:100dvh;overflow:hidden}
.admin-root{height:100dvh;min-height:0;overflow:hidden}
.login-page{height:100dvh;min-height:0;overflow:hidden}
.login-card{max-height:calc(100dvh - 50px);overflow-y:auto}
@media(max-width:850px){
.admin-shell{display:flex;flex-direction:column}
.admin-main{height:auto;flex:1 1 auto}
}
/* Keep static admin cards at their own height. Only long data collections
become scroll surfaces, so a busy event feed cannot stretch its neighbour
or turn the whole admin view into a second page. */
.admin-main>.page-alert{flex:0 0 auto}
.page-content{display:flex;flex:1 1 auto;min-height:0;flex-direction:column;overflow:hidden}
.overview-page{padding:28px 0 18px}
.overview-page .import-notice{flex:0 0 auto;margin-top:0;margin-bottom:12px}
.overview-page .hero-status{flex:0 0 auto;padding:24px}
.overview-page .metric-grid{flex:0 0 auto;gap:12px;margin:14px 0}
.overview-page .metric-grid article{padding:18px}
.overview-page .overview-columns{flex:1 1 0;min-height:0;align-items:stretch;gap:14px}
.target-health-card{align-self:start}
.recent-events-card{display:flex;height:100%;min-height:0;flex-direction:column;overflow:hidden}
.recent-events-card .event-list{flex:1 1 auto;min-height:0;max-height:none;overflow-y:auto}
.server-page{padding:28px 0 18px}
.server-page .page-heading{flex:0 0 auto;margin-bottom:14px}
.server-page .settings-grid{flex:1 1 auto;min-height:0;align-items:stretch;gap:14px}
.server-page .settings-card{min-height:0;overflow-y:auto;padding:20px}
.server-page .readonly-card{flex:0 0 auto;margin-top:14px;padding:16px 20px}
.server-page .readonly-card dl{gap:10px;margin-top:12px}
.operations-page{height:auto;min-height:0}
.operations-primary{flex:0 0 250px}
.operations-primary>.operation-card{overflow-y:auto}
.operations-primary>.operation-card{padding:14px 16px}
.operations-primary .operation-card header p{line-height:1.3}
.operations-primary .invite-form{gap:6px;margin-top:8px}
.operations-primary label>span{margin-bottom:4px}
.operations-primary input{height:34px;padding:7px 10px}
.operations-primary .field-help{margin-top:-4px}
.operations-primary .primary-button{min-height:34px}
/* Theme all native scrollbars used by the admin surfaces. */
:global(*){scrollbar-color:#8fcfc7 transparent;scrollbar-width:thin}
:global(*::-webkit-scrollbar){width:8px;height:8px}
:global(*::-webkit-scrollbar-track){background:transparent}
:global(*::-webkit-scrollbar-thumb){background:#a7d9d2;background-clip:padding-box;border:2px solid transparent;border-radius:999px}
:global(*::-webkit-scrollbar-thumb:hover){background:#6bbab1;background-clip:padding-box;border-width:1px}
:global(:root[data-theme="dark"] *){scrollbar-color:#438f88 transparent}
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb){background:#438f88;border-color:transparent}
:global(:root[data-theme="dark"] *::-webkit-scrollbar-thumb:hover){background:#69c7bc}
@media(max-width:850px){
.page-content{width:min(100% - 28px,700px);padding-top:20px;padding-bottom:14px}
.overview-page .hero-status{padding:18px}
.overview-page .hero-status h2{font-size:24px}
.overview-page .metric-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:7px;margin:10px 0}
.overview-page .metric-grid article{padding:12px}
.overview-page .metric-grid article>span{top:10px;right:10px;width:28px;height:28px}
.overview-page .metric-grid strong{margin-top:9px;font-size:15px}
.overview-page .overview-columns{grid-template-rows:minmax(0,1fr) minmax(0,1fr);overflow:hidden}
.overview-page .target-health-card{align-self:stretch;min-height:0;overflow-y:auto}
.overview-page .recent-events-card{height:100%}
.server-page .settings-grid{grid-template-columns:1fr;grid-auto-rows:minmax(190px,1fr);overflow-y:auto}
.server-page .readonly-card dl{grid-template-columns:repeat(2,minmax(0,1fr))}
.operations-page{height:100%;overflow:hidden}
.operations-page .operations-primary,.operations-page .lower-operations{grid-template-columns:1fr;min-height:0;overflow-y:auto;align-content:start}
.operations-page .operations-primary{grid-auto-rows:240px}
.operations-page .lower-operations{grid-auto-rows:190px}
.operations-page .lower-operations{flex:1 1 0}
}
.advanced-card{grid-column:1 / -1}
.advanced-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}
.advanced-card .toggle-choice{margin:0}
.webrtc-port-fields{display:grid;gap:10px;padding:14px;background:#f6f9f8;border:1px solid #e4efeb;border-radius:10px}
.port-fields-heading strong,.port-fields-heading small{display:block}
.port-fields-heading strong{font-size:11px}
.port-fields-heading small{margin-top:4px;color:#899792;font-size:10px;line-height:1.45}
.port-inputs{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.port-inputs label>span{font-size:10px}
.port-inputs input:disabled{color:#70817b;background:#e9f1ee;border-color:#d7e5e1;cursor:not-allowed;opacity:1}
.modal-backdrop{position:fixed;z-index:20;inset:0;display:grid;place-items:center;padding:22px;background:rgba(5,41,38,.38);backdrop-filter:blur(3px)}
.modal-card{width:min(410px,100%);padding:26px;background:#fff;border:1px solid #d9e9e4;border-radius:16px;box-shadow:0 20px 60px rgba(14,62,55,.2)}
.modal-icon{display:grid;place-items:center;width:38px;height:38px;color:#087d74;background:#e3f5f0;border-radius:11px}
.modal-card h2{margin:16px 0 8px;font-size:20px}
.modal-card p{margin:0 0 20px;color:#71817c;font-size:12px;line-height:1.7}
:global(:root[data-theme="dark"]) .webrtc-port-fields{background:#202f2c;border-color:#30413d}
:global(:root[data-theme="dark"]) .port-fields-heading small{color:#9bb0aa}
:global(:root[data-theme="dark"]) .port-inputs input:disabled{color:#9bb0aa;background:#263a35;border-color:#3a514b}
:global(:root[data-theme="dark"]) .modal-card{color:#e8f3f0;background:#172321;border-color:#30413d}
:global(:root[data-theme="dark"]) .modal-card p{color:#9bb0aa}
@media(max-width:520px){.advanced-card{grid-column:auto}.port-inputs{grid-template-columns:1fr}}
/* Server settings are a short form, not a set of independent data feeds.
Let each card keep its natural height so a few extra pixels do not create
three nested scrollbars. The section itself is the only fallback scroll
surface when a small viewport cannot show the complete form. */
.server-page{overflow-x:hidden;overflow-y:auto}
.server-page .settings-grid{flex:0 0 auto;min-height:auto;align-items:start;overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{height:auto;min-height:0;overflow:visible;padding:16px;gap:12px}
.server-page .settings-card input{height:40px}
.server-page .settings-card .choice{padding:10px;gap:8px}
.server-page .settings-card .choice small{margin-top:3px}
.server-page .webrtc-port-fields{padding:12px;gap:8px}
.server-page .readonly-card{margin-top:12px;padding:14px 16px}
.server-page .readonly-card dl{gap:8px;margin-top:10px}
@media(max-width:850px){
.server-page .settings-grid{overflow:visible;grid-auto-rows:auto}
.server-page .settings-card{overflow:visible}
}
/* Mobile admin pages should read like one continuous form. Keep the desktop
viewport shell untouched, but let the document grow vertically on narrow
screens instead of trapping content inside cards and nested panes. */
@media(max-width:850px){
:global(html),:global(body),:global(#app){height:auto;min-height:100%;max-height:none;overflow:auto}
.admin-root{height:auto;min-height:100dvh;overflow:visible}
.admin-shell{height:auto;min-height:100dvh;overflow:visible}
.admin-main{height:auto;min-height:0;overflow:visible}
.page-content{display:block;height:auto;min-height:0;overflow:visible}
.login-page{height:auto;min-height:100dvh;overflow:visible}
.login-card{max-height:none;overflow:visible}
.overview-page{height:auto;min-height:0;overflow:visible}
.overview-page .overview-columns{grid-template-rows:auto;overflow:visible}
.overview-page .target-health-card,.overview-page .recent-events-card{height:auto;min-height:0;overflow:visible}
.overview-page .recent-events-card .event-list{max-height:none;overflow:visible}
.server-page{height:auto;min-height:0;overflow:visible}
.server-page .settings-grid{height:auto;overflow:visible}
.operations-page{height:auto;min-height:0;overflow:visible}
.operations-page .operations-primary,.operations-page .lower-operations{height:auto;min-height:0;overflow:visible;grid-auto-rows:auto;flex:none}
.operations-page .operation-card{height:auto;min-height:0;overflow:visible}
.operations-primary .table-wrap{max-height:none;overflow-x:auto;overflow-y:visible}
.operations-primary .invite-list{max-height:none;overflow:visible}
.logs-card .log-list,.audit-card .event-list{max-height:none;overflow:visible;flex:none}
.logs-card .log-list{width:100%;min-width:0}
.logs-card .log-row{min-width:0;max-width:100%;overflow:hidden}
.logs-card .log-row>div{width:0;max-width:100%;flex:1 1 auto;min-width:0;overflow:hidden}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
}
/* Long log messages should wrap on every screen size instead of widening the
log card or introducing page-level horizontal scrolling. */
.logs-card .log-row{min-width:0}
.logs-card .log-row strong,.logs-card .log-row small{overflow-wrap:anywhere;white-space:normal;word-break:break-word}
.login-actions{display:flex;align-items:center;justify-content:center;gap:12px;margin-top:20px;flex-wrap:wrap}
.login-actions .language-link{margin-top:0}
.home-link{display:inline-flex;align-items:center;gap:6px;padding:8px 12px;color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;font-size:11px;font-weight:700;text-decoration:none}
.home-link:hover{background:#d8eee9}
</style>
+94
View File
@@ -0,0 +1,94 @@
<template>
<div class="demo-page">
<header class="demo-header">
<div class="demo-brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><button type="button" @click="toggleLanguage">{{ copy.languageSwitch }}</button><a href="/">{{ copy.back }}</a></div>
</header>
<div v-if="reconnecting" class="demo-reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" @click="reconnecting = false">{{ copy.restore }}</button></div>
<main class="demo-shell">
<aside class="demo-channel-panel">
<div class="demo-panel-title"><span>{{ copy.channels }}</span><strong>{{ selectedChannel.name }}</strong></div>
<div v-for="channel in channels" :key="channel.id" :class="['demo-channel', { active: selectedChannelId === channel.id }]">
<button type="button" @click="selectChannel(channel.id)"><Icon name="volume" :size="16" /><span>{{ channel.name }}</span><small>{{ channel.members.length }}</small></button>
<div class="demo-channel-members"><span v-for="member in channel.members" :key="member.id" :class="{ speaking: speakingId === member.id }"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i>{{ member.name }}</span></div>
</div>
</aside>
<section class="demo-main">
<div class="demo-hero"><div><span class="demo-live"><i></i>{{ copy.simulated }}</span><h1><Icon name="volume" :size="24" /> {{ selectedChannel.name }}</h1><p>{{ copy.heroLead }}</p><small><Icon name="users" :size="14" /> {{ selectedChannel.members.length }} {{ copy.online }}</small></div><div class="demo-wave" aria-hidden="true"><i v-for="bar in bars" :key="bar" :style="{ height: `${bar}px` }"></i></div></div>
<div class="demo-section-heading"><span>{{ copy.voiceActivity }}</span><strong>{{ copy.speakingNow }}</strong></div>
<div class="demo-voice-grid"><article v-for="member in selectedChannel.members" :key="member.id" :class="['demo-voice-card', { speaking: speakingId === member.id }]" @click="speakingId = member.id"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i><strong>{{ member.name }}</strong><span>{{ speakingId === member.id ? copy.speaking : copy.connected }}</span></article></div>
<div class="demo-chat-head"><div><span>{{ copy.textChannel }}</span><strong># {{ selectedChannel.name }} {{ copy.chat }}</strong></div><div class="demo-tabs"><button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: activeTab === tab.id }" @click="activeTab = tab.id">{{ tab.label }}</button></div></div>
<div class="demo-messages"><div v-for="message in visibleMessages" :key="message.id" :class="['demo-message', { mine: message.mine }]" @dblclick="message.mine = !message.mine"><i :style="avatarStyle(message.author)">{{ message.author[0] }}</i><div><small>{{ message.author }} · {{ message.time }}</small><p>{{ messageText(message) }}</p></div></div><div v-if="!visibleMessages.length" class="demo-empty"><Icon name="message" :size="22" /><strong>{{ copy.emptyChat }}</strong></div></div>
<form class="demo-composer" @submit.prevent="sendMessage"><input v-model="draft" :placeholder="copy.placeholder" :aria-label="copy.placeholder" /><button type="submit" :disabled="!draft.trim()"><Icon name="send" :size="17" /></button></form>
</section>
<aside class="demo-actions-panel"><div class="demo-panel-title"><span>{{ copy.voice }}</span><strong>{{ copy.simulationControls }}</strong></div><button type="button" @click="toggleSpeaking"><Icon name="mic" :size="17" /> {{ speakingId ? copy.stopSpeaking : copy.simulateSpeaking }}</button><button type="button" @click="poke = !poke"><Icon name="bell" :size="17" /> {{ copy.poke }}</button><button type="button" @click="reconnecting = true"><Icon name="refresh" :size="17" /> {{ copy.simulateReconnect }}</button><div class="demo-note"><Icon name="shield" :size="16" /><span>{{ copy.demoNote }}</span></div><div class="demo-user"><i :style="avatarStyle('illusia')">I</i><div><strong>illusia</strong><small>{{ copy.you }} · {{ copy.ready }}</small></div><span class="demo-green-dot"></span></div></aside>
</main>
<div v-if="poke" class="demo-poke" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" @click="poke = false"><Icon name="close" :size="14" /></button></div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import Icon from "../components/Icon.vue";
type Language = "zh" | "en";
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; mine: boolean }
type Tab = "channel" | "server";
const language = ref<Language>(localStorage.getItem("webspeak:language") === "en" ? "en" : "zh");
const copy = computed(() => language.value === "zh" ? zh : en);
const selectedChannelId = ref("quiet");
const activeTab = ref<Tab>("channel");
const speakingId = ref("illusia");
const reconnecting = ref(false);
const poke = ref(false);
const draft = ref("");
const bars = [15, 31, 21, 42, 25, 50, 32, 21, 38, 27, 45, 18, 33];
const channels = [
{ id: "quiet", name: "Quiet Zone", members: [{ id: "illusia", name: "illusia" }, { id: "msicbot", name: "msicbot" }] },
{ id: "lounge", name: "Lounge", members: [{ id: "alice", name: "Alice" }] },
{ id: "music", name: "Music room", members: [] },
];
const messages = ref<DemoMessage[]>([
{ id: 1, author: "illusia", time: "10:24", text: "", zhText: "大家好,欢迎来到 WebSpeak。", enText: "Hello everyone, welcome to WebSpeak.", mine: true },
{ id: 2, author: "msicbot", time: "10:25", text: "", zhText: "语音和文字频道都已同步。", enText: "Voice and text channels are in sync.", mine: false },
]);
const zh = { browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
const en = { browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
const tabs = computed(() => [{ id: "channel" as const, label: copy.value.channel }, { id: "server" as const, label: copy.value.server }]);
const selectedChannel = computed(() => channels.find((channel) => channel.id === selectedChannelId.value) ?? channels[0]);
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); }
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : message.enText ?? message.text; }
function sendMessage() { const text = draft.value.trim(); if (!text) return; messages.value.push({ id: Date.now(), author: "illusia", time: "now", text, mine: true }); draft.value = ""; }
function avatarStyle(name: string) { let hash = 0; for (const char of name) hash = char.charCodeAt(0) + ((hash << 5) - hash); const colors = ["#168f83", "#7b9ed0", "#b99070", "#8b78b9"]; return { background: colors[Math.abs(hash) % colors.length] }; }
</script>
<style scoped>
:global(*) { box-sizing: border-box; }
:global(body) { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f7f9f8; color: #1c2b28; }
.demo-page { min-height: 100dvh; padding: 0 28px 38px; background: radial-gradient(circle at 72% 12%, rgba(126, 213, 205, .18), transparent 26rem), #f7f9f8; }
.demo-header { display: flex; align-items: center; justify-content: space-between; width: min(1380px, 100%); min-height: 82px; margin: 0 auto; }
.demo-brand, .demo-tools, .demo-brand > div, .demo-tools { display: flex; align-items: center; }.demo-brand { gap: 10px; }.demo-brand > span { display: grid; place-items: center; width: 39px; height: 39px; color: #fff; background: #006a64; border-radius: 12px; }.demo-brand strong, .demo-brand small { display: block; }.demo-brand strong { color: #006a64; font-size: 18px; }.demo-brand small { margin-top: 2px; color: #84938e; font-size: 10px; }.demo-tools { gap: 15px; color: #68807a; font-size: 12px; }.demo-tools button, .demo-tools a { padding: 7px 10px; color: #006a64; background: #e1f2ee; border: 1px solid #cbe6e0; border-radius: 7px; font-size: 11px; font-weight: 700; text-decoration: none; cursor: pointer; }.demo-badge { color: #2d7d50; font-weight: 700; }
.demo-reconnect { display: flex; align-items: center; gap: 9px; width: min(1380px, 100%); margin: 0 auto 14px; padding: 11px 14px; color: #8b6537; background: #fff8e9; border: 1px solid #efd9aa; border-radius: 10px; }.demo-reconnect span { flex: 1; }.demo-reconnect button { padding: 6px 10px; color: #7d5d35; background: #fff; border: 1px solid #ead0a0; border-radius: 6px; cursor: pointer; }
.demo-shell { display: grid; grid-template-columns: 240px minmax(0, 1fr) 235px; gap: 18px; width: min(1380px, 100%); min-height: 720px; margin: 0 auto; }.demo-channel-panel, .demo-actions-panel, .demo-main { min-width: 0; padding: 20px; border: 1px solid #e0ebe7; border-radius: 16px; background: rgba(255,255,255,.9); box-shadow: 0 12px 30px rgba(26,66,59,.05); }.demo-panel-title { display: grid; gap: 5px; margin-bottom: 20px; }.demo-panel-title span, .demo-section-heading span, .demo-chat-head span { color: #79918c; font-size: 10px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }.demo-panel-title strong { color: #263a35; font-size: 18px; }.demo-channel { margin: 4px -8px 12px; padding: 3px 8px 9px; border-radius: 10px; }.demo-channel.active { background: #e2f3ef; }.demo-channel > button { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 0; color: #45635b; background: transparent; border: 0; text-align: left; cursor: pointer; }.demo-channel.active > button { color: #006a64; font-weight: 800; }.demo-channel button span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.demo-channel button small { color: #84a19a; }.demo-channel-members { display: grid; gap: 7px; padding-left: 22px; color: #7b8e88; font-size: 11px; }.demo-channel-members span { display: flex; align-items: center; gap: 7px; }.demo-channel-members i, .demo-user > i, .demo-voice-card > i, .demo-message > i { display: grid; place-items: center; flex: 0 0 auto; color: #fff; border-radius: 50%; font-style: normal; font-weight: 800; }.demo-channel-members i { width: 20px; height: 20px; font-size: 9px; }.demo-channel-members span.speaking i { box-shadow: 0 0 0 2px #83e88d, 0 0 10px rgba(83,214,105,.45); }
.demo-main { padding: 27px 32px; }.demo-hero { display: flex; align-items: center; justify-content: space-between; min-height: 190px; padding: 26px 29px; overflow: hidden; border-radius: 14px; background: linear-gradient(112deg, #dff3ef, #f6fbfa); }.demo-live { display: inline-flex; align-items: center; gap: 7px; padding: 5px 9px; color: #2d7e48; background: #d4f3d9; border-radius: 999px; font-size: 10px; font-weight: 700; }.demo-live i, .demo-green-dot { width: 7px; height: 7px; background: #58d476; border-radius: 50%; }.demo-hero h1 { display: flex; align-items: center; gap: 8px; margin: 17px 0 7px; color: #18302c; font-size: 28px; letter-spacing: -.05em; }.demo-hero p { margin: 0 0 15px; color: #64817a; font-size: 12px; }.demo-hero small { display: flex; align-items: center; gap: 6px; color: #52716b; font-size: 11px; }.demo-wave { display: flex; align-items: center; gap: 5px; height: 60px; padding-right: 22px; }.demo-wave i { width: 4px; border-radius: 4px; background: #65cabe; }.demo-wave i:nth-child(3n) { background: #8fe990; }.demo-section-heading { display: grid; gap: 5px; margin: 31px 0 15px; }.demo-section-heading strong { color: #1d2c28; font-size: 21px; }.demo-voice-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(125px, 1fr)); gap: 11px; }.demo-voice-card { display: grid; justify-items: center; gap: 7px; padding: 15px 8px; border: 1px solid #edf1ef; border-radius: 12px; background: #fff; cursor: pointer; }.demo-voice-card > i { width: 56px; height: 56px; font-size: 18px; }.demo-voice-card strong { color: #2c3935; font-size: 12px; }.demo-voice-card span { color: #91a09a; font-size: 10px; }.demo-voice-card.speaking { border-color: #83e88d; box-shadow: 0 0 0 2px rgba(131,232,141,.18), 0 8px 20px rgba(68,173,79,.12); }.demo-voice-card.speaking span { color: #2e8b45; }.demo-chat-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; margin-top: 33px; padding-top: 23px; border-top: 1px solid #edf2f0; }.demo-chat-head strong { display: block; margin-top: 6px; color: #1d2c28; font-size: 20px; }.demo-tabs { display: flex; gap: 5px; }.demo-tabs button { padding: 7px 9px; color: #78908a; background: #f0f6f3; border: 0; border-radius: 7px; cursor: pointer; }.demo-tabs button.active { color: #006a64; background: #dff1ed; font-weight: 700; }.demo-messages { display: grid; align-content: start; gap: 13px; min-height: 215px; max-height: 270px; margin-top: 17px; overflow-y: auto; padding: 7px 3px; }.demo-message { display: flex; align-items: flex-start; gap: 9px; max-width: 76%; }.demo-message.mine { justify-self: end; flex-direction: row-reverse; text-align: right; }.demo-message > i { width: 29px; height: 29px; font-size: 10px; }.demo-message small { color: #9ca9a4; font-size: 9px; }.demo-message p { margin: 4px 0 0; padding: 8px 11px; color: #43534e; background: #f1f5f3; border-radius: 4px 11px 11px 11px; font-size: 12px; }.demo-message.mine p { color: #fff; background: #006a64; border-radius: 11px 4px 11px 11px; }.demo-empty { display: grid; place-content: center; justify-items: center; gap: 8px; min-height: 170px; color: #91a29b; }.demo-empty strong { font-size: 12px; }.demo-composer { display: flex; gap: 8px; padding: 7px 8px 7px 12px; background: #f1f6f4; border-radius: 10px; }.demo-composer input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; font-size: 12px; }.demo-composer button { display: grid; place-items: center; width: 34px; height: 34px; color: #fff; background: #006a64; border: 0; border-radius: 8px; cursor: pointer; }.demo-composer button:disabled { opacity: .35; cursor: not-allowed; }
.demo-actions-panel { display: flex; flex-direction: column; gap: 9px; }.demo-actions-panel > button { display: flex; align-items: center; gap: 8px; padding: 10px; color: #4d6a62; background: #f0f6f3; border: 1px solid #e1ece8; border-radius: 8px; text-align: left; cursor: pointer; }.demo-actions-panel > button:hover { color: #006a64; border-color: #b9ddd6; }.demo-note { display: flex; gap: 8px; margin-top: 10px; padding: 11px; color: #68837b; background: #eef8f4; border-radius: 9px; font-size: 10px; line-height: 1.5; }.demo-user { display: flex; align-items: center; gap: 9px; margin-top: auto; padding-top: 15px; border-top: 1px solid #e9efed; }.demo-user > i { width: 35px; height: 35px; font-size: 12px; }.demo-user div { min-width: 0; flex: 1; }.demo-user strong, .demo-user small { display: block; }.demo-user strong { color: #34423d; font-size: 12px; }.demo-user small { margin-top: 4px; color: #8a9a94; font-size: 10px; }.demo-poke { position: fixed; z-index: 10; top: 82px; right: 25px; display: flex; align-items: center; gap: 9px; max-width: min(380px, calc(100% - 32px)); padding: 11px 12px; color: #52645c; background: #fffdf6; border: 1px solid #f0dfbd; border-radius: 9px; box-shadow: 0 8px 22px rgba(88,65,28,.12); font-size: 12px; }.demo-poke span { flex: 1; }.demo-poke strong { color: #8f6532; }.demo-poke button { display: grid; place-items: center; padding: 3px; color: #9b8a6e; background: transparent; border: 0; cursor: pointer; }
@media (max-width: 1080px) { .demo-shell { grid-template-columns: 210px minmax(0, 1fr); }.demo-actions-panel { grid-column: 1 / -1; min-height: 160px; }.demo-actions-panel .demo-panel-title { margin-bottom: 3px; }.demo-actions-panel > button { display: inline-flex; width: fit-content; }.demo-note { margin-top: 4px; }.demo-user { margin-top: 0; } }
@media (max-width: 720px) { .demo-page { padding: 0 14px 24px; }.demo-header { min-height: 68px; }.demo-tools { gap: 6px; font-size: 10px; }.demo-badge { display: none; }.demo-shell { display: block; min-height: 0; }.demo-channel-panel { margin-bottom: 12px; }.demo-channel-panel .demo-channel:not(.active) { display: none; }.demo-actions-panel { margin-top: 12px; }.demo-main { padding: 17px 14px; }.demo-hero { min-height: 170px; padding: 20px; }.demo-wave { padding-right: 0; transform: scale(.75); transform-origin: right center; }.demo-chat-head { display: grid; align-items: start; }.demo-tabs { overflow-x: auto; }.demo-message { max-width: 94%; } }
@media (max-width: 360px) { .demo-tools a { display: none; }.demo-hero h1 { font-size: 23px; }.demo-hero p { font-size: 11px; }.demo-voice-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
:global(:root[data-theme="dark"]) .demo-page { color: #e8f3f0; background: #101918; }
:global(:root[data-theme="dark"]) .demo-channel-panel, :global(:root[data-theme="dark"]) .demo-actions-panel, :global(:root[data-theme="dark"]) .demo-main, :global(:root[data-theme="dark"]) .demo-voice-card { background: #172321; border-color: #30413d; }
:global(:root[data-theme="dark"]) .demo-panel-title strong, :global(:root[data-theme="dark"]) .demo-hero h1, :global(:root[data-theme="dark"]) .demo-section-heading strong, :global(:root[data-theme="dark"]) .demo-chat-head strong, :global(:root[data-theme="dark"]) .demo-voice-card strong, :global(:root[data-theme="dark"]) .demo-user strong { color: #e8f3f0; }
:global(:root[data-theme="dark"]) .demo-hero { background: linear-gradient(112deg, #173e3a, #172321); }
:global(:root[data-theme="dark"]) .demo-message p, :global(:root[data-theme="dark"]) .demo-composer, :global(:root[data-theme="dark"]) .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
:global(:root[data-theme="dark"]) .demo-chat-head, :global(:root[data-theme="dark"]) .demo-user { border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .demo-channel-panel, :global(:root[data-theme="system"]) .demo-actions-panel, :global(:root[data-theme="system"]) .demo-main, :global(:root[data-theme="system"]) .demo-voice-card { background: #172321; border-color: #30413d; } }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
</style>
+1049 -236
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -6,9 +6,9 @@ export default defineConfig({
server: {
port: 5173,
proxy: {
"/api": "http://localhost:3030",
"/api": "http://localhost:3040",
"/ws": {
target: "ws://localhost:3030",
target: "ws://localhost:3040",
ws: true,
},
},