Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69f8d66ca9 | ||
|
|
7789758024 | ||
|
|
c211deeb98 | ||
|
|
aad7833509 | ||
|
|
39413cf840 | ||
|
|
50d9d58ad0 | ||
|
|
0a552f7ee8 | ||
|
|
568b8fd8be | ||
|
|
d919df1273 | ||
|
|
921e83dfb3 | ||
|
|
77fef3bed9 | ||
|
|
2c49ee2599 | ||
|
|
81a860c3df | ||
|
|
d327c6f179 | ||
|
|
7baeff00ba | ||
|
|
777c779d79 | ||
|
|
051cb402e5 | ||
|
|
1791d5946d | ||
|
|
39eba1b121 | ||
|
|
a195681e78 | ||
|
|
172347aaa7 | ||
|
|
8e28bca634 | ||
|
|
4ef7ec5ee3 | ||
|
|
f18fa63001 | ||
|
|
6ed8abfb15 | ||
|
|
8b6c998c43 | ||
|
|
d2caaa8f3c | ||
|
|
83b2430d18 | ||
|
|
a416e36bd1 | ||
|
|
a2f91e606f | ||
|
|
9dfded0fb7 | ||
|
|
15e22d3099 | ||
|
|
db08fbda6b | ||
|
|
c16d1d4cfb | ||
|
|
5855d0ba67 | ||
|
|
f11fe26bfe | ||
|
|
1a46ab83a3 | ||
|
|
878e94a93a | ||
|
|
2047e30984 | ||
|
|
3dfd25dab7 | ||
|
|
c8417edd7d | ||
|
|
49481145ef | ||
|
|
3b5c0dfc7d | ||
|
|
525f512f4a | ||
|
|
0785f82386 | ||
|
|
797fc135a9 | ||
|
|
f0712fa3fc | ||
|
|
e2f0a43762 | ||
|
|
8960189bc7 | ||
|
|
f4cbd61cff | ||
|
|
541a216c4d | ||
|
|
aeaeb15965 | ||
|
|
9e2b9bf564 | ||
|
|
0a4fff6f6f | ||
|
|
e0d5916a86 | ||
|
|
e8dc71329b | ||
|
|
30682cd659 | ||
|
|
e09a19b7b4 | ||
|
|
2b7e908d31 | ||
|
|
0ea85752fd | ||
|
|
97b7127ca3 | ||
|
|
db38feba52 | ||
|
|
1bab4df64e | ||
|
|
193130c50f | ||
|
|
c7794a12e7 | ||
|
|
408d8bcda4 | ||
|
|
5a3eebecbd | ||
|
|
713716dacc | ||
|
|
3a7a162f97 | ||
|
|
2f8614d53a | ||
|
|
bdac15afac | ||
|
|
7f49e2f2d7 | ||
|
|
24f1b9a4b8 | ||
|
|
79b91fca44 | ||
|
|
6a821b760e | ||
|
|
6539479d10 | ||
|
|
8ed3e788be | ||
|
|
de8f6a11c9 | ||
|
|
21d53a30c9 | ||
|
|
22656b2e7d | ||
|
|
3a18bcebbc | ||
|
|
7b35c63a74 | ||
|
|
6b9038da6c | ||
|
|
1dd04bf7ca | ||
|
|
15af861389 | ||
|
|
7ea63c525e | ||
|
|
3d0b8a5c97 | ||
|
|
fb39d82c01 | ||
|
|
ae530963bf | ||
|
|
f8554fc991 | ||
|
|
a3dad55c76 | ||
|
|
0b29742bce | ||
|
|
c2c38fa011 | ||
|
|
578217ba41 | ||
|
|
d75bdccfd9 | ||
|
|
412f560677 | ||
|
|
fdccf86458 | ||
|
|
d43a33aa15 | ||
|
|
056b57bcd1 | ||
|
|
688eb3174e | ||
|
|
c38f67bc3b | ||
|
|
67c7a27af6 | ||
|
|
6d1d2a1f92 | ||
|
|
faff7a2237 | ||
|
|
dc63f4b45b | ||
|
|
380fb67090 | ||
|
|
b71632cc29 | ||
|
|
38f7c94a65 | ||
|
|
d91a145657 | ||
|
|
a2e33ff176 | ||
|
|
010b8ef072 | ||
|
|
883703dd0c | ||
|
|
bcf212738b | ||
|
|
fae21ec086 | ||
|
|
22dcf93925 | ||
|
|
4df59b80d0 | ||
|
|
c49b4ec715 | ||
|
|
1c80791109 | ||
|
|
85f87ecd0b | ||
|
|
3d6752a5e4 | ||
|
|
a0921c35b2 | ||
|
|
ace9e84889 | ||
|
|
4ead174c04 | ||
|
|
f628d19ebf | ||
|
|
75de8f1d2b | ||
|
|
1ba8cd5ee1 | ||
|
|
f639825775 | ||
|
|
0b40a69d74 | ||
|
|
6defbff591 | ||
|
|
b5d167e1e7 | ||
|
|
7f97d54206 | ||
|
|
ef3e65ea0b | ||
|
|
d13b3207a9 | ||
|
|
7e08ee54a5 | ||
|
|
6d8e289b81 | ||
|
|
defbb766e4 | ||
|
|
69043748a1 | ||
|
|
8046985574 | ||
|
|
5ce73d2c84 | ||
|
|
2d1d202981 | ||
|
|
73313f9e2d | ||
|
|
097c72bc5d | ||
|
|
71f219b7ca | ||
|
|
bacc9fe07e | ||
|
|
a9c360fb9c | ||
|
|
04926c8491 | ||
|
|
fa1d1ad01b | ||
|
|
c0fc18c344 | ||
|
|
69d69f0a5a | ||
|
|
6d7976e5d8 | ||
|
|
aef1f68875 | ||
|
|
06e5cc6d8b | ||
|
|
7782e9b327 | ||
|
|
b82c4fe0af | ||
|
|
45584810a2 | ||
|
|
bfefd053a0 | ||
|
|
324213de14 | ||
|
|
a041ba90bb | ||
|
|
0dc623eb69 | ||
|
|
3e6876dbe7 | ||
|
|
a60abffd3b | ||
|
|
2b43952c01 | ||
|
|
12f440ab8b | ||
|
|
7221af78bf | ||
|
|
a88b0616f5 | ||
|
|
ea4d5b2a70 | ||
|
|
a439100ad6 | ||
|
|
620d24f796 | ||
|
|
fc3bbd0c59 | ||
|
|
3b5ce9b446 | ||
|
|
37de6067d0 | ||
|
|
45410fcc7d | ||
|
|
166cb543a1 | ||
|
|
a295ff4b27 | ||
|
|
dcc52c4530 | ||
|
|
dc3ad6a598 | ||
|
|
ef59e51e32 | ||
|
|
9bbc22de25 | ||
|
|
335d93a8b8 | ||
|
|
52ff0560d1 | ||
|
|
a5e5dd6592 | ||
|
|
62e41dbc51 | ||
|
|
d8b2fd9e1b | ||
|
|
8ca3249832 | ||
|
|
92574fddb1 | ||
|
|
596114e6a3 | ||
|
|
2868f7a478 | ||
|
|
63ef6b673d | ||
|
|
5a56e1706f | ||
|
|
986814441d | ||
|
|
0ab6fb6f3f | ||
|
|
a966be4db6 | ||
|
|
556084233d | ||
|
|
c38239ec35 | ||
|
|
21041346e3 | ||
|
|
7320aa3bb5 | ||
|
|
d9b8ea625a | ||
|
|
2323e22fef | ||
|
|
b5f8f01301 | ||
|
|
e964ff460e | ||
|
|
21d8d9c3bc | ||
|
|
169cf88306 | ||
|
|
059435f4cb | ||
|
|
4d4d4cdeb1 | ||
|
|
d42e7a033c | ||
|
|
0986c65551 | ||
|
|
694f864d36 | ||
|
|
512854ab9f | ||
|
|
b298496911 | ||
|
|
b6367e2645 | ||
|
|
b0fa4bf5d0 | ||
|
|
cb3dbe4ca4 | ||
|
|
96ba467d52 | ||
|
|
20fdcc7b1d | ||
|
|
feea39a81c | ||
|
|
69d1653f99 | ||
|
|
a18a5b4920 | ||
|
|
343dd84132 | ||
|
|
a037962cc1 | ||
|
|
680ce246fd | ||
|
|
baa09ad38c | ||
|
|
767bdea018 | ||
|
|
83a8fd0d5a | ||
|
|
e14ddc9465 | ||
|
|
7feb97d77d | ||
|
|
434360cda9 | ||
|
|
d0a2e9edc0 | ||
|
|
61f66ab319 | ||
|
|
e79ad66e1f | ||
|
|
522fa8f409 | ||
|
|
c7def28a8f | ||
|
|
d6c8ccb73f | ||
|
|
ab5851935c | ||
|
|
5c3d1b7e5d | ||
|
|
ecff06e9a1 | ||
|
|
9c3f09b55b | ||
|
|
b42c455e7f | ||
|
|
40ea30b9e2 | ||
|
|
a4cf5b5359 | ||
|
|
1d41d5a3e7 | ||
|
|
46b190a913 | ||
|
|
8abd2d6228 | ||
|
|
7ff6836a7e | ||
|
|
a6187c18af | ||
|
|
8ab2fbe8ea | ||
|
|
3e7674c94f | ||
|
|
30c0d09a33 | ||
|
|
d9904fa154 | ||
|
|
afbbd1e2d4 | ||
|
|
adca8cc1db | ||
|
|
9788e7fa1c | ||
|
|
66da7efe4a | ||
|
|
3fb7000d02 | ||
|
|
03c95abcf7 | ||
|
|
d2ffbee873 | ||
|
|
413dbaf3a8 | ||
|
|
9187d2faed | ||
|
|
af85a73c7d | ||
|
|
b3ace7d7b6 | ||
|
|
49c8aee795 | ||
|
|
cd6dd69d9b | ||
|
|
325c907683 | ||
|
|
41666a5531 | ||
|
|
0732e2df7d | ||
|
|
d7766497e8 | ||
|
|
aa5c5e687f | ||
|
|
8a06382cec | ||
|
|
1fe11850b7 | ||
|
|
a5a8648240 | ||
|
|
81212b420b | ||
|
|
3ec9ab497a | ||
|
|
bf1158aff2 | ||
|
|
a4cbcf536f | ||
|
|
797c5b118a | ||
|
|
6337789afa | ||
|
|
87fcd736be | ||
|
|
f5bd06fdaf | ||
|
|
96ef77c789 | ||
|
|
cab7707e51 | ||
|
|
277fa9d8fe | ||
|
|
509dc038c1 | ||
|
|
2f8301d188 | ||
|
|
3397e90749 | ||
|
|
3cca211ae9 | ||
|
|
8c7a940de5 | ||
|
|
4a5d1ca0da | ||
|
|
7dcbcaae78 | ||
|
|
34ef16b737 | ||
|
|
31f320d4c1 | ||
|
|
960be106bb |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: webspeak-skin-development
|
||||
description: Create, refine, package, and verify WebSpeak visual skins while preserving the product's translated content, fixed component geometry, and interactions.
|
||||
---
|
||||
|
||||
# WebSpeak skin development
|
||||
|
||||
Use this skill when editing or authoring a WebSpeak `.wskin` package, the ILLUSIA built-in skin, or skin-facing UI hooks. A skin changes artwork and visual treatment; WebSpeak owns page structure, text, and behavior. The administrator console is deliberately outside the skin scope.
|
||||
|
||||
## Before editing
|
||||
|
||||
- Read [`docs/SKIN_DEVELOPMENT.md`](../../../docs/SKIN_DEVELOPMENT.md) for the current package validator and public hooks.
|
||||
- Use [`docs/examples/illusia-voice/`](../../../docs/examples/illusia-voice/) and [`docs/examples/ILLUSIA-VOICE.md`](../../../docs/examples/ILLUSIA-VOICE.md) as the reference implementation. Do not restore the removed Aurora Voice sample.
|
||||
- Inspect the actual component markup for `data-ws-page`, `data-ws-part`, and `data-ws-state` hooks. Treat Vue classes and incidental DOM structure as private.
|
||||
|
||||
## Preserve the interface
|
||||
|
||||
- Keep WebSpeak's translations and semantic content as the baseline. Add `content.json` only when a text override is an explicit part of the request; never use it to implement visual artwork.
|
||||
- Skin only with supported visual CSS and package-local images/fonts. The upload validator rejects layout, positioning, sizing, spacing, clipping, text-flow, and interaction-geometry changes. Do not work around it with selectors, pseudo-elements, or animation.
|
||||
- Never hide or obstruct critical controls, make a card or player move/resize, change a floating menu into a modal, or make artwork intercept pointer input. Keep `/admin/**` unskinned.
|
||||
- Use the host's reserved artwork hooks for layered character art and the headphone scene. Prefer transparent assets and `background-size: contain` where the reference requires the full character or chibi to remain visible; arrange the artwork around the fixed hook rather than changing its geometry.
|
||||
- Build visual depth with separate background, surface, and foreground artwork already exposed by the hooks. Avoid duplicate static decorations when an animated replacement exists. For motion, keep waveforms/sonar smooth and restrained, honor reduced-motion preferences, and retain readable focus, error, mute, and speaking states.
|
||||
- Keep skin-specific CSS variables under `--skin-*`. Use only package-local assets and confirm their redistribution rights.
|
||||
|
||||
## Verify and package
|
||||
|
||||
1. Compare the implementation with its visual reference at desktop and narrow widths. Check the homepage, voice workspace, empty chat, member list, screen-share player, selectors, and `/demo`; verify no crop, overflow, text collision, or control overlap.
|
||||
2. Check all five interface languages, day/night modes, keyboard focus, and reduced-motion behavior. Confirm the admin console is unchanged.
|
||||
3. Run `npm test` and `npm --prefix web run build`. Fix validator or build failures rather than weakening the layout guardrails.
|
||||
4. Package the contents of the skin directory so `manifest.json` is at the archive root, then import it through `/admin/skins` and retest the installed `.wskin` in a visitor session.
|
||||
|
||||
The three shipped skins—default day, default night, and ILLUSIA—are protected built-ins. Do not change their IDs or introduce upload/update flows that can disable, replace, or remove them.
|
||||
@@ -0,0 +1,22 @@
|
||||
.git
|
||||
.github
|
||||
.claude
|
||||
node_modules
|
||||
web/node_modules
|
||||
mobile/node_modules
|
||||
web/android
|
||||
.local-opus-hook.cjs
|
||||
界面参考
|
||||
dist
|
||||
web/dist
|
||||
data
|
||||
certs
|
||||
release-artifacts
|
||||
scripts/acceleration-poc
|
||||
*.tar.gz
|
||||
*.tar.xz
|
||||
claude.pem
|
||||
config.json
|
||||
.env
|
||||
.env.*
|
||||
*.log
|
||||
@@ -1,50 +1,78 @@
|
||||
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.2.6
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
windows-x64:
|
||||
runs-on: windows-latest
|
||||
verify:
|
||||
uses: ./.github/workflows/ci.yml
|
||||
|
||||
windows:
|
||||
needs: verify
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: windows-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.22.2
|
||||
architecture: x64
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
package-lock.json
|
||||
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 }
|
||||
npm --prefix web run build
|
||||
$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 run web:build
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run build
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm prune --omit=dev --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
- name: Package and smoke-test Windows x64
|
||||
- name: Package and smoke-test Windows ${{ matrix.arch }}
|
||||
shell: pwsh
|
||||
env:
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
PACKAGE_ARCH: ${{ matrix.arch }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$packageName = "webspeak-webclient-v$env:RELEASE_VERSION-windows-x64"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
$packageName = "webspeak-webclient-v$releaseVersion-windows-$env:PACKAGE_ARCH"
|
||||
$packageRoot = Join-Path $env:RUNNER_TEMP $packageName
|
||||
$runtimeRoot = Split-Path -Parent (Get-Command node).Source
|
||||
New-Item -ItemType Directory -Path $packageRoot | Out-Null
|
||||
@@ -71,8 +99,8 @@ jobs:
|
||||
$smokeRoot = Join-Path $env:RUNNER_TEMP ($packageName + "-smoke")
|
||||
Copy-Item -Recurse -LiteralPath $packageRoot -Destination $smokeRoot
|
||||
@{
|
||||
port = 31440
|
||||
tsHost = "203.0.113.10"
|
||||
port = 3040
|
||||
tsHost = "127.0.0.1"
|
||||
tsPort = 9987
|
||||
tsServerPassword = ""
|
||||
tsServerProtocol = "ts6"
|
||||
@@ -85,9 +113,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 {
|
||||
@@ -96,36 +124,57 @@ jobs:
|
||||
Compress-Archive -LiteralPath $packageRoot -DestinationPath (Join-Path $env:GITHUB_WORKSPACE ($packageName + ".zip")) -CompressionLevel Optimal
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x64
|
||||
path: webspeak-webclient-v${{ inputs.version }}-windows-x64.zip
|
||||
name: windows-${{ matrix.arch }}
|
||||
path: webspeak-webclient-v*-windows-${{ matrix.arch }}.zip
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
linux-x64:
|
||||
runs-on: ubuntu-latest
|
||||
linux:
|
||||
needs: verify
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: ubuntu-latest
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.22.2
|
||||
architecture: ${{ matrix.arch == 'arm64' && 'arm64' || 'x64' }}
|
||||
cache: npm
|
||||
cache-dependency-path: |
|
||||
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
|
||||
npm --prefix web run build
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
npm version --no-git-tag-version "$release_version"
|
||||
fi
|
||||
npm run web:build
|
||||
npm run build
|
||||
npm prune --omit=dev --no-audit --no-fund
|
||||
- name: Package and smoke-test Linux x64
|
||||
- name: Package and smoke-test Linux ${{ matrix.arch }}
|
||||
env:
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
PACKAGE_ARCH: ${{ matrix.arch }}
|
||||
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-${PACKAGE_ARCH}"
|
||||
package_root="$RUNNER_TEMP/$package_name"
|
||||
runtime_root="$(dirname "$(dirname "$(command -v node)")")"
|
||||
mkdir -p "$package_root/web" "$package_root/runtime"
|
||||
@@ -148,8 +197,8 @@ jobs:
|
||||
cp -a "$package_root" "$smoke_root"
|
||||
cat > "$smoke_root/config.json" <<'CONFIG'
|
||||
{
|
||||
"port": 31441,
|
||||
"tsHost": "203.0.113.10",
|
||||
"port": 3040,
|
||||
"tsHost": "127.0.0.1",
|
||||
"tsPort": 9987,
|
||||
"tsServerPassword": "",
|
||||
"tsServerProtocol": "ts6",
|
||||
@@ -164,17 +213,127 @@ 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
|
||||
name: linux-${{ matrix.arch }}
|
||||
path: webspeak-webclient-v*-linux-${{ matrix.arch }}.tar.gz
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
android:
|
||||
needs: 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
|
||||
mobile/package-lock.json
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
- uses: android-actions/setup-android@v4
|
||||
with:
|
||||
packages: platform-tools
|
||||
- name: Build Android APKs
|
||||
env:
|
||||
RELEASE_REF: ${{ inputs.version || github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
version_code="$(node -e 'const [major, minor, patch] = process.argv[1].split(".").map(Number); process.stdout.write(String(major * 10000 + minor * 100 + patch))' "$release_version")"
|
||||
sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.0.0"
|
||||
npm ci --ignore-scripts --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 run prepare:sdk
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
npm run android:sync
|
||||
cd web/android
|
||||
chmod +x gradlew
|
||||
./gradlew --no-daemon assembleDebug -PappVersion="$release_version" -PappVersionCode="$version_code"
|
||||
cd "$GITHUB_WORKSPACE"
|
||||
mkdir -p release-apks
|
||||
for apk in web/android/app/build/outputs/apk/debug/app-*-debug.apk; do
|
||||
abi="${apk##*/app-}"
|
||||
abi="${abi%-debug.apk}"
|
||||
cp "$apk" "release-apks/webspeak-android-v${release_version}-${abi}-debug.apk"
|
||||
done
|
||||
test "$(find release-apks -maxdepth 1 -name '*.apk' | wc -l)" -eq 3
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android-apks
|
||||
path: release-apks/*.apk
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
publish-release:
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: [windows, linux, android]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Download deployment packages
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: '*'
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Create checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd release-assets
|
||||
sha256sum * > SHA256SUMS.txt
|
||||
- name: Publish GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: WebSpeak ${{ github.ref_name }}
|
||||
body_path: docs/releases/${{ github.ref_name }}.md
|
||||
files: release-assets/*
|
||||
- name: Remove superseded preview release and tag
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const tag = 'v0.2.6-preview';
|
||||
try {
|
||||
const release = await github.rest.repos.getReleaseByTag({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
tag,
|
||||
});
|
||||
await github.rest.repos.deleteRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: release.data.id,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
try {
|
||||
await github.rest.git.deleteRef({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
ref: `tags/${tag}`,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.status !== 404 && error.status !== 422) throw error;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
name: Continuous integration
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [dev, master]
|
||||
pull_request:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
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 application
|
||||
run: npm run verify
|
||||
|
||||
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
|
||||
@@ -0,0 +1,51 @@
|
||||
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:
|
||||
verify:
|
||||
uses: ./.github/workflows/ci.yml
|
||||
|
||||
publish:
|
||||
needs: verify
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- 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
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -1,9 +1,31 @@
|
||||
node_modules/
|
||||
dist/
|
||||
web/dist/
|
||||
mobile/node_modules/
|
||||
web/android/.gradle/
|
||||
web/android/build/
|
||||
web/android/app/build/
|
||||
web/android/local.properties
|
||||
web/android/app/src/main/assets/public/
|
||||
web/android/app/src/main/assets/capacitor.config.json
|
||||
data/
|
||||
config.json
|
||||
*.log
|
||||
.env
|
||||
webspeak-update.tar.gz
|
||||
# Local deployment/download artifacts (see docs/LOCAL_ARTIFACTS.zh-CN.md).
|
||||
/release-artifacts/
|
||||
/webspeak-deploy*.tar.gz
|
||||
/webspeak-update*.tar.gz
|
||||
/teamspeak6-server-linux-amd64.tar.xz
|
||||
/.local-opus-hook.cjs
|
||||
/界面参考/stitch_teamspeak_web_interface.zip
|
||||
claude.pem
|
||||
|
||||
# Private credentials and deployment notes stay local.
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
*.key
|
||||
/.claude/
|
||||
/LOCAL-RELEASE-RUNBOOK.md
|
||||
/DEPLOYMENT-*.md
|
||||
@@ -0,0 +1,457 @@
|
||||
# Changelog
|
||||
|
||||
## [0.2.6] — 2026-10-08(相对 0.2.5 正式版)
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) 中 Docker/Compose 短主机名解析和 HTTPS 健康检查问题;实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) 的 TeamSpeak 身份导入、转换与导出;加固 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) 静音状态同步及 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) TS6 屏幕共享清理流程。
|
||||
- 实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 所需的公网媒体地址、IPv6 候选和语音 STUN 管理配置;修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的连接后漏掉既有 TS6 原生屏幕共享的问题。媒体直连仍要求 UDP 路径可达,需按部署环境配置并验证。
|
||||
- 改善语音与 WebRTC 会话稳定性:隔离连接切换后的音频、目录和统计事件,改进 Opus 协商及连续编码状态,并修复静音麦克风时伴奏被一并静音的问题。
|
||||
- 优化移动端语音控制、屏幕常亮和窄屏布局;改进管理后台状态生命周期与语音工作区组件结构。
|
||||
- 发布包提供 Windows x64 与 Linux x64/ARM64;Docker 镜像支持 amd64/arm64;增加 Android 客户端 APK,包含 arm64-v8a、armeabi-v7a、x86_64 三种构建。Android APK 使用 debug 签名,供侧载测试,不代表已完成真机 TeamSpeak 语音验收。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed Docker/Compose short-hostname resolution and HTTPS health checks in [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); implemented TeamSpeak identity import, conversion, and export for [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); hardened mute-state synchronization for [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) and TS6 screen-share cleanup for [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
|
||||
- Added the public media address, IPv6-candidate, and voice-STUN controls requested by [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12), and fixed the missed-existing-TS6-share case described in [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Direct media still requires a reachable UDP path and deployment-specific configuration and testing.
|
||||
- Improved voice and WebRTC session stability by isolating audio, directory, and statistics events across reconnects, tightening Opus negotiation and encoder continuity, and keeping accompaniment audible while the microphone is muted.
|
||||
- Refined mobile voice controls, screen wake behavior, and narrow layouts; improved administration state lifecycles and voice-workspace component boundaries.
|
||||
- Added Windows x64 and Linux x64/ARM64 packages; Docker images support amd64/arm64. Android APKs are available for arm64-v8a, armeabi-v7a, and x86_64. They use debug signing for sideload testing; real-device TeamSpeak voice has not been validated.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Docker-/Compose-Auflösung kurzer Hostnamen und HTTPS-Gesundheitsprüfungen aus [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) behoben; Import, Konvertierung und Export von TeamSpeak-Identitäten für [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) ergänzt; Stummschaltungssynchronisierung aus [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) und TS6-Bildschirmfreigabe-Bereinigung aus [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) gehärtet.
|
||||
- Die in [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) gewünschten Einstellungen für öffentliche Medienadresse, IPv6-Kandidaten und Sprach-STUN ergänzt; den Fall verpasst synchronisierter, bereits aktiver TS6-Freigaben aus [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) behoben. Direkte Medien benötigen weiterhin einen erreichbaren UDP-Pfad und deployment-spezifische Konfiguration und Tests.
|
||||
- Sprach- und WebRTC-Sitzungen stabilisiert, Opus-Aushandlung verbessert und Begleitton bei stummgeschaltetem Mikrofon erhalten. Mobile Sprachsteuerung, Bildschirm-Wachhalten und schmale Layouts wurden überarbeitet.
|
||||
- Windows-x64- und Linux-x64/ARM64-Pakete sowie Docker-Images für amd64/arm64 ergänzt. Android-APKs gibt es für arm64-v8a, armeabi-v7a und x86_64; sie sind für Seiteneinladungstests debug-signiert. Reale TeamSpeak-Sprachtests auf Geräten sind nicht bestätigt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Исправлены разрешение коротких имён Docker/Compose и HTTPS-проверки работоспособности из [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10); добавлен импорт, преобразование и экспорт идентификаторов TeamSpeak для [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9); усилена синхронизация микрофона из [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) и очистка трансляции экрана TS6 из [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7).
|
||||
- Добавлены настройки публичного адреса медиа, IPv6-кандидатов и голосового STUN по запросу [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12); исправлен пропуск уже запущенной трансляции TS6 после подключения из [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13). Для прямого медиа по-прежнему нужен доступный UDP-маршрут и настройка конкретного развёртывания.
|
||||
- Повышена устойчивость голосовых сессий и WebRTC: события аудио, каталога и статистики изолированы при переподключении, улучшены согласование Opus и непрерывность кодирования; музыка сопровождения остаётся слышна при выключенном микрофоне. Улучшены мобильные элементы управления и узкие экраны.
|
||||
- Доступны пакеты Windows x64 и Linux x64/ARM64, Docker-образы — для amd64/arm64. Android APK собраны для arm64-v8a, armeabi-v7a и x86_64 и подписаны отладочным ключом для установки вручную; голос TeamSpeak на реальных устройствах не проверен.
|
||||
|
||||
### 日本語
|
||||
|
||||
- [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10) の Docker/Compose 短縮ホスト名解決と HTTPS ヘルスチェックを修正。[#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9) の TeamSpeak ID インポート・変換・エクスポートを実装し、[#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6) のミュート同期と [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7) の TS6 画面共有終了処理を強化しました。
|
||||
- [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) の要望に沿って公開メディアアドレス、IPv6 候補、音声 STUN の設定を追加し、[PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) が報告した接続前から存在する TS6 画面共有の見落としを修正しました。直接メディア通信には到達可能な UDP 経路と環境ごとの設定・検証が必要です。
|
||||
- 音声/WebRTC セッションの安定性を改善し、再接続後に古い音声・ディレクトリ・統計イベントが混ざらないようにしました。Opus のネゴシエーションと連続エンコードを改善し、マイクをミュートしても伴奏が聞こえるよう修正しました。モバイル操作と狭い画面のレイアウトも改善しました。
|
||||
- Windows x64 と Linux x64/ARM64 のサーバーパッケージ、amd64/arm64 の Docker イメージに対応。Android APK は arm64-v8a、armeabi-v7a、x86_64 を用意しました。APK はサイドロードテスト向けのデバッグ署名で、実機 TeamSpeak 音声は未検証です。
|
||||
|
||||
## [0.2.5] — 2026-09-27(相对 0.2.4)
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 `.wskin` 视觉皮肤系统:用户可在首页、语音工作区和 `/demo` 选择外观;皮肤可更换背景、美术素材与组件视觉,但页面结构、排版空间、控件位置和交互仍由 WebSpeak 固定提供,管理后台不受皮肤影响。
|
||||
- 管理员可在皮肤库启用/停用自定义皮肤并指定实例默认皮肤;访客手动选择会保留,未手动选择的访客采用实例默认。默认日间、默认夜间和 ILLUSIA 风是受保护内置皮肤,不能删除、停用或替换。
|
||||
- 将完成度不足的 Aurora Voice 示例移除,以 ILLUSIA 风作为完整皮肤开发样例;细化首页装饰、语音区跨层级立绘、耳机场景、聊天空状态和屏幕播放器表现,并修复深色模式控件可读性、组件溢出和皮肤加载闪烁。
|
||||
- 新增官方仓库皮肤开发 Agent Skill,配套更新开发规范与多语言功能说明;访客总数在统计暂不可用时也不会低于当前访客序号。
|
||||
- 缩小 ILLUSIA 语音活动立绘并固定在容器右下角,避免遮挡成员名单和屏幕共享播放器。
|
||||
|
||||
### English
|
||||
|
||||
- Added the `.wskin` visual skin system. Visitors can choose appearances on the home page, voice workspace, and `/demo`; skins may customize artwork and component visuals while WebSpeak retains page structure, layout, control placement, and behavior. The administration console remains unskinned.
|
||||
- Administrators can enable/disable custom skins and set an instance default. Deliberate visitor choices are preserved; visitors without an explicit choice receive the instance default. Default Day, Default Night, and ILLUSIA are protected built-ins that cannot be removed, disabled, or replaced.
|
||||
- Removed the unfinished Aurora Voice sample and made ILLUSIA the complete reference skin. Refined homepage artwork, layered voice-room character art and headphone scene, the empty-chat backdrop, and the screen-share player; fixed dark-mode control contrast, overflow, and skin-load flashes.
|
||||
- Added the repository's official skin-development Agent Skill and synchronized the guide and localized feature notes. The displayed visitor total also remains at least as high as the current visitor ordinal when the counter is unavailable.
|
||||
- Reduced and anchored the ILLUSIA voice-activity artwork to the lower-right corner so it no longer obscures member cards or the screen-share player.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Das visuelle `.wskin`-System wurde ergänzt. Besucher können das Design auf der Startseite, im Sprachbereich und unter `/demo` wählen. Skins dürfen Grafiken und die visuelle Darstellung anpassen; Seitenstruktur, Layout, Positionen der Bedienelemente und Verhalten bleiben von WebSpeak vorgegeben. Die Administrationskonsole bleibt ungestaltet.
|
||||
- Administratoren können eigene Skins aktivieren/deaktivieren und ein Standarddesign für die Instanz festlegen. Eine bewusst getroffene Besucherauswahl bleibt erhalten; ohne eigene Auswahl gilt der Instanzstandard. Tagesmodus, Nachtmodus und ILLUSIA sind geschützte integrierte Skins und können weder gelöscht noch deaktiviert oder ersetzt werden.
|
||||
- Das unfertige Aurora-Voice-Beispiel wurde entfernt; ILLUSIA ist nun das vollständige Referenzdesign. Startseitenkunst, Ebenenillustration und Kopfhörerszene im Sprachbereich, leerer Chat-Hintergrund und Bildschirmfreigabe-Player wurden verfeinert. Außerdem wurden dunkle Bedienelemente, Überläufe und Skin-Ladeblitze korrigiert.
|
||||
- Der offizielle Skin-Entwicklungs-Agent-Skill des Repositorys wurde ergänzt; Anleitung und lokalisierte Funktionsübersichten wurden aktualisiert. Die Besucher-Gesamtzahl fällt bei nicht verfügbarem Zähler nicht unter die aktuelle Besuchernummer.
|
||||
- Die ILLUSIA-Illustration bei Sprachaktivität wurde verkleinert und unten rechts verankert, damit sie weder Mitgliederkarten noch den Bildschirmfreigabe-Player verdeckt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена визуальная система скинов `.wskin`: посетители могут выбирать оформление на главной странице, в голосовом пространстве и в `/demo`. Скины меняют иллюстрации и внешний вид компонентов, а структуру, компоновку, расположение элементов управления и поведение задаёт WebSpeak. Панель администратора не оформляется скинами.
|
||||
- Администраторы могут включать и отключать пользовательские скины и задавать оформление по умолчанию для экземпляра. Явный выбор посетителя сохраняется; без него используется настройка экземпляра. Дневная тема, ночная тема и ILLUSIA — защищённые встроенные скины, которые нельзя удалить, отключить или заменить.
|
||||
- Удалён незавершённый пример Aurora Voice; полной эталонной темой стала ILLUSIA. Улучшены иллюстрации главной страницы, многослойный персонаж и сцена с наушниками в голосовой комнате, фон пустого чата и проигрыватель трансляции экрана. Исправлены контраст элементов в тёмном режиме, переполнение и вспышки при загрузке скина.
|
||||
- В официальный репозиторий добавлен Agent Skill для разработки скинов, обновлены руководство и локализованные описания функций. При недоступности счётчика общее число посетителей не опускается ниже текущего номера посетителя.
|
||||
- Иллюстрация ILLUSIA при голосовой активности уменьшена и закреплена внизу справа, чтобы не перекрывать список участников и проигрыватель трансляции экрана.
|
||||
|
||||
### 日本語
|
||||
|
||||
- `.wskin` ビジュアルスキン機能を追加しました。ホーム、音声ワークスペース、`/demo` で外観を選択できます。背景や素材、コンポーネントの見た目を変更できますが、ページ構造、レイアウト、操作部品の位置と動作は WebSpeak が管理します。管理コンソールには適用されません。
|
||||
- 管理者はカスタムスキンの有効/無効と、インスタンスのデフォルトスキンを設定できます。訪問者が明示的に選んだスキンは維持され、未選択の場合はインスタンスのデフォルトを使用します。昼、夜、ILLUSIA の3種類は保護された内蔵スキンで、削除・無効化・置換できません。
|
||||
- 未完成の Aurora Voice サンプルを削除し、ILLUSIA を完成版のリファレンスにしました。ホームのアート、音声画面の重ね合わせ立ち絵とヘッドホン背景、空のチャット背景、画面共有プレーヤーを調整し、ダークモードの視認性、はみ出し、読み込み時のちらつきを修正しました。
|
||||
- 公式リポジトリにスキン開発 Agent Skill を追加し、ガイドと各言語の機能説明を更新しました。カウンターを取得できない場合も、訪問者総数が現在の訪問者番号を下回らないようにしました。
|
||||
- 音声アクティビティの ILLUSIA 立ち絵を縮小して右下に固定し、メンバー一覧や画面共有プレーヤーを隠さないようにしました。
|
||||
|
||||
## [0.2.4] — 2026-09-22
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增跨端 P2P 屏幕共享:浏览器用户可以与 TeamSpeak 6 原生客户端互相发现、发起和观看屏幕共享;浏览器之间以及浏览器与原生客户端之间的媒体流优先通过 WebRTC/ICE 直连,WebSpeak 仅负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。
|
||||
- 默认使用 TeamSpeak 官方 STUN 服务发现直连候选,并支持管理员显式配置外部 TURN;即使使用 TURN,媒体也经过外部服务而不是 WebSpeak 网关。
|
||||
- 新增屏幕共享直播状态、观众人数、播放器音量、全屏和退出控制,并提供发送端/接收端 WebRTC 实时统计。
|
||||
- 提供浏览器屏幕采集分辨率和帧率设置,最高支持 1080p、60 FPS;设置改为独立弹窗,避免成员卡片被撑高。
|
||||
- 新增首页访客编号,并优化屏幕共享成员卡片和观看交互。
|
||||
- 修正输出限制的应用方式:保持所选桌面或窗口的原始采集尺寸,由发送端编码器按设置缩放和限帧;首页同时显示当前访客序号和累计访客数。
|
||||
- 修复 TeamSpeak 握手期间服务器拒绝错误被误报为连接超时的问题;昵称长度不符合要求时会显示明确的修改提示。
|
||||
|
||||
### English
|
||||
|
||||
- Added cross-platform P2P screen sharing: browser users can discover, start, and watch screen shares with native TeamSpeak 6 clients. Media between browsers, and between a browser and a native client, prefers a direct WebRTC/ICE path; WebSpeak handles session authorization, share state, and SDP/ICE signaling only and does not carry screen media.
|
||||
- Added TeamSpeak's public STUN services for direct-candidate discovery by default, with optional administrator-configured external TURN. Even with TURN, media uses the external service rather than the WebSpeak gateway.
|
||||
- Added live screen-share status, viewer counts, player volume, fullscreen, and exit controls, plus live sender/receiver WebRTC statistics.
|
||||
- Added browser capture-resolution and frame-rate controls up to 1080p and 60 FPS; moved the controls into a standalone modal so member cards no longer stretch.
|
||||
- Added homepage visitor numbering and refined screen-share member-card and viewing interactions.
|
||||
- Fixed output-limit handling so the selected desktop or window keeps its native capture size while the sender encoder applies the requested scale and frame-rate cap; the homepage now also shows the total visitor count.
|
||||
- Fixed handshake refusals being reported as connection timeouts; invalid nickname lengths now show a clear prompt to change the nickname.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Plattformübergreifendes P2P-Bildschirmteilen ergänzt: Browsernutzer können Bildschirmfreigaben mit nativen TeamSpeak-6-Clients erkennen, starten und ansehen. Die Medienübertragung zwischen Browsern sowie zwischen Browser und nativem Client nutzt möglichst direkte WebRTC-/ICE-Verbindungen; WebSpeak übernimmt nur Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung und transportiert keine Bildschirmmedien.
|
||||
- Öffentliche TeamSpeak-STUN-Dienste werden standardmäßig zur Ermittlung direkter Kandidaten verwendet; ein externes TURN kann ausdrücklich durch den Administrator konfiguriert werden. Auch mit TURN läuft die Medienübertragung über den externen Dienst und nicht über das WebSpeak-Gateway.
|
||||
- Live-Status, Zuschauerzahl, Lautstärke, Vollbild- und Beenden-Steuerung für Bildschirmfreigaben sowie laufende WebRTC-Statistiken für Sender und Empfänger ergänzt.
|
||||
- Aufnahmeauflösung und Bildrate im Browser bis 1080p und 60 FPS konfigurierbar; die Einstellungen wurden in ein eigenes Modal verschoben, damit Mitgliederkarten nicht mehr in die Höhe wachsen.
|
||||
- Besucherzählung auf der Startseite ergänzt und die Interaktion von Bildschirmfreigabe-Karten und Player verbessert.
|
||||
- Die Ausgabelimits werden nun am Sender-Encoder angewendet, während die native Aufnahmegröße des ausgewählten Desktops oder Fensters erhalten bleibt; auf der Startseite wird zusätzlich die Gesamtzahl der Besucher angezeigt.
|
||||
- Behoben, dass Ablehnungen während des TeamSpeak-Handshakes als Zeitüberschreitung angezeigt wurden; bei ungültiger Nicknamenslänge erscheint nun ein klarer Änderungshinweis.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлена кроссплатформенная P2P-трансляция экрана: пользователи браузера могут обнаруживать, запускать и смотреть трансляции вместе с нативными клиентами TeamSpeak 6. Медиа между браузерами, а также между браузером и нативным клиентом по возможности передаётся напрямую через WebRTC/ICE; WebSpeak отвечает только за авторизацию сессии, состояние трансляции и SDP/ICE-сигналы и не переносит медиаданные экрана.
|
||||
- По умолчанию добавлено обнаружение прямых кандидатов через публичные STUN-сервисы TeamSpeak; администратор может явно настроить внешний TURN. Даже при использовании TURN медиа идёт через внешний сервис, а не через шлюз WebSpeak.
|
||||
- Добавлены статус трансляции, число зрителей, громкость проигрывателя, полноэкранный режим и выход, а также текущая статистика WebRTC для отправителя и получателя.
|
||||
- Добавлены настройки разрешения и частоты кадров захвата в браузере до 1080p и 60 FPS; настройки вынесены в отдельное окно, чтобы карточки участников не растягивались.
|
||||
- Добавлен номер посетителя на главной странице и улучшено управление карточками и просмотром трансляций.
|
||||
- Исправлено применение ограничений вывода: выбранный рабочий стол или окно сохраняет исходный размер захвата, а запрошенное масштабирование и ограничение частоты кадров применяются кодировщиком отправителя; на главной странице также показывается общее число посетителей.
|
||||
- Исправлено ошибочное отображение отказов TeamSpeak во время рукопожатия как тайм-аута; при недопустимой длине имени показывается понятная просьба изменить его.
|
||||
|
||||
### 日本語
|
||||
|
||||
- クロスプラットフォーム P2P 画面共有を追加しました。ブラウザユーザーは TeamSpeak 6 ネイティブクライアントと互いに画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間のメディアは可能な限り WebRTC/ICE で直接送信され、WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングだけを担当し、画面メディアは運びません。
|
||||
- 初期設定で TeamSpeak 公開 STUN サービスによる直接候補の検出に対応し、管理者が外部 TURN を明示的に設定できるようにしました。TURN 使用時もメディアは外部サービスを経由し、WebSpeak ゲートウェイは経由しません。
|
||||
- 配信状態、視聴者数、プレーヤー音量、全画面、終了操作と、送信側・受信側の WebRTC 統計を追加しました。
|
||||
- ブラウザの画面取得設定で最大 1080p / 60 FPS を選択できます。設定を独立したモーダルに移し、メンバーカードが縦に伸びないようにしました。
|
||||
- ホームページの訪問者番号を追加し、画面共有カードと視聴操作を改善しました。
|
||||
- 出力制限を送信側エンコーダーで適用するよう修正し、選択したデスクトップやウィンドウの元の取得サイズを維持します。ホームページには訪問者番号に加えて累計訪問者数も表示します。
|
||||
- TeamSpeak の接続ハンドシェイク中の拒否がタイムアウトとして表示される問題を修正しました。ニックネームの長さが不適切な場合は、変更を促すメッセージを表示します。
|
||||
|
||||
## [0.2.3] — 2026-09-19
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增频道成员调度入口:保留拖放移动,并在右键菜单提供“调度到”二级菜单和“我所在的频道”快捷项。
|
||||
- 支持按 TeamSpeak 权限直接移动成员;具备权限时无需重复输入频道密码,无权限时不提供该操作。
|
||||
- 支持成员头像显示、麦克风静音状态同步和保存身份恢复,并增强指针拖动兼容性。
|
||||
- 更新中文、English、Deutsch、Русский、日本語五种语言的功能截图和文档页面。
|
||||
- 修复高分辨率桌面端管理员设置页面底部内容被裁切的问题,并收紧中继卡片的宽度约束。
|
||||
|
||||
### English
|
||||
|
||||
- Added member-management entry points: drag-and-drop remains available, while the context menu now provides a “Move to” submenu with a “My channel” shortcut.
|
||||
- Added permission-aware direct member moves: authorized users can move clients without redundant channel-password prompts, while the action is unavailable without the required TeamSpeak permission.
|
||||
- Added client-avatar display, microphone mute-state synchronization, and remembered-identity recovery, with improved pointer-drag compatibility.
|
||||
- Refreshed feature screenshots and documentation pages for all five supported languages.
|
||||
- Fixed clipped lower content in the high-resolution desktop admin settings page and tightened relay-card width constraints.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Neue Einstiege für die Mitgliederverwaltung: Ziehen und Ablegen bleibt verfügbar, zusätzlich bietet das Kontextmenü ein Untermenü „Verschieben nach“ mit dem Eintrag „Mein Kanal“.
|
||||
- Direkte, berechtigungsabhängige Mitgliederverschiebung ergänzt: Benutzer mit den erforderlichen TeamSpeak-Rechten benötigen keine erneute Kanalpasswortabfrage; ohne diese Rechte steht die Aktion nicht zur Verfügung.
|
||||
- Anzeige von Client-Avataren, Synchronisierung des Mikrofon-Stummschaltstatus und Wiederherstellung gespeicherter Identitäten ergänzt; Zeigerbedienung verbessert.
|
||||
- Funktionsscreenshots und Dokumentationsseiten für alle fünf unterstützten Sprachen aktualisiert.
|
||||
- Das Abschneiden unterer Inhalte in den Admin-Einstellungen bei hoher Desktop-Auflösung behoben und die Breitenbegrenzung der Relay-Karten verbessert.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлены способы управления участниками: перетаскивание сохранено, а в контекстном меню появился пункт «Переместить в» с быстрым вариантом «Мой канал».
|
||||
- Добавлено прямое перемещение с учётом прав TeamSpeak: пользователям с нужными правами не нужно повторно вводить пароль канала, а без этих прав действие недоступно.
|
||||
- Добавлены отображение аватаров клиентов, синхронизация состояния микрофона и восстановление сохранённой идентичности; улучшено перетаскивание указателем.
|
||||
- Обновлены функциональные скриншоты и страницы документации для всех пяти поддерживаемых языков.
|
||||
- Исправлено обрезание нижнего содержимого настроек администратора на десктопах с высоким разрешением и ограничена ширина карточек ретрансляторов.
|
||||
|
||||
### 日本語
|
||||
|
||||
- メンバー操作を追加しました。ドラッグ&ドロップに加えて、コンテキストメニューに「移動先」サブメニューと「自分のチャンネル」ショートカットを用意しました。
|
||||
- TeamSpeak 権限に応じた直接移動を追加しました。必要な権限があればチャンネルパスワードを再入力せずに移動でき、権限がなければ操作は表示されません。
|
||||
- クライアントアバターの表示、マイクミュート状態の同期、保存した ID の復元に対応し、ポインター操作も改善しました。
|
||||
- 対応する 5 言語すべての機能スクリーンショットとドキュメントページを更新しました。
|
||||
- 高解像度デスクトップで管理設定の下部が切れる問題を修正し、中継カードの幅制約を改善しました。
|
||||
|
||||
## [0.2.2] — 2026-09-17
|
||||
|
||||
### 中文
|
||||
|
||||
- 提供可开关的浏览器端麦克风降噪功能。
|
||||
- 优化前端音量交互逻辑:桌面端悬停麦克风和整体音量按钮即可调整,降噪开关收纳在麦克风菜单中。
|
||||
- 在 PR #2 基础上优化错误提示和错误代码显示。
|
||||
- 提供俄语和日语界面支持,并支持按语言单独调整欢迎文字。
|
||||
|
||||
### English
|
||||
|
||||
- Added optional browser-side microphone noise suppression.
|
||||
- Refined volume interaction: desktop microphone and master-volume controls open on hover, with noise suppression in the microphone menu.
|
||||
- Improved error messages and error-code display on top of PR #2.
|
||||
- Added Russian and Japanese UI support and per-language welcome text configuration.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Optionale browserseitige Mikrofon-Geräuschunterdrückung hinzugefügt.
|
||||
- Lautstärkeinteraktion verbessert: Desktop-Mikrofon- und Gesamtlautstärkeregler öffnen sich beim Überfahren; die Geräuschunterdrückung befindet sich im Mikrofonmenü.
|
||||
- Fehlertexte und Fehlercodes auf Basis von PR #2 verbessert.
|
||||
- Russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt.
|
||||
|
||||
### Русский
|
||||
|
||||
- Добавлено опциональное шумоподавление микрофона в браузере.
|
||||
- Улучшено управление громкостью: на компьютере регуляторы открываются при наведении, а шумоподавление находится в меню микрофона.
|
||||
- Улучшены сообщения и коды ошибок на основе PR #2.
|
||||
- Добавлены русский и японский интерфейсы и отдельная настройка приветствия для каждого языка.
|
||||
|
||||
### 日本語
|
||||
|
||||
- ブラウザ側で任意に使えるマイクノイズ抑制を追加しました。
|
||||
- 音量操作を改善し、デスクトップではマイクと全体音量のボタンにカーソルを合わせると調整画面を表示し、ノイズ抑制をマイクメニューにまとめました。
|
||||
- PR #2 を基にエラー表示とエラーコードを改善しました。
|
||||
- ロシア語・日本語 UI と言語別ウェルカム文の設定を追加しました。
|
||||
|
||||
## [0.2.1] — 2026-09-13
|
||||
|
||||
### 中文
|
||||
|
||||
- 统一首页连接错误显示:保留错误代码,未知错误安全截断,并显示可追溯的服务端原因。
|
||||
- 默认支持 IPv6 TeamSpeak 目标,并补充主机、运行时和网络条件说明。
|
||||
|
||||
### English
|
||||
|
||||
- Unified connection-error display on the welcome page: preserve error codes, safely truncate unknown codes, and show traceable server reasons.
|
||||
- Added default IPv6 TeamSpeak target support and documented the required host, runtime, and network conditions.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Verbindungsfehler auf der Willkommensseite vereinheitlicht: Fehlercodes bleiben erhalten, unbekannte Codes werden sicher gekürzt und nachvollziehbare Serverursachen angezeigt.
|
||||
- IPv6-Ziele für TeamSpeak standardmäßig unterstützt und erforderliche Host-, Laufzeit- und Netzwerkbedingungen dokumentiert.
|
||||
|
||||
## [0.2.0] — 2026-09-10
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增 README“高级功能”章节,补充 WebRTC 与中继服务器的配置和使用步骤。
|
||||
- 明确 WebRTC 的 UDP 端口、安全组与防火墙要求,以及中继令牌和管理员控制台配置方式。
|
||||
- 标注中继服务为 WebSpeak 自带实现;同时注明 WebRTC 使用 MIT 许可的 `werift` 依赖,TeamSpeak 连接使用项目维护的 SDK fork。
|
||||
- 细分 TeamSpeak 连接失败原因,服务器需要密码时提示用户输入密码并重试。
|
||||
- 优化管理员历史连接日志:能够追溯时显示具体原因,无法追溯时使用通用失败提示,不猜测历史原因。
|
||||
- 新增正式中继部署模式:中继实例不提供前台和管理员后台,只接受带令牌的网关转发会话。
|
||||
- 管理员可配置多个中继节点,访客可在欢迎页为当前连接选择直连或指定中继。
|
||||
- 修复用户正常断开后被管理员运维日志误显示为“请求失败”的问题。
|
||||
|
||||
### English
|
||||
|
||||
- Added an “Advanced features” section to the README with WebRTC and relay configuration and usage steps.
|
||||
- Documented WebRTC UDP, security-group, and firewall requirements, plus relay-token and administration-console setup.
|
||||
- Clarified that the relay is built into WebSpeak, while WebRTC uses the MIT-licensed `werift` dependency and TeamSpeak connectivity uses the project-maintained SDK fork.
|
||||
- Classified TeamSpeak connection failures and prompt users for a server password with a retry when authentication requires one.
|
||||
- Improved administrator connection history: show a specific reason when available and use a generic failure message when older records cannot be traced, without guessing.
|
||||
- Added a formal relay deployment mode: relay instances expose no visitor or admin UI and accept only token-authenticated gateway sessions.
|
||||
- Administrators can configure multiple relay nodes, and visitors can choose direct access or a specific relay for each connection.
|
||||
- Fixed normal user disconnects being shown as “request failed” in administrator connection history.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Einen Abschnitt „Erweiterte Funktionen“ mit Anleitungen für WebRTC und Relay-Server zur README hinzugefügt.
|
||||
- UDP-, Sicherheitsgruppen- und Firewall-Anforderungen für WebRTC sowie Relay-Token und Administrationskonfiguration dokumentiert.
|
||||
- Klargestellt, dass das Relay Bestandteil von WebSpeak ist; WebRTC verwendet die MIT-lizenzierte Abhängigkeit `werift`, die TeamSpeak-Verbindung den projektgepflegten SDK-Fork.
|
||||
- TeamSpeak-Verbindungsfehler genauer klassifiziert und bei erforderlichem Serverpasswort eine Eingabe mit Wiederholung angeboten.
|
||||
- Den Verlauf der Administrator-Verbindungen verbessert: verfügbare Ursachen werden angezeigt, ältere nicht nachvollziehbare Einträge erhalten eine allgemeine Fehlermeldung statt einer Vermutung.
|
||||
- Einen dedizierten Relay-Bereitstellungsmodus ergänzt: Relay-Instanzen stellen keine Besucher- oder Admin-Oberfläche bereit und akzeptieren nur Gateway-Sitzungen mit Token.
|
||||
- Administratoren können mehrere Relay-Knoten konfigurieren; Besucher wählen pro Verbindung Direktzugriff oder ein bestimmtes Relay.
|
||||
- Behoben, dass normale Benutzertrennungen im Administrationsverlauf als „Anfrage fehlgeschlagen“ erschienen.
|
||||
|
||||
## [0.1.8] — 2026-09-08
|
||||
|
||||
### 中文
|
||||
|
||||
- Docker 默认使用 host 网络,支持网关访问同机 TeamSpeak 并直接暴露 WebRTC UDP 端口。
|
||||
- 开放模式统一校验用户提交的目标地址,包括管理员默认目标,修复本机与内网目标绕过限制的问题。
|
||||
- TeamSpeak SDK 连接握手增加 15 秒超时,失败连接会及时清理。
|
||||
- 网络性能面板改为持续监测,打开后每 3 秒更新一次延迟与丢包率。
|
||||
|
||||
### English
|
||||
|
||||
- Docker now uses host networking by default, allowing the gateway to reach a local TeamSpeak server and expose the WebRTC UDP range directly.
|
||||
- Open access now validates every submitted target, including the administrator default, closing loopback and private-network bypasses.
|
||||
- Added a 15-second TeamSpeak SDK handshake timeout with prompt cleanup after failed connections.
|
||||
- The network performance panel now measures continuously and refreshes latency and packet loss every 3 seconds while open.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Docker verwendet standardmäßig das Host-Netzwerk, damit das Gateway einen lokalen TeamSpeak-Server erreicht und den WebRTC-UDP-Bereich direkt bereitstellt.
|
||||
- Der offene Zugriffsmodus prüft nun jedes Ziel einschließlich des Administrator-Standards und schließt Umgehungen für Loopback- und private Netze.
|
||||
- Für den TeamSpeak-SDK-Handshake gilt jetzt ein Timeout von 15 Sekunden; fehlgeschlagene Verbindungen werden zeitnah bereinigt.
|
||||
- Das Netzwerkleistungsfeld misst bei geöffneter Ansicht fortlaufend und aktualisiert Latenz und Paketverlust alle 3 Sekunden.
|
||||
|
||||
## [0.1.7] — 2026-09-06
|
||||
|
||||
### 中文
|
||||
|
||||
- 增加 Deutsch 界面支持和 Telegram 群组入口。
|
||||
- 增加桌面端整体音量滑块,默认收起并在悬停时展开。
|
||||
- 修复伴奏音量忽大忽小的问题。
|
||||
- 增加可展开的网络性能面板,显示浏览器、WebSpeak 与 TeamSpeak 之间的延迟和丢包率。
|
||||
- 管理员连接测试改用服务端多次主机 Ping 并显示丢包率,不再创建临时 TeamSpeak 客户端。
|
||||
- 统一中文、English、Deutsch 的旗帜代码语言菜单。
|
||||
- 修复 TeamSpeak 使用 TCP 探测导致的误报丢包,并修正语言菜单异常留白。
|
||||
- 移除 WebRTC 桥接中的 RMS 静音帧过滤,安静帧仅用于发言状态指示,不再丢弃。
|
||||
- 修复 Docker 运行环境缺少 ICMP Ping 工具导致管理员测试误报 100% 丢包。
|
||||
|
||||
### English
|
||||
|
||||
- Added German UI support and a Telegram community link.
|
||||
- Added a compact desktop master-volume slider that expands on hover.
|
||||
- Fixed accompaniment volume fluctuations.
|
||||
- Added an expandable network performance panel with latency and packet loss across the browser, WebSpeak, and TeamSpeak path.
|
||||
- Updated the administrator connection test to use repeated host pings, report packet loss, and avoid creating temporary TeamSpeak clients.
|
||||
- Unified the Chinese, English, and German flag/code language menu.
|
||||
- Fixed false packet-loss reports caused by probing the TeamSpeak UDP service with TCP, and corrected excess space in the language menu.
|
||||
- Removed RMS-based silence filtering from the WebRTC bridge; quiet frames are now retained for the codec timeline.
|
||||
- Fixed Docker admin diagnostics falsely reporting 100% packet loss when the runtime lacked the ICMP ping tool.
|
||||
|
||||
### Deutsch
|
||||
|
||||
- Deutsche Benutzeroberfläche und Telegram-Community-Link hinzugefügt.
|
||||
- Kompakten Gesamtlautstärkeregler für den Desktop ergänzt, der sich beim Überfahren öffnet.
|
||||
- Schwankende Lautstärke bei der Begleittonfreigabe behoben.
|
||||
- Aufklappbares Netzwerkleistungsfeld mit Latenz und Paketverlust zwischen Browser, WebSpeak und TeamSpeak ergänzt.
|
||||
- Verbindungstest in der Administration auf wiederholte Host-Pings mit Paketverlustanzeige umgestellt, ohne temporäre TeamSpeak-Clients zu erzeugen.
|
||||
- Einheitliches Sprachmenü mit Flaggen und Sprachcodes für Chinesisch, Englisch und Deutsch ergänzt.
|
||||
- Falsche Paketverlustmeldungen durch TCP-Prüfung des UDP-Dienstes behoben und übermäßigen Leerraum im Sprachmenü korrigiert.
|
||||
- RMS-basierte Stillefilterung aus der WebRTC-Brücke entfernt; leise Frames bleiben nun im Codec-Zeitverlauf erhalten.
|
||||
- Falsche 100-%-Paketverlustmeldungen behoben, wenn dem Docker-Laufzeitimage das ICMP-Ping-Tool fehlte.
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
### English
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections in the same browser.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
## [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.
|
||||
@@ -1,87 +1,210 @@
|
||||
# WebSpeak — TeamSpeak Browser Gateway
|
||||
# WebSpeak TeamSpeak Browser Gateway
|
||||
|
||||
Server-side bridge that lets users join TeamSpeak voice channels from a browser. No TS client install needed.
|
||||
WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-hosted Node.js gateway. Each connected browser session owns an independent TeamSpeak client. The repository also contains a standalone UDP acceleration relay and an Android preview with an embedded local gateway.
|
||||
|
||||
## Architecture
|
||||
## Application boundaries
|
||||
|
||||
```
|
||||
Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpeak server
|
||||
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
|
||||
| Location | Responsibility |
|
||||
| --- | --- |
|
||||
| `src/index.ts` | Gateway startup, SQLite, master secret, admin service and shutdown; also supports relay mode |
|
||||
| `src/server/server.ts` | HTTP or HTTPS, public configuration, skins, join tickets, admin routes and static frontend |
|
||||
| `src/server/voice-bridge.ts` | `/ws/voice`, admission, connection/reconnection orchestration and voice transport assembly |
|
||||
| `src/server/voice-commands.ts`, `directory-view.ts`, `audio-stats.ts` | Command execution, public directory projection and diagnostic snapshots |
|
||||
| `src/server/member-avatars.ts` | Generation-bound optional avatar downloads, bounded sequential batches, cached images and timer cleanup |
|
||||
| `src/server/session-events.ts` | Session-owned SDK subscriptions, directory projection, self/channel state, chat mapping and avatar coordination |
|
||||
| `src/server/screen-share-coordinator.ts` | Server/channel-scoped sharing membership and browser/native signaling |
|
||||
| `src/shared/` | Browser-safe wire types and runtime parsers shared by both endpoints |
|
||||
| `src/shared/admin-inputs.ts`, `admin-responses.ts` | Shared admin request types and runtime-checked response projections |
|
||||
| `src/server/ts-client.ts` and `teamspeak-adapter.ts` | SDK integration, TS3/TS6 negotiation, identity, chat, voice and client events |
|
||||
| `src/server/session-manager.ts` and `directory-sync.ts` | Connection state, teardown, admission limits and directory reconciliation |
|
||||
| `src/server/webrtc-audio.ts` and `opus-codec.ts` | WebRTC audio mixing and platform-specific Opus codecs |
|
||||
| `src/server/session-audio.ts` | Per-session PCM encoding, exclusive WebRTC/WebSocket routing, whisper dispatch, bounded egress and audio counters |
|
||||
| `src/admin/`, `src/security/`, `src/persistence/` | Administration, access policies, credentials and persistent settings |
|
||||
| `src/relay.ts` and `src/server/acceleration-relay.ts` | Standalone relay and gateway-side relay transport |
|
||||
| `web/src/views/` and `web/src/composables/` | Vue pages, connection state, audio controls, chat and screen sharing |
|
||||
| `web/src/voice/screen-share.ts` | Per-session screen capture, peer negotiation, cleanup and diagnostics |
|
||||
| `web/src/voice/remote-playback.ts` | Per-speaker compatibility decoding, bounded scheduling, volume and resource cleanup |
|
||||
| `web/src/voice/microphone-test.ts` | Cancellable recording tests, recorder deadline and playback URL ownership |
|
||||
| `web/src/voice/microphone-capture.ts` | Prepared microphone processing graphs, per-context worklet loading, optional RNNoise and independent PCM activation/cleanup |
|
||||
| `web/src/voice/audio-sink.ts` | Serialized device routing per audio endpoint, with stale-operation guards |
|
||||
| `web/src/voice/accompaniment.ts` | Generation-bound display-audio capture, immediate pending-capture cancellation, ended listeners and committed activity |
|
||||
| `web/src/voice/webrtc-input.ts` | Stable WebRTC sender output, microphone gain and transactional accompaniment-source attachment |
|
||||
| `web/src/voice/microphone-meter.ts` | Optional per-peer level sampling, owned analysis nodes and timer, partial-failure cleanup and stale-tick rejection |
|
||||
| `web/src/voice/webrtc-transport.ts`, `webrtc-playback.ts` | Per-attempt peer negotiation, input/meter ownership, compatibility fallback and independently owned playback elements and retries |
|
||||
| `web/src/voice/connection.ts`, `commands.ts` | Cancellable ticket acquisition, socket and connection generations, plus per-command acknowledgement deadlines and cleanup |
|
||||
| `web/src/voice/session-state.ts` | Reactive directory, chat history, events and notifications; complete versus omitted directory data, session resets and private-conversation identity scopes |
|
||||
| `web/src/composables/useWebClientChat.ts`, `useWebClientChannels.ts` | Destination-owned drafts and pending sends, identity-bound private history, and iterative channel-tree projection |
|
||||
| `web/src/composables/useWebClientIdentity.ts`, `web/src/components/web-client/IdentityImportDialog.vue` | Page-owned identity reads, parsing, restoration and exports; a presentation dialog with explicit input and action events |
|
||||
| `web/src/voice/audio-diagnostics.ts`, `web/src/composables/useWebClientPerformance.ts` | Session-owned diagnostic probes and compatibility counters, browser statistics, comparable sample scopes and cancellable UI polling |
|
||||
| `web/src/platform/` | Browser mounting and cancellable Android gateway readiness handshake |
|
||||
| `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations |
|
||||
| `web/src/composables/usePublicSkin.ts`, `web/src/services/skin-operation.ts` | Shared public-page skin initialization and selection, page ownership, cancellation and bounded loading |
|
||||
| `web/src/services/admin-api.ts`, `admin-requests.ts` | Admin HTTP validation and cancellation, session-bound CSRF and per-feature request ownership, including skin uploads and backup downloads |
|
||||
| `web/src/composables/useAdminServerSettings.ts`, `useAdminOperations.ts`, `useAdminSkins.ts` | Admin form merging, probes, operational actions and skin state; the page owns authentication, routing and overview |
|
||||
| `web/src/components/admin/` | Server settings, operations and skin presentation; the parent page retains the feature controller instances across subroute changes |
|
||||
| `web/src/composables/useAdminI18n.ts`, `web/src/i18n/admin.ts` | Admin formatting and error/status mappings; all five languages explicitly implement the same translation keys |
|
||||
| `src/mobile/`, `mobile/`, `web/android/` | Android loopback gateway, asset packaging and Capacitor container |
|
||||
|
||||
## Connection and control protocol
|
||||
|
||||
1. The browser requests `/api/join-ticket`. The gateway validates the request against its access policy and issues a short-lived, single-use ticket.
|
||||
2. The browser presents the ticket to `/ws/voice`. The bridge admits a session, acquires any required identity lease and creates its TeamSpeak client.
|
||||
3. WebSocket text messages carry JSON commands, events, WebRTC negotiation and screen-sharing signaling. The server uses the WebSocket `isBinary` flag to distinguish audio from control messages.
|
||||
4. Register TeamSpeak event listeners before connecting: directory and membership events may arrive during the handshake.
|
||||
|
||||
Channel and member data come from SDK directory snapshots and client-protocol commands, followed by realtime notifications. WebQuery and its API key are not required. `DirectorySynchronizer` reconciles snapshots with membership events.
|
||||
|
||||
`SessionEventCoordinator` subscribes before SDK connection and closes before waiting for peer shutdown. Remove only its own listeners and guard captured callbacks as well as registered ones. Directory events are accepted during authentication, synchronization and the live connection, but not reconnect backoff. SDK adapter listeners must reject events from a replaced client before mutating state or forwarding them. A kick remains terminal if the disconnect notification already started recovery.
|
||||
|
||||
Avatar downloads belong to the connected directory generation. Reset them on SDK interruption and close them before awaiting session teardown. Old success or failure results cannot refill caches, publish images, start another download, or unlock newer work. `isAlive` is only the WebSocket heartbeat acknowledgement flag; it is not a lifecycle predicate. Keep avatar failure optional, the 50-member batch limit and 250 ms continuation delay.
|
||||
|
||||
The SDK avatar method captures its client and connection generation across metadata, transfer initialization and download. Recheck both after each await, including reconnects that reuse the same SDK object; never continue an old transfer through a replacement `this.client`. A retired SDK client's disconnect event must not clear the current connection.
|
||||
|
||||
Session teardown must remain safe when requested more than once or when sockets and codec resources are already closed. Reconnection is governed by `reconnect-policy.ts`; preserve terminal error handling, bounded retries and the previous-channel fallback.
|
||||
|
||||
Invalidate session audio before awaiting peer closure. Each codec and track must be released independently so one disposal failure cannot abandon the remaining resources. WebRTC close callers share one completion promise, including a peer-close rejection. Preserve WebSocketServer's close listener: it owns removal from the server's client set and allows shutdown to finish.
|
||||
|
||||
Late socket messages and media permission/negotiation results must not mutate a replacement session. Screen-sharing ownership is scoped to both the TeamSpeak target and channel; another member moving channels must not stop the current user's share. Preserve these invariants when extracting the remaining audio responsibilities.
|
||||
|
||||
WebRTC offers, answers, playback callbacks and accompaniment capture belong to the session and peer that started them. Invalidate pending negotiation on stop, reconnect or teardown before awaiting resource closure. A stale peer must not publish errors, counters or audio into its successor. Negotiation and track setup failures must restore compatibility capture without misreporting a microphone failure.
|
||||
|
||||
The WebRTC transport owns its peer, input mixer, meter, ICE wait and answer deadline. The capture layer retains ownership of the original microphone and PCM graph; releasing input during microphone preparation must not invalidate the preparing transport. Failed stop signaling cannot prevent local cleanup or compatibility fallback. A fallback permission failure must still belong to the connection and transport generation that initiated it.
|
||||
|
||||
Each remote WebRTC audio element owns its in-flight play attempt and retry listeners. Coalesce overlapping gestures, guard captured callbacks against replacement and release partial element setup. Pause, listener removal, source clearing or peer closure failures must not interrupt release of other resources.
|
||||
|
||||
Ticket acquisition has a 15-second browser deadline covering preference readiness, fetch and response-body reading. Disconnect and replacement abort the owning request immediately; stale success, rejection and deadline callbacks cannot open a socket or update a newer connection. This is separate from the gateway's TeamSpeak handshake policy. Browser cancellation does not undo a server-side invite consumption or ticket issuance. Preserve the gateway close code over generic WebSocket errors, detach retired handlers, and tolerate socket-close failures.
|
||||
|
||||
Every acknowledged command owns its original socket, connection generation and deadline. Success, server rejection, synchronous send failure, timeout and disconnect all use one idempotent completion path; release the registration and timer immediately. Fire-and-forget commands keep the existing shared wire contract.
|
||||
|
||||
Chat sends require a connected TeamSpeak session and append local history only after acknowledgement. A queued acknowledgement cannot append after session resource release. Recovery rejections retain the command request ID. Optional channelId and clientUid command fields let the gateway verify the actual channel and recipient before invoking the SDK; legacy payloads remain accepted without those additional guards. Confirmation is not a read receipt, and a timeout does not prove non-delivery.
|
||||
|
||||
Directory, chat, events and poke lists retain their reactive array identities. Complete channel snapshots replace the member directory, while omitted members remain unknown rather than empty. Channel projections share canonical members. Departure and UID replacement release the old member's playback, speaking state, temporary volume and whisper selection; persisted UID-based preferences remain. A recovered TeamSpeak connection replaces its directory even when the connected message omits members.
|
||||
|
||||
Explicit disconnect, target replacement and ordinary socket closure reset message state and advance the page's session epoch. Same-socket recovery may preserve chat history, but cannot send until connected; recovered directories and events replace old snapshots and clear old pokes. Failed recovery may retain its history for the failure panel until retry or exit.
|
||||
|
||||
Private history uses UID scopes when available and member-lifetime scopes for legacy clients without UIDs. Unknown senders must not become later members merely because a numeric ID matches. Preserve the recipient name in outgoing history. Drafts, pending submissions and errors belong to a destination within a session; switching tabs cannot duplicate an in-flight send. Confirmation clears only the unchanged submitted draft, including when its tab is inactive. Reset or disposal retires late feedback.
|
||||
|
||||
Channel projection uses iterative parent and sibling traversal, emits each ID at most once, keeps the first duplicate, promotes missing-parent channels to roots and starts isolated cycles at their first source entry. Do not reintroduce recursive traversal or silently discard the entire directory on a malformed topology.
|
||||
|
||||
Audio diagnostic probes retain their cancellation entry and deadline until both gateway and browser statistics finish. Bind the result to the original socket, connection generation and peer; disconnect settles pending consumers immediately, and a late browser getStats result cannot mix with a replacement peer. A probe send failure returns no sample.
|
||||
|
||||
Diagnostic samples also include the WebRTC transport generation, so a probe cannot survive a failed attempt that starts and ends without a peer. A browser-local scope ID changes with the source and session resets; compatibility counters reset at session teardown and snapshots stay independent. The scope ID is internal metadata, not part of the gateway protocol. Keep the exported diagnostic types available from the voice composable for existing callers.
|
||||
|
||||
The performance panel only subtracts counters from matching scopes, transports and downlink sources (PCM, RTP or gateway frames). Null or rejected probes clear stale activity and restart the baseline. Check the polling generation before starting work as well as after awaiting results; unmount retires callbacks and manual refresh. Preserve the 2-second polling interval. For loss estimates, packetsSent already includes all sent packets, while packetsReceived requires adding lost packets to form the denominator; keep percentages bounded and treat RTCP/local snapshots as estimates.
|
||||
|
||||
Accompaniment changes keep the WebRTC sender output alive. Prepare and connect the new source before replacing the old one; a failure preserves the current microphone and accompaniment. The input mixer owns its nodes and output track, never the externally owned capture streams. Release partial allocations and continue cleanup if an individual node fails. Application audio bypasses microphone gain/denoising and retains its source level.
|
||||
|
||||
The accompaniment controller owns both active and pending captures. Stop, disconnect and replacement immediately release candidates already returned by the browser, even while optional constraints are pending. Late permissions are stopped on arrival; ended or stale candidates cannot be published. Register ended listeners during preparation and publish activity only after attachment succeeds. Optional content hints and processing constraints may fail without losing capture; distinguish audio attachment errors from permission errors in all five languages.
|
||||
|
||||
Microphone metering is optional and must not interrupt voice. Its nodes and timer belong to one meter instance; a queued old tick cannot read the next session's analyser or publish a level. Allocation, connection and read failures release all meter resources and clear level/speaking presentation, while preserving the capture stream and peer. Keep the 512-sample analyser and 50 ms cadence unless audio validation justifies changing them.
|
||||
|
||||
## Audio and screen sharing
|
||||
|
||||
The compatibility voice path captures 48 kHz mono PCM using an AudioWorklet, with a ScriptProcessor fallback. The browser assembles 960-sample, 20 ms frames and sends 1,920-byte Int16 payloads over WebSocket. The gateway encodes them as Opus for TeamSpeak. Incoming Opus uses a three-byte header containing codec and client ID, then browser WebCodecs decoding and playback.
|
||||
|
||||
When enabled by the administrator, WebRTC provides a separate voice transport between the browser and gateway. The gateway uses `werift` and mixes incoming TeamSpeak speakers for WebRTC playback. Negotiation failures can fall back to the compatibility path. Keep microphone mute, per-member volume and playback behavior consistent across both transports.
|
||||
|
||||
Screen sharing has its own peer connections. The gateway coordinates stream membership and SDP/ICE signaling between browsers and supported TeamSpeak 6 clients. Screen media travels directly or through an externally configured TURN server; the WebSpeak gateway does not carry screen media.
|
||||
|
||||
Preserve bounded audio buffering and stale-playback recovery. Audio counters stay in memory and are exposed in session diagnostics. Do not add per-frame persistent logging to the voice path.
|
||||
|
||||
Remote playback owns each speaker's decoder, gain and source nodes as one resource set. Member departure, decoder failure and session teardown release that set; queued callbacks must not touch its replacement. Preserve the 80 ms playback window and three-frame decoder queue threshold unless audio validation justifies changing them.
|
||||
|
||||
Microphone recording tests own their recorder, timeout and object URL, while the capture layer owns the microphone stream. A normal stop may publish its final recording; replacement and session teardown discard late results and revoke the old URL. Stopping a test while connected must preserve room capture. Test cancellation and stale permission failures must not change a newer test's state.
|
||||
|
||||
Device and noise-suppression changes share one configuration operation. Persist only the last successful settings; stale failures cannot roll back a newer choice. Acquiring a replacement microphone must preserve the current WebRTC peer and compatibility PCM capture until the replacement is ready. Capture callbacks are invalidated when their graph stops, separately from permission-request generations. Closing settings also releases standalone device-preview capture when no recording was started.
|
||||
|
||||
Prepare microphone nodes and streams before replacing the live graph. A failed allocation or delayed worklet load must leave the old capture usable. Aborting preparation releases its candidate resources immediately; only activation enables PCM callbacks. Worklet module caches belong to their AudioContext. Device removal uses the normal input/output configuration transactions, including WebRTC restart and rollback on failed default-device selection. A committed graph becomes the fallback preference before subsequent device enumeration completes.
|
||||
|
||||
Serialize `setSinkId` on each audio context or media element, since an in-flight browser sink change cannot be cancelled. Bind subsequent work to the original endpoint and current operation; session teardown invalidates queued changes and device enumeration results. If one output endpoint rejects after another changed, attempt to restore the last committed output.
|
||||
|
||||
`src/server/opus-codec.ts` loads the native `@discordjs/opus` implementation for server deployments and `opusscript` for the Android bundle. Dispose codec and media resources at the end of their owning session.
|
||||
|
||||
## Configuration and persistence
|
||||
|
||||
Identity file reads belong to the current selection, text revision and dialog lifetime. New files (including invalid selections), manual edits, closing, entering the room, clearing local data and page disposal retire old results. Parsing owns its submitted draft; only a current result may replace the identity or notify. Preserve the 128 KiB limit, UTF-8/UTF-16 BOM decoding and existing busy-close behavior. The dialog disables submission while a selected file is being read and disables edits while parsing.
|
||||
|
||||
Startup identity restoration must not overwrite a newer import or remember preference. Exports belong to the identity and page that started them; coalesce pending clicks, discard late serialization and release download anchors, URLs and timers independently. Keep codec parsing in the existing identity service and persistence in the page/storage layer.
|
||||
|
||||
Admin requests belong to the login session and feature that started them. Invalidate pending work on authentication changes and page disposal; cancel feature work on management subroute exit. A late 401 must not expire a newer session, and late login or backup results must not navigate or download after disposal. Aborted work is not a user-facing failure. Failed logout preserves the authenticated draft; successful logout or session expiry resets private page state.
|
||||
|
||||
Settings responses merge against the submitted snapshot instead of replacing newer edits. Password and action, and relay token and action, are atomic draft groups. Clear acknowledged secret inputs, retain edits made during the request, merge relay nodes by ID, and do not restore obsolete probe metadata. Serialize skin mutations and prevent duplicate invite actions; cancelling browser work does not undo a server mutation already executed.
|
||||
|
||||
| Source | Purpose |
|
||||
| --- | --- |
|
||||
| SQLite `webspeak.db` | Admin credentials, target and access settings, relay nodes, invitations, audit records and visitor metadata |
|
||||
| `master.key` beside the database | Encryption key for persisted secrets; retain it with database backups |
|
||||
| `/admin` | Normal configuration and operational controls |
|
||||
| Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings |
|
||||
| `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` |
|
||||
| `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup |
|
||||
| Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings |
|
||||
| Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state |
|
||||
|
||||
The current SQLite schema version is defined in `src/persistence/database.ts`. Keep schema migrations separate from structural refactors. Legacy fields such as `voiceToken`, `tsApiKey`, `tsQueryPort`, `port` and `maxClients` do not configure the current gateway.
|
||||
|
||||
The gateway HTTP port is `3040`. Its admission ceiling is `100` sessions, defined in `src/constants.ts`; this is an application limit, not a TeamSpeak license allowance or a measured performance guarantee. Target server capacity and permissions still apply.
|
||||
|
||||
The server uses HTTPS when `certs/cert.pem` and `certs/key.pem` are supplied; otherwise it starts HTTP. It does not generate certificates. Use an appropriate secure browser origin for microphone and screen capture, typically HTTPS in public deployments. Feature support depends on the browser and selected transport; do not infer a universal minimum browser version from WebCodecs alone.
|
||||
|
||||
## Development and verification
|
||||
|
||||
Server deployments require Node.js 22.5 or newer. CI uses Node.js 22.22.2. Root and frontend dependencies are installed separately. The pinned Git SDK and native Opus module require the preparation steps used by CI:
|
||||
|
||||
```sh
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
npm run verify
|
||||
```
|
||||
|
||||
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
|
||||
- Frontend captures PCM via `ScriptProcessorNode`, sends as 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
|
||||
- Channel/member list fetched via TS6 WebQuery HTTP API (port 10080, requires API key)
|
||||
- WebSocket text frames = JSON commands, binary frames = PCM audio / Opus relay
|
||||
`npm run verify` runs unit tests, the backend build and `npm run web:build`. The latter delegates to the frontend build, including `vue-tsc --noEmit`. Use `npm run dev` and `npm run web:dev` for development, or `npm start` after building both applications.
|
||||
|
||||
## Project Structure
|
||||
Headless Vue tests use Vite middleware mode with both HMR and the WebSocket listener disabled (`hmr: false`, `ws: false`). Disabling HMR alone still reserves Vite's default socket port and causes parallel test processes to conflict.
|
||||
|
||||
```
|
||||
web/ # Vue 3 + Vite frontend (SPA)
|
||||
src/composables/useVoiceWebSocket.ts # Mic capture, VOX/PTT, playback, WS client
|
||||
src/views/WebClient.vue # Connect form + channel/member tree
|
||||
src/
|
||||
index.ts # Entry point, config loading, server startup
|
||||
config.ts # AppConfig interface + load/save
|
||||
logger.ts # Pino wrapper
|
||||
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
|
||||
```
|
||||
CI verifies pushes to `dev` and `master`, pull requests and manual runs. Docker publication on `master` or release tags, and release packaging on tags or manual runs, call the same verification workflow before publishing or packaging. Verification includes the application checks and a Docker HTTP health smoke test; that smoke test does not prove voice or screen-sharing functionality.
|
||||
|
||||
## Key Technical Details
|
||||
Tests requiring a real TeamSpeak server, browser media devices or Android hardware must document their environment and outcome separately. Never substitute a mock codec or an HTTP health response for a successful audio test.
|
||||
|
||||
### Audio Pipeline
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
|
||||
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)`
|
||||
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
|
||||
## Android preview
|
||||
|
||||
### CJS Interop
|
||||
`@discordjs/opus` is CommonJS, loaded via:
|
||||
```ts
|
||||
import { createRequire } from "node:module";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus");
|
||||
```
|
||||
The Android app starts an embedded Node.js gateway on `127.0.0.1:3040` and opens it in the WebView. This preview disables gateway WebRTC voice and the admin console, while reusing the compatibility voice path. Its dependencies and runtime differ from server deployments.
|
||||
|
||||
### WebSocket Message Routing
|
||||
- Text frames → JSON commands (`listChannels`, `switchChannel`)
|
||||
- Binary frames → PCM audio (browser→server) or Opus frames (server→browser)
|
||||
- JSON detection: `typeof data === "string"` first, then fallback `data[0] === 0x7b` with try/catch
|
||||
See `mobile/README.md` for build steps and recorded limitations. The embedded Node.js version, SDK compatibility, real-device connections, background audio and native screen sharing require their own validation. Do not present these capabilities as production-ready based on desktop tests.
|
||||
|
||||
### Event Handlers
|
||||
Must be registered BEFORE `tsClient.connect()` because `clientEnter`/`clientLeave` fire during handshake.
|
||||
Platform startup owns its message listener, polling interval and deadline, including slow listener registration. Release them on success, failure, timeout and page exit. The retry button repeats the readiness handshake; it does not restart the embedded Node.js runtime.
|
||||
|
||||
### Channel List
|
||||
Uses TS6 WebQuery HTTP API (`http://tsHost:tsQueryPort/1/channellist`) with `x-api-key` header. Falls back empty if `tsApiKey` not configured. Regular TS3 voice clients lack permission for `listChannels`/`listClients`.
|
||||
## Repository maintenance
|
||||
|
||||
### Config (config.json)
|
||||
```json
|
||||
{
|
||||
"port": 3040, "tsHost": "127.0.0.1", "tsPort": 9987,
|
||||
"tsQueryPort": 10080, "tsServerProtocol": "ts6",
|
||||
"tsApiKey": "", "voiceToken": "change-me", "maxClients": 10
|
||||
}
|
||||
```
|
||||
Routes load their page modules on demand. Document-level page styles must be gated by `html[data-ws-route]` because loaded CSS remains after navigation. The admin stylesheet is independent of public skins. Component extraction must retain `data-ws-part` hooks and account for Vue scoped styles across component boundaries.
|
||||
|
||||
## Build & Deploy
|
||||
```bash
|
||||
npm install && cd web && npm install && npx vite build && cd .. && npx tsc
|
||||
node dist/index.js
|
||||
```
|
||||
The identity dialog retains page-owned CSS with narrowly targeted `:deep` selectors so the existing declaration order and specificity remain intact. Shared button rules target its dedicated classes across the component boundary. Its close button is positioned within the modal. Public skin-contract tests include Vue files recursively under `components/web-client`; keep new public parts documented.
|
||||
|
||||
## Git
|
||||
- Remote: `https://github.com/EchoSixHIYA/web-client-for-TeamSpeak`
|
||||
- `webspeak-update.tar.gz` is in .gitignore (deployment artifact)
|
||||
- No secrets in source; config.json is gitignored
|
||||
The public join form uses explicit named field models and emits page actions. The chat panel receives a presentation subset of the single page-owned chat controller; keep its list ref bound to the rendered scroller so tab changes and new messages retain automatic scrolling. Form grid columns must allow shrinking, and narrow identity/relay controls must wrap without clipping translated text.
|
||||
|
||||
## Known Limitations
|
||||
- Browser must be Chrome/Edge 94+ (WebCodecs AudioDecoder)
|
||||
- HTTPS required (self-signed cert OK, generated in `certs/`)
|
||||
- Max 32 concurrent users (TS3 license limit)
|
||||
- `tsApiKey` required for channel list; voice works without it
|
||||
The member panel and actions menu also share one page-owned member controller. The panel exposes an audio-dock slot; menu placement uses measured viewport bounds, converts through the page CSS zoom, and releases its resize observer/listener on unmount. Only desktop may open the move submenu on hover: mobile bottom-anchored menus change position when expanded and must open on click to avoid moving a member accidentally. Constrain short-window menus and allow scrolling.
|
||||
|
||||
Voice member cards receive the current channel projection, speaking/avatar helpers and a narrow sharing interface. Keep the sharing refs stable; member menus and stop-sharing actions return to the page through events. Empty, self, speaking, starting, sharing and viewing states must retain their skin hooks and mobile behavior.
|
||||
|
||||
Voice diagnostics and screen-sharing presentation also reuse page-owned controllers. Bind the player and video with explicit element callbacks. Rebind an existing stream when its video element changes, clear the previous element, and never stop the media owner's tracks during presentation cleanup. Fullscreen requires a non-null owned player; removing it exits only its own fullscreen. Known screen owner IDs take precedence over nickname fallback, including duplicate nicknames. Sharing settings use the common dialog focus handling.
|
||||
|
||||
The audio dock and whisper strip share the page-owned audio controller. Push-to-talk belongs to one primary pointer or one Space/Enter press; unrelated releases and key repeats must not change it. Failed pointer capture must not enable whispering. Clear ownership before releasing capture, and stop on blur, hidden controls/pages and disposal. The whisper component owns and releases its window/document listeners; keep media state in the voice layer.
|
||||
|
||||
Audio settings and password dialogs retain one page-owned media/connection state. Dialog focus supports initial focus, Tab cycling, Escape and return to the opener, with a connect-button fallback after pending connections disable that opener. Settings error feedback belongs to the current opening and latest request; closing synchronously stops recording tests, and scope disposal retires pending feedback and stops tests too. A non-password channel error must release the password dialog's pending state and preserve its draft for retry; reject duplicate submissions while pending.
|
||||
|
||||
Admin presentation components receive stable feature controllers; do not instantiate duplicate controllers in children. The welcome-language model remains page-owned and the skin file input belongs to its presentation component. Feature CSS crosses these boundaries with `:deep`, while shell and language-control selectors retain their existing scope. On narrow screens the brand and logout occupy the first row and all four navigation links share a separate row with at least 44 px high targets.
|
||||
|
||||
Keep each repair batch tied to its current plan item. Combine related fixes before running the full verification command; use focused checks during diagnosis and repeat the full suite only when subsequent changes or failures warrant it.
|
||||
|
||||
Keep template/CSS formatting separate from behavior changes. Preserve inline whitespace text nodes when wrapping Vue tags; compare compiled render output when needed. CSS formatting must retain selector meaning, values and declaration/rule order. Layout assertions should tolerate formatting whitespace while still checking the intended rules and values.
|
||||
|
||||
Public skin activation is last-choice-owned across both public pages. Retire previous runtime work before preparing a replacement, and reject results after page disposal, a newer choice or local-data reset. Check ownership before modifying document styles, selected content, asset URLs or stored preferences. An already aborted caller must not cancel a newer page's activation. Release compiled candidate URLs on failed installation.
|
||||
|
||||
Skin initialization has an 8-second total deadline covering preference reads, directory fetch and body, package loading and activation. Network stages also have bounded standalone operations. A timeout reveals a usable built-in palette and retires late work; retain the explicit skin choice for a later retry. Normal initialization still respects the enabled instance default unless the visitor made a deliberate choice. Home and demo use the same controller; do not restore duplicate unguarded refresh paths.
|
||||
|
||||
Skin cache writes and preference persistence accept the owning AbortSignal, including while waiting for IndexedDB to open and during its write transaction. Report storage success at transaction completion. Merge preferences within one transaction so concurrent unrelated settings are preserved. Cancellation of optional persistence must never block page use.
|
||||
|
||||
Validate admin responses before applying them to page state. Network and protocol failures must preserve unsaved input; a failed logout must not be presented as a successful logout. Keep secret keep/replace/remove actions intact and do not persist credentials in UI error messages or diagnostic logs.
|
||||
|
||||
The repository remote is `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak`. Preserve existing local work when implementing the plan in `docs/CODE_REFACTOR_PLAN.zh-CN.md`. Keep private configuration, runtime data and local deployment archives out of source commits. Preserve documented skin hooks and browser persistence formats during component refactors.
|
||||
@@ -0,0 +1,46 @@
|
||||
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 run web: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 iputils-ping \
|
||||
&& 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
|
||||
COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./scripts/docker-healthcheck.mjs
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
@@ -1,354 +1,97 @@
|
||||
# WebSpeak
|
||||
<div align="center">
|
||||
<a id="readme-top"></a>
|
||||
|
||||
TeamSpeak 浏览器客户端:在服务器上运行 Node.js 服务,用户无需安装 TeamSpeak 客户端,即可通过浏览器加入语音频道。
|
||||
<img src="./image.png" alt="WebSpeak 项目横幅" width="100%" />
|
||||
|
||||
[English](#english) · [中文](#中文) · [AGPL-3.0 License](LICENSE)
|
||||
<h1>WebSpeak</h1>
|
||||
|
||||
## English
|
||||
<p><strong>让 TeamSpeak 自然地进入浏览器。</strong></p>
|
||||
<p>A self-hosted browser voice client for TeamSpeak 3 and TeamSpeak 6.</p>
|
||||
|
||||
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.
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
|
||||
[](./LICENSE)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
|
||||
<br />
|
||||
[](https://www.teamspeak.com/)
|
||||
[](https://nodejs.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
|
||||
|
||||
### Highlights
|
||||
<p>
|
||||
<a href="./docs/README.zh-CN.md">简体中文文档</a> ·
|
||||
<a href="./docs/README.en.md">English documentation</a> ·
|
||||
<a href="./docs/README.de.md">Deutsche Dokumentation</a> ·
|
||||
<a href="./docs/README.ru.md">Русская документация</a> ·
|
||||
<a href="./docs/README.ja.md">日本語ドキュメント</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
- 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
|
||||
## 项目简介 · Overview
|
||||
|
||||
### Requirements
|
||||
| 逻辑 | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| **WHAT** | WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。 | WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. |
|
||||
| **WHY** | 无需安装桌面客户端,用户打开网页即可加入频道;部署者仍然掌控目标服务器、访问策略和数据。 | Users can join a voice channel from a browser without installing a desktop client, while the operator keeps control of servers, access, and data. |
|
||||
| **HOW** | 部署后在管理员控制台配置 TeamSpeak 目标和访问方式,浏览器负责交互与音频,WebSpeak 负责网关连接。 | Configure the TeamSpeak target and access policy in the administration console. The browser handles interaction and audio; WebSpeak provides the gateway connection. |
|
||||
|
||||
- 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
|
||||
## 文档 · Documentation
|
||||
|
||||
### How it works
|
||||
- [简体中文](./docs/README.zh-CN.md)
|
||||
- [English](./docs/README.en.md)
|
||||
- [Deutsch](./docs/README.de.md)
|
||||
- [Русский](./docs/README.ru.md)
|
||||
- [日本語](./docs/README.ja.md)
|
||||
- [皮肤开发规范](./docs/SKIN_DEVELOPMENT.md)
|
||||
- [WebSpeak 皮肤开发 Agent Skill](./.agents/skills/webspeak-skin-development/SKILL.md)
|
||||
|
||||
```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 │
|
||||
└──────────────────────┘
|
||||
```
|
||||
## 社区 · Community
|
||||
|
||||
### Quick start
|
||||
<div align="center">
|
||||
|
||||
#### 1. Install dependencies
|
||||
<a href="http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475">
|
||||
<img src="./web/public/qq-group-qr.jpg" alt="WebSpeak QQ 群二维码" width="290" />
|
||||
</a>
|
||||
|
||||
```bash
|
||||
# Native build tools are required by @discordjs/opus.
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential python3
|
||||
**QQ群 / QQ group:`869500475`**
|
||||
|
||||
npm install
|
||||
npm --prefix web install
|
||||
```
|
||||
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
|
||||
On Windows, install Visual Studio Build Tools with **Desktop development with C++** before running `npm install`.
|
||||
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
|
||||
`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.
|
||||
</div>
|
||||
|
||||
#### 2. Build
|
||||
## 友链项目 · Friend projects
|
||||
|
||||
```bash
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
```
|
||||
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
|
||||
|
||||
The build output is written to `web/dist/` and `dist/`.
|
||||
面向 TeamSpeak 3/6 的多平台音乐点播机器人,支持网易云音乐、QQ 音乐和 Bilibili 音频播放,并提供 Web 控制台。<br />
|
||||
A multi-platform music bot for TeamSpeak 3/6 with Netease Cloud Music, QQ Music, and Bilibili playback, plus a web console.<br />
|
||||
Ein plattformübergreifender Musikbot für TeamSpeak 3/6 mit Netease Cloud Music, QQ Music und Bilibili sowie Webkonsole.
|
||||
|
||||
#### 3. Configure `config.json`
|
||||
## Contributors · 贡献者
|
||||
|
||||
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.
|
||||
感谢提交 PR 的贡献者:
|
||||
|
||||
```json
|
||||
{
|
||||
"port": 3040,
|
||||
"tsHost": "127.0.0.1",
|
||||
"tsPort": 9987,
|
||||
"tsServerPassword": "",
|
||||
"tsServerProtocol": "ts6",
|
||||
"maxClients": 20,
|
||||
"trustProxy": false
|
||||
}
|
||||
```
|
||||
- [LainHE](https://github.com/LainHE) — [PR #2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/2):浏览器端报错翻译与提示改造。
|
||||
|
||||
| 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. |
|
||||
## 许可证 · License · Lizenz · Лицензия · ライセンス
|
||||
|
||||
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 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
|
||||
|
||||
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.
|
||||
WebSpeak is released under the [GNU Affero General Public License v3.0 only](./LICENSE). If a modified version is offered to users over a network, its corresponding source code must be offered under AGPL-3.0.
|
||||
|
||||
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.
|
||||
WebSpeak wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
|
||||
|
||||
#### 4. Enable HTTPS
|
||||
WebSpeak распространяется по лицензии [GNU Affero General Public License v3.0 only](./LICENSE). Если изменённая версия предоставляется пользователям через сеть, соответствующий исходный код должен быть доступен этим пользователям на условиях AGPL-3.0.
|
||||
|
||||
WebSpeak automatically serves HTTPS when `certs/cert.pem` and `certs/key.pem` exist:
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](./LICENSE) の下で公開されています。変更版をネットワーク経由でユーザーに提供する場合は、対応するソースコードを AGPL-3.0 に従ってユーザーに提供する必要があります。
|
||||
|
||||
```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"
|
||||
```
|
||||
## Star History
|
||||
|
||||
For public use, prefer a trusted certificate from Let's Encrypt or terminate TLS at Nginx. Do not commit private keys to Git.
|
||||
<a href="https://star-history.com/#EchoSixHIYA/WebSpeak-client-for-TeamSpeak&Date">
|
||||
<img src="https://api.star-history.com/svg?repos=EchoSixHIYA/WebSpeak-client-for-TeamSpeak&type=Date" alt="WebSpeak Star History" width="100%" />
|
||||
</a>
|
||||
|
||||
#### 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.
|
||||
|
||||
## 中文
|
||||
|
||||
WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端。服务运行在服务器上,用户无需安装 TeamSpeak 客户端,打开网页即可加入语音频道。每个网页用户拥有独立的 TeamSpeak 连接,并使用自己的可见频道和成员信息。
|
||||
|
||||
### 主要功能
|
||||
|
||||
- 低延迟 PCM/Opus 语音转发
|
||||
- 自由麦(VOX)与空格键按键说话
|
||||
- 枚举并切换浏览器真实麦克风设备
|
||||
- 频道切换与完整频道/成员树,空频道也会显示
|
||||
- 为每个成员单独调整播放音量
|
||||
- 正在发言的成员头像实时显示绿色边框
|
||||
- 文字聊天、邀请链接分享、中英文界面切换
|
||||
- 不依赖 WebQuery/SSH Query,不使用邀请 token
|
||||
- 网页端直接设置 TeamSpeak 地址和语音端口
|
||||
- 不需要浏览器插件或桌面版 TeamSpeak 客户端
|
||||
|
||||
### 环境要求
|
||||
|
||||
- 推荐 Linux 服务器,也支持 Windows
|
||||
- Node.js 22 或更高版本
|
||||
- 可访问的 TeamSpeak 3 或 TeamSpeak 6 服务器
|
||||
- 较新的 Chrome 或 Edge 浏览器
|
||||
- 生产环境使用 HTTPS;浏览器麦克风和 WebCodecs 都要求安全上下文
|
||||
|
||||
### 快速开始
|
||||
|
||||
```bash
|
||||
# Ubuntu/Debian
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential python3
|
||||
|
||||
# 安装服务端和前端依赖
|
||||
npm install
|
||||
npm --prefix web install
|
||||
|
||||
# 构建前端和后端
|
||||
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
|
||||
```
|
||||
|
||||
访问:
|
||||
|
||||
```text
|
||||
https://你的域名或IP:3040/
|
||||
```
|
||||
|
||||
在页面中填写 TeamSpeak 地址、语音端口和昵称。首次使用时允许浏览器访问麦克风。进入语音空间后,打开“音频设置”即可选择具体麦克风、调整输入/输出音量并进行真实麦克风电平测试。
|
||||
|
||||
连接后的控制项统一放在顶部,不再遮挡聊天区域;“自由麦”和“按键说话”可以在“音频设置”中切换。
|
||||
|
||||
### 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`。
|
||||
|
||||
### 开发命令
|
||||
|
||||
```bash
|
||||
# 前端热更新
|
||||
npm run web:dev
|
||||
|
||||
# 前端类型检查并构建
|
||||
npm --prefix web run build
|
||||
|
||||
# 后端 TypeScript 构建
|
||||
npm run build
|
||||
```
|
||||
|
||||
请不要在 Issue 或 Pull Request 中提交 `config.json`、API 密钥、证书、私钥或服务器日志。
|
||||
|
||||
### 许可证
|
||||
|
||||
本项目仅按 [GNU Affero General Public License v3.0](LICENSE)(`AGPL-3.0-only`)授权。如果你将修改版作为网络服务运行,必须按照许可证要求向服务用户提供对应源代码。
|
||||
|
||||
如果 WebSpeak 对你有帮助,欢迎在 GitHub 点一个 Star。维护者:[EchoSixHIYA](https://github.com/EchoSixHIYA)。
|
||||
|
||||
### 加入交流群
|
||||
|
||||
扫描下方二维码加入群聊(群号:`869500475`):
|
||||
|
||||

|
||||
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
|
||||
@@ -1,9 +1,5 @@
|
||||
{
|
||||
"port": 3040,
|
||||
"tsHost": "127.0.0.1",
|
||||
"tsPort": 9987,
|
||||
"tsServerPassword": "",
|
||||
"tsServerProtocol": "ts6",
|
||||
"maxClients": 20,
|
||||
"trustProxy": false
|
||||
"tsServerPassword": ""
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
services:
|
||||
webspeak:
|
||||
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
|
||||
pull_policy: missing
|
||||
restart: unless-stopped
|
||||
# WebSpeak needs to reach a TeamSpeak server running on the same host.
|
||||
# Host networking also exposes the configured WebRTC UDP range directly.
|
||||
network_mode: host
|
||||
volumes:
|
||||
- webspeak-data:/data
|
||||
|
||||
volumes:
|
||||
webspeak-data:
|
||||
@@ -0,0 +1,801 @@
|
||||
# WebSpeak 代码待修改清单与修改方向
|
||||
|
||||
本文聚焦 `webspeak-webclient`,记录代码结构、修复方向与实施结果。2026 年 10 月 3 日按用户地址 `<TS3_TEST_HOST>:9987` 成功连接 TeamSpeak 3.13.8 / Linux,完成真实目录、私聊、状态及 PCM/WebRTC 媒体链路检查,并修复麦克风静音时伴奏被 TeamSpeak 丢弃、WebRTC 下行编码器状态不连续导致音量衰减的问题。上海 TS6 节点恢复后,已补验消息、媒体及共享信令,并修复状态恢复与共享清理问题。Android 已按用户要求移出本轮修复计划。用户随后明确跳过剩余设备、原生交互和旧版本验收;按调整后的范围,本轮施工已完成。跳过项保留未验收状态,不认定为已通过。
|
||||
|
||||
按用户要求,每批仅处理当前节点相关问题,合并相关修复后统一验证,不扩展到无关模块。管理页主要交互与布局已检查,原生确认框阻塞的操作验收单独保留。加入、聊天、频道成员、成员菜单、音频设置及密码弹窗已拆分;音频工具栏、私语控制条、语音诊断、共享设置与播放器已提取,语音活动成员卡片也已提取。06-L 的保序格式整理及两份页面样式确认冗余项已完成。真实消息与 TeamSpeak 媒体按已取得的证据记录范围;Android 既有结果仅作历史记录,不作为当前完成门槛。媒体、连接、命令、诊断、消息、身份及公共皮肤状态已有独立模块,继续复用。当前完成状态和跳过项放在前部,历史修复及验证记录保留在后部。
|
||||
|
||||
## 范围与依据
|
||||
|
||||
- 最新环境更新:用户确认上海节点恢复后,`<TS6_TEST_HOST>:9987` 实测为 TeamSpeak `6.0.0-beta13.1` / Linux,已补充下述 TS6 消息、媒体及静音恢复验收。此前旧 IP 超时仅作为历史记录,不再阻止该节点测试;`<TS3_TEST_HOST>:9987` 的 TS3 结果仍保留。
|
||||
- 记录日期:2026 年 10 月 3 日。
|
||||
- 当前代码基线:`dev` 分支,`50d71891034736d32a1accea94d13be91c8a3003`;应用版本 `0.2.5-preview`。本次收尾仅更新本文,不修改实现。
|
||||
- 最后一批代码修复覆盖 02-C TS6 共享清理参数及命令确认,新增 7 项回归。合并修改后一次 `npm run verify` 通过 434 项测试及前后端构建。该提交远端 CI 的 verify 与 docker-smoke 均成功,含 Docker 构建及健康检查([运行 37103379056](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/37103379056))。文档收尾不重复运行全量验证。
|
||||
- `6aa19c4` 的 CI、Docker 构建和健康检查已确认成功(运行 36896144974)。此前 `662dad3` 的手动发布工作流完整验证、Windows/Linux 打包启动及 Docker 健康检查通过(运行 36857782727);这些结果保留各自验证范围。
|
||||
- 既有皮肤修复记录记载新增 23 项测试,以及 `npm run verify` 通过 385 项测试和前后端构建;其中 5 项先复现旧结果覆盖及失效归属问题。这些是此前批次的验证结果,不是本轮重新执行的结果。
|
||||
- Android 从 `662dad3` 源码归档重新安装三套依赖并重建 SDK,在短路径完成 android:sync 和 assembleDebug,134 个 Gradle 任务执行,三个 ABI 包内容及 SHA-256 已检查。首次深层目录因原生工具路径限制失败,短路径重建通过;没有把构建成功写成设备或媒体验收。
|
||||
- 各平台构建环境、执行范围、Actions 归档摘要与本机 APK 校验和见 `docs/LOCAL_ARTIFACTS.zh-CN.md`。`662dad3` 的 x86_64 新包已在只读 Android 15 模拟器安装并冷启动,内嵌网关返回正确健康状态和版本;Android 布局复验仍待可交互环境。
|
||||
- 下文“代码可确认”指控制流或配置可直接支持的判断;具体故障发生条件仍需回归用例验证。“待验收”表示证据尚缺,不等于已发生故障。P1/P2/P3 表示建议实施顺序,不代表安全漏洞等级。
|
||||
- 后文身份、消息、媒体、皮肤等“实施记录”属于此前批次;其中“本批”指各记录对应的历史批次。当前待办以本页前部状态表为准。
|
||||
|
||||
## 当前代码结构
|
||||
|
||||
| 部分 | 主要位置 | 当前职责及整理判断 |
|
||||
| --- | --- | --- |
|
||||
| 启动与 HTTP | `src/index.ts`、`src/server/server.ts` | 网关启动、公共配置、加入凭证、管理路由与静态页面 |
|
||||
| 实时会话 | `src/server/voice-bridge.ts`、`session-manager.ts` | 接入、独立 TeamSpeak 客户端、连接恢复、会话终止及模块组装;桥接入口 782 行 |
|
||||
| 服务端会话子模块 | `session-audio.ts`、`session-events.ts`、`member-avatars.ts` | 音频转发、SDK 监听与目录编排、头像批次和生命周期均已提取 |
|
||||
| SDK 与媒体 | `ts-client.ts`、`teamspeak-adapter.ts`、`webrtc-audio.ts`、`opus-codec.ts` | SDK 连接及事件适配、WebRTC 混音、平台编解码 |
|
||||
| 共享契约 | `src/shared/` | 命令、服务端消息、WebRTC、屏幕共享、皮肤和管理请求与响应;后续复用现有模型 |
|
||||
| 管理与持久化 | `src/admin/`、`src/security/`、`src/persistence/` | 登录、配置、邀请、审计、访问策略与 SQLite |
|
||||
| 前端语音入口 | `web/src/composables/useVoiceWebSocket.ts` | 1,468 行;保留媒体组装、连接状态及业务动作,委托媒体、连接、命令、诊断和消息投影 |
|
||||
| 浏览器媒体模块 | `web/src/voice/` | 已有屏幕共享、远端播放、麦克风采集、录音测试、输出设备切换、伴奏、输入混音及电平监测;WebRTC 传输 194 行、播放 114 行 |
|
||||
| 浏览器连接与命令 | `web/src/voice/connection.ts`、`commands.ts` | 连接模块 132 行,拥有请求取消、期限、socket 与代次;命令模块 59 行,拥有确认等待及统一收尾 |
|
||||
| 浏览器诊断 | `web/src/voice/audio-diagnostics.ts`、`web/src/composables/useWebClientPerformance.ts` | 采样模块 168 行,拥有等待、来源范围与兼容计数;面板 composable 管理轮询和可比样本的展示 |
|
||||
| 会话消息状态 | `web/src/voice/session-state.ts` | 172 行;拥有成员与频道、聊天历史、事件、通知、会话范围和私聊身份映射 |
|
||||
| 页面与业务状态 | `web/src/views/`、`web/src/composables/` | 格式展开后主页面 1,337 行,管理页 580 行;聊天 composable 管理按会话和对象隔离的草稿、发送等待及反馈 |
|
||||
| 管理展示组件 | `web/src/components/admin/` | 格式展开后服务器设置 415 行、运维 326 行、皮肤 187 行;状态仍由父页创建,主要表单与路由交互已验收 |
|
||||
| 身份导入与导出 | `useWebClientIdentity.ts`、`components/web-client/IdentityImportDialog.vue` | 159 行状态模块与 151 行展示组件;异步操作、启动恢复与导出资源独立归属 |
|
||||
| 前端基础服务 | `web/src/services/`、`web/src/i18n/`、`web/src/skins/` | 请求、浏览器存储、身份导入、主题、皮肤及多语言;皮肤运行时的提交受取消和期限保护 |
|
||||
| 公共皮肤状态 | `usePublicSkin.ts`、`skin-operation.ts` | 104 行共享页面控制器与 38 行等待控制;管理初始化、选择、失效、回退和 8 秒期限 |
|
||||
| Android | `web/src/platform/`、`src/mobile/`、`mobile/`、`web/android/` | 本机网关就绪握手、移动打包和原生容器;运行时与设备验收独立 |
|
||||
| 独立中继 | `src/relay.ts`、`src/server/acceleration-relay.ts` | 中继进程及网关接入,本轮不扩展其功能 |
|
||||
|
||||
主链路为:浏览器申请一次性加入凭证,经 `/ws/voice` 建立网关会话,网关创建独立 TeamSpeak 客户端。WebSocket 承载控制消息和兼容音频;启用 WebRTC 时语音走另一条媒体通道。屏幕共享使用独立连接,由网关协调参与者及信令。
|
||||
|
||||
文件行数包含空行,仅用于定位职责集中处;“文件变短”不是验收标准。
|
||||
|
||||
## 完成状态与本轮跳过项
|
||||
|
||||
沿用原清单编号:06-H、06-I、06-J 已有身份与皮肤修复;06-K 管理导航已修复;06-C 展示拆分及主要交互已完成;06-L 格式及确认冗余项清理已完成。2026 年 10 月 3 日,用户明确要求“跳过这些内容”,以下剩余验收从本轮完成条件移除,不再等待环境或版本答复。按调整后的范围,本轮无剩余施工项;下表只保留未验收边界,已完成事项另列。
|
||||
|
||||
| 编号 | 本轮状态 | 保留的未验收边界 |
|
||||
| --- | --- | --- |
|
||||
| 06-C 客户端验收 | 按用户要求跳过 | 真实触屏拖动、原生离开/戳人输入框的操作及取消流程 |
|
||||
| 06-C 管理页 | 按用户要求跳过 | 原生确认框的移除、断开会话及取消流程;此前工具超时记录保留 |
|
||||
| 03 | 按用户要求跳过 | 真实旧客户端/旧网关版本矩阵;现有 TS3/TS6 消息和旧格式请求结果不代表旧应用整体通过 |
|
||||
| 02-C | 按用户要求跳过剩余验收 | 真实麦克风、扬声器、屏幕采集、完整音质、浏览器自动回退及官方 TS6 客户端视频共享;已完成的实服和合成端点结果保留其实际范围 |
|
||||
|
||||
当前范围调整:07-A 全部 Android 运行时、真机和媒体事项,以及 09-A 的 Android 布局复验,按用户要求暂不纳入本轮修复和完成条件。已有 Android 构建及启动记录保留,不认定为这些剩余能力已通过。09-A 在本轮保留的 Windows/Linux/Docker 干净构建与启动要求已完成。
|
||||
|
||||
以下实施过程、原修改方向和历史记录中的“待验收”“仍待完成”“继续”等描述,保留当时的验证边界;涉及上述跳过项时,不构成本轮新的待办。以后只有用户重新纳入范围才继续这些验收。
|
||||
|
||||
### 旧 IP 连接记录(2026-10-02,已由域名端点替代)
|
||||
|
||||
- 用户给出的 HTTP 形式链接按 TeamSpeak 地址 `<TS6_TEST_HOST>:9987` 使用;连接走 SDK 的 UDP 客户端协议,没有把 HTTP 探测当作 TeamSpeak 连通证据。
|
||||
- 使用当前源码的 `TSClient`、锁文件 SDK 和临时测试身份,不读取或修改真实配置、密码或持久身份。第一次连接返回 `timeout / TeamSpeak connection timed out`,随后正常断开。
|
||||
- 第二次在相同实际连接外增加只计数的 UDP 诊断:发起 15 次发送、510 字节,从该服务器收到 0 个数据报、0 字节,未收到 socket error 事件;同样超时并清理连接。这是进程级发送/接收记录,不是网卡抓包证据。
|
||||
- 两次均未取得已认证会话、服务器版本或目录,未发送聊天、戳人或音频。当前只能确认本机未获得协议响应,不能区分服务端状态、网络路径或协议响应原因;待确认公网 UDP 端口及接入条件后继续该节点。
|
||||
|
||||
### 域名实服与静音伴奏修复(2026-10-03)
|
||||
|
||||
- 通过当前 `TSClient` 和锁定 SDK 连接 `<TS3_TEST_HOST>:9987`,服务器返回 `3.13.8`、build `1779874471`、Linux;初次连接约 7.2 秒,自身目录项存在,正常断开。此前 IP 超时不再作为当前接入阻塞。
|
||||
- 两个临时 WebSocket 客户端经本机实际 `VoiceBridge` 连接远端服务,使用真实原生 Opus,无 SDK/编码器替身。临时身份不写入用户配置;私聊、戳人及私语音频仅发给测试会话。目录互见、带 UID 与省略 UID 的私聊、离开/返回、戳人和非法 PCM 拒绝通过;所见 JSON 消息全部通过共享解析器。
|
||||
- WebRTC 使用本机 werift 合成端点,经真实 ICE/DTLS/SRTP 与网关通信,再通过真实 TeamSpeak 服务到另一测试端。修复后上行 50/50 帧到达;反向 50 帧被网关接收并转发到 WebRTC,输出能解码出测试音频。没有使用浏览器麦克风、扬声器或屏幕采集。
|
||||
- 故障先在实服复现:麦克风静音后开启伴奏,网关发送 30 帧,对端收到 0 帧;仅取消静音后,同一伴奏收到 30 帧。原因是 `client_input_muted=1` 会使服务器丢弃该客户端的全部音频,而网关原本只更新混音器伴奏标志。
|
||||
- SDK 适配层现在分别记录逻辑麦克风静音和伴奏状态,串行提交组合后的 TeamSpeak 输入标志,成功后才更新状态;失败不污染后续更新,旧连接的排队/迟到结果失效。播放伴奏时允许整体输入,浏览器仍将麦克风静音;停止伴奏、WebRTC 停止及协商失败恢复输入状态,初始静音加伴奏也走相同处理。
|
||||
- 修复后静音伴奏和初始静音加伴奏均收到 30/30 帧(codec 5);停止伴奏后再次发送的帧均被抑制,关闭 WebRTC 后其他会话看到输入静音恢复。活动 WebRTC 停止后 PCM 恢复,本次观察收到 48/50 帧。测试会话已全部关闭,本机网关活动计数归零。
|
||||
- 质量边界:WebRTC 下行采样中,50 帧远端输入只有 30 个输出帧达到所设 RMS 门槛;该段网关记录 0 队列丢弃、0 解码错误,不能据此判断连续音质通过,也不能直接把帧数差归为网络丢包。下行解码连续性与混音仍需定位。合成无效 SDP 的尝试得到 answer,没有形成预期失败,因此未记为协商失败回退通过。
|
||||
- 416 项本地统一验证及实服结果覆盖本节点;TS6、旧应用版本、浏览器设备、多人/跨频道共享和原生输入框仍按待办推进,Android 不重新纳入。
|
||||
|
||||
### WebRTC 下行编码连续性修复(2026-10-03)
|
||||
|
||||
- 将前次实服音量异常缩小到实际 `WebRtcAudioSession` 混音器,用手动推进音频时钟排除网络和调度影响;源编码、网关解码和输出解码均使用原生 Opus。旧路径中,50 个语音帧与静音交替时,50 个输出全部低于 RMS 100;同样输入强制重编码后 50 个全部超过门槛。这证明存在独立于网络的代码故障。
|
||||
- 原因是单人且音量为 1 时直接转发源 Opus,静音、音量变化或多人混音则使用网关编码器;同一 RTP 流交替携带不同编码器历史,接收端无法维持连续解码状态。现在全部下行音频通过同一个会话编码器,删除原始 Opus 直通分支;队列、节拍、成员音量和上行路径保持原规则。
|
||||
- 新增 3 项回归覆盖静音间隔、交替说话者和音量变化,每项 50 个活动输出均达到预期电平,解码错误及队列丢弃为 0。本批一次统一验证通过 419 项测试及前后端构建。代价是单人默认音量也需要重编码,增加编码工作和一次有损转换;尚未完成容量压测。
|
||||
- 实服复查使用 `<TS3_TEST_HOST>:9987`、两个临时身份与本机 werift 端点。下行 50 个发送帧中网关收到 46 帧、向混音器提交 46 帧,队列丢弃和上下行解码错误均为 0;解码输出有测试音频。RMS 超门槛输出计数为 70,包含编码尾音,不能解释为 70/50 帧交付或完整音质通过。
|
||||
- 本次整套实服脚本未通过:后续静音伴奏收到 27/30 帧,严格数量断言失败;该段网关入口和 TeamSpeak 发送累计均为 80 帧且发送错误为 0。尚未定位这 3 帧差值发生于哪一段,不能直接归因于网络,也不修改断言掩盖结果。此前 30/30 的结果保留为此前批次记录。所有临时连接已清理,网关活动会话归零。
|
||||
- 当前代码故障及确定性回归已闭环;实服帧差、浏览器设备和完整媒体矩阵继续归 02-C。未扩展到其他模块,也未恢复 Android 待办。
|
||||
|
||||
### 音频分段复查与协商失败回退(2026-10-03)
|
||||
|
||||
- 针对前次伴奏 27/30 的帧差,临时测试进程记录 UDP 发送回调、接收数据报、解密后的音频包序号、SDK 事件和 WebSocket 输出,不修改生产诊断或 SDK。三轮静音伴奏各发送 50 帧,各段计数均为 50,序号分别为 0–49、50–99、100–149,无发送错误或网关输出丢弃;每次停止伴奏后再发送 10 帧均被静音抑制。此次未复现原帧差,不能倒推原故障原因或声称永不丢帧;不继续无差别重复探测。
|
||||
- 继续验收回退时确认:旧网关会对无音频的 `invalid sdp` 返回空 answer,也会协商只包含 PCMU 的真实音频 offer,但收发实现只处理 Opus。PCMU 被排在首位时,werift 发送器还会按首个协商编码标记实际 Opus 数据。这些会形成协商成功但媒体不可用的会话。
|
||||
- 现在将该音频 peer 的能力限定为 Opus,并从实际协商出的音频 transceiver 读取 payload type;未协商到 Opus 时进入现有失败清理和 `WEBRTC_NEGOTIATION_FAILED` 分支。删除扫描整个 SDP 和猜测默认 payload type 的路径;不修改共享信令格式、屏幕共享或其他模块。
|
||||
- 新增 4 项回归:无效 SDP、仅 PCMU、仅 Opus 109、PCMU 优先且 Opus 109。前两项受控失败,后两项 answer 只包含 Opus 109。统一 423 项测试及前后端构建通过。
|
||||
- 实服通过真实 `VoiceBridge` 验证两种失败均返回错误并清除 WebRTC 路由,无需先发送 `webrtcStop` 即可恢复 PCM。无效 SDP 后 50 帧收到 49 帧、RMS 1264;仅 PCMU 且初始静音加伴奏时,失败后 TeamSpeak 输入静音恢复,取消静音后 PCM 收到 50/50 帧、RMS 1259。这证明网关回退可用,不替代浏览器自动采集回退或完整音质验收。
|
||||
- 修改后另用 PCMU 优先、Opus payload type 109 的真实 ICE/DTLS/SRTP 合成端点连接实服:50 个静音伴奏帧从 RTP 入口到对端 WebSocket 全部到达,音频包序号连续;停止伴奏后静音恢复。上述临时会话均关闭,网关活动会话归零。
|
||||
- 已请求明确旧客户端/旧网关版本矩阵及 TS6、设备测试环境;未指定前保留验收缺口,Android 仍排除。此前原生确认框工具阻塞不重复重试。
|
||||
|
||||
### 实服双人混音与成员音量验收(2026-10-03)
|
||||
|
||||
- 当前 `6616d0b` 源码、原生 Opus、三个临时 TeamSpeak 身份连接 `<TS3_TEST_HOST>:9987`。两位发送者通过 WebSocket PCM 同时生成 500 Hz 和 850 Hz 音频,仅私语到第三个测试身份;接收端通过真实 werift ICE/DTLS/SRTP 解码网关混音。未向其他用户发送测试音频,未使用真实麦克风或扬声器。
|
||||
- 默认音量、第一位静音、第一位四分之一音量三组,每组两位各发送 100 帧。网关每组接收并提交混音 200 帧,队列丢弃和解码错误均为 0。持续使用同一个输出解码器,按 850 Hz 分量超过 500 的输出帧选取样本,比较两种频率的幅度中位数。
|
||||
- 默认音量的 500/850 Hz 幅度分别为 1211/1235;第一位静音后为 74/1187;第一位四分之一音量后为 370/1268。两种声音同时存在,单成员静音及衰减不抑制另一位。该频谱抽样只证明本场景的混音与音量控制,不作为精确增益、听感、所有网络条件或容量结论。
|
||||
- 第一次脚本在首组通过后请求统计过快,触发现有 750 毫秒限频并等待超时;只将临时脚本采样间隔调至 1100 毫秒后完成全部场景,没有修改生产限频或放宽断言。全部临时会话已关闭,网关活动会话归零。
|
||||
- 输出中超过频率门槛的帧数大于源帧数,不能用于计算交付率。额外用实际混音器和原生编解码器验证停止输入后的尾音:首个静音 tick 的 RMS 为 726,第二个为 6,第八个起为 0;没有观察到本地持续长尾音。实服节拍中的间隔与编码过渡仍需结合真实设备试听,不能仅以频谱计数宣称完整音质通过。
|
||||
|
||||
### Edge 原生确认框复核及剩余环境缺口(2026-10-03)
|
||||
|
||||
- 本轮浏览器清单出现可连接的 Edge 扩展后,使用独立临时数据库、临时皮肤和模拟会话重新检查管理确认流程。实际管理页登录、皮肤列表展示成功;点击移除时工具输入命令超时,但 `getJsDialog()` 确认弹窗类型为 `confirm`。
|
||||
- 对该弹窗执行 `dismiss()` 后,工具在焦点模拟命令超时,后续读取弹窗和关闭测试标签也超时。不能确认“取消”完整生效,更未执行确认移除或断开会话。只读检查临时后端显示测试皮肤仍存在、模拟会话仍活动,审计仅有初始化、改测试密码和登录记录,没有业务删除记录。
|
||||
- 临时服务进程已终止并确认退出;工具未确认测试标签关闭,不标记为已关闭。没有接触真实管理配置或用户会话,也没有为了工具限制重写原生确认逻辑。内置浏览器与 Edge 均已留下阻塞证据,后续只在工具状态有明确变化或有人工结果时补验。
|
||||
- 现有可自动执行的 TS3 媒体节点已有上述结果;剩余真实麦克风/扬声器及屏幕采集、触屏和原生弹窗流程需要可交互环境。旧应用版本矩阵与 TS6 端点仍等待明确。不能用再跑单元测试或合成音频替代这些验收,也不新增无关修复或容量目标。
|
||||
|
||||
### 上海 TS6 节点恢复与防刷期间静音恢复修复(2026-10-03)
|
||||
|
||||
- 用户确认节点更新后,以当前 SDK 和临时身份连接 `<TS6_TEST_HOST>:9987`,约 290 毫秒取得连接及版本:`6.0.0-beta13.1`、build `1790080330`、Linux,协议识别为 `ts6`;3 个频道、自身目录项存在,探测后正常断开。未修改部署、真实配置或持久身份。
|
||||
- 首轮快速并行验收触发 `FLOOD_PROTECTION`,同时首个 RTC 上行数量断言未通过,不能据此归因于媒体实现。随后将临时脚本的控制命令间隔调为 1 秒、接入后等待 1.5 秒并串行验收;没有更改服务器防刷设置或音频帧节拍。
|
||||
- 消息与 PCM 场景通过:目录互见、带 UID 与省略 UID 的双向私聊、离开/返回、测试身份间戳人、非法 PCM 拒绝;双向 PCM 和停止 WebRTC 后 PCM 均收到 50/50 帧,RMS 分别为 1268、1269、1259。全部实际 JSON 消息通过共享解析器。
|
||||
- WebRTC 使用本机 werift 合成端点和真实 ICE/DTLS/SRTP。上行 50/50 帧到达;反向网关收到并提交 50 帧,队列丢弃和解码错误为 0;输出可解码。麦克风静音阻止音频、静音伴奏及取消静音伴奏各收到 30/30 帧(codec 5);停止伴奏恢复静音,活动 WebRTC 停止后 PCM 收到 50/50 帧。输出 RMS 计数包含编码过渡,不作为交付率。
|
||||
- 第二次以初始静音加伴奏启动后,停止 WebRTC 未恢复对端可见静音。缩小为连续两次启停后稳定复现:第二次 `setAccompanimentActive(false)` 被服务端拒绝,明确返回 `client is flooding (id=524)`,对端仍显示 `inputMuted=false`。单次启停能正常恢复,故不是 TS6 完全不支持该状态。
|
||||
- 输入状态队列现在只跳过已经成功确认且有效静音值不变的上报,同时仍记录逻辑麦克风/伴奏变化;连接重建和失败确认使缓存失效。仅对防刷错误增加最多两次重试,分别等待 1 秒、2 秒;每次重试检查原连接及代次,成功确认后才提交状态,权限等其他错误不重试。持续拒绝仍向调用方返回失败,不无限重试或承诺服务器总能接受。
|
||||
- 新增 4 项回归覆盖相同有效静音值下的逻辑状态、恢复静音时防刷重试、重试上限及后续队列、连接替换后禁止旧重试。统一 427 项测试及前后端构建通过。修改后实服按相同两次启停复查,每次伴奏收到 30/30 帧,停止后对端均显示 `inputMuted=true`,传输返回 WebSocket;全部临时连接清理,活动会话归零。
|
||||
- 本轮解决了 TS6 测试端点缺失和实际发现的输入状态恢复问题。仍未完成 TS6 原生客户端共享、真实浏览器采集/设备试听、触屏及原生弹窗、指定旧应用版本矩阵;不把本轮合成端点结果扩大为这些项目通过。
|
||||
|
||||
### TS6 共享清理参数与服务端确认修复(2026-10-03)
|
||||
|
||||
- 使用上海 `<TS6_TEST_HOST>:9987`、实际 VoiceBridge 网关、独立 SDK 测试身份与两个本机 werift peer,验证网页侧发布经 TS6 通知另一端,加入请求、offer/answer 和 ICE/DTLS/SRTP 建立成功;共享音频收到 30/30 帧,解码 RMS 1270。video transceiver 参与协商,但没有发送视频帧,也未运行官方 TS6 客户端或浏览器屏幕采集。
|
||||
- 原代码在网页移除 TS6 观看者时遗漏 `removeclientfromstream` 的 `reason` 参数,服务器明确返回 `id=1542 / missing required parameter`;本地却立即减少观看者。停止共享又被防刷拒绝(`id=524`),未取得服务端停止通知。根因还包括适配层使用不等待回执的发送方法,使上层无法获知真实拒绝。
|
||||
- 两处移除命令补充 `reason=1`;共享命令等待服务端确认。网页移除原生观看者仅在确认或服务端离开通知后减少计数,拒绝时保留成员并返回现有错误消息;通知早于确认时不重复发送离开事件。仅对 `stopstream` 和 `removeclientfromstream` 的明确防刷拒绝重试,最多两次,等待 4 秒、8 秒;每次检查连接及代次。offer/ICE 和其他错误不重试,停止发布最终失败记入日志。
|
||||
- 新增 7 项回归覆盖等待确认、拒绝传播、清理重试间隔及上限、非清理信令不重放、连接替换失效、移除参数、失败保留成员及通知与确认去重(部分用例覆盖多项)。统一 434 项测试、后端编译、前端类型检查和构建通过,未逐项重跑全量验证。
|
||||
- 修改后通过原先失败的网关路径复查,共享音频仍收到 30/30 帧,TS6 发回观看者离开通知。停止共享连续两次收到防刷拒绝,服务器附带等待值约 6098/7063 毫秒;有限重试后收到实际停止通知。临时脚本将清理结果等待上限由 10 秒调整为 20 秒,以覆盖 12 秒重试等待;没有放宽音频数量或用本地状态代替服务端通知。全部会话断开,网关活动计数归零。
|
||||
- 反向检查由独立 SDK 身份先发布,再接入网页网关:发现已存在共享、加入请求到达来源、offer/answer、共享音频 30/30 帧(RMS 1270)、网页离开得到 TS6 通知、来源停止传播到网页均通过;JSON 全部通过共享解析器。首次临时脚本昵称过长,被服务器明确拒绝;仅缩短测试昵称后继续,未修改昵称业务规则。该结果仍是 SDK 与合成 peer 互通,未替代官方客户端的视频验收。
|
||||
- 跨频道实服检查:频道 2 要求密码,改用实际可进入的频道 3,未改变服务端权限。观看者换频道后退出、列表不可见、跨频道加入返回 `SCREEN_SHARE_TARGET_MISMATCH`,返回原频道后可重新加入;共享者换频道后两端收到网页停止事件。TS6 的停止命令确认成功,但两侧均未收到原生停止广播,原先仅等待广播的脚本因此超时,不能把脚本整体记为通过。
|
||||
- 为核对上述结果,另作一次单发布者查询:换频道前 `requeststreaminfo` 返回完整共享 ID/属性;换频道清理获成功回执后,同一查询只返回含 `return_code` 的空 `notifystreaminfo`,原共享已不可查询。临时断言原本预期报错而非空通知,因此断言失败;保留原始记录,并对已采集的前后结果检查“之前有 ID、之后无共享字段、会话归零”,通过。该节点没有新增代码故障,也未为通知差异修改生产行为;官方客户端视频和真实设备仍待验收。
|
||||
|
||||
## 待修改事项的具体方向
|
||||
|
||||
### 04-D 前端媒体与连接编排
|
||||
|
||||
[useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 保留为页面调用入口。媒体、连接、命令、诊断和消息投影已交由各自模块管理,页面拆分继续复用现有响应式数据。
|
||||
|
||||
| 现有边界 | 应拥有的状态与资源 | 重点约束 |
|
||||
| --- | --- | --- |
|
||||
| 伴奏采集,已提取 | 授权操作、候选与当前采集流、结束监听、错误状态 | 生命周期绑定当前会话和混音目标;取消立即释放已取得的流 |
|
||||
| WebRTC 输入混音,已提取 | 输出流、麦克风源和音量节点、可选伴奏源 | 不停止外部模块拥有的原始麦克风;准备失败保留可用输出 |
|
||||
| 电平监测,已提取 | 输入源、分析器、静音输出节点和周期计时器 | 旧回调失效;失败只停止监测,不影响语音发送 |
|
||||
| WebRTC 传输与播放,已提取 | PeerConnection、offer/answer、ICE 等待、播放元素和协商计时器 | 旧 peer 无法写回;失败恢复兼容 PCM;关闭完整释放 |
|
||||
| 连接控制,已提取 | WebSocket、加入凭证请求、取消器与连接代次;通过回调更新页面状态 | 旧 socket 消息不写回;取消、超时和失败语义明确 |
|
||||
| 命令等待,已提取 | 请求标识、待确认登记、期限和结束函数 | 结束幂等;发送失败和断开立即释放 |
|
||||
| 诊断采样,已提取 | 统计等待、兼容计数、浏览器统计和样本范围 | 只组合当前来源数据;失败与会话释放清除等待;范围不进入网关协议 |
|
||||
| 状态投影,已提取 | 成员与频道事件、聊天历史、事件、通知、私聊身份范围 | 保留数组引用;区分完整与未知目录;退出及替换重置会话数据 |
|
||||
|
||||
上表边界已有实现,不再作为待提取清单。`useVoiceWebSocket.ts` 仍有设备协调、音量与页面动作,但本轮没有仅凭行数新增重构任务。若后续修改反复涉及同一组状态,再按具体职责提取一个边界。保留 `releaseSessionResources` 作为会话统一释放入口,模块只释放自身拥有的资源,避免多个模块共同修改大型状态对象。
|
||||
|
||||
现有规则继续有效:采集层拥有麦克风流;录音测试只拥有录音器、期限和试听 URL;设备替换在候选处理链就绪后提交;输出设备切换按端点串行执行。模块拆分不能撤销这些已实现的行为。
|
||||
|
||||
### 06-C 页面组件
|
||||
|
||||
当前依据:[WebClient.vue](../web/src/views/WebClient.vue#L1) 格式展开后有 1,337 行,加入表单、聊天面板、频道成员、成员菜单、身份导入、音频设置及密码弹窗已独立;成员卡片也已提取,父页保留页面编排及区域组合。[AdminView.vue](../web/src/views/AdminView.vue#L41) 拆分后为 251 行,本批仅展开格式后为 580 行,三个管理模板已迁移到独立组件。管理页剩余浏览器验收缺口见前表,客户端继续明确展示边界;不以文件长度推定运行故障。
|
||||
|
||||
以下名称为建议,实施时按实际接口确定。按稳定区域迁移,相关展示区域合并后统一验收,避免同时重写模板和业务状态。
|
||||
|
||||
| 区域 | 建议组件及职责 | 状态保留位置与接口 | 重点验收 |
|
||||
| --- | --- | --- | --- |
|
||||
| 加入页,已提取 | `JoinForm` 展示目标、昵称、频道、身份选项与连接状态 | 连接与历史仍由现有 composable 管理;表单用明确字段模型,提交、取消和导入用事件 | 固定与开放模式、收藏与历史、连接等待及取消、密码交互 |
|
||||
| 频道与成员,已提取 | `ChannelMemberPanel` 与 `MemberActionsMenu` 展示层级、成员状态和操作入口 | 复用父页单一 `useWebClientMembers`;面板保留音频工具栏插槽,菜单拥有定位观察器;动作仍交回现有控制层 | 搜索、频道切换、桌面指针拖动、调度及菜单边界已检查;真实触屏拖动及原生输入框仍待验收 |
|
||||
| 聊天,已提取 | `ChatPanel` 展示标签、历史、草稿和发送反馈 | 草稿与待确认状态继续由单一 `useWebClientChat` 实例管理;保留外部打开私聊的入口 | 切标签保留草稿、发送失败与重试、目标离线、滚动和移动端切页 |
|
||||
| 设置与密码弹窗,已提取 | `AudioSettingsDialog`、`ChannelPasswordDialog`、`ServerPasswordDialog` 展示设置及连接反馈;身份导入此前已提取 | 复用父页单一媒体与连接状态;设置错误受打开代次和请求顺序保护;共享焦点工具管理循环、Esc 和返回 | 焦点、Esc、设置持久化、密码等待与重试已检查;真实设备切换与录音待媒体验收 |
|
||||
| 音频工具栏与私语,已提取 | `AudioDock` 展示桌面快捷操作;`WhisperControls` 展示目标与按住讲话入口 | 使用父页单一音频控制器;私语按钮只拥有当前输入,隐藏、失焦和卸载时停止;监听随组件释放 | 静音、音量、设置入口、伴奏不可用提示、指针/键盘命令及布局已检查,真实媒体另行验收 |
|
||||
| 诊断与共享展示,已提取 | `VoicePerformancePanel`、`ScreenShareSettingsDialog`、`ScreenSharePlayer` | 父页创建诊断与共享控制器;视频和播放器通过明确函数引用交回控制器,组件不创建采集或 PeerConnection | 兼容传输诊断、设置字段/焦点、合成视频元素替换与全屏已检查;真实 WebRTC/TeamSpeak 互通仍待验证 |
|
||||
| 语音成员卡片,已提取 | `VoiceMemberCards` 展示成员状态、头像和共享操作入口 | 复用父页频道投影、成员动作与共享控制器,停止共享及菜单用事件返回;活动区域仍由父页组合 | 在线、发言、自身、空成员、共享等待/停止、观看切换、移动菜单和抽样布局已检查 |
|
||||
| 管理功能页,已提交 | `AdminServerSettings`、`AdminOperations`、`AdminSkins` 已提取,先验收这三个边界 | 父页创建三个管理 composable,通过稳定 `model` 对象传入;登录、CSRF、路由与总览仍在页面;欢迎词语言用具名模型传递,WebRTC 提示用事件返回 | 保存期间继续编辑、请求失败保留草稿、欢迎词语言、退出失败、路由切换、皮肤文件选择及操作互斥 |
|
||||
|
||||
接口只传该区域需要的状态和动作,避免把整页上下文塞进一个对象,也避免父子各自实例化同一个业务 composable。管理组件当前使用 `ReturnType<typeof useAdmin...>` 描述功能控制器,并在 setup 中解构,因此依赖父页维持同一控制器实例;若后续支持替换实例,需要同步调整读取方式。可以用 `Pick` 或专用接口缩小暴露范围,但不为形式重写已明确的状态归属。展示辅助函数如头像、时间格式在确有多处复用时集中,不额外引入全局状态层。
|
||||
|
||||
样式需要随组件边界一并核对。[客户端样式入口](../web/src/views/WebClient.vue#L1337)和[管理页样式入口](../web/src/views/AdminView.vue#L580)均使用 `scoped`,格式展开并清理重复声明后 CSS 分别为 7,659 与 3,737 行。身份弹窗已有针对组件的 `:deep` 规则;管理页当前改动将大量功能区选择器改为 `:deep`,并保留部分外壳和语言控件选择器的原作用范围。不要把这项源码变化直接等同于视觉一致:需对比子组件内部、共享按钮与语言菜单的字体、间距、尺寸、折行,以及样式声明顺序和优先级。必要时改为组件自有样式或更窄的区域选择器,保留明暗主题、`data-ws-part` 和路由隔离,管理页保持独立于公开皮肤。
|
||||
|
||||
测试也需跟随边界调整:[皮肤节点检查](../web/src/services/skin-pack.test.ts#L80)在当前工作区已递归读取 `components/web-client` 和 `components/admin` 下的 Vue 文件,保留公开节点契约及管理页隔离检查。[管理页状态测试](../web/test/admin-view.test.mjs#L79)已改为读取父页功能模型,仍用 `render: () => null` 替换模板,不能单独证明子组件的字段与事件接线正确。后续验收必须覆盖真实渲染的表单、按钮和路由交互;这属于测试覆盖边界,不能推定测试已发现业务故障。
|
||||
|
||||
管理组件验收至少包括:服务器保存时继续编辑、失败保留草稿、不同语言欢迎词往返、WebRTC 开关触发父页提示;邀请创建和撤销、刷新与路由取消;皮肤默认选择、启停、文件导入反馈;认证失效清理和失败退出保留状态。检查桌面与 390 × 844 窄屏、明暗主题、五语长文案,以及公开页进入管理页再返回的样式隔离。既有记录完成了三个桌面页面的静态外观对比;本批补充主要表单交互和窄屏导航检查,具体结果见下节。
|
||||
|
||||
每个区域验收包括桌面与窄屏、五语长文案、明暗主题和自定义皮肤;对比布局、滚动、弹层遮挡及键盘操作。编译通过和源码正则匹配不能替代实际渲染检查。
|
||||
|
||||
### 语音成员卡片的上批结果
|
||||
|
||||
- `VoiceMemberCards.vue` 接收当前频道成员、发言判断与头像辅助函数,以及共享状态和动作的必要子集。共享状态引用保持稳定;停止与成员菜单事件回到父页,不复制频道、成员或媒体状态。
|
||||
- 保留现有皮肤节点和样式声明顺序。20 个可见元素对比中,字体、颜色及内边距一致;观测到的元素尺寸和居中边距差异小于 1 像素,不能宣称像素完全相同。
|
||||
- 模拟网关的发言消息正确更新 Alice 卡片;观看入口发出 `screenShareJoin`,目标为该成员的 `preview-share`。网关无真实共享,因此返回共享不存在的预期错误;此检查只证明目标与反馈接线。移动端卡片菜单仍对应 Alice,共享设置入口仍打开原弹窗。
|
||||
- 独立受控展示页检查开始等待时出现停止按钮、停止后恢复开始入口、共享成功状态显示标记、观看/取消观看切换以及空成员提示。没有用该页面宣称实际媒体链路成功。临时页面与进程在收尾时移除。
|
||||
- zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对分别检查 1280×720、390×844、320×568,共 15 组;成员卡片、共享按钮和直播标记均未横向越界,应用浏览器日志无错误或警告。
|
||||
- 本批一次统一验证通过 409 项测试及前后端构建。06-C 主要结构拆分已完成,触屏与原生输入框验收缺口仍在状态表;下一结构节点为 06-L 的保序格式整理。
|
||||
### 此前诊断与屏幕共享展示的结果
|
||||
|
||||
- 三个展示组件使用父页单一控制器,诊断采样继续在原模块运行;共享设置沿用原输出参数和存储行为,补上 Tab 循环、Esc 关闭和返回入口焦点。播放器通过 `setVideoElement` 与 `setPlayerElement` 绑定真实 DOM,不把组件实例当成播放器。
|
||||
- 原视频绑定仅监听流和音量,元素替换而流不变时会漏绑。现在同时监听视频元素,在渲染后绑定当前流与音量;旧元素立即清空 `srcObject`,卸载不停止其他模块拥有的媒体轨道。
|
||||
- 原全屏判断在两个元素都为空时会为真。现在要求当前播放器存在;播放器移除或作用域释放仅退出自身拥有的全屏,失败时从真实文档状态重新同步。
|
||||
- 有明确成员 ID 或 TeamSpeak peer ID 的共享流以该身份为准,不再因昵称相同匹配到另一成员;缺少身份的旧数据仍保留昵称兼容。
|
||||
- 新增 6 项测试验证上述绑定、清理、全屏归属、同昵称匹配及 720p/30 FPS 输出参数。最终统一验证为 409 项测试及前后端构建通过。原有 4 条播放器皮肤样式断言保留颜色和层级要求,只兼容 `:deep` 写法。
|
||||
- 实际应用中,诊断面板 37 个可见元素和共享设置 21 个可见元素的尺寸、字体、颜色、间距与拆分前一致。共享设置选择 720p/30 FPS 后关闭再打开仍保留;Tab 首尾循环、Esc 与返回入口焦点通过。诊断浏览器结果覆盖兼容传输分支,WebRTC peer 数据的真实链路仍归媒体验收。
|
||||
- 共享设置与诊断分别在 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对下检查 1280×720、390×844、320×568,共 30 组;等待实际语言及皮肤生效后记录,弹层均在窗口内。
|
||||
- 独立本地预览用画布生成 640×360 媒体:新播放器可继续播放现有流,旧视频已解绑、轨道仍存活;全屏状态可进入,退出播放器后全屏清除。这只是浏览器展示生命周期证据,不代表真实共享采集、信令或跨端媒体已验收。临时预览文件和进程在收尾时移除。
|
||||
### 此前音频工具栏与私语控制的结果
|
||||
|
||||
- `AudioDock.vue` 通过稳定对象接收所需语音引用与动作,设置及输出静音用事件返回;`WhisperControls.vue` 复用同一控制器,清空目标仍交回成员模块。原有皮肤节点和样式声明顺序保留。
|
||||
- 私语只接受主指针左键,记录捕获指针并忽略其他指针的松开;捕获失败不进入讲话状态。新增空格/回车按住支持,忽略重复按键与无关松开。停止先清除归属,再释放捕获,避免丢失捕获事件重复停止。
|
||||
- 控件失焦、窗口失焦、页面隐藏、移动页切走和组件卸载均停止当前按住操作;组件释放监听,音频控制器作用域释放也停止私语。5 项新增测试验证输入归属与清理。
|
||||
- 浏览器确认右键不启动、左键启动、移出后松开停止;空格/回车各产生一组真实 WebSocket 开始/停止命令,模拟网关收到 `[true, false, true, false]`。窄屏隐藏与按钮失焦时状态停止,清空目标移除控制条。浏览器错误与警告记录为空。
|
||||
- 工具栏拆分前后 22 个可见元素的尺寸、字体、颜色和间距一致。麦克风及输出静音、输入与输出音量、设置入口/关闭、伴奏缺少 WebRTC 的反馈已检查;当前没有真实麦克风授权,不作为音频效果证据。
|
||||
- 布局使用 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对,每组检查 1280×720、390×844、320×568,共 15 组;另核对每组桌面输入/输出音量面板,共 10 个面板。等待语言及皮肤实际生效后记录边界,控件均未横向越界,音量面板均位于窗口内。
|
||||
- 本批统一验证 403 项测试与前后端构建通过;属性接口简化后前端类型检查及构建再次通过。真实语音、伴奏和触屏设备结果仍归原媒体验收节点。
|
||||
### 此前音频设置与密码弹窗的结果
|
||||
|
||||
- 三个展示组件复用父页现有状态,设置仅接收所需语音引用与控制动作,两个密码弹窗使用字段模型及提交/取消事件。共享焦点工具处理初始焦点、Tab 循环、Esc 和关闭后返回;服务器连接等待会使原按钮失焦,因此增加返回连接按钮的回退。
|
||||
- 设置准备、设备选择和录音测试的错误只允许当前打开代次及最新请求发布;关闭同步停止录音测试,作用域释放也停止并使迟到反馈失效。5 项测试先在旧实现全部失败,再验证修复;没有改写底层媒体事务。
|
||||
- 频道密码提交遇普通错误原先可能持续禁用输入。现在显示本次错误、解除等待、保留密码供重试,并阻止等待期间重复提交。3 项测试覆盖重复提交、普通错误重试和成功关闭。
|
||||
- 设置提取前后对比 88 个可见元素,发现权限拒绝颜色未跨组件边界生效并修正;最终拒绝颜色与基线一致。通知音量、VOX 阈值关闭再打开仍保留;权限拒绝提示、Tab 首尾循环、Esc 及返回焦点通过。当前浏览器无麦克风授权,不能将这些检查当作真实录音或设备切换验收。
|
||||
- 两个密码流程检查必填提示、错误密码、正确密码及取消。频道提交受控等待期间输入与按钮禁用;普通权限错误后恢复输入,撤除模拟故障后不重填密码即可成功重试。频道取消恢复原选择,服务器取消返回连接按钮。
|
||||
- 三个弹窗分别检查 zh/浅色、en/深色、de/ILLUSIA、ru/浅色、ja/深色五组配对,每组使用 1280×720、390×844、320×568,合计 45 组边界检查通过。这是抽样配对,不是五语言与三皮肤的完整交叉组合。最终浏览器错误与警告记录为空。
|
||||
- 最终统一 `npm run verify`:398 项测试全部通过,后端编译、前端类型检查和生产构建通过。真实媒体、触屏及原生输入框等缺口仍按原节点跟踪。
|
||||
|
||||
### 此前频道成员与菜单的结果
|
||||
|
||||
- `ChannelMemberPanel.vue` 接收频道投影、明确字段模型及成员控制器的展示子集;音频工具栏通过插槽保留在父页。`MemberActionsMenu.vue` 共用同一控制器,私聊和音量通过事件交回父页,不复制成员状态。
|
||||
- 组件提取前后 90 个成员面板可见元素的尺寸、字体、间距及颜色一致。按成员名/频道名搜索、空结果、键盘清空搜索、嵌套频道切换、菜单调度、私语目标增删、私聊入口、成员音量回传和桌面指针拖动已检查。模拟客户端按实际移动事件广播目录变化。
|
||||
- 移动端误调度:鼠标进入“调度到”会先展开子菜单,底部菜单随之上移,点击可能命中目标频道。现仅桌面允许悬停展开,移动端通过点击展开;复查展开后目录不变,明确点击目标后才移动成员。
|
||||
- 菜单越界:1280×568 窗口曾测得主菜单底部 580、子菜单底部 615;320×568 时最后一个目标底部 505,而导航从 494 开始。菜单现在按实际尺寸限制位置,子菜单空间不足时向左/上调整,超高菜单允许滚动,保留 CSS 缩放换算。组件拥有尺寸观察器及 resize 监听,卸载时释放。
|
||||
- 最终 390 项测试及前后端构建通过;其中 5 项定位回归覆盖短窗口、底部子菜单、右侧翻转、过大内容和缩放后的尺寸。五语×浅色/深色/ILLUSIA×1280×568、390×844、320×568 共 45 组 DOM 边界检查通过。实际点击确认短屏滚动选项和重定位子菜单均能调度,浏览器无警告/错误日志。
|
||||
- 验收限制:IAB 不支持 `Input.dispatchTouchEvent`,真实触屏拖动未完成;“离开/戳一戳”依赖原生输入框,本批未执行其完整流程。一次批量浏览器检查超时后按已完成组合恢复并补验,未据此改动业务代码。模拟服务不能证明生产调度权限或真实媒体。
|
||||
|
||||
### 加入表单与聊天面板的此前结果
|
||||
|
||||
- `JoinForm.vue` 通过七个具名模型回传字段,连接、取消、收藏、历史选择及身份操作通过事件回到父页。固定模式提交、开放模式目标/端口/昵称/频道/密码/中继回传、收藏与最近连接回填、身份弹窗入口和取消连接均已检查。取消后释放迟到的凭证响应,页面仍停留加入页。
|
||||
- `ChatPanel.vue` 接收父页单一聊天控制器的展示子集,保留草稿与确认状态归属;DOM 滚动引用仍接回该控制器。频道/服务器草稿切换、失败保留、成功回执清空、事件日志、外部打开私聊及私聊草稿恢复均已检查。两条长消息后实际滚动位置为 351,内容 867、可视高度 516,底部剩余距离为 0。
|
||||
- 拆分前后桌面空聊天面板 29 个元素的尺寸、字体、间距及颜色一致。加入页保留原结构、字段标识与皮肤节点;样式声明顺序不变,仅调整跨组件选择器和下述布局问题。
|
||||
- 窄屏问题:开放模式与展开身份选项时,长文案撑宽隐式网格列;俄语 320 像素视口实测表单宽 250、内容列约 369 像素。改为 `minmax(0, 1fr)` 列,窄屏身份按钮允许换行,中继说明与选择框纵向排列,并允许字段标签折行。修复后表单、聊天各 45 组五语×三皮肤×三宽度的控件边界检查通过。皮肤为内置浅色、深色及随项目提供的 ILLUSIA;未覆盖任意第三方皮肤包。
|
||||
- 浏览器无警告/错误日志。本批主要覆盖模拟服务的正常展示和操作;真实目标离线、真实媒体及生产消息兼容不归为本批完成项。其余客户端展示边界仍见 06-C 待办。
|
||||
|
||||
### 管理组件的此前验收结果
|
||||
|
||||
三个展示组件继续使用父页创建的控制器,未复制业务状态。欢迎词语言通过具名模型传递,WebRTC 提示通过事件返回父页,皮肤文件输入由展示组件持有。现有管理状态测试改为访问功能模型;皮肤契约检查包含递归的管理组件目录。
|
||||
|
||||
- 服务器设置:受控迟到保存不覆盖后续编辑,失败保留草稿;路由往返保留名称与欢迎词语言;WebRTC 开关触发提示并锁定端口;连接测试反馈、中继增删接线正常。连接测试使用模拟结果,未访问真实 TeamSpeak。
|
||||
- 运维与认证:邀请创建与撤销、数值字段及路由草稿已检查;退出失败保留草稿,成功退出移除管理内容,再进入读取已保存配置;当前 401 返回登录页并清理管理内容。
|
||||
- 皮肤:默认项保存、失败回滚、等待时操作互斥、启停、错误包反馈、合法包导入与文件输入重置已检查。包内容由实际前端解析器检查,预览服务端使用内存皮肤目录,不把该结果表述为生产注册表端到端验证。
|
||||
- 布局:系统深色下四路由 × 五语 × 四宽度,共 80 组导航、工具栏和页面横向边界检查通过;另有浅色 320 像素四路由检查。键盘从服务器链接按 Tab 可聚焦运维链接。
|
||||
- 剩余验收:点击移除测试皮肤后,浏览器工具在原生确认框处超时;新标签可继续其余检查。没有据此修改 `window.confirm` 或业务逻辑。移除、断开会话及下载类操作的完整浏览器流程仍未确认。
|
||||
|
||||
本批统一验证为 385 项测试及前后端构建通过。未因纯展示提取新增镜像实现测试;真实模板接线以以上浏览器结果补充已有状态和接口测试。
|
||||
|
||||
### 06-K 管理页窄屏导航修复
|
||||
|
||||
依据:[管理页侧栏模板](../web/src/views/AdminView.vue#L23)和[窄屏样式](../web/src/styles/admin.css#L318)。修改前品牌、四个链接和退出按钮在窄屏继续同排。浏览器已复现:390 像素视口的布局可用宽度为 375 像素,退出按钮右边缘约为 455 像素,入口被裁切。
|
||||
|
||||
已实施:不超过 850 像素时品牌与退出按钮占第一行,导航独占第二行,以四列等宽网格约束宽度,点击区域至少 44 像素高。保留桌面侧栏、可访问名称与当前页面标识,不使用隐藏横向溢出来掩盖不可见入口。
|
||||
|
||||
320、390、768、1280 像素及五语的边界检查通过,四个入口和退出按钮均在可见区;浅色窄屏与键盘导航通过。此处改变属于预期修复,与组件提取的外观保持检查分别记录。
|
||||
|
||||
### 06-L 模板和样式的可读性
|
||||
|
||||
原静态统计发现页面模板和 CSS 存在数千至上万字符的单行,增加审阅与定位成本,不等于存在运行故障。本批已展开主页面、管理页及所属展示组件的 20 个模板,以及两份页面样式;CSS 现为 7,854 与 3,852 行,行数增长来自排版。
|
||||
|
||||
模板使用固定版本 Prettier 3.6.2 整理,仅取其模板输出,脚本保持逐字一致。逐个比较 Vue 编译出的渲染函数语法树,20 个全部等价;比对发现成员菜单及共享错误提示中图标后的空格被换行消除,已保留原空白文本。CSS 使用现有 PostCSS 解析器展开声明,核对选择器、属性值、声明及规则顺序、条件和注释均不变。
|
||||
|
||||
两条既有布局断言调整为接受声明间换行,仍检查原选择器和值。首轮测试因单行断言失败,修正后统一验证 409 项测试及前后端构建全部通过。编译及解析等价是本批格式验证依据,未额外重复上批浏览器矩阵。临时核对脚本与报告留在本地 `.git`,未加入产品代码或依赖。
|
||||
|
||||
后续维护继续按组件边界核对后置覆盖和 `:deep` 作用范围。不同值的覆盖及非相邻断点具有顺序意义,不能仅为减少行数搬移;主题功能改写不属于本节点。两份样式的确认冗余项及对应浏览器比较现已完成,记录如下。
|
||||
|
||||
#### 管理样式冗余清理
|
||||
|
||||
删除 58 条被后续同条件、同选择器、同属性、同值及同重要性声明覆盖的早期声明,删除因此产生的空规则,并合并一组相邻的 520px 断点。桌面运维邀请表单及诊断区域的整段重复规则保留最后一份。日志折行注释移至保留规则旁。不同值的覆盖及非相邻断点仍保留,不能仅凭名称相同就移动合并。
|
||||
|
||||
静态核对保留的 1,776 条声明及其顺序不变;全量统一验证一次通过 409 项测试及前后端构建。实际管理页在 320、560、850、1280px 下,对四个路由及明暗主题共 32 组逐元素比较尺寸与 25 项计算样式,结果一致;展开全部服务器设置后,在 320、520、560、850、851、1100、1101、1280px 下另比较 8 组,结果一致且无横向溢出。浏览器日志无警告或错误,临时预览已关闭。该管理批次没有修改客户端 CSS;后续客户端清理结果见下一节。
|
||||
|
||||
#### 客户端样式冗余清理与 06-L 收尾
|
||||
|
||||
删除 116 条相同条件、选择器、属性、值及重要性的早期重复声明,主要涉及重复的工作区头部整段样式、移动端尺寸与滚动、菜单和页脚。删除空规则并合并两组相邻 740px 断点。保留 4,075 条声明的值、条件、选择器及相对顺序,没有更改脚本、模板、皮肤包或测试。统一运行一次全量验证,409 项测试及前后端构建通过。
|
||||
|
||||
浏览器比较 zh/浅色、en/深色、de/ILLUSIA 三组配对,在 320、740、741、980、1201、1280px 下检查首页与连接视图,共 36 组;另在 320、740px 下比较频道、聊天、语音、更多四分区及成员菜单、音频设置弹窗,共 12 组。针对受影响选择器检查尺寸及 37 项计算样式,最终比较一致且无横向溢出,浏览器日志无警告或错误。
|
||||
|
||||
首轮快速采样抓到 QQ 按钮 180ms 尺寸过渡,以及 741px 的响应式控件更新中间态。为排除实际回归,另构建原样式到本地隔离目录,对首页 18 组及临界宽度的三组皮肤补做稳定状态比较;统一移动分区后均一致。该补核没有修改业务逻辑,也没有重复运行全量测试。所有预览进程和标签已关闭,基线及临时记录仅留在本地 .git。
|
||||
|
||||
06-L 的格式及已确认冗余清理完成。不同值的后置覆盖、跨区域样式与非相邻断点继续保留其作用顺序,不将结构更短作为额外目标。剩余验收项以状态表为准。
|
||||
|
||||
### 03 与 02-C 契约和真实媒体
|
||||
|
||||
不另建平行协议类型。用真实连接中的脱敏样本补充现有解析用例,重点核对大整数频道标识、可选字段、未知消息、非法列表项和旧客户端兼容。行为变更单独记录兼容范围。
|
||||
|
||||
协议验收记录至少区分“当前客户端与当前网关”“当前客户端与受支持旧网关”“受支持旧客户端与当前网关”。重点核对 `commandCompleted`、可选的 `channelId` 与 `clientUid`;旧端没有某项能力时明确最低兼容版本或降级行为,不能直接把确认超时判定为消息未送达。只有真实样本暴露不一致时,才形成相应解析或兼容代码修改。
|
||||
|
||||
真实媒体验收至少覆盖 TeamSpeak 3 与 6、WebRTC 与兼容传输、协商失败回退、双向语音、静音与音量、伴奏启停、多人同时发言、频道切换及断线重连。屏幕共享另外验证频道隔离和停止后的资源释放。记录可重现的环境与结果;先由实际失败形成修复项,不预先宣称存在某类网络故障。
|
||||
|
||||
### 09-A 服务端发布与暂缓的 Android 事项
|
||||
|
||||
[mobile/README.md](../mobile/README.md) 保留 Android 已有构建、启动和运行时差异记录。用户明确 Android 暂不纳入修复计划,因此本轮不再推进 07-A、Android 布局或设备验收,也不以这些事项阻塞当前目标。
|
||||
|
||||
若以后恢复 Android 范围,再验收真实 SDK 连接、双向语音、输入输出切换、重连、资源释放及布局;既有构建和首页启动结果不替代这些检查。后台音频、前台服务和原生屏幕共享也保持独立能力范围。
|
||||
|
||||
本轮发布检查范围为 Windows、Linux 和 Docker,现有 CI 与打包工作流已提供干净构建和启动证据。参照 [本地产物说明](LOCAL_ARTIFACTS.zh-CN.md),保留未知用途文件及历史产物,构建输入仅来自声明的源码与依赖。`.local-opus-hook.cjs` 是原样复制缓冲区的实验替身,不作为正式音频验收依据;容器健康检查只证明其检查的 HTTP 启动路径。
|
||||
|
||||
平台记录保留提交号、构建主机与运行时版本、安装与构建命令、产物名称及校验和、启动与媒体结果。Android 的后台音频、前台服务和原生屏幕共享仍是单独的能力范围,不混入本轮代码整理的完成条件。
|
||||
|
||||
## 已完成事项与后续约束
|
||||
|
||||
以下实现已存在,不重复作为待开发任务。各批验证范围保留在文末。
|
||||
|
||||
| 原事项或范围 | 当前状态 |
|
||||
| --- | --- |
|
||||
| 09-A 干净构建 | 本轮 Windows/Linux/Docker 的构建和 HTTP 启动要求已通过;Android 构建与启动结果保留为历史证据,其剩余布局与真机验收暂不纳入本轮 |
|
||||
| 06-L 客户端样式冗余 | 删除 116 条重复声明并合并两组相邻断点;409 项测试和前后端构建、48 组浏览器比较通过 |
|
||||
| 06-L 管理样式冗余 | 删除 58 条重复声明及一组相邻重复断点;409 项测试和前后端构建、40 组浏览器前后对比通过 |
|
||||
| 06-L 保序格式整理 | 20 个模板编译结果等价、脚本原样保留;两份 CSS 规则树等价;409 项测试及前后端构建通过,后续两批规则清理也已完成 |
|
||||
| 06-C 语音成员卡片 | 展示提取完成,409 项测试及 15 组布局抽样通过;状态、共享入口与菜单接线已验证,媒体实测另行保留 |
|
||||
| 06-C 诊断与共享展示 | 三个组件已提取;修复视频重新绑定、全屏空值判断及同昵称归属,409 项测试与 30 组布局抽样通过,真实跨端共享验收保留 |
|
||||
| 06-C 工具栏与私语 | 两个展示组件已提取,修复指针归属并支持键盘按住;隐藏、失焦及释放停止,403 项测试及浏览器接线/布局检查通过 |
|
||||
| 06-C 设置与密码弹窗 | 三个展示组件已提取;修复迟到设置错误及频道密码普通错误后卡等待,新增 8 项回归;398 项测试与 45 组抽样布局检查通过,真实媒体验收另行保留 |
|
||||
| 06-K 管理页导航 | 窄屏改为品牌与退出、四项导航两行布局;五语四路由四宽度共 80 组边界检查通过 |
|
||||
| 06-C 频道成员与菜单 | 两个展示组件已提取;修复移动端误调度及短窗口菜单越界,390 项测试与 45 组边界检查通过;触屏及原生输入框验收仍保留 |
|
||||
| 06-C 加入与聊天 | 两个展示组件已提取;修复开放表单长文案撑宽,表单与聊天共 90 组语言/皮肤/宽度边界检查通过 |
|
||||
| 06-C 管理展示组件 | 三个组件已提取,父页保持状态归属;主要交互和两项实际下载通过,十类管理审计名称已补齐;原生确认验收缺口按用户要求跳过,见前部状态表 |
|
||||
| 06-I、06-J 皮肤生命周期 | 最新选择、页面取消、目录乱序、8 秒等待期限、资源及存储归属已修复;23 项新增测试与本机浏览器检查通过 |
|
||||
| 06-H 身份异步操作及 06-C 身份弹窗 | 24 项时序与资源测试通过,状态与模板分离,关闭按钮定位修正;正常文件读取、错误反馈、焦点和响应式布局已有浏览器验证 |
|
||||
| 04-K、04-L、04-D 消息状态 | 成员快照与增量统一投影,退出清理通知,恢复保留规则及会话范围已有实现;保留响应式数组引用 |
|
||||
| 06-E、06-F 聊天与私聊 | 发送等待确认,失败保留草稿;私聊按身份归属,网关可核对频道与 UID;上一批有状态与浏览器验证记录 |
|
||||
| 06-G 频道层级 | 迭代遍历处理环、重复 ID 和孤儿节点;正常顺序及深层目录已有回归记录 |
|
||||
| 04-E 至 04-J 浏览器媒体、连接与诊断 | 伴奏切换及取消、电平监测、命令等待、凭证取消和诊断来源隔离已有实现;此前验证结果保留于对应章节 |
|
||||
| 05-A 服务端会话音频 | `SessionAudioTransport` 已接入 PCM、WebRTC 和 TeamSpeak 下行,统一路由、背压与统计 |
|
||||
| 05-B、05-C WebRTC 关闭 | 已逐项容错释放资源,重复关闭共享完成 Promise,包括失败结果 |
|
||||
| 02-B 测试入口遗漏 | WebRTC、诊断、身份、皮肤和存储回归均进入统一命令;当前 42 个列出的测试文件均存在 |
|
||||
| 05-D SDK 事件与目录 | `SessionEventCoordinator` 已提取;旧 SDK 来源、关闭等待、重连等待及踢出到达顺序已有实现和回归记录 |
|
||||
| 成员头像 | 下载控制器与 SDK 异步阶段均绑定连接代次;批次、缓存、监听及迟到结果有生命周期限制 |
|
||||
| 前端基础整理 | 共享消息契约、管理请求与三个状态模块、五语管理文案、头部组件及路由延迟加载已实现 |
|
||||
| 浏览器媒体基础 | 远端播放、录音测试、麦克风处理链、设备切换事务及 Android 启动握手已独立实现 |
|
||||
|
||||
原清单记录以下批次的 CI 与 Docker 检查成功:[音频与关闭批次 972ee79](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819043190)、[头像控制器批次 e9b8c2b](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36819750447)、[SDK 下载边界 cc9714b](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36820095236)。这些链接保留为历史依据,本轮未重新核对,也不替代当前提交的独立验证。
|
||||
|
||||
后续结构调整保留以下约定:
|
||||
|
||||
- 兼容音频为 48 kHz 单声道、20 ms、1,920 字节 PCM;TeamSpeak 下行保留 3 字节头。缓冲、背压和混音参数调整需另有音频依据。
|
||||
- WebSocket 背压阈值保留 4,096 字节;WebRTC 每位说话者最多 4 帧混音队列及 20 ms 调度节拍保持不变。浏览器远端播放保留现有 80 ms 窗口及解码队列限制。
|
||||
- 控制消息错误码、浏览器存储格式、身份占用、一次性凭证、会话上限及共享频道隔离保持兼容。
|
||||
- 服务端各层只解绑所属监听,不删除 WebSocketServer 管理连接集合所需的关闭监听;语音路径不增加逐帧持久化日志。
|
||||
- 保存失败保留草稿;秘密字段保留、替换、删除语义不变。依赖主版本、数据库 schema 和音质参数不与结构整理混在同一批修改。
|
||||
|
||||
## 原实施顺序与验收方式(历史依据)
|
||||
|
||||
以下保留原施工顺序和当时的验收要求。各节点实现及验证结果见前文;用户明确跳过的剩余验收以本页前部范围调整为准,不再作为本轮完成门槛。
|
||||
|
||||
| 顺序 | 内容 | 验收方式 |
|
||||
| --- | --- | --- |
|
||||
| 既有完成 | 06-I、06-J:皮肤激活与启动等待 | 历史记录包含 23 项新增测试与浏览器验证,本轮不重复实施 |
|
||||
| 本批实现 | 06-C、06-K:管理组件及窄屏导航 | 主要交互与 80 组边界检查通过;原生确认及下载类操作保留浏览器验收缺口 |
|
||||
| 随后 | 06-C:其余客户端组件 | 一次拆一个稳定区域;保留业务状态实例,检查主题、皮肤、五语、键盘与窄屏 |
|
||||
| 已完成整理 | 06-L:模板格式、两份页面样式的确认冗余项 | 保留非冗余覆盖顺序;后续业务修改继续维护现有边界 |
|
||||
| 联调阶段 | 03:契约兼容核对 | 收集脱敏真实消息;分别记录新旧客户端与网关组合的确认和目标校验行为 |
|
||||
| 联调阶段 | 02-C:真实 TeamSpeak | 使用用户指定服务器,先解决接入无回包条件,再记录协议与媒体实际结果 |
|
||||
| 已完成 | 09-A:Windows/Linux/Docker 干净构建与启动 | 已有产物和启动记录;Android 范围按用户要求暂缓 |
|
||||
|
||||
本节点统一执行一次 `npm run verify`,385 项测试及前后端构建通过。后续把同节点的相关修复合并后验证;新增测试文件纳入显式入口,后续改动或失败有必要时才重复完整检查。浏览器布局、真实媒体及平台验收单独记录,不能由类型检查或单元测试代替。真实环境记录至少包含提交、服务端与客户端版本、设备、传输方式、操作步骤、预期、实际结果及未通过原因。不要把纯结构调整与依赖主版本升级、数据库迁移或音质参数调整合并实施。
|
||||
|
||||
## 历史记录说明
|
||||
|
||||
以下保留此前批次的实施过程、只读整理及验证结果,用于追溯。各节中的“本批”“当前”及文件行号对应当时记录,不应覆盖前部待办表和本轮基线;历史测试、浏览器和 CI 结果均不表示本轮重新执行。
|
||||
|
||||
## 皮肤生命周期修复结果
|
||||
|
||||
### 06-I 皮肤异步激活归属
|
||||
|
||||
施工前,[skin-runtime.ts](../web/src/services/skin-runtime.ts#L36) 在本地读取、下载和包解析后直接修改样式及存储。五项用例先复现:慢自定义皮肤覆盖新的内置选择、旧下载失败回退覆盖新皮肤、清理后旧读取重新生效、页面取消后仍提交,以及旧目录重新启用已被新目录禁用的皮肤。
|
||||
|
||||
已实施:运行时按最新激活拥有提交权,目录请求有独立的同类归属;请求替换和外部取消立即结束等待,不能取消的底层操作也不能迟到提交。已失效调用不能取消下一页面的激活。失败安装释放候选对象 URL,正常替换后才释放旧资源。
|
||||
|
||||
主页与演示页共用 [usePublicSkin.ts](../web/src/composables/usePublicSkin.ts),所有初始化、手动选择、恢复回退和本地数据清理均由所属页面管理。卸载使旧操作失效;皮肤内容、选择标识及偏好只接受当前结果。去除两页重复的无归属版本刷新路径,正常加载仍核对目录版本与实例默认值。
|
||||
|
||||
缓存写入和偏好保存传递所属取消信号。本地数据库打开后再次检查信号,写事务期间可以取消;存储操作在事务完成时才报告成功。偏好读取和合并改在同一事务内完成,避免皮肤写入覆盖并发修改的其他设置。没有调整存储 schema 或已有键名。
|
||||
|
||||
### 06-J 皮肤启动期限与回退
|
||||
|
||||
已实施:[skin-operation.ts](../web/src/services/skin-operation.ts) 提供统一等待与取消,页面初始化默认总期限为 8 秒,覆盖偏好读取、目录、响应体、皮肤包及激活。目录与激活独立调用同样有期限。超时先使旧链失效,再显示可用内置主题,避免整页继续隐藏;显式皮肤偏好保留供下次重试。
|
||||
|
||||
正常网络下保留实例默认皮肤、已禁用皮肤过滤和缓存版本更新。页面不再重复发起同一版本的无归属刷新;后来的选择不能被启动响应覆盖。清理本地数据时先取消旧操作,再清理存储和重置外观,目录刷新失败不阻止页面使用。
|
||||
|
||||
验证:[skin-lifecycle.test.mjs](../web/test/skin-lifecycle.test.mjs) 的 17 项用例覆盖旧结果、目录乱序、本地读取与响应体挂起、页面退出、初始默认值、重置和候选 URL 清理;[local-persistence.test.ts](../web/src/services/local-persistence.test.ts) 的 6 项用例覆盖延迟打开、事务取消、提交确认和偏好合并。共 23 项新增用例均通过。
|
||||
|
||||
浏览器通过真实 HTTP 接口人为保持目录和皮肤包响应未完成,检查页面恢复和请求中止;取消旧下载后刷新仍为新的内置选择。正常加载 ILLUSIA 皮肤并进入演示页,内容和外观恢复成功,未发现浏览器错误日志。网络和数据库边界测试不替代真实媒体与设备验收。
|
||||
|
||||
## 身份导入与组件拆分实施
|
||||
|
||||
### 06-H 身份文件读取的异步归属
|
||||
|
||||
原入口为 `28eda60` 中的 `WebClient.vue` 文件读取、弹窗开关与卸载函数。当前实现见 [useWebClientIdentity.ts](../web/src/composables/useWebClientIdentity.ts) 与 [IdentityImportDialog.vue](../web/src/components/web-client/IdentityImportDialog.vue)。
|
||||
|
||||
修改前,`readIdentityFile` 等待 `file.arrayBuffer()` 后直接写入导入文本或错误,没有读取序号、弹窗代次或页面失效检查。文件读取也不设置 `identityImportBusy`;该标志用于点击导入后的解析阶段,不能阻止读取中的关闭操作。以下时序已通过可控制返回顺序的用例复现:
|
||||
|
||||
- 先选文件 A,再选文件 B;若 A 最后返回,会覆盖 B 的文本,A 的迟到失败也可能覆盖当前错误状态。
|
||||
- 读取期间关闭并重新打开弹窗;旧读取可能把上一次的内容写进新弹窗。
|
||||
- 读取期间手动编辑文本;旧读取完成后可能覆盖刚输入的内容。
|
||||
|
||||
已实施:状态模块统一持有操作代次,新的选择、文本修改、关闭、进入房间、清除本地数据或页面卸载使旧结果失效。文件仍在读取时不能提交旧文本;解析只提交所属草稿,失败保留输入。展示组件只接收文本、状态与文案并发出操作事件,文件输入和焦点归组件管理。
|
||||
|
||||
保留 128 KiB 文件限制、UTF-8 与带 BOM 的 UTF-16 解码、身份格式校验和五语提示。解析期间维持不允许关闭的行为,同时禁用编辑与文件选择。导出等待绑定当前身份与页面,重复点击合并,迟到结果不下载;锚点、对象 URL 和计时器分别释放。启动身份读取同样检查修订,不能覆盖新导入、已取消的记忆偏好或清理后的状态。
|
||||
|
||||
验证:[identity-dialog.test.mjs](../web/test/identity-dialog.test.mjs) 的 24 项测试覆盖上述时序、格式读取、正常提交、解析失败、导出与 URL 清理、启动恢复;其中 10 项先失败后通过。既有格式测试继续保留。浏览器实际选择 UTF-16 测试文件并验证错误反馈、保留文本、关闭和重开;桌面及窄屏对比发现原关闭按钮位于屏幕右上角,现定位于弹窗内。没有把该批验证扩展解释为真实 TeamSpeak 或 Android 验收。
|
||||
|
||||
## 上一批状态与聊天修复
|
||||
|
||||
以下问题描述与带行号的原入口引用对应上一批施工前基线 `a97fa54`;本节“本批”均指该历史批次。成员与消息的当前实现见 [session-state.ts](../web/src/voice/session-state.ts),聊天交互见 [useWebClientChat.ts](../web/src/composables/useWebClientChat.ts)。
|
||||
|
||||
### 04-K 统一成员目录更新
|
||||
|
||||
依据:[前端消息分支](../web/src/composables/useVoiceWebSocket.ts#L1072)、[服务端成员更新](../src/server/session-events.ts#L121)、[私聊名称](../web/src/composables/useWebClientChat.ts#L50)及[私语目标](../web/src/composables/useWebClientChannels.ts#L133)。
|
||||
|
||||
修改前,服务端收到成员更新后发布 `channelList`;浏览器只替换 `channels`,不更新扁平 `members`,导致频道树与私聊、私语名称不同步。进入事件丢失部分状态,离开事件也未立即移除频道副本。
|
||||
|
||||
已实施:消息模块拥有响应式数组,频道引用同一份成员数据;完整快照替换目录,旧网关省略成员时保留未知部分。进入更新全部已提供字段;离开同时清理各投影、播放、发言、临时音量和私语目标。UID 改变不继承旧成员音量,按 UID 保存的用户偏好仍保留。头像继续核对 UID。
|
||||
|
||||
验收:改名、静音、离开、再次进入、头像迟到、重复进入,以及省略成员字段的兼容消息;各处名称与状态一致,旧会话事件不能写入新会话。
|
||||
|
||||
### 06-E 明确聊天发送结果并保留失败草稿
|
||||
|
||||
依据:[命令发送](../web/src/voice/commands.ts#L19)、[聊天发送入口](../web/src/composables/useVoiceWebSocket.ts#L1266)、[提交草稿](../web/src/composables/useWebClientChat.ts#L99)及[发送按钮](../web/src/views/WebClient.vue#L255)。
|
||||
|
||||
修改前,普通命令在 socket 未打开时直接返回,聊天入口仍追加消息并清空草稿。重连期间界面允许提交,服务端拒绝也没有与本地消息关联的确认。
|
||||
|
||||
已实施:三个聊天动作返回 Promise,等待现有 `commandCompleted` 后才追加成功消息。未连接时拒绝发送;网关在恢复期间拒绝命令时保留 `requestId`。草稿、等待和错误按聊天对象隔离;切换标签再返回不能重复提交在途消息,确认只清理已提交且未被修改的草稿。退出或卸载使旧反馈失效。五语提示区分等待、对象失效、频道变化和发送未确认;超时可能已送达,提示核对后再重试,不声称对方已读。
|
||||
|
||||
频道消息新增可选 `channelId`,网关在调用 SDK 前核对实际频道,避免频道切换失败后把显示在目标频道的消息发到旧频道。旧客户端省略该字段时保留原行为。
|
||||
|
||||
验收:socket 关闭、TeamSpeak 重连、成员离线、服务端拒绝、超时、重复点击和等待期间继续输入;失败不伪装为成功,成功仅出现一次,本人回显不重复。保留现有 500 字符限制和五语提示。
|
||||
|
||||
### 06-F 将私聊目标绑定到所属会话
|
||||
|
||||
依据:[私聊状态与发送](../web/src/composables/useWebClientChat.ts#L45)、[连接动作](../web/src/composables/useWebClientConnection.ts#L90)及[页面组装](../web/src/views/WebClient.vue#L862)。
|
||||
|
||||
修改前,私聊选择与草稿未随退出重置,历史只按数字 ID 分组。编号复用可使旧私聊自动对应新成员;本批已用跨服务器和同服务器替换场景复现。
|
||||
|
||||
已实施:退出或目标替换清理选择和全部草稿;同一连接内按私聊身份保存草稿。历史带浏览器本地 `conversationKey` 和对方名称快照;有 UID 时按 UID 识别,旧网关无 UID 时按成员生命周期分配范围,离开或重连重新分配。未知发送者与后来出现的同编号成员不合并。离线历史仍可查看,不能向已变更身份的目标继续发送。
|
||||
|
||||
私聊命令新增可选 `clientUid`;浏览器提交当前选定身份,网关在调用 SDK 前核对,防止请求途中发生编号复用。省略字段的旧客户端仍可使用现有协议,但没有该新增校验;旧网关是否支持确认及目标校验纳入事项 03 的兼容验收。
|
||||
|
||||
验收:服务器 A 和 B 都有编号相同的成员、同服务器内编号复用、目标离线,以及重连前后编号改变;旧选择不能自动指向新对象,其他会话的草稿不会出现在当前私聊。
|
||||
|
||||
### 04-L 统一会话通知清理规则
|
||||
|
||||
依据:[断开处理](../web/src/composables/useVoiceWebSocket.ts#L982)、[连接成功及事件处理](../web/src/composables/useVoiceWebSocket.ts#L1052)和[通知展示](../web/src/views/WebClient.vue#L933)。
|
||||
|
||||
修改前,显式断开没有清空事件和戳一戳通知;成功连接虽然替换事件,仍会展示旧通知。本批通过退出与替换目标用例复现。
|
||||
|
||||
已实施:消息状态与媒体释放保持独立,所有列表保留响应式引用。
|
||||
|
||||
| 场景 | 当前规则 |
|
||||
| --- | --- |
|
||||
| 显式退出、更换目标、普通 socket 关闭 | 清空目录、聊天、事件及通知,重置页面聊天选择和草稿 |
|
||||
| 同 socket 的 TeamSpeak 恢复等待 | 保留历史供查看,媒体和待确认命令释放,禁止发送 |
|
||||
| 恢复成功 | 替换成员、清除旧频道等待新快照、替换事件、清除通知;保留聊天历史,重新核对私聊身份 |
|
||||
| 恢复最终失败 | 保留失败面板及历史,禁止发送;后续重试连接或退出按新会话重置 |
|
||||
|
||||
验收:收到通知后退出、换服、重连成功或失败;旧通知不出现在新服务器,恢复目录和事件时不重复触发提示音。保留已存身份和用户音频偏好的现有语义。
|
||||
|
||||
### 06-G 防止异常频道层级导致递归失控
|
||||
|
||||
依据:[频道树遍历](../web/src/composables/useWebClientChannels.ts#L30)与[频道消息校验](../src/shared/server-messages.ts#L59)。
|
||||
|
||||
修改前,父子遍历 `visit` 没有访问保护。共享解析器允许形状有效但父子成环的目录,本批自环与双节点环用例实际触发栈溢出;不推定正常 TeamSpeak 一定产生这种目录。
|
||||
|
||||
已实施:父子及兄弟顺序都使用迭代遍历;重复 ID 保留第一项,缺少父节点的频道作为根,孤立环从其第一项展开,每个 ID 至多输出一次。深度由实际输出层级计算,不改变共享解析器的兼容范围。正常前驱顺序和 5,000 层目录用例通过。
|
||||
|
||||
验收:自环、双节点环、孤儿节点、重复 ID、深层目录,以及正常兄弟顺序;输出可终止、节点不重复、页面仍可操作。
|
||||
|
||||
## 连接与命令问题的修复结果
|
||||
|
||||
本节及后续“近期修复”记载此前已实施的工作;其中的“本批”指对应历史批次。本轮未重做这些修复,统一测试继续覆盖已有回归。
|
||||
|
||||
### 04-H 命令发送异常立即清理等待资源
|
||||
|
||||
当前实现:[commands.ts](../web/src/voice/commands.ts)。原入口先创建默认 8 秒计时器、登记等待,再发送命令。同步发送抛错后 Promise 拒绝,但登记和计时器未立即清理。本批通过发送故障注入复现该缺口。
|
||||
|
||||
已实施:每条命令拥有统一且幂等的结束函数,成功、服务端错误、发送异常、超时及断开都通过它清理。确认等待绑定原 socket 与连接代次,保留默认 8 秒期限、共享命令类型和现有调用接口。
|
||||
|
||||
已验证:正常确认、服务端拒绝及错误码、发送抛错、超时、断开、重复回复、已排队的旧期限和旧 socket 回复;发送失败后计时器立即移除,旧操作不影响替代连接的命令。
|
||||
|
||||
### 04-I 加入凭证请求可取消且等待有期限
|
||||
|
||||
当前实现:[connection.ts](../web/src/voice/connection.ts)。原请求只有代次检查,没有取消信号和应用层期限;请求或响应体迟迟不返回时,页面持续处于连接中。原 socket 关闭异常还会跳过后续页面状态清理。本批已通过边界替身复现。
|
||||
|
||||
已实施:连接控制器持有取消器、15 秒期限、socket 和连接代次。期限覆盖偏好就绪、HTTP 请求及响应体;新连接和断开立即取消旧请求,旧期限与迟到响应不能写回。socket 关闭前解绑所属监听,关闭异常不妨碍其余状态清理。超时用 `REQUEST_TIMEOUT` 和五语提示说明网关等待失败。
|
||||
|
||||
已验证:请求无响应、响应体挂起、主动取消、连续连接不同目标、取消后迟到成功或失败、旧期限、socket 关闭异常和网关关闭码。邀请、身份、频道、密码和中继参数保持一致。浏览器取消不撤销服务端已执行的邀请使用或凭证签发,服务端的有效期和一次性使用规则保持不变。
|
||||
|
||||
### WebRTC 与诊断实现的验证结果
|
||||
|
||||
[webrtc-transport.ts](../web/src/voice/webrtc-transport.ts) 已集中 peer、输入混音、电平监测、ICE 等待、answer 期限和兼容回退;[webrtc-playback.ts](../web/src/voice/webrtc-playback.ts) 已集中播放元素、播放中的 Promise 和用户手势重试监听。原始麦克风和 PCM 由采集层管理,控制 socket 由连接模块管理,入口负责组装。
|
||||
|
||||
诊断请求现由采样模块管理,保留等待期限直至网关和浏览器统计均返回,并检查原 socket、连接与传输代次和 peer;断开立即结束消费者等待。清理异常、旧播放重试、旧协商期限、回退信令失败、统计挂起、替换 peer 和诊断发送失败均已纳入 [voice-session.test.mjs](../web/test/voice-session.test.mjs),当前全部通过。此处验证浏览器边界行为,不等同于真实网络媒体验收。
|
||||
|
||||
### 04-J 诊断采样与展示只比较同一来源
|
||||
|
||||
当前实现:[audio-diagnostics.ts](../web/src/voice/audio-diagnostics.ts) 与 [useWebClientPerformance.ts](../web/src/composables/useWebClientPerformance.ts)。原面板直接相减前后样本中的下行计数,来源可能分别为 RTP 包、兼容音频帧或网关发送帧。peer 替换后新计数若大于旧值,也会被误当成同一流的增长。采样失败时保留旧活动状态,已排队的旧轮询会设置运行标志却无法清除;卸载后手动刷新仍能发起请求。
|
||||
|
||||
已实施:采样模块拥有等待登记、总期限、兼容计数和浏览器统计。样本携带仅用于浏览器内部的 `scopeId`,不修改网关协议;连接或传输变化以及会话释放会使范围失效。兼容计数随会话重置,旧快照保持独立。面板只比较相同范围、传输和下行计数来源;缺失或拒绝的采样清除旧状态,下一样本重新建立基线。轮询开始前与结果返回后均校验代次,卸载同时禁止旧回调和手动刷新。
|
||||
|
||||
[W3C WebRTC 统计定义](https://www.w3.org/TR/webrtc-stats/#dom-rtcsentrtpstreamstats-packetssent) 将 `packetsSent` 定义为已发送包总数。据此,上行丢包估算分母使用发送数,不再重复加上丢失数;下行仍以接收数加丢失数计算。浏览器提供的 `fractionLost` 用于采样中的上行百分比,否则按计数估算。RTCP 反馈和本地计数采样时间可能不同,不能将该估算表述为精确网络测量。
|
||||
|
||||
已验证:10 项实际 Vue 状态用例,其中 8 项先失败后通过;语音会话新增 3 项范围与重连用例并增强 1 项丢包率断言,均先失败后通过。保留每 2 秒轮询、采样总期限和已有音频状态提示。并行运行时发现 Vite 即使关闭 HMR 仍监听默认 WebSocket 端口,三个无界面测试入口现同时设置 `ws: false`,无需占用该端口。
|
||||
|
||||
## 近期修复的浏览器媒体问题
|
||||
|
||||
### 04-E 保留可用发送链并完整清理失败候选
|
||||
|
||||
修改前位置:`c9740c4` 中 [useVoiceWebSocket.ts](../web/src/composables/useVoiceWebSocket.ts) 的混音创建、替换和伴奏启停函数,原第 752–918 行。当前实现位于 [webrtc-input.ts](../web/src/voice/webrtc-input.ts) 和 [accompaniment.ts](../web/src/voice/accompaniment.ts)。
|
||||
|
||||
原实现的顺序及缺口:
|
||||
|
||||
- `createWebRtcMixStream` 先调用 `stopWebRtcMix`,其中会停止当前输出音轨;之后才创建新节点并调用 `sender.replaceTrack`。创建或替换失败时,旧音轨已经结束,没有可用旧链供回滚。
|
||||
- 更换伴奏时,在混音接入成功前就停止旧伴奏,并发送 `active: true`。失败后再发送 `false`,无法保留原本正常的伴奏;错误统一归为 `permission`,也不能区分用户授权与音频处理失败。
|
||||
- 混音节点先在局部变量中创建,之后才写入清理函数使用的引用;如果中途创建或连接失败,已取得的候选节点及输出音轨缺少完整释放路径。
|
||||
- 停止伴奏也会重建整个混音并替换发送轨道,因而停止操作同样依赖新节点分配成功。
|
||||
|
||||
本批通过故障注入实际复现旧发送轨道结束、旧伴奏丢失、部分节点及输出音轨未释放、停止依赖新分配,以及混音节点释放异常中断会话清理。测试使用实际 composable 和浏览器边界替身,不代表已测真实浏览器的故障频率或音质。
|
||||
|
||||
已实施:每个 WebRTC peer 保持稳定输出轨道,仅接入或移除伴奏源;新源连接成功后再解除旧源并停止旧采集。混音模块拥有节点和输出流,独立释放部分分配及关闭资源。只有接入成功后才更新活动状态;音频处理失败使用独立错误码和五语提示,可选内容提示失败不再遗留采集。
|
||||
|
||||
已验证:节点分配或连接失败保留原麦克风输出与旧伴奏;启停伴奏不结束或替换发送轨道;停止不依赖新输出分配;候选失败和重复清理释放所属资源。麦克风静音和音量设置在启停期间保持有效,伴奏不经过麦克风降噪与增益,也不额外添加固定衰减。
|
||||
|
||||
### 04-F 停止操作立即释放已取得的候选采集
|
||||
|
||||
位置:[accompaniment.ts](../web/src/voice/accompaniment.ts),由语音入口调用;回归位于 [voice-session.test.mjs](../web/test/voice-session.test.mjs)。以下描述修改前的行为。
|
||||
|
||||
`getDisplayMedia` 返回后,候选 `nextStream` 在等待 `applyConstraints` 期间仍是局部变量。停止或断开只清理已提交的 `accompanimentStream` 并使代次失效;候选流需等约束 Promise 结束,执行后续失效检查才被停止。现有取消用例也是先结束约束等待,再断言音轨已停止,没有覆盖立即释放。
|
||||
|
||||
此外,音轨的 `ended` 监听在约束等待后才注册,提交前也没有检查 `readyState`。若用户在等待期间结束采集,代码仍可能将已结束的音轨标记为活动。
|
||||
|
||||
已实施:伴奏控制器同时拥有当前流和已取得但未提交的候选流。停止、断开或新操作取代旧操作时,立即释放候选资源;仍未返回的授权请求在结果到达时立即释放。操作绑定原混音目标与代次,提交前复核目标和音轨状态,旧结束事件不能停止新采集。
|
||||
|
||||
已验证:约束 Promise 未完成时音轨已经停止;等待期间结束采集不会发送活动状态;迟到授权和旧失败不影响新伴奏。现有四项伴奏用例继续保留,其中取消用例增加立即释放断言;另验证无音频来源失败保留旧伴奏、断开清除旧错误,以及采集处理约束与五语错误映射。
|
||||
|
||||
### 04-G 电平监测失败不影响语音与后续连接
|
||||
|
||||
位置:[microphone-meter.ts](../web/src/voice/microphone-meter.ts),由语音入口的监测启停函数组装。
|
||||
|
||||
原实现只在全部节点连接完成后才记录清理引用,分析器分配或连接失败会遗留先前创建的节点。计时器回调读取全局分析器引用,已排队的旧回调会读取替代连接的分析器并更新电平;读取异常没有受控处理,释放异常也可能中断 peer 和麦克风清理。五项故障用例均在修复前复现。
|
||||
|
||||
已实施:每个监测实例独立拥有节点与计时器,停止先使回调失效,再逐项释放资源。准备或读取失败只停止电平监测,清除电平与发言提示,保留麦克风流和语音 peer。已验证 512 点采样、50 ms 周期、原有 RMS 电平比例及上限保持一致;此处不声称真实设备的电平与音质已验收。
|
||||
|
||||
## 本批施工前的只读整理结果
|
||||
|
||||
- 以 `cdc5f03` 和当前工作区为依据,核对模块职责、文件规模、36 个测试入口及既有打包流程。
|
||||
- 新增 06-I 皮肤异步激活归属、06-J 首屏等待期限两项待修改问题,说明静态依据、触发顺序、修改方向和验收条件,未声称已经复现。
|
||||
- 将管理页三组件由“待提取”改为“工作区已有、待验收”,列明样式边界和真实模板交互检查;保留客户端拆分、协议、媒体、Android 和发布待办。
|
||||
- 保留历史实施记录;此次仅修改本文,开始时已有的业务代码与测试改动保持原样。
|
||||
|
||||
## 身份模块施工前的只读整理结果
|
||||
|
||||
- 以 `28eda60` 为基线更新当前结构与剩余待办,区分静态判断、待验收项目和历史验证结果。
|
||||
- 新增 06-H 身份文件异步覆盖问题,细化 06-C 的组件职责、状态归属、样式和交互验证方向。
|
||||
- 保留既有修复记录;只修改本文,未修改业务代码、测试、配置、依赖和本地产物,未运行测试或构建,未提交或推送。
|
||||
|
||||
## 本批施工前的只读整理记录
|
||||
|
||||
- 基于 `a97fa54` 更新当前基线,核对模块职责、入口规模和 35 个显式测试文件的存在性。
|
||||
- 新增五项待修改问题,写明源码依据、触发条件、大致修改方向和验收要求;按用户交互问题、生命周期、结构拆分和真实环境安排后续顺序。
|
||||
- 将已实施的 04-E 至 04-J 移出剩余待办表,保留历史实现及测试结果,避免重复施工。
|
||||
- 本轮仅修改本文;未修改业务代码、测试、配置或依赖,未运行测试和构建,未删除产物,未提交或推送。
|
||||
|
||||
## 连接与命令实施前的只读整理结果
|
||||
|
||||
- 更新当前提交、工作区状态、模块职责和文件规模,保留既有实现与验证记录。
|
||||
- 新增命令发送异常清理、加入凭证取消与期限两项待修改问题,注明静态依据、修改方向及验收条件。
|
||||
- 将已有 WebRTC 拆分列为待核对实现,按连接与命令、页面组件、真实环境和发布整理后续顺序。
|
||||
- 该轮仅修改本文;原有源码与测试改动保留,未新增代码修改、测试运行、构建、提交或推送。其后的施工与验证见本批实施记录。
|
||||
|
||||
## 前轮只记录的整理结果
|
||||
|
||||
- 更新到 `c9740c4` 的干净代码基线,整理当前模块边界及已完成事项。
|
||||
- 新增伴奏混音失败回滚和候选采集取消的具体待办,注明静态依据、建议方案与验收条件。
|
||||
- 明确前端拆分、页面整理、契约、真机及发布的后续方向,保留下方历史实施记录。
|
||||
- 仅修改本文;未修改源码、测试、配置或依赖,未运行测试和构建,未删除产物,未提交或推送。
|
||||
|
||||
## 已有实施与验证记录
|
||||
|
||||
以下保留实施与验证记录,段落内“本批”指该批次。旧结果仅适用于各自提交或快照;播放、录音及设备验证见各自条目。Android 预览及首次清单提交为 `0276b6e`;第一批构建、测试及文档修正记录对应 `5c11bd9`。
|
||||
|
||||
| 事项 | 已实施内容 | 验证依据 |
|
||||
| --- | --- | --- |
|
||||
| 01 | 新增 `npm run verify`;根目录前端构建包含类型检查;CI 覆盖 `dev`、`master`、PR 和手动运行;镜像及发布包工作流先调用同一验证工作流 | 本地完整验证成功;`5c11bd9` 的远端 `verify` 和 `docker-smoke` 均已通过 |
|
||||
| 02 | 新增凭证、身份占用、会话状态与清理、目录同步、重连策略等 5 个测试文件,共 18 项测试 | 单元测试由 33 项增加至 51 项,全部通过 |
|
||||
| 02 发现的问题 | 离开成员可能被迟到的分段快照重新加入目录;记录离开状态,直到明确重新进入或连接目录重置 | 回归测试先复现失败,修复后通过;同时覆盖迟到更新、重新进入和目录重置 |
|
||||
| 08 | 更新 `CLAUDE.md` 的协议、音频、配置、容量、构建及 Android 边界说明 | 对照入口、SDK 适配、配置导入、常量及工作流核对 |
|
||||
|
||||
第一批本地验证环境为 Windows、Node.js 24.12.0,执行过 `npm run verify`,包含 51 项单元测试、后端 TypeScript 编译及前端类型检查和生产构建。随后共享协议迁移增加了 7 项测试,当时 58 项测试及前后端构建通过。该阶段前端存在单个产物超过 500 kB 的提示;本批路由分包后的结果见事项 06。
|
||||
|
||||
此前记录的[提交 `5c11bd9` 的 GitHub Actions](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36796987777) 已完成并成功,包括 Node.js 22.22.2 下的测试与构建、Docker 镜像构建和容器 HTTP 健康检查。该结果不覆盖随后新增的共享协议和媒体改动;后续提交需重新通过 CI。
|
||||
|
||||
### 共享协议与前端生命周期实施记录
|
||||
|
||||
- 对应提交 `ab4ad48` 已推送至 `dev`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36799503102) 的验证、Docker 构建和容器健康检查均通过。
|
||||
- 共享命令、服务端消息、屏幕共享模型和皮肤目录类型集中到 `src/shared/`;服务端发送与前端接收均接入公共契约。
|
||||
- 屏幕共享控制器只依赖传输状态与发送接口,自行管理采集音轨、PeerConnection、ICE 配置、协商计时器和统计。
|
||||
- 新增 11 项前端测试。其中 9 项先复现了失败:旧 socket 污染新成员列表、异常断开未停止共享、断开后获批的共享采集未释放、取消后协商仍发送信令、旧开始确认干扰新采集、旧授权结果覆盖新采集参数、缺少视频轨时其他轨道未释放,以及麦克风授权迟到和旧授权阻塞新会话。
|
||||
- 本地 `npm run verify` 通过:69 项测试、后端编译、前端类型检查及生产构建;开发服务器实际请求确认共享协议与屏幕共享模块可返回成功响应。Vite 依赖扫描限定为网页入口,避免扫描 Android 生成页面。
|
||||
- 尚未完成真实 TeamSpeak 双向音频、WebRTC 语音回退、浏览器实际媒体连接、Android 真机及各平台发布包验证。此处的模拟边界测试只证明相应状态和资源生命周期行为。
|
||||
|
||||
### 服务端桥接拆分实施记录
|
||||
|
||||
- 对应提交 `254bc4b`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36800632198) 的测试、构建、Docker 构建和容器健康检查均已确认成功。
|
||||
- 拆出命令处理、目录展示、音频统计和屏幕共享协调四个模块,入口保留会话组装职责;原有统计类型导出保持兼容。
|
||||
- 新增 20 项测试,其中 7 项先复现失败后修复:统计快照共享实时对象、结构化权限错误映射遗漏、其他成员换频道误停共享、跨服务器客户端 ID 混用、重复或迟到的原生发布通知生成多余共享、最后会话离开后发现状态未重置,以及旧加入失败移除新观看关系。
|
||||
- TeamSpeak 连接中断时清理共享关系;原生源频道从当前服务器目录确定,无法确认所属频道时不猜测广播范围。
|
||||
- 本地 `npm run verify` 通过:89 项测试、后端编译、前端类型检查及生产构建。该提交远端 CI 已通过,真实媒体联调仍待验证。
|
||||
|
||||
### 媒体协商与平台启动实施记录
|
||||
|
||||
- 对应提交 `8138969`;本批再次查询确认其[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36804423805) 的验证、Docker 构建和健康检查成功。以下其余内容为该批次已有记录。
|
||||
- 前端新增 14 项、服务端桥接新增 8 项行为测试;其中 15 项在修改前实际复现失败,修复后通过。取消后的采集、协商、播放及服务端音频回调不再修改新会话。
|
||||
- 协商失败和音轨挂载失败均可回到兼容采集,测试验证实际发送 1,920 字节 PCM 帧,并且不会错误报告麦克风故障。此处未使用真实网络媒体连接。
|
||||
- Android 启动已独立到 `web/src/platform/`,7 项启动测试通过。错误、超时和取消统一清理监听器及计时器,重试仅重做健康握手。
|
||||
- 忽略规则和本地产物说明已整理;代表性发布包、缓存和实验编解码脚本被忽略,共享协议、平台源码、Android Java、Gradle wrapper 和皮肤资源仍可跟踪。
|
||||
- 该批次本地 `npm run verify` 完整通过,共 118 项测试。额外使用真实原生 Opus 将 1,920 字节 PCM 编为 202 字节并解回 1,920 字节,未使用实验替身;这只证明本机编解码路径可运行。
|
||||
- Android 资源打包、Capacitor 同步及 `assembleDebug` 通过,生成 arm64-v8a、armeabi-v7a 和 x86_64 三种 APK。x86_64 APK 在 Android 15 只读模拟器安装、冷启动成功,`/health` 返回 `webspeak-android`,公共配置返回 `mobile: true`,截图确认 WebView 已显示首页。窄屏头部重叠已列入事项 06;真实 TeamSpeak、Android 真机和后台音频仍未验收。
|
||||
|
||||
### 前轮只读文档核对记录
|
||||
|
||||
- 只读取 Git 状态、提交记录、相关源码、测试定义、构建脚本和已有文档,更新本清单。
|
||||
- 修正基线、文件规模和状态:Android 启动及忽略规则已提交;WebRTC 契约、管理页文案、头部组件和路由延迟加载已有未提交实现。
|
||||
- 新增路由全局样式隔离缺口及布局待验收事项,明确后续顺序、模块边界和完成条件。
|
||||
- 未执行代码修复、测试或构建,未删除产物,未提交或推送。后续实施需以新的验证结果更新状态。
|
||||
|
||||
### 共享契约与页面请求层实施记录
|
||||
|
||||
- 对应提交 `9bfe4b9`;本批重新查询确认其 [CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36808150705) 的应用验证、Docker 构建和健康检查成功。
|
||||
|
||||
- 完成 WebRTC 控制契约与 SDP 校验统一,新增 3 项兼容和边界测试。
|
||||
- 管理输入与响应模型集中到共享目录;新增 8 项请求层用例和 1 项真实 HTTP 集成用例,临时数据库覆盖配置、密码和中继令牌动作、邀请、登录状态及 SQLite 备份。未连接外部 TeamSpeak 服务。
|
||||
- 管理页文案、样式、网络请求及首页头部独立成模块,路由改为延迟加载。修复头部窄屏分行、长品牌名溢出、状态圆点、管理样式路由限制及暗色选择框。
|
||||
- 本地 130 项测试、后端编译、前端类型检查和生产构建通过。最后的样式与错误反馈调整再次通过前端构建;浏览器用隔离的本机测试数据验证保存失败和成功、登录过期、退出失败以及管理页面展示。
|
||||
- 该批没有重做真实语音、Android 设备和跨平台发布包验收,也没有完成 04、05 和 06 的所有剩余拆分。
|
||||
|
||||
### 前轮只读梳理补充记录
|
||||
|
||||
- 核对 Git 状态、主要模块、测试定义、构建与发布工作流,以及现有文档;更新本文的基线、待办、修改方向与验收要求。
|
||||
- 记录远端播放迁移的旧函数引用,补充录音、设备切换、管理请求竞态、剩余文案及平台文档状态等待办。
|
||||
- 仅更新本文;未修改业务代码、测试、配置或依赖,未运行测试与构建,未提交或推送。已有未提交源码继续保留。
|
||||
|
||||
### 远端播放与录音测试实施记录
|
||||
|
||||
- 对应提交 `ad83c87`;[远端 CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36809738335) 的应用验证、Docker 构建和健康检查已确认成功。
|
||||
- 远端播放控制器统一拥有每位成员的解码器、播放源、增益节点和排队时间;重置、失败和成员退出都释放所属资源,旧回调不能清理替代资源。
|
||||
- 修复提取过程中遗漏的成员退出调用点。该用例先复现成员无法移除,修复后验证只停止离开者的音频。
|
||||
- 录音测试独立管理操作身份、录音器、五秒期限与试听 URL。六项录音问题先复现失败后修复:断开未停止、连续启动未停止旧录音、旧权限错误清除新状态、取消后仍创建录音器、自然结束仍显示活动,以及启动失败遗留采集。
|
||||
- 相对起始提交新增 19 项测试。当前 149 项测试、后端编译、前端类型检查和生产构建通过;录音与解码使用浏览器边界替身,未声称真实音质或设备兼容性已通过。
|
||||
- 输入输出设备切换、管理请求竞态、剩余模块提取、真实 TeamSpeak、Android 真机与各平台发布包仍待完成,持续目标保持未完成。
|
||||
|
||||
### 设备切换与采集连续性实施记录
|
||||
|
||||
- 输入设备和降噪设置共用配置操作,只有当前操作能够提交或回滚,持久化保存最后成功的选择。麦克风授权失败保留原有 WebRTC peer 和采集流。
|
||||
- 输出切换按 AudioContext 或音频元素分别串行执行;断开后跳过排队任务,旧端点回调不能设置新端点。某个端点拒绝时尝试恢复先前输出。
|
||||
- 设备列表只采用当前查询结果;迟到的成功或失败不能覆盖新列表,或在断开后恢复错误提示。
|
||||
- 分离采集申请与已运行处理链的失效标识,保持等待新设备及授权失败时的兼容 PCM 发送。替换处理链或断开后,旧回调失效。
|
||||
- 新增 15 项测试,其中 10 项先复现失败后修复,包括复查发现的上一批录音提取遗漏:关闭设置但未启动录音时,仍须释放独立采集。
|
||||
- `npm run verify` 通过 164 项测试、后端编译、前端类型检查及生产构建。实际媒体设备和 TeamSpeak 仍未验收;剩余采集模块提取、管理页面与服务端任务继续推进。
|
||||
|
||||
### 前轮只记录的整理结果
|
||||
|
||||
- 以 `407311d` 和当前工作区为依据,更新模块现状、待修改优先级、建议顺序及验收标准。
|
||||
- 登记已有 7 个源码与测试文件的未提交改动,明确三个管理模块尚未接入页面、新增页面测试尚未进入统一命令。
|
||||
- 仅更新本文。未运行测试或构建,未修改源码、测试、配置、依赖及已有草稿,未提交或推送。
|
||||
|
||||
### 管理页面请求与状态实施记录
|
||||
|
||||
- 起始提交为 `407311d`,实施结果已纳入 `11d2fa5`;后者的 [CI](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36813991856) 及 Docker 健康检查已记录成功。该结果不覆盖之后的未提交多语言改动。
|
||||
- 三个功能模块已接入实际页面,请求分别绑定登录会话、页面与功能生命周期,覆盖 JSON、上传校验和备份读取。过期响应不再修改当前页面或触发旧跳转。
|
||||
- 保存按快照保留后续编辑,秘密值与更新动作成组处理;保存不回填过期探测信息。各功能提交状态独立,皮肤操作互斥,撤销邀请防重复,退出失败保留草稿。
|
||||
- 相对基线新增 25 项测试,共 189 项通过,后端编译、前端类型检查和生产构建通过。本批 10 个页面测试先复现失败再通过;控制 HTTP 顺序的页面测试不声称真实登录或数据库端到端已通过。
|
||||
- 本机内存数据库与模拟响应的浏览器检查确认:旧保存响应保留新输入,保存失败保留草稿;皮肤请求期间相关控件禁用,失败保留启用状态,成功切换与默认项保存正常;跨功能页清除旧错误。浏览器日志未见警告或错误。
|
||||
- 临时浏览器页和预览进程已关闭。剩余内联文案、页面组件、媒体模块、真实 TeamSpeak、Android 真机及各平台发布包验收继续推进,完整目标尚未完成。
|
||||
|
||||
### 本次待修改文档整理记录
|
||||
|
||||
- 基线更新为 `11d2fa5`,保留各批历史实施及验证范围,避免把已修复的管理请求问题再次列为待开发。
|
||||
- 登记三处现有未提交源码,说明五语文案与格式化已有实现;新增管理页窄屏长文案布局待办 06-D。
|
||||
- 建议实施顺序为管理页文案与布局收尾、剩余媒体职责整理、页面组件拆分;真实服务、真机和干净打包按独立验收项推进。
|
||||
- 本次整理仅更新本文,未继续修改源码、测试、配置或依赖,未重新运行测试与构建,未提交或推送。
|
||||
|
||||
### 管理页五语与窄屏工具栏实施记录
|
||||
|
||||
- 五种语言各有 267 个显式键,不再通过展开英语字典掩盖缺项;统一时间、状态、审计事件及错误映射,保留未知值回退和两类密码错误的区别。
|
||||
- 管理页状态圆点与按钮分组,窄屏主题按钮采用图标,状态文字和按钮名称保留辅助技术可读性。
|
||||
- 当前代码通过 19 项实际 SFC 页面测试和前端类型检查、生产构建;此前同批文案快照通过完整 189 项测试和前后端构建。
|
||||
- 本机隔离数据浏览器检查覆盖五语状态、时长、审计与中继失败提示;五语及 320、393、740、1440 像素共 20 组工具栏边界检查全部通过,键盘主题切换和明暗布局正常,控制台未见警告或错误。临时页面、视口覆盖和预览进程已清理。
|
||||
- 本批没有验证真实 TeamSpeak 媒体或 Android 真机;后续继续采集失败回滚、设备热插拔、媒体模块提取及页面组件拆分。
|
||||
|
||||
### 采集处理链与设备热插拔实施记录
|
||||
|
||||
- 新增 `web/src/voice/microphone-capture.ts`,集中管理原始音轨、处理节点、RNNoise、worklet 加载、PCM 激活和释放;处理设置类型由原入口继续导出,保持调用兼容。
|
||||
- 新处理链完全就绪后才替换旧流;节点创建失败、worklet 等待及取消不影响仍在运行的旧链。中断准备立即释放候选音轨与节点,迟到回调不能向新连接发送音频。首次创建失败现在产生麦克风错误提示。
|
||||
- 设备热插拔复用输入与输出切换事务,默认输入替换后重新协商 WebRTC;失败保留最后成功设置,输出失败提供五语提示。新的失败切换以实际已运行的处理链作为回滚基线。
|
||||
- 新增 10 项回归测试,其中 7 项先复现既有问题;另外覆盖 worklet 正常发送、准备中断的资源清理,以及迁移后初始设备查询期间断开的取消语义。
|
||||
- `npm run verify` 通过 199 项测试、后端编译、前端类型检查与生产构建。媒体设备、worklet 和 WebRTC 使用边界替身,不能据此认定真实音质、物理热插拔或 TeamSpeak 双向语音已验收。
|
||||
- 伴奏与 WebRTC 控制、服务端音频、剩余页面组件、Android 真机及干净发布包验证尚未完成。
|
||||
|
||||
### 服务端音频与关闭流程实施记录
|
||||
|
||||
- 提取 `SessionAudioTransport`,三条媒体路径共用当前会话校验、耳语分发与统计;迟到帧不能写入已移除会话,WebRTC 与兼容 PCM 不重复转发。
|
||||
- 保留 1,920 字节 PCM、下行 3 字节头和 4,096 字节背压阈值;补齐无效说话者标识、编码失败与发送失败的受控处理。
|
||||
- 会话构造失败释放准入名额;音频清理早于等待 peer 关闭;保留 WebSocketServer 关闭监听,最后的统计读取失败不打断资源清理。
|
||||
- WebRTC 逐项容错释放资源,共享同一关闭 Promise;本批实际先复现资源释放中断和并发关闭提前完成,再验证修复。补充关闭失败结果共享测试。
|
||||
- 新增 20 项测试,统一入口包含 31 个测试文件。`npm run verify` 通过 219 项测试、后端编译、前端类型检查和生产构建。
|
||||
- 网关集成测试使用本机真实 HTTP/WebSocket 和原生 Opus,外部 TeamSpeak SDK 使用替身;没有据此认定真实服务、网络媒体或设备验收完成。SDK 事件、剩余前端媒体与页面拆分继续推进。
|
||||
|
||||
### 成员头像生命周期实施记录
|
||||
|
||||
- 从桥接入口提取 `MemberAvatarLoader`,拥有计时器和下载批次;重连清空缓存并立即失效旧工作,终止会话先关闭头像控制器再等待其他资源。
|
||||
- 三项网关集成用例先复现再通过:终止后迟到结果回填且继续下载、等待心跳响应时错误停止刷新、SDK 中断后继续使用旧批次结果。
|
||||
- 七项独立测试覆盖 UID 去重且同步所有匹配成员、权限或格式失败、旧成功和失败与新批次交错、定时器清理、成员 ID 重用、50 位成员分批及新增成员调度。
|
||||
- 统一入口包含 32 个测试文件,本地 `npm run verify` 通过 229 项测试和前后端构建。外部 SDK 下载仍使用替身;实际服务器头像权限与文件传输兼容不据此认定已验收。
|
||||
- 音频批次 `972ee79` 的 CI 与 Docker 检查已确认通过。头像批次仍需对应提交的独立 CI;SDK 目录事件整体拆分及真实媒体、真机与发布包验收继续保留。
|
||||
|
||||
### SDK 头像下载边界实施记录
|
||||
|
||||
- 前一头像控制器批次 `e9b8c2b` 的 CI 与 Docker 检查已确认通过。
|
||||
- 复查并修复下载方法内部重新读取 `this.client` 的问题:各异步阶段使用原 SDK 客户端,结合连接代次校验;主动断开、SDK 中断及开始连接都会使旧下载失效。
|
||||
- 新增 6 项实际适配方法测试,其中 4 项先复现失败:旧元数据在替代客户端上发起传输、初始化期间断开后空引用、断开后返回已下载内容、同一 SDK 对象重用时恢复旧请求。另覆盖正常内容与 UID 校验、旧客户端断线不能干扰新请求。
|
||||
- 当前统一入口包含 33 个测试文件,`npm run verify` 通过 235 项测试和前后端构建。SDK 网络边界使用替身,本批未声称实际 TeamSpeak 文件传输或媒体连接已验收。
|
||||
- 剩余 SDK 目录事件提取、前端媒体与页面组件、真实服务及平台验收仍未完成,完整目标保持进行中。
|
||||
|
||||
### SDK 会话事件与目录实施记录
|
||||
|
||||
- 新增 `SessionEventCoordinator`,集中 SDK 订阅、目录与成员投影、自身频道、耳语目标收敛、频道事件、聊天及头像协调;桥接入口继续负责准入、连接恢复与传输组装。
|
||||
- 先复现并修复关闭等待期间目录回填、重连等待期间旧快照污染下一连接,以及十类旧 SDK 客户端事件进入替代会话。监听按所属模块解绑,已捕获的旧回调也会被拒绝。
|
||||
- 额外先复现断线通知早于踢出时继续重连的问题;现在两种到达顺序均终止会话,保留踢出错误码和服务器原因。
|
||||
- 新增 19 项测试,其中 13 项先失败后通过;统一入口共 34 个测试文件,`npm run verify` 通过 254 项测试、后端编译、前端类型检查和生产构建。
|
||||
- `cc9714b` 的 CI 与 Docker 检查已确认成功。本批真实服务、网络媒体、Android 真机及发布包未验收,剩余前端媒体与页面组件继续推进。
|
||||
|
||||
### 伴奏采集与 WebRTC 输入混音实施记录
|
||||
|
||||
- 提取 `accompaniment.ts` 与 `webrtc-input.ts`,分别拥有候选和当前采集,以及稳定的 WebRTC 输出、麦克风增益和伴奏源;语音入口由 2,129 行降至 1,988 行,页面调用接口保留。
|
||||
- 伴奏启停不再结束或替换正在发送的输出轨道,新源连接成功后才替换旧源和旧采集。节点创建或连接失败保留可用输入;部分分配和单节点释放失败均不会遗漏后续清理。
|
||||
- 停止、断开或新采集取代旧采集时,立即释放已经取得的候选流,不等待约束结束;准备期间结束的音轨不能被激活。可选内容提示失败不丢失采集,旧授权失败不影响替代操作。
|
||||
- 活动状态只在接入成功后发布;音频接入失败与授权失败分开提示,新增五语文案。麦克风静音和增益、应用音频不经过语音处理的约束保持不变。
|
||||
- 新增 14 项测试并增强 1 项已有取消用例,其中 12 项先失败后通过。`npm run verify` 通过全部 268 项测试、后端编译、前端类型检查和生产构建,显式入口仍为 34 个测试文件。
|
||||
- 前一事件协调提交 `c9740c4` 的 CI 与 Docker 检查已确认成功。本批媒体用例使用浏览器边界替身,未声称真实音质、TeamSpeak 双向语音、Android 真机或发布包验收完成;WebRTC 传输、连接与命令及页面组件仍有后续工作。
|
||||
|
||||
### 麦克风电平监测实施记录
|
||||
|
||||
- 前一伴奏提交 `0f0c52d` 的 CI 与 Docker 构建及健康检查已确认成功。
|
||||
- 提取 `microphone-meter.ts`,独立拥有分析节点、静音输出与计时器;语音入口只处理电平和发言提示,降至 1,960 行。
|
||||
- 五项用例先复现再通过:分析器不可用时遗留输入源、连接失败遗留候选节点、旧计时器读取替代会话、分析读取异常外泄,以及释放异常阻断会话清理。另验证原有周期、RMS 比例、上限和停止行为。
|
||||
- 监测失败不会关闭语音 peer 或停止外部拥有的麦克风;失效回调不再读取新分析器,停止或读取失败清除展示状态。
|
||||
- 本批新增 6 项测试,`npm run verify` 通过 274 项测试、后端编译、前端类型检查和生产构建。真实媒体、Android 真机和跨平台发布仍未验收。
|
||||
|
||||
### WebRTC 传输与诊断实施记录
|
||||
|
||||
- 提取 `webrtc-transport.ts` 与 `webrtc-playback.ts`,分别拥有协商尝试及播放元素;原始麦克风和 PCM 仍归采集层。语音入口由 1,960 行降至 1,743 行。
|
||||
- 协商尝试独立持有 ICE 等待和 answer 期限;播放元素独立持有手势重试与播放 Promise。旧计时器和旧播放回调不能触及替代实例,重叠手势合并为一次播放尝试。
|
||||
- 单个播放元素或 peer 释放失败不再中断其余清理;回退信令发送失败仍释放 WebRTC 并恢复兼容采集,旧回退授权失败不修改新会话。
|
||||
- 诊断保留总期限直至两端统计完成,断开立即结束等待;旧 peer 的统计不混入新会话,发送失败受控返回空结果。
|
||||
- 增加 13 项回归用例,其中 12 项先失败后通过。接续检查确认既有验证进程成功完成;本批后续 300 项统一验证也覆盖这些用例。真实媒体仍未验收。
|
||||
|
||||
### 连接控制与命令等待实施记录
|
||||
|
||||
- 提取 `connection.ts` 与 `commands.ts`,独立拥有凭证请求、socket、连接代次,以及命令确认登记和期限。页面状态与业务错误映射仍由入口持有,入口降至 1,664 行。
|
||||
- 命令发送异常立即移除登记和计时器;成功、拒绝、超时和断开统一结束且幂等。旧 socket 的回复和旧期限不影响替代命令,默认 8 秒确认期限不变。
|
||||
- 凭证获取增加 15 秒期限,覆盖偏好等待、HTTP 和响应体读取。断开和替换立即 abort,旧响应不再继续读取正文;旧期限无法取消新请求。socket 关闭失败不再阻止状态清理,保留网关关闭码优先规则。
|
||||
- 增加 13 项测试,其中 7 项故障回归和 1 项新提示缺失检查先失败后通过。另验证命令确认与错误码、旧期限、请求字段及五语超时提示。旧音频事件用例改为执行已捕获的回调,继续覆盖监听解绑后的迟到执行。
|
||||
- `npm run verify` 通过 300 项测试、后端编译、前端类型检查和生产构建;显式入口仍包含 34 个测试文件。起始提交 `44f2b7d` 的 CI 与 Docker 检查已重新确认成功,本批远端结果按新提交核对。
|
||||
- 本批未完成真实 TeamSpeak 双向语音、Android 真机或跨平台发布验收;诊断与状态投影、页面组件仍有后续工作,完整目标继续进行。
|
||||
|
||||
### 诊断采样与面板状态实施记录
|
||||
|
||||
- 起始提交 `6700466` 的 CI、Docker 构建和 HTTP 健康检查已查询确认成功。
|
||||
- 提取 `audio-diagnostics.ts`,集中统计等待、期限、来源范围和兼容播放计数;原有诊断类型通过语音入口继续导出,入口降至 1,519 行。
|
||||
- 样本比较增加范围与来源检查,修复跨传输、跨 peer 和浏览器统计缺失时的虚假速率。采样捕获 WebRTC 代次,开始于 peer 分配前的旧探测不能跨越失败回退。
|
||||
- 面板采样失败清除旧活动状态,下一次成功重新建立基线;旧轮询、卸载后的回调与手动刷新不再开启请求或遗留运行标志。会话恢复重置兼容计数且不修改旧快照。
|
||||
- 修正上行丢包率分母;新增 13 项测试并增强 1 项已有断言,其中 12 项新增或增强用例先失败后通过。三个 Vue 测试入口禁用 Vite WebSocket 监听,消除并行测试端口竞争。
|
||||
- 统一入口增加到 35 个测试文件,`npm run verify` 通过 313 项测试、后端编译、前端类型检查和生产构建。真实 TeamSpeak、Android 真机及发布包仍未验收,状态投影和页面组件继续跟踪。
|
||||
|
||||
### 消息状态与聊天归属实施记录
|
||||
|
||||
- 基线 `a97fa54` 的 CI 与 Docker 检查已确认成功。保留并更新此前只读整理文档,本批进入代码实施。
|
||||
- 提取 172 行的 `session-state.ts`,集中目录、聊天历史、事件、通知和私聊身份范围;语音入口现为 1,468 行。修复目录双份数据不同步、进入字段丢失、离开残留、编号复用继承临时音量,以及退出未清通知等问题。
|
||||
- 聊天等待命令确认后写入成功历史;未连接、拒绝和超时保留草稿,退出或卸载使迟到反馈失效。按目标保存等待、草稿及错误,切换标签再返回不能重复发送。网关恢复期间的拒绝保留请求标识。
|
||||
- 私聊历史按 UID 或成员生命周期分组,保留对方名称;未知发送者与后来的同编号成员隔离。新增可选私聊 UID 和频道 ID 字段,网关在调用 SDK 前核对,旧客户端省略字段仍可使用原协议。
|
||||
- 频道树改为迭代遍历,重复 ID 保留第一项,孤儿及环受控展开;保留正常兄弟顺序,验证 5,000 层目录。
|
||||
- 新增 25 项测试,其中 20 项先失败后通过;35 个测试文件的 `npm run verify` 通过 338 项测试及前后端构建。新增聊天状态的五语提示及公开皮肤节点已登记,完整皮肤契约测试通过。
|
||||
- 本机网关使用真实 HTTP/WebSocket、模拟 TeamSpeak SDK。实际浏览器验证等待、拒绝、成功及私聊标签,检查桌面与 390 × 844 布局,无浏览器错误日志;临时页面、视口覆盖及进程已清理。浏览器验证不代表真实语音或真机验收。
|
||||
- 06-C 页面组件、03 实际消息兼容、02-C 真实媒体、07-A Android、09-A 发布复现仍未完成,完整目标保持进行中。
|
||||
|
||||
### 管理下载与审计名称验收记录
|
||||
|
||||
- 使用实际管理路由、登录与 CSRF、独立 SQLite 数据库和皮肤目录搭建本地验收环境;会话枚举和终止回调使用一次性测试数据,没有连接实际 TeamSpeak 服务。
|
||||
- 页面诊断链接下载 `webspeak-diagnostic-report.json`(750 字节),备份按钮下载 `webspeak-backup-2026-10-01.db`(61,440 字节)。浏览器完成事件与下载目录文件一致;JSON 可解析,版本和统计符合临时环境且不含测试密码及目标字段;SQLite 文件头正确,`PRAGMA integrity_check` 返回 `ok`。
|
||||
- 备份下载的高层事件等待超时,但底层浏览器下载完成事件和落盘文件均正常。因此不将该工具超时认定为应用下载失败,也不修改 Blob URL 释放逻辑。
|
||||
- 实际页面发现备份与密码变更退化为“系统事件”;补齐同一审计映射中十类缺失事件的中文、英文、德文、俄文及日文名称,覆盖密码、备份、断开、皮肤与邀请。保留未知事件回退;20 项已有管理测试、前端类型检查及生产构建一次通过,浏览器复查显示具体操作名称。
|
||||
- 原生移除确认框依然导致按键和调试命令超时,弹窗查询为空,关闭该页也超时。已停止重复尝试;此结果不证明移除或断开业务失败,两项确认/取消流程保留待验收。独立新页的下载验收不受影响。
|
||||
- 复查 Android 文档与锁定 SDK 的运行时约束,差异已在 07-A 登记;此前 Node 18 冒烟不能替代真实 SDK 连接,本轮没有据此升级依赖或重复运行已完成的冒烟。
|
||||
|
||||
### 皮肤生命周期实施记录
|
||||
|
||||
- 基线 `cdc5f03` 的 CI 与 Docker 检查确认成功;保留此前的管理组件工作区改动。
|
||||
- 先复现 5 个皮肤和目录竞态,再接入运行时取消、8 秒总期限、共享页面控制器及可取消存储事务。新增 23 项用例,38 个测试文件的统一验证通过 385 项测试及前后端构建。
|
||||
- 浏览器验证目录挂起后恢复、旧下载取消、刷新保留最后选择、正常自定义皮肤及演示页恢复。管理三页桌面样式与基线一致;窄屏导航溢出登记为 06-K,管理组件交互和客户端组件继续待办。
|
||||
- 真实 TeamSpeak 收发及媒体、Android 真机和跨平台发布仍未验收,完整目标保持进行中。
|
||||
@@ -0,0 +1,64 @@
|
||||
# WebSpeak 本地产物与源码边界
|
||||
|
||||
源码、依赖锁文件、构建脚本、Android 原生工程和必要的皮肤资源纳入版本管理。运行数据和可再生成的产物留在本地,按以下规则处理;本次整理没有删除、移动或覆盖既有发布包与参考素材。
|
||||
|
||||
| 路径 | 用途 | 处理方式 |
|
||||
| --- | --- | --- |
|
||||
| `src/`、`web/src/`、`mobile/` 中的入口及打包脚本 | 服务端、网页和 Android 实现 | 跟踪源码;各自依赖和锁文件明确保留 |
|
||||
| `web/android/` | Android 原生工程 | 跟踪原生源码、Gradle 配置与 wrapper;忽略缓存、生成资产和本机 SDK 路径;整个目录不进入服务端 Docker 构建上下文 |
|
||||
| 各级 `node_modules/`、`dist/` | 安装依赖和构建输出 | 忽略 Git;Docker 重新安装并构建;Android 资产由 `npm run android:sync` 生成 |
|
||||
| `release-artifacts/` | 本地发布包及校验和,包括 Android APK | 本地保留,忽略 Git 和 Docker;正式发布使用发布工作流的产物 |
|
||||
| 根目录 `webspeak-deploy*.tar.gz`、`webspeak-update*.tar.gz` | 历史部署与更新包 | 本地保留,按项目专用名称忽略,不使用忽略全部压缩包的 Git 规则 |
|
||||
| 根目录 `teamspeak6-server-linux-amd64.tar.xz` | 下载的 TeamSpeak 服务端归档 | 本地保留,忽略 Git 和 Docker |
|
||||
| `界面参考/stitch_teamspeak_web_interface.zip` | 界面参考归档 | 本地保留并忽略 Git;参考素材不进入服务端 Docker 上下文 |
|
||||
| `.local-opus-hook.cjs` | 用原样缓冲区替代编解码的实验脚本 | 本地保留,忽略 Git 和 Docker;不接入正式启动、构建及媒体验收 |
|
||||
| `data/`、`config.json`、`.env`、日志 | 运行数据和本机设置 | 按部署备份策略保管,不能当作可删除的构建缓存;Docker 上下文显式排除 `.env` 及 `.env.*`,避免本地环境文件进入构建阶段 |
|
||||
|
||||
检查规则时,用 `git check-ignore` 确认构建产物被忽略,同时确认 `src/shared/`、平台启动源码、Android Java 文件、Gradle wrapper 和皮肤资源仍可跟踪。新增文件若是构建必需输入,应随源码声明;构建不得依赖上述历史发布包或实验脚本。
|
||||
|
||||
未来需要清理磁盘时,先核对产物的来源、是否可重新生成及保留位置,再选择具体文件。未跟踪或已忽略状态本身不是删除依据。
|
||||
|
||||
## 2026-10-08 v0.2.6 Android APK 构建
|
||||
|
||||
在当前 v0.2.6 发布准备工作树中执行 `npm run android:sync` 和 Gradle `assembleDebug`,使用 Android Studio JDK 25.0.2、Gradle 9.5.0、Android SDK 36。134 个 Gradle 任务通过;APK 清单均为 `versionName=0.2.6`、`versionCode=206`、最低 SDK 24、目标 SDK 36。`apksigner` 验证了三包的 v2 签名;这是 debug 签名,仅适合手动侧载测试。没有 Android 模拟器连接,本轮未安装或测试真实 TeamSpeak 语音。
|
||||
|
||||
文件保存在被 Git 忽略的 `release-artifacts/android/`:
|
||||
|
||||
| APK | 字节数 | 本机复算 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| `webspeak-android-v0.2.6-arm64-v8a-debug.apk` | 76,341,182 | `e1851ecbff6b7d133b8f3747781be6d79aeae94bb5a6add723a4b6a7cf868b12` |
|
||||
| `webspeak-android-v0.2.6-armeabi-v7a-debug.apk` | 72,114,332 | `08007e23e384577872f6f9747ec33bcfb59bbef44b819d7ad7fc032a1e923929` |
|
||||
| `webspeak-android-v0.2.6-x86_64-debug.apk` | 80,953,005 | `69a5a71aa0d78f6a8ca43131107eb308d6df31858fce972a5d3d4852ce95c94c` |
|
||||
|
||||
## 2026-10-01 干净构建记录(09-A)
|
||||
|
||||
构建输入为提交 `662dad36fc4d8cf9f35268a99b8221851f6fc52c`,应用版本 `0.2.5-preview`。本轮没有创建版本标签或发布正式 Release。
|
||||
|
||||
[手动发布构建 36857782727](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36857782727) 的测试、Docker、Windows x64、Linux x64 四个作业全部成功;正式发布步骤按分支条件跳过。服务器构建使用工作流指定的 Node.js 22.22.2,Docker 使用 Dockerfile 声明的 Node.js 22 镜像。各平台重新检出源码、安装依赖、构建锁定的 SDK,再编译和打包;Windows 和 Linux 包均包含 Node.js 运行时,并在独立临时目录通过 HTTP 健康状态及版本检查。Docker 镜像也通过 HTTP 健康检查。这些结果不证明真实语音和屏幕共享可用,也不表示产物逐字节可重现。
|
||||
|
||||
| Actions 产物 | 归档字节数 | Actions 报告的 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| windows-x64 | 52,431,874 | `790e2d712060b1254498641590c9aed05c065eec416797c4280140531e78ee05` |
|
||||
| linux-x64 | 59,322,525 | `892aaa190f8d138917ef5775dbf05b620abc2033fbc5089821eb8bda15c99e9c` |
|
||||
|
||||
上表摘要属于 Actions 外层产物归档,不是其中部署包的摘要;当前证据来自 Actions API,不能写成已在本机复算。对应部署包由工作流生成,版本和启动结果已由平台作业检查。
|
||||
|
||||
Android 使用同一提交的 `git archive` 源码归档,在新目录安装根、web、mobile 三套锁定依赖并重建 SDK,没有复制当前工作区的 node_modules 或历史发布包。构建主机为 Windows x64,Node.js 24.12.0、Android Studio JDK 25.0.2、Gradle 9.5.0、Android SDK 36;依次执行依赖安装、`prepare:sdk`、`android:sync`、`assembleDebug --no-daemon`。短路径目录 `<TEMP_BUILD_DIR>` 构建成功,134 个 Gradle 任务全部执行。
|
||||
|
||||
| Android 调试产物 | 字节数 | 本机复算 SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| app-arm64-v8a-debug.apk | 76,289,469 | `7bd977906397ab467655862e1182b1021d6d0b2f255aebcae644eaf5db201006` |
|
||||
| app-armeabi-v7a-debug.apk | 72,062,619 | `a28471b248e944d01c1e72d1066711aafe7dda6524ad1736becfb4d436a064a8` |
|
||||
| app-x86_64-debug.apk | 80,901,292 | `853a82786d1733686329568661954642c60482fd9ad3e7b910856b050d157532` |
|
||||
|
||||
APK 位于上述目录的 `web/android/app/build/outputs/apk/debug`。逐包检查了移动网关入口、TeamSpeak SDK、Opus WASM、网页和匹配 ABI 的 Node.js 原生库;未发现项目私有配置或实验 Opus 脚本。arm64 包的清单版本为 `0.2.5-preview` / code `25`,最低 SDK 24、目标 SDK 36。构建当日尚未安装新包;后续 x86_64 安装与启动结果见下节,Android 布局和真机媒体仍待验收。
|
||||
|
||||
本轮发现并处理两处构建边界问题:`.dockerignore` 补充排除本地 `.env` 与 `.env.*`;Android 深层临时目录触发 CMake 250 字符对象路径警告及 Ninja 建目录失败,同源码在短路径重建通过,已将该主机构建约束补入移动文档。没有为此更改应用或原生插件逻辑。Windows 首次 npm ci 约耗时三分钟,随后构建、打包和启动均正常。
|
||||
|
||||
## 2026-10-02 Android 安装与冷启动(09-A)
|
||||
|
||||
安装对象为上表同一 `662dad3` 的 x86_64 APK,安装前复算 SHA-256 与记录一致。使用已有 `ws` AVD 的只读 Android 15 / x86_64 实例,启动参数包含 `-read-only -no-snapshot-save -no-window -no-audio -port 5580`,没有修改原 AVD 数据或保存新快照。
|
||||
|
||||
`adb -s emulator-5580 install -r <APK>` 返回 `Success`;包管理器报告 `versionName=0.2.5-preview`、`versionCode=25`、最低 SDK 24、目标 SDK 36。强制停止后启动 `io.webspeak.client/.MainActivity` 返回 `Status: ok`、`LaunchState: COLD`,启动耗时 1,822 毫秒。
|
||||
|
||||
通过临时 ADB 转发 `tcp:53040` → 设备 `tcp:3040`,实际内嵌网关 `/health` 返回 `status: ok`、`engine: webspeak-android`;`/api/public-config` 返回 `version: 0.2.5-preview`、`mobile: true`、`initialized: true`。这补齐该干净构建产物的安装、冷启动及 HTTP 网关证据;没有交互式检查 Android WebView 布局、触屏或真实媒体,不能据此关闭这些待办。验收后移除端口转发并关闭该只读模拟器。
|
||||
@@ -0,0 +1,248 @@
|
||||
# WebSpeak · Deutsch
|
||||
|
||||
[Projektstartseite](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Webclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer können ohne Desktop-Client im Browser Kanälen beitreten; Administratoren verwalten Zielserver, Zugriff und Laufzeitstatus über die Webkonsole.
|
||||
|
||||
## Live-Demo
|
||||
|
||||
Adresse: <https://webspeak.example.invalid>
|
||||
|
||||
Die öffentliche Demo läuft in Hongkong. Netzwerkbedingungen und Auslastung können instabil sein; Latenz, Verbindungsabbrüche oder kurze Ausfälle beschreiben nicht jede eigene Bereitstellung.
|
||||
|
||||
## ✨ Funktionen
|
||||
|
||||
| Funktion | Beschreibung |
|
||||
| --- | --- |
|
||||
| TeamSpeak-Kompatibilität | Unterstützt TeamSpeak 3 und TeamSpeak 6 und erkennt das Zielprotokoll automatisch. |
|
||||
| Plattformübergreifendes P2P-Bildschirmteilen | Browsernutzer und native TeamSpeak-6-Clients können die Bildschirmfreigabe gegenseitig starten und ansehen; WebRTC/ICE überträgt Medien direkt, WebSpeak leitet nur die Signalisierung weiter. |
|
||||
| IPv6-Ziele | IPv6-TeamSpeak-Ziele und über DNS aufgelöste IPv6-Adressen werden standardmäßig unterstützt. |
|
||||
| Kanäle und Mitglieder | Kanalstruktur und aktuelle Mitglieder anzeigen und Kanäle wechseln. |
|
||||
| Echtzeit-Sprache | Opus-Audio mit kompatiblem Transport und optional integriertem WebRTC für geringere Latenz. |
|
||||
| Audiosteuerung | Mikrofon und Lautsprecher auswählen, Lautstärke regeln, testen, stummschalten, VOX und individuelle Mitgliedslautstärke. |
|
||||
| Browserseitige Geräuschunterdrückung | Optionale Mikrofon-Geräuschunterdrückung in der Browseraufnahme, ohne zusätzliche serverseitige Audioverarbeitung. |
|
||||
| Nachrichten und Aktionen | Kanal- und Serverchat, private Nachrichten, Anstupsen und Flüsterziele. |
|
||||
| Desktop-Begleitton | Audio eines freigegebenen Fensters oder Browser-Tabs im aktuellen Kanal teilen. |
|
||||
| Identität und Zugriff | Gespeicherte Identität, eigene Ziele und widerrufbare Einladungslinks mit Ablaufzeit. |
|
||||
| Administration | Ziele, Zugriff, WebRTC, Relays, Einladungen, Sitzungen, Protokolle, Diagnosen und Backups verwalten. |
|
||||
| Skins | Geschützte Tages-, Nacht- und ILLUSIA-Skins sowie instanzverwaltete `.wskin`-Designs mit Aktivierungs- und Standardauswahl im Adminbereich. |
|
||||
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche sowie responsive Desktop-/Mobilansicht. |
|
||||
| Selbsthosting | Daten bleiben beim Betreiber; Docker-, Windows-x64- und Linux-x64-Bereitstellung sind verfügbar. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
Die Screenshots zeigen die deutsche Willkommensseite, den Sprachbereich, die Audiosteuerung und das Mitgliedermenü.
|
||||
|
||||
### Willkommensseite
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-home.png" alt="WebSpeak deutsche Willkommensseite" width="100%" /></p>
|
||||
|
||||
### Sprachbereich
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de.png" alt="WebSpeak deutscher Sprachbereich" width="100%" /></p>
|
||||
|
||||
### Audiosteuerung
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-audio.png" alt="WebSpeak deutsche Audiosteuerung" width="100%" /></p>
|
||||
|
||||
### Mitgliedermenü
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-de-menu.png" alt="WebSpeak deutsches Mitgliedermenü" width="100%" /></p>
|
||||
|
||||
## 🧩 Erweiterte Funktionen
|
||||
|
||||
Diese Funktionen sind optional. Ohne sie arbeitet WebSpeak weiterhin mit dem kompatiblen Sprachtransport. Die Einstellungen befinden sich unter **Administration → Server** und gelten für neue Verbindungen.
|
||||
|
||||
### 1. WebRTC-Sprache mit niedriger Latenz
|
||||
|
||||
WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht außerdem Desktop-Begleitton. Das aktuelle WebSpeak-Gateway stellt WebRTC selbst bereit; ein zusätzlicher Medienserver ist nicht erforderlich.
|
||||
|
||||
1. Unter `/admin` anmelden und auf der Seite **Server** die **Erweiterten Einstellungen** öffnen.
|
||||
2. Bei deaktiviertem WebRTC Start- und Endport für UDP festlegen. Der Standardbereich ist `40000–40099`.
|
||||
3. Den gesamten UDP-Bereich in Sicherheitsgruppe und Firewall des WebSpeak-Hosts freigeben.
|
||||
4. **WebRTC** aktivieren und speichern. Nicht unterstützte Browser oder Netzwerke wechseln automatisch zum kompatiblen Transport.
|
||||
|
||||
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
|
||||
|
||||
### ICE-Kandidaten für Bildschirmfreigabe
|
||||
|
||||
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niemals das WebSpeak-Gateway. Ohne TURN werden nur direkte ICE-Pfade und STUN verwendet.
|
||||
|
||||
### Plattformübergreifendes P2P-Bildschirmteilen
|
||||
|
||||
Browsernutzer und native TeamSpeak-6-Clients können Bildschirmfreigaben gegenseitig erkennen, starten und ansehen. Zwischen Browsern sowie zwischen Browser und nativem Client werden die Bildschirmmedien möglichst über eine direkte WebRTC/ICE-Peer-to-Peer-Verbindung übertragen; WebSpeak übernimmt Sitzungsberechtigung, Freigabestatus und SDP-/ICE-Signalisierung, transportiert aber keine Bildschirmmedien. Die Oberfläche zeigt Live-Status und Zuschauerzahl und bietet Lautstärke-, Vollbild- und Beenden-Steuerung. Für die Aufnahme stehen bis zu 1080p und 60 FPS sowie WebRTC-Statistiken zur Verfügung.
|
||||
|
||||
### 2. Relay-Modus
|
||||
|
||||
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
|
||||
|
||||
Eine Relay-Instanz ist ein dedizierter Weiterleitungsdienst ohne Besucher- oder Administrationsseite. Sie akzeptiert nur Gateway-Sitzungen mit passendem Token. Ein zufälliges Token mit mindestens 16 Zeichen verwenden.
|
||||
|
||||
#### Aus dem Quellcode starten
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Aus einem Release-Paket starten
|
||||
|
||||
Das passende Paket aus den [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und entpacken:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Unter Windows PowerShell dieselben Variablen setzen und `.\runtime\node.exe .\dist\index.js` ausführen.
|
||||
|
||||
#### Mit Docker starten
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Den UDP-Listening-Port des Relay-Hosts freigeben, standardmäßig `39087`.
|
||||
|
||||
#### Im Gateway aktivieren
|
||||
|
||||
1. **Administration → Server → Relay-Server** öffnen und einen oder mehrere Knoten hinzufügen.
|
||||
2. Für jeden Knoten einen Anzeigenamen, einen Endpunkt wie `relay.example.com#39087` und das passende Token eintragen und speichern.
|
||||
3. Besucher können auf der Willkommensseite Direktzugriff oder einen konfigurierten Relay-Knoten auswählen.
|
||||
|
||||
Relay deaktivieren und speichern, um die Option von der Willkommensseite zu entfernen.
|
||||
|
||||
### 3. Abhängigkeiten und Hinweise zur Herkunft
|
||||
|
||||
- Der Relay-Dienst ist Bestandteil von WebSpeak und verwendet Node.js-Standardbibliotheken; GOST, sing-box oder ein anderes Proxy-Framework werden nicht verwendet.
|
||||
- WebRTC verwendet [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`; das Upstream-Projekt steht unter MIT-Lizenz.
|
||||
- Die TeamSpeak-Protokollverbindung verwendet den projektgepflegten [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js)-SDK-Fork.
|
||||
|
||||
## 🧾 Änderungsprotokoll
|
||||
|
||||
| Version | Datum | Zusammenfassung |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Gegenüber 0.2.5 #10 behoben, #9/#12 umgesetzt, #6/#7 abgesichert und den in PR #13 beschriebenen TS6-Freigabefall korrigiert; Sprach- und Mobilinteraktionen verbessert; Windows x64, Linux x64/ARM64, Docker amd64/arm64 und Android-APKs für drei ABIs ergänzt. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | `.wskin`-Skins, Aktivierungs-/Standardverwaltung und geschützte Tages-, Nacht- und ILLUSIA-Skins ergänzt; unfertiges Aurora-Voice-Beispiel entfernt, Skin-Ladeblitze, dunkle Bedienelemente und Artwork-Ebenen im Sprachbereich korrigiert sowie offiziellen Skin-Entwicklungs-Agent-Skill hinzugefügt. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Plattformübergreifendes P2P-Bildschirmteilen zwischen Browsern und nativen TeamSpeak-6-Clients ergänzt; STUN-/externes-TURN-Konfiguration, Live-Player und Zuschauerstatus, Aufnahmeoptionen bis 1080p/60 FPS und WebRTC-Statistiken hinzugefügt; Bildschirmfreigabe-Interaktion verbessert und Besucherzählung ergänzt. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Mitgliederplanung und direkte Verschiebung nach Berechtigung ergänzt; Avatar-, Stummschaltstatus- und Identitätsunterstützung hinzugefügt; Screenshots und Dokumentation für alle fünf Sprachen aktualisiert. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Browserseitige Mikrofon-Geräuschunterdrückung, russische und japanische Oberfläche sowie sprachabhängige Begrüßungstexte ergänzt; Lautstärkeinteraktion und Fehlertexte/-codes auf Basis von PR #2 verbessert. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Verbindungsfehler auf der Willkommensseite verbessert, Fehlercodes erhalten und sicher gekürzt sowie IPv6-Ziele standardmäßig unterstützt. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Passwortabfrage, dedizierter Relay-Modus, Auswahl mehrerer Relays und Ursachendarstellung in der Administration ergänzt. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Docker-Bereitstellung vereinfacht, lokale TeamSpeak-Ziele unterstützt, 15-Sekunden-Timeout ergänzt und kontinuierliche Netzwerküberwachung eingeführt. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Deutsch, Telegram, Netzwerkleistung und Gesamtlautstärke ergänzt; Lautstärkeschwankungen beim Begleitton behoben. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Desktop-Begleitton, Hinweise zur gespeicherten Identität und Website-Symbol ergänzt; WebRTC-Mitgliederlautstärke korrigiert. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Identitätsspeicherung korrigiert und Designumschaltung verbessert. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | WebRTC und Kanalchat korrigiert sowie Administration, Protokolle und Mobilansicht verbessert. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Integriertes WebRTC, aktualisiertes TeamSpeak-SDK und bessere Mitgliedersynchronisierung und Sprachpufferung. |
|
||||
|
||||
Vollständige Historie: [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Bereitstellung
|
||||
|
||||
| Methode | Geeignet für | Umgebung |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (empfohlen) | Dauerbetrieb, einfache Updates und persistente Daten | Docker Engine + Docker Compose |
|
||||
| Release-Paket | Betrieb ohne Node.js und Build-Werkzeuge | Windows x64 oder Linux x64/ARM64 |
|
||||
| Aus dem Quellcode | Entwicklung und Anpassungen | Node.js 22.5+, Git und native Build-Werkzeuge |
|
||||
|
||||
### Docker Compose (empfohlen)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Nach dem Start ist WebSpeak unter `http://<dein-host>:3040` erreichbar. Bei einem Reverse Proxy auf diese Adresse zeigen; für WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben. Die Daten liegen im Volume `webspeak-data`.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
`docker compose down -v` nicht ausführen, da dadurch Datenbank und Administratoreinstellungen gelöscht werden.
|
||||
|
||||
### Release-Paket
|
||||
|
||||
Das passende `windows-x64.zip`, `linux-x64.tar.gz` oder `linux-arm64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen und den enthaltenen Starter ausführen. Die Pakete enthalten Node.js und Produktionsabhängigkeiten. Docker unterstützt amd64/arm64.
|
||||
|
||||
Android-APKs für `arm64-v8a`, `armeabi-v7a` und `x86_64` sind ebenfalls verfügbar. Sie sind für Tests per Sideload debug-signiert, keine Google-Play-Pakete; echte TeamSpeak-Sprachtests auf Geräten stehen noch aus.
|
||||
|
||||
### Aus dem Quellcode
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für den Bau von `@discordjs/opus` werden Python, Make und eine C/C++-Toolchain benötigt.
|
||||
|
||||
### Erste Konfiguration
|
||||
|
||||
1. `http://<dein-host>:3040/admin` öffnen.
|
||||
2. Mit `admin` / `admin` anmelden und sofort ein neues Passwort mit mindestens 12 Zeichen setzen.
|
||||
3. Unter **Server** TeamSpeak-Ziel und Zugriffsmethode konfigurieren, zum Beispiel `voice.example.com#9987`.
|
||||
4. Für öffentliche Nutzung HTTPS einrichten; bei aktiviertem WebRTC den im Adminbereich angezeigten UDP-Bereich freigeben.
|
||||
|
||||
## ⚠️ Voraussetzungen und Hinweise
|
||||
|
||||
| Bereich | Hinweis |
|
||||
| --- | --- |
|
||||
| Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Mikrofon- und Fenster-Audio benötigen normalerweise HTTPS. |
|
||||
| TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können; der Standard-Sprachport ist `9987`. |
|
||||
| Webnetzwerk | Der Dienst verwendet `3040/TCP`; öffentlich sollte ein HTTPS-Reverse-Proxy für Seite und WebSocket verwendet werden. |
|
||||
| IPv6 | Literale Ziele als `[2001:db8::1]#9987` eintragen. Host/Container benötigen geroutetes IPv6, aktiviertes IPv6 in Betriebssystem und Node.js sowie passende Firewall-Regeln. |
|
||||
| WebRTC | Standardbereich `40000–40099/UDP`; den gesamten Bereich freigeben und WebRTC vor einer Änderung deaktivieren. |
|
||||
| Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung halten. Für parallele Verbindungen deaktivieren oder ein anderes Browserprofil verwenden. |
|
||||
| Begleitton | Nur auf dem Desktop verfügbar und WebRTC erforderlich. Bei Fenster- oder Tab-Freigabe auch Audio freigeben. |
|
||||
| Daten | Docker verwendet `webspeak-data`; Release-Pakete und Quellcode verwenden `data/`. Vor Updates sichern. |
|
||||
| Sitzungslimit | Eine Instanz akzeptiert bis zu 100 aktive Browser-Sitzungen. |
|
||||
@@ -0,0 +1,256 @@
|
||||
# WebSpeak · English
|
||||
|
||||
[Project home](../README.md) · [简体中文](./README.zh-CN.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors can join channels without installing a desktop client, while administrators manage the target servers, access policy, and runtime state from the web console.
|
||||
|
||||
## Live demo
|
||||
|
||||
URL: <https://webspeak.example.invalid>
|
||||
|
||||
The public demo is hosted in Hong Kong and its network conditions and load may be unstable. Latency, disconnections, or temporary downtime do not represent every self-hosted deployment.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
| Capability | Description |
|
||||
| --- | --- |
|
||||
| TeamSpeak compatibility | Supports TeamSpeak 3 and TeamSpeak 6 and automatically detects the target protocol. |
|
||||
| Cross-platform P2P screen sharing | Browser users and native TeamSpeak 6 clients can start and watch each other's screen shares; WebRTC/ICE carries media directly while WebSpeak relays negotiation signaling only. |
|
||||
| IPv6 targets | IPv6 TeamSpeak targets and IPv6 addresses resolved from hostnames are supported by default. |
|
||||
| Channels and members | Browse the channel tree, see live member states, and switch channels. |
|
||||
| Realtime voice | Opus audio with a compatibility transport and optional bundled WebRTC low-latency transport. |
|
||||
| Audio controls | Select microphones and speakers, adjust volume, test the microphone, mute, use VOX, and control member volume. |
|
||||
| Browser-side noise suppression | Optional microphone noise suppression runs at the browser capture stage, without adding server-side audio processing. |
|
||||
| Messaging and actions | Channel chat, server chat, private messages, poke actions, and whisper targets. |
|
||||
| Desktop accompaniment | Select an audio-enabled window or browser tab and share its sound with the current channel. |
|
||||
| Identity and access | Remembered identity, visitor-defined targets, and revocable expiring invite links. |
|
||||
| Administration | Manage targets, access policy, WebRTC, relays, invites, sessions, logs, diagnostics, and backups. |
|
||||
| Skins | Protected Day, Night, and ILLUSIA skins, plus instance-managed `.wskin` appearances with administrator enable/default controls. |
|
||||
| User experience | Chinese, English, German, Russian, and Japanese UI with responsive desktop/mobile layouts. |
|
||||
| Self-hosting | Data stays with the operator; Docker amd64/arm64, Windows x64 and Linux x64/ARM64 packages, and an Android client are provided. |
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
The screenshots show the English welcome page, voice workspace, audio controls, and member menu.
|
||||
|
||||
### Welcome page
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-home.png" alt="WebSpeak English welcome page" width="100%" /></p>
|
||||
|
||||
### Voice workspace
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en.png" alt="WebSpeak English voice workspace" width="100%" /></p>
|
||||
|
||||
### Audio controls
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-audio.png" alt="WebSpeak English audio controls" width="100%" /></p>
|
||||
|
||||
### Member menu
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-en-menu.png" alt="WebSpeak English member menu" width="100%" /></p>
|
||||
|
||||
## 🧩 Advanced features
|
||||
|
||||
These features are optional. WebSpeak continues to work with the compatibility voice transport when they are disabled. Configure them under **Administration → Servers**; saved changes apply to new connections.
|
||||
|
||||
### 1. WebRTC low-latency voice
|
||||
|
||||
WebRTC moves browser voice to a realtime media path and also enables desktop accompaniment. The current WebSpeak gateway provides it directly; no separate media server is required.
|
||||
|
||||
1. Sign in at `/admin` and open **Advanced settings** on the **Servers** page.
|
||||
2. While WebRTC is disabled, choose the UDP start and end ports. The default range is `40000–40099`.
|
||||
3. Allow the complete UDP range in the WebSpeak host's security group and firewall.
|
||||
4. Enable **WebRTC** and save. New visitors will negotiate WebRTC; unsupported browsers and networks fall back to the compatibility transport.
|
||||
|
||||
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
|
||||
|
||||
### Voice WebRTC behind a reverse proxy or TCP tunnel
|
||||
|
||||
The WebRTC advanced settings now include a **public media address**, **IPv6 candidates**, and a **voice STUN server**. The media address must be a gateway IP or hostname reachable over UDP, without a scheme, path or port. It overrides the address inferred from `Origin`, `X-Forwarded-Host`, or `Host`; DNS names are resolved into IP candidates. IPv6 is opt-in and retains IPv4 candidates.
|
||||
|
||||
Set a UDP STUN URL such as `stun:turn.teamspeak.com:3478` to use the same discovery service in the browser and gateway. Empty preserves the previous behavior: the gateway library uses its built-in STUN service while the browser has none. The gateway requires an IPv4-reachable UDP STUN hostname or IPv4 address; IPv6 literals and TURN credentials are not accepted. IPv6 media candidates work independently of STUN. Save and reconnect to apply changes.
|
||||
|
||||
HTTP/WebSocket reachability does not imply media reachability. Allow the complete configured UDP range and preserve port numbers when using static port forwarding. STUN discovers mappings but cannot relay audio or traverse every NAT. Deployments with only a TCP tunnel and no usable UDP/IPv6 path still fall back to compatibility transport.
|
||||
|
||||
### Screen-share ICE candidates
|
||||
|
||||
Screen-share media still prefers a direct browser-to-browser path; WebSpeak only relays negotiation signaling. By default it uses TeamSpeak's public STUN services to discover server-reflexive candidates; STUN does not carry media. If the deployment has an authorized external TURN service, set `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` before starting WebSpeak with a JSON array, for example:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
With TURN configured, media may use that external TURN service but never the WebSpeak gateway; without it, only direct ICE paths and STUN are used.
|
||||
|
||||
### Cross-platform P2P screen sharing
|
||||
|
||||
Browser users and native TeamSpeak 6 clients can discover, start, and watch each other's screen shares. Screen media between browsers, and between a browser and a native client, is sent over a WebRTC/ICE peer-to-peer path whenever possible; WebSpeak handles session authorization, share state, and SDP/ICE signaling, but does not carry the screen media. The UI includes live status, viewer count, player volume, fullscreen, and exit controls. Share settings support up to 1080p and 60 FPS, with live WebRTC statistics for diagnosis.
|
||||
|
||||
### 2. Relay mode
|
||||
|
||||
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
|
||||
|
||||
A relay instance is a dedicated forwarding service with no visitor page or administration console. It accepts only gateway sessions with a matching token. Use a random token of at least 16 characters.
|
||||
|
||||
#### Run from source
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### Run from a release package
|
||||
|
||||
Download and extract the appropriate package from [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest):
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
On Windows PowerShell, set the same variables and run `.\runtime\node.exe .\dist\index.js`.
|
||||
|
||||
#### Run with Docker
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
Allow the relay host's UDP listen port, `39087` by default.
|
||||
|
||||
#### Enable it in the gateway
|
||||
|
||||
1. Open **Administration → Servers → Relay server** and add one or more nodes.
|
||||
2. Set a custom display name, endpoint such as `relay.example.com#39087`, and matching token for each node, then save.
|
||||
3. Visitors can choose direct access or one of the configured relays on the welcome page.
|
||||
|
||||
Disable and save the relay configuration to remove the relay option from the welcome page.
|
||||
|
||||
### 3. Dependencies and attribution
|
||||
|
||||
- The relay service is built into WebSpeak with Node.js standard libraries; it does not use GOST, sing-box, or another proxy framework.
|
||||
- WebRTC uses [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`, whose upstream project is licensed under MIT.
|
||||
- TeamSpeak protocol connectivity uses the project-maintained [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork.
|
||||
|
||||
## 🧾 Changelog
|
||||
|
||||
| Version | Date | Summary |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | Relative to 0.2.5, fixed #10, implemented #9/#12, hardened #6/#7, and fixed the existing-share discovery case reported in PR #13; improved voice and mobile interactions; added Windows x64, Linux x64/ARM64, amd64/arm64 Docker, and three-ABI Android packages. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | Added `.wskin` skins, administrator enable/default controls, and protected Day/Night/ILLUSIA built-ins; removed the unfinished Aurora Voice sample, fixed skin-load flashes, dark-control contrast, and voice-room artwork layering, and added the official skin-development Agent Skill. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | Added cross-platform P2P screen sharing between browsers and native TeamSpeak 6 clients; added STUN/external-TURN configuration, live player and viewer state, 1080p/60 FPS capture settings, and WebRTC statistics; refined screen-share interactions and added visitor numbering. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | Added channel member scheduling and permission-aware direct moves; added avatar, mute-state, and remembered-identity support; refreshed feature screenshots and documentation for all five languages. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | Added browser-side microphone noise suppression, Russian and Japanese UI, and per-language welcome text; refined volume interaction and error messages/codes on top of PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | Improved welcome-page connection errors, preserved and safely truncated error codes, and added default IPv6 target support. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | Added server-password prompts, formal relay mode, multiple relay selection, and administrator connection-reason reporting. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | Simplified Docker deployment, supported local TeamSpeak targets, added a 15-second connection timeout, and made network monitoring continuous. |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | Added German, Telegram, network performance, and master-volume features; fixed accompaniment volume fluctuation. |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | Added desktop accompaniment, remembered-identity guidance, and the site icon; fixed WebRTC member volume. |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | Fixed identity persistence and refined the theme toggle. |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | Fixed WebRTC and channel chat and refined administration, logs, and mobile layouts. |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | Added bundled WebRTC, migrated the TeamSpeak SDK, and improved member synchronization and voice buffering. |
|
||||
|
||||
See the complete history in [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
| Method | Best for | Environment |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose (recommended) | Long-running servers, simple upgrades, and persistent data | Docker Engine + Docker Compose |
|
||||
| Release package | Running without Node.js or build dependencies | Windows x64 or Linux x64/ARM64 |
|
||||
| From source | Development, debugging, and customization | Node.js 22.5+, Git, and native build tools |
|
||||
|
||||
### Docker Compose (recommended)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://<your-host>:3040` after startup. If using a reverse proxy, point it to that address. When WebRTC is enabled, allow the UDP range shown in the administration console. Data is stored in the `webspeak-data` volume.
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Do not run `docker compose down -v`; it removes the database and administrator settings.
|
||||
|
||||
### Release package
|
||||
|
||||
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
|
||||
|
||||
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
|
||||
|
||||
### From source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain.
|
||||
|
||||
### First-time setup
|
||||
|
||||
1. Open `http://<your-host>:3040/admin`.
|
||||
2. Sign in with `admin` / `admin` and immediately set a new password of at least 12 characters.
|
||||
3. Configure the TeamSpeak target and access mode under **Servers**, for example `voice.example.com#9987`.
|
||||
4. Configure HTTPS for public access; when WebRTC is enabled, allow the UDP range shown in the console.
|
||||
|
||||
## ⚠️ Requirements and notes
|
||||
|
||||
| Area | Requirement or note |
|
||||
| --- | --- |
|
||||
| Browser | Use a current Chrome, Edge, or other modern browser with WebRTC support. Microphone and window audio normally require HTTPS. |
|
||||
| TeamSpeak network | The WebSpeak host must reach the target TeamSpeak server; the default voice port is `9987`. |
|
||||
| Web network | The service uses `3040/TCP`; public deployments should expose the page and WebSocket through an HTTPS reverse proxy. |
|
||||
| IPv6 | Write literal targets as `[2001:db8::1]#9987`. The host/container needs routed IPv6, IPv6 enabled in the OS and Node.js, and the relevant firewall rules. |
|
||||
| WebRTC | The default range is `40000–40099/UDP`; allow it and disable WebRTC before changing the range. |
|
||||
| Remembered identity | One browser identity can hold one active remembered connection. Disable it for parallel connections or use another browser profile. |
|
||||
| Accompaniment | Desktop only and requires WebRTC. Enable audio sharing when selecting a window or tab. |
|
||||
| Data | Docker data is in `webspeak-data`; release packages and source installs use `data/`. Back up before upgrades. |
|
||||
| Session limit | One instance accepts up to 100 active browser sessions. |
|
||||
@@ -0,0 +1,151 @@
|
||||
# WebSpeak · 日本語
|
||||
|
||||
[プロジェクトトップ](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md)
|
||||
|
||||
## プロジェクト概要
|
||||
|
||||
| 観点 | 説明 |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak は TeamSpeak 3 / TeamSpeak 6 向けのセルフホスト型ブラウザクライアント兼音声ゲートウェイです。 |
|
||||
| **WHY** | デスクトップクライアントをインストールせず、ブラウザからチャンネルに参加できます。運用者はサーバーとデータを管理できます。 |
|
||||
| **HOW** | 起動後、管理コンソールで TeamSpeak の接続先とアクセス方針を設定します。ブラウザが画面と音声を担当し、WebSpeak がゲートウェイとして接続します。 |
|
||||
|
||||
## オンラインデモ
|
||||
|
||||
アドレス: <https://webspeak.example.invalid>
|
||||
|
||||
デモは香港にあります。ネットワークと負荷が不安定な場合があるため、遅延、切断、一時的な利用不可は各自の環境での動作を示すものではありません。
|
||||
|
||||
## ✨ 機能
|
||||
|
||||
| 機能 | 説明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak | TeamSpeak 3 / 6 に対応し、対象プロトコルを自動検出します。 |
|
||||
| クロスプラットフォーム P2P 画面共有 | ブラウザユーザーと TeamSpeak 6 ネイティブクライアントが互いに画面共有を開始・視聴できます。メディアは WebRTC/ICE で直接送信し、WebSpeak はシグナリングだけを中継します。 |
|
||||
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
|
||||
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
|
||||
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
|
||||
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
|
||||
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
|
||||
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
|
||||
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
|
||||
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
|
||||
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
|
||||
| スキン | 保護された昼・夜・ILLUSIA スキンに加え、管理者が有効化とデフォルトを管理するインスタンス `.wskin` に対応。 |
|
||||
| インターフェース | 中文、English、Deutsch、Русский、日本語、レスポンシブ表示。 |
|
||||
|
||||
## 🖼️ インターフェースのスクリーンショット
|
||||
|
||||
日本語のホーム、音声ワークスペース、オーディオ設定、メンバー操作メニューを掲載しています。
|
||||
|
||||
### ホーム
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-home.png" alt="WebSpeak 日本語ホーム" width="100%" /></p>
|
||||
|
||||
### 音声ワークスペース
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja.png" alt="WebSpeak 日本語音声ワークスペース" width="100%" /></p>
|
||||
|
||||
### オーディオ設定
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-audio.png" alt="WebSpeak 日本語オーディオ設定" width="100%" /></p>
|
||||
|
||||
### メンバーメニュー
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ja-menu.png" alt="WebSpeak 日本語メンバーメニュー" width="100%" /></p>
|
||||
|
||||
## 🧩 高度な機能
|
||||
|
||||
### WebRTC
|
||||
|
||||
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
|
||||
|
||||
### 画面共有の ICE 候補
|
||||
|
||||
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
|
||||
|
||||
### クロスプラットフォーム P2P 画面共有
|
||||
|
||||
ブラウザユーザーと TeamSpeak 6 ネイティブクライアントは、互いの画面共有を検出・開始・視聴できます。ブラウザ間、およびブラウザとネイティブクライアント間の画面メディアは、可能な限り WebRTC/ICE の直接接続で送信されます。WebSpeak はセッション認証、共有状態、SDP/ICE シグナリングを担当しますが、画面メディア自体は転送しません。画面には配信中の状態と視聴者数が表示され、音量、全画面、終了を操作できます。取得設定は最大 1080p / 60 FPS に対応し、WebRTC 統計も確認できます。
|
||||
|
||||
### 中継サーバー
|
||||
|
||||
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
|
||||
|
||||
中継サービスは WebSpeak に組み込まれており、Node.js の標準ライブラリを使用します。GOST や sing-box などのプロキシフレームワークは不要です。WebRTC は [werift](https://github.com/shinyoshiaki/werift-webrtc)、TeamSpeak 接続はプロジェクトが保守する [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK を使用します。
|
||||
|
||||
## 🚀 デプロイ
|
||||
|
||||
| 方法 | 用途 |
|
||||
| --- | --- |
|
||||
| Docker Compose | 常時稼働サーバーと簡単な更新 |
|
||||
| Release パッケージ | Node.js やビルドツールを使わない起動 |
|
||||
| ソースから | 開発やカスタマイズ |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
起動後に `http://<your-host>:3040/admin` を開き、`admin` / `admin` でログインして直ちにパスワードを変更し、TeamSpeak を設定します。データは `webspeak-data` volume に保存されます。データベースを消さない場合は `docker compose down -v` を実行しないでください。
|
||||
|
||||
### Release パッケージ
|
||||
|
||||
[Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) から `windows-x64.zip`、`linux-x64.tar.gz`、`linux-arm64.tar.gz` のいずれかを取得し、同梱ランチャーを実行します。Docker は amd64/arm64 に対応します。`arm64-v8a`、`armeabi-v7a`、`x86_64` の Android APK もあります。APK は手動インストールとテスト向けのデバッグ署名で、Google Play 用ではありません。実機 TeamSpeak 音声は未検証です。
|
||||
|
||||
### ソースから
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ 要件と注意
|
||||
|
||||
- ソースからのビルドには Node.js `>=22.5` が必要です。Docker と Release には必要な実行環境が含まれます。
|
||||
- WebRTC に対応した最新の Chrome、Edge などを使用してください。マイクとウィンドウ音声には通常 HTTPS が必要です。
|
||||
- WebSpeak のホストから TeamSpeak に到達できる必要があります。標準音声ポートは `9987` です。
|
||||
- Web サービスは `3040/TCP` を使用します。公開時は HTTPS と WebSocket をリバースプロキシ経由で公開してください。
|
||||
- IPv6 にはルーティング可能な IPv6、OS/コンテナで有効な IPv6、適切なファイアウォール設定が必要です。リテラルは `[2001:db8::1]#9987` の形式です。
|
||||
- 保存したブラウザ ID は同じブラウザで同時に1接続だけ使用できます。
|
||||
- BGM共有はデスクトップのみで、WebRTC が必要です。
|
||||
|
||||
## コミュニティと関連プロジェクト
|
||||
|
||||
- [QQ グループ](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram グループ](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — Web コンソール付き TeamSpeak 音楽ボット。
|
||||
|
||||
## 🧾 更新履歴
|
||||
|
||||
| バージョン | 内容 |
|
||||
| --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | #10 を修正、#9/#12 の設定を実装し、#6/#7 を強化。PR #13 が報告した TS6 共有の見落としも修正しました。Windows x64、Linux x64/ARM64、Docker amd64/arm64、3 ABI の Android APK を追加しました。 |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | `.wskin` スキン、管理者向けの有効化/デフォルト設定、保護された昼・夜・ILLUSIA 内蔵スキンを追加。未完成の Aurora Voice サンプルを削除し、読み込み時のちらつき、ダークモードの視認性、音声画面のアートレイヤーを修正。公式スキン開発 Agent Skill も追加しました。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | ブラウザと TeamSpeak 6 ネイティブクライアント間のクロスプラットフォーム P2P 画面共有を追加しました。STUN/外部 TURN 設定、プレーヤーと視聴者状態、1080p/60 FPS 取得設定、WebRTC 統計に対応し、共有操作と訪問者番号も改善しました。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | チャンネルメンバーの移動操作と権限に応じた直接移動を追加し、アバター表示、ミュート状態の同期、保存 ID の復元に対応しました。5 言語のスクリーンショットとドキュメントも更新しました。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | ブラウザ側マイクノイズ抑制、ロシア語・日本語 UI、言語別ウェルカム文を追加。音量操作と PR #2 を基にしたエラー表示・エラーコードを改善しました。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 接続エラー表示を改善し、IPv6 接続先を標準対応しました。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | パスワード案内、正式な中継モード、複数中継選択、接続診断を追加しました。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Docker 起動を簡略化し、15秒の接続タイムアウトと継続的なネットワーク監視を追加しました。 |
|
||||
|
||||
完全な履歴は [CHANGELOG.md](../CHANGELOG.md) を参照してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
WebSpeak は [GNU Affero General Public License v3.0 only](../LICENSE) の下で公開されています。
|
||||
@@ -0,0 +1,151 @@
|
||||
# WebSpeak · Русский
|
||||
|
||||
[Главная проекта](../README.md) · [简体中文](./README.zh-CN.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [日本語](./README.ja.md)
|
||||
|
||||
## О проекте
|
||||
|
||||
| Логика | Описание |
|
||||
| --- | --- |
|
||||
| **WHAT** | WebSpeak — самостоятельно размещаемый веб-клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. |
|
||||
| **WHY** | Пользователям не нужно устанавливать настольный клиент: достаточно открыть браузер, а оператор сохраняет контроль над сервером и данными. |
|
||||
| **HOW** | После запуска настройте цель TeamSpeak и политику доступа в панели администратора. Браузер отвечает за интерфейс и аудио, WebSpeak — за шлюз. |
|
||||
|
||||
## Онлайн-демо
|
||||
|
||||
Адрес: <https://webspeak.example.invalid>
|
||||
|
||||
Демо-сервер находится в Гонконге; сеть и нагрузка могут быть нестабильными. Задержки, разрывы или временная недоступность демо не характеризуют самостоятельное развертывание.
|
||||
|
||||
## ✨ Возможности
|
||||
|
||||
| Возможность | Описание |
|
||||
| --- | --- |
|
||||
| TeamSpeak | Поддержка TeamSpeak 3 и TeamSpeak 6 с автоматическим определением протокола. |
|
||||
| Кроссплатформенная P2P-трансляция экрана | Пользователи браузера и нативные клиенты TeamSpeak 6 могут запускать и смотреть трансляции друг друга; медиаданные идут напрямую по WebRTC/ICE, а WebSpeak передаёт только сигнальные сообщения. |
|
||||
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
|
||||
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
|
||||
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
|
||||
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
|
||||
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
|
||||
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
|
||||
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
|
||||
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
|
||||
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
|
||||
| Скины | Защищённые дневная, ночная и ILLUSIA-темы, а также `.wskin` экземпляра с управлением включением и темой по умолчанию в панели администратора. |
|
||||
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, адаптивная верстка. |
|
||||
|
||||
## 🖼️ Скриншоты интерфейса
|
||||
|
||||
Скриншоты показывают русскую главную страницу, голосовое пространство, настройки аудио и меню участника.
|
||||
|
||||
### Главная страница
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-home.png" alt="Главная страница WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Голосовое пространство
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru.png" alt="Русское голосовое пространство WebSpeak" width="100%" /></p>
|
||||
|
||||
### Настройки аудио
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-audio.png" alt="Настройки аудио WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
### Меню участника
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-ru-menu.png" alt="Меню участника WebSpeak на русском" width="100%" /></p>
|
||||
|
||||
## 🧩 Расширенные функции
|
||||
|
||||
### WebRTC
|
||||
|
||||
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
|
||||
|
||||
### ICE для демонстрации экрана
|
||||
|
||||
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
|
||||
|
||||
### Кроссплатформенная P2P-трансляция экрана
|
||||
|
||||
Пользователи браузера и нативные клиенты TeamSpeak 6 могут обнаруживать, запускать и смотреть трансляции друг друга. Между браузерами, а также между браузером и нативным клиентом, экран передаётся по прямому соединению WebRTC/ICE, когда это возможно; WebSpeak отвечает за авторизацию сессии, состояние трансляции и передачу SDP/ICE-сигналов, но не переносит медиаданные экрана. Интерфейс показывает статус трансляции и число зрителей и предоставляет регулировку громкости, полноэкранный режим и выход. Для захвата доступны настройки до 1080p и 60 FPS, а также статистика WebRTC.
|
||||
|
||||
### Ретрансляторы
|
||||
|
||||
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
|
||||
|
||||
Сервис ретрансляции встроен в WebSpeak и использует стандартные библиотеки Node.js; GOST, sing-box и другие прокси-фреймворки не требуются. WebRTC использует [werift](https://github.com/shinyoshiaki/werift-webrtc), а TeamSpeak — поддерживаемый проектом [SDK EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js).
|
||||
|
||||
## 🚀 Развертывание
|
||||
|
||||
| Способ | Подходит для |
|
||||
| --- | --- |
|
||||
| Docker Compose | Постоянного сервера и простых обновлений |
|
||||
| Пакет Release | Запуска без Node.js и инструментов сборки |
|
||||
| Из исходников | Разработки и настройки проекта |
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
После запуска откройте `http://<ваш-хост>:3040/admin`, войдите с `admin` / `admin`, сразу смените пароль и настройте TeamSpeak. Данные хранятся в volume `webspeak-data`. Не используйте `docker compose down -v`, если не хотите удалить базу и настройки.
|
||||
|
||||
### Пакет Release
|
||||
|
||||
Скачайте подходящий пакет `windows-x64.zip`, `linux-x64.tar.gz` или `linux-arm64.tar.gz` из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) и запустите приложенный скрипт. Docker поддерживает amd64/arm64. Также доступны Android APK для `arm64-v8a`, `armeabi-v7a` и `x86_64`; они подписаны отладочным ключом для ручной установки и тестирования, а не для Google Play. Голос TeamSpeak на реальных устройствах пока не проверен.
|
||||
|
||||
### Из исходников
|
||||
|
||||
```bash
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## ⚠️ Требования и замечания
|
||||
|
||||
- Node.js `>=22.5` нужен для сборки из исходников; Docker и Release уже содержат необходимые компоненты.
|
||||
- Нужен современный Chrome, Edge или другой браузер с WebRTC. Микрофон и звук окна обычно требуют HTTPS.
|
||||
- WebSpeak должен иметь доступ к TeamSpeak; стандартный голосовой порт — `9987`.
|
||||
- Веб-сервис использует `3040/TCP`; для публичного сайта направьте HTTPS и WebSocket через обратный прокси.
|
||||
- Для IPv6 нужен маршрутизируемый IPv6, включённый IPv6 в ОС/контейнере и правила firewall. Литерал задаётся как `[2001:db8::1]#9987`.
|
||||
- Одна сохранённая браузерная идентичность может использоваться только одним активным подключением.
|
||||
- Фоновая музыка доступна только на компьютере и требует WebRTC.
|
||||
|
||||
## Сообщество и проекты
|
||||
|
||||
- [QQ-группа](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
|
||||
- [Telegram-группа](https://t.me/+8qShpTcuN9A3MWY9)
|
||||
- [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot) — музыкальный бот для TeamSpeak с веб-консолью.
|
||||
|
||||
## 🧾 История изменений
|
||||
|
||||
| Версия | Изменения |
|
||||
| --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | Исправлена #10, реализованы настройки #9/#12, усилены исправления #6/#7 и исправлен случай из PR #13; улучшено мобильное управление; добавлены Windows x64, Linux x64/ARM64, Docker amd64/arm64 и Android APK для трёх ABI. |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | Добавлены скины `.wskin`, управление включением и темой по умолчанию, а также защищённые темы «День», «Ночь» и ILLUSIA; удалён незавершённый пример Aurora Voice, исправлены мерцание при загрузке скина, контраст элементов в тёмном режиме и слои иллюстраций в голосовом пространстве; добавлен официальный Agent Skill для разработки скинов. |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | Добавлена кроссплатформенная P2P-трансляция экрана между браузерами и нативными клиентами TeamSpeak 6; добавлены настройка STUN/внешнего TURN, проигрыватель и состояние зрителей, захват до 1080p/60 FPS и статистика WebRTC; улучшено управление трансляцией и добавлен номер посетителя. |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | Добавлены управление перемещением участников и прямое перемещение с учётом прав; поддержаны аватары, синхронизация микрофона и восстановление идентичности; обновлены скриншоты и документация для пяти языков. |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | Добавлены браузерное шумоподавление микрофона, русский и японский интерфейсы и отдельные тексты приветствия; улучшены управление громкостью и сообщения/коды ошибок на основе PR #2. |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | Улучшены ошибки на странице входа и добавлена поддержка IPv6-целей по умолчанию. |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | Добавлены подсказки пароля, режим ретранслятора, выбор нескольких узлов и диагностика подключений. |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | Упрощён Docker-запуск, добавлен тайм-аут подключения 15 секунд и непрерывный сетевой мониторинг. |
|
||||
|
||||
Полная история находится в [CHANGELOG.md](../CHANGELOG.md).
|
||||
|
||||
## Лицензия
|
||||
|
||||
WebSpeak распространяется по [GNU Affero General Public License v3.0 only](../LICENSE).
|
||||
@@ -0,0 +1,258 @@
|
||||
# WebSpeak · 简体中文
|
||||
|
||||
[返回项目首页](../README.md) · [English](./README.en.md) · [Deutsch](./README.de.md) · [Русский](./README.ru.md) · [日本語](./README.ja.md)
|
||||
|
||||
WebSpeak 是一个可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户无需安装桌面客户端即可从浏览器加入频道,管理员可以在控制台管理目标服务器、访问方式和运行状态。
|
||||
|
||||
## 在线 Demo
|
||||
|
||||
地址:<https://webspeak.example.invalid>
|
||||
|
||||
公共 Demo 位于香港,网络和负载可能不稳定。延迟、断线或暂时不可用不代表自行部署后的实际表现。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
| 能力 | 说明 |
|
||||
| --- | --- |
|
||||
| TeamSpeak 兼容 | 支持 TeamSpeak 3 与 TeamSpeak 6,并自动探测目标服务器协议。 |
|
||||
| 跨端 P2P 屏幕共享 | 支持浏览器用户与 TeamSpeak 6 原生客户端互相发起和观看屏幕共享;媒体优先通过 WebRTC/ICE 直连,WebSpeak 仅转发协商信令。 |
|
||||
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
|
||||
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
|
||||
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
|
||||
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
|
||||
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
|
||||
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
|
||||
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
|
||||
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
|
||||
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
|
||||
| 皮肤 | 提供日间、夜间和 ILLUSIA 三款受保护皮肤,并支持实例自定义 `.wskin` 外观与管理员默认/启用管理。 |
|
||||
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語及响应式桌面/移动布局。 |
|
||||
| 自托管 | 数据由部署者保存,支持 Docker amd64/arm64、Windows x64、Linux x64/ARM64 服务端包和 Android 客户端。 |
|
||||
|
||||
## 🖼️ 界面截图
|
||||
|
||||
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
|
||||
|
||||
### 欢迎页
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-home.png" alt="WebSpeak 中文欢迎页" width="100%" /></p>
|
||||
|
||||
### 语音工作区
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh.png" alt="WebSpeak 中文语音工作区" width="100%" /></p>
|
||||
|
||||
### 音量控制
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-audio.png" alt="WebSpeak 中文音量控制" width="100%" /></p>
|
||||
|
||||
### 成员菜单
|
||||
|
||||
<p align="center"><img src="./screenshots/webspeak-zh-menu.png" alt="WebSpeak 中文成员菜单" width="100%" /></p>
|
||||
|
||||
## 🧩 高级功能
|
||||
|
||||
高级功能均为可选项;关闭时仍可使用兼容语音传输。配置入口在管理员控制台的“服务器”页,保存后对新连接生效。
|
||||
|
||||
### 1. WebRTC 低延迟语音
|
||||
|
||||
WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏。媒体服务由当前 WebSpeak 网关直接提供,不需要另设媒体服务器。
|
||||
|
||||
1. 登录 `/admin`,打开“服务器”页的“高级参数”。
|
||||
2. 关闭 WebRTC 时设置 UDP 起止端口,默认范围为 `40000–40099`。
|
||||
3. 在 WebSpeak 主机的安全组和防火墙中放行整个 UDP 范围。
|
||||
4. 勾选“启用 WebRTC”并保存,用户重新进入后即可协商;不支持时会回退到兼容传输。
|
||||
|
||||
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
|
||||
|
||||
### 反向代理 / TCP 隧道下的语音 WebRTC
|
||||
|
||||
在管理后台的 WebRTC 高级参数中可设置:
|
||||
|
||||
- **公网媒体地址**:WebSpeak 网关可被 UDP 访问的 IP 或域名,不含协议、路径或端口。优先于网页入口推断;留空时按 `Origin`、`X-Forwarded-Host`、`Host` 推断。域名会解析为 IP 候选。反代域名不一定是媒体地址。
|
||||
- **启用 IPv6 候选**:默认关闭;开启后保留 IPv4,同时收集 IPv6。需确保 IPv6 路由及 UDP 防火墙放行。
|
||||
- **语音 STUN 服务**:可设置 `stun:turn.teamspeak.com:3478`,浏览器和网关使用同一服务发现公网映射。留空保留旧行为:werift 网关仍使用库内置 STUN,浏览器不配置 STUN。当前字段仅支持可通过 IPv4 访问的 UDP STUN 域名或 IPv4 地址,不接受 IPv6 字面量、TURN 或凭据;IPv6 媒体候选独立于 STUN 开关。
|
||||
|
||||
保存后重新连接。网页和 WebSocket 经反代可达,不代表媒体 UDP 可达;STUN 仅发现地址,不中继音频,也不保证穿透所有 NAT。只有 TCP 隧道而无可用 UDP/IPv6 路径时,仍会回退兼容传输。应开放配置的整个 UDP 端口范围;静态端口转发需保持相同端口映射。
|
||||
|
||||
### 屏幕共享的 ICE 候选
|
||||
|
||||
屏幕共享媒体仍优先走浏览器之间的直连,WebSpeak 只转发协商信令。默认使用 TeamSpeak 官方 STUN 服务发现公网候选地址;STUN 不承载媒体。若部署者有合规的外部 TURN 服务,可在启动 WebSpeak 前设置 `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS`,值为 JSON 数组,例如:
|
||||
|
||||
```json
|
||||
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
|
||||
```
|
||||
|
||||
配置 TURN 后,媒体可能经过该外部 TURN 服务,但不会经过 WebSpeak 网关;未配置时只使用直连和 STUN。
|
||||
|
||||
### 跨端 P2P 屏幕共享
|
||||
|
||||
浏览器用户与 TeamSpeak 6 原生客户端可以互相发现、发起和观看屏幕共享。浏览器之间以及浏览器与原生客户端之间的屏幕媒体优先通过 WebRTC/ICE 端到端传输;WebSpeak 负责会话鉴权、共享状态和 SDP/ICE 信令转发,不承载屏幕媒体流量。页面提供直播状态、观众人数、播放器音量、全屏和退出控制,也可在共享设置窗口中选择最高 1080p 与 60 FPS,并查看 WebRTC 统计。
|
||||
|
||||
### 2. 中继模式
|
||||
|
||||
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
|
||||
|
||||
中继实例是专用转发服务,不提供前台和管理员后台,只接受带匹配令牌的 WebSpeak 网关会话。令牌至少使用 16 个字符的随机值。
|
||||
|
||||
#### 源码启动
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm run build
|
||||
WEBSPEAK_MODE=relay \
|
||||
WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
WEBSPEAK_RELAY_HOST='0.0.0.0' \
|
||||
WEBSPEAK_RELAY_PORT='39087' \
|
||||
node dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:WEBSPEAK_MODE = "relay"
|
||||
$env:WEBSPEAK_RELAY_TOKEN = "replace-with-a-long-random-token"
|
||||
$env:WEBSPEAK_RELAY_HOST = "0.0.0.0"
|
||||
$env:WEBSPEAK_RELAY_PORT = "39087"
|
||||
node .\dist\index.js
|
||||
```
|
||||
|
||||
#### 发布包启动
|
||||
|
||||
从 [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载并解压对应平台的包:
|
||||
|
||||
```bash
|
||||
# Linux
|
||||
export WEBSPEAK_MODE=relay
|
||||
export WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token'
|
||||
export WEBSPEAK_RELAY_HOST='0.0.0.0'
|
||||
export WEBSPEAK_RELAY_PORT='39087'
|
||||
./runtime/node ./dist/index.js
|
||||
```
|
||||
|
||||
Windows PowerShell 使用同名环境变量后运行 `.\runtime\node.exe .\dist\index.js`。
|
||||
|
||||
#### Docker 启动
|
||||
|
||||
```bash
|
||||
docker run -d --name webspeak-relay --restart unless-stopped --network host \
|
||||
-e WEBSPEAK_MODE=relay \
|
||||
-e WEBSPEAK_RELAY_TOKEN='replace-with-a-long-random-token' \
|
||||
-e WEBSPEAK_RELAY_PORT='39087' \
|
||||
ghcr.io/echosixhiya/webspeak:latest
|
||||
```
|
||||
|
||||
放行中继主机的 UDP 监听端口,默认是 `39087`。
|
||||
|
||||
#### 在网关中启用
|
||||
|
||||
1. 管理员控制台 → “服务器” → “中继服务器”,添加一个或多个节点。
|
||||
2. 为每个节点填写自定义名称、地址(例如 `relay.example.com#39087`)和匹配令牌并保存。
|
||||
3. 访客欢迎页即可选择直连或其中一个中继。
|
||||
|
||||
关闭并保存中继配置后,访客页面不会显示中继选项。
|
||||
|
||||
### 3. 依赖与归属
|
||||
|
||||
- 中继服务是 WebSpeak 自带实现,使用 Node.js 标准库,不依赖 GOST、sing-box 或其他代理框架。
|
||||
- WebRTC 使用 [werift](https://github.com/shinyoshiaki/werift-webrtc) `0.24.4`,上游采用 MIT 许可证。
|
||||
- TeamSpeak 协议使用项目维护的 [EchoSixHIYA/teamspeak-js](https://github.com/EchoSixHIYA/teamspeak-js) SDK fork。
|
||||
|
||||
## 🧾 更新日志
|
||||
|
||||
| 版本 | 日期 | 摘要 |
|
||||
| --- | --- | --- |
|
||||
| [v0.2.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.6) | 2026-10-08 | 相对 0.2.5 修复 #10、实现 #9/#12,并加固 #6/#7;修复 PR #13 所报告的既有屏幕共享漏同步;改善语音和移动端交互;发布 Windows x64、Linux x64/ARM64、Docker amd64/arm64 和 Android 三种 ABI 构建包。 |
|
||||
| [v0.2.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) | 2026-09-27 | 新增 `.wskin` 皮肤系统、管理员启用/默认管理和受保护的日间/夜间/ILLUSIA 内置皮肤;移除未完成 Aurora Voice 样例,修复皮肤加载闪烁、暗色控件可读性与语音界面美术层级,并加入官方皮肤开发 Agent Skill。 |
|
||||
| [v0.2.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.4) | 2026-09-22 | 新增浏览器与 TeamSpeak 6 原生客户端之间的跨端 P2P 屏幕共享;提供 STUN/外部 TURN 配置、直播播放器、观众状态、1080p/60 FPS 采集设置和 WebRTC 统计;优化屏幕共享交互并新增访客编号。 |
|
||||
| [v0.2.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.3) | 2026-09-19 | 新增频道成员调度与按权限直接移动;支持头像、静音状态同步和身份恢复;更新五种语言的功能截图与文档。 |
|
||||
| [v0.2.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.2) | 2026-09-17 | 提供浏览器端麦克风降噪、俄语和日语支持及按语言欢迎词配置;优化音量交互和 PR #2 基础上的错误提示与错误代码。 |
|
||||
| [v0.2.1](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.1) | 2026-09-13 | 优化首页连接错误显示,保留并安全截断错误代码;默认支持 IPv6 TeamSpeak 目标。 |
|
||||
| [v0.2.0](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.0) | 2026-09-10 | 增加服务器密码提示、正式中继部署模式、多中继选择和管理员日志原因显示。 |
|
||||
| [v0.1.8](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.8) | 2026-09-08 | 简化 Docker 部署,支持同机 TeamSpeak,增加 15 秒连接超时和持续网络监测。 |
|
||||
| [v0.1.7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.7) | 2026-09-06 | 增加德语、Telegram、网络性能面板和整体音量;修复伴奏音量波动。 |
|
||||
| [v0.1.6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6) | 2026-09-04 | 增加桌面端伴奏、身份保持提醒和网站图标;修复 WebRTC 成员独立音量。 |
|
||||
| [v0.1.5](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.5) | 2026-09-04 | 修复身份保存逻辑并优化主题切换。 |
|
||||
| [v0.1.4](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4) | 2026-09-03 | 修复 WebRTC、频道聊天并优化管理页、日志和移动端布局。 |
|
||||
| [v0.1.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.3) | 2026-09-03 | 引入内置 WebRTC、迁移 TeamSpeak SDK 并改善成员同步和语音缓冲。 |
|
||||
|
||||
完整记录见 [CHANGELOG.md](../CHANGELOG.md)。
|
||||
|
||||
## 🚀 部署方案
|
||||
|
||||
| 方案 | 适用场景 | 环境 |
|
||||
| --- | --- | --- |
|
||||
| Docker Compose(推荐) | 长期运行、升级简单、数据持久化 | Docker Engine + Docker Compose |
|
||||
| 发布包 | 不安装 Node.js 和构建依赖 | Windows x64 或 Linux x64/ARM64 |
|
||||
| 源码运行 | 开发、调试和二次开发 | Node.js 22.5+、Git 和本地编译工具 |
|
||||
|
||||
### Docker Compose(推荐)
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
启动后访问 `http://<你的主机>:3040`。使用反向代理时将上游指向该地址;启用 WebRTC 时放行控制台显示的 UDP 端口范围。数据保存在 `webspeak-data` volume 中。
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f webspeak
|
||||
```
|
||||
|
||||
升级:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`,否则会删除数据库和管理员设置。
|
||||
|
||||
### 发布包
|
||||
|
||||
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
|
||||
|
||||
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
|
||||
|
||||
### 源码运行
|
||||
|
||||
```bash
|
||||
git clone https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
|
||||
cd WebSpeak-client-for-TeamSpeak
|
||||
npm ci --ignore-scripts
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts
|
||||
npm --prefix web ci
|
||||
npm --prefix web run build
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
构建 `@discordjs/opus` 需要 Python、Make 和 C/C++ 编译工具。
|
||||
|
||||
### 首次配置
|
||||
|
||||
1. 打开 `http://<你的主机>:3040/admin`。
|
||||
2. 使用默认账号 `admin` / `admin` 登录,并立即设置至少 12 位的新密码。
|
||||
3. 在“服务器”页配置 TeamSpeak 目标和访问方式,例如 `voice.example.com#9987`。
|
||||
4. 公网使用时配置 HTTPS;启用 WebRTC 时放行控制台显示的 UDP 范围。
|
||||
|
||||
## ⚠️ 要求和注意事项
|
||||
|
||||
| 项目 | 要求或注意事项 |
|
||||
| --- | --- |
|
||||
| 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和窗口音频通常要求 HTTPS。 |
|
||||
| TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak;默认语音端口为 `9987`。 |
|
||||
| Web 服务网络 | 服务使用 `3040/TCP`,公网建议通过 HTTPS 反向代理提供网页和 WebSocket。 |
|
||||
| IPv6 | IPv6 字面量写为 `[2001:db8::1]#9987`。主机/容器需要可路由 IPv6、启用 IPv6 的操作系统和 Node.js,以及相应防火墙放行。 |
|
||||
| WebRTC | 默认使用 `40000–40099/UDP`,启用后需放行整个范围;修改范围前先关闭 WebRTC。 |
|
||||
| 身份保持 | 同一浏览器身份同时只能保持一条活动连接;并行连接请关闭第二条的身份保持或使用其他浏览器配置文件。 |
|
||||
| 伴奏 | 仅桌面端提供且要求 WebRTC;选择窗口或标签页时还要勾选共享音频。 |
|
||||
| 数据 | Docker 数据在 `webspeak-data` volume;发布包和源码运行数据在 `data/`。升级前建议备份。 |
|
||||
| 会话上限 | 单实例最多允许 100 个活动网页会话。 |
|
||||
@@ -0,0 +1,251 @@
|
||||
# WebSpeak 皮肤开发规范
|
||||
|
||||
本文说明如何制作、校验并发布 WebSpeak `.wskin` 皮肤包。皮肤可为公开页面逐个部件定制二次元美术表现:背景、素材、配色、轮廓、圆角、阴影、头像装饰、按钮质感、滚动条颜色和播放器外观都可以自定义;但组件的位置、尺寸、排列、文字排版空间及交互结构由 WebSpeak 固定提供,皮肤不得重排或覆盖。
|
||||
|
||||
页面结构、必要控件和所有基础翻译均由 WebSpeak 提供。皮肤包不必携带文案;如果只包含样式与美术素材,所有界面文字仍由 WebSpeak 按当前语言显示。`content.json` 仅用于可选覆盖,缺少的语言或字段回退到 WebSpeak 的基础内容。皮肤不注入 HTML 或 JavaScript,也不改变语音、权限、连接、拖动和屏幕共享行为。**管理后台 `/admin/**` 不属于皮肤范围,始终使用 WebSpeak 自己的固定样式。**
|
||||
|
||||
可直接查看 [ILLUSIA 风示例源码](examples/illusia-voice/) 与 [示例说明](examples/ILLUSIA-VOICE.md)。它使用本地美术素材和 CSS 完整定制首页、语音房间、成员区、聊天空状态及播放器,同时沿用 WebSpeak 提供的基础翻译;也是管理控制台内置且不可移除的示例皮肤。
|
||||
|
||||
## 使用与发布
|
||||
|
||||
管理员在 `/admin/skins` 查看三款随 WebSpeak 提供的内置皮肤,并可导入、替换、启用/停用或删除实例自定义皮肤;还可指定访客首次访问时使用的默认皮肤。默认日间、默认夜间和 ILLUSIA 风为受保护内置项,不可替换、停用或移除。访客手动选择的皮肤保存在该浏览器,后续实例默认值变更不会覆盖该明确选择;仅自动套用过旧默认值的浏览器会采用最新实例默认值。皮肤包会缓存在浏览器本地;页面启动时会查询实例目录,目录可用且版本更新时拉取新包。若网络不可用,已缓存的版本仍可使用。
|
||||
|
||||
选择器提供默认日间、默认夜间、内置 ILLUSIA 风和已启用的实例皮肤;没有“跟随系统”选项。停用的实例皮肤不向访客展示,也不能从服务端下载;若它是当前默认皮肤,系统会安全回退到默认日间。管理员设置的默认值只影响未手动选择皮肤的访客。自定义皮肤是独立的外观选择,不继承之前的日间或夜间模式;皮肤未覆盖的部件回退到浅色基础外观,避免一套组件混入另一套模式。自定义皮肤可自行声明 `color-scheme` 并定义深色外观;切换为日间或夜间时,会停用当前自定义包。文档级 `data-theme` 仍由 WebSpeak 保留给管理后台使用。
|
||||
|
||||
## 包结构
|
||||
|
||||
`.wskin` 是标准 ZIP 容器,推荐把下列文件直接放在 ZIP 根目录:
|
||||
|
||||
```text
|
||||
manifest.json # 必需:身份、版本与入口
|
||||
skin.css # 必需:皮肤样式
|
||||
content.json # 可选:首页内容与多语言界面文案
|
||||
assets/preview.jpg # 可选:管理后台显示的预览图,也可在 CSS 中使用
|
||||
assets/background.webp # 可选:页面艺术素材
|
||||
assets/brand.woff2 # 可选:自带字体
|
||||
```
|
||||
|
||||
所有资源路径使用 `/`,区分大小写,并相对于包根目录。CSS 的 `url()` 使用同样的包根相对路径,例如 `url("assets/background.webp")`。不得使用机器本地路径、站点绝对路径或远程 URL。
|
||||
|
||||
### `manifest.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.25",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A visual-only art skin using the WebSpeak interface translations.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.6"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | 当前必须为数字 `1`。 |
|
||||
| `id` | 必需,最多 80 个字符;只允许小写字母、数字、点和连字符;不能以 `builtin.` 开头,也不能使用受保护 ID `builtin.light`、`builtin.dark` 或 `community.illusia-voice`。发布后不要更改。 |
|
||||
| `name`、`author`、`license` | 必需,各最多 80 个字符。资源授权由作者负责确认。 |
|
||||
| `version`、`minAppVersion` | 必需,使用语义化版本号,例如 `1.2.0`。 |
|
||||
| `entry` | 必需,包内 CSS 文件路径,最多 120 个字符。 |
|
||||
| `content` | 可选,包内 JSON 文件路径,最多 120 个字符。 |
|
||||
| `preview` | 可选,包内 PNG、JPG/JPEG、WebP、AVIF 或 GIF 图片路径,最多 120 个字符。 |
|
||||
| `description` | 可选,最多 400 个字符。 |
|
||||
|
||||
清单不得重复声明同一个文件为 CSS、内容或预览入口。
|
||||
|
||||
## 首页内容和文案
|
||||
|
||||
`content.json` 完全可选。WebSpeak 自带中文、英语、德语、俄语和日语的基础内容,因此纯美术皮肤无需复制翻译文件。若希望为皮肤定制部分文案,可按 locale 覆盖连接首页内容和公开界面文案;未定义的语言、字段或翻译键会回退到 WebSpeak 内容,不要求皮肤重复提供整套文字。当前允许 1–20 个 locale,locale 写作 `en`、`zh-CN`、`ja-JP` 等形式。`defaultLocale` 必须指向一个已定义的 locale。示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultLocale": "en",
|
||||
"locales": {
|
||||
"en": {
|
||||
"home": {
|
||||
"eyebrow": "A room of your own",
|
||||
"title": "Talk",
|
||||
"titleAccent": "together",
|
||||
"description": "Join a voice room from your browser.",
|
||||
"welcomeTitle": "Join the room",
|
||||
"welcomeDescription": "Choose a name and connect.",
|
||||
"features": [
|
||||
{ "title": "Clear voice", "description": "Low-latency Opus audio." }
|
||||
]
|
||||
},
|
||||
"messages": {
|
||||
"home.connect": "Enter the room",
|
||||
"voice.activity-heading": "Voice activity",
|
||||
"demo.heroLead": "A preview customized by this skin."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`home` 支持 `brandName`、`eyebrow`、`title`、`titleAccent`、`description`、`welcomeTitle`、`welcomeDescription` 和 `features`。普通文字最多 500 个字符;`features` 最多 8 项,每项的 `title` 最多 80 个字符、`description` 最多 240 个字符。功能卡片图标和状态由应用提供,皮肤不能通过 JSON 注入节点。
|
||||
|
||||
`messages` 的键是公开页面中翻译调用使用的键;首页/语音页键可在 `web/src/i18n/web-client.ts` 查找,演示页键使用 `demo.` 前缀加字段名(例如 `demo.heroLead`、`demo.speakingNow`)。每个 locale 最多覆盖 200 条,每条文案最多 500 个字符。键只能由小写字母开头,并包含字母、数字或点。语言回退顺序为默认 locale、当前语言和更具体的 locale;之后回退到 WebSpeak 原文。
|
||||
|
||||
管理后台的文字不读取皮肤包,不能通过 `messages` 修改。
|
||||
|
||||
## CSS 皮肤接口
|
||||
|
||||
### 自动隔离
|
||||
|
||||
运行时把 `skin.css` 的每个选择器限定在皮肤自己的公开页面根节点内:
|
||||
|
||||
```css
|
||||
/* 选择器必须使用公开的页面/部件钩子;运行时再加上皮肤根作用域。 */
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid var(--skin-accent);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
实际规则会被限定在类似下面的根节点内,不会匹配 `/admin/**`:
|
||||
|
||||
```css
|
||||
[data-ws-page="voice"] [data-ws-part="voice.member.avatar"]
|
||||
```
|
||||
|
||||
也可以写 `:root { --skin-accent: ... }` 设置皮肤自己的变量;`:root` 会被转换成当前皮肤根。选择器必须包含 `:root`、`[data-ws-page]` 或 `[data-ws-part]`。不要写 `:global()`、`html`、`body` 或 Vue 内部 class 作为公开接口。组件 class 可能随版本调整,`data-ws-part` 才是皮肤作者接口。自定义变量名必须使用 `--skin-` 前缀,不能覆盖 WebSpeak 的内部令牌。
|
||||
|
||||
页面根节点使用 `data-ws-page` 区分 `home`、`voice` 和 `demo`。使用 `data-ws-state` 选择明确状态,如 `active`、`idle`、`current`、`open`、`closed`、`drag-over`、`dragging`、`speaking`、`connected`、`self`、`mine` 或 `other`。语音成员还提供 `data-ws-speaking="true|false"` 和 `data-ws-self="true|false"`。交互元素会带有 `data-ws-critical="true"`;没有专属部件名称的按钮、链接、输入框、滑块和可拖动成员会使用通用部件 `data-ws-part="control"`,并以 `data-ws-control-kind` 标出 `button`、`link`、`input`、`checkbox`、`range`、`select`、`textarea`、`menuitem` 或 `draggable`。
|
||||
|
||||
### 已发布的部件名称
|
||||
|
||||
下列名称来自当前前端模板。对新功能,作者可以先用通用 `control` 部件;后续新增稳定部件会更新本目录。
|
||||
|
||||
| 页面区域 | `data-ws-part` |
|
||||
| --- | --- |
|
||||
| 通用 | `app`、`app.toast`、`control`、`skin.trigger`、`skin.menu`、`skin.option`、`language.trigger`、`language.menu`、`language.option` |
|
||||
| 首页 | `home`、`home.header`、`home.brand`、`home.header-tools`、`home.gateway-status`、`home.content`、`home.hero`、`home.hero.eyebrow`、`home.hero.title`、`home.hero.description`、`home.features`、`home.feature`、`home.visitors`、`home.join-card`、`home.join-card.waveform`、`home.join-card.sonar`、`home.join-title`、`home.join-description`、`home.notice`、`home.form`、`home.server-target`、`home.field-label`、`home.field`、`home.relay-choice`、`home.relay-choice.copy`、`home.server-history`、`home.server-history.group`、`home.favorite-toggle`、`home.identity`、`home.identity-actions`、`home.identity-import.open`、`home.identity-export.button`、`home.identity-import-dialog`、`home.identity-import.header`、`home.identity-import.close`、`home.identity-import.textarea`、`home.identity-import.drop-zone`、`home.identity-import.file-button`、`home.identity-import.error`、`home.identity-import.security`、`home.identity-import.footer`、`home.identity-import.cancel`、`home.identity-import.submit`、`home.connect`、`home.security-note`、`home.footer`、`home.community-dialog` |
|
||||
| 语音工作区 | `voice.shell`、`voice.workspace`、`voice.header`、`voice.header-actions`、`voice.breadcrumbs`、`voice.performance`、`voice.performance.panel`、`voice.performance.route`、`voice.performance.metrics`、`voice.performance.status`、`voice.performance.webrtc-stats`、`voice.connection-status`、`voice.audio-status`、`voice.poke`、`voice.scroll`、`voice.content`、`voice.activity`、`voice.activity.artwork`、`voice.activity-heading`、`voice.screen-share-error`、`voice.members`、`voice.members.empty`、`voice.member`、`voice.member.avatar-wrap`、`voice.member.avatar`、`voice.member.name`、`voice.member.status`、`voice.member.live-indicator`、`voice.member.stop-share`、`voice.member.share-actions`、`voice.member-panel`、`voice.member-panel.heading`、`voice.member-panel.search`、`voice.member-panel.channels`、`voice.channel-group`、`voice.channel-group.heading`、`voice.channel-group.members`、`voice.member-row`、`voice.member-row.avatar`、`voice.member-row.copy`、`voice.member-row.flags`、`voice.member-row.volume`、`voice.whisper-strip`、`voice.audio-dock`、`voice.audio-dock.microphone`、`voice.audio-dock.microphone-panel`、`voice.audio-dock.output`、`voice.audio-dock.output-panel`、`voice.audio-settings`、`voice.mobile-more`、`voice.mobile-nav` |
|
||||
| 聊天与菜单 | `voice.chat`、`voice.chat.tabs`、`voice.chat.tab`、`voice.chat.heading`、`voice.chat.messages`、`voice.chat.event`、`voice.chat.message`、`voice.chat.message-avatar`、`voice.chat.message-body`、`voice.chat.message-bubble`、`voice.chat.empty`、`voice.chat.composer`、`voice.chat.status`、`voice.context-menu-backdrop`、`voice.context-menu`、`voice.context-menu.header`、`voice.context-menu.move-submenu` |
|
||||
| 屏幕共享 | `voice.screen-share-settings`、`voice.screen-share-settings.heading`、`voice.screen-share-settings.fields`、`voice.screen-share-settings.note`、`voice.screen-share-settings.actions`、`voice.screen-player`、`voice.screen-player.stage`、`voice.screen-player.video`、`voice.screen-player.placeholder`、`voice.screen-player.exit`、`voice.screen-player.viewers`、`voice.screen-player.viewer-avatar`、`voice.screen-player.live`、`voice.screen-player.source`、`voice.screen-player.controls`、`voice.screen-player.volume`、`voice.screen-player.fullscreen` |
|
||||
| `/demo` 演示页 | `demo.header`、`demo.brand`、`demo.header-tools`、`demo.badge`、`demo.skin-switcher`、`demo.language-switcher`、`demo.home-link`、`demo.reconnect`、`demo.reconnect.restore`、`demo.layout`、`demo.channels`、`demo.channels.heading`、`demo.channel`、`demo.channel.select`、`demo.channel.members`、`demo.main`、`demo.hero`、`demo.live`、`demo.hero.title`、`demo.hero.description`、`demo.hero.online`、`demo.wave`、`demo.voice-heading`、`demo.voice-grid`、`demo.voice-card`、`demo.avatar`、`demo.member-name`、`demo.member-status`、`demo.chat.heading`、`demo.chat.tabs`、`demo.chat.tab`、`demo.chat.messages`、`demo.chat.message`、`demo.chat.empty`、`demo.chat.composer`、`demo.chat.input`、`demo.chat.send`、`demo.actions`、`demo.actions.heading`、`demo.action.speaking`、`demo.action.poke`、`demo.action.reconnect`、`demo.note`、`demo.user`、`demo.poke-notification`、`demo.poke.dismiss` |
|
||||
|
||||
`voice.member.avatar` 是语音活动区头像;`voice.member-row.avatar` 是右侧成员树头像。状态属性还会使用 `current`、`drag-over`、`dragging`、`self`、`events-empty` 和 `messages-empty`。当前根节点以及屏幕共享播放器、弹窗、菜单都属于同一皮肤作用域。
|
||||
|
||||
首页身份选项支持导入 TeamSpeak `.ini` 或身份字段,并可导出为 TeamSpeak `.ini`;导入弹窗解析身份的过程在浏览器本地完成。自定义皮肤可以分别调整身份操作按钮、粘贴区、拖放区域、安全提示和弹窗按钮,但不得隐藏或弱化权限继承与私钥安全提示。
|
||||
|
||||
`voice.activity.artwork` 是位于语音活动区内容上方的固定装饰平面。皮肤可以在其上绘制带透明背景的立绘,让角色压住成员卡片或直播画面的边缘;平面本身不占布局空间、不拦截点击,成员和播放器控件仍保持可交互。只通过背景图及背景定位/缩放来适配素材,不改变其定位和层级。
|
||||
|
||||
`voice.member-panel` 的 `::before` 是成员栏耳机/场景插画层,宿主已固定它的尺寸、位置、透视和前后层级;皮肤只需提供透明背景素材并调整背景显示、滤镜或阴影,不能自行定位或改变尺寸。消息空状态的 `::before` / `::after` 预留给气泡等小型装饰,宿主负责形状位置;皮肤可以绘制边框、底色和点状背景,但标题和说明文字仍由 WebSpeak 翻译并保持可见。
|
||||
|
||||
皮肤与语言选择器的触发按钮、菜单和每个选项都提供上述通用部件钩子。`skin.option` 另带有 `data-ws-skin-id`(内置项为 `builtin.light`、`builtin.dark` 和 `community.illusia-voice`,实例皮肤项为其清单 ID);`language.option` 带有 `data-ws-language`。皮肤可以据此只装饰自己的选择项,而不影响其他皮肤、语言选项或选择器交互。例如:
|
||||
|
||||
```css
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
background-image: linear-gradient(110deg, #efffff, #c8f3f2);
|
||||
}
|
||||
```
|
||||
|
||||
### 令牌、字体、动效和图片
|
||||
|
||||
皮肤只负责“画什么样”,不负责“放在哪里”。可用的视觉规则包括文字/背景颜色、背景图片及其裁切、圆角、轮廓、阴影、滤镜和动画;边框可用不占空间的内阴影绘制。推荐先定义皮肤变量,再为公开部件编写视觉规则:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--skin-page-bg: #091317;
|
||||
--skin-panel: #142329;
|
||||
--skin-text: #edf8f5;
|
||||
--skin-muted: #9db5af;
|
||||
--skin-accent: #47dcc4;
|
||||
--skin-card-radius: 20px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: var(--skin-card-radius);
|
||||
box-shadow: 0 18px 50px #0008, inset 0 0 0 1px color-mix(in srgb, var(--skin-accent) 50%, transparent);
|
||||
}
|
||||
```
|
||||
|
||||
`url()` 只允许引用包内图片或 WOFF2 字体。支持 PNG、JPG/JPEG、WebP、AVIF、GIF 和 WOFF2;SVG 不接受。自带字体示例:
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "ILLUSIA Sans";
|
||||
src: url("assets/illusia-sans.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
[data-ws-page="voice"] { font-family: "ILLUSIA Sans", sans-serif; }
|
||||
```
|
||||
|
||||
字体必须随包附带并拥有可再分发许可。自定义字体可能改变不同语言的字宽,因此校验器会给出提示;发布前必须检查中文、英语、德语、俄语和日语下的标题、按钮和长文案是否仍完整可读。字体族名和 `@keyframes` / `@layer` 名称会自动隔离,避免与其他皮肤冲突。请支持 `prefers-reduced-motion`,并确保焦点、错误、静音、正在说话等状态仍容易辨认。
|
||||
|
||||
### 固定布局与交互边界
|
||||
|
||||
皮肤校验器会拒绝改变布局、定位、尺寸、文字流向/换行或交互命中区域的 CSS 声明,包括 `display`、`position`、`inset`、`z-index`、宽高、内外边距、网格/弹性布局、间距、溢出裁切、变换、指针事件、字号、行高、字距、大小写转换和换行方式等。也不能通过 `all` 重置组件或用伪元素生成/替换文字。动画可以用于颜色、阴影、滤镜等装饰效果,但关键帧同样不能动画化布局属性。
|
||||
|
||||
因此,皮肤可以把成员头像绘制成角色徽章、给屏幕播放器加主题边框和背景、换首页美术素材,但不能移动播放器、压缩文字、扩大/缩小成员卡片、把锚定浮层改成模态弹窗,或挪动按钮的点击区域。用 `background-position` / `background-size` 只调整图片在既有区域中的裁切,不改变组件盒子。轮廓或内阴影可作为不参与排版的描边。
|
||||
|
||||
外观可以因窄屏而更换图片裁切或装饰,但 `@media` 规则也受同一限制,不能用来重排组件。上线前仍需预览桌面与窄屏、所有五种语言、日夜基础主题、键盘焦点、减少动效偏好,并确认浮层和必要控件保持在原位、文字未被裁切。
|
||||
|
||||
## 安全边界和限制
|
||||
|
||||
校验在上传端和服务端执行;服务端只登记有效皮肤包,访客只能下载登记的包。当前限制如下:
|
||||
|
||||
| 项目 | 上限 |
|
||||
| --- | ---: |
|
||||
| ZIP `.wskin` | 20 MiB |
|
||||
| 解压总大小 | 50 MiB |
|
||||
| ZIP 条目数 | 128 |
|
||||
| 单个 CSS 文件 | 512 KiB |
|
||||
| `content.json` | 256 KiB |
|
||||
| 单张图片(包括预览) | 16 MiB |
|
||||
| 单个 WOFF2 字体 | 4 MiB |
|
||||
| 每实例皮肤数 | 50 |
|
||||
| 每实例皮肤包总存储 | 200 MiB |
|
||||
|
||||
压缩包路径穿越、重复/冲突路径、符号链接、异常 ZIP 元数据和本地文件头/目录不一致都会被拒绝。仅允许受支持的 CSS at-rule:`@media`、`@supports`、`@container`、具名 `@layer`、`@font-face` 和 keyframes。`@import`、脚本、HTML、外部网络资源会被拒绝;`!important` 可用于皮肤作用域内的样式。字体 `local()` 也会拒绝,避免绕过包内字体来源。
|
||||
|
||||
必要操作控件(加入/退出、麦克风、设置、菜单、屏幕共享退出、音量、全屏等)及其布局容器不能被隐藏或整体重置。只有下列明确标记为可选的装饰部件,才允许通过不改变排版盒子的透明度效果淡出:
|
||||
|
||||
```css
|
||||
[data-ws-part="home.hero.eyebrow"]
|
||||
[data-ws-part="home.gateway-status"]
|
||||
[data-ws-part="home.features"]
|
||||
[data-ws-part="home.feature"]
|
||||
[data-ws-part="home.visitors"]
|
||||
[data-ws-part="voice.activity-heading"]
|
||||
[data-ws-part="voice.member.avatar"]
|
||||
[data-ws-part="voice.member.live-indicator"]
|
||||
[data-ws-part="voice.member-row.avatar"]
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"]
|
||||
[data-ws-part="voice.screen-player.live"]
|
||||
[data-ws-part="demo.badge"]
|
||||
[data-ws-part="demo.wave"]
|
||||
[data-ws-part="demo.avatar"]
|
||||
[data-ws-part="demo.member-status"]
|
||||
[data-ws-part="demo.note"]
|
||||
```
|
||||
|
||||
上面必须使用单独的精确属性选择器;不能通过父容器、组合选择器或子元素间接隐藏/重置内容。关键帧只有在其动画仅被这些可选部件引用时,才可使用透明度归零;若关键帧也被必要控件引用或动画名通过变量指定,则会被拒绝。`clip`、`clip-path` 和 `mask` 一律不允许,避免视觉裁切误伤真实控件。校验器是防止布局回归的边界,不是视觉质量证明;自定义字体、复杂背景和高对比特效仍需人工检查文字可读性与控件辨识度。
|
||||
|
||||
皮肤可以重画控制外观,但不能重新布置或阻断加入/退出、麦克风状态、设置、菜单、屏幕共享退出、音量、全屏等必要操作。校验成功不代表设计质量合格;提交前要逐页实测窄屏和桌面尺寸、所有界面语言、日夜基础主题、键盘焦点与减少动效设置。
|
||||
|
||||
CSS 被限定在 `.ws-skin-root` 内,管理员页面不会继承皮肤。删除实例里的包会停止从服务器提供该包;已经下载过的浏览器副本会保留在本地存储,因此仍可能在该浏览器的选择器中出现。清除该站点的浏览器数据可移除本地副本。
|
||||
|
||||
## 制作与验收
|
||||
|
||||
1. 复制 `docs/examples/illusia-voice/`,先修改 `manifest.json` 的唯一 `id`、名称、作者、版本和授权。ILLUSIA 是完整的美术参考,不是必须沿用的角色或配色。
|
||||
2. 只使用本目录公开的 `data-ws-part`、`data-ws-page`、状态属性和包内静态资源。不要依赖 Vue 内部 class。
|
||||
3. 使用本地资源编写 `skin.css`;需要改首页文字或公开翻译时补充 `content.json`。
|
||||
4. 在包根目录生成 ZIP,再改扩展名为 `.wskin`。PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\illusia-voice.zip -Force
|
||||
Rename-Item .\illusia-voice.zip illusia-voice.wskin
|
||||
```
|
||||
|
||||
5. 在管理员后台 `/admin/skins` 上传。用访客浏览器分别检查连接首页、进入语音页和 `/demo`;测试自定义图片、所有交互控件、语音/静音状态、成员列表、聊天、屏幕共享播放器和设置,确认组件位置、尺寸、排列与未启用皮肤时一致。
|
||||
6. 检查至少一个窄屏尺寸和桌面尺寸,并检查焦点可见、对比度、动效偏好;确认没有第三方素材授权问题。
|
||||
|
||||
当前自动化回归涵盖 ZIP/清单验证、资源路径、CSS 隔离与拒绝规则、文案结构和服务端皮肤目录读写。视觉排版、内容遮挡和浏览器间表现仍须人工预览。
|
||||
@@ -0,0 +1,14 @@
|
||||
# ILLUSIA风
|
||||
|
||||
ILLUSIA风 is a visual-only `.wskin` example built from the local artwork in `illusia-voice/assets/`. It styles the WebSpeak home page, voice workspace, screen-share player, and `/demo` with bright glass surfaces and cyan accents. The homepage skin follows the supplied reference art for the translucent navigation, matching glass skin and language selectors, an illustrated animated ILLUSIA skin option, a floating mascot with a visibly pulsing cyan waveform and expanding halo in the join card, a softly animated cyan aurora inspired by the visitor badge, three feature tiles, character visitor badge, mascot-accented join action, and full-width curved footer. The ambient waveform and halo slow down when reduced motion is enabled instead of disappearing. The voice-room skin uses the resting chibi illustration as the message-empty backdrop and places the main character illustration on the dedicated non-interactive artwork layer so it can rest over the edge of member cards or a live screen-share player without moving or blocking their controls.
|
||||
|
||||
This package intentionally omits `content.json`: the existing WebSpeak translations supply every label and message, including the current and total visitor counts. A skin may optionally add localized copy overrides, but missing locales and fields continue to use WebSpeak's base content. Its CSS is visual-only: WebSpeak retains its component positions, dimensions, text flow, and interactions. In the voice room, the main illustration and headset use separate, non-interactive foreground layers with restrained perspective and shadows; the chat's empty state includes a CSS-drawn speech-bubble ornament, while its translated copy remains visible. The footer wave is a pre-rendered transparent asset sampled from the example's original curve, so it decorates the existing footer instead of introducing another layout element.
|
||||
|
||||
The package source is in [`illusia-voice/`](illusia-voice/). To build it from the repository root:
|
||||
|
||||
```powershell
|
||||
Compress-Archive -Path .\docs\examples\illusia-voice\* -DestinationPath .\docs\examples\illusia-voice.zip -Force
|
||||
Rename-Item .\docs\examples\illusia-voice.zip illusia-voice.wskin -Force
|
||||
```
|
||||
|
||||
Use only artwork you have permission to redistribute when publishing a skin to other WebSpeak instances.
|
||||
|
After Width: | Height: | Size: 1014 KiB |
|
After Width: | Height: | Size: 365 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 358 KiB |
|
After Width: | Height: | Size: 738 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 85 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "community.illusia-voice",
|
||||
"name": "ILLUSIA风",
|
||||
"version": "1.0.27",
|
||||
"author": "WebSpeak Project",
|
||||
"license": "All rights reserved",
|
||||
"description": "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
"entry": "skin.css",
|
||||
"preview": "assets/background-composite.webp",
|
||||
"minAppVersion": "0.2.6"
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
/* ILLUSIA风: bright glass surfaces, cyan accents, and project artwork. */
|
||||
:root {
|
||||
--skin-illusia-ink: #123849;
|
||||
--skin-illusia-muted: #4f6974;
|
||||
--skin-illusia-teal: #087e86;
|
||||
--skin-illusia-aqua: #47c9d4;
|
||||
--skin-illusia-glass: rgba(250, 254, 255, .96);
|
||||
--skin-illusia-line: rgba(115, 205, 218, .38);
|
||||
--skin-illusia-shadow: 0 20px 56px rgba(29, 91, 113, .16);
|
||||
}
|
||||
|
||||
/* Homepage uses the full-resolution original-character composition. */
|
||||
[data-ws-part="home"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image:
|
||||
radial-gradient(ellipse at 14% 78%, rgba(90, 222, 230, .28), transparent 34%),
|
||||
radial-gradient(ellipse at 83% 21%, rgba(94, 190, 255, .24), transparent 30%),
|
||||
radial-gradient(ellipse at 52% 56%, rgba(190, 239, 255, .16), transparent 42%),
|
||||
linear-gradient(90deg, rgba(246, 252, 255, .91) 0%, rgba(246, 252, 255, .82) 33%, rgba(246, 252, 255, .32) 60%, rgba(246, 252, 255, .08) 100%),
|
||||
url("assets/background-composite.webp");
|
||||
background-position: 0% 100%, 100% 0%, 50% 50%, center, center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 132% 130%, 122% 124%, 116% 116%, cover, cover;
|
||||
animation: illusia-home-aura 18s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes illusia-home-aura {
|
||||
from { background-position: 0% 100%, 100% 0%, 50% 50%, center, center; }
|
||||
to { background-position: 20% 82%, 78% 18%, 55% 45%, center, center; }
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] {
|
||||
border-color: rgba(255, 255, 255, .85);
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, .8), rgba(255, 255, 255, .45));
|
||||
box-shadow: 0 26px 80px rgba(78, 150, 173, .17), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
backdrop-filter: blur(22px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .76);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .84);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.header"] [data-ws-part="control"]:hover {
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
/* ARIA selectors raise specificity over component defaults without private classes. */
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="skin.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .46);
|
||||
background-image: linear-gradient(112deg, rgba(255, 255, 255, .96), rgba(225, 250, 249, .96), rgba(188, 241, 237, .94), rgba(255, 255, 255, .96));
|
||||
background-position: 0% 50%;
|
||||
background-size: 240% 100%;
|
||||
box-shadow: 0 4px 14px rgba(30, 170, 184, .17), inset 0 0 0 1px rgba(255, 255, 255, .86);
|
||||
animation: illusia-option-gradient 8s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] > :first-child {
|
||||
color: #07858a;
|
||||
filter: drop-shadow(0 0 5px rgba(71, 201, 212, .54));
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"][aria-selected="true"] {
|
||||
color: #056e76;
|
||||
border-color: rgba(44, 186, 197, .7);
|
||||
background-image: linear-gradient(112deg, #faffff 0%, #c8f5f1 36%, #82e2dc 70%, #d9fbf8 100%);
|
||||
background-position: 100% 50%;
|
||||
box-shadow: 0 5px 18px rgba(30, 170, 184, .23), inset 0 0 0 1px rgba(255, 255, 255, .94);
|
||||
}
|
||||
|
||||
@keyframes illusia-option-gradient {
|
||||
from { background-position: 0% 50%; }
|
||||
to { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .82);
|
||||
border-radius: 999px;
|
||||
background: rgba(250, 254, 255, .86);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:hover,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"]:focus-visible,
|
||||
[data-ws-part="language.trigger"][aria-haspopup="listbox"][aria-expanded="true"][data-ws-state="open"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .52);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="language.menu"][role="listbox"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(104, 196, 211, .58);
|
||||
border-radius: 15px;
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(222, 246, 250, .96));
|
||||
box-shadow: 0 18px 42px rgba(29, 115, 139, .22), inset 0 1px 0 rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(18px) saturate(1.18);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 9px;
|
||||
background: rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="language.option"][role="option"]:hover,
|
||||
[data-ws-part="language.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="language.option"][role="option"][aria-selected="true"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="skin.option"][role="option"]:hover,
|
||||
[data-ws-part="skin.option"][role="option"]:focus-visible,
|
||||
[data-ws-part="skin.option"][role="option"][aria-selected="true"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .42);
|
||||
background: rgba(211, 245, 248, .92);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .82);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] strong,
|
||||
[data-ws-part="home.hero.title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.brand"] small,
|
||||
[data-ws-part="home.hero.description"],
|
||||
[data-ws-part="home.join-description"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.title"] em {
|
||||
color: var(--skin-illusia-teal);
|
||||
text-shadow: 0 8px 28px rgba(47, 192, 202, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.hero.eyebrow"] {
|
||||
color: #087a76;
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] {
|
||||
border-color: rgba(255, 255, 255, .94);
|
||||
border-radius: 18px;
|
||||
background: rgba(255, 255, 255, .79);
|
||||
box-shadow: 0 14px 28px rgba(68, 158, 173, .12), inset 0 0 0 1px rgba(255, 255, 255, .42);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] > span:first-child {
|
||||
box-shadow: 0 5px 14px rgba(43, 157, 167, .12), inset 0 0 0 1px rgba(255, 255, 255, .56);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] b {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.feature"] small {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] {
|
||||
color: #075c67;
|
||||
border-color: var(--skin-illusia-line);
|
||||
background-color: rgba(247, 254, 255, .9);
|
||||
background-image: linear-gradient(105deg, rgba(247, 254, 255, .98), rgba(237, 252, 253, .84));
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 10px 28px rgba(19, 142, 157, .14), inset 0 0 0 1px rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(14px) saturate(1.12);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) {
|
||||
color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/visitor-avatar.webp");
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
box-shadow: 0 0 0 3px rgba(71, 201, 212, .26), 0 5px 16px rgba(19, 142, 157, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:nth-child(2) svg {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="home.visitors"] > span:last-child {
|
||||
color: #41bdcc;
|
||||
text-shadow: 0 0 12px rgba(71, 201, 212, .42);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(255, 255, 255, .9);
|
||||
border-radius: 26px;
|
||||
background-color: var(--skin-illusia-glass);
|
||||
background-image: url("assets/banner-mascot-blob.webp");
|
||||
background-position: right 18px top 10px;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 96px 68px;
|
||||
box-shadow: var(--skin-illusia-shadow), 0 0 15px rgba(71, 201, 212, .14), inset 0 0 0 1px rgba(255, 255, 255, .84);
|
||||
backdrop-filter: blur(22px);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] {
|
||||
color: #47c9d4;
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.waveform"] i {
|
||||
box-shadow: 0 0 8px rgba(71, 201, 212, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] {
|
||||
color: rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-card.sonar"] i {
|
||||
box-shadow: 0 0 12px rgba(71, 201, 212, .16);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="skin.option"][data-ws-skin-id="community.illusia-voice"][role="option"] {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="home.join-title"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] {
|
||||
color: #4f6974;
|
||||
border-color: rgba(134, 190, 200, .42);
|
||||
border-radius: 12px;
|
||||
background: rgba(232, 244, 247, .96);
|
||||
box-shadow: inset 0 0 0 1px rgba(134, 190, 200, .24);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home.field"] input::placeholder {
|
||||
color: #8ba4aa;
|
||||
}
|
||||
|
||||
[data-ws-part="home.field-label"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"] {
|
||||
color: #fff;
|
||||
border-radius: 14px;
|
||||
background-color: var(--skin-illusia-teal);
|
||||
background:
|
||||
url("assets/button-mascot.webp") right 4px center / 112px 74px no-repeat,
|
||||
linear-gradient(100deg, #38d6d0 0%, #0c9caf 62%, #08788d 100%) center / cover no-repeat;
|
||||
box-shadow: 0 12px 22px rgba(16, 181, 192, .24), inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 0 0 1px rgba(141, 255, 255, .52);
|
||||
}
|
||||
|
||||
[data-ws-part="home"] [data-ws-part="home.connect"]:hover {
|
||||
background-color: #087078;
|
||||
box-shadow: 0 14px 30px rgba(8, 126, 134, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="home.security-note"],
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="home.footer"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: transparent;
|
||||
background-color: transparent;
|
||||
background-image: url("assets/footer-wave.png");
|
||||
background-position: center top;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 58px;
|
||||
box-shadow: none;
|
||||
backdrop-filter: blur(8px) saturate(1.04);
|
||||
}
|
||||
|
||||
/* Voice room: let the artwork flow through the UI instead of stacking opaque cards. */
|
||||
:root {
|
||||
--skin-room-line: rgba(76, 176, 193, .3);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.shell"] {
|
||||
color-scheme: light;
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #dff4f8;
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.55px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 188px, rgba(71, 201, 212, .13) 189px 190px, transparent 191px 229px, rgba(71, 201, 212, .09) 230px 231px, transparent 232px),
|
||||
radial-gradient(ellipse at 13% 5%, rgba(107, 226, 232, .2), transparent 36%),
|
||||
linear-gradient(125deg, rgba(229, 248, 251, .19), rgba(239, 251, 253, .06) 48%, rgba(190, 235, 242, .22)),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: 0 0, right top, left top, center, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, 560px 450px, auto, auto, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.workspace"] {
|
||||
background: linear-gradient(145deg, rgba(239, 251, 253, .22), rgba(218, 244, 248, .12) 48%, rgba(245, 253, 254, .2));
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
border-color: rgba(113, 211, 222, .62);
|
||||
border-radius: 24px;
|
||||
background-color: rgba(227, 247, 250, .64);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 82% 48%, rgba(91, 215, 224, .19), rgba(91, 215, 224, .04) 34%, transparent 65%),
|
||||
linear-gradient(90deg, rgba(230, 248, 251, .78), rgba(230, 248, 251, .36) 38%, rgba(230, 248, 251, .08) 72%),
|
||||
url("assets/bg-room-main.webp");
|
||||
background-position: right 5% center, center, center 48%;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 48% 100%, 100% 100%, cover;
|
||||
box-shadow: 0 15px 38px rgba(30, 111, 132, .13), inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
backdrop-filter: blur(10px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: url("assets/banner-character-main.webp");
|
||||
background-position: right 16px bottom 8px;
|
||||
background-size: auto 150px;
|
||||
filter: drop-shadow(0 18px 22px rgba(30, 113, 134, .2));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.header"] {
|
||||
border-color: rgba(126, 191, 203, .36);
|
||||
background: linear-gradient(105deg, rgba(249, 254, 255, .76), rgba(222, 246, 250, .57) 56%, rgba(247, 253, 254, .72));
|
||||
box-shadow: 0 8px 28px rgba(27, 92, 112, .08), inset 0 1px 0 rgba(255, 255, 255, .62);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: var(--skin-room-line);
|
||||
background-color: rgba(221, 245, 249, .66);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(25, 145, 161, .065) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 0%, transparent 0 86px, rgba(71, 201, 212, .16) 87px 88px, transparent 89px 119px, rgba(71, 201, 212, .1) 120px 121px, transparent 122px),
|
||||
radial-gradient(ellipse at 100% 0%, rgba(107, 226, 232, .2), transparent 43%),
|
||||
linear-gradient(155deg, rgba(248, 254, 255, .75), rgba(222, 246, 249, .58) 48%, rgba(213, 241, 246, .7));
|
||||
background-position: 0 0, right top, right top, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 360px 320px, auto, auto;
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
/* Keep the headset as an independent foreground object instead of flattening
|
||||
it into the member rail's background. Its slight perspective and shadow
|
||||
make it sit in front of the room, while the actual controls remain above it. */
|
||||
[data-ws-part="voice.member-panel"]::before {
|
||||
background-image: url("assets/foreground-headphone.webp");
|
||||
background-position: left bottom;
|
||||
background-repeat: no-repeat;
|
||||
background-size: contain;
|
||||
filter: drop-shadow(16px 18px 17px rgba(36, 105, 119, .24));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] {
|
||||
color: #4f7982;
|
||||
border-color: rgba(103, 186, 198, .28);
|
||||
background: linear-gradient(110deg, rgba(232, 249, 251, .86), rgba(216, 242, 247, .68));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .58);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-panel.search"] input::placeholder {
|
||||
color: #78979d;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"] {
|
||||
border-color: rgba(8, 126, 134, .32);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group"][data-ws-state="current"] {
|
||||
border-color: rgba(8, 126, 134, .48);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"] {
|
||||
color: #386b75;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(100deg, rgba(223, 246, 249, .68), rgba(237, 250, 251, .34));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.channel-group.heading"][data-ws-state="current"] {
|
||||
color: #087e86;
|
||||
background: linear-gradient(100deg, rgba(179, 235, 239, .78), rgba(224, 248, 249, .5));
|
||||
box-shadow: inset 3px 0 0 rgba(37, 175, 188, .74);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"] {
|
||||
border-radius: 11px;
|
||||
transition: background .16s ease, box-shadow .16s ease;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member-row"]:hover,
|
||||
[data-ws-part="voice.member-row"][data-ws-state="speaking"] {
|
||||
background: linear-gradient(100deg, rgba(198, 240, 243, .38), rgba(238, 251, 252, .28));
|
||||
box-shadow: inset 0 0 0 1px rgba(92, 190, 202, .16);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member"] {
|
||||
border-color: rgba(91, 184, 198, .36);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(222, 246, 249, .7);
|
||||
background-image:
|
||||
radial-gradient(ellipse at 100% 0%, rgba(102, 220, 226, .24), transparent 62%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .72), rgba(224, 246, 249, .62) 56%, rgba(210, 241, 246, .66));
|
||||
box-shadow: 0 12px 32px rgba(31, 99, 123, .12), inset 0 1px 0 rgba(255, 255, 255, .76);
|
||||
backdrop-filter: blur(12px) saturate(1.08);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .8);
|
||||
outline-offset: 4px;
|
||||
box-shadow: 0 0 24px rgba(71, 201, 212, .28);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.live-indicator"] {
|
||||
color: #08706f;
|
||||
border-radius: 999px;
|
||||
background: rgba(237, 255, 251, .96);
|
||||
box-shadow: 0 6px 20px rgba(42, 160, 162, .18), inset 0 0 0 1px rgba(71, 201, 212, .5);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(116, 194, 205, .42);
|
||||
border-radius: 22px;
|
||||
background-color: rgba(222, 246, 249, .8);
|
||||
background-image:
|
||||
radial-gradient(circle at 0% 100%, transparent 0 35px, rgba(71, 201, 212, .16) 36px 37px, transparent 38px 57px, rgba(71, 201, 212, .1) 58px 59px, transparent 60px),
|
||||
linear-gradient(125deg, rgba(250, 255, 255, .76), rgba(222, 246, 249, .68) 55%, rgba(205, 238, 244, .76));
|
||||
box-shadow: 0 12px 34px rgba(28, 91, 111, .16), inset 0 1px 0 rgba(255, 255, 255, .74);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat"] {
|
||||
border-color: rgba(100, 184, 198, .34);
|
||||
border-radius: 20px;
|
||||
background-color: rgba(221, 245, 249, .58);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .055) 1px, transparent 1.5px),
|
||||
radial-gradient(ellipse at 0% 100%, rgba(102, 220, 226, .16), transparent 42%),
|
||||
linear-gradient(145deg, rgba(249, 254, 255, .72), rgba(226, 247, 250, .48) 52%, rgba(214, 242, 247, .62));
|
||||
background-position: 0 0, left bottom, center;
|
||||
background-repeat: repeat, no-repeat, no-repeat;
|
||||
background-size: 24px 24px, auto, auto;
|
||||
backdrop-filter: blur(14px) saturate(1.05);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"] {
|
||||
color: #547780;
|
||||
border-color: rgba(95, 180, 193, .24);
|
||||
background: linear-gradient(115deg, rgba(242, 252, 253, .72), rgba(217, 243, 247, .56));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.tab"]:hover,
|
||||
[data-ws-part="voice.chat.tab"][data-ws-state="active"] {
|
||||
color: #087e86;
|
||||
border-color: rgba(71, 201, 212, .48);
|
||||
background: linear-gradient(115deg, rgba(207, 242, 245, .86), rgba(232, 250, 251, .72));
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .6);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .76), rgba(228, 247, 250, .38) 52%, rgba(205, 240, 245, .26)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 10px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
background-color: rgba(218, 244, 248, .4);
|
||||
background-image:
|
||||
radial-gradient(circle at 1px 1px, rgba(21, 139, 157, .075) 1px, transparent 1.5px),
|
||||
radial-gradient(circle at 100% 50%, transparent 0 102px, rgba(71, 201, 212, .13) 103px 104px, transparent 105px 137px, rgba(71, 201, 212, .09) 138px 139px, transparent 140px),
|
||||
linear-gradient(100deg, rgba(237, 250, 252, .68), rgba(228, 247, 250, .34) 50%, rgba(205, 240, 245, .08)),
|
||||
url("assets/chat-empty-chibi.webp");
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-repeat: repeat, no-repeat, no-repeat, no-repeat;
|
||||
background-size: 22px 22px, 300px 250px, cover, min(340px, 46vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::before {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
border-radius: 50%;
|
||||
background-color: rgba(250, 255, 255, .66);
|
||||
background-image:
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px),
|
||||
radial-gradient(circle, #527f91 0 1.6px, transparent 1.9px);
|
||||
background-position: 12px 16px, 22px 12px, 32px 9px;
|
||||
background-repeat: no-repeat;
|
||||
box-shadow: 0 3px 8px rgba(48, 115, 132, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"]::after {
|
||||
color: rgba(71, 126, 148, .9);
|
||||
background: rgba(250, 255, 255, .7);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > strong,
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] > span {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] {
|
||||
color: #587a82;
|
||||
border-color: rgba(78, 176, 191, .38);
|
||||
background: linear-gradient(120deg, rgba(223, 247, 249, .68), rgba(235, 250, 251, .42));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.members.empty"] strong {
|
||||
color: #315c66;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #315360;
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .78), rgba(216, 243, 247, .68));
|
||||
box-shadow: 0 4px 14px rgba(34, 117, 136, .08), inset 0 0 0 1px rgba(255, 255, 255, .54);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.message"][data-ws-state="mine"] [data-ws-part="voice.chat.message-bubble"] {
|
||||
color: #fff;
|
||||
background: linear-gradient(130deg, #0b9da1, #087985);
|
||||
box-shadow: 0 5px 16px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] h2,
|
||||
[data-ws-part="voice.chat.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity-heading"] span,
|
||||
[data-ws-part="voice.chat.heading"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.name"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
/* These controls use the active day/night palette by default. Give them the
|
||||
same readable glass treatment as the rest of this intentionally bright skin. */
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(249, 253, 255, .9);
|
||||
box-shadow: 0 5px 16px rgba(29, 91, 113, .1), inset 0 1px 0 rgba(255, 255, 255, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.performance"] > [data-ws-part="control"][aria-expanded="true"] {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .72);
|
||||
background: rgba(255, 255, 255, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .4);
|
||||
background-color: rgba(223, 246, 249, .96);
|
||||
background-image:
|
||||
radial-gradient(circle at 100% 0%, rgba(71, 201, 212, .16), transparent 52%),
|
||||
linear-gradient(145deg, rgba(250, 255, 255, .96), rgba(224, 246, 249, .94));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] small,
|
||||
[data-ws-part="voice.performance.status"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.panel"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .36);
|
||||
background: rgba(232, 247, 248, .9);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.route"] span,
|
||||
[data-ws-part="voice.performance.metrics"] article,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
border-color: rgba(115, 205, 218, .28);
|
||||
background: linear-gradient(135deg, rgba(232, 248, 250, .88), rgba(212, 241, 245, .72));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] strong,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.performance.metrics"] small,
|
||||
[data-ws-part="voice.performance.metrics"] span,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] small,
|
||||
[data-ws-part="voice.performance.webrtc-stats"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] span {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.audio-dock"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #075f69;
|
||||
border-color: rgba(71, 201, 212, .4);
|
||||
background: rgba(221, 246, 247, .86);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"],
|
||||
[data-ws-part="voice.audio-dock.output-panel"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: linear-gradient(145deg, rgba(250, 255, 255, .98), rgba(221, 246, 249, .96));
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.audio-dock.microphone-panel"] strong,
|
||||
[data-ws-part="voice.audio-dock.output-panel"] strong {
|
||||
color: var(--skin-illusia-teal);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] {
|
||||
background: linear-gradient(110deg, rgba(249, 254, 255, .82), rgba(225, 247, 250, .76) 58%, rgba(214, 242, 247, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(115, 205, 218, .32), 0 5px 18px rgba(36, 130, 148, .07);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"]:focus-within {
|
||||
background: linear-gradient(110deg, rgba(250, 255, 255, .9), rgba(211, 242, 246, .82));
|
||||
box-shadow: inset 0 0 0 1px rgba(71, 201, 212, .55), 0 6px 20px rgba(36, 130, 148, .11);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] input::placeholder {
|
||||
color: #718b92;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.composer"] button[data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .18);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
box-shadow: 0 5px 13px rgba(8, 126, 134, .2);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"] {
|
||||
color: #086b72;
|
||||
border-color: rgba(71, 201, 212, .45);
|
||||
background: rgba(237, 252, 251, .96);
|
||||
box-shadow: 0 3px 10px rgba(29, 120, 130, .12);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:hover,
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"]:focus-visible {
|
||||
color: #064f59;
|
||||
border-color: rgba(8, 126, 134, .58);
|
||||
background: rgba(219, 247, 246, .98);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.share-actions"] button[data-ws-part="control"][data-ws-state="viewing"] {
|
||||
color: #fff;
|
||||
border-color: #087e86;
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.member.stop-share"] {
|
||||
color: #a43e48;
|
||||
border-color: rgba(255, 255, 255, .96);
|
||||
background: #fff6f5;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(250, 254, 255, .98);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] h2 {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.heading"] p,
|
||||
[data-ws-part="voice.screen-share-settings.fields"] label,
|
||||
[data-ws-part="voice.screen-share-settings.note"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] select {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .42);
|
||||
background: rgba(235, 247, 248, .94);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings"] [data-ws-part="control"] {
|
||||
color: var(--skin-illusia-teal);
|
||||
border-color: rgba(115, 205, 218, .38);
|
||||
background: rgba(232, 247, 248, .92);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-share-settings.actions"] [data-ws-part="control"] {
|
||||
color: #fff;
|
||||
border-color: rgba(8, 126, 134, .2);
|
||||
background: linear-gradient(135deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
[data-ws-part="voice.chat.empty"] {
|
||||
background-position: 0 0, right 8px center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-position: right 1% center, center, center 48%;
|
||||
background-size: 56% 100%, 100% 100%, cover;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-position: right 12px bottom 6px;
|
||||
background-size: auto 118px;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.chat.empty"][data-ws-state="messages-empty"] {
|
||||
background-position: 0 0, right center, center, center 8px;
|
||||
background-size: 22px 22px, 260px 220px, cover, min(300px, 66vw) auto;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-part="voice.activity"] {
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.activity.artwork"] {
|
||||
background-image: none;
|
||||
}
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player"] {
|
||||
border-radius: 24px;
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: linear-gradient(135deg, rgba(250, 255, 255, .96), rgba(220, 245, 250, .94));
|
||||
box-shadow: 0 22px 60px rgba(10, 68, 88, .3), inset 0 0 0 1px rgba(185, 246, 249, .55);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.stage"] {
|
||||
border-radius: 22px;
|
||||
background: radial-gradient(ellipse at 50% 38%, rgba(248, 255, 255, .98), rgba(220, 246, 250, .92) 58%, rgba(202, 237, 244, .9));
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.video"] {
|
||||
background: #e5f4f8;
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] {
|
||||
color: var(--skin-illusia-muted);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.placeholder"] strong {
|
||||
color: var(--skin-illusia-ink);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.exit"],
|
||||
[data-ws-part="voice.screen-player.fullscreen"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .62);
|
||||
background: rgba(250, 255, 255, .9);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .18);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewers"],
|
||||
[data-ws-part="voice.screen-player.volume"],
|
||||
[data-ws-part="voice.screen-player.source"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-color: rgba(115, 205, 218, .58);
|
||||
background: rgba(250, 255, 255, .88);
|
||||
box-shadow: 0 5px 18px rgba(40, 126, 148, .16);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
border-color: rgba(250, 255, 255, .96);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.live"] {
|
||||
border-radius: 999px;
|
||||
color: #075e68;
|
||||
border-color: rgba(82, 195, 204, .56);
|
||||
background: rgba(239, 253, 254, .94);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .76), 0 5px 18px rgba(40, 126, 148, .16);
|
||||
text-shadow: none;
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
|
||||
[data-ws-part="voice.screen-player.viewer-avatar"] {
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, .94), 0 0 0 4px rgba(71, 201, 212, .72);
|
||||
}
|
||||
|
||||
/* The demo keeps its original controls, labels, and interactions. */
|
||||
[data-ws-page="demo"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
background-color: #eaf7fc;
|
||||
background-image: url("assets/foreground-headphone.webp"), linear-gradient(rgba(239, 250, 253, .7), rgba(239, 250, 253, .82)), url("assets/bg-room-main.webp");
|
||||
background-position: left bottom, center, center;
|
||||
background-repeat: no-repeat, no-repeat, no-repeat;
|
||||
background-size: min(34vw, 430px) auto, auto, cover;
|
||||
background-attachment: fixed, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.header"] {
|
||||
border-color: rgba(126, 191, 203, .3);
|
||||
background: rgba(250, 254, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.channels"],
|
||||
[data-ws-part="demo.actions"],
|
||||
[data-ws-part="demo.main"] {
|
||||
border-color: rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(249, 253, 255, .84);
|
||||
box-shadow: var(--skin-illusia-shadow);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
color: var(--skin-illusia-ink);
|
||||
border-radius: 22px;
|
||||
background-color: #d7f3f7;
|
||||
background-image: linear-gradient(90deg, rgba(239, 251, 254, .94), rgba(227, 248, 251, .48)), url("assets/banner-character-main.webp"), url("assets/banner-mascot-blob.webp");
|
||||
background-position: center, right 46px bottom, right 16px center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover, auto 112%, auto 72%;
|
||||
box-shadow: 0 14px 38px rgba(31, 99, 123, .12), inset 0 0 0 1px rgba(255, 255, 255, .8);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
border-color: rgba(115, 205, 218, .35);
|
||||
border-radius: 19px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
box-shadow: 0 10px 28px rgba(31, 99, 123, .1);
|
||||
}
|
||||
|
||||
[data-ws-part="demo.avatar"] {
|
||||
outline: 2px solid rgba(71, 201, 212, .7);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.chat.send"] {
|
||||
color: #fff;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(110deg, #0a9291, #087580);
|
||||
}
|
||||
|
||||
@media (max-width: 740px) {
|
||||
[data-ws-page="demo"] {
|
||||
background-size: min(62vw, 300px) auto, auto, cover;
|
||||
background-attachment: scroll, scroll, scroll;
|
||||
}
|
||||
|
||||
[data-ws-part="demo.hero"] {
|
||||
background-position: center, right center;
|
||||
background-size: cover, auto 65%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-ws-part="home"] {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
[data-ws-part="home.connect"],
|
||||
[data-ws-part="voice.member"],
|
||||
[data-ws-part="demo.voice-card"] {
|
||||
transition-duration: .01ms;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# WebSpeak 0.2.6
|
||||
|
||||
本版本相对于 [0.2.5 正式版](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.2.5) 更新。
|
||||
|
||||
## 问题修复与功能
|
||||
|
||||
- **已修复 [#10](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/10)**:Docker/Compose 环境下短主机名的本地 DNS 解析回退;云端昵称发现加入超时和直接连接回退,避免外部发现服务不可用时阻塞连接。HTTPS 部署的健康检查也会根据证书配置选择 HTTPS。
|
||||
- **已实现 [#9](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/9)**:导入 TeamSpeak 3 身份 INI 或身份字符串、导出 WebSpeak/TeamSpeak 兼容身份,并在本地校验格式和密钥一致性。
|
||||
- **已修复 [#6](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/6)**:静音同步遇到服务端频率限制时有限重试;会话切换或重连后,旧请求不会覆盖当前麦克风状态。
|
||||
- **已修复 [#7](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/7)**:TS6 屏幕共享清理等待服务器确认,携带清理原因并对频率限制有限重试,避免本地提前显示清理成功。
|
||||
- **已实现 [#12](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/issues/12) 请求的配置入口**:管理员可设置公网媒体地址、IPv6 候选和语音 STUN,以适配反向代理或 TCP 隧道后的 UDP 媒体路径。直接媒体仍要求 UDP 可达,STUN 不提供中继。
|
||||
- 修复 [PR #13](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/pull/13) 所报告的问题:新 WebSpeak 会话会发现已经开始的 TS6 原生屏幕共享,并将发现过程按服务器协调。PR 本身没有合并。
|
||||
- 改善语音稳定性:隔离重连前后的音频帧、播放回调、目录事件和性能统计;保留连续 Opus 编码状态,只协商受支持的音频参数;切换麦克风或伴奏设置时尽量保留正在工作的采集链路。
|
||||
- 改善移动端布局和语音控制,增加语音会话期间的屏幕常亮行为;梳理管理后台状态请求和语音工作区组件边界。
|
||||
|
||||
## 发布包与架构
|
||||
|
||||
- Windows:`windows-x64.zip`。
|
||||
- Linux:`linux-x64.tar.gz`、`linux-arm64.tar.gz`。
|
||||
- Docker:同一镜像标签提供 `linux/amd64` 和 `linux/arm64`。
|
||||
- Android:分别提供 `arm64-v8a`、`armeabi-v7a`、`x86_64` APK。APK 使用 Android debug 签名,适合手动安装和测试,不是 Google Play 发布包。Android 端的真实 TeamSpeak 连接、双向语音和后台行为仍需真机验收。
|
||||
- `SHA256SUMS.txt` 列出本次附件的 SHA-256,可用于下载后校验。
|
||||
|
||||
## 验证
|
||||
|
||||
发布流程运行完整自动化测试和前后端构建;Windows x64、Linux x64/ARM64 发布包均启动内置健康检查,Android 流程构建三种 ABI 的 APK。Windows ARM64 未纳入本次发布:当前 `@discordjs/opus` 上游只声明支持 Windows x64,ARM64 源码构建在 MSVC 下失败。自动化构建成功不等于真实 TeamSpeak 服务器或 Android 真机媒体链路已经验收。
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,48 @@
|
||||
# Android client
|
||||
|
||||
The Android app packages the Vue client with a small local gateway. Capacitor starts the embedded Node.js runtime, the gateway listens on `127.0.0.1:3040`, and the WebView opens that local address. The gateway is loopback-only; it does not expose an HTTP listener to the LAN. Release APKs are debug-signed sideload packages, not Google Play builds.
|
||||
|
||||
## Build on Windows
|
||||
|
||||
Use a short checkout path such as `C:\src\webspeak`. The Node.js plugin's CMake/Ninja object paths can exceed the Windows toolchain limit in deeply nested workspaces. A clean build in a nested validation directory failed with CMake's 250-character object-path warning and a Ninja `mkdir` error; the same source and dependencies built successfully from a shorter path. Changing application code or the embedded runtime is not required for this build-host issue.
|
||||
|
||||
Use the server development Node.js version (22.5 or newer) on the build host. Install all three dependency sets, then prepare and sync the Android project:
|
||||
|
||||
```powershell
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
npm --prefix mobile ci --no-audit --no-fund
|
||||
npm run android:sync
|
||||
```
|
||||
|
||||
Build the debug APKs with Android Studio's JDK and the checked-in Gradle wrapper:
|
||||
|
||||
```powershell
|
||||
$env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr"
|
||||
$env:ANDROID_HOME = "$env:LOCALAPPDATA\Android\Sdk"
|
||||
Set-Location web\android
|
||||
.\gradlew.bat assembleDebug
|
||||
```
|
||||
|
||||
Gradle writes one APK per supported CPU architecture under `web/android/app/build/outputs/apk/debug/`: `arm64-v8a`, `armeabi-v7a`, and `x86_64`. Use `arm64-v8a` for most modern Android phones and `x86_64` for the Android emulator. GitHub Releases contains all three APKs with versioned filenames.
|
||||
|
||||
## Current scope
|
||||
|
||||
- Platform startup is isolated in `web/src/platform/`. Ordinary browser sessions mount directly; the native shell loads the Node.js plugin only while waiting for its loopback gateway. Startup errors, timeouts and page exit release polling and message listeners. Retry repeats the readiness handshake without restarting the embedded Node.js runtime.
|
||||
- The local gateway serves the join page, public configuration, skin package, join-ticket endpoint, and voice WebSocket bridge.
|
||||
- The admin console and server-side skin management are not available in the Android package.
|
||||
- Mobile audio encoding uses the JavaScript/WASM Opus codec. The normal server build continues to use the native Opus codec.
|
||||
- The embedded runtime supplied by the current Capacitor Node.js plugin is Node.js 18.20.4. The gateway, identity parsing, and Opus encode/decode paths have been smoke-checked on that runtime. The TeamSpeak SDK declares Node.js 20.19 or newer, so real TeamSpeak connectivity and two-way audio remain unverified on Android; the APKs are for sideload testing.
|
||||
- Android WebView on the tested emulator does not expose `getDisplayMedia`; screen sharing needs a native MediaProjection integration. A persistent Android foreground service and real-device background audio behavior also remain to be implemented and verified.
|
||||
|
||||
## Recorded validation
|
||||
|
||||
On October 1, 2026, the platform startup tests passed as part of 118 application tests. Backend compilation, frontend type checking, Vite production build, asset packaging, Capacitor sync and `assembleDebug` passed. Gradle produced arm64-v8a, armeabi-v7a and x86_64 debug APKs.
|
||||
|
||||
The x86_64 APK installed and cold-started in a read-only Android 15 emulator. The embedded gateway returned `webspeak-android` from `/health` and `mobile: true` from `/api/public-config`; a screenshot confirmed that the WebView reached the join homepage. The narrow header was subsequently corrected and checked in desktop responsive viewports. The clean rebuild below includes those changes; its installation and startup were checked on October 2, while Android layout checks remain pending. The earlier emulator check covers startup and rendering only; real TeamSpeak connectivity, two-way audio and physical-device behavior remain unverified.
|
||||
|
||||
Later on October 1, commit `662dad36fc4d8cf9f35268a99b8221851f6fc52c` was exported with `git archive` into a fresh short directory. All three dependency sets were installed again from their lock files, and the pinned TeamSpeak SDK was rebuilt. `android:sync` and `assembleDebug --no-daemon` passed using Windows x64, Node.js 24.12.0, Android Studio JDK 25.0.2, Gradle 9.5.0 and Android SDK 36. All 134 Gradle tasks executed. The three ABI-specific APKs contain the gateway entry, SDK bundle, Opus WASM, frontend and matching native Node.js libraries; their manifest reports version `0.2.5-preview` / code `25`, minimum SDK 24 and target SDK 36. Artifact hashes are recorded in `docs/LOCAL_ARTIFACTS.zh-CN.md`. This was a debug build check, not a signed release or a new device/media test.
|
||||
|
||||
On October 2, the same clean x86_64 APK was installed in a read-only Android 15 emulator after rechecking its SHA-256. Installation succeeded and the package manager confirmed version `0.2.5-preview` / code `25`. A cold start of `io.webspeak.client/.MainActivity` completed in 1,822 ms. An ADB-forwarded HTTP check reached the embedded gateway: `/health` returned `status: ok` and `engine: webspeak-android`, while `/api/public-config` reported the expected version and `mobile: true`. The forwarding and emulator were then closed without saving a snapshot. This check did not exercise WebView layout, touch input, real TeamSpeak connectivity or audio.
|
||||
@@ -0,0 +1,33 @@
|
||||
const path = require("node:path");
|
||||
const os = require("node:os");
|
||||
let app;
|
||||
let channel;
|
||||
try {
|
||||
({ app, channel } = require("bridge"));
|
||||
} catch (error) {
|
||||
if (error.code !== "MODULE_NOT_FOUND") throw error;
|
||||
app = { datadir: () => path.join(os.tmpdir(), "webspeak-android-gateway-dev") };
|
||||
channel = { on: () => {}, post: () => {} };
|
||||
}
|
||||
|
||||
process.env.WEBSPEAK_MOBILE = "1";
|
||||
process.env.WEBSPEAK_DATA_DIR = app.datadir();
|
||||
process.env.WEBSPEAK_MOBILE_WWW = path.join(__dirname, "www");
|
||||
process.env.WEBSPEAK_VERSION = require("./package.json").version;
|
||||
|
||||
let gatewayReady = false;
|
||||
const gatewayPort = Number(process.env.WEBSPEAK_MOBILE_PORT || 3040);
|
||||
channel.on("webspeak-health", () => {
|
||||
channel.post("webspeak-health", { ready: gatewayReady, port: gatewayPort });
|
||||
});
|
||||
|
||||
import("./dist/mobile/index.js")
|
||||
.then(() => {
|
||||
gatewayReady = true;
|
||||
channel.post("webspeak-health", { ready: true, port: gatewayPort });
|
||||
})
|
||||
.catch((error) => {
|
||||
const message = error instanceof Error ? error.stack || error.message : String(error);
|
||||
console.error("WebSpeak mobile gateway failed:", message);
|
||||
channel.post("webspeak-error", { message });
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { cp, mkdir, readdir, copyFile, stat, readFile, writeFile, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const mobileDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = path.resolve(mobileDir, "..");
|
||||
const webDist = path.join(rootDir, "web", "dist");
|
||||
const outputDir = path.join(webDist, "nodejs");
|
||||
|
||||
for (const required of [path.join(rootDir, "dist", "mobile", "index.js"), path.join(mobileDir, "node_modules"), path.join(webDist, "index.html")]) {
|
||||
if (!(await stat(required).catch(() => null))) throw new Error(`Missing Android build input: ${required}`);
|
||||
}
|
||||
|
||||
await rm(outputDir, { recursive: true, force: true });
|
||||
await mkdir(path.join(outputDir, "www"), { recursive: true });
|
||||
await cp(path.join(rootDir, "dist"), path.join(outputDir, "dist"), { recursive: true, force: true });
|
||||
await cp(path.join(mobileDir, "node_modules"), path.join(outputDir, "node_modules"), { recursive: true, force: true });
|
||||
await copyFile(path.join(mobileDir, "index.cjs"), path.join(outputDir, "index.cjs"));
|
||||
const appPackage = JSON.parse(await readFile(path.join(rootDir, "package.json"), "utf8"));
|
||||
const mobilePackage = JSON.parse(await readFile(path.join(mobileDir, "package.json"), "utf8"));
|
||||
mobilePackage.version = appPackage.version;
|
||||
await writeFile(path.join(outputDir, "package.json"), `${JSON.stringify(mobilePackage, null, 2)}\n`);
|
||||
|
||||
for (const entry of await readdir(webDist, { withFileTypes: true })) {
|
||||
if (entry.name === "nodejs") continue;
|
||||
await cp(path.join(webDist, entry.name), path.join(outputDir, "www", entry.name), { recursive: entry.isDirectory(), force: true });
|
||||
}
|
||||
|
||||
console.log(`Android gateway assets prepared at ${outputDir}`);
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
"dependencies": {
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^4.21.2",
|
||||
"opusscript": "^0.1.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,35 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.6",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"description": "Server-side browser gateway for TeamSpeak — deploy on your server, users join from any browser",
|
||||
"engines": {
|
||||
"node": ">=22.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/member-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"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": "npm --prefix web run build",
|
||||
"android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs",
|
||||
"android:sync": "npm run android:prepare && cd web && npx cap sync android",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs",
|
||||
"acceleration:poc": "node scripts/acceleration-poc/smoke.mjs",
|
||||
"acceleration:ipv6-smoke": "node scripts/acceleration-poc/smoke-ipv6.mjs",
|
||||
"acceleration:sdk-smoke": "node scripts/acceleration-poc/sdk-smoke.mjs",
|
||||
"acceleration:relay": "node dist/relay.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.2",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#56d426d24852c39439f7bfe1d5850b574a1b0811",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -26,5 +38,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"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
# WebSpeak 加速通道 PoC
|
||||
|
||||
这是第一版隔离测试 Demo,不属于 WebSpeak 生产运行链路,也不会被复制到 Docker 镜像或发布包中。
|
||||
|
||||
它验证以下核心能力:
|
||||
|
||||
- 客户端向远端中继发起认证;
|
||||
- 每个会话动态指定 TeamSpeak 目标地址;
|
||||
- 双向 UDP 数据报转发,并保持数据包边界;
|
||||
- 会话之间按随机 ID 隔离;
|
||||
- 错误密钥不能建立会话;
|
||||
- 不修改系统路由,因此不是 VPN。
|
||||
|
||||
## 本地冒烟
|
||||
|
||||
在仓库根目录运行:
|
||||
|
||||
```bash
|
||||
npm run acceleration:poc
|
||||
```
|
||||
|
||||
成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。
|
||||
|
||||
IPv6 回环验证:
|
||||
|
||||
```bash
|
||||
npm run acceleration:ipv6-smoke
|
||||
```
|
||||
|
||||
## 通过隧道连接指定 TeamSpeak
|
||||
|
||||
必须先将下方示例域名替换为你获准测试的 TeamSpeak 地址;脚本不内置真实服务器默认值。下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
|
||||
|
||||
```bash
|
||||
$env:WEBSPEAK_ACCEL_TS_TARGET="ts.example.invalid#9987"
|
||||
npm run acceleration:sdk-smoke
|
||||
```
|
||||
|
||||
跨机器验证时,需要在目标服务器启动 `relay-server.mjs`,再把 `WEBSPEAK_ACCEL_RELAY` 指向中继地址。当前项目不会自动部署或启动该远程进程。
|
||||
|
||||
## 手动启动中继
|
||||
|
||||
仅用于实验,不要直接暴露到公网:
|
||||
|
||||
```bash
|
||||
WEBSPEAK_ACCEL_TOKEN="change-this-to-a-long-random-token" \
|
||||
WEBSPEAK_ACCEL_HOST="0.0.0.0" \
|
||||
WEBSPEAK_ACCEL_PORT="39087" \
|
||||
node scripts/acceleration-poc/relay-server.mjs
|
||||
```
|
||||
|
||||
当前 Demo 的 UDP 帧协议是实验协议,尚未接入 SDK,也没有替代 GOST 的生产安全审计。正式接入前仍需验证 TeamSpeak 长时间语音、并发会话、IPv6、断线重连和目标地址安全策略。
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export const VERSION = 1;
|
||||
export const HEADER_SIZE = 34;
|
||||
export const MAX_PAYLOAD_SIZE = 60_000;
|
||||
|
||||
export const FrameType = Object.freeze({
|
||||
OPEN: 1,
|
||||
OPEN_OK: 2,
|
||||
OPEN_ERR: 3,
|
||||
DATA: 4,
|
||||
CLOSE: 5,
|
||||
PING: 6,
|
||||
PONG: 7,
|
||||
});
|
||||
|
||||
function asSecret(secret) {
|
||||
if (typeof secret !== "string" || secret.length < 16) {
|
||||
throw new Error("The PoC token must contain at least 16 characters");
|
||||
}
|
||||
return Buffer.from(secret, "utf8");
|
||||
}
|
||||
|
||||
function signFrame(frame, secret, payload) {
|
||||
return createHmac("sha256", asSecret(secret))
|
||||
.update(frame.subarray(0, 18))
|
||||
.update(payload)
|
||||
.digest()
|
||||
.subarray(0, 16);
|
||||
}
|
||||
|
||||
export function encodeFrame(type, sessionId, sequence, payload = Buffer.alloc(0), secret) {
|
||||
const body = Buffer.from(payload);
|
||||
if (!Number.isInteger(type) || type < 1 || type > 255) throw new Error("Invalid frame type");
|
||||
if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > 0xffffffff) throw new Error("Invalid session id");
|
||||
if (!Number.isInteger(sequence) || sequence < 0 || sequence > 0xffffffff) throw new Error("Invalid sequence");
|
||||
if (body.length > MAX_PAYLOAD_SIZE) throw new Error(`Payload exceeds ${MAX_PAYLOAD_SIZE} bytes`);
|
||||
|
||||
const frame = Buffer.alloc(HEADER_SIZE + body.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt16BE(0, 6);
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(body.length, 16);
|
||||
body.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, secret, body).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
export function decodeFrame(packet) {
|
||||
const frame = Buffer.from(packet);
|
||||
if (frame.length < HEADER_SIZE || !frame.subarray(0, 4).equals(MAGIC)) return null;
|
||||
if (frame[4] !== VERSION) return null;
|
||||
const payloadLength = frame.readUInt16BE(16);
|
||||
if (frame.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return {
|
||||
type: frame[5],
|
||||
sessionId: frame.readUInt32BE(8),
|
||||
sequence: frame.readUInt32BE(12),
|
||||
payload: frame.subarray(HEADER_SIZE),
|
||||
auth: frame.subarray(18, HEADER_SIZE),
|
||||
raw: frame,
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyFrame(frame, secret) {
|
||||
const expected = signFrame(frame.raw, secret, frame.payload);
|
||||
return timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
export function randomSessionId() {
|
||||
let id = randomBytes(4).readUInt32BE(0);
|
||||
if (id === 0) id = 1;
|
||||
return id;
|
||||
}
|
||||
|
||||
export function jsonPayload(value) {
|
||||
return Buffer.from(JSON.stringify(value), "utf8");
|
||||
}
|
||||
|
||||
export function parseJsonPayload(payload) {
|
||||
try {
|
||||
return JSON.parse(Buffer.from(payload).toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseEndpoint(value, defaultPort) {
|
||||
if (typeof value !== "string" || !value.trim()) throw new Error("Endpoint is required");
|
||||
const text = value.trim();
|
||||
if (text.startsWith("[")) {
|
||||
const end = text.indexOf("]");
|
||||
if (end < 0) throw new Error(`Invalid endpoint: ${value}`);
|
||||
const host = text.slice(1, end);
|
||||
const portText = text.slice(end + 1).replace(/^[:#]/, "");
|
||||
return { host, port: parsePort(portText || defaultPort, value) };
|
||||
}
|
||||
const hash = text.lastIndexOf("#");
|
||||
if (hash > 0) return { host: text.slice(0, hash), port: parsePort(text.slice(hash + 1), value) };
|
||||
const colon = text.lastIndexOf(":");
|
||||
if (colon > 0 && text.indexOf(":") === colon) {
|
||||
return { host: text.slice(0, colon), port: parsePort(text.slice(colon + 1), value) };
|
||||
}
|
||||
return { host: text, port: parsePort(defaultPort, value) };
|
||||
}
|
||||
|
||||
function parsePort(value, original) {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid port in endpoint: ${original}`);
|
||||
return port;
|
||||
}
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, randomSessionId, parseEndpoint, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
export async function createRelayClient({
|
||||
relayHost,
|
||||
relayPort,
|
||||
targetHost,
|
||||
targetPort,
|
||||
token,
|
||||
localHost = "127.0.0.1",
|
||||
localPort = 0,
|
||||
timeoutMs = 5_000,
|
||||
} = {}) {
|
||||
if (!relayHost || !Number.isInteger(relayPort)) throw new Error("Relay endpoint is required");
|
||||
if (!targetHost || !Number.isInteger(targetPort)) throw new Error("Target endpoint is required");
|
||||
const relayFamily = isIP(relayHost) === 6 ? "udp6" : "udp4";
|
||||
const localFamily = isIP(localHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket(localFamily);
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let peer = null;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady;
|
||||
let rejectReady;
|
||||
const readyPromise = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
|
||||
function sendFrame(type, payload = Buffer.alloc(0)) {
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, token);
|
||||
relaySocket.send(packet, relayPort, relayHost);
|
||||
}
|
||||
|
||||
function closeSockets() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
try { relaySocket.close(); } catch {}
|
||||
try { localSocket.close(); } catch {}
|
||||
}
|
||||
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
ready = true;
|
||||
resolveReady();
|
||||
} else if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = (() => { try { return JSON.parse(frame.payload.toString("utf8")); } catch { return {}; } })();
|
||||
rejectReady(new Error(detail.code ?? "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
} else if (frame.type === FrameType.DATA && peer) {
|
||||
localSocket.send(frame.payload, peer.port, peer.address);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
closeSockets();
|
||||
}
|
||||
});
|
||||
|
||||
const onSocketError = (error) => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
await Promise.all([
|
||||
new Promise((resolve) => relaySocket.bind(0, relayFamily === "udp6" ? "::" : "0.0.0.0", resolve)),
|
||||
new Promise((resolve) => localSocket.bind(localPort, localHost, resolve)),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, timeoutMs);
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost, targetPort }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const localAddress = localSocket.address();
|
||||
return {
|
||||
sessionId,
|
||||
localHost,
|
||||
localPort: typeof localAddress === "object" ? localAddress.port : localPort,
|
||||
waitReady: () => readyPromise,
|
||||
close() {
|
||||
if (closed) return;
|
||||
if (ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch {}
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parseRelayEndpoint(value) {
|
||||
return parseEndpoint(value, 39087);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { decodeFrame, encodeFrame, FrameType, jsonPayload, parseJsonPayload, verifyFrame } from "./protocol.mjs";
|
||||
|
||||
function endpointKey(address, port) {
|
||||
return `${address}/${port}`;
|
||||
}
|
||||
|
||||
function isPrivateAddress(host) {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const octets = host.split(".").map(Number);
|
||||
return octets[0] === 10
|
||||
|| (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31)
|
||||
|| octets[0] === 192 && octets[1] === 168
|
||||
|| octets[0] === 127
|
||||
|| octets[0] === 169 && octets[1] === 254
|
||||
|| octets[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLowerCase();
|
||||
return normalized === "::1"
|
||||
|| normalized === "::"
|
||||
|| normalized.startsWith("fc")
|
||||
|| normalized.startsWith("fd")
|
||||
|| normalized.startsWith("fe8")
|
||||
|| normalized.startsWith("fe9")
|
||||
|| normalized.startsWith("fea")
|
||||
|| normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host) {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
export async function createRelayServer({
|
||||
host = "127.0.0.1",
|
||||
port = 0,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
} = {}) {
|
||||
const serverFamily = isIP(host) === 6 ? "udp6" : "udp4";
|
||||
const socket = createSocket(serverFamily);
|
||||
const sessions = new Map();
|
||||
let closed = false;
|
||||
|
||||
function sendToClient(session, type, payload = Buffer.alloc(0)) {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, session.id, session.outSequence++, payload, token);
|
||||
socket.send(packet, session.client.port, session.client.address);
|
||||
}
|
||||
|
||||
function cleanup(session) {
|
||||
if (!session || session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
}
|
||||
|
||||
async function openSession(frame, client) {
|
||||
const request = parseJsonPayload(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) {
|
||||
return;
|
||||
}
|
||||
if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) {
|
||||
const error = { code: "PRIVATE_TARGET_BLOCKED" };
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = sessions.get(frame.sessionId);
|
||||
if (existing) cleanup(existing);
|
||||
const session = {
|
||||
id: frame.sessionId,
|
||||
client,
|
||||
clientKey: endpointKey(client.address, client.port),
|
||||
outSequence: 1,
|
||||
lastActivity: Date.now(),
|
||||
targetSocket: null,
|
||||
closed: false,
|
||||
};
|
||||
sessions.set(session.id, session);
|
||||
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.DATA, payload);
|
||||
});
|
||||
targetSocket.on("error", (error) => {
|
||||
if (!session.closed) sendToClient(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message }));
|
||||
cleanup(session);
|
||||
});
|
||||
targetSocket.connect(request.targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
sendToClient(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort: request.targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: error.message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openSession(frame, client);
|
||||
return;
|
||||
}
|
||||
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.clientKey !== endpointKey(rinfo.address, rinfo.port)) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) {
|
||||
session.targetSocket.send(frame.payload);
|
||||
} else if (frame.type === FrameType.CLOSE) {
|
||||
sendToClient(session, FrameType.CLOSE);
|
||||
cleanup(session);
|
||||
} else if (frame.type === FrameType.PING) {
|
||||
sendToClient(session, FrameType.PONG);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) {
|
||||
if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const onError = (error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
family: serverFamily,
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]?.replaceAll("\\", "/")}`) {
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN;
|
||||
if (!token) throw new Error("Set WEBSPEAK_ACCEL_TOKEN before starting the PoC relay");
|
||||
const host = process.env.WEBSPEAK_ACCEL_HOST ?? "0.0.0.0";
|
||||
const port = Number(process.env.WEBSPEAK_ACCEL_PORT ?? 39087);
|
||||
const server = await createRelayServer({ host, port, token });
|
||||
console.log(`ACCELERATION_RELAY_LISTEN ${server.host}:${server.port}`);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Client, generateIdentity } from "../../../teamspeak-js/dist/index.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { parseEndpoint } from "./protocol.mjs";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCEL_TOKEN ?? "local-acceleration-poc-token";
|
||||
const targetAddress = process.env.WEBSPEAK_ACCEL_TS_TARGET;
|
||||
if (!targetAddress?.trim()) {
|
||||
throw new Error("Set WEBSPEAK_ACCEL_TS_TARGET to your authorized TeamSpeak test endpoint");
|
||||
}
|
||||
const target = parseEndpoint(targetAddress, 9987);
|
||||
const relayEndpoint = process.env.WEBSPEAK_ACCEL_RELAY;
|
||||
let relayServer = null;
|
||||
let relayClient = null;
|
||||
let tsClient = null;
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error(`${label}_TIMEOUT`)), timeoutMs)),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
let relay;
|
||||
if (relayEndpoint) {
|
||||
relay = parseEndpoint(relayEndpoint, 39087);
|
||||
} else {
|
||||
relayServer = await createRelayServer({ host: "127.0.0.1", port: 0, token, allowPrivate: true });
|
||||
relay = { host: "127.0.0.1", port: relayServer.port };
|
||||
}
|
||||
|
||||
relayClient = await createRelayClient({
|
||||
relayHost: relay.host,
|
||||
relayPort: relay.port,
|
||||
targetHost: target.host,
|
||||
targetPort: target.port,
|
||||
token,
|
||||
});
|
||||
|
||||
tsClient = new Client(generateIdentity(8), `127.0.0.1:${relayClient.localPort}`, "acceleration-sdk-smoke");
|
||||
await withTimeout(tsClient.connect(), 15_000, "TS_CONNECT");
|
||||
console.log(`TS_ACCEL_CONNECTED target=${target.host}#${target.port}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await tsClient.disconnect();
|
||||
console.log("TS_ACCEL_DISCONNECTED");
|
||||
} catch (error) {
|
||||
console.error("TS_ACCEL_SMOKE_FAILED", error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
try { await tsClient?.disconnect(); } catch {}
|
||||
relayClient?.close();
|
||||
relayServer?.close();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-ipv6-acceleration-poc-token";
|
||||
const PACKET_COUNT = 50;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(port, "::1", () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp6");
|
||||
target.on("message", (payload, rinfo) => target.send(payload, rinfo.port, rinfo.address));
|
||||
await bind(target);
|
||||
const targetPort = target.address().port;
|
||||
|
||||
const relay = await createRelayServer({ host: "::1", port: 0, token: TOKEN, allowPrivate: true });
|
||||
const client = await createRelayClient({
|
||||
relayHost: "::1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "::1",
|
||||
targetPort,
|
||||
token: TOKEN,
|
||||
localHost: "::1",
|
||||
});
|
||||
|
||||
const sender = createSocket("udp6");
|
||||
await bind(sender);
|
||||
const pending = new Set(Array.from({ length: PACKET_COUNT }, (_, index) => index));
|
||||
sender.on("message", (payload) => pending.delete(payload.readUInt32BE(0)));
|
||||
for (let index = 0; index < PACKET_COUNT; index++) {
|
||||
const payload = Buffer.alloc(512, index & 0xff);
|
||||
payload.writeUInt32BE(index, 0);
|
||||
sender.send(payload, client.localPort, "::1");
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 3000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
const received = PACKET_COUNT - pending.size;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
console.log(`ipv6_packets=${PACKET_COUNT} received=${received} loss=${((pending.size / PACKET_COUNT) * 100).toFixed(2)}%`);
|
||||
if (received !== PACKET_COUNT) throw new Error("IPV6_ACCELERATION_POC_FAILED");
|
||||
console.log("IPV6_ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { createSocket } from "node:dgram";
|
||||
import { createRelayServer } from "./relay-server.mjs";
|
||||
import { createRelayClient } from "./relay-client.mjs";
|
||||
|
||||
const TOKEN = "local-acceleration-poc-token";
|
||||
const PACKET_COUNT = 200;
|
||||
const PACKET_SIZE = 1920;
|
||||
|
||||
function bind(socket, port = 0) {
|
||||
return new Promise((resolve) => socket.bind(port, "127.0.0.1", resolve));
|
||||
}
|
||||
|
||||
function close(socket) {
|
||||
try { socket.close(); } catch {}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const target = createSocket("udp4");
|
||||
target.on("message", (payload, rinfo) => {
|
||||
target.send(payload, rinfo.port, rinfo.address);
|
||||
});
|
||||
await bind(target);
|
||||
const targetAddress = target.address();
|
||||
|
||||
const relay = await createRelayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
token: TOKEN,
|
||||
allowPrivate: true,
|
||||
});
|
||||
const client = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: TOKEN,
|
||||
});
|
||||
|
||||
let rejectedBadToken = false;
|
||||
try {
|
||||
const badClient = await createRelayClient({
|
||||
relayHost: "127.0.0.1",
|
||||
relayPort: relay.port,
|
||||
targetHost: "127.0.0.1",
|
||||
targetPort: targetAddress.port,
|
||||
token: "wrong-token-that-is-long-enough",
|
||||
timeoutMs: 250,
|
||||
});
|
||||
badClient.close();
|
||||
} catch {
|
||||
rejectedBadToken = true;
|
||||
}
|
||||
|
||||
const sender = createSocket("udp4");
|
||||
await bind(sender);
|
||||
const pending = new Map();
|
||||
const samples = [];
|
||||
sender.on("message", (payload) => {
|
||||
const id = payload.readUInt32BE(0);
|
||||
const sentAt = pending.get(id);
|
||||
if (sentAt !== undefined) {
|
||||
pending.delete(id);
|
||||
samples.push(Number(process.hrtime.bigint() - sentAt) / 1_000_000);
|
||||
}
|
||||
});
|
||||
|
||||
for (let id = 0; id < PACKET_COUNT; id++) {
|
||||
const payload = Buffer.alloc(PACKET_SIZE, id & 0xff);
|
||||
payload.writeUInt32BE(id, 0);
|
||||
pending.set(id, process.hrtime.bigint());
|
||||
sender.send(payload, client.localPort, "127.0.0.1");
|
||||
await new Promise((resolve) => setTimeout(resolve, 1));
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (pending.size && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
const received = samples.length;
|
||||
const loss = ((PACKET_COUNT - received) / PACKET_COUNT) * 100;
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const percentile = (ratio) => sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * ratio))] : 0;
|
||||
const average = sorted.length ? sorted.reduce((sum, value) => sum + value, 0) / sorted.length : 0;
|
||||
|
||||
sender.close();
|
||||
client.close();
|
||||
relay.close();
|
||||
target.close();
|
||||
|
||||
console.log(`relay=127.0.0.1:${relay.port}`);
|
||||
console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`);
|
||||
console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`);
|
||||
console.log(`bad_token_rejected=${rejectedBadToken}`);
|
||||
if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED");
|
||||
console.log("ACCELERATION_POC_OK");
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = path.resolve(scriptDirectory, "..");
|
||||
const defaultCertDirectory = path.join(appRoot, "certs");
|
||||
|
||||
export function healthcheckUsesHttps(certDirectory = defaultCertDirectory) {
|
||||
return existsSync(path.join(certDirectory, "cert.pem"));
|
||||
}
|
||||
|
||||
export function runDockerHealthcheck({ mode = process.env.WEBSPEAK_MODE, certDirectory = defaultCertDirectory } = {}) {
|
||||
if (mode?.trim().toLowerCase() === "relay") {
|
||||
process.exitCode = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const secure = healthcheckUsesHttps(certDirectory);
|
||||
const client = secure ? https : http;
|
||||
const request = client.get({
|
||||
hostname: "127.0.0.1",
|
||||
port: 3040,
|
||||
path: "/health",
|
||||
...(secure ? { rejectUnauthorized: false } : {}),
|
||||
}, (response) => {
|
||||
response.resume();
|
||||
process.exitCode = response.statusCode >= 200 && response.statusCode < 300 ? 0 : 1;
|
||||
});
|
||||
request.setTimeout(4_000, () => request.destroy(new Error("Healthcheck timed out")));
|
||||
request.on("error", () => { process.exitCode = 1; });
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
runDockerHealthcheck();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { healthcheckUsesHttps } from "./docker-healthcheck.mjs";
|
||||
|
||||
test("Docker healthcheck selects HTTP or HTTPS from the same certificate marker as the server", (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-healthcheck-"));
|
||||
context.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
|
||||
assert.equal(healthcheckUsesHttps(directory), false);
|
||||
mkdirSync(directory, { recursive: true });
|
||||
writeFileSync(path.join(directory, "cert.pem"), "test certificate marker");
|
||||
assert.equal(healthcheckUsesHttps(directory), true);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$width = 3200
|
||||
$height = 116
|
||||
$outputPath = Join-Path $PSScriptRoot "..\docs\examples\illusia-voice\assets\footer-wave.png"
|
||||
$bitmap = [System.Drawing.Bitmap]::new($width, $height, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
|
||||
$graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::HighQuality
|
||||
$graphics.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
$topEdge = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$topEdge.StartFigure()
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(0, 20),
|
||||
[System.Drawing.PointF]::new(240, 4),
|
||||
[System.Drawing.PointF]::new(460, 0),
|
||||
[System.Drawing.PointF]::new(700, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(700, 10),
|
||||
[System.Drawing.PointF]::new(1000, 26),
|
||||
[System.Drawing.PointF]::new(1200, 36),
|
||||
[System.Drawing.PointF]::new(1600, 36)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(1600, 36),
|
||||
[System.Drawing.PointF]::new(2000, 36),
|
||||
[System.Drawing.PointF]::new(2200, 26),
|
||||
[System.Drawing.PointF]::new(2500, 10)
|
||||
)
|
||||
$topEdge.AddBezier(
|
||||
[System.Drawing.PointF]::new(2500, 10),
|
||||
[System.Drawing.PointF]::new(2740, 0),
|
||||
[System.Drawing.PointF]::new(2960, 4),
|
||||
[System.Drawing.PointF]::new(3200, 20)
|
||||
)
|
||||
|
||||
$surface = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$surface.AddPath($topEdge, $false)
|
||||
$surface.AddLine(3200, 20, 3200, $height)
|
||||
$surface.AddLine(3200, $height, 0, $height)
|
||||
$surface.CloseFigure()
|
||||
|
||||
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new(
|
||||
[System.Drawing.Rectangle]::new(0, 0, $width, $height),
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255),
|
||||
[System.Drawing.Drawing2D.LinearGradientMode]::Vertical
|
||||
)
|
||||
$blend = [System.Drawing.Drawing2D.ColorBlend]::new(3)
|
||||
$blend.Colors = [System.Drawing.Color[]]@(
|
||||
[System.Drawing.Color]::FromArgb(138, 244, 252, 254),
|
||||
[System.Drawing.Color]::FromArgb(194, 248, 253, 254),
|
||||
[System.Drawing.Color]::FromArgb(245, 252, 255, 255)
|
||||
)
|
||||
$blend.Positions = [single[]]@(0.0, 0.58, 1.0)
|
||||
$brush.InterpolationColors = $blend
|
||||
$pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(118, 103, 210, 221), 1.5)
|
||||
$pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
|
||||
$accentBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(150, 99, 216, 225))
|
||||
$accentPath = [System.Drawing.Drawing2D.GraphicsPath]::new()
|
||||
$leftDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(126, 47),
|
||||
[System.Drawing.PointF]::new(136, 58),
|
||||
[System.Drawing.PointF]::new(126, 69),
|
||||
[System.Drawing.PointF]::new(116, 58)
|
||||
)
|
||||
$rightDiamond = [System.Drawing.PointF[]]@(
|
||||
[System.Drawing.PointF]::new(3074, 47),
|
||||
[System.Drawing.PointF]::new(3084, 58),
|
||||
[System.Drawing.PointF]::new(3074, 69),
|
||||
[System.Drawing.PointF]::new(3064, 58)
|
||||
)
|
||||
$accentPen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(94, 91, 211, 223), 1.2)
|
||||
$accentPen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
$accentPen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
|
||||
|
||||
$graphics.FillPath($brush, $surface)
|
||||
$graphics.DrawPath($pen, $topEdge)
|
||||
$graphics.DrawLine($accentPen, 82, 58, 116, 58)
|
||||
$graphics.DrawLine($accentPen, 136, 58, 170, 58)
|
||||
$graphics.DrawLine($accentPen, 3030, 58, 3064, 58)
|
||||
$graphics.DrawLine($accentPen, 3084, 58, 3118, 58)
|
||||
$accentPath.AddPolygon($leftDiamond)
|
||||
$accentPath.AddPolygon($rightDiamond)
|
||||
$graphics.FillPath($accentBrush, $accentPath)
|
||||
[System.IO.Directory]::CreateDirectory((Split-Path -Parent $outputPath)) | Out-Null
|
||||
$bitmap.Save($outputPath, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
|
||||
$accentPen.Dispose()
|
||||
$accentBrush.Dispose()
|
||||
$accentPath.Dispose()
|
||||
$pen.Dispose()
|
||||
$brush.Dispose()
|
||||
$surface.Dispose()
|
||||
$topEdge.Dispose()
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -0,0 +1,709 @@
|
||||
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
export interface AdminConnectionRecord {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string | null;
|
||||
relayTarget: string | null;
|
||||
startedAt: string;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: "active" | "connecting" | "disconnected" | "failed";
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}
|
||||
|
||||
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;
|
||||
skinRegistry?: SkinRegistry;
|
||||
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("/skins", async (_request, response) => {
|
||||
response.json({
|
||||
skins: await options.skinRegistry?.list() ?? [],
|
||||
defaultSkinId: await options.skinRegistry?.getDefaultSkinId() ?? "builtin.light",
|
||||
});
|
||||
});
|
||||
|
||||
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
|
||||
const settings = await options.skinRegistry.setDefaultSkin(id);
|
||||
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_DEFAULT_INVALID" ? 400 : 409).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id/enabled", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
const body = asRecord(request.body);
|
||||
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
|
||||
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
|
||||
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
|
||||
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_NOT_FOUND" ? 404 : error.code === "SKIN_ENABLE_INVALID" ? 400 : 409;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/skins/:id", requireSameOriginBinary, requireCsrf(options.sessions), expressRaw({ type: "application/octet-stream", limit: "20mb" }), async (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
|
||||
const skin = await options.skinRegistry.save(request.body, id);
|
||||
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
|
||||
response.status(201).json({ ok: true, skin });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
const status = error.code === "SKIN_LIMIT" || error.code === "SKIN_STORAGE_LIMIT" || error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400;
|
||||
response.status(status).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
try {
|
||||
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
|
||||
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
options.service.database.addAudit("ADMIN_SKIN_REMOVED", { id });
|
||||
response.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof SkinRegistryError) {
|
||||
response.status(error.code === "SKIN_BUILTIN_PROTECTED" ? 409 : 400).json({ ok: false, code: error.code, message: error.message });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
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) => {
|
||||
const limit = readLimit(request.query.limit, 100);
|
||||
response.json({
|
||||
available: Boolean(options.logFile && existsSync(options.logFile)),
|
||||
entries: readRecentLogs(options.logFile, limit),
|
||||
sessions: readConnectionHistory(options.logFile, limit),
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/diagnostics", (_request, response) => {
|
||||
const overview = options.service.getOverview(
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
);
|
||||
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,
|
||||
);
|
||||
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();
|
||||
}
|
||||
|
||||
function requireSameOriginBinary(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/octet-stream")) {
|
||||
response.status(415).json({ ok: false, code: "BINARY_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 {
|
||||
const relayNodes = Array.isArray(body.relayNodes)
|
||||
? body.relayNodes.map((value): RelayNodeInput => {
|
||||
const node = asRecord(value);
|
||||
return {
|
||||
id: typeof node.id === "string" ? node.id.slice(0, 110) : undefined,
|
||||
name: typeof node.name === "string" ? node.name.slice(0, 80) : "",
|
||||
target: typeof node.target === "string" ? node.target.slice(0, 300) : "",
|
||||
enabled: node.enabled === true,
|
||||
token: typeof node.token === "string" ? node.token.slice(0, 512) : undefined,
|
||||
tokenAction: readPasswordAction(node.tokenAction),
|
||||
};
|
||||
})
|
||||
: undefined;
|
||||
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),
|
||||
welcomeTextEn: typeof body.welcomeTextEn === "string" ? body.welcomeTextEn.slice(0, 500) : undefined,
|
||||
welcomeTextDe: typeof body.welcomeTextDe === "string" ? body.welcomeTextDe.slice(0, 500) : undefined,
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcPublicHost: body.webRtcPublicHost as string | undefined,
|
||||
webRtcIpv6Enabled: body.webRtcIpv6Enabled as boolean | undefined,
|
||||
webRtcStunServer: body.webRtcStunServer as string | undefined,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
relayEnabled: body.relayEnabled === true,
|
||||
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
|
||||
relayTarget: typeof body.relayTarget === "string" ? body.relayTarget.slice(0, 300) : undefined,
|
||||
relayToken: typeof body.relayToken === "string" ? body.relayToken.slice(0, 512) : undefined,
|
||||
relayTokenAction: readPasswordAction(body.relayTokenAction),
|
||||
relayNodes,
|
||||
};
|
||||
}
|
||||
|
||||
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
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", "clientIp", "relayName", "relayTarget", "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 StructuredLogEntry {
|
||||
timestamp: string | null;
|
||||
message: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function readConnectionHistory(logFile: string | undefined, limit: number): AdminConnectionRecord[] {
|
||||
if (!logFile) return [];
|
||||
const records = new Map<string, {
|
||||
id: string;
|
||||
nickname: string;
|
||||
clientIp: string;
|
||||
target: string;
|
||||
relayName: string;
|
||||
relayTarget: string;
|
||||
startedAt: string | null;
|
||||
connectedAt: string | null;
|
||||
disconnectedAt: string | null;
|
||||
durationSeconds: number | null;
|
||||
status: AdminConnectionRecord["status"];
|
||||
reason: string | null;
|
||||
failureDetail: string | null;
|
||||
}>();
|
||||
for (const log of readStructuredLogs(logFile)) {
|
||||
const entryId = typeof log.raw.entryId === "string" ? log.raw.entryId : "";
|
||||
if (!entryId || !log.timestamp) continue;
|
||||
const current = records.get(entryId) ?? {
|
||||
id: entryId,
|
||||
nickname: "",
|
||||
clientIp: "",
|
||||
target: "",
|
||||
relayName: "",
|
||||
relayTarget: "",
|
||||
startedAt: null,
|
||||
connectedAt: null,
|
||||
disconnectedAt: null,
|
||||
durationSeconds: null,
|
||||
status: "connecting" as const,
|
||||
reason: null,
|
||||
failureDetail: null,
|
||||
};
|
||||
const nickname = typeof log.raw.nickname === "string" ? log.raw.nickname : "";
|
||||
const clientIp = typeof log.raw.clientIp === "string" ? log.raw.clientIp : "";
|
||||
const target = typeof log.raw.target === "string" ? log.raw.target : "";
|
||||
const relayName = typeof log.raw.relayName === "string" ? log.raw.relayName : "";
|
||||
const relayTarget = typeof log.raw.relayTarget === "string" ? log.raw.relayTarget : "";
|
||||
if (nickname) current.nickname = nickname;
|
||||
if (clientIp) current.clientIp = clientIp;
|
||||
if (target) current.target = target;
|
||||
if (relayName) current.relayName = relayName;
|
||||
if (relayTarget) current.relayTarget = relayTarget;
|
||||
if (typeof log.raw.failureDetail === "string" && log.raw.failureDetail) current.failureDetail = log.raw.failureDetail;
|
||||
if (log.message === "WebClient connecting") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.status = "connecting";
|
||||
} else if (log.message === "TS connect failed") {
|
||||
current.reason = typeof log.raw.code === "string" ? log.raw.code : current.reason;
|
||||
current.status = "failed";
|
||||
} else if (log.message === "Web client connected to TeamSpeak") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.connectedAt = log.timestamp;
|
||||
current.status = "active";
|
||||
} else if (log.message === "Client session torn down") {
|
||||
current.startedAt ??= log.timestamp;
|
||||
current.disconnectedAt = log.timestamp;
|
||||
current.durationSeconds = current.connectedAt && typeof log.raw.durationSeconds === "number"
|
||||
? Math.max(0, Math.floor(log.raw.durationSeconds))
|
||||
: current.connectedAt
|
||||
? Math.max(0, Math.floor((Date.parse(log.timestamp) - Date.parse(current.connectedAt)) / 1000))
|
||||
: null;
|
||||
current.status = current.connectedAt ? "disconnected" : "failed";
|
||||
// `reason` is also used for ordinary lifecycle teardown (for example
|
||||
// websocket-close when a user clicks Leave). Only preserve an explicit
|
||||
// TeamSpeak failure code here; otherwise a normal disconnect would be
|
||||
// rendered by the admin UI as the generic request-failed message.
|
||||
current.reason = typeof log.raw.failureCode === "string" && log.raw.failureCode
|
||||
? log.raw.failureCode
|
||||
: current.reason;
|
||||
}
|
||||
records.set(entryId, current);
|
||||
}
|
||||
const now = Date.now();
|
||||
return [...records.values()]
|
||||
.filter((record): record is typeof record & { startedAt: string } => Boolean(record.startedAt))
|
||||
.map((record) => {
|
||||
const start = record.connectedAt ?? record.startedAt;
|
||||
const end = record.disconnectedAt ? Date.parse(record.disconnectedAt) : now;
|
||||
return {
|
||||
id: record.id,
|
||||
nickname: record.nickname || "—",
|
||||
clientIp: record.clientIp || "—",
|
||||
target: record.target || "—",
|
||||
relayName: record.relayName || null,
|
||||
relayTarget: record.relayTarget || null,
|
||||
startedAt: record.startedAt,
|
||||
connectedAt: record.connectedAt,
|
||||
disconnectedAt: record.disconnectedAt,
|
||||
durationSeconds: record.durationSeconds ?? (record.status === "active" || record.status === "connecting"
|
||||
? Math.max(0, Math.floor((end - Date.parse(start)) / 1000))
|
||||
: null),
|
||||
status: record.status,
|
||||
// Older sessions may only contain a teardown record without a
|
||||
// structured failure code. Keep normal disconnects quiet, but make
|
||||
// an untraceable failed connection explicitly visible as the generic
|
||||
// request-failed message instead of implying a guessed cause.
|
||||
reason: record.reason ?? (record.status === "failed" ? "CONNECTION_FAILED" : null),
|
||||
failureDetail: record.failureDetail,
|
||||
};
|
||||
})
|
||||
.sort((left, right) => Date.parse(right.disconnectedAt ?? right.startedAt) - Date.parse(left.disconnectedAt ?? left.startedAt))
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
const paths = [logFile, `${logFile}.1`, `${logFile}.2`, `${logFile}.3`].filter((value, index, all) => value && all.indexOf(value) === index);
|
||||
const entries: StructuredLogEntry[] = [];
|
||||
for (const path of paths) {
|
||||
if (!existsSync(path)) continue;
|
||||
try {
|
||||
for (const line of readFileSync(path, "utf8").split(/\r?\n/).filter(Boolean)) {
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
entries.push({
|
||||
timestamp: typeof raw.time === "string" ? raw.time : null,
|
||||
message: typeof raw.msg === "string" ? raw.msg : "",
|
||||
raw,
|
||||
});
|
||||
} catch {
|
||||
// Non-JSON lines are still shown by the normal log viewer, but cannot
|
||||
// be associated with a user session safely.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A rotated file can disappear between existsSync and readFileSync.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
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" });
|
||||
}
|
||||
@@ -0,0 +1,619 @@
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import 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 PersistedRelayNode, 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 } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
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();
|
||||
const welcomeTexts = resolveWelcomeTexts({
|
||||
zh: settings.welcomeText,
|
||||
en: settings.welcomeTextEn,
|
||||
de: settings.welcomeTextDe,
|
||||
ru: settings.welcomeTextRu,
|
||||
ja: settings.welcomeTextJa,
|
||||
});
|
||||
return {
|
||||
version: this.version,
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
// Keep the old fields for older clients, but return the complete,
|
||||
// already-fallback-resolved map for current clients.
|
||||
welcomeText: welcomeTexts.zh,
|
||||
welcomeTextEn: welcomeTexts.en,
|
||||
welcomeTexts,
|
||||
accessMode: settings.accessMode,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
};
|
||||
}
|
||||
|
||||
getAdminSettings(): AdminSettings {
|
||||
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,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
welcomeDefaults: DEFAULT_WELCOME_TEXTS,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayTarget: settings.relayHost ? formatRelayTarget(settings.relayHost, settings.relayPort) : "",
|
||||
hasRelayToken: Boolean(settings.relayTokenEncrypted),
|
||||
relayNodes: this.getRelayNodeViews(),
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
getWebRtcAudioOptions(): WebRtcAudioOptions {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
enabled: settings.webRtcEnabled,
|
||||
publicHost: settings.webRtcPublicHost,
|
||||
ipv6Enabled: settings.webRtcIpv6Enabled,
|
||||
stunServer: settings.webRtcStunServer,
|
||||
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
|
||||
};
|
||||
}
|
||||
|
||||
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
|
||||
const relays: ConfiguredAccelerationRelay[] = [];
|
||||
for (const node of this.database.listRelayNodes()) {
|
||||
if (!node.enabled || !node.host || !node.tokenEncrypted) continue;
|
||||
try {
|
||||
const token = decryptSecret(node.tokenEncrypted, this.masterSecret);
|
||||
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token });
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error), relayId: node.id }, "Stored acceleration relay token could not be decrypted");
|
||||
}
|
||||
}
|
||||
return relays;
|
||||
}
|
||||
|
||||
getAccelerationRelayName(): string | undefined {
|
||||
return this.getAccelerationRelayOptions()[0]?.name;
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const relayNodes = input.relayNodes === undefined ? undefined : this.normalizeRelayNodes(input.relayNodes);
|
||||
const settings = this.normalizeSettings(input, current, relayNodes);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
|
||||
this.database.updateSettings(settings);
|
||||
if (relayNodes !== undefined) {
|
||||
this.database.replaceRelayNodes(relayNodes);
|
||||
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
|
||||
this.database.replaceRelayNodes(this.legacyRelayNodesFromSettings(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<{ ok: boolean; checkType: "network" | "protocol"; passwordVerified: boolean; latencyMs: number; serverName: string | null; requiresPassword: boolean; packetLossPercent?: number; attempts?: number; successfulAttempts?: number; errorCode?: string }> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
// The admin connection test must not create a temporary TeamSpeak
|
||||
// client: that client becomes visible in the target channel. Use the
|
||||
// WebSpeak host's ICMP route measurement instead. The injected probe is
|
||||
// retained for unit tests and explicit protocol-probe callers.
|
||||
if (this.probe === probeTeamSpeak) {
|
||||
const result = await pingTeamSpeakHost(target.host, { attempts: 4 });
|
||||
const publicResult = {
|
||||
ok: result.ok,
|
||||
checkType: "network" as const,
|
||||
passwordVerified: false,
|
||||
latencyMs: result.latencyMs ?? 0,
|
||||
serverName: null,
|
||||
requiresPassword: false,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
attempts: result.attempts,
|
||||
successfulAttempts: result.successfulAttempts,
|
||||
...(result.errorCode ? { errorCode: result.errorCode } : {}),
|
||||
};
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: result.latencyMs, error: result.ok ? null : (result.errorCode ?? "UNREACHABLE") });
|
||||
this.database.addAudit(result.ok ? "CONNECTION_TEST_SUCCEEDED" : "CONNECTION_TEST_FAILED", {
|
||||
latencyMs: result.latencyMs,
|
||||
packetLossPercent: result.packetLossPercent,
|
||||
...(result.errorCode ? { code: result.errorCode } : {}),
|
||||
});
|
||||
}
|
||||
return publicResult;
|
||||
}
|
||||
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, checkType: "protocol", passwordVerified: true };
|
||||
} 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): AdminOverview {
|
||||
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"]>, relayNodes?: PersistedRelayNode[]): 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();
|
||||
const welcomeTextEn = typeof input.welcomeTextEn === "string" ? input.welcomeTextEn.trim() : current.welcomeTextEn;
|
||||
const welcomeTextDe = typeof input.welcomeTextDe === "string" ? input.welcomeTextDe.trim() : current.welcomeTextDe;
|
||||
const welcomeTextRu = typeof input.welcomeTextRu === "string" ? input.welcomeTextRu.trim() : current.welcomeTextRu;
|
||||
const welcomeTextJa = typeof input.welcomeTextJa === "string" ? input.welcomeTextJa.trim() : current.welcomeTextJa;
|
||||
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 (welcomeTextEn.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_EN", "English welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextDe.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_DE", "German welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextRu.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_RU", "Russian welcome text cannot exceed 500 characters");
|
||||
if (welcomeTextJa.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT_JA", "Japanese 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 webRtcPublicHost = normalizeVoiceMediaHost(input.webRtcPublicHost === undefined ? current.webRtcPublicHost : input.webRtcPublicHost);
|
||||
const webRtcStunServer = normalizeVoiceStunServer(input.webRtcStunServer === undefined ? current.webRtcStunServer : input.webRtcStunServer);
|
||||
const webRtcIpv6Enabled = input.webRtcIpv6Enabled === undefined ? current.webRtcIpv6Enabled : input.webRtcIpv6Enabled;
|
||||
if (webRtcPublicHost === null) throw new AdminInputError("INVALID_WEBRTC_PUBLIC_HOST", "Use an IP address or hostname without a scheme, path or port");
|
||||
if (webRtcStunServer === null) throw new AdminInputError("INVALID_WEBRTC_STUN_SERVER", "Use a UDP STUN URL: stun:host:port");
|
||||
if (typeof webRtcIpv6Enabled !== "boolean") throw new AdminInputError("INVALID_WEBRTC_IPV6", "WebRTC IPv6 value must be boolean");
|
||||
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;
|
||||
|
||||
let relayConfigured = current.relayConfigured;
|
||||
let relayEnabled = current.relayEnabled;
|
||||
let relayName = current.relayName;
|
||||
let relayHost = current.relayHost;
|
||||
let relayPort = current.relayPort || DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
let relayTokenEncrypted = current.relayTokenEncrypted;
|
||||
const relaySettingsAction = input.relaySettingsAction ?? "keep";
|
||||
if (relaySettingsAction === "remove") {
|
||||
relayConfigured = true;
|
||||
relayEnabled = false;
|
||||
relayName = "";
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = null;
|
||||
} else if (relaySettingsAction === "replace") {
|
||||
const relayTarget = (input.relayTarget ?? "").trim();
|
||||
relayEnabled = input.relayEnabled === true;
|
||||
relayName = (input.relayName ?? "").trim();
|
||||
if (relayName.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 80 characters or fewer");
|
||||
if (relayEnabled && !relayName) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name is required when the relay is enabled");
|
||||
if (relayEnabled && !relayTarget) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is required when the relay is enabled");
|
||||
if (relayTarget) {
|
||||
try {
|
||||
const relay = parseTeamSpeakTarget(relayTarget, DEFAULT_ACCELERATION_RELAY_PORT);
|
||||
relayHost = relay.host;
|
||||
relayPort = relay.port;
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
}
|
||||
} else {
|
||||
relayHost = "";
|
||||
relayPort = DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
}
|
||||
const relayTokenAction = input.relayTokenAction ?? (input.relayToken === undefined ? "keep" : "replace");
|
||||
if (relayTokenAction === "remove") relayTokenEncrypted = null;
|
||||
if (relayTokenAction === "replace") relayTokenEncrypted = input.relayToken ? encryptSecret(input.relayToken, this.masterSecret) : null;
|
||||
if (relayEnabled && !relayTokenEncrypted) throw new AdminInputError("INVALID_RELAY_TOKEN", "Relay token is required when the relay is enabled");
|
||||
relayConfigured = true;
|
||||
}
|
||||
if (relayNodes) {
|
||||
const primary = relayNodes.find((node) => node.enabled) ?? relayNodes[0];
|
||||
relayConfigured = relayNodes.length > 0;
|
||||
relayEnabled = primary?.enabled === true;
|
||||
relayName = primary?.name ?? "";
|
||||
relayHost = primary?.host ?? "";
|
||||
relayPort = primary?.port ?? DEFAULT_ACCELERATION_RELAY_PORT;
|
||||
relayTokenEncrypted = primary?.tokenEncrypted ?? null;
|
||||
}
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
welcomeTextEn,
|
||||
welcomeTextDe,
|
||||
welcomeTextRu,
|
||||
welcomeTextJa,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
relayConfigured,
|
||||
relayEnabled,
|
||||
relayName,
|
||||
relayHost,
|
||||
relayPort,
|
||||
relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
private normalizeRelayNodes(inputs: RelayNodeInput[]): PersistedRelayNode[] {
|
||||
if (!Array.isArray(inputs) || inputs.length > 16) throw new AdminInputError("INVALID_RELAY_NODES", "At most 16 relay nodes may be configured");
|
||||
const current = new Map(this.database.listRelayNodes().map((node) => [node.id, node]));
|
||||
const seen = new Set<string>();
|
||||
const now = new Date().toISOString();
|
||||
return inputs.map((input) => {
|
||||
const name = typeof input.name === "string" ? input.name.trim() : "";
|
||||
const targetText = typeof input.target === "string" ? input.target.trim() : "";
|
||||
if (!name || name.length > 80) throw new AdminInputError("INVALID_RELAY_NAME", "Relay name must contain 1 to 80 characters");
|
||||
if (!targetText || targetText.length > 300) throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid");
|
||||
let target: TeamSpeakTarget;
|
||||
try { target = parseTeamSpeakTarget(targetText, DEFAULT_ACCELERATION_RELAY_PORT); }
|
||||
catch { throw new AdminInputError("INVALID_RELAY_TARGET", "Relay target is invalid"); }
|
||||
const id = typeof input.id === "string" && /^relay-[a-z0-9-]{1,100}$/i.test(input.id)
|
||||
? input.id
|
||||
: `relay-${randomBytes(8).toString("hex")}`;
|
||||
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
|
||||
seen.add(id);
|
||||
const previous = current.get(id);
|
||||
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
|
||||
let tokenEncrypted = previous?.tokenEncrypted ?? null;
|
||||
if (tokenAction === "remove") tokenEncrypted = null;
|
||||
if (tokenAction === "replace") {
|
||||
const token = typeof input.token === "string" ? input.token.trim() : "";
|
||||
tokenEncrypted = token ? encryptSecret(token, this.masterSecret) : null;
|
||||
}
|
||||
if (input.enabled === true && (!tokenEncrypted || !this.canDecryptToken(tokenEncrypted))) {
|
||||
throw new AdminInputError("INVALID_RELAY_TOKEN", "A relay token of at least 16 characters is required when the relay is enabled");
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
enabled: input.enabled === true,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
tokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private canDecryptToken(encrypted: string): boolean {
|
||||
try {
|
||||
return decryptSecret(encrypted, this.masterSecret).length >= 16;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
|
||||
return this.database.listRelayNodes().map((node) => ({
|
||||
id: node.id,
|
||||
name: node.name,
|
||||
enabled: node.enabled,
|
||||
target: formatRelayTarget(node.host, node.port),
|
||||
hasToken: Boolean(node.tokenEncrypted),
|
||||
}));
|
||||
}
|
||||
|
||||
private legacyRelayNodesFromSettings(settings: SettingsUpdate): PersistedRelayNode[] {
|
||||
if (!settings.relayConfigured || !settings.relayHost || !settings.relayTokenEncrypted) return [];
|
||||
const previous = this.database.listRelayNodes()[0];
|
||||
const now = new Date().toISOString();
|
||||
return [{
|
||||
id: previous?.id ?? "relay-default",
|
||||
name: settings.relayName || "中继加速",
|
||||
enabled: settings.relayEnabled,
|
||||
host: settings.relayHost,
|
||||
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
|
||||
tokenEncrypted: settings.relayTokenEncrypted,
|
||||
createdAt: previous?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
}];
|
||||
}
|
||||
|
||||
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,
|
||||
welcomeTextEn: settings.welcomeTextEn,
|
||||
welcomeTextDe: settings.welcomeTextDe,
|
||||
welcomeTextRu: settings.welcomeTextRu,
|
||||
welcomeTextJa: settings.welcomeTextJa,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
relayEnabled: settings.relayEnabled,
|
||||
relayName: settings.relayName,
|
||||
relayHost: settings.relayHost,
|
||||
relayPort: settings.relayPort,
|
||||
relayTokenEncrypted: settings.relayTokenEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
welcomeTextEn: current.welcomeTextEn,
|
||||
welcomeTextDe: current.welcomeTextDe,
|
||||
welcomeTextRu: current.welcomeTextRu,
|
||||
welcomeTextJa: current.welcomeTextJa,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcPublicHost: current.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: current.webRtcIpv6Enabled,
|
||||
webRtcStunServer: current.webRtcStunServer,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
relayConfigured: current.relayConfigured,
|
||||
relayEnabled: current.relayEnabled,
|
||||
relayName: current.relayName,
|
||||
relayHost: current.relayHost,
|
||||
relayPort: current.relayPort,
|
||||
relayTokenEncrypted: current.relayTokenEncrypted,
|
||||
}, "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");
|
||||
}
|
||||
|
||||
function formatRelayTarget(host: string, port: number): string {
|
||||
return `${host.includes(":") ? `[${host}]` : host}#${port}`;
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "AdminInputError";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
id: "sample-skin",
|
||||
name: "Sample skin",
|
||||
version: "1.0.0",
|
||||
author: "WebSpeak test",
|
||||
license: "MIT",
|
||||
minAppVersion: "0.2.4",
|
||||
entry: "skin.css",
|
||||
content: "content.json",
|
||||
preview: "assets/preview.png",
|
||||
};
|
||||
|
||||
test("skin registry validates, lists, replaces, serves, and removes packages", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-registry-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
const firstArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(manifest))],
|
||||
["skin.css", Buffer.from(".voice-card { background: url(assets/background.png); }")],
|
||||
["content.json", Buffer.from(JSON.stringify({ defaultLocale: "en", locales: { en: { home: { title: "Hello" } } } }))],
|
||||
["assets/background.png", Buffer.from([1, 2, 3, 4])],
|
||||
["assets/preview.png", Buffer.from([5, 6, 7, 8])],
|
||||
]);
|
||||
const first = await registry.save(firstArchive, "sample-skin");
|
||||
assert.equal(first.id, "sample-skin");
|
||||
assert.equal(first.previewUrl, "/api/skins/sample-skin/preview");
|
||||
assert.equal((await registry.list()).length, 1);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), firstArchive);
|
||||
assert.deepEqual((await registry.readPreview("sample-skin"))?.bytes, Buffer.from([5, 6, 7, 8]));
|
||||
await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
|
||||
const replacement = { ...manifest, version: "2.0.0", content: undefined, preview: undefined };
|
||||
const secondArchive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify(replacement))],
|
||||
["skin.css", Buffer.from(".voice-card { border-radius: 0; }")],
|
||||
]);
|
||||
const second = await registry.save(secondArchive, "sample-skin");
|
||||
assert.equal(second.version, "2.0.0");
|
||||
assert.equal(second.installedAt, first.installedAt);
|
||||
assert.equal(await registry.readPreview("sample-skin"), null);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), secondArchive);
|
||||
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.remove("sample-skin"), false);
|
||||
});
|
||||
|
||||
test("custom skins can be enabled, disabled, and selected as the instance default", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-settings-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const archive = createZip([
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from("[data-ws-part=\"demo.voice-card\"] { color: teal; }")],
|
||||
]);
|
||||
|
||||
const skin = await registry.save(archive, "sample-skin");
|
||||
assert.equal(skin.enabled, true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.getDefaultSkinId(), "sample-skin");
|
||||
|
||||
const disabled = await registry.setEnabled("sample-skin", false);
|
||||
assert.equal(disabled.enabled, false);
|
||||
assert.equal(await registry.readArchive("sample-skin"), null);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
await assert.rejects(registry.setDefaultSkin("sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_DEFAULT_INVALID");
|
||||
|
||||
await registry.setEnabled("sample-skin", true);
|
||||
assert.deepEqual(await registry.readArchive("sample-skin"), archive);
|
||||
await registry.setDefaultSkin("sample-skin");
|
||||
assert.equal(await registry.remove("sample-skin"), true);
|
||||
assert.equal(await registry.getDefaultSkinId(), "builtin.light");
|
||||
});
|
||||
|
||||
test("skin registry rejects path traversal and mismatched local ZIP headers", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-invalid-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
const goodFiles: Array<[string, Buffer]> = [
|
||||
["manifest.json", Buffer.from(JSON.stringify({ ...manifest, content: undefined, preview: undefined }))],
|
||||
["skin.css", Buffer.from(".voice-card { color: teal; }")],
|
||||
];
|
||||
|
||||
await assert.rejects(registry.save(createZip([["../escape.png", Buffer.from([1])], ...goodFiles]), "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_PATH_INVALID");
|
||||
const mismatched = createZip(goodFiles);
|
||||
mismatched[30] ^= 1;
|
||||
await assert.rejects(registry.save(mismatched, "sample-skin"), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_ZIP_INVALID");
|
||||
|
||||
await writeFile(path.join(directory, "orphan.wskin"), createZip(goodFiles));
|
||||
assert.equal(await registry.readArchive("orphan"), null);
|
||||
assert.deepEqual(await registry.list(), []);
|
||||
});
|
||||
|
||||
test("the three bundled skins cannot be replaced or removed through the registry", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-skin-builtins-"));
|
||||
context.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const registry = new SkinRegistry(directory);
|
||||
for (const id of ["builtin.light", "builtin.dark", "community.illusia-voice"]) {
|
||||
await assert.rejects(registry.save(Buffer.alloc(22), id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.remove(id), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
await assert.rejects(registry.setEnabled(id, false), (error: unknown) => error instanceof SkinRegistryError && error.code === "SKIN_BUILTIN_PROTECTED");
|
||||
}
|
||||
});
|
||||
|
||||
function createZip(files: Array<[string, Buffer]>): Buffer {
|
||||
const localRecords: Buffer[] = [];
|
||||
const centralRecords: Buffer[] = [];
|
||||
let localOffset = 0;
|
||||
for (const [name, bytes] of files) {
|
||||
const filename = Buffer.from(name, "utf8");
|
||||
const checksum = crc32(bytes);
|
||||
const local = Buffer.alloc(30 + filename.length + bytes.length);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0, 6);
|
||||
local.writeUInt16LE(0, 8);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(bytes.length, 18);
|
||||
local.writeUInt32LE(bytes.length, 22);
|
||||
local.writeUInt16LE(filename.length, 26);
|
||||
filename.copy(local, 30);
|
||||
bytes.copy(local, 30 + filename.length);
|
||||
localRecords.push(local);
|
||||
|
||||
const central = Buffer.alloc(46 + filename.length);
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(0x0314, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE(0, 8);
|
||||
central.writeUInt16LE(0, 10);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(bytes.length, 20);
|
||||
central.writeUInt32LE(bytes.length, 24);
|
||||
central.writeUInt16LE(filename.length, 28);
|
||||
central.writeUInt32LE(0x81a40000, 38);
|
||||
central.writeUInt32LE(localOffset, 42);
|
||||
filename.copy(central, 46);
|
||||
centralRecords.push(central);
|
||||
localOffset += local.length;
|
||||
}
|
||||
const centralDirectory = Buffer.concat(centralRecords);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(centralDirectory.length, 12);
|
||||
end.writeUInt32LE(localOffset, 16);
|
||||
return Buffer.concat([...localRecords, centralDirectory, end]);
|
||||
}
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
import type { SkinCatalogEntry as SharedSkinCatalogEntry } from "../shared/skin-catalog.js";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { inflateRawSync } from "node:zlib";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_FILE_COUNT = 128;
|
||||
const MAX_CSS_BYTES = 512 * 1024;
|
||||
const MAX_CONTENT_BYTES = 256 * 1024;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_FONT_BYTES = 4 * 1024 * 1024;
|
||||
const MAX_SKINS = 50;
|
||||
const MAX_TOTAL_ARCHIVES = 200 * 1024 * 1024;
|
||||
export const BUILTIN_SKIN_IDS = ["builtin.light", "builtin.dark", "community.illusia-voice"] as const;
|
||||
const BUILTIN_SKIN_ID_SET = new Set<string>(BUILTIN_SKIN_IDS);
|
||||
const EOCD_SIGNATURE = 0x06054b50;
|
||||
const CENTRAL_SIGNATURE = 0x02014b50;
|
||||
const LOCAL_SIGNATURE = 0x04034b50;
|
||||
|
||||
export interface SkinCatalogEntry extends SharedSkinCatalogEntry {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface SkinRegistrySettings {
|
||||
defaultSkinId: string;
|
||||
}
|
||||
|
||||
interface SkinArchiveEntry {
|
||||
path: string;
|
||||
compressedSize: number;
|
||||
expandedSize: number;
|
||||
compression: number;
|
||||
crc: number;
|
||||
localOffset: number;
|
||||
flags: number;
|
||||
isDirectory: boolean;
|
||||
unixFileType: number;
|
||||
}
|
||||
|
||||
type ParsedSkinManifest = Omit<SkinCatalogEntry, "installedAt" | "previewUrl" | "previewMimeType" | "enabled"> & {
|
||||
entry: string;
|
||||
content?: string;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
export class SkinRegistryError extends Error {
|
||||
constructor(message: string, readonly code: string) {
|
||||
super(message);
|
||||
this.name = "SkinRegistryError";
|
||||
}
|
||||
}
|
||||
|
||||
export function isBuiltinSkinId(id: string): boolean {
|
||||
return BUILTIN_SKIN_ID_SET.has(id);
|
||||
}
|
||||
|
||||
export class SkinRegistry {
|
||||
constructor(private readonly directory: string) {}
|
||||
|
||||
async list(): Promise<SkinCatalogEntry[]> {
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const names = await readdir(this.directory);
|
||||
const entries: SkinCatalogEntry[] = [];
|
||||
for (const filename of names.filter((item) => item.endsWith(".json"))) {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, filename), "utf8"));
|
||||
if (!isCatalogEntry(value) || filename !== `${value.id}.json`) continue;
|
||||
const archiveInfo = await stat(path.join(this.directory, `${value.id}.wskin`)).catch(() => null);
|
||||
if (!archiveInfo?.isFile() || archiveInfo.size < 22 || archiveInfo.size > MAX_ARCHIVE_BYTES) continue;
|
||||
entries.push({ ...value, enabled: value.enabled !== false });
|
||||
} catch {
|
||||
// Ignore incomplete or stale metadata. The archive itself remains untouched.
|
||||
}
|
||||
}
|
||||
return entries.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
async save(bytes: Buffer, expectedId: string): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(expectedId)) throw new SkinRegistryError("Built-in skins cannot be replaced.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(expectedId)) throw new SkinRegistryError("Skin ID is invalid.", "SKIN_ID_INVALID");
|
||||
const parsed = validateSkinArchive(bytes, expectedId);
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const current = await this.list();
|
||||
const replacing = current.some((entry) => entry.id === expectedId);
|
||||
if (!replacing && current.length >= MAX_SKINS) throw new SkinRegistryError("The instance already has the maximum number of skins.", "SKIN_LIMIT");
|
||||
const archivePaths = await Promise.all(current.map(async (entry) => ({ id: entry.id, size: (await stat(path.join(this.directory, `${entry.id}.wskin`)).catch(() => ({ size: 0 }))).size })));
|
||||
const totalBytes = archivePaths.reduce((sum, entry) => sum + (entry.id === expectedId ? 0 : entry.size), bytes.byteLength);
|
||||
if (totalBytes > MAX_TOTAL_ARCHIVES) throw new SkinRegistryError("The total skin storage limit is 200 MiB.", "SKIN_STORAGE_LIMIT");
|
||||
|
||||
const previous = current.find((entry) => entry.id === expectedId);
|
||||
const installedAt = previous?.installedAt ?? Date.now();
|
||||
const catalog: SkinCatalogEntry = {
|
||||
...parsed.manifest,
|
||||
installedAt,
|
||||
enabled: previous?.enabled ?? true,
|
||||
...(parsed.previewMime ? { previewUrl: `/api/skins/${expectedId}/preview`, previewMimeType: parsed.previewMime } : {}),
|
||||
};
|
||||
const nonce = randomBytes(6).toString("hex");
|
||||
const archiveTemp = path.join(this.directory, `.${expectedId}.${nonce}.tmp`);
|
||||
const catalogTemp = path.join(this.directory, `.${expectedId}.${nonce}.json.tmp`);
|
||||
const previewTemp = path.join(this.directory, `.${expectedId}.${nonce}.preview.tmp`);
|
||||
try {
|
||||
await writeFile(archiveTemp, bytes, { flag: "wx", mode: 0o600 });
|
||||
await writeFile(catalogTemp, JSON.stringify(catalog), { flag: "wx", mode: 0o600 });
|
||||
if (parsed.previewBytes) await writeFile(previewTemp, parsed.previewBytes, { flag: "wx", mode: 0o600 });
|
||||
await rename(archiveTemp, path.join(this.directory, `${expectedId}.wskin`));
|
||||
await rename(catalogTemp, path.join(this.directory, `${expectedId}.json`));
|
||||
const previewPath = path.join(this.directory, `${expectedId}.preview`);
|
||||
if (parsed.previewBytes) await rename(previewTemp, previewPath);
|
||||
else await unlink(previewPath).catch(() => undefined);
|
||||
} catch (error) {
|
||||
await Promise.all([archiveTemp, catalogTemp, previewTemp].map((file) => unlink(file).catch(() => undefined)));
|
||||
throw error;
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
async readArchive(id: string): Promise<Buffer | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
if (!(await this.list()).some((entry) => entry.id === id && entry.enabled)) return null;
|
||||
try { return await readFile(path.join(this.directory, `${id}.wskin`)); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
async readPreview(id: string): Promise<{ bytes: Buffer; mimeType: string } | null> {
|
||||
if (!isSafeSkinId(id)) return null;
|
||||
const catalog = (await this.list()).find((entry) => entry.id === id);
|
||||
if (!catalog?.enabled || !catalog.previewUrl) return null;
|
||||
const mimeType = catalog.previewMimeType || "application/octet-stream";
|
||||
try {
|
||||
const bytes = await readFile(path.join(this.directory, `${id}.preview`));
|
||||
return { bytes, mimeType };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<boolean> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be removed.", "SKIN_BUILTIN_PROTECTED");
|
||||
if (!isSafeSkinId(id)) return false;
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const archive = path.join(this.directory, `${id}.wskin`);
|
||||
const catalog = path.join(this.directory, `${id}.json`);
|
||||
const preview = path.join(this.directory, `${id}.preview`);
|
||||
const present = await Promise.all([archive, catalog, preview].map((file) => stat(file).then(() => true).catch(() => false))).then((items) => items.some(Boolean));
|
||||
if (!present) return false;
|
||||
await Promise.all([archive, catalog, preview].map((file) => unlink(file).catch((error: unknown) => {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
})));
|
||||
if (wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return true;
|
||||
}
|
||||
|
||||
async setEnabled(id: string, enabled: boolean): Promise<SkinCatalogEntry> {
|
||||
if (isBuiltinSkinId(id)) throw new SkinRegistryError("Built-in skins cannot be disabled.", "SKIN_BUILTIN_PROTECTED");
|
||||
const entry = (await this.list()).find((item) => item.id === id);
|
||||
if (!entry) throw new SkinRegistryError("The skin was not found.", "SKIN_NOT_FOUND");
|
||||
const wasDefault = await this.getDefaultSkinId() === id;
|
||||
const updated = { ...entry, enabled };
|
||||
await writeAtomicJson(path.join(this.directory, `${id}.json`), updated);
|
||||
if (!enabled && wasDefault) await this.setDefaultSkin("builtin.light");
|
||||
return updated;
|
||||
}
|
||||
|
||||
async getDefaultSkinId(): Promise<string> {
|
||||
try {
|
||||
const value: unknown = JSON.parse(await readFile(path.join(this.directory, "settings.json"), "utf8"));
|
||||
const id = value && typeof value === "object" ? (value as Record<string, unknown>).defaultSkinId : null;
|
||||
if (typeof id !== "string") return "builtin.light";
|
||||
if (isBuiltinSkinId(id)) return id;
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
return entry ? id : "builtin.light";
|
||||
} catch {
|
||||
return "builtin.light";
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultSkin(id: string): Promise<SkinRegistrySettings> {
|
||||
if (!isBuiltinSkinId(id)) {
|
||||
const entry = (await this.list()).find((skin) => skin.id === id && skin.enabled);
|
||||
if (!entry) throw new SkinRegistryError("The default skin must be enabled and installed.", "SKIN_DEFAULT_INVALID");
|
||||
}
|
||||
await mkdir(this.directory, { recursive: true });
|
||||
const settings = { defaultSkinId: id };
|
||||
await writeAtomicJson(path.join(this.directory, "settings.json"), settings);
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeAtomicJson(filename: string, value: unknown): Promise<void> {
|
||||
const temporary = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||
await rename(temporary, filename);
|
||||
} catch (error) {
|
||||
await unlink(temporary).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
|
||||
const entries = inspectArchive(bytes);
|
||||
const regularEntries = entries.filter((entry) => !entry.isDirectory);
|
||||
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
|
||||
const fileBytes = new Map<string, Buffer>();
|
||||
for (const entry of regularEntries) {
|
||||
const packagePath = rootPrefix ? entry.path.slice(rootPrefix.length) : entry.path;
|
||||
if (!isSafePackagePath(packagePath)) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const content = extractEntry(bytes, entry);
|
||||
if (content.byteLength !== entry.expandedSize || crc32(content) !== entry.crc) throw new SkinRegistryError("The package has a damaged file entry.", "SKIN_ZIP_INVALID");
|
||||
if (fileBytes.has(packagePath.toLowerCase())) throw new SkinRegistryError("The package contains duplicate paths.", "SKIN_PATH_DUPLICATE");
|
||||
fileBytes.set(packagePath, content);
|
||||
}
|
||||
const manifestBytes = fileBytes.get("manifest.json");
|
||||
if (!manifestBytes || manifestBytes.byteLength > 32 * 1024) throw new SkinRegistryError("The package needs a small root-level manifest.json.", "SKIN_MANIFEST_MISSING");
|
||||
const manifest = parseManifest(manifestBytes);
|
||||
if (expectedId && manifest.id !== expectedId) throw new SkinRegistryError("The skin ID does not match the upload target.", "SKIN_ID_MISMATCH");
|
||||
const cssBytes = fileBytes.get(manifest.entry);
|
||||
if (!cssBytes || !cssBytes.byteLength || cssBytes.byteLength > MAX_CSS_BYTES) throw new SkinRegistryError("The CSS entry is missing or exceeds 512 KiB.", "SKIN_CSS_SIZE");
|
||||
decodeUtf8(cssBytes, "The CSS entry is not valid UTF-8.");
|
||||
|
||||
let previewBytes: Buffer | undefined;
|
||||
let previewMime: string | undefined;
|
||||
for (const [packagePath, data] of fileBytes) {
|
||||
if (["manifest.json", manifest.entry, manifest.content, manifest.preview].includes(packagePath)) continue;
|
||||
const mimeType = imageMime(packagePath) ?? (packagePath.toLowerCase().endsWith(".woff2") ? "font/woff2" : null);
|
||||
if (!mimeType) throw new SkinRegistryError(`Unsupported package file: ${packagePath}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("image/") && data.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("Each image must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
|
||||
if (mimeType.startsWith("font/") && data.byteLength > MAX_FONT_BYTES) throw new SkinRegistryError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
}
|
||||
if (manifest.content) {
|
||||
const content = fileBytes.get(manifest.content);
|
||||
if (!content || content.byteLength > MAX_CONTENT_BYTES) throw new SkinRegistryError("content.json is missing or exceeds 256 KiB.", "SKIN_CONTENT_SIZE");
|
||||
decodeUtf8(content, "content.json is not valid UTF-8.");
|
||||
try { JSON.parse(content.toString("utf8")); }
|
||||
catch { throw new SkinRegistryError("content.json is not valid JSON.", "SKIN_CONTENT_INVALID"); }
|
||||
}
|
||||
if (manifest.preview) {
|
||||
previewBytes = fileBytes.get(manifest.preview);
|
||||
previewMime = imageMime(manifest.preview) ?? undefined;
|
||||
if (!previewBytes || !previewMime || previewBytes.byteLength > MAX_IMAGE_BYTES) throw new SkinRegistryError("The preview must be a supported image inside the package.", "SKIN_PREVIEW_INVALID");
|
||||
}
|
||||
return { manifest, ...(previewBytes ? { previewBytes, previewMime } : {}) };
|
||||
}
|
||||
|
||||
function inspectArchive(bytes: Buffer): SkinArchiveEntry[] {
|
||||
if (bytes.byteLength < 22 || bytes.byteLength > MAX_ARCHIVE_BYTES) throw new SkinRegistryError("A skin package must be smaller than 20 MiB.", "SKIN_ARCHIVE_SIZE");
|
||||
const minOffset = Math.max(0, bytes.byteLength - 22 - 0xffff);
|
||||
let endOffset = -1;
|
||||
for (let offset = bytes.byteLength - 22; offset >= minOffset; offset -= 1) {
|
||||
if (bytes.readUInt32LE(offset) === EOCD_SIGNATURE) { endOffset = offset; break; }
|
||||
}
|
||||
if (endOffset < 0) throw new SkinRegistryError("The upload is not a valid ZIP package.", "SKIN_ZIP_INVALID");
|
||||
const disk = bytes.readUInt16LE(endOffset + 4);
|
||||
const centralDisk = bytes.readUInt16LE(endOffset + 6);
|
||||
const entriesOnDisk = bytes.readUInt16LE(endOffset + 8);
|
||||
const entryCount = bytes.readUInt16LE(endOffset + 10);
|
||||
const centralSize = bytes.readUInt32LE(endOffset + 12);
|
||||
const centralOffset = bytes.readUInt32LE(endOffset + 16);
|
||||
const commentLength = bytes.readUInt16LE(endOffset + 20);
|
||||
if (disk !== 0 || centralDisk !== 0 || entriesOnDisk !== entryCount || entryCount === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff || endOffset + 22 + commentLength !== bytes.byteLength) {
|
||||
throw new SkinRegistryError("Multi-disk and ZIP64 packages are not supported.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
if (!entryCount || entryCount > MAX_FILE_COUNT || centralOffset + centralSize !== endOffset) throw new SkinRegistryError("The ZIP directory is invalid or contains too many files.", "SKIN_FILE_COUNT");
|
||||
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const entries: SkinArchiveEntry[] = [];
|
||||
const seenPaths = new Set<string>();
|
||||
let offset = centralOffset;
|
||||
let totalExpanded = 0;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (offset + 46 > endOffset || bytes.readUInt32LE(offset) !== CENTRAL_SIGNATURE) throw new SkinRegistryError("The ZIP directory entry is invalid.", "SKIN_ZIP_INVALID");
|
||||
const madeBy = bytes.readUInt16LE(offset + 4);
|
||||
const flags = bytes.readUInt16LE(offset + 8);
|
||||
const compression = bytes.readUInt16LE(offset + 10);
|
||||
const crc = bytes.readUInt32LE(offset + 16);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 20);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 24);
|
||||
const nameLength = bytes.readUInt16LE(offset + 28);
|
||||
const extraLength = bytes.readUInt16LE(offset + 30);
|
||||
const fileCommentLength = bytes.readUInt16LE(offset + 32);
|
||||
const diskStart = bytes.readUInt16LE(offset + 34);
|
||||
const externalAttributes = bytes.readUInt32LE(offset + 38);
|
||||
const localOffset = bytes.readUInt32LE(offset + 42);
|
||||
const recordEnd = offset + 46 + nameLength + extraLength + fileCommentLength;
|
||||
if (recordEnd > endOffset || diskStart !== 0 || flags & ~0x0800 || (compression !== 0 && compression !== 8) || compressedSize === 0xffffffff || expandedSize === 0xffffffff || localOffset === 0xffffffff) {
|
||||
throw new SkinRegistryError("Encrypted, multi-disk, and unsupported ZIP entries are not allowed.", "SKIN_ZIP_FORMAT");
|
||||
}
|
||||
let entryPath: string;
|
||||
try { entryPath = decoder.decode(bytes.subarray(offset + 46, offset + 46 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (!(flags & 0x800) && /[^\x00-\x7f]/.test(entryPath)) throw new SkinRegistryError("Non-ASCII ZIP filenames must be encoded as UTF-8.", "SKIN_PATH_INVALID");
|
||||
if (!isSafePackagePath(entryPath, entryPath.endsWith("/"))) throw new SkinRegistryError("The package contains an unsafe path.", "SKIN_PATH_INVALID");
|
||||
const normalizedPath = entryPath.toLowerCase();
|
||||
if (seenPaths.has(normalizedPath)) throw new SkinRegistryError("The package contains duplicate or case-conflicting paths.", "SKIN_PATH_DUPLICATE");
|
||||
seenPaths.add(normalizedPath);
|
||||
const unixFileType = madeBy >> 8 === 3 ? (externalAttributes >>> 16) & 0xf000 : 0;
|
||||
if (unixFileType !== 0 && unixFileType !== 0x8000 && unixFileType !== 0x4000) throw new SkinRegistryError("Only regular files and directories are allowed in a skin package.", "SKIN_FILE_TYPE");
|
||||
const isDirectory = entryPath.endsWith("/");
|
||||
if ((unixFileType === 0x4000) !== isDirectory && unixFileType !== 0) throw new SkinRegistryError("ZIP file type does not match its path.", "SKIN_FILE_TYPE");
|
||||
if (isDirectory && (compressedSize !== 0 || expandedSize !== 0)) throw new SkinRegistryError("ZIP directory entries cannot contain data.", "SKIN_ZIP_INVALID");
|
||||
if (compression === 0 && compressedSize !== expandedSize) throw new SkinRegistryError("A stored ZIP entry has inconsistent sizes.", "SKIN_ZIP_INVALID");
|
||||
if (!isDirectory) {
|
||||
totalExpanded += expandedSize;
|
||||
if (totalExpanded > MAX_EXPANDED_BYTES) throw new SkinRegistryError("The expanded package exceeds 50 MiB.", "SKIN_EXPANDED_SIZE");
|
||||
if (expandedSize > 1024 * 1024 && expandedSize > Math.max(compressedSize, 1) * 250) throw new SkinRegistryError("The package has an abnormal compression ratio.", "SKIN_COMPRESSION_RATIO");
|
||||
}
|
||||
entries.push({ path: entryPath, compressedSize, expandedSize, compression, crc, localOffset, flags, isDirectory, unixFileType });
|
||||
offset = recordEnd;
|
||||
}
|
||||
if (offset !== centralOffset + centralSize) throw new SkinRegistryError("The ZIP directory length is inconsistent.", "SKIN_ZIP_INVALID");
|
||||
validateLocalEntries(bytes, entries, centralOffset, decoder);
|
||||
return entries;
|
||||
}
|
||||
|
||||
function validateLocalEntries(bytes: Buffer, entries: SkinArchiveEntry[], centralOffset: number, decoder: TextDecoder): void {
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
for (const entry of entries) {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > centralOffset || bytes.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = bytes.readUInt16LE(offset + 6);
|
||||
const compression = bytes.readUInt16LE(offset + 8);
|
||||
const crc = bytes.readUInt32LE(offset + 14);
|
||||
const compressedSize = bytes.readUInt32LE(offset + 18);
|
||||
const expandedSize = bytes.readUInt32LE(offset + 22);
|
||||
const nameLength = bytes.readUInt16LE(offset + 26);
|
||||
const extraLength = bytes.readUInt16LE(offset + 28);
|
||||
const headerEnd = offset + 30 + nameLength + extraLength;
|
||||
if (headerEnd > centralOffset || flags !== entry.flags || compression !== entry.compression || crc !== entry.crc || compressedSize !== entry.compressedSize || expandedSize !== entry.expandedSize) {
|
||||
throw new SkinRegistryError("ZIP local and central headers disagree.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
let localPath: string;
|
||||
try { localPath = decoder.decode(bytes.subarray(offset + 30, offset + 30 + nameLength)); }
|
||||
catch { throw new SkinRegistryError("ZIP filenames must be valid UTF-8.", "SKIN_PATH_INVALID"); }
|
||||
if (localPath !== entry.path) throw new SkinRegistryError("ZIP local and central filenames disagree.", "SKIN_ZIP_INVALID");
|
||||
const end = headerEnd + entry.compressedSize;
|
||||
if (end > centralOffset) throw new SkinRegistryError("A ZIP entry overlaps the central directory.", "SKIN_ZIP_INVALID");
|
||||
spans.push({ start: offset, end });
|
||||
}
|
||||
spans.sort((left, right) => left.start - right.start);
|
||||
for (let index = 1; index < spans.length; index += 1) {
|
||||
if (spans[index].start < spans[index - 1].end) throw new SkinRegistryError("ZIP local file entries overlap.", "SKIN_ZIP_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function extractEntry(archive: Buffer, entry: SkinArchiveEntry): Buffer {
|
||||
const offset = entry.localOffset;
|
||||
if (offset + 30 > archive.byteLength || archive.readUInt32LE(offset) !== LOCAL_SIGNATURE) throw new SkinRegistryError("A ZIP local file header is invalid.", "SKIN_ZIP_INVALID");
|
||||
const flags = archive.readUInt16LE(offset + 6);
|
||||
const compression = archive.readUInt16LE(offset + 8);
|
||||
const nameLength = archive.readUInt16LE(offset + 26);
|
||||
const extraLength = archive.readUInt16LE(offset + 28);
|
||||
if (flags !== entry.flags || compression !== entry.compression) throw new SkinRegistryError("ZIP headers disagree about file compression.", "SKIN_ZIP_INVALID");
|
||||
const dataStart = offset + 30 + nameLength + extraLength;
|
||||
const dataEnd = dataStart + entry.compressedSize;
|
||||
if (dataEnd > archive.byteLength) throw new SkinRegistryError("A ZIP entry extends past the archive.", "SKIN_ZIP_INVALID");
|
||||
const compressed = archive.subarray(dataStart, dataEnd);
|
||||
if (entry.compression === 0) return Buffer.from(compressed);
|
||||
try { return inflateRawSync(compressed, { maxOutputLength: entry.expandedSize + 1 }); }
|
||||
catch { throw new SkinRegistryError("A ZIP entry could not be safely decompressed.", "SKIN_ZIP_INVALID"); }
|
||||
}
|
||||
|
||||
function parseManifest(bytes: Buffer): ParsedSkinManifest {
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(decodeUtf8(bytes, "manifest.json is not valid UTF-8.")); }
|
||||
catch { throw new SkinRegistryError("manifest.json must contain valid JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SkinRegistryError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const value = raw as Record<string, unknown>;
|
||||
const read = (key: string, max: number): string => {
|
||||
const item = value[key];
|
||||
if (typeof item !== "string" || !item.trim() || item.length > max) throw new SkinRegistryError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return item.trim();
|
||||
};
|
||||
const id = read("id", 80);
|
||||
if (value.schemaVersion !== 1 || !isSafeSkinId(id)) throw new SkinRegistryError("The skin schema version or ID is unsupported.", "SKIN_SCHEMA_VERSION");
|
||||
const version = read("version", 32);
|
||||
const minAppVersion = read("minAppVersion", 32);
|
||||
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version) || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(minAppVersion)) throw new SkinRegistryError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
const entry = read("entry", 120);
|
||||
const readOptional = (key: string, max: number): string | undefined => value[key] == null ? undefined : read(key, max);
|
||||
const content = readOptional("content", 120);
|
||||
const preview = readOptional("preview", 120);
|
||||
for (const candidate of [entry, content, preview].filter((item): item is string => Boolean(item))) if (!isSafePackagePath(candidate)) throw new SkinRegistryError("The manifest references an unsafe path.", "SKIN_PATH_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !imageMime(preview))) throw new SkinRegistryError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
if (new Set(["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase())).size !== 2 + Number(Boolean(content)) + Number(Boolean(preview))) throw new SkinRegistryError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
const description = readOptional("description", 400);
|
||||
return { id, name: read("name", 80), version, author: read("author", 80), license: read("license", 80), minAppVersion, entry, ...(content ? { content } : {}), ...(preview ? { preview } : {}), ...(description ? { description } : {}) };
|
||||
}
|
||||
|
||||
function singleRootPrefix(paths: string[]): string {
|
||||
if (!paths.length) return "";
|
||||
const firstSlash = paths[0].indexOf("/");
|
||||
if (firstSlash < 1) return "";
|
||||
const prefix = paths[0].slice(0, firstSlash + 1);
|
||||
return paths.every((item) => item.startsWith(prefix)) ? prefix : "";
|
||||
}
|
||||
|
||||
function isSafePackagePath(value: string, allowDirectory = false): boolean {
|
||||
const candidate = allowDirectory ? value.slice(0, -1) : value;
|
||||
return Boolean(candidate) && !candidate.startsWith("/") && !candidate.includes("\\") && !candidate.includes("\0") && !/^[a-z]:/i.test(candidate)
|
||||
&& candidate.split("/").every((part) => Boolean(part) && part !== "." && part !== ".." && !part.includes(":"));
|
||||
}
|
||||
|
||||
function isSafeSkinId(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value) && !value.startsWith("builtin.");
|
||||
}
|
||||
|
||||
function imageMime(filename: string): string | null {
|
||||
switch (path.extname(filename).toLowerCase()) {
|
||||
case ".png": return "image/png";
|
||||
case ".jpg": case ".jpeg": return "image/jpeg";
|
||||
case ".webp": return "image/webp";
|
||||
case ".avif": return "image/avif";
|
||||
case ".gif": return "image/gif";
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeUtf8(bytes: Buffer, message: string): string {
|
||||
try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||
catch { throw new SkinRegistryError(message, "SKIN_ENCODING_INVALID"); }
|
||||
}
|
||||
|
||||
function isCatalogEntry(value: unknown): value is SkinCatalogEntry {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const item = value as Record<string, unknown>;
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
if (!isSafeSkinId(item.id) || !isShortText(item.name, 80) || !isShortText(item.author, 80) || !isShortText(item.license, 80)) return false;
|
||||
if (typeof item.version !== "string" || !semver.test(item.version) || typeof item.minAppVersion !== "string" || !semver.test(item.minAppVersion)) return false;
|
||||
if (!Number.isSafeInteger(item.installedAt) || (item.installedAt as number) < 0) return false;
|
||||
if (item.enabled !== undefined && typeof item.enabled !== "boolean") return false;
|
||||
if (item.description !== undefined && (typeof item.description !== "string" || item.description.length > 400)) return false;
|
||||
const hasPreview = item.previewUrl !== undefined || item.previewMimeType !== undefined;
|
||||
return !hasPreview || (item.previewUrl === `/api/skins/${item.id}/preview` && ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"].includes(String(item.previewMimeType)));
|
||||
}
|
||||
|
||||
function isShortText(value: unknown, limit: number): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.length <= limit;
|
||||
}
|
||||
|
||||
const crcTable = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < table.length; index += 1) {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
table[index] = value >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32(bytes: Buffer): number {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of bytes) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
export type WebSpeakErrorCode =
|
||||
| "invalid_target"
|
||||
| "invalid_nickname"
|
||||
| "nickname_in_use"
|
||||
| "host_not_found"
|
||||
| "unreachable"
|
||||
| "connection_refused"
|
||||
| "connection_reset"
|
||||
| "timeout"
|
||||
| "authentication_failed"
|
||||
| "channel_password_required"
|
||||
| "identity_security_level_too_low"
|
||||
| "identity_limit_reached"
|
||||
| "client_version_outdated"
|
||||
| "flooding"
|
||||
| "banned"
|
||||
| "kicked"
|
||||
| "server_shutting_down"
|
||||
| "server_full"
|
||||
| "invalid_parameter_size"
|
||||
| "connection_initialisation_failed"
|
||||
| "protocol_negotiation_failed"
|
||||
| "unknown";
|
||||
|
||||
export type ClientConnectionFailureCode =
|
||||
| "INVALID_TARGET"
|
||||
| "INVALID_NICKNAME"
|
||||
| "NICKNAME_IN_USE"
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "CONNECTION_REFUSED"
|
||||
| "CONNECTION_RESET"
|
||||
| "TIMEOUT"
|
||||
| "SERVER_PASSWORD_REQUIRED"
|
||||
| "INVALID_SERVER_PASSWORD"
|
||||
| "CHANNEL_PASSWORD_REQUIRED"
|
||||
| "IDENTITY_SECURITY_LEVEL_TOO_LOW"
|
||||
| "IDENTITY_LIMIT_REACHED"
|
||||
| "CLIENT_VERSION_OUTDATED"
|
||||
| "FLOOD_PROTECTION"
|
||||
| "BANNED"
|
||||
| "KICKED"
|
||||
| "SERVER_SHUTTING_DOWN"
|
||||
| "SERVER_FULL"
|
||||
| "INVALID_PARAMETER"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "CONNECTION_INITIALISATION_FAILED"
|
||||
| "CONNECTION_FAILED";
|
||||
|
||||
export interface TeamSpeakErrorDiagnostics {
|
||||
name?: string;
|
||||
code?: string;
|
||||
id?: string;
|
||||
serverMessage?: string;
|
||||
message?: string;
|
||||
syscall?: string;
|
||||
address?: string;
|
||||
port?: number | string;
|
||||
cause?: string;
|
||||
}
|
||||
|
||||
export class WebSpeakError extends Error {
|
||||
readonly code: WebSpeakErrorCode;
|
||||
readonly retryable: boolean;
|
||||
readonly cause?: unknown;
|
||||
readonly diagnostics: TeamSpeakErrorDiagnostics;
|
||||
|
||||
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown, diagnostics: TeamSpeakErrorDiagnostics = {}) {
|
||||
super(message);
|
||||
this.name = "WebSpeakError";
|
||||
this.code = code;
|
||||
this.retryable = retryable;
|
||||
this.cause = cause;
|
||||
this.diagnostics = diagnostics;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamSpeak server error ids (SDK `public_errors.h`, shared by TS3 and TS6) that
|
||||
* the gateway can name precisely. Ids that are absent on purpose fall through to
|
||||
* the text heuristics below and finally to `unknown`, which still carries the raw
|
||||
* server detail to the browser.
|
||||
*/
|
||||
export const TEAMSPEAK_SERVER_ERROR_IDS: Readonly<Record<string, WebSpeakErrorCode>> = {
|
||||
// Client (0x02xx): nickname, capacity, identity, password, version, flooding.
|
||||
"513": "nickname_in_use",
|
||||
"515": "server_full",
|
||||
"519": "identity_security_level_too_low",
|
||||
"520": "authentication_failed",
|
||||
"521": "identity_limit_reached",
|
||||
"522": "client_version_outdated",
|
||||
"524": "flooding",
|
||||
// Parameter (0x06xx). 1541 is the generic "invalid parameter size" error;
|
||||
// connection-specific classification decides whether that means a nickname.
|
||||
"1536": "invalid_parameter_size",
|
||||
"1537": "invalid_parameter_size",
|
||||
"1538": "invalid_parameter_size",
|
||||
"1539": "invalid_parameter_size",
|
||||
"1540": "invalid_parameter_size",
|
||||
"1541": "invalid_parameter_size",
|
||||
"1542": "invalid_parameter_size",
|
||||
"1543": "protocol_negotiation_failed",
|
||||
// Connection (0x07xx). Keep only ids whose official meaning matches the
|
||||
// normalized code; unrelated SDK operation errors must not be relabelled.
|
||||
"1797": "connection_initialisation_failed",
|
||||
"1798": "host_not_found",
|
||||
"1805": "protocol_negotiation_failed",
|
||||
"1806": "protocol_negotiation_failed",
|
||||
// Server (0x04xx).
|
||||
"1026": "server_shutting_down",
|
||||
"1027": "server_full",
|
||||
"1028": "authentication_failed",
|
||||
"781": "channel_password_required",
|
||||
// Accounting (0x0bxx): the slot and virtual-server limits both surface as a
|
||||
// full server from the user's point of view.
|
||||
"2816": "server_full",
|
||||
"2817": "server_full",
|
||||
// Ban (0x0dxx).
|
||||
"3329": "banned",
|
||||
"3330": "banned",
|
||||
"3331": "flooding",
|
||||
};
|
||||
|
||||
/**
|
||||
* Default (English) message per normalized code. The browser translates these
|
||||
* strings for zh/en/de, so keep them stable and never embed a raw server id here:
|
||||
* the raw detail travels separately in `diagnostics`.
|
||||
*/
|
||||
export const WEBSPEAK_ERROR_MESSAGES: Readonly<Record<WebSpeakErrorCode, string>> = {
|
||||
invalid_target: "The TeamSpeak server address is invalid",
|
||||
invalid_nickname: "TeamSpeak refused the nickname: it must be 3-30 characters long",
|
||||
nickname_in_use: "This nickname is already used by another user on the TeamSpeak server",
|
||||
host_not_found: "TeamSpeak server hostname could not be resolved",
|
||||
unreachable: "TeamSpeak server is unreachable",
|
||||
connection_refused: "TeamSpeak server refused the connection",
|
||||
connection_reset: "TeamSpeak connection was reset",
|
||||
timeout: "TeamSpeak connection timed out",
|
||||
authentication_failed: "TeamSpeak authentication failed",
|
||||
channel_password_required: "The TeamSpeak channel requires a password",
|
||||
identity_security_level_too_low: "This TeamSpeak identity's security level is below the server requirement",
|
||||
identity_limit_reached: "This TeamSpeak identity already holds the maximum number of connections",
|
||||
client_version_outdated: "The TeamSpeak server requires a newer client version",
|
||||
flooding: "The TeamSpeak server's flood protection refused the connection",
|
||||
banned: "You are banned from this TeamSpeak server",
|
||||
kicked: "You were kicked from the TeamSpeak server",
|
||||
server_shutting_down: "The TeamSpeak server is shutting down",
|
||||
connection_initialisation_failed: "The TeamSpeak server refused the connection during initialisation",
|
||||
server_full: "The TeamSpeak server is full",
|
||||
invalid_parameter_size: "TeamSpeak refused a parameter because its length or value is out of range",
|
||||
protocol_negotiation_failed: "TeamSpeak protocol negotiation failed",
|
||||
unknown: "TeamSpeak connection failed",
|
||||
};
|
||||
|
||||
// 不可重连的错误码集合:这些错误原样重连必然失败(如被封禁、昵称被占用等),
|
||||
// 集合与消息表相邻存放便于审计重连决策;unknown 保持不可重连,防止未映射的
|
||||
// 服务器拒绝演变成无限重连循环。
|
||||
/**
|
||||
* Codes for which reconnecting unchanged cannot succeed. Keeping the list next to
|
||||
* the messages makes the retry decision auditable; `unknown` stays non-retryable
|
||||
* so an unmapped server refusal can never turn into a reconnect loop.
|
||||
*/
|
||||
const NON_RETRYABLE_CODES: ReadonlySet<WebSpeakErrorCode> = new Set<WebSpeakErrorCode>([
|
||||
"invalid_target",
|
||||
"invalid_nickname",
|
||||
"nickname_in_use",
|
||||
"authentication_failed",
|
||||
"channel_password_required",
|
||||
"identity_security_level_too_low",
|
||||
"identity_limit_reached",
|
||||
"client_version_outdated",
|
||||
"banned",
|
||||
"kicked",
|
||||
"invalid_parameter_size",
|
||||
"connection_initialisation_failed",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnostics: TeamSpeakErrorDiagnostics): WebSpeakError {
|
||||
return new WebSpeakError(code, WEBSPEAK_ERROR_MESSAGES[code], !NON_RETRYABLE_CODES.has(code), cause, diagnostics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw TeamSpeak server error id to a normalized code. Accepts the
|
||||
* decimal form the SDK forwards (`err.id`, `id=515`) and the hex form used by the
|
||||
* official headers (`0x0203`), because both shapes show up in logs.
|
||||
*/
|
||||
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
|
||||
if (id === undefined || id === null) return null;
|
||||
const text = String(id).trim().toLocaleLowerCase();
|
||||
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
|
||||
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
|
||||
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
// 归一化入口:按「服务器错误ID → 关键词启发式 → 异常类名 → 传输层特征」的
|
||||
// 优先级,把 SDK/Node 抛出的原始错误收敛为带稳定错误码的 WebSpeakError。
|
||||
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
if (error instanceof WebSpeakError) return error;
|
||||
|
||||
const diagnostics = collectDiagnostics(error);
|
||||
const text = diagnosticText(error).toLocaleLowerCase();
|
||||
|
||||
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
|
||||
// keyword heuristic below. The inline scan keeps the `id=515` shape
|
||||
// working even when the SDK does not attach the id as a structured field.
|
||||
const inlineId = /\bid[\s=:]*(\d{3,5})\b/.exec(text)?.[1];
|
||||
const serverErrorCode =
|
||||
teamSpeakServerErrorCode(diagnostics.id) ?? teamSpeakServerErrorCode(diagnostics.code) ?? teamSpeakServerErrorCode(inlineId);
|
||||
if (serverErrorCode) return createTeamSpeakError(serverErrorCode, error, diagnostics);
|
||||
|
||||
// 2) Explicit refusals that arrive without a stable id. Every pattern stays
|
||||
// narrow on purpose: bare words such as "password", "network", "socket",
|
||||
// "crypto" or "denied" also appear in unrelated Teamspeak messages and used
|
||||
// to steal the classification from the real cause.
|
||||
if (/nickname.{0,20}(length|size)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_nickname", error, diagnostics);
|
||||
}
|
||||
if (/invalid[\s_-]*parameter[\s_-]*size|parameter.{0,20}(size|out of range)/.test(text)) {
|
||||
return createTeamSpeakError("invalid_parameter_size", error, diagnostics);
|
||||
}
|
||||
if (/nickname.{0,30}(in use|already (in )?use|taken|exists)|nickname_in_use/.test(text)) {
|
||||
return createTeamSpeakError("nickname_in_use", error, diagnostics);
|
||||
}
|
||||
if (/channel.{0,30}password|password.{0,30}channel|i_channel_password/.test(text)) {
|
||||
return createTeamSpeakError("channel_password_required", error, diagnostics);
|
||||
}
|
||||
if (/security ?level|insufficient security|could not validate identity/.test(text)) {
|
||||
return createTeamSpeakError("identity_security_level_too_low", error, diagnostics);
|
||||
}
|
||||
if (/too many clones|clone.{0,20}(limit|connected)|identity.{0,20}(limit|maximum|max).{0,20}connection/.test(text)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/version.{0,25}(outdated|out of date|too old|not allowed|unsupported)|outdated.{0,25}version/.test(text)) {
|
||||
return createTeamSpeakError("client_version_outdated", error, diagnostics);
|
||||
}
|
||||
if (/flood/.test(text)) {
|
||||
return createTeamSpeakError("flooding", error, diagnostics);
|
||||
}
|
||||
if (/\bban(ned)?\b|blacklist|you may retry in/.test(text)) {
|
||||
return createTeamSpeakError("banned", error, diagnostics);
|
||||
}
|
||||
if (/kicked/.test(text)) {
|
||||
return createTeamSpeakError("kicked", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,20}shut ?down|server_shutdown|server is shutting down/.test(text)) {
|
||||
return createTeamSpeakError("server_shutting_down", error, diagnostics);
|
||||
}
|
||||
if (/failed[\s_-]*connection[\s_-]*initiali[sz]ation|connection initiali[sz]ation failed|failed to (initialise|initialize) the connection/.test(text)) {
|
||||
return createTeamSpeakError("connection_initialisation_failed", error, diagnostics);
|
||||
}
|
||||
if (/server.{0,25}full|server is full|maximum (number of )?(clients|slots)|slot limit|client protocol limit/.test(text)) {
|
||||
return createTeamSpeakError("server_full", error, diagnostics);
|
||||
}
|
||||
if (/invalid (server )?password|wrong (server )?password|password (is )?(invalid|incorrect|wrong)|password required|i_server_password|authentication failed|not authorized|invalid credential|login (failed|refused)/.test(text)) {
|
||||
return createTeamSpeakError("authentication_failed", error, diagnostics);
|
||||
}
|
||||
|
||||
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
|
||||
// the class name before falling back to the message text.
|
||||
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
|
||||
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
if (/alreadyconnected/.test(errorName)) {
|
||||
return createTeamSpeakError("identity_limit_reached", error, diagnostics);
|
||||
}
|
||||
if (/timeout/.test(errorName)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
|
||||
// 4) Transport level failures reported by Node or the TLS layer.
|
||||
if (/enotfound|eai_again|host not found|name or service not known|getaddrinfo/.test(text)) {
|
||||
return createTeamSpeakError("host_not_found", error, diagnostics);
|
||||
}
|
||||
if (/econnrefused|connection refused/.test(text)) {
|
||||
return createTeamSpeakError("connection_refused", error, diagnostics);
|
||||
}
|
||||
if (/econnreset|econnaborted|connection reset|connection aborted|socket hang up/.test(text)) {
|
||||
return createTeamSpeakError("connection_reset", error, diagnostics);
|
||||
}
|
||||
if (/timeout|timed out|ack timeout|idle timeout|etimedout/.test(text)) {
|
||||
return createTeamSpeakError("timeout", error, diagnostics);
|
||||
}
|
||||
if (/ehostunreach|enetunreach|network is unreachable|no route to host|unable to connect|transport error|unexpected eof/.test(text)) {
|
||||
return createTeamSpeakError("unreachable", error, diagnostics);
|
||||
}
|
||||
if (/handshake|protocol|eax|crypto ?(init|handshake|setup)|init1|signature|license/.test(text)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
return createTeamSpeakError("unknown", error, diagnostics);
|
||||
}
|
||||
|
||||
export function clientConnectionFailureCode(error: WebSpeakError, serverPassword = ""): ClientConnectionFailureCode {
|
||||
if (error.code === "authentication_failed") {
|
||||
return serverPassword.trim() ? "INVALID_SERVER_PASSWORD" : "SERVER_PASSWORD_REQUIRED";
|
||||
}
|
||||
const mapping: Record<WebSpeakErrorCode, ClientConnectionFailureCode> = {
|
||||
invalid_target: "INVALID_TARGET",
|
||||
invalid_nickname: "INVALID_NICKNAME",
|
||||
nickname_in_use: "NICKNAME_IN_USE",
|
||||
host_not_found: "HOST_NOT_FOUND",
|
||||
unreachable: "UNREACHABLE",
|
||||
connection_refused: "CONNECTION_REFUSED",
|
||||
connection_reset: "CONNECTION_RESET",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: "SERVER_PASSWORD_REQUIRED",
|
||||
channel_password_required: "CHANNEL_PASSWORD_REQUIRED",
|
||||
identity_security_level_too_low: "IDENTITY_SECURITY_LEVEL_TOO_LOW",
|
||||
identity_limit_reached: "IDENTITY_LIMIT_REACHED",
|
||||
client_version_outdated: "CLIENT_VERSION_OUTDATED",
|
||||
flooding: "FLOOD_PROTECTION",
|
||||
banned: "BANNED",
|
||||
kicked: "KICKED",
|
||||
server_shutting_down: "SERVER_SHUTTING_DOWN",
|
||||
connection_initialisation_failed: "CONNECTION_INITIALISATION_FAILED",
|
||||
server_full: "SERVER_FULL",
|
||||
// During the initial connect handshake this generic TeamSpeak id is most
|
||||
// commonly emitted for an invalid nickname length/format. Operation errors
|
||||
// still retain the generic invalid_parameter_size message.
|
||||
invalid_parameter_size: "INVALID_NICKNAME",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
unknown: "CONNECTION_FAILED",
|
||||
};
|
||||
return mapping[error.code];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the SDK `kicked` event. TeamSpeak reports a kick/ban as a
|
||||
* `clientleftview` whose reason id is 4 (kicked) or 5 (kicked with ban) and whose
|
||||
* `reasonMsg` is written by the admin, e.g. "Slow down!" or "you may retry in
|
||||
* 300 seconds". Before this helper existed the reason text was dropped and the
|
||||
* browser only showed a generic connection failure, which is exactly the
|
||||
* experience this translation layer removes. The ban/kick split prefers the
|
||||
* server text and falls back to reason id 5.
|
||||
*/
|
||||
export function normalizeTeamSpeakKickedReason(reasonMsg: unknown, reasonId?: unknown): WebSpeakError {
|
||||
const text = typeof reasonMsg === "string" ? reasonMsg.trim() : "";
|
||||
const numericReasonId = typeof reasonId === "number" ? reasonId : Number(reasonId);
|
||||
const isBan = /\bban(ned)?\b|blacklist|you may retry in/i.test(text) || numericReasonId === 5;
|
||||
const diagnostics: TeamSpeakErrorDiagnostics = { name: isBan ? "TeamSpeakBan" : "TeamSpeakKick" };
|
||||
if (text) diagnostics.serverMessage = text;
|
||||
if (Number.isFinite(numericReasonId)) diagnostics.id = String(numericReasonId);
|
||||
return createTeamSpeakError(isBan ? "banned" : "kicked", reasonMsg, diagnostics);
|
||||
}
|
||||
|
||||
/** Format useful SDK/Node details for a safe operational log field. */
|
||||
export function describeTeamSpeakError(error: WebSpeakError): string {
|
||||
const details = error.diagnostics;
|
||||
const parts = [
|
||||
details.name,
|
||||
details.code,
|
||||
details.id ? `id=${details.id}` : "",
|
||||
details.serverMessage,
|
||||
details.syscall,
|
||||
details.address ? `address=${details.address}` : "",
|
||||
details.port !== undefined ? `port=${details.port}` : "",
|
||||
details.cause,
|
||||
details.message,
|
||||
].filter(Boolean);
|
||||
return parts.length ? parts.join("; ") : error.message;
|
||||
}
|
||||
|
||||
function diagnosticText(error: unknown): string {
|
||||
const values: string[] = [];
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) values.push(current.name, current.message);
|
||||
else values.push(String(current));
|
||||
if (typeof current === "object") {
|
||||
const candidate = current as { code?: unknown; id?: unknown; serverMessage?: unknown; cause?: unknown };
|
||||
for (const value of [candidate.code, candidate.id, candidate.serverMessage]) if (value !== undefined) values.push(String(value));
|
||||
current = candidate.cause;
|
||||
} else break;
|
||||
}
|
||||
return values.join(" ");
|
||||
}
|
||||
|
||||
function collectDiagnostics(error: unknown): TeamSpeakErrorDiagnostics {
|
||||
const result: TeamSpeakErrorDiagnostics = {};
|
||||
let current: unknown = error;
|
||||
const seen = new Set<unknown>();
|
||||
for (let depth = 0; depth < 4 && current && !seen.has(current); depth += 1) {
|
||||
seen.add(current);
|
||||
if (current instanceof Error) {
|
||||
result.name ??= current.name;
|
||||
result.message ??= current.message;
|
||||
const errorRecord = current as Error & Record<string, unknown>;
|
||||
if (typeof errorRecord.code === "string" || typeof errorRecord.code === "number") result.code ??= String(errorRecord.code);
|
||||
if (typeof errorRecord.id === "string" || typeof errorRecord.id === "number") result.id ??= String(errorRecord.id);
|
||||
if (typeof errorRecord.serverMessage === "string") result.serverMessage ??= errorRecord.serverMessage;
|
||||
if (typeof errorRecord.syscall === "string") result.syscall ??= errorRecord.syscall;
|
||||
if (typeof errorRecord.address === "string") result.address ??= errorRecord.address;
|
||||
if (typeof errorRecord.port === "string" || typeof errorRecord.port === "number") result.port ??= errorRecord.port;
|
||||
const cause = current.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
if (typeof current !== "object") { result.cause ??= String(current); break; }
|
||||
const candidate = current as Record<string, unknown>;
|
||||
if (typeof candidate.name === "string") result.name ??= candidate.name;
|
||||
if (typeof candidate.code === "string" || typeof candidate.code === "number") result.code ??= String(candidate.code);
|
||||
if (typeof candidate.id === "string" || typeof candidate.id === "number") result.id ??= String(candidate.id);
|
||||
if (typeof candidate.serverMessage === "string") result.serverMessage ??= candidate.serverMessage;
|
||||
if (typeof candidate.message === "string") result.message ??= candidate.message;
|
||||
if (typeof candidate.syscall === "string") result.syscall ??= candidate.syscall;
|
||||
if (typeof candidate.address === "string") result.address ??= candidate.address;
|
||||
if (typeof candidate.port === "string" || typeof candidate.port === "number") result.port ??= candidate.port;
|
||||
const cause = candidate.cause;
|
||||
if (cause && cause !== current) { current = cause; continue; }
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,41 +1,77 @@
|
||||
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 { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
|
||||
import { SkinRegistry } from "./admin/skin-registry.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();
|
||||
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig(CONFIG_PATH);
|
||||
saveConfig(CONFIG_PATH, config);
|
||||
|
||||
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
|
||||
await runRelayMode();
|
||||
return;
|
||||
}
|
||||
const [{ createLogger }, { createWebServer }, { APP_PORT }, { WebSpeakDatabase }, { loadOrCreateMasterSecret }, { AdminService }, { JoinTicketStore }] = await Promise.all([
|
||||
import("./logger.js"),
|
||||
import("./server/server.js"),
|
||||
import("./constants.js"),
|
||||
import("./persistence/database.js"),
|
||||
import("./security/master-secret.js"),
|
||||
import("./admin/admin-service.js"),
|
||||
import("./server/join-ticket.js"),
|
||||
]);
|
||||
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(),
|
||||
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
|
||||
// The public gateway only uses the relay configuration explicitly
|
||||
// saved in the admin console. Environment variables belong to the
|
||||
// standalone relay process and must never make the relay option appear
|
||||
// in the visitor UI after an administrator disables it.
|
||||
acceleration: () => adminService.getAccelerationRelayOptions(),
|
||||
accelerationName: () => adminService.getAccelerationRelayName(),
|
||||
},
|
||||
adminService,
|
||||
skinRegistry: new SkinRegistry(path.join(DATA_DIR, "skins")),
|
||||
logger,
|
||||
nextVisitorNumber: () => database.nextVisitorNumber(),
|
||||
visitorCount: () => database.getVisitorCount(),
|
||||
});
|
||||
|
||||
await webServer.start();
|
||||
@@ -44,12 +80,68 @@ 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"));
|
||||
}
|
||||
|
||||
async function runRelayMode(): Promise<void> {
|
||||
const token = (process.env.WEBSPEAK_RELAY_TOKEN || process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN)?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_RELAY_TOKEN is required in relay mode");
|
||||
const host = (process.env.WEBSPEAK_RELAY_HOST || process.env.WEBSPEAK_ACCELERATION_RELAY_HOST)?.trim() || "0.0.0.0";
|
||||
const port = parsePort(process.env.WEBSPEAK_RELAY_PORT || process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087);
|
||||
const allowPrivate = parseBoolean(process.env.WEBSPEAK_RELAY_ALLOW_PRIVATE || process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE);
|
||||
const server = await createAccelerationRelayServer({ host, port, token, allowPrivate });
|
||||
console.log(`WebSpeak relay mode listening on ${server.host}:${server.port}`);
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid relay port");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
|
||||
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
|
||||
const raw = value?.trim();
|
||||
if (!raw) return normalizeScreenShareIceServers();
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined);
|
||||
} catch {
|
||||
// A simple comma/space-separated list is convenient for STUN-only setups.
|
||||
return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import express from "express";
|
||||
import { createServer } from "node:http";
|
||||
import path from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { createLogger } from "../logger.js";
|
||||
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore } from "../server/join-ticket.js";
|
||||
import { JoinRateLimiter } from "../server/join-rate-limit.js";
|
||||
import { VoiceBridge } from "../server/voice-bridge.js";
|
||||
import { DEFAULT_WELCOME_TEXTS } from "../site-copy.js";
|
||||
|
||||
const port = Number(process.env.WEBSPEAK_MOBILE_PORT || 3040);
|
||||
const host = "127.0.0.1";
|
||||
const dataDir = process.env.WEBSPEAK_DATA_DIR;
|
||||
const staticDir = process.env.WEBSPEAK_MOBILE_WWW;
|
||||
if (!dataDir || !staticDir || !existsSync(path.join(staticDir, "index.html"))) {
|
||||
throw new Error("Android gateway data or web assets are missing");
|
||||
}
|
||||
|
||||
const logger = createLogger(path.join(dataDir, "logs"));
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
const joinTickets = new JoinTicketStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const voiceBridge = new VoiceBridge({ joinTickets, webRtc: { enabled: false } }, logger);
|
||||
|
||||
app.use(express.json({ limit: "100kb" }));
|
||||
app.get("/health", (_request, response) => response.json({ status: "ok", engine: "webspeak-android" }));
|
||||
app.get("/api/health", (_request, response) => response.json({ status: "ok", engine: "webspeak-android" }));
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json({
|
||||
version: process.env.WEBSPEAK_VERSION ?? "0.2.6",
|
||||
initialized: true,
|
||||
siteName: "WebSpeak",
|
||||
welcomeText: DEFAULT_WELCOME_TEXTS.zh,
|
||||
welcomeTextEn: DEFAULT_WELCOME_TEXTS.en,
|
||||
welcomeTexts: DEFAULT_WELCOME_TEXTS,
|
||||
accessMode: "open",
|
||||
target: "",
|
||||
targetPrefillBlocked: false,
|
||||
accelerationAvailable: false,
|
||||
accelerationRelays: [],
|
||||
mobile: true,
|
||||
});
|
||||
});
|
||||
app.get("/api/skins", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.json({ skins: [], defaultSkinId: "builtin.light" });
|
||||
});
|
||||
app.post("/api/join-ticket", (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 (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
|
||||
return;
|
||||
}
|
||||
const body = request.body && typeof request.body === "object" && !Array.isArray(request.body)
|
||||
? request.body as Record<string, unknown>
|
||||
: {};
|
||||
const nickname = typeof body.nickname === "string" ? body.nickname.trim().slice(0, 30) : "";
|
||||
const channel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
|
||||
const serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
if (!nickname) {
|
||||
response.status(400).json({ ok: false, code: "INVALID_NICKNAME" });
|
||||
return;
|
||||
}
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(typeof body.target === "string" ? body.target : "");
|
||||
} catch {
|
||||
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
|
||||
return;
|
||||
}
|
||||
let identity: string | undefined;
|
||||
if (typeof body.identity === "string" && body.identity.length <= 8192) {
|
||||
try {
|
||||
identityFromString(body.identity);
|
||||
identity = body.identity;
|
||||
} catch {
|
||||
// Corrupt local identity should not prevent an ephemeral join.
|
||||
}
|
||||
}
|
||||
const ticket = 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(express.static(staticDir));
|
||||
app.get(/^(?!\/api|\/ws)/, (_request, response) => response.sendFile(path.join(staticDir, "index.html")));
|
||||
voiceBridge.attach(server);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, host, () => {
|
||||
server.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
logger.info({ host, port, dataDir }, "Android gateway started");
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
await voiceBridge.shutdown();
|
||||
server.close();
|
||||
}
|
||||
process.once("SIGTERM", () => { void shutdown(); });
|
||||
process.once("SIGINT", () => { void shutdown(); });
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const requestHost = request.header("host");
|
||||
try {
|
||||
return Boolean(origin && requestHost && new URL(origin).host === requestHost);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
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 = 8;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn: string;
|
||||
welcomeTextDe: string;
|
||||
welcomeTextRu: string;
|
||||
welcomeTextJa: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
detectedProtocol: TeamSpeakProtocol | null;
|
||||
lastTestAt: string | null;
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost: string;
|
||||
webRtcIpv6Enabled: boolean;
|
||||
webRtcStunServer: string;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost?: string;
|
||||
webRtcIpv6Enabled?: boolean;
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relayConfigured: boolean;
|
||||
relayEnabled: boolean;
|
||||
relayName: string;
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
relayTokenEncrypted: string | null;
|
||||
}
|
||||
|
||||
export interface PersistedRelayNode {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
tokenEncrypted: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
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;
|
||||
welcome_text_en: string;
|
||||
welcome_text_de: string;
|
||||
welcome_text_ru: string;
|
||||
welcome_text_ja: 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_ipv6_enabled: number;
|
||||
webrtc_stun_server: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
relay_configured: number;
|
||||
relay_enabled: number;
|
||||
relay_name: string;
|
||||
relay_host: string;
|
||||
relay_port: number;
|
||||
relay_token_encrypted: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface RelayNodeRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: number;
|
||||
host: string;
|
||||
port: number;
|
||||
token_encrypted: string | null;
|
||||
created_at: string;
|
||||
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,
|
||||
welcomeTextEn: row.welcome_text_en,
|
||||
welcomeTextDe: row.welcome_text_de,
|
||||
welcomeTextRu: row.welcome_text_ru,
|
||||
welcomeTextJa: row.welcome_text_ja,
|
||||
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,
|
||||
webRtcPublicHost: row.webrtc_public_host,
|
||||
webRtcIpv6Enabled: row.webrtc_ipv6_enabled === 1,
|
||||
webRtcStunServer: row.webrtc_stun_server,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
relayEnabled: row.relay_enabled === 1,
|
||||
relayName: row.relay_name,
|
||||
relayHost: row.relay_host,
|
||||
relayPort: row.relay_port,
|
||||
relayTokenEncrypted: row.relay_token_encrypted,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
listRelayNodes(): PersistedRelayNode[] {
|
||||
const rows = this.database.prepare(
|
||||
"SELECT * FROM relay_nodes ORDER BY created_at ASC, id ASC",
|
||||
).all() as RelayNodeRow[];
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
enabled: row.enabled === 1,
|
||||
host: row.host,
|
||||
port: row.port,
|
||||
tokenEncrypted: row.token_encrypted,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}));
|
||||
}
|
||||
|
||||
replaceRelayNodes(nodes: Array<Omit<PersistedRelayNode, "createdAt" | "updatedAt"> & { createdAt?: string; updatedAt?: string }>): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.database.exec("DELETE FROM relay_nodes");
|
||||
const insert = this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const node of nodes) {
|
||||
insert.run(
|
||||
node.id,
|
||||
node.name,
|
||||
node.enabled ? 1 : 0,
|
||||
node.host,
|
||||
node.port,
|
||||
node.tokenEncrypted,
|
||||
node.createdAt ?? now,
|
||||
node.updatedAt ?? now,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
nextVisitorNumber(): number {
|
||||
let nextNumber = 1;
|
||||
this.transaction(() => {
|
||||
const currentValue = this.getMeta("visitor_count");
|
||||
const current = currentValue ? Number.parseInt(currentValue, 10) : 0;
|
||||
nextNumber = Number.isSafeInteger(current) && current >= 0 && current < Number.MAX_SAFE_INTEGER
|
||||
? current + 1
|
||||
: 1;
|
||||
this.setMeta("visitor_count", String(nextNumber));
|
||||
});
|
||||
return nextNumber;
|
||||
}
|
||||
|
||||
getVisitorCount(): number {
|
||||
const value = this.getMeta("visitor_count");
|
||||
const count = value ? Number.parseInt(value, 10) : 0;
|
||||
return Number.isSafeInteger(count) && count >= 0 ? count : 0;
|
||||
}
|
||||
|
||||
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");
|
||||
});
|
||||
version = 3;
|
||||
}
|
||||
if (version === 3) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 4");
|
||||
});
|
||||
version = 4;
|
||||
}
|
||||
if (version === 4) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN relay_configured INTEGER NOT NULL DEFAULT 0 CHECK (relay_configured IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_enabled INTEGER NOT NULL DEFAULT 0 CHECK (relay_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN relay_name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_host TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN relay_port INTEGER NOT NULL DEFAULT 39087 CHECK (relay_port BETWEEN 1 AND 65535);
|
||||
ALTER TABLE settings ADD COLUMN relay_token_encrypted TEXT;
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 5");
|
||||
});
|
||||
version = 5;
|
||||
}
|
||||
if (version === 5) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE relay_nodes (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
|
||||
token_encrypted TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX relay_nodes_enabled_idx ON relay_nodes(enabled);
|
||||
`);
|
||||
const legacy = this.database.prepare(
|
||||
`SELECT relay_configured, relay_enabled, relay_name, relay_host, relay_port, relay_token_encrypted
|
||||
FROM settings WHERE id = 1`,
|
||||
).get() as {
|
||||
relay_configured?: number;
|
||||
relay_enabled?: number;
|
||||
relay_name?: string;
|
||||
relay_host?: string;
|
||||
relay_port?: number;
|
||||
relay_token_encrypted?: string | null;
|
||||
} | undefined;
|
||||
if (legacy?.relay_configured === 1 && legacy.relay_host && legacy.relay_token_encrypted) {
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
||||
VALUES ('relay-default', ?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(
|
||||
legacy.relay_name || "中继加速",
|
||||
legacy.relay_enabled === 1 ? 1 : 0,
|
||||
legacy.relay_host,
|
||||
legacy.relay_port || 39087,
|
||||
legacy.relay_token_encrypted,
|
||||
now,
|
||||
now,
|
||||
);
|
||||
}
|
||||
this.database.exec("PRAGMA user_version = 6");
|
||||
});
|
||||
version = 6;
|
||||
}
|
||||
if (version === 6) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_de TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ru TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE settings ADD COLUMN welcome_text_ja TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
version = 7;
|
||||
}
|
||||
if (version === 7) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN webrtc_ipv6_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_ipv6_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN webrtc_stun_server TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 8");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.welcomeTextEn ?? "",
|
||||
settings.welcomeTextDe ?? "",
|
||||
settings.welcomeTextRu ?? "",
|
||||
settings.welcomeTextJa ?? "",
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcPublicHost ?? "",
|
||||
settings.webRtcIpv6Enabled ? 1 : 0,
|
||||
settings.webRtcStunServer ?? "",
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
settings.relayEnabled ? 1 : 0,
|
||||
settings.relayName,
|
||||
settings.relayHost,
|
||||
settings.relayPort,
|
||||
settings.relayTokenEncrypted,
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
|
||||
|
||||
const token = process.env.WEBSPEAK_ACCELERATION_RELAY_TOKEN?.trim();
|
||||
if (!token) throw new Error("WEBSPEAK_ACCELERATION_RELAY_TOKEN is required");
|
||||
|
||||
const server = await createAccelerationRelayServer({
|
||||
host: process.env.WEBSPEAK_ACCELERATION_RELAY_HOST?.trim() || "0.0.0.0",
|
||||
port: parsePort(process.env.WEBSPEAK_ACCELERATION_RELAY_PORT, 39087),
|
||||
token,
|
||||
allowPrivate: parseBoolean(process.env.WEBSPEAK_ACCELERATION_RELAY_ALLOW_PRIVATE),
|
||||
});
|
||||
|
||||
console.log(`WebSpeak acceleration relay listening on ${server.host}:${server.port}`);
|
||||
|
||||
const shutdown = (): void => {
|
||||
server.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGINT", shutdown);
|
||||
process.once("SIGTERM", shutdown);
|
||||
|
||||
function parsePort(value: string | undefined, fallback: number): number {
|
||||
const port = value ? Number(value) : fallback;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid WEBSPEAK_ACCELERATION_RELAY_PORT");
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined): boolean {
|
||||
return value === "1" || value?.toLowerCase() === "true";
|
||||
}
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isSafeOpenTargetForPrefill } from "./open-target-policy.js";
|
||||
|
||||
test("open-mode target prefill follows the same allow/deny result as the join policy", async () => {
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "198.51.100.24", port: 9987 }, {
|
||||
resolveTarget: async (target) => target,
|
||||
}), true);
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "teamspeak", port: 9987 }, {
|
||||
resolveTarget: async () => { throw new Error("private or unresolved target"); },
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("open-mode target prefill fails closed when DNS validation stalls", async () => {
|
||||
const result = await isSafeOpenTargetForPrefill({ host: "internal.example", port: 9987 }, {
|
||||
timeoutMs: 10,
|
||||
resolveTarget: async () => new Promise(() => undefined),
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
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 };
|
||||
}
|
||||
|
||||
/** A bounded, non-authoritative check used only to avoid pre-filling a target that open mode will reject. */
|
||||
export async function isSafeOpenTargetForPrefill(
|
||||
target: TeamSpeakTarget,
|
||||
options: { timeoutMs?: number; resolveTarget?: (target: TeamSpeakTarget) => Promise<TeamSpeakTarget> } = {},
|
||||
): Promise<boolean> {
|
||||
const timeoutMs = options.timeoutMs ?? 1_000;
|
||||
const resolveTarget = options.resolveTarget ?? resolveSafeOpenTarget;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
Promise.resolve().then(() => resolveTarget(target)).then(() => true, () => false),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { isIP } from "node:net";
|
||||
import { lookup } from "node:dns/promises";
|
||||
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const VERSION = 1;
|
||||
const HEADER_SIZE = 34;
|
||||
const MAX_PAYLOAD_SIZE = 60_000;
|
||||
export const DEFAULT_ACCELERATION_RELAY_PORT = 39087;
|
||||
|
||||
const enum FrameType {
|
||||
OPEN = 1,
|
||||
OPEN_OK = 2,
|
||||
OPEN_ERR = 3,
|
||||
DATA = 4,
|
||||
CLOSE = 5,
|
||||
PING = 6,
|
||||
PONG = 7,
|
||||
}
|
||||
|
||||
export interface AccelerationRelayOptions {
|
||||
relayHost: string;
|
||||
relayPort: number;
|
||||
token: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface ConfiguredAccelerationRelay extends AccelerationRelayOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AccelerationTarget {
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
export interface AccelerationRelayClient {
|
||||
readonly localHost: string;
|
||||
readonly localPort: number;
|
||||
readonly sessionId: number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface Frame {
|
||||
type: FrameType;
|
||||
sessionId: number;
|
||||
sequence: number;
|
||||
payload: Buffer;
|
||||
auth: Buffer;
|
||||
raw: Buffer;
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayClient(
|
||||
options: AccelerationRelayOptions & AccelerationTarget,
|
||||
): Promise<AccelerationRelayClient> {
|
||||
validateRelayOptions(options);
|
||||
const relayFamily = isIP(options.relayHost) === 6 ? "udp6" : "udp4";
|
||||
const relaySocket = createSocket(relayFamily);
|
||||
const localSocket = createSocket("udp4");
|
||||
const sessionId = randomSessionId();
|
||||
let sequence = 1;
|
||||
let ready = false;
|
||||
let closed = false;
|
||||
let resolveReady: () => void = () => undefined;
|
||||
let rejectReady: (error: Error) => void = () => undefined;
|
||||
let keepAlive: ReturnType<typeof setInterval> | null = null;
|
||||
const readyPromise = new Promise<void>((resolve, reject) => {
|
||||
resolveReady = resolve;
|
||||
rejectReady = reject;
|
||||
});
|
||||
|
||||
const sendFrame = (type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
const packet = encodeFrame(type, sessionId, sequence++, payload, options.token);
|
||||
try {
|
||||
relaySocket.send(packet, options.relayPort, options.relayHost);
|
||||
} catch (error) {
|
||||
if (!ready) rejectReady(asError(error));
|
||||
}
|
||||
};
|
||||
|
||||
const closeSockets = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (keepAlive) clearInterval(keepAlive);
|
||||
keepAlive = null;
|
||||
try { relaySocket.close(); } catch { /* already closed */ }
|
||||
try { localSocket.close(); } catch { /* already closed */ }
|
||||
};
|
||||
|
||||
const onSocketError = (error: Error): void => {
|
||||
if (!ready) rejectReady(error);
|
||||
closeSockets();
|
||||
};
|
||||
relaySocket.once("error", onSocketError);
|
||||
localSocket.once("error", onSocketError);
|
||||
|
||||
let peer: { address: string; port: number } | null = null;
|
||||
relaySocket.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId || !verifyFrame(frame, options.token)) return;
|
||||
if (frame.type === FrameType.OPEN_OK) {
|
||||
if (ready) return;
|
||||
ready = true;
|
||||
keepAlive = setInterval(() => sendFrame(FrameType.PING), 10_000);
|
||||
keepAlive.unref?.();
|
||||
resolveReady();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.OPEN_ERR) {
|
||||
const detail = parseJson(frame.payload);
|
||||
rejectReady(new Error(typeof detail?.code === "string" ? detail.code : "ACCELERATION_OPEN_FAILED"));
|
||||
closeSockets();
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.DATA && peer) {
|
||||
try { localSocket.send(frame.payload, peer.port, peer.address); } catch { /* peer is gone */ }
|
||||
return;
|
||||
}
|
||||
if (frame.type === FrameType.CLOSE) closeSockets();
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
bindSocket(relaySocket, relayFamily === "udp6" ? "::" : "0.0.0.0"),
|
||||
bindSocket(localSocket, "127.0.0.1"),
|
||||
]);
|
||||
|
||||
localSocket.on("message", (payload, rinfo) => {
|
||||
if (closed) return;
|
||||
peer = { address: rinfo.address, port: rinfo.port };
|
||||
if (ready) sendFrame(FrameType.DATA, payload);
|
||||
});
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
rejectReady(new Error("ACCELERATION_OPEN_TIMEOUT"));
|
||||
closeSockets();
|
||||
}, options.timeoutMs ?? 15_000);
|
||||
timer.unref?.();
|
||||
sendFrame(FrameType.OPEN, jsonPayload({ targetHost: options.host, targetPort: options.port }));
|
||||
try {
|
||||
await readyPromise;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
const address = localSocket.address();
|
||||
return {
|
||||
localHost: "127.0.0.1",
|
||||
localPort: typeof address === "object" ? address.port : 0,
|
||||
sessionId,
|
||||
close(): void {
|
||||
if (!closed && ready) {
|
||||
try { sendFrame(FrameType.CLOSE); } catch { /* best effort */ }
|
||||
}
|
||||
closeSockets();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createAccelerationRelayServer({
|
||||
host = "0.0.0.0",
|
||||
port = 39087,
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
}: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
token: string;
|
||||
allowPrivate?: boolean;
|
||||
idleTimeoutMs?: number;
|
||||
}): Promise<{ host: string; port: number; close(): void }> {
|
||||
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
|
||||
const sessions = new Map<number, RelaySession>();
|
||||
let closed = false;
|
||||
|
||||
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
try { socket.send(encodeFrame(type, session.id, session.outSequence++, payload, token), session.client.port, session.client.address); } catch { /* client is gone */ }
|
||||
};
|
||||
const cleanup = (session: RelaySession): void => {
|
||||
if (session.closed) return;
|
||||
session.closed = true;
|
||||
sessions.delete(session.id);
|
||||
session.targetSocket?.close();
|
||||
};
|
||||
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
const client = { address: rinfo.address, port: rinfo.port };
|
||||
if (frame.type === FrameType.OPEN) {
|
||||
void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup);
|
||||
return;
|
||||
}
|
||||
const session = sessions.get(frame.sessionId);
|
||||
if (!session || session.client.address !== rinfo.address || session.client.port !== rinfo.port) return;
|
||||
session.lastActivity = Date.now();
|
||||
if (frame.type === FrameType.DATA && session.targetSocket) session.targetSocket.send(frame.payload);
|
||||
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
|
||||
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
|
||||
});
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref?.();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
close(): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface RelaySession {
|
||||
id: number;
|
||||
client: { address: string; port: number };
|
||||
targetSocket: ReturnType<typeof createSocket> | null;
|
||||
outSequence: number;
|
||||
lastActivity: number;
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
async function openRelaySession(
|
||||
frame: Frame,
|
||||
client: { address: string; port: number },
|
||||
socket: ReturnType<typeof createSocket>,
|
||||
sessions: Map<number, RelaySession>,
|
||||
token: string,
|
||||
allowPrivate: boolean,
|
||||
send: (session: RelaySession, type: FrameType, payload?: Buffer) => void,
|
||||
cleanup: (session: RelaySession) => void,
|
||||
): Promise<void> {
|
||||
const request = parseJson(frame.payload);
|
||||
if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return;
|
||||
const targetPort = request.targetPort as number;
|
||||
if (!allowPrivate && isPrivateAddress(request.targetHost)) {
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address);
|
||||
return;
|
||||
}
|
||||
const previous = sessions.get(frame.sessionId);
|
||||
if (previous) cleanup(previous);
|
||||
const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false };
|
||||
sessions.set(session.id, session);
|
||||
try {
|
||||
const target = await resolveTarget(request.targetHost);
|
||||
const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4");
|
||||
session.targetSocket = targetSocket;
|
||||
targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); });
|
||||
targetSocket.on("error", (error) => { if (!session.closed) send(session, FrameType.OPEN_ERR, jsonPayload({ code: "TARGET_SOCKET_ERROR", message: error.message })); cleanup(session); });
|
||||
targetSocket.connect(targetPort, target.host, () => {
|
||||
session.lastActivity = Date.now();
|
||||
send(session, FrameType.OPEN_OK, jsonPayload({ targetHost: target.host, targetPort }));
|
||||
});
|
||||
} catch (error) {
|
||||
cleanup(session);
|
||||
socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "TARGET_OPEN_FAILED", message: asError(error).message }), token), client.port, client.address);
|
||||
}
|
||||
}
|
||||
|
||||
function validateRelayOptions(options: AccelerationRelayOptions & AccelerationTarget): void {
|
||||
if (!options.relayHost || !Number.isInteger(options.relayPort) || options.relayPort < 1 || options.relayPort > 65535) throw new Error("Invalid acceleration relay endpoint");
|
||||
if (!options.host || !Number.isInteger(options.port) || options.port < 1 || options.port > 65535) throw new Error("Invalid accelerated TeamSpeak target");
|
||||
if (!options.token || options.token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
}
|
||||
|
||||
function bindSocket(socket: ReturnType<typeof createSocket>, address: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind(0, address);
|
||||
});
|
||||
}
|
||||
|
||||
function encodeFrame(type: FrameType, sessionId: number, sequence: number, payload: Buffer, token: string): Buffer {
|
||||
if (payload.length > MAX_PAYLOAD_SIZE) throw new Error("Acceleration relay payload is too large");
|
||||
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = VERSION;
|
||||
frame[5] = type;
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(sequence >>> 0, 12);
|
||||
frame.writeUInt16BE(payload.length, 16);
|
||||
payload.copy(frame, HEADER_SIZE);
|
||||
signFrame(frame, payload, token).copy(frame, 18);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function decodeFrame(packet: Buffer): Frame | null {
|
||||
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== VERSION) return null;
|
||||
const payloadLength = packet.readUInt16BE(16);
|
||||
if (packet.length !== HEADER_SIZE + payloadLength || payloadLength > MAX_PAYLOAD_SIZE) return null;
|
||||
return { type: packet[5] as FrameType, sessionId: packet.readUInt32BE(8), sequence: packet.readUInt32BE(12), payload: packet.subarray(HEADER_SIZE), auth: packet.subarray(18, HEADER_SIZE), raw: packet };
|
||||
}
|
||||
|
||||
function verifyFrame(frame: Frame, token: string): boolean {
|
||||
const expected = signFrame(frame.raw, frame.payload, token);
|
||||
return expected.length === frame.auth.length && timingSafeEqual(expected, frame.auth);
|
||||
}
|
||||
|
||||
function signFrame(frame: Buffer, payload: Buffer, token: string): Buffer {
|
||||
return createHmac("sha256", Buffer.from(token, "utf8")).update(frame.subarray(0, 18)).update(payload).digest().subarray(0, 16);
|
||||
}
|
||||
|
||||
function randomSessionId(): number {
|
||||
const id = randomBytes(4).readUInt32BE(0);
|
||||
return id === 0 ? 1 : id;
|
||||
}
|
||||
|
||||
function jsonPayload(value: unknown): Buffer { return Buffer.from(JSON.stringify(value), "utf8"); }
|
||||
|
||||
function parseJson(payload: Buffer): Record<string, unknown> | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(payload.toString("utf8"));
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function isPrivateAddress(host: string): boolean {
|
||||
const family = isIP(host);
|
||||
if (family === 4) {
|
||||
const parts = host.split(".").map(Number);
|
||||
return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0;
|
||||
}
|
||||
if (family === 6) {
|
||||
const normalized = host.toLocaleLowerCase();
|
||||
return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
|
||||
}
|
||||
return host === "localhost" || host.endsWith(".localhost");
|
||||
}
|
||||
|
||||
async function resolveTarget(host: string): Promise<{ host: string; family: number }> {
|
||||
const family = isIP(host);
|
||||
if (family) return { host, family };
|
||||
const records = await lookup(host, { all: true, verbatim: true });
|
||||
const record = records.find((item) => item.family === 4) ?? records[0];
|
||||
if (!record) throw new Error("TARGET_DNS_EMPTY");
|
||||
return { host: record.address, family: record.family };
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createAudioFlowStats, snapshotAudioStats, snapshotAudioStatus } from "./audio-stats.js";
|
||||
import type { WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
test("diagnostic snapshots remain stable while new traffic changes live counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.egressFramesByClient[2] = 3;
|
||||
const snapshot = snapshotAudioStats({ audio, webrtc: null });
|
||||
audio.egressFramesByClient[2]++;
|
||||
assert.equal(snapshot.egressFramesByClient[2], 3);
|
||||
snapshot.egressFramesByClient[2] = 10;
|
||||
assert.equal(audio.egressFramesByClient[2], 4);
|
||||
});
|
||||
|
||||
test("public audio status includes live WebRTC counters without losing gateway counters", () => {
|
||||
const audio = createAudioFlowStats();
|
||||
audio.ingressFrames = 12;
|
||||
const rtc: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 7, webrtcIngressRtpFirstAt: 100, webrtcIngressRtpLastAt: 220, webrtcIngressRtpMaxGapMs: 20,
|
||||
webrtcEgressRtpFrames: 3, webrtcEgressRtpFirstAt: 100, webrtcEgressRtpLastAt: 140, webrtcEgressRtpMaxGapMs: 20,
|
||||
webrtcQueuePeakFrames: 2, webrtcQueueDroppedFrames: 1, webrtcQueueUnderrunTicks: 0, webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 1, webrtcIngressQuietFrames: 0, webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 3, webrtcDownlinkDecodeErrors: 0, webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
const source = { audio, webrtc: { getStats: () => rtc } };
|
||||
const status = snapshotAudioStatus(source);
|
||||
assert.equal(status.transport, "webrtc");
|
||||
assert.equal(status.ingressFrames, 12);
|
||||
assert.equal(status.webrtcIngressRtpFrames, 7);
|
||||
assert.equal(snapshotAudioStatus({ audio, webrtc: null }).transport, "websocket");
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { VoiceAudioBridgeStats } from "../shared/voice-models.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
|
||||
|
||||
export interface AudioFlowStats extends WebRtcAudioStats {
|
||||
ingressFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressFirstAt: number | null;
|
||||
ingressLastAt: number | null;
|
||||
ingressMaxGapMs: number;
|
||||
tsSendFrames: number;
|
||||
tsSendErrors: number;
|
||||
tsSendFirstAt: number | null;
|
||||
tsSendLastAt: number | null;
|
||||
tsSendMaxGapMs: number;
|
||||
tsEncodeMaxMs: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveFirstAt: number | null;
|
||||
tsReceiveLastAt: number | null;
|
||||
tsReceiveMaxGapMs: number;
|
||||
egressFrames: number;
|
||||
egressDroppedFrames: number;
|
||||
egressFirstAt: number | null;
|
||||
egressLastAt: number | null;
|
||||
egressMaxGapMs: number;
|
||||
egressSentFirstAt: number | null;
|
||||
egressSentLastAt: number | null;
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
|
||||
}
|
||||
|
||||
export interface AudioStatsSource {
|
||||
audio: AudioFlowStats;
|
||||
webrtc: Pick<WebRtcAudioSession, "getStats"> | null;
|
||||
}
|
||||
|
||||
export function createAudioFlowStats(): AudioFlowStats {
|
||||
return {
|
||||
ingressFrames: 0,
|
||||
ingressDroppedFrames: 0,
|
||||
ingressFirstAt: null,
|
||||
ingressLastAt: null,
|
||||
ingressMaxGapMs: 0,
|
||||
tsSendFrames: 0,
|
||||
tsSendErrors: 0,
|
||||
tsSendFirstAt: null,
|
||||
tsSendLastAt: null,
|
||||
tsSendMaxGapMs: 0,
|
||||
tsEncodeMaxMs: 0,
|
||||
tsReceiveFrames: 0,
|
||||
tsReceiveFirstAt: null,
|
||||
tsReceiveLastAt: null,
|
||||
tsReceiveMaxGapMs: 0,
|
||||
egressFrames: 0,
|
||||
egressDroppedFrames: 0,
|
||||
egressFirstAt: null,
|
||||
egressLastAt: null,
|
||||
egressMaxGapMs: 0,
|
||||
egressSentFirstAt: null,
|
||||
egressSentLastAt: null,
|
||||
egressSentMaxGapMs: 0,
|
||||
egressPeakBufferedBytes: 0,
|
||||
egressFramesByClient: {},
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function snapshotAudioStats(entry: AudioStatsSource): AudioFlowStats {
|
||||
const stats = { ...entry.audio, egressFramesByClient: { ...entry.audio.egressFramesByClient } };
|
||||
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
|
||||
if (webRtcStats) Object.assign(stats, webRtcStats);
|
||||
return stats;
|
||||
}
|
||||
|
||||
export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeStats {
|
||||
const stats = snapshotAudioStats(entry);
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
egressDroppedFrames: stats.egressDroppedFrames,
|
||||
egressMaxGapMs: stats.egressMaxGapMs,
|
||||
webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames,
|
||||
webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs,
|
||||
webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames,
|
||||
webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs,
|
||||
webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames,
|
||||
webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks,
|
||||
webrtcPacerLateTicks: stats.webrtcPacerLateTicks,
|
||||
webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors,
|
||||
webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors,
|
||||
};
|
||||
}
|
||||
|
||||