From 541a216c4d0c67e63f5138a01598bf80da8d308f Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Thu, 1 Oct 2026 08:34:04 +0800 Subject: [PATCH] test: establish gateway refactoring checks and prevent stale directory entries --- .github/workflows/build-release.yml | 9 +- .github/workflows/ci.yml | 10 +- .github/workflows/docker-publish.yml | 4 + CLAUDE.md | 155 +++++++++++++-------------- Dockerfile | 2 +- docs/CODE_REFACTOR_PLAN.zh-CN.md | 27 +++-- package.json | 5 +- src/server/directory-sync.test.ts | 61 +++++++++++ src/server/directory-sync.ts | 8 ++ src/server/identity-lease.test.ts | 24 +++++ src/server/join-ticket.test.ts | 51 +++++++++ src/server/reconnect-policy.test.ts | 28 +++++ src/server/session-manager.test.ts | 95 ++++++++++++++++ 13 files changed, 385 insertions(+), 94 deletions(-) create mode 100644 src/server/directory-sync.test.ts create mode 100644 src/server/identity-lease.test.ts create mode 100644 src/server/join-ticket.test.ts create mode 100644 src/server/reconnect-policy.test.ts create mode 100644 src/server/session-manager.test.ts diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index 60ae5fb..f61822c 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -16,7 +16,11 @@ permissions: contents: read jobs: + verify: + uses: ./.github/workflows/ci.yml + windows-x64: + needs: verify runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -47,7 +51,7 @@ jobs: npm version --no-git-tag-version $releaseVersion if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } - npm --prefix web run build + npm run web:build if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } npm run build if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } @@ -118,6 +122,7 @@ jobs: compression-level: 0 linux-x64: + needs: verify runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -142,7 +147,7 @@ jobs: if [ "$current_version" != "$release_version" ]; then npm version --no-git-tag-version "$release_version" fi - npm --prefix web run build + npm run web:build npm run build npm prune --omit=dev --no-audit --no-fund - name: Package and smoke-test Linux x64 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a2431d3..4f8048d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,10 @@ name: Continuous integration on: push: - branches: [main] + branches: [dev, master] pull_request: + workflow_call: + workflow_dispatch: permissions: contents: read @@ -26,10 +28,8 @@ jobs: 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 + - name: Test and build application + run: npm run verify docker-smoke: needs: verify diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 5d4e5bb..aaea48c 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -14,7 +14,11 @@ env: IMAGE_NAME: ghcr.io/echosixhiya/webspeak jobs: + verify: + uses: ./.github/workflows/ci.yml + publish: + needs: verify runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/CLAUDE.md b/CLAUDE.md index 711c564..c57e4df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,90 +1,89 @@ -# WebSpeak — TeamSpeak Browser Gateway +# WebSpeak TeamSpeak Browser Gateway -Server-side bridge that lets users join TeamSpeak voice channels from a browser. No TS client install needed. +WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-hosted Node.js gateway. Each connected browser session owns an independent TeamSpeak client. The repository also contains a standalone UDP acceleration relay and an Android preview with an embedded local gateway. -## Architecture +## Application boundaries -``` -Browser (PCM capture) → WebSocket → Node.js server (PCM→Opus) → TeamSpeak server -Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpeak server +| Location | Responsibility | +| --- | --- | +| `src/index.ts` | Gateway startup, SQLite, master secret, admin service and shutdown; also supports relay mode | +| `src/server/server.ts` | HTTP or HTTPS, public configuration, skins, join tickets, admin routes and static frontend | +| `src/server/voice-bridge.ts` | `/ws/voice`, session orchestration, control commands, voice and screen-sharing signaling | +| `src/server/ts-client.ts` and `teamspeak-adapter.ts` | SDK integration, TS3/TS6 negotiation, identity, chat, voice and client events | +| `src/server/session-manager.ts` and `directory-sync.ts` | Connection state, teardown, admission limits and directory reconciliation | +| `src/server/webrtc-audio.ts` and `opus-codec.ts` | WebRTC audio mixing and platform-specific Opus codecs | +| `src/admin/`, `src/security/`, `src/persistence/` | Administration, access policies, credentials and persistent settings | +| `src/relay.ts` and `src/server/acceleration-relay.ts` | Standalone relay and gateway-side relay transport | +| `web/src/views/` and `web/src/composables/` | Vue pages, connection state, audio controls, chat and screen sharing | +| `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations | +| `src/mobile/`, `mobile/`, `web/android/` | Android loopback gateway, asset packaging and Capacitor container | + +## Connection and control protocol + +1. The browser requests `/api/join-ticket`. The gateway validates the request against its access policy and issues a short-lived, single-use ticket. +2. The browser presents the ticket to `/ws/voice`. The bridge admits a session, acquires any required identity lease and creates its TeamSpeak client. +3. WebSocket text messages carry JSON commands, events, WebRTC negotiation and screen-sharing signaling. The server uses the WebSocket `isBinary` flag to distinguish audio from control messages. +4. Register TeamSpeak event listeners before connecting: directory and membership events may arrive during the handshake. + +Channel and member data come from SDK directory snapshots and client-protocol commands, followed by realtime notifications. WebQuery and its API key are not required. `DirectorySynchronizer` reconciles snapshots with membership events. + +Session teardown must remain safe when requested more than once or when sockets and codec resources are already closed. Reconnection is governed by `reconnect-policy.ts`; preserve terminal error handling, bounded retries and the previous-channel fallback. + +## Audio and screen sharing + +The compatibility voice path captures 48 kHz mono PCM using an AudioWorklet, with a ScriptProcessor fallback. The browser assembles 960-sample, 20 ms frames and sends 1,920-byte Int16 payloads over WebSocket. The gateway encodes them as Opus for TeamSpeak. Incoming Opus uses a three-byte header containing codec and client ID, then browser WebCodecs decoding and playback. + +When enabled by the administrator, WebRTC provides a separate voice transport between the browser and gateway. The gateway uses `werift` and mixes incoming TeamSpeak speakers for WebRTC playback. Negotiation failures can fall back to the compatibility path. Keep microphone mute, per-member volume and playback behavior consistent across both transports. + +Screen sharing has its own peer connections. The gateway coordinates stream membership and SDP/ICE signaling between browsers and supported TeamSpeak 6 clients. Screen media travels directly or through an externally configured TURN server; the WebSpeak gateway does not carry screen media. + +Preserve bounded audio buffering and stale-playback recovery. Audio counters stay in memory and are exposed in session diagnostics. Do not add per-frame persistent logging to the voice path. + +`src/server/opus-codec.ts` loads the native `@discordjs/opus` implementation for server deployments and `opusscript` for the Android bundle. Dispose codec and media resources at the end of their owning session. + +## Configuration and persistence + +| Source | Purpose | +| --- | --- | +| SQLite `webspeak.db` | Admin credentials, target and access settings, relay nodes, invitations, audit records and visitor metadata | +| `master.key` beside the database | Encryption key for persisted secrets; retain it with database backups | +| `/admin` | Normal configuration and operational controls | +| Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings | +| `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` | +| `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup | +| Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings | +| Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state | + +The current SQLite schema version is defined in `src/persistence/database.ts`. Keep schema migrations separate from structural refactors. Legacy fields such as `voiceToken`, `tsApiKey`, `tsQueryPort`, `port` and `maxClients` do not configure the current gateway. + +The gateway HTTP port is `3040`. Its admission ceiling is `100` sessions, defined in `src/constants.ts`; this is an application limit, not a TeamSpeak license allowance or a measured performance guarantee. Target server capacity and permissions still apply. + +The server uses HTTPS when `certs/cert.pem` and `certs/key.pem` are supplied; otherwise it starts HTTP. It does not generate certificates. Use an appropriate secure browser origin for microphone and screen capture, typically HTTPS in public deployments. Feature support depends on the browser and selected transport; do not infer a universal minimum browser version from WebCodecs alone. + +## Development and verification + +Server deployments require Node.js 22.5 or newer. CI uses Node.js 22.22.2. Root and frontend dependencies are installed separately. The pinned Git SDK and native Opus module require the preparation steps used by CI: + +```sh +npm ci --ignore-scripts --no-audit --no-fund +npm run prepare:sdk +npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund +npm --prefix web ci --no-audit --no-fund +npm run verify ``` -- Each browser user = one independent TS3 virtual client via `@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 -- Channel/member list fetched via TS6 WebQuery HTTP API (port 10080, requires API key) -- WebSocket text frames = JSON commands, binary frames = PCM audio / Opus relay +`npm run verify` runs unit tests, the backend build and `npm run web:build`. The latter delegates to the frontend build, including `vue-tsc --noEmit`. Use `npm run dev` and `npm run web:dev` for development, or `npm start` after building both applications. -## Project Structure +CI verifies pushes to `dev` and `master`, pull requests and manual runs. Docker publication on `master` or release tags, and release packaging on tags or manual runs, call the same verification workflow before publishing or packaging. Verification includes the application checks and a Docker HTTP health smoke test; that smoke test does not prove voice or screen-sharing functionality. -``` -web/ # Vue 3 + Vite frontend (SPA) - src/composables/useVoiceWebSocket.ts # Mic capture, VOX/PTT, playback, WS client - src/views/WebClient.vue # Connect form + channel/member tree -src/ - index.ts # Entry point, config loading, server startup - config.ts # AppConfig interface + load/save - logger.ts # Pino wrapper - server/ - server.ts # Express + HTTPS + WS setup - voice-bridge.ts # /ws/voice endpoint, PCM→Opus encoding, WebQuery API - ts-client.ts # TS3Client wrapper around @echosixhiya/teamspeak-client -``` +Tests requiring a real TeamSpeak server, browser media devices or Android hardware must document their environment and outcome separately. Never substitute a mock codec or an HTTP health response for a successful audio test. -## Key Technical Details +## Android preview -### Audio Pipeline -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 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. +The Android app starts an embedded Node.js gateway on `127.0.0.1:3040` and opens it in the WebView. This preview disables gateway WebRTC voice and the admin console, while reusing the compatibility voice path. Its dependencies and runtime differ from server deployments. -Audio flow counters are kept in memory and exposed in admin session summaries. Do not add per-frame persistent logging to the voice path. +See `mobile/README.md` for build steps and recorded limitations. The embedded Node.js version, SDK compatibility, real-device connections, background audio and native screen sharing require their own validation. Do not present these capabilities as production-ready based on desktop tests. -### CJS Interop -`@discordjs/opus` is CommonJS, loaded via: -```ts -import { createRequire } from "node:module"; -const require = createRequire(import.meta.url); -const { OpusEncoder } = require("@discordjs/opus"); -``` +## Repository maintenance -### WebSocket Message Routing -- Text frames → JSON commands (`listChannels`, `switchChannel`) -- Binary frames → PCM audio (browser→server) or Opus frames (server→browser) -- JSON detection: `typeof data === "string"` first, then fallback `data[0] === 0x7b` with try/catch - -### Event Handlers -Must be registered BEFORE `tsClient.connect()` because `clientEnter`/`clientLeave` fire during handshake. - -### Channel List -Uses TS6 WebQuery HTTP API (`http://tsHost:tsQueryPort/1/channellist`) with `x-api-key` header. Falls back empty if `tsApiKey` not configured. Regular TS3 voice clients lack permission for `listChannels`/`listClients`. - -### Config (config.json) -```json -{ - "port": 3040, "tsHost": "127.0.0.1", "tsPort": 9987, - "tsQueryPort": 10080, "tsServerProtocol": "ts6", - "tsApiKey": "", "voiceToken": "change-me", "maxClients": 10 -} -``` - -## Build & Deploy -```bash -npm install && cd web && npm install && npx vite build && cd .. && npx tsc -node dist/index.js -``` - -## Git -- Remote: `https://github.com/EchoSixHIYA/web-client-for-TeamSpeak` -- `webspeak-update.tar.gz` is in .gitignore (deployment artifact) -- No secrets in source; config.json is gitignored - -## Known Limitations -- Browser must be Chrome/Edge 94+ (WebCodecs AudioDecoder) -- HTTPS required (self-signed cert OK, generated in `certs/`) -- Max 32 concurrent users (TS3 license limit) -- `tsApiKey` required for channel list; voice works without it +The repository remote is `https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak`. Preserve existing local work when implementing the plan in `docs/CODE_REFACTOR_PLAN.zh-CN.md`. Keep private configuration, runtime data and local deployment archives out of source commits. Preserve documented skin hooks and browser persistence formats during component refactors. diff --git a/Dockerfile b/Dockerfile index f46f3df..237b45c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,7 @@ RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund RUN npm --prefix web ci COPY . . -RUN npm --prefix web run build \ +RUN npm run web:build \ && npm run build \ && npm prune --omit=dev \ && rm -rf web/node_modules diff --git a/docs/CODE_REFACTOR_PLAN.zh-CN.md b/docs/CODE_REFACTOR_PLAN.zh-CN.md index 1ff6a89..ad685bf 100644 --- a/docs/CODE_REFACTOR_PLAN.zh-CN.md +++ b/docs/CODE_REFACTOR_PLAN.zh-CN.md @@ -1,6 +1,6 @@ # WebSpeak 代码待修改清单与修改方向 -本文记录 `webspeak-webclient` 当前需要整理的代码、工程流程和文档,并给出大致修改方向及验收标准。建议先统一验证流程、补充关键行为测试,再逐步拆分语音与会话模块。本文中的事项均待实施。 +本文记录 `webspeak-webclient` 需要整理的代码、工程流程和文档,并给出大致修改方向及验收标准。按统一验证流程、补充关键行为测试、逐步拆分模块的顺序推进;当前状态见待修改事项总览和实施记录。 ## 范围与基线 @@ -9,9 +9,9 @@ - 分析对象:当前工作区,包含已有未提交改动,不等同于该提交的干净检出。 - 工作区现状:记录时已有 10 个受跟踪文件修改;Android 相关目录、Opus 适配文件及部分本地产物尚未跟踪。 - 验证范围:静态阅读源码、配置和工作流,未运行构建、单元测试、真实 TeamSpeak 连接或 Android 真机验证。 -- 本次交付:新增本清单,未实施下面的代码修改。 +- 首次交付:仅新增本清单;随后从已提交并同步到远端的 `0276b6e` 开始第一批施工。 -下文将已确认的现状与建议方向分开描述。优先级表示建议实施顺序,不代表已确认的故障或安全漏洞等级。 +下文的现状描述保留首次梳理时的依据,后续变化记录在实施记录中。优先级表示建议实施顺序,不代表已确认的故障或安全漏洞等级。 ## 当前代码边界 @@ -32,14 +32,14 @@ | 编号 | 优先级 | 事项 | 性质 | 状态 | | --- | --- | --- | --- | --- | -| 01 | P1 | 统一构建命令与 CI 验证入口 | 已确认的工程配置差异 | 待实施 | -| 02 | P1 | 补齐会话与媒体关键行为测试 | 已观察到的测试缺口 | 待实施 | +| 01 | P1 | 统一构建命令与 CI 验证入口 | 已确认的工程配置差异 | 已实现并本地验证,远端 CI 待验证 | +| 02 | P1 | 补齐会话与媒体关键行为测试 | 已观察到的测试缺口 | 进行中,已补充 18 项基础行为测试 | | 03 | P2 | 集中前后端协议契约 | 重构建议 | 待实施 | | 04 | P2 | 拆分前端语音核心模块 | 重构建议 | 待实施 | | 05 | P2 | 拆分服务端实时桥接模块 | 重构建议 | 待实施 | | 06 | P2 | 拆分页面组件与管理页逻辑 | 重构建议 | 待实施 | | 07 | P2 | 明确 Android 平台边界与验证范围 | 未提交扩展的整理与验证 | 待实施 | -| 08 | P1 | 修正文档与实现不一致的说明 | 已确认的文档偏差 | 待实施 | +| 08 | P1 | 修正文档与实现不一致的说明 | 已确认的文档偏差 | 已修正并核对实现 | | 09 | P3 | 整理源码与本地产物边界 | 仓库维护建议 | 待实施 | P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性改进。大文件行数仅用于定位职责集中处,不作为拆分目标或质量评分。 @@ -139,3 +139,18 @@ P1 为后续重构的准备工作,P2 为模块整理,P3 为维护便利性 - SQLite schema、依赖主版本及新增原生功能按独立变更处理,以便验证和回退。 - 普通代码修改执行相关测试与前后端构建;涉及媒体行为时补充真实连接验证;涉及打包流程时执行对应平台构建。 - 各事项完成后记录修改范围、验证结果和剩余限制,再更新清单状态。本文的验收标准不代表相关检查已经通过。 + +## 第一批实施记录 + +实施日期为 2026 年 10 月 1 日。基线提交 `0276b6e` 已同步到远端 `dev`,本地与远端提交哈希一致;第一批施工改动保留在该提交之后的工作区,尚未再次提交或推送。 + +| 事项 | 已实施内容 | 验证依据 | +| --- | --- | --- | +| 01 | 新增 `npm run verify`;根目录前端构建包含类型检查;CI 覆盖 `dev`、`master`、PR 和手动运行;镜像及发布包工作流先调用同一验证工作流 | 本地完整验证命令成功;工作流 YAML、调用关系和发布依赖已静态检查 | +| 02 | 新增凭证、身份占用、会话状态与清理、目录同步、重连策略等 5 个测试文件,共 18 项测试 | 单元测试由 33 项增加至 51 项,全部通过 | +| 02 发现的问题 | 离开成员可能被迟到的分段快照重新加入目录;记录离开状态,直到明确重新进入或连接目录重置 | 回归测试先复现失败,修复后通过;同时覆盖迟到更新、重新进入和目录重置 | +| 08 | 更新 `CLAUDE.md` 的协议、音频、配置、容量、构建及 Android 边界说明 | 对照入口、SDK 适配、配置导入、常量及工作流核对 | + +本地验证环境为 Windows、Node.js 24.12.0,执行了 `npm run verify`,包含 51 项单元测试、后端 TypeScript 编译及前端类型检查和生产构建。前端仍存在原有的单个产物超过 500 kB 的提示,本批未调整分包。 + +远端 GitHub Actions、Docker 镜像构建及容器启动尚未验证,本机未提供 Docker 命令。真实 TeamSpeak 音频、WebRTC 回退、屏幕共享资源清理、Android 真机行为仍需后续验证;已有状态机和策略测试不能代替这些集成验证。事项 02 保持进行中,事项 03 至 07 及 09 尚未实施。 diff --git a/package.json b/package.json index e2c2f7f..ce94eb5 100644 --- a/package.json +++ b/package.json @@ -11,10 +11,11 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts scripts/docker-healthcheck.test.mjs web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts", + "test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/reconnect-policy.test.ts scripts/docker-healthcheck.test.mjs web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts", + "verify": "npm test && npm run build && npm run web:build", "start": "node dist/index.js", "web:dev": "cd web && npx vite --host", - "web:build": "cd web && npx vite build", + "web:build": "npm --prefix web run build", "android:prepare": "npm run build && npm --prefix web run build && node mobile/pack.mjs", "android:sync": "npm run android:prepare && cd web && npx cap sync android", "prepare:sdk": "node scripts/prepare-sdk.mjs", diff --git a/src/server/directory-sync.test.ts b/src/server/directory-sync.test.ts new file mode 100644 index 0000000..beacc5f --- /dev/null +++ b/src/server/directory-sync.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { DirectoryClientInfo, DirectorySnapshot } from "@echosixhiya/teamspeak-client"; +import { DirectorySynchronizer } from "./directory-sync.js"; + +function member(id: number, channelID = 1n, overrides: Partial = {}): DirectoryClientInfo { + return { id, channelID, nickname: `Member ${id}`, uid: `uid-${id}`, serverGroups: [], type: 0, ...overrides }; +} + +function snapshot(...clients: DirectoryClientInfo[]): DirectorySnapshot { + return { channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }], clients }; +} + +test("events received during the welcome sequence override the initial snapshot in order", () => { + const directory = new DirectorySynchronizer(); + directory.applyClientMoved(1, 2n); + directory.applyClientLeave(2); + directory.applyClientEnter(member(3)); + directory.applyClientUpdated(member(3, 1n, { inputMuted: true })); + assert.equal(directory.ready, false); + assert.equal(directory.getSnapshot(), null); + directory.applySnapshot(snapshot(member(1), member(2))); + assert.equal(directory.ready, true); + assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n), member(3, 1n, { inputMuted: true })]); +}); + +test("partial snapshots retain earlier clients and state omitted by a later snapshot", () => { + const directory = new DirectorySynchronizer(); + directory.applySnapshot(snapshot(member(1, 1n, { inputMuted: true }), member(2))); + directory.applySnapshot(snapshot(member(1, 2n), member(3))); + assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n, { inputMuted: true }), member(2), member(3)]); +}); + +test("a stale partial snapshot cannot bring back a departed client before an explicit rejoin", () => { + const directory = new DirectorySynchronizer(); + directory.applySnapshot(snapshot(member(1), member(2))); + directory.applyClientLeave(2); + directory.applySnapshot(snapshot(member(2), member(3))); + directory.applyClientUpdated(member(2, 1n, { away: true })); + assert.deepEqual(directory.getSnapshot()?.clients.map((client) => client.id), [1, 3]); + directory.applyClientEnter(member(2, 2n, { uid: "new-uid" })); + assert.deepEqual(directory.getSnapshot()?.clients.find((client) => client.id === 2), member(2, 2n, { uid: "new-uid" })); +}); + +test("clearing the directory drops pending events and departure history for a new connection", () => { + const directory = new DirectorySynchronizer(); + directory.applyClientLeave(1); + directory.applyClientEnter(member(2)); + directory.clear(); + directory.applySnapshot(snapshot(member(1))); + directory.applyClientLeave(1); + directory.clear(); + assert.equal(directory.ready, false); + directory.applySnapshot(snapshot(member(1))); + const exposed = directory.getSnapshot()!; + assert.deepEqual(exposed.clients, [member(1)]); + exposed.clients.pop(); + exposed.channels.pop(); + assert.equal(directory.getSnapshot()?.clients.length, 1); + assert.equal(directory.getSnapshot()?.channels.length, 1); +}); diff --git a/src/server/directory-sync.ts b/src/server/directory-sync.ts index 99e4e2b..4501566 100644 --- a/src/server/directory-sync.ts +++ b/src/server/directory-sync.ts @@ -16,6 +16,9 @@ type DirectoryDelta = export class DirectorySynchronizer { private snapshot: TSDirectorySnapshot | null = null; private clients = new Map(); + // A delayed welcome snapshot or update must not undo an explicit leave. + // Client IDs can be reused, so a new enter event releases the tombstone. + private departedClientIds = new Set(); private pending: DirectoryDelta[] = []; get ready(): boolean { @@ -25,6 +28,7 @@ export class DirectorySynchronizer { applySnapshot(snapshot: TSDirectorySnapshot): void { this.snapshot = { channels: snapshot.channels.slice(), clients: [] }; for (const client of snapshot.clients) { + if (this.departedClientIds.has(client.id)) continue; const previous = this.clients.get(client.id); this.clients.set(client.id, previous ? { ...previous, ...client } : client); } @@ -59,6 +63,7 @@ export class DirectorySynchronizer { clear(): void { this.snapshot = null; this.clients.clear(); + this.departedClientIds.clear(); this.pending = []; } @@ -72,14 +77,17 @@ export class DirectorySynchronizer { private applyDelta(delta: DirectoryDelta): void { if (delta.type === "clientEnter") { + this.departedClientIds.delete(delta.info.id); this.clients.set(delta.info.id, delta.info); return; } if (delta.type === "clientLeave") { + this.departedClientIds.add(delta.id); this.clients.delete(delta.id); return; } if (delta.type === "clientUpdated") { + if (this.departedClientIds.has(delta.info.id)) return; const current = this.clients.get(delta.info.id); this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info); return; diff --git a/src/server/identity-lease.test.ts b/src/server/identity-lease.test.ts new file mode 100644 index 0000000..a66ee6c --- /dev/null +++ b/src/server/identity-lease.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { IdentityLeaseStore } from "./identity-lease.js"; + +test("an identity lease rejects another session until its owner disconnects", () => { + const leases = new IdentityLeaseStore(); + const key = "voice.example.com:9987|identity-1"; + assert.equal(leases.acquire(key, "session-a"), true); + assert.equal(leases.acquire(key, "session-a"), true); + assert.equal(leases.acquire(key, "session-b"), false); + leases.release(key, "session-b"); + assert.equal(leases.acquire(key, "session-b"), false); + leases.release(key, "session-a"); + assert.equal(leases.acquire(key, "session-b"), true); + leases.release(key, "session-a"); + assert.equal(leases.acquire(key, "session-c"), false); +}); + +test("distinct target or identity keys can be leased independently", () => { + const leases = new IdentityLeaseStore(); + assert.equal(leases.acquire("one.example.com|identity-1", "a"), true); + assert.equal(leases.acquire("two.example.com|identity-1", "b"), true); + assert.equal(leases.acquire("one.example.com|identity-2", "c"), true); +}); diff --git a/src/server/join-ticket.test.ts b/src/server/join-ticket.test.ts new file mode 100644 index 0000000..a765263 --- /dev/null +++ b/src/server/join-ticket.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js"; + +const payload: JoinTicketPayload = { + target: { host: "voice.example.com", port: 9987 }, + serverPassword: "test-password", + nickname: "Visitor", + channel: "Lobby", + identity: "test-identity", + rememberIdentity: true, + accelerated: true, + accelerationRelayId: "relay-1", +}; + +test("join tickets preserve connection options and can only be consumed once", () => { + const tickets = new JoinTicketStore(); + const token = tickets.create(payload, 1_000); + assert.deepEqual(tickets.consume(token, 1_001), payload); + assert.equal(tickets.consume(token, 1_002), null); + assert.equal(tickets.consume("unknown-ticket", 1_002), null); +}); + +test("join tickets expire at their deadline even if no new ticket was created", () => { + const tickets = new JoinTicketStore(100); + const valid = tickets.create(payload, 1_000); + const expired = tickets.create(payload, 1_000); + assert.deepEqual(tickets.consume(valid, 1_099), payload); + assert.equal(tickets.consume(expired, 1_100), null); + assert.equal(tickets.consume(expired, 1_101), null); +}); + +test("ticket capacity evicts the oldest request while keeping newer joins usable", () => { + const tickets = new JoinTicketStore(100, 2); + const oldest = tickets.create(payload, 0); + const second = tickets.create({ ...payload, nickname: "Second" }, 1); + const newest = tickets.create({ ...payload, nickname: "Newest" }, 2); + assert.equal(tickets.consume(oldest, 3), null); + assert.equal(tickets.consume(second, 3)?.nickname, "Second"); + assert.equal(tickets.consume(newest, 3)?.nickname, "Newest"); +}); + +test("expired tickets do not evict a still-valid join when capacity is reclaimed", () => { + const tickets = new JoinTicketStore(100, 2); + const expired = tickets.create(payload, 0); + const live = tickets.create(payload, 90); + const latest = tickets.create(payload, 100); + assert.equal(tickets.consume(expired, 100), null); + assert.deepEqual(tickets.consume(live, 100), payload); + assert.deepEqual(tickets.consume(latest, 100), payload); +}); diff --git a/src/server/reconnect-policy.test.ts b/src/server/reconnect-policy.test.ts new file mode 100644 index 0000000..ee03b2f --- /dev/null +++ b/src/server/reconnect-policy.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { WebSpeakError } from "../errors.js"; +import { isRecoverable, reconnectDelayMs, reconnectWindowOpen, RECONNECT_WINDOW_MS } from "./reconnect-policy.js"; + +test("reconnect backoff has bounded jitter and stops growing for repeated failures", () => { + assert.equal(reconnectDelayMs(1, () => 0), 900); + assert.equal(reconnectDelayMs(1, () => 1), 1_100); + assert.equal(reconnectDelayMs(2, () => 0.5), 2_000); + assert.equal(reconnectDelayMs(100, () => 0), 27_000); + assert.equal(reconnectDelayMs(100, () => 1), 33_000); + assert.equal(reconnectDelayMs(0, () => 0.5), 1_000); +}); + +test("reconnect attempts stop exactly at the recovery window deadline", () => { + const interruptedAt = 1_000; + assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt), true); + assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS - 1), true); + assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS), false); + assert.equal(reconnectWindowOpen(interruptedAt, interruptedAt + RECONNECT_WINDOW_MS + 1), false); +}); + +test("retry policy respects terminal errors while allowing transient and unclassified disconnects", () => { + assert.equal(isRecoverable(new WebSpeakError("timeout", "timed out", true)), true); + assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "wrong password", false)), false); + assert.equal(isRecoverable(new WebSpeakError("banned", "banned", false)), false); + assert.equal(isRecoverable(null), true); +}); diff --git a/src/server/session-manager.test.ts b/src/server/session-manager.test.ts new file mode 100644 index 0000000..62956e3 --- /dev/null +++ b/src/server/session-manager.test.ts @@ -0,0 +1,95 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { ConnectionStateMachine, SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js"; + +function connect(session: ManagedSession | ConnectionStateMachine): void { + session.transition("connecting"); + session.transition("authenticating"); + session.transition("syncing"); + session.transition("connected"); +} + +test("a connected session can reconnect successfully and later fail cleanly", () => { + const state = new ConnectionStateMachine(); + assert.throws(() => state.transition("connected"), /Illegal connection state transition/); + assert.equal(state.state, "idle"); + connect(state); + state.transition("interrupted"); + state.transition("reconnecting"); + connect(state); + assert.equal(state.state, "connected"); + state.transition("interrupted"); + state.transition("reconnecting"); + state.transition("failed"); + state.transition("disconnecting"); + state.transition("idle"); + assert.equal(state.state, "idle"); +}); + +test("concurrent teardown requests run cleanup once and retain admission until it finishes", async () => { + const manager = new SessionManager(); + const reasons: SessionTeardownReason[] = []; + let release!: () => void; + const pending = new Promise((resolve) => { release = resolve; }); + const session = manager.admit("browser", async (reason) => { reasons.push(reason); await pending; }); + assert.ok(session); + connect(session); + + const first = manager.teardown("browser", "websocket-close"); + const second = manager.teardown("browser", "admin-terminated"); + assert.deepEqual(reasons, ["websocket-close"]); + assert.equal(session.state, "disconnecting"); + assert.equal(manager.activeCount, 1); + release(); + await Promise.all([first, second]); + await manager.teardown("browser", "websocket-error"); + assert.equal(session.state, "idle"); + assert.equal(manager.activeCount, 0); + assert.equal(manager.get("browser"), undefined); + assert.deepEqual(reasons, ["websocket-close"]); +}); + +test("cleanup errors still release the session and allow a new admission", async () => { + const manager = new SessionManager(); + const session = manager.admit("browser", async () => { throw new Error("socket already closed"); }); + assert.ok(session); + session.transition("connecting"); + await manager.teardown("browser", "teamSpeak-connect-failed"); + assert.equal(session.state, "idle"); + assert.equal(manager.activeCount, 0); + assert.ok(manager.admit("browser", async () => {})); + await manager.shutdown(); +}); + +test("admission enforces capacity and reuses slots only after teardown", async () => { + const manager = new SessionManager(); + for (let index = 0; index < manager.maxSessions; index++) { + assert.ok(manager.admit(String(index), async () => {})); + } + assert.equal(manager.admit("overflow", async () => {}), null); + assert.equal(manager.createdCount, manager.maxSessions); + await manager.teardown("0", "client-disconnect"); + assert.ok(manager.admit("replacement", async () => {})); + assert.equal(manager.createdCount, manager.maxSessions + 1); + assert.equal(manager.peakCount, manager.maxSessions); + await manager.shutdown(); + assert.equal(manager.activeCount, 0); +}); + +test("shutdown stops admission immediately and waits for every cleanup even when one fails", async () => { + const manager = new SessionManager(); + const reasons: SessionTeardownReason[] = []; + let release!: () => void; + const pending = new Promise((resolve) => { release = resolve; }); + manager.admit("slow", async (reason) => { reasons.push(reason); await pending; }); + manager.admit("failed", async (reason) => { reasons.push(reason); throw new Error("closed"); }); + const shutdown = manager.shutdown(); + assert.equal(manager.isAccepting, false); + assert.equal(manager.admit("late", async () => {}), null); + assert.deepEqual(reasons, ["gateway-shutdown", "gateway-shutdown"]); + release(); + await shutdown; + await manager.shutdown(); + assert.equal(manager.activeCount, 0); + assert.equal(reasons.length, 2); +});