Compare commits

..
174 Commits
Author SHA1 Message Date
illusia c49b4ec715 release: prepare v0.2.2 2026-09-17 14:36:40 +08:00
illusia 1c80791109 feat: refine desktop audio controls 2026-09-17 14:28:18 +08:00
illusia 85f87ecd0b feat: add Russian Japanese localization and welcome templates 2026-09-17 13:49:43 +08:00
illusia 3d6752a5e4 docs: split README by language 2026-09-17 13:22:40 +08:00
illusia a0921c35b2 merge master error handling into denoise branch 2026-09-17 12:56:49 +08:00
Object ILLUSIA ace9e84889 Merge pull request #2 from LainHE/master
feat: 浏览器端报错翻译与提示改造(vibe coding)
2026-09-17 07:45:00 +08:00
LainHE 4ead174c04 feat: 浏览器端报错翻译与提示改造
- errors: 新增 TeamSpeak 服务器错误 ID 映射表与不可重连错误码集合,归一化
  normalizeTeamSpeakError 按 错误ID/关键词/异常类/传输层特征 分级收敛错误
- voice-bridge: 身份无效/客户端不可用时先发结构化 connectionFailed 帧再关闭,
  新增 pendingKickReason 机制在 kicked 事件后优先回放踢出原因;Opus 编码器
  不可用时限流上报 AUDIO_ENCODER_UNAVAILABLE
- ts-client: 记录本端退出 reasonID,转发 kicked 事件并归一化踢出/封禁原因
- network-probe/teamspeak-probe: 收窄关键字匹配、拒绝原因收敛到既有探测码
- session-manager: 新增 teamSpeak-kicked 拆除原因
- WebClient: 麦克风失败不再假成功,音频状态避免自相矛盾,新增降级横幅与
  中/英/德三语提示词表
- useVoiceWebSocket: 导出 ensureMicrophone 供开麦前预检,新增音频诊断状态、
  CONNECTION_FAILURE_MESSAGES 总表与网关关闭码映射
- 关键新增逻辑补充中文注释说明改动意图
2026-09-16 22:24:25 +08:00
illusia f628d19ebf fix: denoise microphone and honor WebRTC mute 2026-09-15 23:17:23 +08:00
illusia 75de8f1d2b test: use native microphone noise suppression 2026-09-15 22:05:15 +08:00
illusia 1ba8cd5ee1 docs: reorder README sections 2026-09-13 16:49:57 +08:00
illusia f639825775 docs: align README friend project section 2026-09-13 16:18:23 +08:00
illusia 0b40a69d74 docs: add dedicated friend projects section 2026-09-13 16:16:12 +08:00
illusia 6defbff591 docs: add NeteaseTSBot friend link 2026-09-13 16:13:53 +08:00
illusia b5d167e1e7 release: prepare v0.2.1 2026-09-13 08:26:45 +08:00
illusia 7f97d54206 fix: surface all connection error codes on join page 2026-09-13 08:20:27 +08:00
illusia ef3e65ea0b fix: show invalid nickname connection errors 2026-09-13 08:08:40 +08:00
illusia d13b3207a9 fix: send localized connection failure details 2026-09-13 08:00:07 +08:00
illusia 7e08ee54a5 fix: classify TeamSpeak connection failures 2026-09-12 08:09:52 +08:00
illusia 6d8e289b81 feat: scale frontend from 1080p baseline 2026-09-11 11:20:45 +08:00
illusia defbb766e4 feat: include relay route in connection records 2026-09-11 07:34:52 +08:00
illusia 69043748a1 feat: show client IP in connection records 2026-09-10 21:28:34 +08:00
illusia 8046985574 docs: clarify relay deployment instructions 2026-09-10 20:52:54 +08:00
illusia 5ce73d2c84 docs: finalize v0.2.0 release notes 2026-09-10 20:42:17 +08:00
illusia 2d1d202981 fix: use valid Docker healthcheck syntax 2026-09-10 20:20:09 +08:00
illusia 73313f9e2d feat: add relay deployment mode and multiple relays 2026-09-10 20:16:50 +08:00
illusia 097c72bc5d release: prepare v0.2.0 2026-09-10 17:47:34 +08:00
illusia 71f219b7ca merge: promote 0.2.0 preview features 2026-09-10 17:29:35 +08:00
illusia bacc9fe07e merge: integrate connection error fixes 2026-09-10 17:28:41 +08:00
illusia a9c360fb9c docs: describe 0.2.0 connection fixes 2026-09-10 17:27:44 +08:00
illusia 04926c8491 docs: record admin log improvements 2026-09-10 17:25:28 +08:00
illusia fa1d1ad01b docs: add advanced feature guides 2026-09-10 17:22:13 +08:00
illusia c0fc18c344 docs: add advanced feature guides 2026-09-10 17:20:13 +08:00
illusia 69d69f0a5a fix: show generic reason for untraceable history 2026-09-10 17:03:22 +08:00
illusia 6d7976e5d8 fix: hide disabled relay and report password errors 2026-09-10 16:32:18 +08:00
illusia aef1f68875 fix: explain TeamSpeak connection failures 2026-09-10 16:11:18 +08:00
illusia 06e5cc6d8b fix: allow explicit private targets on relay service 2026-09-10 15:35:57 +08:00
illusia 7782e9b327 feat: expose acceleration relay settings in admin console 2026-09-10 15:25:47 +08:00
illusia b82c4fe0af feat: add mainland acceleration preview 2026-09-10 14:27:33 +08:00
illusia 45584810a2 test: add IPv6 acceleration smoke 2026-09-10 11:54:31 +08:00
illusia bfefd053a0 feat: add acceleration tunnel proof of concept 2026-09-10 11:29:18 +08:00
illusia 324213de14 chore: remove repository test sources 2026-09-10 10:54:18 +08:00
illusia a041ba90bb fix: support IPv6 TeamSpeak targets safely 2026-09-10 10:39:02 +08:00
illusia 0dc623eb69 docs: simplify Docker deployment instructions 2026-09-08 13:38:23 +08:00
illusia 3e6876dbe7 release: prepare v0.1.8 2026-09-08 11:25:50 +08:00
illusia a60abffd3b fix: make performance probe handlers browser-safe 2026-09-08 11:09:51 +08:00
illusia 2b43952c01 fix: harden local targets and monitor network continuously 2026-09-08 11:01:28 +08:00
Object ILLUSIA 12f440ab8b Update README to remove image width attribute
Removed width attribute from project icon image.
2026-09-07 13:39:11 +08:00
Object ILLUSIA 7221af78bf Change project icon image in README
Updated the image source in the README file.
2026-09-07 13:38:39 +08:00
Object ILLUSIA a88b0616f5 upload banner
banner
2026-09-07 13:38:14 +08:00
illusia ea4d5b2a70 docs: expand localized interface screenshots 2026-09-06 15:36:46 +08:00
illusia a439100ad6 docs: add localized interface screenshots 2026-09-06 15:28:37 +08:00
illusia 620d24f796 fix: compact latin locale typography 2026-09-06 15:24:51 +08:00
illusia fc3bbd0c59 fix: install ping for admin diagnostics 2026-09-06 15:08:19 +08:00
illusia 3b5ce9b446 fix: restore dark welcome contrast 2026-09-06 14:51:51 +08:00
illusia 37de6067d0 fix: widen language menu options 2026-09-06 14:40:51 +08:00
illusia 45410fcc7d fix: keep quiet WebRTC audio frames 2026-09-06 14:33:15 +08:00
illusia 166cb543a1 fix: make admin diagnostics clientless 2026-09-06 14:18:41 +08:00
illusia a295ff4b27 fix: measure TeamSpeak latency over its protocol 2026-09-06 14:04:41 +08:00
illusia dcc52c4530 release: refresh v0.1.7 diagnostics 2026-09-06 13:47:37 +08:00
illusia dc3ad6a598 release: prepare v0.1.7 2026-09-06 10:48:16 +08:00
illusia ef59e51e32 fix: reveal master volume slider on hover 2026-09-06 10:38:54 +08:00
illusia 9bbc22de25 feat: add master output volume control 2026-09-06 10:25:18 +08:00
illusia 335d93a8b8 fix: preserve accompaniment levels and channel password retry 2026-09-06 09:54:01 +08:00
illusia 52ff0560d1 feat: add German language option and Telegram community link 2026-09-06 09:10:58 +08:00
illusia a5e5dd6592 fix: align connection diagnostics and localize announcement 2026-09-06 08:53:39 +08:00
illusia 62e41dbc51 docs: show demo URL directly 2026-09-06 00:59:00 +08:00
illusia d8b2fd9e1b docs: reorganize bilingual README 2026-09-06 00:49:56 +08:00
illusia 8ca3249832 feat: use penguin icon for QQ entry 2026-09-05 23:35:42 +08:00
illusia 92574fddb1 feat: add QQ community entry to homepage 2026-09-05 21:59:15 +08:00
illusia 596114e6a3 fix: repair admin theme and merge connection history 2026-09-05 21:45:54 +08:00
illusia 2868f7a478 feat: animate welcome page text 2026-09-05 20:08:29 +08:00
illusia 63ef6b673d docs: remove private server address from README 2026-09-05 19:52:04 +08:00
illusia 5a56e1706f fix: remove welcome artwork 2026-09-05 18:09:37 +08:00
illusia 986814441d fix: keep welcome artwork and text readable 2026-09-05 18:09:06 +08:00
illusia 0ab6fb6f3f fix: remove welcome background overlay 2026-09-05 17:43:06 +08:00
illusia a966be4db6 feat: refresh welcome page visuals 2026-09-05 17:35:49 +08:00
illusia 556084233d fix: do not drop WebRTC volume updates 2026-09-04 19:39:45 +08:00
illusia c38239ec35 fix: apply member volume in WebRTC playback 2026-09-04 19:31:50 +08:00
illusia 21041346e3 docs: update README version badge 2026-09-04 16:59:55 +08:00
illusia 7320aa3bb5 release: prepare v0.1.6 2026-09-04 16:31:59 +08:00
illusia d9b8ea625a feat: add repository and site branding 2026-09-04 16:08:43 +08:00
illusia 2323e22fef fix: keep identity concurrency warning visible 2026-09-04 16:03:13 +08:00
illusia b5f8f01301 fix: guard concurrent remembered identities 2026-09-04 15:53:15 +08:00
illusia e964ff460e fix: bypass mixer for single accompaniment stream 2026-09-04 15:41:58 +08:00
illusia 21d8d9c3bc fix: preserve accompaniment audio levels 2026-09-04 14:30:51 +08:00
illusia 169cf88306 fix: preserve accompaniment frames in WebRTC mixer 2026-09-04 12:46:07 +08:00
illusia 059435f4cb fix: preserve WebRTC playback diagnostics 2026-09-04 11:59:53 +08:00
illusia 4d4d4cdeb1 fix: pace WebRTC downlink audio 2026-09-04 11:50:26 +08:00
illusia d42e7a033c fix: handle canceled accompaniment sharing 2026-09-04 10:37:38 +08:00
illusia 0986c65551 feat: add desktop accompaniment controls 2026-09-04 10:24:10 +08:00
illusia 694f864d36 fix: include ca certificates in docker build 2026-09-04 08:38:06 +08:00
illusia 512854ab9f fix: pin sdk lockfile for reproducible installs 2026-09-04 08:31:48 +08:00
illusia b298496911 fix: make sdk release preparation deterministic 2026-09-04 08:27:28 +08:00
illusia b6367e2645 release: prepare v0.1.5 2026-09-04 08:18:56 +08:00
illusia b0fa4bf5d0 fix: make theme toggle respond on first click 2026-09-04 08:05:19 +08:00
illusia cb3dbe4ca4 fix: preserve remembered browser identity on exit 2026-09-03 23:40:38 +08:00
illusia 96ba467d52 release: prepare v0.1.4 2026-09-03 17:07:35 +08:00
illusia 20fdcc7b1d fix: fit welcome header actions on narrow screens 2026-09-03 16:59:28 +08:00
illusia feea39a81c feat: add bilibili profile link 2026-09-03 16:57:35 +08:00
illusia 69d1653f99 feat: add home link to admin login 2026-09-03 16:53:39 +08:00
illusia a18a5b4920 fix: wrap long admin logs on desktop 2026-09-03 16:46:40 +08:00
illusia 343dd84132 fix: wrap long mobile admin logs 2026-09-03 16:44:52 +08:00
illusia a037962cc1 fix: let mobile admin pages scroll naturally 2026-09-03 16:40:22 +08:00
illusia 680ce246fd fix: compact server settings layout 2026-09-03 16:36:52 +08:00
illusia baa09ad38c feat: customize and lock WebRTC media ports 2026-09-03 16:28:49 +08:00
illusia 767bdea018 fix: show channel broadcast messages 2026-09-03 16:08:51 +08:00
illusia 83a8fd0d5a fix: enforce WebRTC microphone mute at gateway 2026-09-03 15:25:34 +08:00
illusia e14ddc9465 fix: filter silent WebRTC uplink frames 2026-09-03 15:16:20 +08:00
illusia 7feb97d77d fix: keep WebRTC playback on native media output 2026-09-03 14:52:59 +08:00
illusia 434360cda9 fix: recover WebRTC playback and speaker state 2026-09-03 14:45:44 +08:00
illusia d0a2e9edc0 fix: make WebRTC playback reliable 2026-09-03 14:28:47 +08:00
illusia 61f66ab319 docs: simplify user-facing README 2026-09-03 12:54:11 +08:00
illusia e79ad66e1f docs: document WebRTC public UDP setup 2026-09-03 11:59:03 +08:00
illusia 522fa8f409 fix: remove obsolete WebRTC error labels 2026-09-03 11:02:42 +08:00
illusia c7def28a8f feat: make WebRTC media service self-contained 2026-09-03 10:56:39 +08:00
illusia d6c8ccb73f fix(ui): remove real IP from WebRTC placeholder 2026-09-03 08:01:08 +08:00
illusia ab5851935c merge: admin-managed WebRTC settings 2026-09-03 07:52:21 +08:00
illusia 5c3d1b7e5d feat(admin): manage WebRTC settings from console 2026-09-03 07:52:13 +08:00
illusia ecff06e9a1 docs: record SDK migration in v0.1.3 2026-09-03 07:32:11 +08:00
illusia 9c3f09b55b merge: release v0.1.3 2026-09-03 07:28:29 +08:00
illusia b42c455e7f release: prepare v0.1.3 2026-09-03 07:28:14 +08:00
illusia 40ea30b9e2 fix(audio): cleanly fall back from WebRTC 2026-09-03 01:29:34 +08:00
illusia a4cf5b5359 fix(audio): use OpusEncoder decoder API 2026-09-03 01:23:34 +08:00
illusia 1d41d5a3e7 fix(audio): honor negotiated WebRTC Opus payload 2026-09-03 01:17:01 +08:00
illusia 46b190a913 fix(audio): avoid duplicate WebRTC playback 2026-09-03 01:02:18 +08:00
illusia 8abd2d6228 feat(audio): add experimental WebRTC transport 2026-09-03 00:47:51 +08:00
illusia 7ff6836a7e fix(audio): tighten gateway voice backpressure 2026-09-03 00:23:16 +08:00
illusia a6187c18af chore(audio): attribute egress frames by client 2026-09-03 00:19:45 +08:00
illusia 8ab2fbe8ea fix(audio): move capture framing to audio worklet 2026-09-03 00:13:48 +08:00
illusia 3e7674c94f chore(audio): capture sampled flow timing 2026-09-03 00:04:17 +08:00
illusia 30c0d09a33 chore(audio): include session flow counters in teardown 2026-09-03 00:01:50 +08:00
illusia d9904fa154 fix(audio): bound realtime voice buffering 2026-09-02 23:56:24 +08:00
illusia afbbd1e2d4 refactor: migrate to maintained TeamSpeak SDK 2026-09-02 23:27:32 +08:00
illusia adca8cc1db docs(deploy): standardize published Docker image flow 2026-09-02 16:26:20 +08:00
illusia 9788e7fa1c release: prepare v0.1.2 2026-09-02 16:11:59 +08:00
illusia 66da7efe4a fix(web): align settings icons on narrow screens 2026-09-02 15:48:39 +08:00
illusia 3fb7000d02 feat(web): add prominent GitHub repository link 2026-09-02 15:35:54 +08:00
illusia 03c95abcf7 docs(deploy): simplify Docker startup and document demo 2026-09-02 12:51:43 +08:00
illusia d2ffbee873 refactor(admin): hide protocol details from users 2026-09-02 10:38:46 +08:00
illusia 413dbaf3a8 docs: record microphone mute update 2026-09-02 08:01:08 +08:00
illusia 9187d2faed fix(web): replace browser ptt with microphone mute 2026-09-02 07:52:54 +08:00
illusia af85a73c7d feat(web): optimize mobile client experience 2026-09-02 06:23:07 +08:00
illusia b3ace7d7b6 release: consolidate final v0.1.1 documentation 2026-09-02 00:13:58 +08:00
illusia 49c8aee795 release: make v0.1.3 publishing reliable 2026-09-02 00:08:12 +08:00
illusia cd6dd69d9b release: prepare v0.1.2 docker and packages 2026-09-02 00:02:20 +08:00
illusia 325c907683 docs: add Chinese community section and release publishing 2026-09-01 23:58:21 +08:00
illusia 41666a5531 docs: separate bilingual navigation and dated changelog 2026-09-01 23:53:04 +08:00
illusia 0732e2df7d docs: align bilingual readme and changelog 2026-09-01 23:48:48 +08:00
illusia d7766497e8 fix complete directory sync for late web clients 2026-09-01 23:32:15 +08:00
illusia aa5c5e687f fix private chat disconnect and member menu 2026-09-01 23:23:47 +08:00
illusia 8a06382cec docs: remove implementation details from readme 2026-09-01 23:12:13 +08:00
illusia 1fe11850b7 docs: rewrite project readme 2026-09-01 23:02:43 +08:00
illusia a5a8648240 fix: keep admin lists inside their cards 2026-09-01 22:54:49 +08:00
illusia 81212b420b fix: keep page scrolling inside view containers 2026-09-01 22:26:32 +08:00
illusia 3ec9ab497a feat: split TeamSpeak address and port inputs 2026-09-01 22:12:37 +08:00
illusia bf1158aff2 fix: complete admin session translations 2026-09-01 21:47:32 +08:00
illusia a4cbcf536f feat: expose audit and update status in operations 2026-09-01 18:28:12 +08:00
illusia 797c5b118a fix: pass package version to admin overview 2026-09-01 18:26:06 +08:00
illusia 6337789afa chore: harden release operations and freeze docs 2026-09-01 18:24:09 +08:00
illusia 87fcd736be feat: add admin operations dashboard 2026-09-01 18:19:18 +08:00
illusia f5bd06fdaf feat: add managed invites and admin diagnostics backend 2026-09-01 18:16:22 +08:00
illusia 96ef77c789 feat: add real TeamSpeak whisper routing 2026-09-01 18:08:07 +08:00
illusia cab7707e51 feat: complete M008 web ux and demo 2026-09-01 17:54:51 +08:00
illusia 277fa9d8fe feat: complete M007 audio system 2026-09-01 17:41:12 +08:00
illusia 509dc038c1 M006: add scoped chat and client interactions 2026-09-01 17:32:00 +08:00
illusia 2f8301d188 M005: add local identity and preference persistence 2026-09-01 17:19:15 +08:00
illusia 3397e90749 M004: close Docker and deployment workflow 2026-09-01 17:02:54 +08:00
illusia 3cca211ae9 M003: add TeamSpeak reconnect recovery 2026-09-01 16:59:48 +08:00
illusia 8c7a940de5 M002: harden session lifecycle and directory sync 2026-09-01 16:52:26 +08:00
illusia 4a5d1ca0da Use admin default target on welcome page 2026-09-01 13:12:43 +08:00
illusia 7dcbcaae78 M001: replace bootstrap setup with forced password rotation 2026-09-01 13:09:51 +08:00
illusia 34ef16b737 chore: update frontend security dependencies 2026-09-01 08:07:27 +08:00
illusia 31f320d4c1 M001: add secure admin foundation 2026-09-01 08:00:24 +08:00
illusia 960be106bb M000: normalize configuration and TeamSpeak adapter 2026-08-31 20:14:08 +08:00
93 changed files with 15422 additions and 1439 deletions

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
.git
.github
.claude
node_modules
web/node_modules
dist
web/dist
data
certs
release-artifacts
scripts/acceleration-poc
*.tar.gz
*.tar.xz
claude.pem
config.json
*.log
+63 -16
View File
@@ -1,12 +1,15 @@
name: Build release assets
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
inputs:
version:
description: Release version without the v prefix
required: true
default: 0.1.0
default: 0.1.3
type: string
permissions:
@@ -26,12 +29,24 @@ jobs:
web/package-lock.json
- name: Build application
shell: pwsh
env:
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
$ErrorActionPreference = "Stop"
npm ci --no-audit --no-fund
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
npm ci --ignore-scripts --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm run prepare:sdk
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm --prefix web ci --no-audit --no-fund
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$currentVersion = node -p "require('./package.json').version"
if ($currentVersion -ne $releaseVersion) {
npm version --no-git-tag-version $releaseVersion
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
npm --prefix web run build
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm run build
@@ -41,10 +56,11 @@ jobs:
- name: Package and smoke-test Windows x64
shell: pwsh
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
$ErrorActionPreference = "Stop"
$packageName = "webspeak-webclient-v$env:RELEASE_VERSION-windows-x64"
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
$packageName = "webspeak-webclient-v$releaseVersion-windows-x64"
$packageRoot = Join-Path $env:RUNNER_TEMP $packageName
$runtimeRoot = Split-Path -Parent (Get-Command node).Source
New-Item -ItemType Directory -Path $packageRoot | Out-Null
@@ -71,7 +87,7 @@ jobs:
$smokeRoot = Join-Path $env:RUNNER_TEMP ($packageName + "-smoke")
Copy-Item -Recurse -LiteralPath $packageRoot -Destination $smokeRoot
@{
port = 31440
port = 3040
tsHost = "203.0.113.10"
tsPort = 9987
tsServerPassword = ""
@@ -85,9 +101,9 @@ jobs:
$health = $null
for ($attempt = 0; $attempt -lt 30 -and -not $health; $attempt++) {
Start-Sleep -Milliseconds 500
try { $health = Invoke-RestMethod -Uri "http://127.0.0.1:31440/api/health" -TimeoutSec 2 } catch {}
try { $health = Invoke-RestMethod -Uri "http://127.0.0.1:3040/api/health" -TimeoutSec 2 } catch {}
}
if (-not $health -or $health.status -ne "ok" -or $health.version -ne $env:RELEASE_VERSION) {
if (-not $health -or $health.status -ne "ok" -or $health.version -ne $releaseVersion) {
throw "Windows release health check failed"
}
} finally {
@@ -97,7 +113,7 @@ jobs:
- uses: actions/upload-artifact@v4
with:
name: windows-x64
path: webspeak-webclient-v${{ inputs.version }}-windows-x64.zip
path: webspeak-webclient-v*-windows-x64.zip
if-no-files-found: error
compression-level: 0
@@ -113,19 +129,29 @@ jobs:
package-lock.json
web/package-lock.json
- name: Build application
env:
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
set -euo pipefail
npm ci --no-audit --no-fund
release_version="${RELEASE_REF#v}"
npm ci --ignore-scripts --no-audit --no-fund
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
npm --prefix web ci --no-audit --no-fund
current_version="$(node -p "require('./package.json').version")"
if [ "$current_version" != "$release_version" ]; then
npm version --no-git-tag-version "$release_version"
fi
npm --prefix web run build
npm run build
npm prune --omit=dev --no-audit --no-fund
- name: Package and smoke-test Linux x64
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_REF: ${{ inputs.version || github.ref_name }}
run: |
set -euo pipefail
package_name="webspeak-webclient-v${RELEASE_VERSION}-linux-x64"
release_version="${RELEASE_REF#v}"
package_name="webspeak-webclient-v${release_version}-linux-x64"
package_root="$RUNNER_TEMP/$package_name"
runtime_root="$(dirname "$(dirname "$(command -v node)")")"
mkdir -p "$package_root/web" "$package_root/runtime"
@@ -148,7 +174,7 @@ jobs:
cp -a "$package_root" "$smoke_root"
cat > "$smoke_root/config.json" <<'CONFIG'
{
"port": 31441,
"port": 3040,
"tsHost": "203.0.113.10",
"tsPort": 9987,
"tsServerPassword": "",
@@ -164,17 +190,38 @@ jobs:
trap 'kill "$app_pid" 2>/dev/null || true; wait "$app_pid" 2>/dev/null || true' EXIT
health=""
for _ in $(seq 1 30); do
health="$(curl -fsS --max-time 2 http://127.0.0.1:31441/api/health 2>/dev/null || true)"
if grep -q '"status":"ok"' <<<"$health" && grep -q "\"version\":\"$RELEASE_VERSION\"" <<<"$health"; then break; fi
health="$(curl -fsS --max-time 2 http://127.0.0.1:3040/api/health 2>/dev/null || true)"
if grep -q '"status":"ok"' <<<"$health" && grep -q "\"version\":\"$release_version\"" <<<"$health"; then break; fi
sleep 0.5
done
grep -q '"status":"ok"' <<<"$health"
grep -q "\"version\":\"$RELEASE_VERSION\"" <<<"$health"
grep -q "\"version\":\"$release_version\"" <<<"$health"
)
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
- uses: actions/upload-artifact@v4
with:
name: linux-x64
path: webspeak-webclient-v${{ inputs.version }}-linux-x64.tar.gz
path: webspeak-webclient-v*-linux-x64.tar.gz
if-no-files-found: error
compression-level: 0
publish-release:
if: startsWith(github.ref, 'refs/tags/v')
needs: [windows-x64, linux-x64]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Download deployment packages
uses: actions/download-artifact@v4
with:
pattern: '*-x64'
path: release-assets
merge-multiple: true
- name: Publish GitHub release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: WebSpeak ${{ github.ref_name }}
generate_release_notes: true
files: release-assets/*
+53
View File
@@ -0,0 +1,53 @@
name: Continuous integration
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22.22.2
cache: npm
cache-dependency-path: |
package-lock.json
web/package-lock.json
- name: Install dependencies
run: |
npm ci --ignore-scripts --no-audit --no-fund
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
npm --prefix web ci --no-audit --no-fund
- name: Build application
run: |
npm run build
npm --prefix web run build
docker-smoke:
needs: verify
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Build image
run: docker build --tag webspeak:ci .
- name: Run health smoke test
run: |
set -euo pipefail
docker run --detach --name webspeak-ci --publish 3040:3040 webspeak:ci
trap 'docker logs webspeak-ci; docker rm --force webspeak-ci' EXIT
for attempt in $(seq 1 30); do
if curl --fail --silent http://127.0.0.1:3040/health | grep -q '"status":"ok"'; then
exit 0
fi
sleep 2
done
exit 1
+45
View File
@@ -0,0 +1,45 @@
name: Publish Docker image
on:
push:
branches: [master]
tags: ["v*.*.*"]
workflow_dispatch:
permissions:
contents: read
packages: write
env:
IMAGE_NAME: ghcr.io/echosixhiya/webspeak
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=ref,event=tag
type=sha
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+282
View File
@@ -0,0 +1,282 @@
# Changelog
## [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.
+8 -5
View File
@@ -9,8 +9,8 @@ Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpea
Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server
```
- Each browser user = one independent TS3 virtual client via `@honeybbq/teamspeak-client`
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
@@ -30,16 +30,19 @@ src/
server/
server.ts # Express + HTTPS + WS setup
voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API
ts-client.ts # TS3Client wrapper around @honeybbq/teamspeak-client
ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client
```
## Key Technical Details
### Audio Pipeline
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path.
### CJS Interop
`@discordjs/opus` is CommonJS, loaded via:
+45
View File
@@ -0,0 +1,45 @@
FROM node:22-bookworm-slim AS build
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
&& rm -rf /var/lib/apt/lists/*
COPY package.json package-lock.json ./
COPY web/package.json web/package-lock.json ./web/
RUN npm ci --ignore-scripts --no-audit --no-fund
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
RUN npm run prepare:sdk
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
RUN npm --prefix web ci
COPY . .
RUN npm --prefix web run build \
&& npm run build \
&& npm prune --omit=dev \
&& rm -rf web/node_modules
FROM node:22-bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates libstdc++6 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
USER node
VOLUME ["/data"]
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ["sh", "-c", "if [ \"$WEBSPEAK_MODE\" = \"relay\" ]; then node -e \"process.exit(0)\"; else node -e \"fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\"; fi"]
CMD ["node", "dist/index.js"]
+56 -329
View File
@@ -1,354 +1,81 @@
# WebSpeak
<div align="center">
<a id="readme-top"></a>
TeamSpeak 浏览器客户端:在服务器上运行 Node.js 服务,用户无需安装 TeamSpeak 客户端,即可通过浏览器加入语音频道。
<img src="./仓库图标.png" alt="WebSpeak 项目图标" width="180" />
[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.
[![Latest Release](https://img.shields.io/github/v/release/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?sort=semver&display_name=tag&style=flat-square&color=0f766e)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest)
[![Docker Image](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml/badge.svg?branch=master)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/workflows/docker-publish.yml)
[![License](https://img.shields.io/badge/license-AGPL--3.0--only-0f766e?style=flat-square)](./LICENSE)
[![GitHub Stars](https://img.shields.io/github/stars/EchoSixHIYA/WebSpeak-client-for-TeamSpeak?style=flat-square&logo=github&color=0f766e)](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/stargazers)
<br />
[![TeamSpeak](https://img.shields.io/badge/TeamSpeak-3%20%7C%206-2580C3?style=flat-square)](https://www.teamspeak.com/)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.5-339933?style=flat-square&logo=nodedotjs&logoColor=white)](https://nodejs.org/)
[![Vue](https://img.shields.io/badge/Vue-3-42B883?style=flat-square&logo=vuedotjs&logoColor=white)](https://vuejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-6-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Docker](https://img.shields.io/badge/Docker-GHCR-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/EchoSixHIYA/packages/container/package/webspeak)
### 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
详细的特性、截图、高级功能、部署方案、要求和更新日志已按语言拆分:
```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 │
└──────────────────────┘
```
- [简体中文](./docs/README.zh-CN.md)
- [English](./docs/README.en.md)
- [Deutsch](./docs/README.de.md)
- [Русский](./docs/README.ru.md)
- [日本語](./docs/README.ja.md)
### Quick start
## 社区 · Community
#### 1. Install dependencies
<div align="center">
```bash
# Native build tools are required by @discordjs/opus.
sudo apt-get update
sudo apt-get install -y build-essential python3
<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>
npm install
npm --prefix web install
```
**QQ群 / QQ group:`869500475`**
On Windows, install Visual Studio Build Tools with **Desktop development with C++** before running `npm install`.
[通过群聊链接直接加入 / Join directly](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=yhumUMDD9PmyYFWdXWUb_x7hM5trFQY8&authKey=Pw3HBGT7GwMinTQnuFGfnpf0aRSzXOJKcAiujVP1%2BXMpjheAKrncTRivicBJxpjV&noverify=0&group_code=869500475)
`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.
[Telegram 群组 / Telegram group](https://t.me/+8qShpTcuN9A3MWY9)
#### 2. Build
</div>
```bash
npm --prefix web run build
npm run build
```
## 友链项目 · Friend projects
The build output is written to `web/dist/` and `dist/`.
### [NeteaseTSBot](https://github.com/yichen11818/NeteaseTSBot)
#### 3. Configure `config.json`
面向 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.
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.
## 许可证 · License · Lizenz
```json
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
}
```
WebSpeak 使用 [GNU Affero General Public License v3.0 only](./LICENSE) 发布。你可以使用、研究、修改和再分发本项目;如果修改后的版本通过网络向用户提供服务,需要按照 AGPL-3.0 向这些用户提供对应源代码。
| 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. |
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 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 wird unter der [GNU Affero General Public License v3.0 only](./LICENSE) veröffentlicht. Bei Bereitstellung einer veränderten Version über ein Netzwerk muss der entsprechende Quellcode unter AGPL-3.0 angeboten werden.
WebSpeak uses each user's regular TeamSpeak client connection for both voice and directory data. TeamSpeak sends the initial channel/member snapshot during the normal client welcome sequence; WebSpeak then subscribes that regular client to the complete channel tree, just as a native client does, and applies channel/member notifications immediately afterward. A member moving out of the current channel is retained and reassigned to the target channel instead of being mistaken for a server disconnect. WebSpeak does not start a maintenance client and does not call the permission-restricted `channellist` or `clientlist` commands. The visible result is the same view available to that TeamSpeak identity.
The connected layout keeps the member/channel tree on the left. During the first connection, WebSpeak uses the current channel ID from TeamSpeak's welcome sequence to place the web client in the actual default channel instead of a placeholder group. The small speaking indicator is status-only: it is not a mute control. The avatar border turns green while a voice packet is active, then fades after the stream becomes quiet.
#### 4. Enable HTTPS
WebSpeak automatically serves HTTPS when `certs/cert.pem` and `certs/key.pem` exist:
```bash
mkdir -p certs
openssl req -x509 -newkey rsa:2048 \
-keyout certs/key.pem \
-out certs/cert.pem \
-days 365 -nodes \
-subj "/CN=your-domain.example"
```
For public use, prefer a trusted certificate from Let's Encrypt or terminate TLS at Nginx. Do not commit private keys to Git.
#### 5. Start WebSpeak
```bash
node dist/index.js
```
Open:
```text
https://your-domain.example:3040/
```
Enter the TeamSpeak server address, voice port, and nickname on the page. The browser will request microphone permission. Open **Audio settings** to select a specific microphone, change input/output volume, or run the real microphone-level test.
The connected page keeps its controls in the header so the chat viewport remains unobstructed. Microphone mode selection (free microphone or push-to-talk) is available in **Audio settings**.
### Production deployment
Example systemd unit:
```ini
[Unit]
Description=WebSpeak TeamSpeak browser gateway
After=network.target
[Service]
Type=simple
User=teamspeak
WorkingDirectory=/opt/webspeak
ExecStart=/usr/bin/node /opt/webspeak/dist/index.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
```
Enable it with:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now webspeak.service
sudo systemctl status webspeak.service
```
If Nginx terminates HTTPS, leave `certs/` absent so WebSpeak listens over local HTTP, then proxy both normal traffic and WebSocket upgrades:
```nginx
server {
listen 443 ssl;
server_name ts.example.com;
ssl_certificate /etc/letsencrypt/live/ts.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/ts.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3040;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Set `trustProxy` to `true` only after verifying that the proxy is trusted and cannot be bypassed.
### Troubleshooting
| Symptom | Check |
| --- | --- |
| Microphone is unavailable | Use HTTPS, grant the browser microphone permission, and check the selected device in Audio settings. |
| Only the default microphone appears | Reload after granting permission; browser device labels are hidden until permission is granted. Disconnect/reconnect if the device was plugged in later. |
| Channel/member list is empty | Check the TeamSpeak address/voice port and `tsServerProtocol`. The directory is populated from the normal client welcome sequence. |
| The channel directory is still loading | Keep the page connected briefly while the welcome snapshot arrives. Later member and channel changes are pushed to the page automatically in real time. |
| The current user is missing | Keep the connection open until the TeamSpeak welcome snapshot arrives. WebSpeak uses the current channel ID to place the user in the default channel, then updates the tree from realtime member notifications. |
| Page loads without audio | Use a recent Chrome/Edge build, verify HTTPS, and check browser output volume. |
| `Cannot find module '@discordjs/opus'` | Install the native build prerequisites and run `npm install` again. |
| `EADDRINUSE` | Change `port` or stop the process already listening on that port. |
### Project layout
```text
src/
server/voice-bridge.ts WebSocket bridge and per-user voice clients
server/ts-client.ts TeamSpeak protocol adapter and live directory adapter
config.example.json Safe starting configuration; copy to config.json
scripts/
patch-teamspeak-sdk.mjs Preserve TeamSpeak welcome directory data
web/
src/views/WebClient.vue Browser UI and bilingual presentation
src/composables/useVoiceWebSocket.ts
Voice, chat, device and channel state
```
### Development
```bash
# Frontend hot reload
npm run web:dev
# Type-check and production-build frontend
npm --prefix web run build
# Type-check backend
npm run build
```
Contributions and issue reports are welcome. Please do not include `config.json`, certificates, private keys, or server logs in issues or pull requests.
### License
WebSpeak is released under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version as a network service, you must offer its users the corresponding source code as required by the license.
## 中文
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`):
![WebSpeak 群聊二维码](group-chat.png)
<div align="right"><a href="#readme-top">返回顶部 · Back to top ↑</a></div>
+1 -5
View File
@@ -1,9 +1,5 @@
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
"tsServerPassword": ""
}
+13
View File
@@ -0,0 +1,13 @@
services:
webspeak:
image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest}
pull_policy: missing
restart: unless-stopped
# 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:
+226
View File
@@ -0,0 +1,226 @@
# 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. |
| 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. |
| Oberfläche | Chinesische, englische, deutsche, russische und japanische Oberfläche, helle/dunkle Designs 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.
### 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.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 |
| 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` oder `linux-x64.tar.gz` aus den [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) herunterladen, in ein eigenes Verzeichnis entpacken und `start-webspeak.cmd` bzw. `./start-webspeak.sh` starten. Die Pakete enthalten Node.js und Produktionsabhängigkeiten.
### 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. |
+226
View File
@@ -0,0 +1,226 @@
# 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. |
| 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. |
| User experience | Chinese, English, German, Russian, and Japanese UI, light/dark themes, and responsive desktop/mobile layouts. |
| Self-hosting | Data stays with the operator; Docker, Windows x64, and Linux x64 deployment options 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.
### 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.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 |
| 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` or `linux-x64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), extract it into a dedicated directory, and run `start-webspeak.cmd` on Windows or `./start-webspeak.sh` on Linux. Packages include the Node.js runtime and production dependencies.
### 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. |
+111
View File
@@ -0,0 +1,111 @@
# 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 に対応し、対象プロトコルを自動検出します。 |
| IPv6 | IPv6 の接続先と DNS から解決された IPv6 アドレスに標準対応します。 |
| チャンネルとメンバー | チャンネルツリー、リアルタイムのメンバー状態、チャンネル移動。 |
| リアルタイム音声 | Opus、互換トランスポート、内蔵 WebRTC による低遅延音声。 |
| 音声操作 | マイク、スピーカー、音量、VOX、ミュート、メンバーごとの音量調整。 |
| ブラウザ側ノイズ抑制 | マイクのノイズ抑制をブラウザの音声取得段階で任意に使用でき、サーバー側の追加処理は不要です。 |
| チャットと操作 | チャンネル/サーバーチャット、個人メッセージ、つつく、ウィスパー対象。 |
| BGM共有 | デスクトップブラウザで音声付きウィンドウやタブの音をチャンネルに共有。 |
| ID とアクセス | ID の保存、接続先の指定、期限・回数付き招待リンク。 |
| 管理コンソール | 接続先、アクセス、WebRTC、中継、招待、セッション、ログ、診断、バックアップ。 |
| インターフェース | 中文、English、Deutsch、Русский、日本語、ライト/ダークテーマ、レスポンシブ表示。 |
## 🧩 高度な機能
### WebRTC
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
### 中継サーバー
中継は現在の 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 または Linux x64 のパッケージを取得し、専用フォルダーに展開して `start-webspeak.cmd` または `./start-webspeak.sh` を実行します。
### ソースから
```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.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) の下で公開されています。
+111
View File
@@ -0,0 +1,111 @@
# 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 с автоматическим определением протокола. |
| IPv6 | IPv6-цели и IPv6-адреса, полученные через DNS, поддерживаются по умолчанию. |
| Каналы и участники | Дерево каналов, состояние участников в реальном времени и переход между каналами. |
| Голос в реальном времени | Opus, совместимый транспорт и встроенный WebRTC с низкой задержкой. |
| Управление аудио | Микрофон, динамики, громкость, VOX, отключение микрофона и отдельная громкость участников. |
| Шумоподавление в браузере | Опциональное шумоподавление микрофона на этапе захвата в браузере без дополнительной обработки звука на сервере. |
| Чат и действия | Чат канала и сервера, личные сообщения, толчки и цели шёпота. |
| Фоновая музыка | На компьютере можно поделиться звуком окна или вкладки с текущим каналом. |
| Идентичность и доступ | Сохранение идентичности, собственные цели и приглашения с ограничением срока и числа использований. |
| Панель администратора | Цели, доступ, WebRTC, ретрансляторы, приглашения, сессии, логи, диагностика и резервные копии. |
| Интерфейс | 中文, English, Deutsch, Русский и 日本語, светлая/тёмная тема и адаптивная верстка. |
## 🧩 Расширенные функции
### WebRTC
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
### Ретрансляторы
Ретранслятор передаёт только 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 или Linux x64 из [Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest), распакуйте в отдельную папку и запустите `start-webspeak.cmd` или `./start-webspeak.sh`.
### Из исходников
```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.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).
+226
View File
@@ -0,0 +1,226 @@
# 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,并自动探测目标服务器协议。 |
| IPv6 目标 | 默认支持 IPv6 TeamSpeak 目标和域名解析出的 IPv6 地址。 |
| 频道与成员 | 浏览频道树、查看实时成员状态并切换频道。 |
| 实时语音 | 使用 Opus,支持兼容传输和可选的内置 WebRTC 低延迟传输。 |
| 音频控制 | 选择麦克风与扬声器、调节音量、测试麦克风、闭麦、VOX 和成员独立音量。 |
| 浏览器端降噪 | 提供可开关的麦克风降噪,在浏览器采集端处理,不增加服务器端音频处理压力。 |
| 消息与互动 | 支持频道消息、服务器消息、私聊、戳一戳和耳语目标。 |
| 桌面端伴奏 | 在桌面浏览器选择带音频的窗口或标签页,将声音分享给当前频道。 |
| 身份与访问 | 支持身份保持、访客自定义目标和可撤销、可过期的邀请链接。 |
| 管理控制台 | 管理目标、访问策略、WebRTC、中继、邀请、会话、日志、诊断和备份。 |
| 界面体验 | 提供中文、English、Deutsch、Русский、日本語、浅色/深色主题及响应式桌面/移动布局。 |
| 自托管 | 数据由部署者保存,提供 Docker、Windows x64 和 Linux x64 方案。 |
## 🖼️ 界面截图
以下截图展示中文界面的欢迎页、语音工作区、音量控制和成员操作菜单。
### 欢迎页
<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。
### 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.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 |
| 源码运行 | 开发、调试和二次开发 | 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`,解压后运行 Windows 的 `start-webspeak.cmd` 或 Linux 的 `./start-webspeak.sh`。发布包自带 Node.js 运行时和生产依赖。
### 源码运行
```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 个活动网页会话。 |
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+709 -206
View File
File diff suppressed because it is too large. Load diff
+17 -4
View File
@@ -1,23 +1,31 @@
{
"name": "webspeak-webclient",
"version": "0.1.0",
"version": "0.2.2",
"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",
"start": "node dist/index.js",
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite build"
"web:build": "cd web && npx vite build",
"prepare:sdk": "node scripts/prepare-sdk.mjs",
"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#a145338",
"express": "^5.2.1",
"pino": "^10.3.1",
"werift": "0.24.4",
"ws": "^8.20.0"
},
"devDependencies": {
@@ -26,5 +34,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"
}
}
+52
View File
@@ -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
下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开:
```bash
$env:WEBSPEAK_ACCEL_TS_TARGET="203.0.113.10#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、断线重连和目标地址安全策略。
+116
View File
@@ -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");
+106
View File
@@ -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);
}
+180
View File
@@ -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}`);
}
+50
View File
@@ -0,0 +1,50 @@
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 target = parseEndpoint(process.env.WEBSPEAK_ACCEL_TS_TARGET ?? "203.0.113.10#9987", 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();
}
+60
View File
@@ -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;
});
+100
View File
@@ -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;
});
-148
View File
@@ -1,148 +0,0 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client");
const marker = "webspeak-directory-snapshot";
const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
if (packageJson.version !== "0.2.2") {
throw new Error(`Unsupported @honeybbq/teamspeak-client version: ${packageJson.version}`);
}
const cjsPath = path.join(packageRoot, "dist", "index.cjs");
const mjsPath = path.join(packageRoot, "dist", "index.mjs");
const [cjs, mjs] = await Promise.all([
readFile(cjsPath, "utf8"),
readFile(mjsPath, "utf8"),
]);
const patchedCjs = patchCjs(cjs);
const patchedMjs = patchMjs(mjs);
await Promise.all([
writeFile(cjsPath, patchedCjs, "utf8"),
writeFile(mjsPath, patchedMjs, "utf8"),
]);
function patchCjs(source) {
if (source.includes(marker)) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var K=class", `${helper}var K=class`);
// TS6 reports a client that moved out of our current view as
// notifyclientleftview with a non-zero ctid. Preserve that client and apply
// the target channel; ctid=0 is the actual server leave case.
const replacements = [
[
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t;return r!==0&&n.delete(r),{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
"function L(e,t,n){let r=j(e.params.clid??``),i=M(e.params.reasonid??``),a=r===t,o=A(e.params.ctid??``),s=o!==0n;if(r!==0)if(s){let e=n.get(r);e&&n.set(r,{...e,channelID:o})}else n.delete(r);return s?{kind:`clientMoved`,event:{id:r,targetChannelID:o,reasonID:i,invokerID:j(e.params.invokerid??``),invokerName:e.params.invokername??``,invokerUID:e.params.invokeruid??``}}:{kind:`clientLeave`,event:{id:r,reasonID:i,reasonMsg:e.params.reasonmsg??``,targetID:j(e.params.targetid??``)},isSelf:a}}",
],
[
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
"var K=class{crypt;handler;logger;nickname;clid=0;#e;#t;#n;#r;#i=e.t.Disconnected;#a=new W;#o=new d;#s=new m;#c=new Map;#q=new Map;#R=[];#L=!1;#l=[];#u=[];#d=[];#f=[];#p=[];#m=[];#h=[];#g=[];#_=[];#v=[];#y=[];#b=[];#x;#S;constructor",
],
[
"case`voiceData`:this.#h.push(t);break;case`connected`:",
"case`voiceData`:this.#h.push(t);break;case`directorySnapshot`:this.#R.push(t);break;case`connected`:",
],
[
"this.#o.reset(),this.#s.reset(),this.#c.clear(),this.clid=0",
"this.#o.reset(),this.#s.reset(),this.#q.clear(),this.#c.clear(),this.#L=!1,this.clid=0",
],
[
"case`initserver`:w(this,t.params);break;case`error`:this.#A(t.params);break;default:{",
"case`initserver`:w(this,t.params);break;case`channellist`:{let e=webSpeakDirectoryChannel(t.params,a.i);e&&this.#q.set(e.id,e),this.#Y();break}case`channelclientlist`:{let e=webSpeakDirectoryClient(t.params,a.i);e&&this.#c.set(e.id,e),this.#Y();break}case`error`:this.#A(t.params);break;default:{",
],
[
"if(t.name.startsWith(`notify`)){let e=F(t,this.clid,this.#c,this.nickname);this.#j(e,t.params);return}",
"if(t.name.startsWith(`notify`)){let e=webSpeakDirectoryChannelNotification(t.name,t.params,a.i,this.#q),n=F(t,this.clid,this.#c,this.nickname);this.#j(n,t.params),e&&this.#Y();return}",
],
[
"case`clientEnter`:{let t=e.info;t.id!==0&&N(this.nickname,t.nickname)&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete()),this.#M(`clientEnter`,t);break}",
"case`clientEnter`:{let t=e.info,r=webSpeakDirectoryBigInt(arguments[1]?.cid??arguments[1]?.ctid??\"0\");r!==0n&&(t={...t,channelID:r},this.#c.set(t.id,t));let n=this.#c.get(t.id);n&&t.channelID===0n&&n.channelID!==0n&&(t={...t,channelID:n.channelID},this.#c.set(t.id,t));let i=t.id!==0&&N(this.nickname,t.nickname);i&&(this.clid=t.id,this.handler.setClientID(t.id),this.#o.signalWelcomeComplete(),this.#Y()),this.#M(`clientEnter`,t),!i&&this.#i===2&&this.#Y();break}",
],
[
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event);break;",
"case`clientLeave`:if(this.#M(`clientLeave`,e.event),this.#i===2&&this.#Y(),e.isSelf&&(e.event.reasonID===4||e.event.reasonID===5)){let t=e.event.reasonMsg;for(let e of this.#v)setImmediate(()=>e(t))}break;case`clientMoved`:this.#M(`clientMoved`,e.event),this.#i===2&&this.#Y();break;",
],
[
"#M(e,t){this.#S(t)}#N(e,t){",
"#Y(){if(this.#L)return;this.#L=!0,setImmediate(()=>{this.#L=!1;const e={channels:Array.from(this.#q.values()).map(e=>({...e})),clients:Array.from(this.#c.values()).map(e=>({...e,serverGroups:[...(e.serverGroups??[])]}))};for(const t of this.#R)setImmediate(()=>t(e))})}#M(e,t){this.#S(t)}#N(e,t){",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch CJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
function patchMjs(source) {
if (source.includes(marker)) return source;
const helper = `/* ${marker} */
function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}}
function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}}
function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}}
function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}}
`;
source = source.replace("var k = class", `${helper}var k = class`);
// Keep the readable ESM build behavior identical to the minified CJS build.
const replacements = [
[
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t;\n\treturn r !== 0 && n.delete(r), {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
"function ie(e, t, n) {\n\tlet r = Y(e.params.clid ?? \"\"), i = X(e.params.reasonid ?? \"\"), a = r === t, targetChannelID = J(e.params.ctid ?? \"\"), moved = targetChannelID !== 0n;\n\tif (r !== 0) {\n\t\tif (moved) {\n\t\t\tconst current = n.get(r);\n\t\t\tif (current) n.set(r, { ...current, channelID: targetChannelID });\n\t\t} else {\n\t\t\tn.delete(r);\n\t\t}\n\t}\n\treturn moved ? {\n\t\tkind: \"clientMoved\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\ttargetChannelID,\n\t\t\treasonID: i,\n\t\t\tinvokerID: Y(e.params.invokerid ?? \"\"),\n\t\t\tinvokerName: e.params.invokername ?? \"\",\n\t\t\tinvokerUID: e.params.invokeruid ?? \"\"\n\t\t}\n\t} : {\n\t\tkind: \"clientLeave\",\n\t\tevent: {\n\t\t\tid: r,\n\t\t\treasonID: i,\n\t\t\treasonMsg: e.params.reasonmsg ?? \"\",\n\t\t\ttargetID: Y(e.params.targetid ?? \"\")\n\t\t},\n\t\tisSelf: a\n\t};\n}",
],
[
"\t#c = /* @__PURE__ */ new Map();\n\t#l = [];",
"\t#c = /* @__PURE__ */ new Map();\n\t#q = /* @__PURE__ */ new Map();\n\t#R = [];\n\t#L = false;\n\t#l = [];",
],
[
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
"\t\t\tcase \"voiceData\":\n\t\t\t\tthis.#h.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"directorySnapshot\":\n\t\t\t\tthis.#R.push(t);\n\t\t\t\tbreak;\n\t\t\tcase \"connected\":",
],
[
"this.#o.reset(), this.#s.reset(), this.#c.clear(), this.clid = 0",
"this.#o.reset(), this.#s.reset(), this.#q.clear(), this.#c.clear(), this.#L = false, this.clid = 0",
],
[
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":",
"\t\t\t\tcase \"initserver\":\n\t\t\t\t\tH(this, t.params);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"channellist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryChannel(t.params, S);\n\t\t\t\t\tif (e) this.#q.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"channelclientlist\": {\n\t\t\t\t\tconst e = webSpeakDirectoryClient(t.params, S);\n\t\t\t\t\tif (e) this.#c.set(e.id, e);\n\t\t\t\t\tthis.#Y();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"error\":",
],
[
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\treturn;\n\t\t\t}",
"\t\t\tif (t.name.startsWith(\"notify\")) {\n\t\t\t\tconst directoryChanged = webSpeakDirectoryChannelNotification(t.name, t.params, S, this.#q);\n\t\t\t\tlet e = ne(t, this.clid, this.#c, this.nickname);\n\t\t\t\tthis.#j(e, t.params);\n\t\t\t\tif (directoryChanged) this.#Y();\n\t\t\t\treturn;\n\t\t\t}",
],
[
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tt.id !== 0 && Z(this.nickname, t.nickname) && (this.clid = t.id, this.handler.setClientID(t.id), this.#o.signalWelcomeComplete()), this.#M(\"clientEnter\", t);\n\t\t\t\tbreak;\n\t\t\t}",
"\t\t\tcase \"clientEnter\": {\n\t\t\t\tlet t = e.info;\n\t\t\t\tconst rawChannelID = webSpeakDirectoryBigInt(arguments[1]?.cid ?? arguments[1]?.ctid ?? \"0\");\n\t\t\t\tif (rawChannelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: rawChannelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst cached = this.#c.get(t.id);\n\t\t\t\tif (cached && t.channelID === 0n && cached.channelID !== 0n) {\n\t\t\t\t\tt = { ...t, channelID: cached.channelID };\n\t\t\t\t\tthis.#c.set(t.id, t);\n\t\t\t\t}\n\t\t\t\tconst own = t.id !== 0 && Z(this.nickname, t.nickname);\n\t\t\t\tif (own) {\n\t\t\t\t\tthis.clid = t.id;\n\t\t\t\t\tthis.handler.setClientID(t.id);\n\t\t\t\t\tthis.#o.signalWelcomeComplete();\n\t\t\t\t\tthis.#Y();\n\t\t\t\t}\n\t\t\t\tthis.#M(\"clientEnter\", t);\n\t\t\t\tif (!own && this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;\n\t\t\t}",
],
[
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
"\t\t\tcase \"clientLeave\":\n\t\t\t\tif (this.#M(\"clientLeave\", e.event), this.#i === n.Connected && this.#Y(), e.isSelf && (e.event.reasonID === 4 || e.event.reasonID === 5)) {",
],
[
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tbreak;",
"\t\t\tcase \"clientMoved\":\n\t\t\t\tthis.#M(\"clientMoved\", e.event);\n\t\t\t\tif (this.#i === n.Connected) this.#Y();\n\t\t\t\tbreak;",
],
[
"\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
"\t#Y() {\n\t\tif (this.#L) return;\n\t\tthis.#L = true;\n\t\tsetImmediate(() => {\n\t\t\tthis.#L = false;\n\t\t\tconst e = {\n\t\t\t\tchannels: Array.from(this.#q.values()).map((item) => ({ ...item })),\n\t\t\t\tclients: Array.from(this.#c.values()).map((item) => ({ ...item, serverGroups: [...(item.serverGroups ?? [])] })),\n\t\t\t};\n\t\t\tfor (const handler of this.#R) setImmediate(() => handler(e));\n\t\t});\n\t}\n\t#M(e, t) {\n\t\tthis.#S(t);\n\t}\n\t#N(e, t) {",
],
];
for (const [before, after] of replacements) {
if (!source.includes(before)) throw new Error(`Could not patch MJS SDK segment: ${before.slice(0, 80)}`);
source = source.replace(before, after);
}
return source;
}
+48
View File
@@ -0,0 +1,48 @@
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import process from "node:process";
const root = process.cwd();
const sdkPackage = "@echosixhiya/teamspeak-client";
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const dependency = packageJson.dependencies?.[sdkPackage];
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
if (!match) {
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
}
const [, repository, commit] = match;
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
try {
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
const runNpm = (args) => {
if (process.platform === "win32") {
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
} else {
execFileSync("npm", args, npmOptions);
}
};
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
runNpm(["run", "build"]);
const source = join(temporaryRoot, "dist");
if (!existsSync(join(source, "index.mjs"))) {
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
}
mkdirSync(dirname(destination), { recursive: true });
mkdirSync(destination, { recursive: true });
for (const entry of readdirSync(source)) {
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
}
console.log(`Prepared ${sdkPackage} from ${commit}`);
} finally {
rmSync(temporaryRoot, { recursive: true, force: true });
}
+624
View File
@@ -0,0 +1,624 @@
import { Router, type NextFunction, type Request, type Response } from "express";
import { existsSync, readFileSync } from "node:fs";
import type { Logger } from "../logger.js";
import { AdminInputError, AdminService, type AdminSettingsInput, 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";
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;
startedAt: number;
}
export function createAdminRouter(options: AdminRouterOptions): Router {
const router = Router();
const limiter = new AdminLoginRateLimiter();
const logger = options.logger.child({ component: "admin-api" });
router.use((_request, response, next) => {
response.setHeader("Cache-Control", "no-store");
next();
});
router.get("/status", (_request, response) => {
response.json({ initialized: options.service.isInitialized() });
});
router.get("/session", (request, response) => {
const session = options.sessions.get(request);
response.json({
initialized: options.service.isInitialized(),
authenticated: Boolean(session),
mustChangePassword: Boolean(session) && options.service.isPasswordChangeRequired(),
...(session ? { csrfToken: session.csrfToken, expiresAt: session.expiresAt } : {}),
});
});
router.post("/login", requireSameOrigin, async (request, response) => {
if (!options.service.isInitialized()) {
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
const peer = request.socket.remoteAddress ?? "unknown";
const retryAfterMs = limiter.retryAfterMs(peer);
if (retryAfterMs > 0) {
response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
return;
}
const body = asRecord(request.body);
const username = readString(body, "username", 64).trim();
const password = readOptionalString(body, "password", 1024);
if (!await options.service.verifyPassword(username, password)) {
const delayMs = limiter.recordFailure(peer);
await waitFor(delayMs);
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
logger.warn("Administrator login failed");
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
return;
}
limiter.recordSuccess(peer);
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
const session = options.sessions.create(response, isSecureRequest(request));
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
});
router.post("/change-password", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
const body = asRecord(request.body);
await options.service.changePassword(readString(body, "newPassword", 1024));
response.json({ ok: true, mustChangePassword: false });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/logout", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
options.sessions.destroy(request, response, isSecureRequest(request));
options.service.database.addAudit("ADMIN_LOGOUT");
response.json({ ok: true });
});
router.use(requireAdmin(options.sessions, options.service));
router.get("/overview", (_request, response) => {
response.json(options.service.getOverview(
options.getActiveSessions(),
options.getPeakSessions(),
options.startedAt,
));
});
router.get("/server", (_request, response) => {
response.json(options.service.getAdminSettings());
});
router.get("/sessions", (_request, response) => {
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
});
router.post("/sessions/:id/terminate", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!options.terminateSession || !id || !(await options.terminateSession(id))) {
response.status(404).json({ ok: false, code: "SESSION_NOT_FOUND" });
return;
}
options.service.database.addAudit("ADMIN_SESSION_TERMINATED", { id });
response.json({ ok: true });
});
router.get("/invites", (_request, response) => {
response.json({ invites: options.service.listManagedInvites() });
});
router.post("/invites", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
const body = asRecord(request.body);
const created = options.service.createManagedInvite({
channel: readOptionalString(body, "channel", 100),
expiresInHours: readOptionalNumber(body, "expiresInHours", 1),
maxUses: readOptionalNumber(body, "maxUses", 0),
});
response.status(201).json({ ok: true, ...created });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/invites/:id/revoke", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!id) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
if (!options.service.revokeManagedInvite(id)) {
response.status(404).json({ ok: false, code: "INVITE_NOT_FOUND" });
return;
}
response.json({ ok: true });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.get("/audit", (request, response) => {
response.json({ events: options.service.database.recentAudit(readLimit(request.query.limit, 50)) });
});
router.get("/logs", (request, response) => {
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,
) as unknown as AdminOverview;
response.json({
generatedAt: new Date().toISOString(),
gateway: {
version: options.version ?? "0.1.0",
uptimeSeconds: overview.gateway.uptimeSeconds,
node: process.version,
platform: process.platform,
arch: process.arch,
},
sessions: {
active: options.getActiveSessions(),
peak: options.getPeakSessions(),
created: options.getCreatedSessions?.() ?? 0,
limit: 100,
},
teamSpeak: overview.teamSpeak,
database: { schemaVersion: options.service.database.schemaVersion },
logs: { available: Boolean(options.logFile && existsSync(options.logFile)) },
});
});
router.get("/diagnostics/report", (_request, response) => {
const overview = options.service.getOverview(
options.getActiveSessions(),
options.getPeakSessions(),
options.startedAt,
) as unknown as AdminOverview;
const report = {
generatedAt: new Date().toISOString(),
gateway: {
version: options.version ?? "0.1.0",
uptimeSeconds: overview.gateway.uptimeSeconds,
node: process.version,
platform: process.platform,
arch: process.arch,
},
sessions: {
active: options.getActiveSessions(),
peak: options.getPeakSessions(),
created: options.getCreatedSessions?.() ?? 0,
limit: 100,
},
teamSpeak: {
status: overview.teamSpeak.status,
lastTestAt: overview.teamSpeak.lastTestAt,
latencyMs: overview.teamSpeak.latencyMs,
lastError: overview.teamSpeak.lastError,
},
database: { schemaVersion: options.service.database.schemaVersion },
audit: options.service.database.recentAudit(50),
};
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.setHeader("Content-Disposition", `attachment; filename="webspeak-diagnostic-report.json"`);
response.send(JSON.stringify(report, null, 2));
});
router.get("/backup", (_request, response) => {
try {
const backup = options.service.database.exportBackup();
options.service.database.addAudit("ADMIN_BACKUP_EXPORTED");
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", `attachment; filename="webspeak-backup-${new Date().toISOString().slice(0, 10)}.db"`);
response.send(backup);
} catch {
response.status(500).json({ ok: false, code: "BACKUP_FAILED" });
}
});
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
response.json({ ok: true, settings: options.service.getAdminSettings() });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/server/test", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const body = asRecord(request.body);
const action = readPasswordAction(body.passwordAction);
const password = action === "remove"
? ""
: typeof body.serverPassword === "string"
? body.serverPassword.slice(0, 512)
: options.service.getConnectionPolicy().serverPassword;
await runProbe(options.service, response, readString(body, "target", 300), password, true);
});
router.post("/legacy-import/dismiss", requireSameOrigin, requireCsrf(options.sessions), (_request, response) => {
options.service.dismissLegacyImportNotice();
response.json({ ok: true });
});
router.use((error: unknown, _request: Request, response: Response, _next: NextFunction) => {
sendAdminError(response, error);
});
return router;
}
function requireAdmin(sessions: AdminSessionStore, service: AdminService) {
return (request: Request, response: Response, next: NextFunction): void => {
if (!sessions.get(request)) {
response.status(401).json({ ok: false, code: "AUTH_REQUIRED" });
return;
}
if (service.isPasswordChangeRequired()) {
response.status(403).json({ ok: false, code: "PASSWORD_CHANGE_REQUIRED" });
return;
}
next();
};
}
function requireCsrf(sessions: AdminSessionStore) {
return (request: Request, response: Response, next: NextFunction): void => {
const session = sessions.get(request);
const csrf = request.header("x-csrf-token");
if (!session || !csrf || csrf !== session.csrfToken) {
response.status(403).json({ ok: false, code: "CSRF_REJECTED" });
return;
}
next();
};
}
function requireSameOrigin(request: Request, response: Response, next: NextFunction): void {
if (!request.is("application/json")) {
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
return;
}
const origin = request.header("origin");
const host = request.header("host");
try {
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
} catch {
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
return;
}
next();
}
async function runProbe(
service: AdminService,
response: Response,
target: string,
password: string,
persistResult: boolean,
): Promise<void> {
try {
response.json(await service.testConnection(target, password, persistResult));
} catch (error: unknown) {
if (error instanceof TeamSpeakProbeError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
sendAdminError(response, error);
}
}
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
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,
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 ?? ""));
}
interface AdminOverview {
gateway: { uptimeSeconds: number };
teamSpeak: {
target: string;
status: string;
lastTestAt: string | null;
latencyMs: number | null;
lastError: string | null;
};
}
function logLevelName(level: unknown): string {
if (level === 10) return "DEBUG";
if (level === 30) return "INFO";
if (level === 40) return "WARN";
if (level === 50) return "ERROR";
if (level === 60) return "FATAL";
return typeof level === "string" ? level.toUpperCase() : "INFO";
}
function sendAdminError(response: Response, error: unknown): void {
if (error instanceof AdminInputError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
}
+634
View File
@@ -0,0 +1,634 @@
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 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 AdminSettingsInput {
target: string;
serverPassword?: string;
passwordAction?: "keep" | "replace" | "remove";
accessMode: AccessMode;
siteName: string;
welcomeText: string;
welcomeTextEn?: string;
welcomeTextDe?: string;
welcomeTextRu?: string;
welcomeTextJa?: string;
webRtcEnabled: boolean;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
relaySettingsAction?: "keep" | "replace" | "remove";
relayEnabled?: boolean;
relayName?: string;
relayTarget?: string;
relayToken?: string;
relayTokenAction?: "keep" | "replace" | "remove";
relayNodes?: RelayNodeInput[];
}
export interface RelayNodeInput {
id?: string;
name: string;
target: string;
enabled: boolean;
token?: string;
tokenAction?: "keep" | "replace" | "remove";
}
export interface ConnectionPolicy {
defaultTarget: TeamSpeakTarget;
serverPassword: string;
accessMode: AccessMode;
}
export interface ManagedInviteInput {
channel: string;
expiresInHours: number;
maxUses: number;
}
export interface ManagedInviteView {
id: string;
target: string;
channel: string;
expiresAt: string;
maxUses: number;
useCount: number;
createdAt: string;
revokedAt: string | null;
status: "active" | "expired" | "exhausted" | "revoked";
}
type ProbeFunction = typeof probeTeamSpeak;
export class AdminService {
constructor(
readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
private readonly logger: Logger,
private readonly legacyConfigPath: string,
private readonly probe: ProbeFunction = probeTeamSpeak,
private readonly version = "0.1.0",
) {}
async initialize(): Promise<void> {
this.importLegacyConfigOnce();
if (!this.database.hasAdmin()) {
const credential = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
this.database.initializeAdmin(credential, this.toSettingsUpdate(this.database.getSettings()));
this.logger.warn("Default admin account created. Change the password on first login.");
}
}
isInitialized(): boolean {
return this.database.hasAdmin();
}
async verifyPassword(username: string, password: string): Promise<boolean> {
const credential = this.database.getAdminCredential();
return credential?.username === username && await verifyAdminPassword(password, credential);
}
isPasswordChangeRequired(): boolean {
return this.database.getAdminCredential()?.mustChangePassword === true;
}
async changePassword(password: string): Promise<void> {
const credential = this.database.getAdminCredential();
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
const passwordError = validateAdminPassword(password);
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
this.database.updateAdminCredential(replacement);
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
}
getPublicConfig(): Record<string, unknown> {
const settings = this.database.getSettings();
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(): Record<string, unknown> {
const settings = this.database.getSettings();
return {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
hasPassword: Boolean(settings.tsPasswordEncrypted),
accessMode: settings.accessMode,
siteName: settings.siteName,
welcomeText: settings.welcomeText,
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,
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,
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): Record<string, unknown> {
const settings = this.database.getSettings();
return {
gateway: {
status: "running",
version: this.version,
uptimeSeconds: Math.max(0, Math.floor((Date.now() - startedAt) / 1000)),
},
teamSpeak: {
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
lastTestAt: settings.lastTestAt,
latencyMs: settings.lastTestLatencyMs,
lastError: settings.lastTestError,
},
sessions: { active: activeSessions, peak: peakSessions, limit: 100 },
recentEvents: this.database.recentAudit(),
legacyConfigImported: this.database.getMeta("legacy_import_notice_pending") === "1",
};
}
createManagedInvite(input: ManagedInviteInput): { invite: ManagedInviteView; token: string } {
const channel = input.channel.trim();
if (channel.length > 100) throw new AdminInputError("INVALID_INVITE_CHANNEL", "Invite channel cannot exceed 100 characters");
if (!Number.isFinite(input.expiresInHours) || input.expiresInHours < 1 || input.expiresInHours > 720) {
throw new AdminInputError("INVALID_INVITE_EXPIRY", "Invite expiry must be between 1 and 720 hours");
}
if (!Number.isInteger(input.maxUses) || input.maxUses < 0 || input.maxUses > 10000) {
throw new AdminInputError("INVALID_INVITE_USES", "Invite max uses must be between 0 and 10000");
}
const settings = this.database.getSettings();
const token = randomBytes(32).toString("base64url");
const record = this.database.createManagedInvite({
id: `invite-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`,
tokenHash: hashInviteToken(token),
targetHost: settings.tsHost,
targetPort: settings.tsPort,
serverPasswordEncrypted: settings.tsPasswordEncrypted,
channel,
expiresAt: new Date(Date.now() + input.expiresInHours * 60 * 60 * 1000).toISOString(),
maxUses: input.maxUses,
});
this.database.addAudit("INVITE_CREATED", { id: record.id, channel, maxUses: input.maxUses });
return { invite: this.toInviteView(record), token };
}
listManagedInvites(): ManagedInviteView[] {
return this.database.listManagedInvites().map((record) => this.toInviteView(record));
}
revokeManagedInvite(id: string): boolean {
if (!/^invite-[a-z0-9-]+$/i.test(id) || id.length > 100) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
const revoked = this.database.revokeManagedInvite(id);
if (revoked) this.database.addAudit("INVITE_REVOKED", { id });
return revoked;
}
consumeManagedInvite(token: string): { target: TeamSpeakTarget; serverPassword: string; channel: string } | null {
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
const record = this.database.consumeManagedInvite(hashInviteToken(token));
if (!record) return null;
let serverPassword = "";
try {
serverPassword = decryptSecret(record.serverPasswordEncrypted, this.masterSecret);
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error), inviteId: record.id }, "Managed invite password could not be decrypted");
}
this.database.addAudit("INVITE_CONSUMED", { id: record.id });
return { target: { host: record.targetHost, port: record.targetPort }, serverPassword, channel: record.channel };
}
dismissLegacyImportNotice(): void {
this.database.setMeta("legacy_import_notice_pending", "0");
}
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>, 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 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,
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,
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,
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";
}
}
+77
View File
@@ -0,0 +1,77 @@
import { createHash, randomBytes } from "node:crypto";
import type { Request, Response } from "express";
import type { TLSSocket } from "node:tls";
const COOKIE_NAME = "webspeak_admin";
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
interface AdminSession {
csrfToken: string;
expiresAt: number;
}
export class AdminSessionStore {
private readonly sessions = new Map<string, AdminSession>();
create(response: Response, secure: boolean, now = Date.now()): { csrfToken: string; expiresAt: number } {
const token = randomBytes(32).toString("base64url");
const csrfToken = randomBytes(24).toString("base64url");
const expiresAt = now + SESSION_TTL_MS;
this.sessions.set(hashToken(token), { csrfToken, expiresAt });
response.cookie(COOKIE_NAME, token, {
httpOnly: true,
sameSite: "strict",
secure,
path: "/",
maxAge: SESSION_TTL_MS,
});
return { csrfToken, expiresAt };
}
get(request: Request, now = Date.now()): AdminSession | null {
const token = readCookie(request.headers.cookie, COOKIE_NAME);
if (!token) return null;
const key = hashToken(token);
const session = this.sessions.get(key);
if (!session) return null;
if (session.expiresAt <= now) {
this.sessions.delete(key);
return null;
}
return session;
}
destroy(request: Request, response: Response, secure: boolean): void {
const token = readCookie(request.headers.cookie, COOKIE_NAME);
if (token) this.sessions.delete(hashToken(token));
response.clearCookie(COOKIE_NAME, { httpOnly: true, sameSite: "strict", secure, path: "/" });
}
clear(): void {
this.sessions.clear();
}
}
export function isSecureRequest(request: Request): boolean {
return (request.socket as TLSSocket).encrypted === true;
}
function hashToken(token: string): string {
return createHash("sha256").update(token).digest("base64url");
}
function readCookie(header: string | undefined, name: string): string | null {
if (!header) return null;
for (const part of header.split(";")) {
const separator = part.indexOf("=");
if (separator < 0) continue;
if (part.slice(0, separator).trim() === name) {
try {
return decodeURIComponent(part.slice(separator + 1).trim());
} catch {
return null;
}
}
}
return null;
}
+55
View File
@@ -0,0 +1,55 @@
const WINDOW_MS = 5 * 60 * 1000;
const MAX_FAILURES = 5;
interface LoginAttempt {
failures: number;
firstFailureAt: number;
}
export class AdminLoginRateLimiter {
private readonly attempts = new Map<string, LoginAttempt>();
constructor(private readonly maxTrackedPeers = 1024) {}
retryAfterMs(peer: string, now = Date.now()): number {
const attempt = this.attempts.get(peer);
if (!attempt) return 0;
if (now - attempt.firstFailureAt >= WINDOW_MS) {
this.attempts.delete(peer);
return 0;
}
if (attempt.failures < MAX_FAILURES) return 0;
return WINDOW_MS - (now - attempt.firstFailureAt);
}
recordFailure(peer: string, now = Date.now()): number {
const current = this.attempts.get(peer);
if (!current) {
this.pruneExpired(now);
while (this.attempts.size >= this.maxTrackedPeers) {
const oldestPeer = this.attempts.keys().next().value;
if (!oldestPeer) break;
this.attempts.delete(oldestPeer);
}
}
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
? { failures: 1, firstFailureAt: now }
: { ...current, failures: current.failures + 1 };
this.attempts.set(peer, attempt);
return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
}
recordSuccess(peer: string): void {
this.attempts.delete(peer);
}
private pruneExpired(now: number): void {
for (const [peer, attempt] of this.attempts) {
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
}
}
}
export function waitFor(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+45 -36
View File
@@ -1,65 +1,74 @@
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import {
DEFAULT_TEAM_SPEAK_PORT,
parseTeamSpeakTargetParts,
} from "./domain/teamspeak-target.js";
/** The only TeamSpeak state still read from the legacy JSON config. */
export interface AppConfig {
/** HTTP server port */
port: number;
/** TeamSpeak server host */
tsHost: string;
/** TeamSpeak voice/UDP port */
tsPort: number;
/** TS server password (empty if none) */
tsServerPassword: string;
/** Force protocol: "ts3" | "ts6" | undefined for auto-detect */
tsServerProtocol?: "ts3" | "ts6";
/** Max concurrent web clients */
maxClients: number;
/** Trust X-Forwarded-* headers (for reverse proxy) */
trustProxy: boolean;
}
export function getDefaultConfig(): AppConfig {
return {
port: 3040,
tsHost: "127.0.0.1",
tsPort: 9987,
tsPort: DEFAULT_TEAM_SPEAK_PORT,
tsServerPassword: "",
tsServerProtocol: undefined,
maxClients: 20,
trustProxy: false,
};
}
/**
* Convert both the old JSON shape and the M000 shape into the normalized
* normalized legacy model. Deprecated fields are intentionally ignored and disappear
* when the migrated model is written back.
*/
export function migrateConfig(input: unknown): AppConfig {
const defaults = getDefaultConfig();
if (!isRecord(input)) return defaults;
const rawHost = typeof input.tsHost === "string" && input.tsHost.trim()
? input.tsHost.trim()
: defaults.tsHost;
const rawPort = input.tsPort === undefined ? undefined : input.tsPort;
let target;
try {
target = parseTeamSpeakTargetParts(rawHost, toPortValue(rawPort), defaults.tsPort);
} catch {
target = { host: defaults.tsHost, port: defaults.tsPort };
}
return {
tsHost: target.host,
tsPort: target.port,
tsServerPassword: typeof input.tsServerPassword === "string" ? input.tsServerPassword : defaults.tsServerPassword,
};
}
export function loadConfig(path: string): AppConfig {
const defaults = getDefaultConfig();
try {
const input = JSON.parse(readFileSync(path, "utf-8")) as Record<string, unknown>;
const positiveInt = (value: unknown, fallback: number) => {
const number = typeof value === "number" ? value : Number(value);
return Number.isInteger(number) && number > 0 ? number : fallback;
};
const protocol = input.tsServerProtocol === "ts3" || input.tsServerProtocol === "ts6"
? input.tsServerProtocol
: defaults.tsServerProtocol;
return {
port: positiveInt(input.port, defaults.port),
tsHost: typeof input.tsHost === "string" && input.tsHost.trim() ? input.tsHost.trim() : defaults.tsHost,
tsPort: positiveInt(input.tsPort, defaults.tsPort),
tsServerPassword: typeof input.tsServerPassword === "string" ? input.tsServerPassword : defaults.tsServerPassword,
tsServerProtocol: protocol,
maxClients: positiveInt(input.maxClients, defaults.maxClients),
trustProxy: typeof input.trustProxy === "boolean" ? input.trustProxy : defaults.trustProxy,
};
return migrateConfig(JSON.parse(readFileSync(path, "utf-8")) as unknown);
} catch {
return defaults;
return getDefaultConfig();
}
}
/** Write only the normalized legacy shape; this is the one-time legacy cleanup. */
export function saveConfig(path: string, config: AppConfig): void {
try {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(config, null, 2), "utf-8");
writeFileSync(path, JSON.stringify(migrateConfig(config), null, 2), "utf-8");
} catch {
// config.json may be read-only (e.g. running under systemd as non-root)
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function toPortValue(value: unknown): string | number | undefined {
return typeof value === "string" || typeof value === "number" ? value : undefined;
}
+9
View File
@@ -0,0 +1,9 @@
/** The HTTP port is part of the WebSpeak deployment contract. */
export const APP_PORT = 3040;
/** Hard safety ceiling for independently connected browser sessions. */
export const MAX_ACTIVE_SESSIONS = 100;
export function canAcceptSession(activeSessionCount: number): boolean {
return Number.isInteger(activeSessionCount) && activeSessionCount >= 0 && activeSessionCount < MAX_ACTIVE_SESSIONS;
}
+99
View File
@@ -0,0 +1,99 @@
export const DEFAULT_TEAM_SPEAK_PORT = 9987;
export interface TeamSpeakTarget {
host: string;
port: number;
}
export class InvalidTeamSpeakTargetError extends Error {
constructor(message = "Invalid TeamSpeak server address") {
super(message);
this.name = "InvalidTeamSpeakTargetError";
}
}
/** Parse a user-facing TeamSpeak target such as example.com:9988 or example.com#9988. */
export function parseTeamSpeakTarget(value: string, fallbackPort = DEFAULT_TEAM_SPEAK_PORT): TeamSpeakTarget {
const input = value.trim();
if (!input) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
const hash = input.indexOf("#");
if (hash >= 0) {
if (input.indexOf("#", hash + 1) >= 0) {
throw new InvalidTeamSpeakTargetError("TeamSpeak target has too many port separators");
}
const hashHost = input.slice(0, hash);
const host = hashHost.startsWith("[") && hashHost.endsWith("]") ? hashHost.slice(1, -1) : hashHost;
return createTarget(host, input.slice(hash + 1));
}
if (input.startsWith("[")) {
const closingBracket = input.indexOf("]");
if (closingBracket < 0) throw new InvalidTeamSpeakTargetError("IPv6 addresses must close with ]");
const host = input.slice(1, closingBracket);
const suffix = input.slice(closingBracket + 1);
if (suffix && !suffix.startsWith(":")) {
throw new InvalidTeamSpeakTargetError("Invalid port separator after IPv6 address");
}
return createTarget(host, suffix ? suffix.slice(1) : fallbackPort);
}
const colon = input.indexOf(":");
if (colon < 0) return createTarget(input, fallbackPort);
if (input.indexOf(":", colon + 1) >= 0) {
throw new InvalidTeamSpeakTargetError("IPv6 addresses must use bracket notation");
}
return createTarget(input.slice(0, colon), input.slice(colon + 1));
}
/** Parse the legacy split host/port fields while accepting a bracketed IPv6 host. */
export function parseTeamSpeakTargetParts(
hostValue: string,
portValue?: string | number,
fallbackPort = DEFAULT_TEAM_SPEAK_PORT,
): TeamSpeakTarget {
const host = hostValue.trim();
if (!host) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
if (portValue !== undefined && String(portValue).trim() !== "") {
const hostOnly = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
if (hostOnly.includes(":")) return createTarget(hostOnly, portValue);
if (host.includes(":")) {
throw new InvalidTeamSpeakTargetError("Use one TeamSpeak address field when specifying a port");
}
return createTarget(hostOnly, portValue);
}
return parseTeamSpeakTarget(host, fallbackPort);
}
export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
return target.host.includes(":") ? `[${target.host}]:${target.port}` : `${target.host}:${target.port}`;
}
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
return formatTeamSpeakTarget(target).toLocaleLowerCase();
}
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
const host = hostValue.trim().toLocaleLowerCase();
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
if (host.includes(":")) {
// A raw IPv6 host is valid only when it came from bracket notation.
if (!host.split(":").every((part) => /^[0-9a-f]*$/i.test(part))) {
throw new InvalidTeamSpeakTargetError("Invalid IPv6 server address");
}
} else if (!/^[a-z0-9._-]+$/i.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
const portText = String(portValue).trim();
if (!/^\d+$/.test(portText)) throw new InvalidTeamSpeakTargetError("TeamSpeak port must be a number");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new InvalidTeamSpeakTargetError("TeamSpeak port must be between 1 and 65535");
}
return { host, port };
}
+416
View File
@@ -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;
}
+89 -16
View File
@@ -1,40 +1,69 @@
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";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
const CONFIG_PATH = path.join(ROOT_DIR, "config.json");
const CERT_DIR = path.join(ROOT_DIR, "certs");
const DATA_DIR = path.join(ROOT_DIR, "data");
// Production images mount the persistent volume at /data. Source installs
// keep the historical project-local data directory unless overridden.
const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "data");
const LOG_DIR = path.join(DATA_DIR, "logs");
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
const APP_VERSION = readPackageVersion();
async function main() {
const config = loadConfig(CONFIG_PATH);
saveConfig(CONFIG_PATH, config);
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(),
// 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,
logger,
});
@@ -44,12 +73,56 @@ 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";
}
main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
+55 -16
View File
@@ -1,5 +1,9 @@
import pino from "pino";
import { mkdirSync } from "node:fs";
import { appendFile, existsSync, mkdirSync, renameSync, statSync } from "node:fs";
import { Writable } from "node:stream";
const MAX_LOG_BYTES = 10 * 1024 * 1024;
const MAX_ROTATED_LOGS = 3;
export interface Logger {
debug(obj: Record<string, unknown>, msg: string): void;
@@ -14,23 +18,17 @@ export interface Logger {
}
export function createLogger(logDir?: string): Logger {
const targets: pino.TransportTargetOptions[] = [
{ target: "pino/file", options: { destination: 1 }, level: "info" },
];
if (logDir) {
mkdirSync(logDir, { recursive: true });
targets.push({
target: "pino/file",
options: { destination: `${logDir}/webspeak.log` },
level: "debug",
});
}
const baseLogger = pino({
const loggerOptions = {
level: "debug",
timestamp: pino.stdTimeFunctions.isoTime,
...(targets.length > 1 ? { transport: { targets } } : {}),
});
redact: {
paths: ["password", "*.password", "serverPassword", "*.serverPassword", "token", "*.token", "identity", "*.identity"],
censor: "[Redacted]",
},
};
const baseLogger = logDir
? createFileLogger(loggerOptions, `${logDir}/webspeak.log`)
: pino(loggerOptions, pino.destination(1));
function wrap(l: pino.Logger): Logger {
function doLog(
@@ -60,3 +58,44 @@ export function createLogger(logDir?: string): Logger {
return wrap(baseLogger);
}
function createFileLogger(options: { level: string; timestamp: typeof pino.stdTimeFunctions.isoTime }, logPath: string): pino.Logger {
mkdirSync(logPath.replace(/[\\/][^\\/]+$/, ""), { recursive: true });
return pino(options, pino.multistream([
{ level: "info", stream: process.stdout },
{ level: "debug", stream: new RotatingFileStream(logPath) },
]));
}
class RotatingFileStream extends Writable {
private bytes: number;
constructor(private readonly filePath: string) {
super();
this.bytes = existsSync(filePath) ? statSync(filePath).size : 0;
if (this.bytes >= MAX_LOG_BYTES) this.rotate();
}
override _write(chunk: unknown, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), encoding);
try {
if (this.bytes + buffer.length > MAX_LOG_BYTES) this.rotate();
appendFile(this.filePath, buffer, (error) => {
if (!error) this.bytes += buffer.length;
callback(error);
});
} catch (error: unknown) {
callback(error instanceof Error ? error : new Error(String(error)));
}
}
private rotate(): void {
for (let index = MAX_ROTATED_LOGS - 1; index >= 1; index--) {
const source = `${this.filePath}.${index}`;
const destination = `${this.filePath}.${index + 1}`;
if (existsSync(source)) renameSync(source, destination);
}
if (existsSync(this.filePath)) renameSync(this.filePath, `${this.filePath}.1`);
this.bytes = 0;
}
}
+627
View File
@@ -0,0 +1,627 @@
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 = 7;
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;
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;
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_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,
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);
}
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");
});
}
}
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_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.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,
};
}
+30
View File
@@ -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";
}
+75
View File
@@ -0,0 +1,75 @@
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
const KEY_LENGTH = 64;
const SCRYPT_PARAMETERS = Object.freeze({ N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
export interface AdminCredential {
version: 1;
username: string;
mustChangePassword: boolean;
salt: string;
hash: string;
parameters: {
N: number;
r: number;
p: number;
};
}
export interface AdminPasswordOptions {
username?: string;
mustChangePassword?: boolean;
allowWeakPassword?: boolean;
}
export function validateAdminPassword(password: string): string | null {
if (password.length < 12) return "Admin password must contain at least 12 characters";
if (password.length > 1024) return "Admin password is too long";
return null;
}
export async function hashAdminPassword(password: string, options: AdminPasswordOptions = {}): Promise<AdminCredential> {
const validationError = options.allowWeakPassword ? null : validateAdminPassword(password);
if (validationError) throw new Error(validationError);
const salt = randomBytes(16);
const hash = await derive(password, salt, SCRYPT_PARAMETERS);
return {
version: 1,
username: options.username ?? "admin",
mustChangePassword: options.mustChangePassword ?? false,
salt: salt.toString("base64url"),
hash: hash.toString("base64url"),
parameters: {
N: SCRYPT_PARAMETERS.N,
r: SCRYPT_PARAMETERS.r,
p: SCRYPT_PARAMETERS.p,
},
};
}
export async function verifyAdminPassword(password: string, credential: AdminCredential): Promise<boolean> {
if (credential.version !== 1 || typeof password !== "string" || password.length > 1024) return false;
try {
const expected = Buffer.from(credential.hash, "base64url");
const actual = await derive(password, Buffer.from(credential.salt, "base64url"), {
...credential.parameters,
maxmem: 64 * 1024 * 1024,
});
return expected.length === actual.length && timingSafeEqual(expected, actual);
} catch {
return false;
}
}
async function derive(
password: string,
salt: Buffer,
parameters: { N: number; r: number; p: number; maxmem: number },
): Promise<Buffer> {
return new Promise((resolve, reject) => {
scrypt(password, salt, KEY_LENGTH, parameters, (error, result) => {
if (error) reject(error);
else resolve(Buffer.from(result));
});
});
}
+42
View File
@@ -0,0 +1,42 @@
import {
chmodSync,
closeSync,
mkdirSync,
openSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
import { randomBytes } from "node:crypto";
const MASTER_KEY_BYTES = 32;
/** Create or load the installation-local key used to protect secrets at rest. */
export function loadOrCreateMasterSecret(path: string): Buffer {
mkdirSync(dirname(path), { recursive: true });
try {
const descriptor = openSync(path, "wx", 0o600);
try {
writeFileSync(descriptor, randomBytes(MASTER_KEY_BYTES));
} finally {
closeSync(descriptor);
}
} catch (error: unknown) {
if (!isAlreadyExistsError(error)) throw error;
}
const key = readFileSync(path);
if (key.length !== MASTER_KEY_BYTES) {
throw new Error(`Invalid WebSpeak master secret: expected ${MASTER_KEY_BYTES} bytes`);
}
try {
chmodSync(path, 0o600);
} catch {
// Windows and some container filesystems do not expose POSIX permissions.
}
return key;
}
function isAlreadyExistsError(error: unknown): boolean {
return error instanceof Error && "code" in error && error.code === "EEXIST";
}
+68
View File
@@ -0,0 +1,68 @@
import { isIP } from "node:net";
import { lookup } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export class UnsafeTeamSpeakTargetError extends Error {
constructor(message = "This TeamSpeak target is not allowed in open mode") {
super(message);
this.name = "UnsafeTeamSpeakTargetError";
}
}
/** Resolve and reject addresses that could turn a public gateway into an internal network probe. */
export async function assertSafeOpenTarget(target: TeamSpeakTarget): Promise<void> {
await resolveSafeOpenTarget(target);
}
export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<TeamSpeakTarget> {
const literalVersion = isIP(target.host);
const addresses = literalVersion
? [{ address: target.host, family: literalVersion }]
: await lookup(target.host, { all: true, verbatim: true });
if (!addresses.length || addresses.some(({ address }) => isRestrictedAddress(address))) {
throw new UnsafeTeamSpeakTargetError();
}
// Use the address that was actually validated so a second DNS lookup cannot
// rebind the gateway connection to a private network.
return { host: addresses[0]!.address, port: target.port };
}
export function isRestrictedAddress(address: string): boolean {
const version = isIP(address);
if (version === 4) return isRestrictedIpv4(address);
if (version !== 6) return true;
const normalized = address.toLocaleLowerCase();
if (normalized === "::" || normalized === "::1") return true;
if (normalized.startsWith("::ffff:")) {
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
if (normalized.startsWith("2001:db8:")) return true; // documentation range
return false;
}
function isRestrictedIpv4(address: string): boolean {
const parts = address.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
const [a, b] = parts as [number, number, number, number];
return a === 0
|| a === 10
|| a === 127
|| (a === 100 && b >= 64 && b <= 127)
|| (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 0)
|| (a === 192 && b === 168)
|| (a === 192 && b === 0 && parts[2] === 2)
|| (a === 198 && (b === 18 || b === 19))
|| (a === 198 && b === 51 && parts[2] === 100)
|| (a === 203 && b === 0 && parts[2] === 113)
|| a >= 224;
}
+36
View File
@@ -0,0 +1,36 @@
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHM = "aes-256-gcm";
const VERSION = "v1";
const AAD = Buffer.from("webspeak:teamspeak-password:v1", "utf8");
export function encryptSecret(value: string, masterKey: Buffer): string {
if (!value) return "";
assertMasterKey(masterKey);
const nonce = randomBytes(12);
const cipher = createCipheriv(ALGORITHM, masterKey, nonce);
cipher.setAAD(AAD);
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return [VERSION, nonce.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(":");
}
export function decryptSecret(payload: string | null | undefined, masterKey: Buffer): string {
if (!payload) return "";
assertMasterKey(masterKey);
const [version, nonceText, tagText, ciphertextText, ...extra] = payload.split(":");
if (version !== VERSION || !nonceText || !tagText || ciphertextText === undefined || extra.length) {
throw new Error("Unsupported encrypted secret format");
}
const decipher = createDecipheriv(ALGORITHM, masterKey, Buffer.from(nonceText, "base64url"));
decipher.setAAD(AAD);
decipher.setAuthTag(Buffer.from(tagText, "base64url"));
return Buffer.concat([
decipher.update(Buffer.from(ciphertextText, "base64url")),
decipher.final(),
]).toString("utf8");
}
function assertMasterKey(masterKey: Buffer): void {
if (masterKey.length !== 32) throw new Error("Invalid master key length");
}
+366
View File
@@ -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)); }
+80
View File
@@ -0,0 +1,80 @@
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
import type { TSDirectorySnapshot } from "./ts-client.js";
type DirectoryDelta =
| { type: "clientEnter"; info: ClientInfo }
| { type: "clientLeave"; id: number }
| { type: "clientMoved"; id: number; channelID: bigint };
/**
* Merges staged welcome snapshots with events received while the snapshot is
* in flight. Some TS6 welcome data arrives in more than one partial snapshot,
* so a later snapshot must not hide clients that were present in an earlier
* one. Explicit leave events remain authoritative removals.
*/
export class DirectorySynchronizer {
private snapshot: TSDirectorySnapshot | null = null;
private clients = new Map<number, ClientInfo>();
private pending: DirectoryDelta[] = [];
get ready(): boolean {
return this.snapshot !== null;
}
applySnapshot(snapshot: TSDirectorySnapshot): void {
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
for (const client of snapshot.clients) {
const previous = this.clients.get(client.id);
this.clients.set(client.id, previous ? { ...previous, ...client } : client);
}
const pending = this.pending.splice(0);
for (const delta of pending) this.applyDelta(delta);
}
applyClientEnter(info: ClientInfo): void {
this.applyOrQueue({ type: "clientEnter", info });
}
applyClientLeave(id: number): void {
this.applyOrQueue({ type: "clientLeave", id });
}
applyClientMoved(id: number, channelID: bigint): void {
this.applyOrQueue({ type: "clientMoved", id, channelID });
}
getSnapshot(): TSDirectorySnapshot | null {
if (!this.snapshot) return null;
return {
channels: this.snapshot.channels.slice(),
clients: [...this.clients.values()],
};
}
clear(): void {
this.snapshot = null;
this.clients.clear();
this.pending = [];
}
private applyOrQueue(delta: DirectoryDelta): void {
if (!this.snapshot) {
if (this.pending.length < 4096) this.pending.push(delta);
return;
}
this.applyDelta(delta);
}
private applyDelta(delta: DirectoryDelta): void {
if (delta.type === "clientEnter") {
this.clients.set(delta.info.id, delta.info);
return;
}
if (delta.type === "clientLeave") {
this.clients.delete(delta.id);
return;
}
const current = this.clients.get(delta.id);
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
}
}
+18
View File
@@ -0,0 +1,18 @@
/**
* Prevents one persisted TeamSpeak identity from being used by two live
* browser sessions at the same target at the same time.
*/
export class IdentityLeaseStore {
private readonly owners = new Map<string, string>();
acquire(key: string, owner: string): boolean {
const currentOwner = this.owners.get(key);
if (currentOwner && currentOwner !== owner) return false;
this.owners.set(key, owner);
return true;
}
release(key: string, owner: string): void {
if (this.owners.get(key) === owner) this.owners.delete(key);
}
}
+37
View File
@@ -0,0 +1,37 @@
const WINDOW_MS = 60 * 1000;
const MAX_REQUESTS = 30;
interface PeerWindow {
startedAt: number;
requests: number;
}
/** Bounds opaque join-ticket creation so one peer cannot fill the in-memory store. */
export class JoinRateLimiter {
private readonly peers = new Map<string, PeerWindow>();
constructor(private readonly maxTrackedPeers = 2048) {}
allow(peer: string, now = Date.now()): boolean {
const current = this.peers.get(peer);
if (!current || now - current.startedAt >= WINDOW_MS) {
this.prune(now);
while (this.peers.size >= this.maxTrackedPeers) {
const oldest = this.peers.keys().next().value;
if (!oldest) break;
this.peers.delete(oldest);
}
this.peers.set(peer, { startedAt: now, requests: 1 });
return true;
}
if (current.requests >= MAX_REQUESTS) return false;
current.requests += 1;
return true;
}
private prune(now: number): void {
for (const [peer, window] of this.peers) {
if (now - window.startedAt >= WINDOW_MS) this.peers.delete(peer);
}
}
}
+49
View File
@@ -0,0 +1,49 @@
import { randomBytes } from "node:crypto";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface JoinTicketPayload {
target: TeamSpeakTarget;
serverPassword: string;
nickname: string;
channel?: string;
identity?: string;
rememberIdentity?: boolean;
accelerated?: boolean;
accelerationRelayId?: string;
}
interface StoredTicket {
payload: JoinTicketPayload;
expiresAt: number;
}
export class JoinTicketStore {
private readonly tickets = new Map<string, StoredTicket>();
constructor(private readonly ttlMs = 30_000, private readonly maxTickets = 256) {}
create(payload: JoinTicketPayload, now = Date.now()): string {
this.prune(now);
while (this.tickets.size >= this.maxTickets) {
const oldest = this.tickets.keys().next().value;
if (!oldest) break;
this.tickets.delete(oldest);
}
const token = randomBytes(24).toString("base64url");
this.tickets.set(token, { payload, expiresAt: now + this.ttlMs });
return token;
}
consume(token: string, now = Date.now()): JoinTicketPayload | null {
const stored = this.tickets.get(token);
this.tickets.delete(token);
if (!stored || stored.expiresAt <= now) return null;
return stored.payload;
}
private prune(now: number): void {
for (const [token, stored] of this.tickets) {
if (stored.expiresAt <= now) this.tickets.delete(token);
}
}
}
+190
View File
@@ -0,0 +1,190 @@
import { spawn } from "node:child_process";
export type TeamSpeakPingErrorCode =
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "TIMEOUT"
| "PING_UNAVAILABLE"
| "INVALID_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "INTERNAL_ERROR";
export interface TeamSpeakPingAttempt {
ok: boolean;
latencyMs: number | null;
errorCode?: TeamSpeakPingErrorCode;
}
export interface TeamSpeakPingResult {
ok: boolean;
latencyMs: number | null;
packetLossPercent: number;
attempts: number;
successfulAttempts: number;
samples: number[];
errorCode?: TeamSpeakPingErrorCode;
}
export type TeamSpeakCommandExecutor = (command: string, timeoutMs?: number) => Promise<unknown>;
export type HostPingExecutor = (host: string, timeoutMs: number) => Promise<number>;
/**
* Measure an already connected TeamSpeak session using the protocol's own
* command channel. TeamSpeak voice/query traffic is UDP; a TCP connect to
* port 9987 is therefore not a valid reachability test and reports false
* packet loss even while voice works normally.
*/
export async function pingTeamSpeakSession(
execute: TeamSpeakCommandExecutor,
timeoutMs = 1_500,
): Promise<TeamSpeakPingAttempt> {
const startedAt = Date.now();
try {
// `version` is read-only and is handled by both TS3 and TS6.
await execute("version", timeoutMs);
return { ok: true, latencyMs: Math.max(0, Date.now() - startedAt) };
} catch (error: unknown) {
return {
ok: false,
latencyMs: null,
errorCode: classifyProbeError(error),
};
}
}
export async function collectTeamSpeakPings(
probe: () => Promise<TeamSpeakPingAttempt>,
options: { attempts?: number } = {},
): Promise<TeamSpeakPingResult> {
const attempts = Math.max(1, Math.min(8, Math.floor(options.attempts ?? 4)));
const results: TeamSpeakPingAttempt[] = [];
// Keep attempts sequential. This measures the real protocol path without
// opening several temporary TeamSpeak sessions at the same time.
for (let index = 0; index < attempts; index += 1) {
results.push(await probe());
}
return summarizeTeamSpeakPings(results, attempts);
}
/**
* Ping the TeamSpeak host from the WebSpeak machine without creating a
* TeamSpeak client. This is intentionally a host/network diagnostic: the
* TeamSpeak voice port is UDP, so a TCP socket probe is not meaningful and a
* client-protocol probe would create an extra visible member.
*/
export async function pingTeamSpeakHost(
host: string,
options: { attempts?: number; timeoutMs?: number; execute?: HostPingExecutor } = {},
): Promise<TeamSpeakPingResult> {
const timeoutMs = Math.max(250, Math.min(5_000, Math.floor(options.timeoutMs ?? 1_000)));
const execute = options.execute ?? pingHostOnce;
return collectTeamSpeakPings(async () => {
try {
return { ok: true, latencyMs: await execute(host, timeoutMs) };
} catch (error: unknown) {
return { ok: false, latencyMs: null, errorCode: classifyProbeError(error) };
}
}, { attempts: options.attempts ?? 4 });
}
export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempts = results.length): TeamSpeakPingResult {
const normalizedAttempts = Math.max(1, attempts);
const samples = results
.filter((result): result is TeamSpeakPingAttempt & { latencyMs: number } => result.ok && result.latencyMs !== null)
.map((result) => result.latencyMs)
.sort((left, right) => left - right);
const errorCode = results.find((result) => result.errorCode)?.errorCode;
return {
ok: samples.length > 0,
latencyMs: samples.length ? samples[Math.floor(samples.length / 2)] : null,
packetLossPercent: Math.round(((normalizedAttempts - samples.length) / normalizedAttempts) * 100),
attempts: normalizedAttempts,
successfulAttempts: samples.length,
samples,
...(errorCode ? { errorCode } : {}),
};
}
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
const text = error instanceof Error ? error.message : String(error);
const lower = text.toLocaleLowerCase();
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
// 关键词刻意收窄:裸的 password/version/denied 会出现在大量无关的 ping/传输
// 输出中,误判会把用户引向错误的排查方向,只把明确的短语视为证据。
// Keep the keywords narrow: a bare "password", "version" or "denied" appears in
// plenty of unrelated ping/transport output, and guessing here used to send the
// user to the wrong remedy. Only explicit phrases are treated as evidence.
if (/invalid password|password (?:required|incorrect|wrong|rejected)|authentication failed|invalid credential/.test(lower)) return "INVALID_PASSWORD";
if (/protocol (?:version )?(?:mismatch|not supported|error)|version (?:is )?(?:outdated|too old|not supported)|handshake (?:failed|error|timeout)|negotiation failed/.test(lower)) return "PROTOCOL_NEGOTIATION_FAILED";
if (/server (?:is )?full|slot limit|client protocol limit|banned?|flooding|server rejected|connection (?:denied|refused) by (?:the )?server/.test(lower)) return "SERVER_REJECTED";
return "UNREACHABLE";
}
function pingHostOnce(host: string, timeoutMs: number): Promise<number> {
return new Promise((resolve, reject) => {
const windows = process.platform === "win32";
const command = windows ? "ping.exe" : "ping";
const args = windows
? ["-n", "1", "-w", String(timeoutMs), host]
: ["-c", "1", "-W", String(Math.max(1, Math.ceil(timeoutMs / 1_000))), host];
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
let output = "";
let settled = false;
const finish = (callback: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
callback();
};
const timer = setTimeout(() => finish(() => {
child.kill();
reject(new Error("ping timeout"));
}), timeoutMs + 250);
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => { output += chunk; });
child.stderr.on("data", (chunk: string) => { output += chunk; });
child.once("error", (error) => finish(() => reject(error)));
child.once("close", (code) => finish(() => {
const match = output.match(/(?:time|时间)\s*[=<]\s*([\d.,]+)\s*(?:ms|毫秒)?/i);
if (code === 0 && match) {
const latencyMs = Number.parseFloat(match[1].replace(",", "."));
if (Number.isFinite(latencyMs)) {
resolve(Math.max(0, latencyMs));
return;
}
}
reject(new Error(output.trim() || `ping exited with code ${code ?? "unknown"}`));
}));
});
}
/**
* Keep a small compatibility helper for callers that only need one protocol
* attempt. It deliberately has no host/port argument because the connected
* TeamSpeak session owns the actual resolved endpoint.
*/
export function pingTeamSpeakPort(
execute: TeamSpeakCommandExecutor,
timeoutMs = 1_500,
): Promise<TeamSpeakPingAttempt> {
return pingTeamSpeakSession(execute, timeoutMs);
}
/*
* This function used to open a raw TCP socket to the TeamSpeak voice port.
* That transport is not TeamSpeak's client protocol and must not be used for
* reachability measurements. Keep the aggregation logic above independent of
* the connection setup so admin tests can supply a real protocol probe.
*/
export async function pingTeamSpeak(
probe: () => Promise<TeamSpeakPingAttempt>,
options: { attempts?: number } = {},
): Promise<TeamSpeakPingResult> {
return collectTeamSpeakPings(probe, options);
}
+19
View File
@@ -0,0 +1,19 @@
import type { WebSpeakError } from "../errors.js";
export const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 30_000] as const;
export const RECONNECT_WINDOW_MS = 5 * 60_000;
export function reconnectDelayMs(attempt: number, random = Math.random): number {
const safeAttempt = Math.max(1, Math.floor(attempt));
const base = RECONNECT_DELAYS_MS[Math.min(safeAttempt, RECONNECT_DELAYS_MS.length) - 1] ?? RECONNECT_DELAYS_MS.at(-1)!;
const jitter = Math.round(base * ((random() * 0.2) - 0.1));
return Math.max(250, base + jitter);
}
export function reconnectWindowOpen(startedAt: number, now = Date.now()): boolean {
return now - startedAt < RECONNECT_WINDOW_MS;
}
export function isRecoverable(error: WebSpeakError | null): boolean {
return error?.retryable ?? true;
}
+154 -21
View File
@@ -3,18 +3,25 @@ import { createServer as createHttpsServer } from "node:https";
import { createServer as createHttpServer } from "node:http";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
import { createAdminRouter } from "../admin/admin-router.js";
import type { AdminService } from "../admin/admin-service.js";
import { AdminSessionStore } from "../admin/admin-session.js";
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
import { identityFromString } from "@echosixhiya/teamspeak-client";
import { JoinRateLimiter } from "./join-rate-limit.js";
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
export interface WebServerOptions {
port: number;
trustProxy: boolean;
version?: string;
logFile?: string;
staticDir?: string;
certDir?: string; // path to cert.pem + key.pem for HTTPS
voiceBridgeOptions: VoiceBridgeOptions;
adminService: AdminService;
logger: Logger;
}
@@ -38,26 +45,131 @@ export function createWebServer(options: WebServerOptions): WebServer {
server = createHttpServer(app);
}
if (options.trustProxy) {
app.set("trust proxy", true);
}
app.use(express.json({ limit: "100kb" }));
app.get("/api/health", (_req, res) => {
res.json({ status: "ok", version: "0.1.0" });
});
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
const adminSessions = new AdminSessionStore();
const joinRateLimiter = new JoinRateLimiter();
const startedAt = Date.now();
// The browser needs the gateway's default target so a user can edit it in
// the join form. No credentials are exposed here.
app.get("/api/public-config", (_req, res) => {
res.json({
tsHost: options.voiceBridgeOptions.tsHost,
tsPort: options.voiceBridgeOptions.tsPort,
tsServerProtocol: options.voiceBridgeOptions.tsServerProtocol ?? null,
const healthHandler: express.RequestHandler = (_request, response) => {
response.json({ status: "ok", version: options.version ?? "0.1.0" });
};
app.get("/health", healthHandler);
app.get("/api/health", healthHandler);
app.get("/api/public-config", (_request, response) => {
response.setHeader("Cache-Control", "no-store");
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
response.json({
...options.adminService.getPublicConfig(),
accelerationAvailable: acceleration.length > 0,
accelerationRelays: acceleration.map((relay) => ({ id: relay.id, name: relay.name })),
});
});
app.post("/api/join-ticket", async (request, response) => {
response.setHeader("Cache-Control", "no-store");
if (!request.is("application/json") || !isSameOrigin(request)) {
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
return;
}
if (!options.adminService.isInitialized()) {
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
return;
}
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
return;
}
const body = isRecord(request.body) ? request.body : {};
const nickname = typeof body.nickname === "string" ? body.nickname.trim().slice(0, 30) : "";
const requestedChannel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
const inviteToken = typeof body.invite === "string" ? body.invite.trim().slice(0, 128) : "";
const requestedIdentity = typeof body.identity === "string" && body.identity.length <= 8192 ? body.identity : "";
let identity: string | undefined;
if (requestedIdentity) {
try {
identityFromString(requestedIdentity);
identity = requestedIdentity;
} catch {
// A stale/corrupt local identity must not block a normal ephemeral join.
}
}
if (!nickname) {
response.status(400).json({ ok: false, code: "INVALID_NICKNAME" });
return;
}
const policy = options.adminService.getConnectionPolicy();
const managedInvite = inviteToken ? options.adminService.consumeManagedInvite(inviteToken) : null;
if (inviteToken && !managedInvite) {
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
return;
}
let target = managedInvite?.target ?? policy.defaultTarget;
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
const channel = requestedChannel || managedInvite?.channel || "";
const requestedRelayId = typeof body.accelerationRelayId === "string" ? body.accelerationRelayId.trim().slice(0, 110) : "";
const accelerationRequested = body.accelerated === true || Boolean(requestedRelayId);
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
if (accelerationRequested && acceleration.length === 0) {
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
return;
}
if (requestedRelayId && !acceleration.some((relay) => relay.id === requestedRelayId)) {
response.status(400).json({ ok: false, code: "ACCELERATION_UNAVAILABLE" });
return;
}
if (!managedInvite) {
try {
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
target = parseTeamSpeakTarget(body.target);
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
// Open mode must protect the gateway even when a user submits the
// same address configured as the administrator's default target.
// The default target only controls which server is prefilled; it is
// not a trust boundary and must not bypass SSRF protection.
target = await resolveSafeOpenTarget(target);
if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
else if (typeof body.serverPassword === "string" && body.serverPassword.trim()) serverPassword = body.serverPassword.slice(0, 512);
} else if (policy.accessMode === "fixed" && typeof body.serverPassword === "string" && body.serverPassword.trim()) {
// The fixed target remains administrator-controlled, but a user may
// retry its server password after the gateway reports that one is
// required. The target itself is never taken from this request.
serverPassword = body.serverPassword.slice(0, 512);
}
} catch {
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
return;
}
}
const ticket = options.voiceBridgeOptions.joinTickets.create({
target,
serverPassword,
nickname,
...(channel ? { channel } : {}),
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
});
response.status(201).json({ ok: true, ticket });
});
app.use("/api/admin", createAdminRouter({
service: options.adminService,
sessions: adminSessions,
logger,
getActiveSessions: () => voiceBridge.getActiveCount(),
getPeakSessions: () => voiceBridge.getPeakCount(),
getCreatedSessions: () => voiceBridge.getCreatedCount(),
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
terminateSession: (id) => voiceBridge.terminateSession(id),
version: options.version,
logFile: options.logFile,
startedAt,
}));
// Serve static frontend
if (options.staticDir) {
app.use(express.static(options.staticDir));
@@ -66,8 +178,6 @@ export function createWebServer(options: WebServerOptions): WebServer {
});
}
// Voice bridge WebSocket at /ws/voice
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
voiceBridge.attach(server);
return {
@@ -80,10 +190,33 @@ export function createWebServer(options: WebServerOptions): WebServer {
});
},
async stop(): Promise<void> {
voiceBridge.shutdown();
await voiceBridge.shutdown();
adminSessions.clear();
return new Promise((resolve) => {
server.close(() => resolve());
});
},
};
}
function resolveAccelerationOptions(
configured: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]) | undefined,
): ConfiguredAccelerationRelay[] {
const value = typeof configured === "function" ? configured() : configured;
if (!value) return [];
return Array.isArray(value) ? value : [value];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isSameOrigin(request: express.Request): boolean {
const origin = request.header("origin");
const host = request.header("host");
try {
return Boolean(origin && host && new URL(origin).host === host);
} catch {
return false;
}
}
+146
View File
@@ -0,0 +1,146 @@
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js";
export type ConnectionState =
| "idle"
| "connecting"
| "authenticating"
| "syncing"
| "connected"
| "interrupted"
| "reconnecting"
| "disconnecting"
| "failed";
export type SessionTeardownReason =
| "client-disconnect"
| "websocket-close"
| "websocket-error"
| "protocol-error"
| "teamSpeak-disconnect"
| "teamSpeak-kicked" // 会话被 TeamSpeak 服务器踢出/封禁时拆除
| "teamSpeak-connect-failed"
| "heartbeat-timeout"
| "admin-terminated"
| "gateway-shutdown";
const ALLOWED_TRANSITIONS: Record<ConnectionState, readonly ConnectionState[]> = {
idle: ["connecting", "disconnecting"],
connecting: ["authenticating", "reconnecting", "failed", "disconnecting"],
authenticating: ["syncing", "reconnecting", "failed", "disconnecting"],
syncing: ["connected", "reconnecting", "failed", "disconnecting"],
connected: ["interrupted", "failed", "disconnecting"],
interrupted: ["reconnecting", "failed", "disconnecting"],
reconnecting: ["connecting", "failed", "disconnecting"],
disconnecting: ["idle"],
failed: ["disconnecting", "idle"],
};
export class ConnectionStateMachine {
private current: ConnectionState = "idle";
get state(): ConnectionState {
return this.current;
}
transition(next: ConnectionState): void {
if (next === this.current) return;
if (!ALLOWED_TRANSITIONS[this.current].includes(next)) {
throw new Error(`Illegal connection state transition: ${this.current} -> ${next}`);
}
this.current = next;
}
}
export type SessionCleanup = (reason: SessionTeardownReason) => Promise<void>;
export class ManagedSession {
readonly createdAt = Date.now();
private readonly stateMachine = new ConnectionStateMachine();
private teardownPromise: Promise<void> | null = null;
constructor(
readonly id: string,
private readonly cleanup: SessionCleanup,
) {}
get state(): ConnectionState {
return this.stateMachine.state;
}
transition(next: ConnectionState): void {
this.stateMachine.transition(next);
}
async teardown(reason: SessionTeardownReason): Promise<void> {
if (this.teardownPromise) return this.teardownPromise;
this.teardownPromise = (async () => {
if (this.state !== "idle" && this.state !== "disconnecting") {
this.stateMachine.transition("disconnecting");
} else if (this.state === "idle") {
this.stateMachine.transition("disconnecting");
}
try {
await this.cleanup(reason);
} catch {
// Teardown is best effort and must not be interrupted by an already
// closed socket, TeamSpeak client, or codec resource.
} finally {
if (this.state === "disconnecting") this.stateMachine.transition("idle");
}
})();
return this.teardownPromise;
}
}
export class SessionManager {
private readonly sessions = new Map<string, ManagedSession>();
private accepting = true;
private peak = 0;
private created = 0;
admit(id: string, cleanup: SessionCleanup): ManagedSession | null {
if (!this.accepting || !canAcceptSession(this.sessions.size)) return null;
if (this.sessions.has(id)) throw new Error(`Session already exists: ${id}`);
const session = new ManagedSession(id, cleanup);
this.sessions.set(id, session);
this.created++;
this.peak = Math.max(this.peak, this.sessions.size);
return session;
}
get(id: string): ManagedSession | undefined {
return this.sessions.get(id);
}
get activeCount(): number {
return this.sessions.size;
}
get peakCount(): number {
return this.peak;
}
get createdCount(): number {
return this.created;
}
get isAccepting(): boolean {
return this.accepting;
}
async teardown(id: string, reason: SessionTeardownReason): Promise<void> {
const session = this.sessions.get(id);
if (!session) return;
await session.teardown(reason);
this.sessions.delete(id);
}
async shutdown(reason: SessionTeardownReason = "gateway-shutdown"): Promise<void> {
this.accepting = false;
await Promise.all([...this.sessions.keys()].map((id) => this.teardown(id, reason)));
}
get maxSessions(): number {
return MAX_ACTIVE_SESSIONS;
}
}
+157
View File
@@ -0,0 +1,157 @@
import {
Client as TeamSpeakClient,
generateIdentity,
type ClientOptions,
type Identity,
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
export type TeamSpeakProtocol = "ts3" | "ts6";
interface CacheEntry {
protocol: TeamSpeakProtocol;
lastSuccessfulAt: number;
}
/** Process-local optimization; protocol is never persisted as user config. */
export class EndpointProtocolCache {
private readonly entries = new Map<string, CacheEntry>();
constructor(
private readonly ttlMs = 30 * 60 * 1000,
private readonly maxEntries = 128,
) {}
get(target: TeamSpeakTarget, now = Date.now()): TeamSpeakProtocol | undefined {
const key = teamSpeakTargetKey(target);
const entry = this.entries.get(key);
if (!entry) return undefined;
if (now - entry.lastSuccessfulAt > this.ttlMs) {
this.entries.delete(key);
return undefined;
}
return entry.protocol;
}
set(target: TeamSpeakTarget, protocol: TeamSpeakProtocol, now = Date.now()): void {
const key = teamSpeakTargetKey(target);
this.entries.delete(key);
this.entries.set(key, { protocol, lastSuccessfulAt: now });
while (this.entries.size > this.maxEntries) {
const oldest = this.entries.keys().next().value;
if (oldest === undefined) break;
this.entries.delete(oldest);
}
}
clear(): void {
this.entries.clear();
}
get size(): number {
return this.entries.size;
}
}
export const endpointProtocolCache = new EndpointProtocolCache();
const TEAM_SPEAK_CONNECT_TIMEOUT_MS = 15_000;
export interface TeamSpeakAdapterOptions {
target: TeamSpeakTarget;
nickname: string;
identity?: Identity;
serverPassword?: string;
defaultChannel?: string;
channelPassword?: string;
}
/**
* The SDK performs the wire-level TS3/TS6 negotiation itself. This adapter is
* the only application boundary that knows about that SDK and records the
* successfully observed server generation for later connections.
*/
export class TeamSpeakAdapter {
readonly client: TeamSpeakClient;
readonly identity: Identity;
private detectedProtocol: TeamSpeakProtocol | null = null;
constructor(
options: TeamSpeakAdapterOptions,
private readonly logger: Logger,
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
) {
this.identity = options.identity ?? generateIdentity(8);
const clientOptions: ClientOptions = {
serverPassword: options.serverPassword,
defaultChannel: options.defaultChannel,
defaultChannelPassword: options.channelPassword,
logger: {
debug: (msg: string) => this.logger.debug(msg),
info: (msg: string) => this.logger.info(msg),
warn: (msg: string) => this.logger.warn(msg),
error: (msg: string) => this.logger.error(msg),
},
};
this.client = new TeamSpeakClient(
this.identity,
formatTeamSpeakTarget(options.target),
options.nickname,
clientOptions,
);
this.target = options.target;
}
private readonly target: TeamSpeakTarget;
async connect(): Promise<void> {
const cachedProtocol = this.protocolCache.get(this.target);
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
try {
await this.client.connect();
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
} catch (error: unknown) {
await this.client.disconnect().catch(() => undefined);
throw normalizeTeamSpeakError(error);
}
const observedProtocol = await this.detectProtocol();
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
}
get protocol(): TeamSpeakProtocol | null {
return this.detectedProtocol;
}
async disconnect(): Promise<void> {
try {
await this.client.disconnect();
} catch {
// Teardown must remain safe when the transport has already gone away.
}
}
private async detectProtocol(): Promise<TeamSpeakProtocol | null> {
try {
const rows = await this.client.execCommandWithResponse("version", 3000);
const versionText = rows
.flatMap((row) => Object.values(row))
.filter((value): value is string => typeof value === "string")
.join(" ");
return detectTeamSpeakProtocol(versionText);
} catch {
// Version discovery is an optimization; connection success is enough to proceed.
return null;
}
}
}
export function detectTeamSpeakProtocol(versionText: string): TeamSpeakProtocol | null {
const text = versionText.trim().toLocaleLowerCase();
if (/teamspeak\s*6|(?:^|\D)6\.\d+/.test(text)) return "ts6";
if (/teamspeak\s*3|(?:^|\D)3\.\d+/.test(text)) return "ts3";
return null;
}
+142
View File
@@ -0,0 +1,142 @@
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { TSClient } from "./ts-client.js";
import type { TeamSpeakProtocol } from "./teamspeak-adapter.js";
export type ProbeErrorCode =
| "INVALID_NICKNAME"
| "HOST_NOT_FOUND"
| "UNREACHABLE"
| "CONNECTION_REFUSED"
| "CONNECTION_RESET"
| "TIMEOUT"
| "PASSWORD_REQUIRED"
| "INVALID_PASSWORD"
| "PROTOCOL_NEGOTIATION_FAILED"
| "SERVER_REJECTED"
| "INTERNAL_ERROR";
export interface TeamSpeakProbeResult {
ok: true;
protocol: TeamSpeakProtocol | null;
latencyMs: number;
serverName: string | null;
requiresPassword: boolean;
}
export class TeamSpeakProbeError extends Error {
constructor(readonly code: ProbeErrorCode, message: string, readonly cause?: unknown) {
super(message);
this.name = "TeamSpeakProbeError";
}
}
interface ProbeAdapter {
connect(): Promise<void>;
disconnect(): Promise<void>;
readonly protocol?: TeamSpeakProtocol | null;
getProtocol?(): TeamSpeakProtocol | null;
execCommandWithResponse?(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
readonly client?: {
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
};
}
export type ProbeAdapterFactory = (input: {
target: TeamSpeakTarget;
password: string;
logger: Logger;
}) => ProbeAdapter;
export async function probeTeamSpeak(
target: TeamSpeakTarget,
password: string,
logger: Logger,
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
(() => {
const client = new TSClient({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger);
return {
connect: () => client.connect(),
disconnect: () => client.disconnect(),
getProtocol: () => client.getProtocol(),
execCommandWithResponse: (command: string, timeoutMs?: number) => client.execCommandWithResponse(command, timeoutMs),
};
})(),
): Promise<TeamSpeakProbeResult> {
const startedAt = Date.now();
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
try {
await adapter.connect();
let serverName: string | null = null;
try {
const execute = adapter.execCommandWithResponse?.bind(adapter) ?? adapter.client?.execCommandWithResponse.bind(adapter.client);
if (!execute) throw new Error("Probe adapter does not support commands");
const rows = await execute("serverinfo", 3000);
const first = rows[0] ?? {};
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
} catch {
// A connected server can restrict serverinfo; reachability is still proven.
}
return {
ok: true,
protocol: adapter.protocol ?? adapter.getProtocol?.() ?? null,
latencyMs: Math.max(0, Date.now() - startedAt),
serverName,
requiresPassword: Boolean(password),
};
} catch (error: unknown) {
throw toProbeError(error, password);
} finally {
try {
await adapter.disconnect();
} catch (error: unknown) {
logger.warn({ err: extractErrorText(error) }, "TeamSpeak probe cleanup failed");
}
}
}
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
if (error instanceof TeamSpeakProbeError) return error;
const normalized = normalizeTeamSpeakError(error);
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
}
// 探测只回答「该地址是否可用」,因此把网关能细分的拒绝原因收敛到既有探测码,
// 具体原因由连接/重连路径向浏览器上报。
// The probe only answers "can this address be used at all", so the richer
// rejection reasons the gateway can now name are bucketed into the existing
// probe codes; the exact reason is reported by the connect/reconnect path.
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
invalid_target: "INTERNAL_ERROR",
invalid_nickname: "INVALID_NICKNAME",
nickname_in_use: "INVALID_NICKNAME",
invalid_parameter_size: "INVALID_NICKNAME",
unreachable: "UNREACHABLE",
host_not_found: "HOST_NOT_FOUND",
connection_refused: "CONNECTION_REFUSED",
connection_reset: "CONNECTION_RESET",
timeout: "TIMEOUT",
authentication_failed: password.trim() ? "INVALID_PASSWORD" : "PASSWORD_REQUIRED",
channel_password_required: "PASSWORD_REQUIRED",
identity_security_level_too_low: "SERVER_REJECTED",
identity_limit_reached: "SERVER_REJECTED",
client_version_outdated: "SERVER_REJECTED",
flooding: "SERVER_REJECTED",
banned: "SERVER_REJECTED",
kicked: "SERVER_REJECTED",
server_shutting_down: "SERVER_REJECTED",
connection_initialisation_failed: "SERVER_REJECTED",
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
server_full: "SERVER_REJECTED",
unknown: "SERVER_REJECTED",
};
return new TeamSpeakProbeError(mapping[normalized.code] ?? "INTERNAL_ERROR", normalized.message, error);
}
function extractErrorText(error: unknown): string {
if (!error || typeof error !== "object") return String(error ?? "");
const candidate = error as { code?: unknown; id?: unknown; serverMessage?: unknown; message?: unknown };
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.id === "string" || typeof candidate.id === "number" ? candidate.id : ""} ${typeof candidate.serverMessage === "string" ? candidate.serverMessage : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
}
+239 -95
View File
@@ -1,23 +1,32 @@
import { EventEmitter } from "node:events";
import {
Client as TS3FullClient,
generateIdentity,
clientMove as tsClientMove,
listChannels as tsListChannels,
listClients as tsListClients,
poke as tsPoke,
sendTextMessage as tsSendTextMessage,
generateIdentity,
type Identity,
type VoiceData,
type ChannelInfo,
type ClientInfo,
} from "@honeybbq/teamspeak-client";
type DirectoryClientInfo,
type DirectorySnapshot,
type TextMessage,
} from "@echosixhiya/teamspeak-client";
import type { Logger } from "../logger.js";
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
export interface TSClientOptions {
host: string;
port: number;
target: TeamSpeakTarget;
nickname: string;
serverPassword?: string;
serverProtocol?: "ts3" | "ts6";
defaultChannel?: string;
channelPassword?: string;
identity?: Identity;
acceleration?: AccelerationRelayOptions;
}
export interface TSVoiceData {
@@ -26,45 +35,145 @@ export interface TSVoiceData {
data: Buffer;
}
export interface TSDirectorySnapshot {
channels: ChannelInfo[];
clients: ClientInfo[];
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryClient = DirectoryClientInfo;
export type TSChatScope = "channel" | "server" | "private";
export interface TSChatMessage {
invokerName: string;
invokerId: number;
invokerUid: string;
message: string;
targetMode: number;
targetId: bigint;
}
/**
* Keep the TeamSpeak target id when adapting SDK events for the gateway.
* Private-message events include a bigint targetID; dropping it makes the
* bridge dereference undefined while echoing the message to the browser.
*/
export function toTSChatMessage(msg: TextMessage): TSChatMessage {
return {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
targetId: msg.targetID,
};
}
export class TSClient extends EventEmitter {
private client: TS3FullClient | null = null;
private identity: Identity;
private adapter: TeamSpeakAdapter | null = null;
private logger: Logger;
private readonly identity: Identity;
private clientId = 0;
private connected = false;
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
// reason message to its `kicked` handler, not the reason id.
private selfLeaveReasonId: number | null = null;
constructor(
private options: TSClientOptions,
logger: Logger,
) {
constructor(private options: TSClientOptions, logger: Logger) {
super();
this.logger = logger.child({ nickname: options.nickname });
this.identity = generateIdentity(8);
this.identity = options.identity ?? generateIdentity(8);
}
async connect(): Promise<void> {
const addr = `${this.options.host}:${this.options.port}`;
this.selfLeaveReasonId = null;
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
if (this.options.acceleration && !this.accelerationClient) {
this.accelerationClient = await createAccelerationRelayClient({
...this.options.acceleration,
host: this.options.target.host,
port: this.options.target.port,
});
transportTarget = { host: this.accelerationClient.localHost, port: this.accelerationClient.localPort };
}
this.adapter = new TeamSpeakAdapter({
target: transportTarget,
nickname: this.options.nickname,
identity: this.identity,
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
channelPassword: this.options.channelPassword,
}, this.logger);
this.client = this.adapter.client;
this.attachClientListeners(this.client);
}
const adapter = this.adapter;
const client = this.client;
this.logger.info({ addr }, "Connecting to TeamSpeak");
await adapter.connect();
this.client = new TS3FullClient(this.identity, addr, this.options.nickname, {
serverPassword: this.options.serverPassword,
defaultChannel: this.options.defaultChannel,
defaultChannelPassword: this.options.channelPassword,
logger: {
debug: (msg: string) => this.logger.debug(msg),
info: (msg: string) => this.logger.info(msg),
warn: (msg: string) => this.logger.warn(msg),
error: (msg: string) => this.logger.error(msg),
},
});
this.clientId = client.clientID();
try {
// A native TeamSpeak client subscribes to the complete channel tree
// after the welcome sequence. Without this command the server only
// exposes members in the current channel, so users disappear as soon as
// they move elsewhere even though both clients are on the same server.
await client.execCommand("channelsubscribeall", 5000);
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
}, "Could not subscribe to all TeamSpeak channels");
}
// Directory snapshots are dispatched through two setImmediate layers in
// the SDK. Let both flush before reconciling with a direct client-protocol
// snapshot so the gateway's first connected state contains every member.
await new Promise<void>((resolve) => setImmediate(resolve));
await new Promise<void>((resolve) => setImmediate(resolve));
this.client.on("voiceData", (data: VoiceData) => {
// TS6 can finish the welcome event stream before it has exposed every
// existing client to a newly connected session. Pull one authoritative
// snapshot through this same client protocol session so users who joined
// earlier are visible immediately as well. Realtime events continue to
// keep the snapshot current after this reconciliation.
try {
const [channels, clients] = await Promise.all([
tsListChannels(client),
tsListClients(client),
]);
this.emit("directorySnapshot", { channels, clients });
} catch (error: unknown) {
this.logger.warn({
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
failureDetail: error instanceof Error ? error.message : String(error),
}, "TeamSpeak directory snapshot unavailable");
}
const connectedChannelId = client.channelID();
if (this.preferredChannelId === 0n) {
this.preferredChannelId = connectedChannelId;
} else if (connectedChannelId !== this.preferredChannelId) {
try {
await tsClientMove(client, this.clientId, this.preferredChannelId);
} catch (error: unknown) {
// The old channel may have been deleted or become inaccessible. The
// SDK has already left us in the server/default channel, which is the
// safe fallback required by the reconnect contract.
this.logger.info({
channelId: this.preferredChannelId.toString(),
err: error instanceof Error ? error.message : String(error),
}, "Previous TeamSpeak channel could not be restored");
this.preferredChannelId = client.channelID();
}
}
this.connected = true;
this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak");
this.emit("connected", this.clientId);
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
clientId: data.clientId,
codec: data.codec,
@@ -72,68 +181,65 @@ export class TSClient extends EventEmitter {
} as TSVoiceData);
});
// The SDK patch exposes the directory that TeamSpeak sends during the
// normal client welcome sequence. This is the same data a native client
// receives and does not require channellist/clientlist permissions.
(this.client as unknown as {
on(event: "directorySnapshot", handler: (snapshot: TSDirectorySnapshot) => void): unknown;
}).on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", snapshot);
});
this.client.on("textMessage", (msg) => {
this.emit("textMessage", {
invokerName: msg.invokerName,
invokerId: msg.invokerID,
invokerUid: msg.invokerUID,
message: msg.message,
targetMode: msg.targetMode,
// The SDK exposes the directory that TeamSpeak sends during the normal
// client welcome sequence. The connect path also reconciles this event
// stream with a complete client-protocol snapshot.
client.on("directorySnapshot", (snapshot) => {
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
clients: snapshot.clients.slice(),
});
});
this.client.on("disconnected", (err) => {
this.logger.warn({ err: err?.message }, "Disconnected from TS");
this.connected = false;
this.clientId = 0;
this.emit("disconnected");
client.on("textMessage", (msg) => {
this.emit("textMessage", toTSChatMessage(msg));
});
this.client.on("clientEnter", (info) => {
client.on("poked", (event) => {
this.emit("poked", event);
});
client.on("disconnected", (err) => {
if (err) {
const normalized = normalizeTeamSpeakError(err);
this.logger.warn({
failureCode: normalized.code.toUpperCase(),
failureDetail: describeTeamSpeakError(normalized),
}, "TeamSpeak transport disconnected unexpectedly");
} else {
this.logger.info("TeamSpeak transport disconnected");
}
this.connected = false;
this.clientId = 0;
this.emit("disconnected", err);
});
client.on("clientEnter", (info) => {
this.emit("clientEnter", info);
});
this.client.on("clientLeave", (info) => {
client.on("clientLeave", (info) => {
// 仅记录本客户端的踢出(4)/踢出并封禁(5)退出原因,供 kicked 事件区分普通踢出与封禁
if (info.id === this.clientId && (info.reasonID === 4 || info.reasonID === 5)) this.selfLeaveReasonId = info.reasonID;
this.emit("clientLeave", info);
});
this.client.on("clientMoved", (info) => {
this.emit("clientMoved", info);
// 转发 SDK 的 kicked 事件:不转发的话管理员填写的踢出原因会被丢弃,浏览器
// 只能看到笼统的「连接失败」。这里把原因连同 reason id 一起归一化后向上抛。
// The SDK emits `kicked` only for a self leave with reason 4 (kick) or 5
// (kick with ban) and hands over the admin written reason message. Without
// this listener the reason was dropped, so the browser degraded to a generic
// "connection failed" right after the transport went away.
client.on("kicked", (reasonMsg) => {
const reasonId = this.selfLeaveReasonId;
this.selfLeaveReasonId = null;
this.emit("kicked", normalizeTeamSpeakKickedReason(reasonMsg, reasonId));
});
await this.client.connect();
await this.client.waitConnected();
this.clientId = this.client.clientID();
try {
// A native TeamSpeak client subscribes to the complete channel tree
// after the welcome sequence. Without this command the server only
// exposes members in the current channel, so users disappear as soon as
// they move elsewhere even though both clients are on the same server.
await this.client.execCommand("channelsubscribeall", 5000);
} catch (error: unknown) {
this.logger.warn({
err: error instanceof Error ? error.message : String(error),
}, "Could not subscribe to all TeamSpeak channels");
}
// Directory snapshots are dispatched through two setImmediate layers in
// the SDK. Let both flush so the gateway's first connected state already
// contains members from every subscribed channel.
await new Promise<void>((resolve) => setImmediate(resolve));
await new Promise<void>((resolve) => setImmediate(resolve));
this.connected = true;
this.logger.info({ clientId: this.clientId }, "Connected to TeamSpeak");
this.emit("connected", this.clientId);
client.on("clientMoved", (info) => {
if (info.id === this.clientId && info.targetChannelID !== 0n) this.preferredChannelId = info.targetChannelID;
this.emit("clientMoved", info);
});
}
sendVoice(data: Buffer, codec: number = 4): void {
@@ -141,20 +247,34 @@ export class TSClient extends EventEmitter {
this.client.sendVoice(data, codec);
}
sendTextMessage(message: string): void {
// We use execCommand for simplicity — the client API has higher-level wrappers
sendWhisper(data: Buffer, clientIds: number[], codec: number = 4): void {
if (!this.client || !this.connected) return;
const escaped = message
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/");
this.client.execCommand(`sendtextmessage targetmode=2 target=0 msg=${escaped}`)
.catch((err: Error) => this.logger.error({ err }, "sendTextMessage failed"));
const targets = [...new Set(clientIds)].filter((clientId) => Number.isInteger(clientId) && clientId > 0 && clientId <= 65535 && clientId !== this.getClientId());
if (!targets.length) throw new Error("Whisper requires at least one valid target");
this.client.sendWhisper(data, targets, codec);
}
async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const targetMode = scope === "private" ? 1 : scope === "server" ? 3 : 2;
await tsSendTextMessage(this.client, targetMode, targetId, message);
}
async poke(clientId: number, message: string): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
await tsPoke(this.client, clientId, message);
}
async setAway(away: boolean, message = ""): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
const escaped = escapeTeamSpeakValue(message);
await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`);
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
if (!this.client) return;
if (!this.client || !this.connected) return;
await tsClientMove(this.client, this.clientId, channelId, password);
this.preferredChannelId = channelId;
}
getClientId(): number {
@@ -164,6 +284,19 @@ export class TSClient extends EventEmitter {
return this.client?.clientID() ?? this.clientId;
}
getProtocol(): TeamSpeakProtocol | null {
return this.adapter?.protocol ?? null;
}
async execCommandWithResponse(command: string, timeoutMs = 3000): Promise<Record<string, string>[]> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
return this.client.execCommandWithResponse(command, timeoutMs);
}
getIdentityString(): string {
return this.identity.toString();
}
getChannelId(): bigint {
if (!this.client) return 0n;
const sdkClient = this.client as unknown as { channelID?: () => bigint };
@@ -176,14 +309,25 @@ export class TSClient extends EventEmitter {
async disconnect(): Promise<void> {
this.connected = false;
if (this.client) {
try {
await this.client.disconnect();
} catch {
// ignore
}
this.selfLeaveReasonId = null;
try {
if (this.adapter) await this.adapter.disconnect();
} finally {
this.accelerationClient?.close();
this.accelerationClient = null;
this.adapter = null;
this.client = null;
this.clientId = 0;
}
this.clientId = 0;
}
}
function escapeTeamSpeakValue(value: string): string {
return value
.replace(/\\/g, "\\\\")
.replace(/ /g, "\\s")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r");
}
+1069 -166
View File
File diff suppressed because it is too large. Load diff
+80
View File
@@ -0,0 +1,80 @@
export interface ClientCommand {
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
requestId?: string;
payload: Record<string, unknown>;
}
export type ClientCommandResult = ClientCommand | { error: { code: string; message: string } };
export function parseClientCommand(raw: string): ClientCommandResult {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
return { error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" } };
}
if (!isRecord(value) || typeof value.type !== "string") {
return { error: { code: "INVALID_MESSAGE", message: "消息类型不能为空" } };
}
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
if (!isRecord(value.payload)) {
return { error: { code: "INVALID_PAYLOAD", message: "消息参数无效" } };
}
if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
}
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendServerMessage" || value.type === "sendPrivateMessage") && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendPrivateMessage" || value.type === "poke") && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
}
if (value.type === "poke" && (typeof value.payload.message !== "string" || value.payload.message.length > 200)) {
return { error: { code: "INVALID_POKE_MESSAGE", message: "戳一戳消息无效" } };
}
if (value.type === "setAway" && (typeof value.payload.away !== "boolean" || (value.payload.message !== undefined && (typeof value.payload.message !== "string" || value.payload.message.length > 200)))) {
return { error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" } };
}
if (value.type === "setWhisperTargets") {
const targetIds = value.payload.targetIds;
if (!Array.isArray(targetIds) || targetIds.length > 8 || targetIds.some((clientId) => typeof clientId !== "number" || !Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) || new Set(targetIds).size !== targetIds.length) {
return { error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" } };
}
}
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
}
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
}
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
}
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
}
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
}
return {
type: value.type as ClientCommand["type"],
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
payload: value.payload,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+474
View File
@@ -0,0 +1,474 @@
import { randomInt } from "node:crypto";
import { createRequire } from "node:module";
import {
MediaStreamTrack,
RtpHeader,
RtpPacket,
RTCPeerConnection,
} from "werift";
import type { Logger as LoggerType } from "../logger.js";
import type { TSVoiceData } from "./ts-client.js";
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
OpusEncoder: new (sampleRate: number, channels: number) => {
decode(data: Buffer): Buffer;
encode(data: Buffer): Buffer;
};
};
const AUDIO_SAMPLE_RATE = 48_000;
const AUDIO_FRAME_SAMPLES = 960;
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
const MAX_MIXER_QUEUE_FRAMES = 4;
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const MIXER_UNDERRUN_WINDOW_MS = 200;
// This threshold is used only for the speaking indicator. It must never decide
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
// packets are still valid media and dropping them can break decoder continuity.
const SPEAKER_ACTIVITY_RMS = 160;
// WebRTC is served by the WebSpeak process itself. The default range is also
// published by the bundled Docker Compose file; advanced administrators can
// change it in the admin console before enabling WebRTC.
export interface WebRtcAudioOptions {
enabled: boolean;
udpPortRange?: [number, number];
}
export interface WebRtcSessionDescription {
type: "offer" | "answer";
sdp: string;
muted?: boolean;
accompanimentActive?: boolean;
}
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
microphoneMuted?: boolean;
accompanimentActive?: boolean;
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
onVoiceActivity: (clientIds: number[]) => void;
}
export interface WebRtcAudioStats {
webrtcIngressRtpFrames: number;
webrtcIngressRtpFirstAt: number | null;
webrtcIngressRtpLastAt: number | null;
webrtcIngressRtpMaxGapMs: number;
webrtcEgressRtpFrames: number;
webrtcEgressRtpFirstAt: number | null;
webrtcEgressRtpLastAt: number | null;
webrtcEgressRtpMaxGapMs: number;
webrtcQueuePeakFrames: number;
webrtcQueueDroppedFrames: number;
webrtcQueueUnderrunTicks: number;
webrtcPacerLateTicks: number;
webrtcQueueCurrentFrames: number;
webrtcIngressQuietFrames: number;
webrtcIngressDecodeErrors: number;
webrtcDownlinkDecodedFrames: number;
webrtcDownlinkDecodeErrors: number;
webrtcDownlinkShortFrames: number;
}
interface PendingAudioFrame {
pcm: Buffer;
receivedAt: number;
/** Preserve a native 20 ms Opus frame when no mix is required. */
opus?: Buffer;
}
interface SelectedAudioFrame extends PendingAudioFrame {
clientId: number;
volume: number;
}
/**
* One low-latency WebRTC audio session for one browser connection.
*
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
* audio track in this first transport, so this class mixes one 20 ms frame
* from each active speaker and packetizes the result as RTP. Each speaker has
* a very small bounded queue so bursts from the TeamSpeak adapter can be
* smoothed without turning into an ever-growing playback delay.
*/
export class WebRtcAudioSession {
readonly peer: RTCPeerConnection;
private readonly logger: LoggerType;
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
private readonly onVoiceActivity: (clientIds: number[]) => void;
private readonly outgoingTrack: MediaStreamTrack;
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
private readonly partialPcmByClient = new Map<number, Buffer>();
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
private readonly memberVolumes = new Map<number, number>();
private readonly activeSpeakerIds = new Set<number>();
private readonly opusPayloadTypes = new Set<number>();
private audioTimer: ReturnType<typeof setTimeout> | null = null;
private readonly activityTimer: ReturnType<typeof setInterval>;
private encoder: { encode(data: Buffer): Buffer } | null;
private sequenceNumber = randomInt(0, 65_536);
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
private closed = false;
private nextAudioDeadline = 0;
private lastIngressRtpAt: number | null = null;
private lastEgressRtpAt: number | null = null;
private lastQueueEnqueuedAt: number | null = null;
private microphoneMuted: boolean;
private accompanimentActive: boolean;
private readonly stats: WebRtcAudioStats = {
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,
};
constructor(options: WebRtcAudioSessionOptions) {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
this.microphoneMuted = options.microphoneMuted === true;
this.accompanimentActive = options.accompanimentActive === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
this.peer = new RTCPeerConnection({
iceServers: [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseTcp: false,
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
});
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
audio.onTrack.subscribe((track) => {
track.onReceiveRtp.subscribe((rtp) => {
if (this.closed) return;
const receivedAt = performance.now();
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
this.lastIngressRtpAt = receivedAt;
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
this.stats.webrtcIngressRtpLastAt = Date.now();
this.stats.webrtcIngressRtpFrames++;
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
const payload = Buffer.from(rtp.payload);
// A muted microphone must stop the browser user's TeamSpeak voice
// packets at the gateway. Browser-side track.enabled/gain changes
// still produce RTP comfort-silence on some browsers, and forwarding
// those packets makes TeamSpeak keep the user in the speaking state.
// When accompaniment is active, keep forwarding the mixed track: the
// browser has already removed only the microphone component.
if (this.microphoneMuted && !this.accompanimentActive) return;
// Forward every valid negotiated Opus payload unchanged. Do not
// decode it for RMS analysis or pass it through a speech/silence gate:
// quiet frames are still part of the codec timeline and dropping them
// can cause downstream gaps, clicks, or decoder recovery artifacts.
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
});
});
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
});
try {
this.encoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
} catch (error: unknown) {
this.encoder = null;
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer encoder");
}
if (!this.encoder) {
this.outgoingTrack.stop();
throw new Error("WebRTC Opus codec is unavailable");
}
this.nextAudioDeadline = performance.now();
this.scheduleAudioTick();
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
this.activityTimer.unref?.();
this.peer.onconnectionstatechange = () => {
this.logger.info({ state: this.peer.connectionState }, "WebRTC connection state changed");
};
}
getStats(): WebRtcAudioStats {
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
}
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
if (this.closed) throw new Error("WebRTC session is closed");
this.setOpusPayloadTypes(offer.sdp);
await this.peer.setRemoteDescription(offer);
const transceiver = this.peer.getTransceivers().find((candidate) => candidate.kind === "audio");
if (transceiver) await transceiver.sender.replaceTrack(this.outgoingTrack);
const answer = await this.peer.createAnswer();
await this.peer.setLocalDescription(answer);
const description = this.peer.localDescription;
if (!description) throw new Error("WebRTC answer was not created");
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
return { type: description.type, sdp: description.sdp };
}
pushTeamSpeakVoice(data: TSVoiceData): void {
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
let decoder = this.decoderByClient.get(data.clientId);
if (!decoder) {
try {
// @discordjs/opus exposes decoding on OpusEncoder instances too;
// there is no separate OpusDecoder constructor in that package.
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
this.decoderByClient.set(data.clientId, decoder);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
return;
}
}
try {
const pcm = decoder.decode(data.data);
this.stats.webrtcDownlinkDecodedFrames++;
if (pcm.length < 2) {
this.stats.webrtcDownlinkShortFrames++;
return;
}
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
// decoded frame per speaker and split every decoded buffer into the
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
// anything after the first 20 ms.
const pendingPcm = this.partialPcmByClient.get(data.clientId);
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
const rms = this.calculateRms(pcm);
// RMS is used only for the UI speaking indicator. Every decoded frame,
// including quiet/comfort-noise frames, continues into the queue so the
// receiver keeps an uninterrupted codec timeline.
if (rms >= SPEAKER_ACTIVITY_RMS) this.activeSpeakerIds.add(data.clientId);
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
let offset = 0;
let enqueued = false;
let queue = this.pendingFrames.get(data.clientId);
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
if (!queue) {
queue = [];
this.pendingFrames.set(data.clientId, queue);
}
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
queue.push({
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
receivedAt: performance.now(),
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
});
enqueued = true;
offset += AUDIO_FRAME_BYTES;
}
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
else this.partialPcmByClient.delete(data.clientId);
if (enqueued) {
this.lastQueueEnqueuedAt = performance.now();
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
}
} catch {
this.stats.webrtcDownlinkDecodeErrors++;
// A malformed or codec-transition packet is discarded without touching
// the peer connection. The next valid Opus frame can recover the stream.
}
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
if (this.audioTimer) clearTimeout(this.audioTimer);
this.audioTimer = null;
clearInterval(this.activityTimer);
this.pendingFrames.clear();
this.memberVolumes.clear();
this.partialPcmByClient.clear();
this.activeSpeakerIds.clear();
this.decoderByClient.clear();
this.encoder = null;
this.outgoingTrack.stop();
await this.peer.close();
}
private scheduleAudioTick(): void {
if (this.closed) return;
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
this.audioTimer.unref?.();
}
private flushAudio(): void {
if (this.closed) return;
const now = performance.now();
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
this.stats.webrtcPacerLateTicks++;
this.nextAudioDeadline = now;
this.trimQueuesAfterLateTick();
}
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
this.audioTimer = null;
this.mixAndSendAudio();
this.scheduleAudioTick();
}
private mixAndSendAudio(): void {
if (!this.encoder) {
return;
}
if (!this.pendingFrames.size) {
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
this.stats.webrtcQueueUnderrunTicks++;
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
const selectedFrames: SelectedAudioFrame[] = [];
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
if (!frame) continue;
const volume = this.memberVolumes.get(clientId) ?? 1;
selectedFrames.push({ ...frame, clientId, volume });
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
}
}
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
this.sendRtpAudio(selectedFrames[0].opus);
return;
}
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
// the waveform's apparent loudness as the source level changes, which
// is especially noticeable on music. Only clip actual overflow caused
// by simultaneous speakers; never normalize by the active speaker count.
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
pcm.writeInt16LE(sample, index * 2);
}
try {
const encoded = this.encoder.encode(pcm);
this.sendRtpAudio(encoded);
} catch {
// A peer closing concurrently may reject a packet; teardown owns the
// session lifecycle and no per-frame error needs to reach the logs.
}
}
private sendRtpAudio(encoded: Buffer): void {
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
const sentAt = performance.now();
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
this.lastEgressRtpAt = sentAt;
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
this.stats.webrtcEgressRtpLastAt = Date.now();
this.stats.webrtcEgressRtpFrames++;
}
private flushSpeakerActivity(): void {
if (this.closed || !this.activeSpeakerIds.size) return;
const ids = [...this.activeSpeakerIds];
this.activeSpeakerIds.clear();
this.onVoiceActivity(ids);
}
setMicrophoneMuted(muted: boolean): void {
this.microphoneMuted = muted;
}
setAccompanimentActive(active: boolean): void {
this.accompanimentActive = active;
}
setMemberVolume(clientId: number, volume: number): void {
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
const normalized = Math.max(0, Math.min(4, volume));
if (normalized === 1) this.memberVolumes.delete(clientId);
else this.memberVolumes.set(clientId, normalized);
}
private calculateRms(pcm: Buffer): number {
let sum = 0;
let samples = 0;
for (let index = 0; index + 1 < pcm.length; index += 2) {
const sample = pcm.readInt16LE(index);
sum += sample * sample;
samples++;
}
return samples ? Math.sqrt(sum / samples) : 0;
}
private trimQueuesAfterLateTick(): void {
const now = performance.now();
for (const [clientId, queue] of this.pendingFrames) {
while (queue.length > 1) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue.length === 0) this.pendingFrames.delete(clientId);
}
}
private getQueueFrameCount(): number {
let count = 0;
for (const queue of this.pendingFrames.values()) count += queue.length;
return count;
}
private setOpusPayloadTypes(sdp: string): void {
this.opusPayloadTypes.clear();
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
const payloadType = Number(match[1]);
if (!Number.isInteger(payloadType) || payloadType < 0 || payloadType > 127) continue;
this.opusPayloadTypes.add(payloadType);
this.outgoingPayloadType = payloadType;
}
if (!this.opusPayloadTypes.size) this.opusPayloadTypes.add(DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE);
}
}
+7
View File
@@ -0,0 +1,7 @@
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
// Kept as a public alias for callers that used the original fixed-range name.
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
export const WEBRTC_UDP_PORT_MIN = 1024;
export const WEBRTC_UDP_PORT_MAX = 65535;
+24
View File
@@ -0,0 +1,24 @@
export type SiteLanguage = "zh" | "en" | "de" | "ru" | "ja";
/**
* Built-in welcome-page templates. An empty administrator value always falls
* back to one of these strings, so adding a language never leaves the page
* with a blank welcome message.
*/
export const DEFAULT_WELCOME_TEXTS: Record<SiteLanguage, string> = {
zh: "无需安装 TeamSpeak 客户端,打开浏览器即可加入语音频道。低延迟、轻量、专注于每一次对话。",
en: "No TeamSpeak client installation required. Open your browser and join a voice channel with low-latency audio built for conversation.",
de: "Keine Installation des TeamSpeak-Clients nötig. Öffne den Browser und tritt einem Sprachkanal bei – leichtgewichtig und mit geringer Latenz.",
ru: "Устанавливать клиент TeamSpeak не нужно: откройте браузер и присоединитесь к голосовому каналу. Низкая задержка и удобное общение в каждом разговоре.",
ja: "TeamSpeak クライアントのインストールは不要です。ブラウザを開くだけで音声チャンネルに参加できます。低遅延で軽快な会話を楽しめます。",
};
export function resolveWelcomeTexts(values: Partial<Record<SiteLanguage, string>>): Record<SiteLanguage, string> {
return {
zh: values.zh?.trim() || DEFAULT_WELCOME_TEXTS.zh,
en: values.en?.trim() || DEFAULT_WELCOME_TEXTS.en,
de: values.de?.trim() || DEFAULT_WELCOME_TEXTS.de,
ru: values.ru?.trim() || DEFAULT_WELCOME_TEXTS.ru,
ja: values.ja?.trim() || DEFAULT_WELCOME_TEXTS.ja,
};
}
+1
View File
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#006a64" />
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
<title>WebSpeak · TeamSpeak Web Client</title>
</head>
<body>
+25 -14
View File
@@ -6,6 +6,7 @@
"": {
"name": "webspeak-webclient-frontend",
"dependencies": {
"@sapphi-red/web-noise-suppressor": "^0.4.0",
"pinia": "^3.0.2",
"vue": "^3.5.13",
"vue-router": "^4.5.1"
@@ -13,7 +14,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.3",
"typescript": "~5.7.0",
"vite": "^6.3.0",
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
}
},
@@ -861,6 +862,16 @@
"win32"
]
},
"node_modules/@sapphi-red/web-noise-suppressor": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@sapphi-red/web-noise-suppressor/-/web-noise-suppressor-0.4.0.tgz",
"integrity": "sha512-vkBEL/VDkbeP3qqSRQFRtPLGa19a38JUzO6J0r5D/MQSumrlERy671DAMaETgY6etXjDCoJcD7JBIaXnuGVtVw==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/sapphi-red"
}
},
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -1104,9 +1115,9 @@
}
},
"node_modules/brace-expansion": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
"integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1301,9 +1312,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"funding": [
{
"type": "github",
@@ -1373,9 +1384,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"funding": [
{
"type": "opencollective",
@@ -1392,7 +1403,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -1514,9 +1525,9 @@
}
},
"node_modules/vite": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz",
"integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==",
"version": "6.4.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"dev": true,
"license": "MIT",
"peer": true,
+2 -1
View File
@@ -8,6 +8,7 @@
"preview": "vite preview"
},
"dependencies": {
"@sapphi-red/web-noise-suppressor": "^0.4.0",
"pinia": "^3.0.2",
"vue": "^3.5.13",
"vue-router": "^4.5.1"
@@ -15,7 +16,7 @@
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.3",
"typescript": "~5.7.0",
"vite": "^6.3.0",
"vite": "^6.4.3",
"vue-tsc": "^2.2.8"
}
}
+35
View File
@@ -0,0 +1,35 @@
const FRAME_SAMPLES = 960;
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
}
process(inputs, outputs) {
const input = inputs[0]?.[0];
const output = outputs[0]?.[0];
if (output) output.fill(0);
if (!input) return true;
let inputOffset = 0;
while (inputOffset < input.length) {
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
this.offset += count;
inputOffset += count;
if (this.offset !== FRAME_SAMPLES) continue;
let sum = 0;
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
const frame = this.frame;
this.frame = new Float32Array(FRAME_SAMPLES);
this.offset = 0;
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
}
return true;
}
}
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

+13
View File
@@ -1,3 +1,16 @@
<template>
<router-view />
</template>
<style>
:root {
--ui-scale: 1;
}
/* Scale the complete application from the 1920×1080 reference viewport so
typography, spacing, controls, and icons grow together instead of drifting
apart when the browser has a high-resolution viewport. */
#app {
zoom: var(--ui-scale);
}
</style>
+28 -2
View File
@@ -26,12 +26,17 @@
<path d="M12 3v12m0 0 4-4m-4 4-4-4M4 19v2h16v-2" />
</template>
<template v-else-if="name === 'settings'">
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0L6.2 6.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.09a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-1.42 1.42-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V20h-2v-.09a1.7 1.7 0 0 0-1.03-1.56 1.7 1.7 0 0 0-1.88.34l-.06.06-1.42-1.42.06-.06A1.7 1.7 0 0 0 9.4 15a1.7 1.7 0 0 0-1.56-1.03H7v-2h.84A1.7 1.7 0 0 0 9.4 11a1.7 1.7 0 0 0-.34-1.88L9 9.06l1.42-1.42.06.06a1.7 1.7 0 0 0 1.88.34A1.7 1.7 0 0 0 13.39 6.5V6h2v.5a1.7 1.7 0 0 0 1.03 1.54 1.7 1.7 0 0 0 1.88-.34l.06-.06 1.42 1.42-.06.06A1.7 1.7 0 0 0 19.4 11a1.7 1.7 0 0 0 1.56 1.03H21v2h-.04A1.7 1.7 0 0 0 19.4 15Z" />
</template>
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
<template v-else-if="name === 'music'">
<path d="M9 18V5l10-2v13" />
<circle cx="6" cy="18" r="3" />
<circle cx="16" cy="16" r="3" />
</template>
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
<template v-else-if="name === 'search'">
@@ -39,7 +44,12 @@
<path d="m16 16 4.5 4.5" />
</template>
<path v-else-if="name === 'bell'" d="M18 9a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4" />
<path v-else-if="name === 'clock'" d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-14v5l3 2" />
<path v-else-if="name === 'help'" d="M9.3 9a3 3 0 1 1 4.9 2.3c-1.3 1-2.2 1.5-2.2 3m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" />
<template v-else-if="name === 'info'">
<circle cx="12" cy="12" r="9" />
<path d="M12 10v6m0-9h.01" />
</template>
<template v-else-if="name === 'plus'">
<path d="M12 5v14M5 12h14" />
</template>
@@ -63,7 +73,23 @@
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
<template v-else-if="name === 'sun'">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
</template>
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
<template v-else-if="name === 'qq'">
<ellipse cx="12" cy="12.3" rx="7.25" ry="8.85" fill="#202a2a" stroke="none" />
<ellipse cx="12" cy="14.8" rx="4.1" ry="5.55" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="14.55" cy="9.55" r="1.35" fill="#fff" stroke="none" />
<circle cx="9.45" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<circle cx="14.55" cy="9.55" r=".52" fill="#202a2a" stroke="none" />
<path d="m10 11.15 2-1.05 2 1.05-2 1.45z" fill="#f2a53d" stroke="none" />
<path d="m5.8 18.55-2.1 2.1 3.75-.45m10.75-1.65 2.1 2.1-3.75-.45" fill="#f2a53d" stroke="#f2a53d" stroke-width="1.5" />
</template>
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
<circle v-else cx="12" cy="12" r="8" />
</svg>
+292
View File
@@ -0,0 +1,292 @@
<template>
<div ref="root" class="language-switcher" :class="{ open }" @keydown.esc="close">
<button
type="button"
class="language-trigger"
:aria-label="menuLabel"
aria-haspopup="listbox"
:aria-expanded="open"
:aria-controls="menuId"
@click.stop="toggle"
>
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
<span class="language-current-code">{{ currentLanguage.code }}</span>
<Icon name="chevron-down" :size="13" />
</button>
<div v-if="open" :id="menuId" class="language-dropdown" role="listbox" :aria-label="menuLabel" @click.stop>
<button
v-for="option in options"
:key="option.value"
type="button"
class="language-option"
:class="{ selected: modelValue === option.value }"
role="option"
:aria-selected="modelValue === option.value"
@pointerdown.stop.prevent="select(option.value)"
@keydown.enter.prevent="select(option.value)"
@keydown.space.prevent="select(option.value)"
>
<span class="language-option-flag" aria-hidden="true">{{ option.flag }}</span>
<span class="language-option-copy">
<strong>{{ option.label }}</strong>
<small>{{ option.code }}</small>
</span>
<Icon v-if="modelValue === option.value" name="check" :size="14" />
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import Icon from "./Icon.vue";
type Language = "zh" | "en" | "de" | "ru" | "ja";
const props = withDefaults(defineProps<{
modelValue: Language;
menuLabel?: string;
}>(), {
menuLabel: "Language",
});
const emit = defineEmits<{
"update:modelValue": [value: Language];
change: [value: Language];
}>();
const options: Array<{ value: Language; code: string; label: string; flag: string }> = [
{ value: "zh", code: "ZH", label: "中文", flag: "🇨🇳" },
{ value: "en", code: "EN", label: "English", flag: "🇬🇧" },
{ value: "de", code: "DE", label: "Deutsch", flag: "🇩🇪" },
{ value: "ru", code: "RU", label: "Русский", flag: "🇷🇺" },
{ value: "ja", code: "JA", label: "日本語", flag: "🇯🇵" },
];
const root = ref<HTMLElement | null>(null);
const open = ref(false);
const menuId = `language-menu-${Math.random().toString(36).slice(2, 9)}`;
const currentLanguage = computed(() => options.find((option) => option.value === props.modelValue) ?? options[0]);
function toggle() {
open.value = !open.value;
}
function close() {
open.value = false;
}
function select(value: Language) {
emit("update:modelValue", value);
emit("change", value);
close();
}
function onDocumentPointerDown(event: PointerEvent) {
if (root.value && !root.value.contains(event.target as Node)) close();
}
onMounted(() => document.addEventListener("pointerdown", onDocumentPointerDown));
onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerDown));
</script>
<style scoped>
.language-switcher {
position: relative;
z-index: 20;
flex: 0 0 auto;
color: #006a64;
font-family: inherit;
}
.language-trigger {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 70px;
min-height: 32px;
padding: 0 9px;
color: #006a64;
background: #e2f2ef;
border: 1px solid #c8e6e1;
border-radius: 8px;
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: color .16s, background .16s, border-color .16s, box-shadow .16s;
}
.language-trigger:hover,
.language-switcher.open .language-trigger {
color: #fff;
background: #006a64;
border-color: #006a64;
box-shadow: 0 7px 16px rgba(0, 106, 100, .16);
}
.language-trigger .ui-icon {
margin-left: auto;
transition: transform .16s;
}
.language-switcher.open .language-trigger .ui-icon {
transform: rotate(180deg);
}
.language-current-flag,
.language-option-flag {
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
line-height: 1;
}
.language-current-flag {
font-size: 15px;
}
.language-current-code {
letter-spacing: .02em;
}
.language-dropdown {
position: absolute;
top: calc(100% + 8px);
right: 0;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-auto-rows: minmax(38px, max-content);
align-items: start;
align-content: start;
gap: 3px;
width: min(360px, calc(100vw - 16px));
height: auto;
max-height: none;
padding: 7px;
overflow: visible;
background: #fff;
border: 1px solid #dce9e5;
border-radius: 13px;
box-shadow: 0 16px 36px rgba(23, 60, 54, .18), 0 3px 8px rgba(23, 60, 54, .06);
animation: language-menu-in .14s ease-out;
}
.language-option {
display: flex;
align-items: center;
align-self: start;
min-width: 0;
gap: 8px;
min-height: 38px;
padding: 6px 8px;
color: #344540;
background: transparent;
border: 1px solid transparent;
border-radius: 8px;
font: inherit;
text-align: left;
cursor: pointer;
transition: color .14s, background .14s, border-color .14s;
}
.language-option:hover,
.language-option:focus-visible,
.language-option.selected {
color: #006a64;
background: #edf8f5;
border-color: #d4eee8;
}
.language-option-flag {
flex: 0 0 auto;
font-size: 17px;
}
.language-option-copy {
display: flex;
align-items: baseline;
justify-content: space-between;
min-width: 0;
flex: 1;
gap: 8px;
}
.language-option strong,
.language-option small {
overflow: visible;
text-overflow: clip;
white-space: nowrap;
}
.language-option strong {
flex: 0 0 auto;
font-size: 12px;
}
.language-option small {
flex: 0 0 auto;
color: #91a19c;
font-size: 10px;
font-weight: 700;
}
.language-option > .ui-icon {
flex: 0 0 auto;
}
@keyframes language-menu-in {
from { opacity: 0; transform: translateY(-4px) scale(.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
:global(html[data-theme="dark"]) .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger {
color: #a9d9d1;
background: #203531;
border-color: #38564f;
}
:global(html[data-theme="dark"]) .language-trigger:hover,
:global(html[data-theme="dark"]) .language-switcher.open .language-trigger,
:global(:root[data-theme="dark"]) .language-trigger:hover,
:global(:root[data-theme="dark"]) .language-switcher.open .language-trigger {
color: #10201d;
background: #69d2c7;
border-color: #69d2c7;
}
:global(html[data-theme="dark"]) .language-dropdown,
:global(:root[data-theme="dark"]) .language-dropdown {
background: #172321;
border-color: #30413d;
box-shadow: 0 16px 36px rgba(0, 0, 0, .32);
}
:global(html[data-theme="dark"]) .language-option,
:global(:root[data-theme="dark"]) .language-option {
color: #d7e7e3;
}
:global(html[data-theme="dark"]) .language-option:hover,
:global(html[data-theme="dark"]) .language-option:focus-visible,
:global(html[data-theme="dark"]) .language-option.selected,
:global(:root[data-theme="dark"]) .language-option:hover,
:global(:root[data-theme="dark"]) .language-option:focus-visible,
:global(:root[data-theme="dark"]) .language-option.selected {
color: #69d2c7;
background: #203531;
border-color: #38564f;
}
@media (max-width: 520px) {
.language-trigger {
min-width: 62px;
min-height: 30px;
padding-inline: 7px;
}
.language-dropdown {
width: min(360px, calc(100vw - 16px));
}
}
</style>
File diff suppressed because it is too large. Load diff
+25
View File
@@ -3,9 +3,34 @@ import { createPinia } from "pinia";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import WebClient from "./views/WebClient.vue";
import AdminView from "./views/AdminView.vue";
import DemoView from "./views/DemoView.vue";
import "./services/theme.js";
const BASELINE_WIDTH = 1920;
const BASELINE_HEIGHT = 1080;
const MAX_UI_SCALE = 1.5;
function applyUiScale(): void {
// Keep the current 1080p layout as the reference. Only enlarge the UI when
// both viewport dimensions provide more space; smaller windows keep the
// existing responsive rules instead of shrinking text until it becomes hard
// to read.
const scale = Math.min(
MAX_UI_SCALE,
Math.max(1, Math.min(window.innerWidth / BASELINE_WIDTH, window.innerHeight / BASELINE_HEIGHT)),
);
document.documentElement.style.setProperty("--ui-scale", scale.toFixed(4));
}
applyUiScale();
window.addEventListener("resize", applyUiScale, { passive: true });
const routes = [
{ path: "/", name: "webclient", component: WebClient },
{ path: "/join", name: "join", component: WebClient },
{ path: "/demo", name: "demo", component: DemoView },
{ path: "/admin/:pathMatch(.*)*", name: "admin", component: AdminView },
];
const router = createRouter({
+256
View File
@@ -0,0 +1,256 @@
const DB_NAME = "webspeak-local";
const DB_VERSION = 1;
const CURRENT_IDENTITY_KEY = "current";
const PREFERENCES_KEY = "singleton";
export interface StoredIdentity {
id: string;
label?: string;
privateMaterial: string;
createdAt: number;
lastUsedAt: number;
}
export interface FavoriteServer {
id: string;
label: string;
address: string;
nickname?: string;
identityId?: string;
lastChannelHint?: { id?: string; name?: string };
}
export interface RecentServer {
id: string;
address: string;
nickname?: string;
identityId?: string;
lastConnectedAt: number;
lastChannelHint?: { id?: string; name?: string };
}
export interface LocalPreferences {
schemaVersion: 1;
locale?: "auto" | "zh-CN" | "en";
theme?: "system" | "light" | "dark";
microphoneMuted?: boolean;
noiseSuppressionEnabled?: boolean;
voxThreshold?: number;
language?: "zh" | "en" | "de" | "ru" | "ja";
preferredInputDeviceId?: string;
preferredOutputDeviceId?: string;
inputGain?: number;
outputVolume?: number;
notificationVolume?: number;
lastNickname?: string;
inputDeviceId?: string;
volumesByUid?: Record<string, number>;
}
let databasePromise: Promise<IDBDatabase> | null = null;
export function isLocalPersistenceAvailable(): boolean {
return typeof indexedDB !== "undefined";
}
function openDatabase(): Promise<IDBDatabase> {
if (!isLocalPersistenceAvailable()) return Promise.reject(new Error("IndexedDB unavailable"));
if (databasePromise) return databasePromise;
databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error ?? new Error("Could not open local storage"));
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains("identities")) database.createObjectStore("identities", { keyPath: "id" });
if (!database.objectStoreNames.contains("preferences")) database.createObjectStore("preferences", { keyPath: "id" });
if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" });
if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" });
};
request.onsuccess = () => {
const database = request.result;
database.onversionchange = () => database.close();
resolve(database);
};
}).catch((error) => {
databasePromise = null;
throw error;
});
return databasePromise!;
}
async function request<T>(storeName: string, mode: IDBTransactionMode, action: (store: IDBObjectStore, resolve: (value: T) => void, reject: (reason?: unknown) => void) => void): Promise<T> {
const database = await openDatabase();
return new Promise<T>((resolve, reject) => {
const transaction = database.transaction(storeName, mode);
action(transaction.objectStore(storeName), resolve, reject);
transaction.onerror = () => reject(transaction.error ?? new Error("Local storage transaction failed"));
});
}
export async function loadStoredIdentity(): Promise<StoredIdentity | null> {
try {
return await request<StoredIdentity | null>("identities", "readonly", (store, resolve, reject) => {
const get = store.get(CURRENT_IDENTITY_KEY);
get.onsuccess = () => resolve((get.result as StoredIdentity | undefined) ?? null);
get.onerror = () => reject(get.error);
});
} catch {
return null;
}
}
export async function saveStoredIdentity(privateMaterial: string, label = "此设备"): Promise<boolean> {
try {
const existing = await loadStoredIdentity();
await request("identities", "readwrite", (store, resolve, reject) => {
const put = store.put({
id: CURRENT_IDENTITY_KEY,
label,
privateMaterial,
createdAt: existing?.createdAt ?? Date.now(),
lastUsedAt: Date.now(),
} satisfies StoredIdentity);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
return true;
} catch {
return false;
}
}
export async function removeStoredIdentity(): Promise<void> {
try {
await request("identities", "readwrite", (store, resolve, reject) => {
const remove = store.delete(CURRENT_IDENTITY_KEY);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Identity removal is best effort when browser storage is unavailable.
}
}
export async function loadLocalPreferences(): Promise<LocalPreferences> {
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
try {
const value = await request<(LocalPreferences & { id: string }) | null>("preferences", "readonly", (store, resolve, reject) => {
const get = store.get(PREFERENCES_KEY);
get.onsuccess = () => resolve((get.result as (LocalPreferences & { id: string }) | undefined) ?? null);
get.onerror = () => reject(get.error);
});
if (!value || value.schemaVersion !== 1) return defaults;
return { ...defaults, ...value, volumesByUid: { ...defaults.volumesByUid, ...value.volumesByUid } };
} catch {
return defaults;
}
}
export async function saveLocalPreferences(preferences: LocalPreferences): Promise<void> {
try {
const existing = await loadLocalPreferences();
await request("preferences", "readwrite", (store, resolve, reject) => {
const put = store.put({
...existing,
...preferences,
volumesByUid: { ...existing.volumesByUid, ...preferences.volumesByUid },
id: PREFERENCES_KEY,
});
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
} catch {
// Local preference persistence is optional and never blocks joining.
}
}
export async function listFavorites(): Promise<FavoriteServer[]> {
try {
return await request<FavoriteServer[]>("favorites", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve((get.result as FavoriteServer[]).sort((a, b) => a.label.localeCompare(b.label)));
get.onerror = () => reject(get.error);
});
} catch {
return [];
}
}
export async function saveFavorite(favorite: FavoriteServer): Promise<void> {
try {
await request("favorites", "readwrite", (store, resolve, reject) => {
const put = store.put(favorite);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
} catch {
// Favorites are an optional convenience.
}
}
export async function removeFavorite(id: string): Promise<void> {
try {
await request("favorites", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Favorites are an optional convenience.
}
}
export async function listRecentServers(): Promise<RecentServer[]> {
try {
const recent = await request<RecentServer[]>("recent", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve(get.result as RecentServer[]);
get.onerror = () => reject(get.error);
});
return recent.sort((a, b) => b.lastConnectedAt - a.lastConnectedAt).slice(0, 10);
} catch {
return [];
}
}
export async function recordRecentServer(server: RecentServer): Promise<void> {
try {
await request("recent", "readwrite", (store, resolve, reject) => {
const put = store.put(server);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
const all = await request<RecentServer[]>("recent", "readonly", (store, resolve, reject) => {
const get = store.getAll();
get.onsuccess = () => resolve(get.result as RecentServer[]);
get.onerror = () => reject(get.error);
});
all.sort((a, b) => b.lastConnectedAt - a.lastConnectedAt);
for (const old of all.slice(10)) await removeRecentServer(old.id);
} catch {
// Recent servers are an optional convenience.
}
}
async function removeRecentServer(id: string): Promise<void> {
await request("recent", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
}
export async function clearLocalData(): Promise<void> {
try {
const database = await openDatabase();
await Promise.all(["identities", "preferences", "favorites", "recent"].map((storeName) => new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.objectStore(storeName).clear();
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error ?? new Error("Local storage clear failed"));
transaction.onabort = () => reject(transaction.error ?? new Error("Local storage clear aborted"));
})));
} catch {
// Clearing local data is best effort when storage is unavailable.
}
}
+56
View File
@@ -0,0 +1,56 @@
export const DEFAULT_TEAM_SPEAK_PORT = "9987";
export interface TeamSpeakTargetFields {
address: string;
port: string;
}
/** Split both the current canonical target and the legacy address#port form. */
export function splitTeamSpeakTarget(value: unknown, fallbackPort = DEFAULT_TEAM_SPEAK_PORT): TeamSpeakTargetFields {
const input = typeof value === "string" ? value.trim() : "";
if (!input) return { address: "", port: fallbackPort };
const hash = input.lastIndexOf("#");
if (hash > 0 && isPort(input.slice(hash + 1))) {
return { address: stripBrackets(input.slice(0, hash)), port: input.slice(hash + 1) };
}
if (input.startsWith("[")) {
const closingBracket = input.indexOf("]");
if (closingBracket > 0) {
const address = input.slice(1, closingBracket);
const suffix = input.slice(closingBracket + 1);
const port = suffix.startsWith(":") && isPort(suffix.slice(1)) ? suffix.slice(1) : fallbackPort;
return { address, port };
}
}
const colon = input.lastIndexOf(":");
if (colon > 0 && input.indexOf(":") === colon && isPort(input.slice(colon + 1))) {
return { address: input.slice(0, colon), port: input.slice(colon + 1) };
}
return { address: stripBrackets(input), port: fallbackPort };
}
/** Build the canonical API value from the two user-facing fields. */
export function combineTeamSpeakTarget(address: string, port: string): string {
const normalizedAddress = stripBrackets(address.trim());
const normalizedPort = port.trim() || DEFAULT_TEAM_SPEAK_PORT;
if (!normalizedAddress) return "";
return normalizedAddress.includes(":") ? `[${normalizedAddress}]:${normalizedPort}` : `${normalizedAddress}:${normalizedPort}`;
}
export function isValidTeamSpeakPort(value: string): boolean {
return isPort(value.trim());
}
function isPort(value: string): boolean {
if (!/^\d+$/.test(value)) return false;
const port = Number(value);
return Number.isInteger(port) && port >= 1 && port <= 65535;
}
function stripBrackets(value: string): string {
return value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
}
+32
View File
@@ -0,0 +1,32 @@
export type ThemeMode = "system" | "light" | "dark";
const THEME_KEY = "webspeak:theme";
export function getStoredTheme(): ThemeMode {
const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY);
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function applyTheme(theme: ThemeMode): void {
if (typeof document === "undefined") return;
document.documentElement.dataset.theme = theme;
}
export function saveTheme(theme: ThemeMode): void {
if (typeof localStorage !== "undefined") localStorage.setItem(THEME_KEY, theme);
applyTheme(theme);
}
export function isDarkTheme(theme: ThemeMode): boolean {
if (theme === "dark") return true;
if (theme === "light") return false;
return typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-color-scheme: dark)").matches
: false;
}
export function nextTheme(theme: ThemeMode): ThemeMode {
return isDarkTheme(theme) ? "light" : "dark";
}
applyTheme(getStoredTheme());
File diff suppressed because it is too large. Load diff
+99
View File
@@ -0,0 +1,99 @@
<template>
<div class="demo-page">
<header class="demo-header">
<div class="demo-brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools"><span class="demo-badge">{{ copy.demoBadge }}</span><LanguageSwitcher v-model="language" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/">{{ copy.back }}</a></div>
</header>
<div v-if="reconnecting" class="demo-reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" @click="reconnecting = false">{{ copy.restore }}</button></div>
<main class="demo-shell">
<aside class="demo-channel-panel">
<div class="demo-panel-title"><span>{{ copy.channels }}</span><strong>{{ selectedChannel.name }}</strong></div>
<div v-for="channel in channels" :key="channel.id" :class="['demo-channel', { active: selectedChannelId === channel.id }]">
<button type="button" @click="selectChannel(channel.id)"><Icon name="volume" :size="16" /><span>{{ channel.name }}</span><small>{{ channel.members.length }}</small></button>
<div class="demo-channel-members"><span v-for="member in channel.members" :key="member.id" :class="{ speaking: speakingId === member.id }"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i>{{ member.name }}</span></div>
</div>
</aside>
<section class="demo-main">
<div class="demo-hero"><div><span class="demo-live"><i></i>{{ copy.simulated }}</span><h1><Icon name="volume" :size="24" /> {{ selectedChannel.name }}</h1><p>{{ copy.heroLead }}</p><small><Icon name="users" :size="14" /> {{ selectedChannel.members.length }} {{ copy.online }}</small></div><div class="demo-wave" aria-hidden="true"><i v-for="bar in bars" :key="bar" :style="{ height: `${bar}px` }"></i></div></div>
<div class="demo-section-heading"><span>{{ copy.voiceActivity }}</span><strong>{{ copy.speakingNow }}</strong></div>
<div class="demo-voice-grid"><article v-for="member in selectedChannel.members" :key="member.id" :class="['demo-voice-card', { speaking: speakingId === member.id }]" @click="speakingId = member.id"><i :style="avatarStyle(member.name)">{{ member.name[0] }}</i><strong>{{ member.name }}</strong><span>{{ speakingId === member.id ? copy.speaking : copy.connected }}</span></article></div>
<div class="demo-chat-head"><div><span>{{ copy.textChannel }}</span><strong># {{ selectedChannel.name }} {{ copy.chat }}</strong></div><div class="demo-tabs"><button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: activeTab === tab.id }" @click="activeTab = tab.id">{{ tab.label }}</button></div></div>
<div class="demo-messages"><div v-for="message in visibleMessages" :key="message.id" :class="['demo-message', { mine: message.mine }]" @dblclick="message.mine = !message.mine"><i :style="avatarStyle(message.author)">{{ message.author[0] }}</i><div><small>{{ message.author }} · {{ message.time }}</small><p>{{ messageText(message) }}</p></div></div><div v-if="!visibleMessages.length" class="demo-empty"><Icon name="message" :size="22" /><strong>{{ copy.emptyChat }}</strong></div></div>
<form class="demo-composer" @submit.prevent="sendMessage"><input v-model="draft" :placeholder="copy.placeholder" :aria-label="copy.placeholder" /><button type="submit" :disabled="!draft.trim()"><Icon name="send" :size="17" /></button></form>
</section>
<aside class="demo-actions-panel"><div class="demo-panel-title"><span>{{ copy.voice }}</span><strong>{{ copy.simulationControls }}</strong></div><button type="button" @click="toggleSpeaking"><Icon name="mic" :size="17" /> {{ speakingId ? copy.stopSpeaking : copy.simulateSpeaking }}</button><button type="button" @click="poke = !poke"><Icon name="bell" :size="17" /> {{ copy.poke }}</button><button type="button" @click="reconnecting = true"><Icon name="refresh" :size="17" /> {{ copy.simulateReconnect }}</button><div class="demo-note"><Icon name="shield" :size="16" /><span>{{ copy.demoNote }}</span></div><div class="demo-user"><i :style="avatarStyle('illusia')">I</i><div><strong>illusia</strong><small>{{ copy.you }} · {{ copy.ready }}</small></div><span class="demo-green-dot"></span></div></aside>
</main>
<div v-if="poke" class="demo-poke" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" @click="poke = false"><Icon name="close" :size="14" /></button></div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
type Language = "zh" | "en" | "de" | "ru" | "ja";
interface DemoMessage { id: number; author: string; time: string; text: string; zhText?: string; enText?: string; ruText?: string; jaText?: string; mine: boolean }
type Tab = "channel" | "server";
const storedLanguage = localStorage.getItem("webspeak:language");
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : "zh");
const copy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
const selectedChannelId = ref("quiet");
const activeTab = ref<Tab>("channel");
const speakingId = ref("illusia");
const reconnecting = ref(false);
const poke = ref(false);
const draft = ref("");
const bars = [15, 31, 21, 42, 25, 50, 32, 21, 38, 27, 45, 18, 33];
const channels = [
{ id: "quiet", name: "Quiet Zone", members: [{ id: "illusia", name: "illusia" }, { id: "msicbot", name: "msicbot" }] },
{ id: "lounge", name: "Lounge", members: [{ id: "alice", name: "Alice" }] },
{ id: "music", name: "Music room", members: [] },
];
const messages = ref<DemoMessage[]>([
{ id: 1, author: "illusia", time: "10:24", text: "", zhText: "大家好,欢迎来到 WebSpeak。", enText: "Hello everyone, welcome to WebSpeak.", mine: true },
{ id: 2, author: "msicbot", time: "10:25", text: "", zhText: "语音和文字频道都已同步。", enText: "Voice and text channels are in sync.", mine: false },
]);
const zh = { languageMenu: "语言", browserClient: "浏览器语音工作台", demoBadge: "演示 — 模拟数据", languageSwitch: "English", back: "返回主页", reconnecting: "连接中断,正在恢复…", restore: "恢复连接", channels: "频道", channel: "频道", simulated: "演示状态", heroLead: "这里展示 WebSpeak 的频道、语音和聊天交互。", online: "人在线", voiceActivity: "语音活动", speakingNow: "正在语音中", speaking: "正在说话…", connected: "已连接", textChannel: "文字频道", chat: "聊天", server: "服务器", emptyChat: "暂无消息", placeholder: "发送一条消息…", voice: "语音", simulationControls: "模拟控制", stopSpeaking: "停止说话", simulateSpeaking: "模拟发言", poke: "戳一戳", simulateReconnect: "模拟重连", demoNote: "此页面不会连接真实 TeamSpeak 服务器。", you: "你", ready: "已就绪", pokedYou: "戳了你一下" };
const en = { languageMenu: "Language", browserClient: "Browser voice workspace", demoBadge: "Demo — simulated data", languageSwitch: "中文", back: "Back home", reconnecting: "Connection interrupted, recovering…", restore: "Restore", channels: "Channels", channel: "Channel", simulated: "Simulation", heroLead: "A preview of WebSpeak channels, voice, and chat interactions.", online: "online", voiceActivity: "VOICE ACTIVITY", speakingNow: "Speaking now", speaking: "Speaking…", connected: "Connected", textChannel: "TEXT CHANNEL", chat: "chat", server: "Server", emptyChat: "No messages yet", placeholder: "Send a message…", voice: "Voice", simulationControls: "Simulation controls", stopSpeaking: "Stop speaking", simulateSpeaking: "Simulate speaking", poke: "Poke", simulateReconnect: "Simulate reconnect", demoNote: "This page never connects to a real TeamSpeak server.", you: "You", ready: "Ready", pokedYou: "poked you" };
const de = { languageMenu: "Sprache", browserClient: "Sprachbereich im Browser", demoBadge: "Demo — simulierte Daten", languageSwitch: "中文", back: "Zur Startseite", reconnecting: "Verbindung unterbrochen, Wiederherstellung…", restore: "Wiederherstellen", channels: "Kanäle", channel: "Kanal", simulated: "Simulation", heroLead: "Eine Vorschau auf Kanäle, Sprache und Chat von WebSpeak.", online: "online", voiceActivity: "SPRACHAKTIVITÄT", speakingNow: "Spricht gerade", speaking: "Spricht…", connected: "Verbunden", textChannel: "TEXTKANAL", chat: "Chat", server: "Server", emptyChat: "Noch keine Nachrichten", placeholder: "Nachricht senden…", voice: "Sprache", simulationControls: "Simulation steuern", stopSpeaking: "Sprechen stoppen", simulateSpeaking: "Sprechen simulieren", poke: "Anstupsen", simulateReconnect: "Verbindung simulieren", demoNote: "Diese Seite verbindet sich nie mit einem echten TeamSpeak-Server.", you: "Du", ready: "Bereit", pokedYou: "hat dich angestupst" };
const ru = { languageMenu: "Язык", browserClient: "Голосовое пространство в браузере", demoBadge: "Демо — симуляция", languageSwitch: "中文", back: "На главную", reconnecting: "Соединение прервано, восстановление…", restore: "Восстановить", channels: "Каналы", channel: "Канал", simulated: "Симуляция", heroLead: "Предпросмотр каналов, голоса и чата WebSpeak.", online: "онлайн", voiceActivity: "ГОЛОСОВАЯ АКТИВНОСТЬ", speakingNow: "Сейчас говорят", speaking: "Говорит…", connected: "Подключён", textChannel: "ТЕКСТОВЫЙ КАНАЛ", chat: "чат", server: "Сервер", emptyChat: "Сообщений пока нет", placeholder: "Написать сообщение…", voice: "Голос", simulationControls: "Управление симуляцией", stopSpeaking: "Остановить речь", simulateSpeaking: "Симулировать речь", poke: "Толкнуть", simulateReconnect: "Симулировать переподключение", demoNote: "Эта страница не подключается к реальному серверу TeamSpeak.", you: "Вы", ready: "Готово", pokedYou: "толкнул вас" };
const ja = { languageMenu: "言語", browserClient: "ブラウザ音声ワークスペース", demoBadge: "デモ — シミュレーション", languageSwitch: "中文", back: "ホームに戻る", reconnecting: "接続が中断されました。復旧中…", restore: "復旧", channels: "チャンネル", channel: "チャンネル", simulated: "シミュレーション", heroLead: "WebSpeak のチャンネル、音声、チャットのプレビューです。", online: "人がオンライン", voiceActivity: "音声アクティビティ", speakingNow: "発話中", speaking: "発話中…", connected: "接続済み", textChannel: "テキストチャンネル", chat: "チャット", server: "サーバー", emptyChat: "メッセージはありません", placeholder: "メッセージを送信…", voice: "音声", simulationControls: "シミュレーション操作", stopSpeaking: "発話を停止", simulateSpeaking: "発話をシミュレート", poke: "つつく", simulateReconnect: "再接続をシミュレート", demoNote: "このページは実際の TeamSpeak サーバーには接続しません。", you: "あなた", ready: "準備完了", pokedYou: "あなたをつつきました" };
const tabs = computed(() => [{ id: "channel" as const, label: copy.value.channel }, { id: "server" as const, label: copy.value.server }]);
const selectedChannel = computed(() => channels.find((channel) => channel.id === selectedChannelId.value) ?? channels[0]);
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); }
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : language.value === "ru" ? message.ruText ?? message.enText ?? message.text : language.value === "ja" ? message.jaText ?? message.enText ?? message.text : message.enText ?? message.text; }
function sendMessage() { const text = draft.value.trim(); if (!text) return; messages.value.push({ id: Date.now(), author: "illusia", time: "now", text, mine: true }); draft.value = ""; }
function avatarStyle(name: string) { let hash = 0; for (const char of name) hash = char.charCodeAt(0) + ((hash << 5) - hash); const colors = ["#168f83", "#7b9ed0", "#b99070", "#8b78b9"]; return { background: colors[Math.abs(hash) % colors.length] }; }
</script>
<style scoped>
:global(*) { box-sizing: border-box; }
:global(body) { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f7f9f8; color: #1c2b28; }
.demo-page { min-height: 100dvh; padding: 0 28px 38px; background: radial-gradient(circle at 72% 12%, rgba(126, 213, 205, .18), transparent 26rem), #f7f9f8; }
.demo-header { display: flex; align-items: center; justify-content: space-between; width: min(1380px, 100%); min-height: 82px; margin: 0 auto; }
.demo-brand, .demo-tools, .demo-brand > div, .demo-tools { display: flex; align-items: center; }.demo-brand { gap: 10px; }.demo-brand > span { display: grid; place-items: center; width: 39px; height: 39px; color: #fff; background: #006a64; border-radius: 12px; }.demo-brand strong, .demo-brand small { display: block; }.demo-brand strong { color: #006a64; font-size: 18px; }.demo-brand small { margin-top: 2px; color: #84938e; font-size: 10px; }.demo-tools { gap: 15px; color: #68807a; font-size: 12px; }.demo-tools button, .demo-tools a { padding: 7px 10px; color: #006a64; background: #e1f2ee; border: 1px solid #cbe6e0; border-radius: 7px; font-size: 11px; font-weight: 700; text-decoration: none; cursor: pointer; }.demo-badge { color: #2d7d50; font-weight: 700; }
.demo-reconnect { display: flex; align-items: center; gap: 9px; width: min(1380px, 100%); margin: 0 auto 14px; padding: 11px 14px; color: #8b6537; background: #fff8e9; border: 1px solid #efd9aa; border-radius: 10px; }.demo-reconnect span { flex: 1; }.demo-reconnect button { padding: 6px 10px; color: #7d5d35; background: #fff; border: 1px solid #ead0a0; border-radius: 6px; cursor: pointer; }
.demo-shell { display: grid; grid-template-columns: 240px minmax(0, 1fr) 235px; gap: 18px; width: min(1380px, 100%); min-height: 720px; margin: 0 auto; }.demo-channel-panel, .demo-actions-panel, .demo-main { min-width: 0; padding: 20px; border: 1px solid #e0ebe7; border-radius: 16px; background: rgba(255,255,255,.9); box-shadow: 0 12px 30px rgba(26,66,59,.05); }.demo-panel-title { display: grid; gap: 5px; margin-bottom: 20px; }.demo-panel-title span, .demo-section-heading span, .demo-chat-head span { color: #79918c; font-size: 10px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }.demo-panel-title strong { color: #263a35; font-size: 18px; }.demo-channel { margin: 4px -8px 12px; padding: 3px 8px 9px; border-radius: 10px; }.demo-channel.active { background: #e2f3ef; }.demo-channel > button { display: flex; align-items: center; gap: 7px; width: 100%; padding: 8px 0; color: #45635b; background: transparent; border: 0; text-align: left; cursor: pointer; }.demo-channel.active > button { color: #006a64; font-weight: 800; }.demo-channel button span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.demo-channel button small { color: #84a19a; }.demo-channel-members { display: grid; gap: 7px; padding-left: 22px; color: #7b8e88; font-size: 11px; }.demo-channel-members span { display: flex; align-items: center; gap: 7px; }.demo-channel-members i, .demo-user > i, .demo-voice-card > i, .demo-message > i { display: grid; place-items: center; flex: 0 0 auto; color: #fff; border-radius: 50%; font-style: normal; font-weight: 800; }.demo-channel-members i { width: 20px; height: 20px; font-size: 9px; }.demo-channel-members span.speaking i { box-shadow: 0 0 0 2px #83e88d, 0 0 10px rgba(83,214,105,.45); }
.demo-main { padding: 27px 32px; }.demo-hero { display: flex; align-items: center; justify-content: space-between; min-height: 190px; padding: 26px 29px; overflow: hidden; border-radius: 14px; background: linear-gradient(112deg, #dff3ef, #f6fbfa); }.demo-live { display: inline-flex; align-items: center; gap: 7px; padding: 5px 9px; color: #2d7e48; background: #d4f3d9; border-radius: 999px; font-size: 10px; font-weight: 700; }.demo-live i, .demo-green-dot { width: 7px; height: 7px; background: #58d476; border-radius: 50%; }.demo-hero h1 { display: flex; align-items: center; gap: 8px; margin: 17px 0 7px; color: #18302c; font-size: 28px; letter-spacing: -.05em; }.demo-hero p { margin: 0 0 15px; color: #64817a; font-size: 12px; }.demo-hero small { display: flex; align-items: center; gap: 6px; color: #52716b; font-size: 11px; }.demo-wave { display: flex; align-items: center; gap: 5px; height: 60px; padding-right: 22px; }.demo-wave i { width: 4px; border-radius: 4px; background: #65cabe; }.demo-wave i:nth-child(3n) { background: #8fe990; }.demo-section-heading { display: grid; gap: 5px; margin: 31px 0 15px; }.demo-section-heading strong { color: #1d2c28; font-size: 21px; }.demo-voice-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(125px, 1fr)); gap: 11px; }.demo-voice-card { display: grid; justify-items: center; gap: 7px; padding: 15px 8px; border: 1px solid #edf1ef; border-radius: 12px; background: #fff; cursor: pointer; }.demo-voice-card > i { width: 56px; height: 56px; font-size: 18px; }.demo-voice-card strong { color: #2c3935; font-size: 12px; }.demo-voice-card span { color: #91a09a; font-size: 10px; }.demo-voice-card.speaking { border-color: #83e88d; box-shadow: 0 0 0 2px rgba(131,232,141,.18), 0 8px 20px rgba(68,173,79,.12); }.demo-voice-card.speaking span { color: #2e8b45; }.demo-chat-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 12px; margin-top: 33px; padding-top: 23px; border-top: 1px solid #edf2f0; }.demo-chat-head strong { display: block; margin-top: 6px; color: #1d2c28; font-size: 20px; }.demo-tabs { display: flex; gap: 5px; }.demo-tabs button { padding: 7px 9px; color: #78908a; background: #f0f6f3; border: 0; border-radius: 7px; cursor: pointer; }.demo-tabs button.active { color: #006a64; background: #dff1ed; font-weight: 700; }.demo-messages { display: grid; align-content: start; gap: 13px; min-height: 215px; max-height: 270px; margin-top: 17px; overflow-y: auto; padding: 7px 3px; }.demo-message { display: flex; align-items: flex-start; gap: 9px; max-width: 76%; }.demo-message.mine { justify-self: end; flex-direction: row-reverse; text-align: right; }.demo-message > i { width: 29px; height: 29px; font-size: 10px; }.demo-message small { color: #9ca9a4; font-size: 9px; }.demo-message p { margin: 4px 0 0; padding: 8px 11px; color: #43534e; background: #f1f5f3; border-radius: 4px 11px 11px 11px; font-size: 12px; }.demo-message.mine p { color: #fff; background: #006a64; border-radius: 11px 4px 11px 11px; }.demo-empty { display: grid; place-content: center; justify-items: center; gap: 8px; min-height: 170px; color: #91a29b; }.demo-empty strong { font-size: 12px; }.demo-composer { display: flex; gap: 8px; padding: 7px 8px 7px 12px; background: #f1f6f4; border-radius: 10px; }.demo-composer input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; font-size: 12px; }.demo-composer button { display: grid; place-items: center; width: 34px; height: 34px; color: #fff; background: #006a64; border: 0; border-radius: 8px; cursor: pointer; }.demo-composer button:disabled { opacity: .35; cursor: not-allowed; }
.demo-actions-panel { display: flex; flex-direction: column; gap: 9px; }.demo-actions-panel > button { display: flex; align-items: center; gap: 8px; padding: 10px; color: #4d6a62; background: #f0f6f3; border: 1px solid #e1ece8; border-radius: 8px; text-align: left; cursor: pointer; }.demo-actions-panel > button:hover { color: #006a64; border-color: #b9ddd6; }.demo-note { display: flex; gap: 8px; margin-top: 10px; padding: 11px; color: #68837b; background: #eef8f4; border-radius: 9px; font-size: 10px; line-height: 1.5; }.demo-user { display: flex; align-items: center; gap: 9px; margin-top: auto; padding-top: 15px; border-top: 1px solid #e9efed; }.demo-user > i { width: 35px; height: 35px; font-size: 12px; }.demo-user div { min-width: 0; flex: 1; }.demo-user strong, .demo-user small { display: block; }.demo-user strong { color: #34423d; font-size: 12px; }.demo-user small { margin-top: 4px; color: #8a9a94; font-size: 10px; }.demo-poke { position: fixed; z-index: 10; top: 82px; right: 25px; display: flex; align-items: center; gap: 9px; max-width: min(380px, calc(100% - 32px)); padding: 11px 12px; color: #52645c; background: #fffdf6; border: 1px solid #f0dfbd; border-radius: 9px; box-shadow: 0 8px 22px rgba(88,65,28,.12); font-size: 12px; }.demo-poke span { flex: 1; }.demo-poke strong { color: #8f6532; }.demo-poke button { display: grid; place-items: center; padding: 3px; color: #9b8a6e; background: transparent; border: 0; cursor: pointer; }
@media (max-width: 1080px) { .demo-shell { grid-template-columns: 210px minmax(0, 1fr); }.demo-actions-panel { grid-column: 1 / -1; min-height: 160px; }.demo-actions-panel .demo-panel-title { margin-bottom: 3px; }.demo-actions-panel > button { display: inline-flex; width: fit-content; }.demo-note { margin-top: 4px; }.demo-user { margin-top: 0; } }
@media (max-width: 720px) { .demo-page { padding: 0 14px 24px; }.demo-header { min-height: 68px; }.demo-tools { gap: 6px; font-size: 10px; }.demo-badge { display: none; }.demo-shell { display: block; min-height: 0; }.demo-channel-panel { margin-bottom: 12px; }.demo-channel-panel .demo-channel:not(.active) { display: none; }.demo-actions-panel { margin-top: 12px; }.demo-main { padding: 17px 14px; }.demo-hero { min-height: 170px; padding: 20px; }.demo-wave { padding-right: 0; transform: scale(.75); transform-origin: right center; }.demo-chat-head { display: grid; align-items: start; }.demo-tabs { overflow-x: auto; }.demo-message { max-width: 94%; } }
@media (max-width: 360px) { .demo-tools a { display: none; }.demo-hero h1 { font-size: 23px; }.demo-hero p { font-size: 11px; }.demo-voice-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
:global(:root[data-theme="dark"]) .demo-page { color: #e8f3f0; background: #101918; }
:global(:root[data-theme="dark"]) .demo-channel-panel, :global(:root[data-theme="dark"]) .demo-actions-panel, :global(:root[data-theme="dark"]) .demo-main, :global(:root[data-theme="dark"]) .demo-voice-card { background: #172321; border-color: #30413d; }
:global(:root[data-theme="dark"]) .demo-panel-title strong, :global(:root[data-theme="dark"]) .demo-hero h1, :global(:root[data-theme="dark"]) .demo-section-heading strong, :global(:root[data-theme="dark"]) .demo-chat-head strong, :global(:root[data-theme="dark"]) .demo-voice-card strong, :global(:root[data-theme="dark"]) .demo-user strong { color: #e8f3f0; }
:global(:root[data-theme="dark"]) .demo-hero { background: linear-gradient(112deg, #173e3a, #172321); }
:global(:root[data-theme="dark"]) .demo-message p, :global(:root[data-theme="dark"]) .demo-composer, :global(:root[data-theme="dark"]) .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
:global(:root[data-theme="dark"]) .demo-chat-head, :global(:root[data-theme="dark"]) .demo-user { border-color: #30413d; }
@media (prefers-color-scheme: dark) { :global(:root[data-theme="system"]) .demo-channel-panel, :global(:root[data-theme="system"]) .demo-actions-panel, :global(:root[data-theme="system"]) .demo-main, :global(:root[data-theme="system"]) .demo-voice-card { background: #172321; border-color: #30413d; } }
:global(button:focus-visible), :global(a:focus-visible), :global(input:focus-visible), :global(select:focus-visible) { outline: 3px solid #69d2c7; outline-offset: 2px; }
</style>
+2406 -265
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+2 -2
View File
@@ -6,9 +6,9 @@ export default defineConfig({
server: {
port: 5173,
proxy: {
"/api": "http://localhost:3030",
"/api": "http://localhost:3040",
"/ws": {
target: "ws://localhost:3030",
target: "ws://localhost:3040",
ws: true,
},
},
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB