M000: normalize configuration and TeamSpeak adapter

This commit is contained in:
illusia committed 2026-08-31 20:14:08 +08:00
1 parent 8d9b8d5627
commit 960be106bb
18 files changed
+587 -161

No files matched your search

+24 -22
View File
@@ -74,27 +74,21 @@ Copy `config.example.json` to `config.json` in the project root, then edit the v
```json
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
"tsServerPassword": ""
}
```
| Field | Description |
| --- | --- |
| `port` | Local HTTP/HTTPS port for WebSpeak. |
| `tsHost` | TeamSpeak server address. Use `127.0.0.1` when it runs on the same host. |
| `tsPort` | TeamSpeak voice port, commonly `9987`. |
| `tsServerPassword` | TeamSpeak server password, if required. |
| `tsServerProtocol` | `"ts3"` or `"ts6"`; omit it to use protocol detection. |
| `maxClients` | Maximum number of simultaneous browser sessions. |
| `trustProxy` | Set to `true` only when a trusted reverse proxy is in front of WebSpeak. |
The join page includes a **Setup guide** button. It generates a copyable `config.json` preview from the server address, voice port, protocol, WebSpeak port, and optional password entered in the page. A browser cannot write files on the server, so save the copied JSON as `config.json` in the project root and restart WebSpeak after changing it.
WebSpeak listens on the fixed internal port `3040` and accepts at most `100` active browser sessions; change the external port in Docker or the reverse proxy. TS3/TS6 is detected automatically by the TeamSpeak adapter. The join page includes a **Setup guide** button and generates a copyable `config.json` preview from the TeamSpeak address, voice port, and optional password. 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.
When an older `config.json` contains `port`, `tsServerProtocol`, `maxClients`, or `trustProxy`, WebSpeak reads the TeamSpeak target and password, ignores those implementation controls, and rewrites the file in the normalized three-field shape above.
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.
@@ -182,7 +176,7 @@ server {
}
```
Set `trustProxy` to `true` only after verifying that the proxy is trusted and cannot be bypassed.
WebSpeak does not use forwarded headers as an authentication or authorization boundary. Keep the gateway behind a trusted reverse proxy and configure the proxy to forward WebSocket upgrades.
### Troubleshooting
@@ -190,17 +184,20 @@ Set `trustProxy` to `true` only after verifying that the proxy is trusted and ca
| --- | --- |
| 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. |
| Channel/member list is empty | Check the TeamSpeak address and voice port. 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. |
| `EADDRINUSE` | Stop the process already listening on fixed port `3040`, or change the external proxy/container port. |
### Project layout
```text
src/
domain/teamspeak-target.ts Normalized host[:port] parsing and endpoint keys
server/teamspeak-adapter.ts TS3/TS6 negotiation boundary and protocol cache
errors.ts Normalized connection error model
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
@@ -223,6 +220,9 @@ npm --prefix web run build
# Type-check backend
npm run build
# Run M000 unit tests
npm test
```
Contributions and issue reports are welcome. Please do not include `config.json`, certificates, private keys, or server logs in issues or pull requests.
@@ -276,13 +276,9 @@ npm run build
```json
{
"port": 3040,
"tsHost": "127.0.0.1",
"tsPort": 9987,
"tsServerPassword": "",
"tsServerProtocol": "ts6",
"maxClients": 20,
"trustProxy": false
"tsServerPassword": ""
}
```
@@ -290,8 +286,11 @@ npm run build
- `tsHost`:TeamSpeak 地址;同机部署使用 `127.0.0.1`。
- `tsPort`:语音端口,通常为 `9987`。
- `tsServerProtocol`:填写 `"ts3"` 或 `"ts6"`,也可以省略并使用自动检测。
加入页面提供“配置引导”按钮,可以根据页面中填写的服务器地址、语音端口、协议、WebSpeak 端口和可选密码生成可复制的 `config.json` 预览。浏览器不能直接写入服务器文件,请将复制的内容保存到项目根目录的 `config.json`,再重启 WebSpeak。
- `tsServerPassword`:TeamSpeak 服务器密码,没有密码时留空。
WebSpeak 内部监听端口固定为 `3040`,最多接受 `100` 个活动网页 Session;外部端口请在 Docker 或反向代理层修改。TS3/TS6 由 TeamSpeak Adapter 自动检测,不需要在配置或网页中选择协议。加入页面提供“配置引导”按钮,可以根据页面中填写的服务器地址、语音端口和可选密码生成可复制的 `config.json` 预览。浏览器不能直接写入服务器文件,请将复制的内容保存到项目根目录的 `config.json`,再重启 WebSpeak。
如果旧版 `config.json` 中仍有 `port`、`tsServerProtocol`、`maxClients` 或 `trustProxy`,WebSpeak 会读取其中的 TeamSpeak 地址和密码,忽略这些实现细节,并在启动时将文件改写为上面的三项配置。
WebSpeak 使用每个网页用户自己的普通 TeamSpeak 客户端连接获取语音和目录数据,不连接 WebQuery/SSH Query,也不启动维护客户端。TeamSpeak 会在普通客户端登录握手阶段下发频道和成员快照;随后 WebSpeak 会像原生客户端一样订阅完整频道树,并实时应用频道/成员通知。成员切换到其他频道时会被移动到目标频道,不再被误判为退出服务器。不会主动调用受权限限制的 `channellist` 或 `clientlist` 命令,显示内容与该 TeamSpeak 身份实际可见的内容一致。
进入后的成员/频道树位于页面左侧。首次进入时,WebSpeak 会使用 TeamSpeak 欢迎握手中返回的当前频道 ID,把自己放入实际所在的默认频道;不会把已进入默认频道的用户显示到错误的占位分组。“正在语音中”旁边不再使用没有功能的禁麦图标;它只是状态提示,真正发言时头像边框会实时变绿,停止发声后自动恢复。
@@ -314,13 +313,13 @@ https://你的域名或IP:3040/
### HTTPS 与反向代理
如果项目根目录存在 `certs/cert.pem` 和 `certs/key.pem`,WebSpeak 会直接提供 HTTPS。公网部署建议使用 Let's Encrypt,或让 Nginx 终止 HTTPS 后反向代理到 `http://127.0.0.1:3040`,并转发 WebSocket 升级请求。使用可信反向代理时,将 `trustProxy` 设置为 `true`。
如果项目根目录存在 `certs/cert.pem` 和 `certs/key.pem`,WebSpeak 会直接提供 HTTPS。公网部署建议使用 Let's Encrypt,或让 Nginx 终止 HTTPS 后反向代理到 `http://127.0.0.1:3040`,并转发 WebSocket 升级请求。WebSpeak 不使用转发头作为认证或授权边界,请确保网关只位于可信反向代理之后。
### 常见问题
- **无法使用麦克风**:确认使用 HTTPS、已经允许浏览器访问麦克风,并在“音频设置”中检查设备。
- **只能看到默认麦克风**:授权前浏览器会隐藏设备名称;授权后刷新页面,或重新连接一次。
- **频道/成员列表为空**:检查网页中的 TeamSpeak 地址、语音端口和协议设置;目录来自普通客户端登录握手数据。
- **频道/成员列表为空**:检查网页中的 TeamSpeak 地址和语音端口;协议会自动检测,目录来自普通客户端登录握手数据。
- **频道/成员目录仍在加载**:保持页面连接,等待登录握手快照到达;之后成员和频道变化会自动实时推送到页面。
- **首次进入看不到自己**:保持连接直到 TeamSpeak 欢迎握手完成;WebSpeak 会根据当前频道 ID 将自己归入默认频道,并在频道成员变化时实时更新。
- **没有声音**:使用较新的 Chrome/Edge,通过 HTTPS 访问,并检查浏览器输出音量。
@@ -337,6 +336,9 @@ npm --prefix web run build
# 后端 TypeScript 构建
npm run build
# 运行 M000 单元测试
npm test
```
请不要在 Issue 或 Pull Request 中提交 `config.json`、API 密钥、证书、私钥或服务器日志。
+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": ""
}
+1
View File
@@ -8,6 +8,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "tsx --test \"test/**/*.test.ts\"",
"start": "node dist/index.js",
"postinstall": "node scripts/patch-teamspeak-sdk.mjs",
"web:dev": "cd web && npx vite --host",
+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 bootstrap file. */
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
* bootstrap 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 M000 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;
}
+89
View File
@@ -0,0 +1,89 @@
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. */
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");
if (input.startsWith("[")) {
const closingBracket = input.indexOf("]");
if (closingBracket < 0) throw new InvalidTeamSpeakTargetError("IPv6 addresses must close with ]");
const host = input.slice(1, closingBracket);
const suffix = input.slice(closingBracket + 1);
if (suffix && !suffix.startsWith(":")) {
throw new InvalidTeamSpeakTargetError("Invalid port separator after IPv6 address");
}
return createTarget(host, suffix ? suffix.slice(1) : fallbackPort);
}
const colon = input.indexOf(":");
if (colon < 0) return createTarget(input, fallbackPort);
if (input.indexOf(":", colon + 1) >= 0) {
throw new InvalidTeamSpeakTargetError("IPv6 addresses must use bracket notation");
}
return createTarget(input.slice(0, colon), input.slice(colon + 1));
}
/** Parse the legacy split host/port fields while accepting a bracketed IPv6 host. */
export function parseTeamSpeakTargetParts(
hostValue: string,
portValue?: string | number,
fallbackPort = DEFAULT_TEAM_SPEAK_PORT,
): TeamSpeakTarget {
const host = hostValue.trim();
if (!host) throw new InvalidTeamSpeakTargetError("TeamSpeak server address is required");
if (portValue !== undefined && String(portValue).trim() !== "") {
const hostOnly = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
if (hostOnly.includes(":")) return createTarget(hostOnly, portValue);
if (host.includes(":")) {
throw new InvalidTeamSpeakTargetError("Use one TeamSpeak address field when specifying a port");
}
return createTarget(hostOnly, portValue);
}
return parseTeamSpeakTarget(host, fallbackPort);
}
export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
return target.host.includes(":") ? `[${target.host}]:${target.port}` : `${target.host}:${target.port}`;
}
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
return formatTeamSpeakTarget(target).toLocaleLowerCase();
}
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
const host = hostValue.trim().toLocaleLowerCase();
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
if (host.includes(":")) {
// A raw IPv6 host is valid only when it came from bracket notation.
if (!host.split(":").every((part) => /^[0-9a-f]*$/i.test(part))) {
throw new InvalidTeamSpeakTargetError("Invalid IPv6 server address");
}
} else if (!/^[a-z0-9._-]+$/i.test(host)) {
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
}
const portText = String(portValue).trim();
if (!/^\d+$/.test(portText)) throw new InvalidTeamSpeakTargetError("TeamSpeak port must be a number");
const port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new InvalidTeamSpeakTargetError("TeamSpeak port must be between 1 and 65535");
}
return { host, port };
}
+45
View File
@@ -0,0 +1,45 @@
export type WebSpeakErrorCode =
| "invalid_target"
| "unreachable"
| "timeout"
| "authentication_failed"
| "protocol_negotiation_failed"
| "server_full"
| "unknown";
export class WebSpeakError extends Error {
readonly code: WebSpeakErrorCode;
readonly retryable: boolean;
readonly cause?: unknown;
constructor(code: WebSpeakErrorCode, message: string, retryable: boolean, cause?: unknown) {
super(message);
this.name = "WebSpeakError";
this.code = code;
this.retryable = retryable;
this.cause = cause;
}
}
export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
if (error instanceof WebSpeakError) return error;
const candidate = error as { code?: unknown; message?: unknown } | null;
const code = typeof candidate?.code === "string" ? candidate.code : "";
const message = typeof candidate?.message === "string" ? candidate.message : String(error);
const text = `${code} ${message}`.toLocaleLowerCase();
if (/password|authenticate|authentication|not authorized|invalid.*(credential|password)/.test(text)) {
return new WebSpeakError("authentication_failed", "TeamSpeak authentication failed", false, error);
}
if (/timeout|timed out|ack timeout|idle timeout/.test(text)) {
return new WebSpeakError("timeout", "TeamSpeak connection timed out", true, error);
}
if (/econnrefused|enotfound|ehostunreach|enetunreach|network|socket|dns/.test(text)) {
return new WebSpeakError("unreachable", "TeamSpeak server is unreachable", true, error);
}
if (/protocol|handshake|crypto|init1/.test(text)) {
return new WebSpeakError("protocol_negotiation_failed", "TeamSpeak protocol negotiation failed", true, error);
}
return new WebSpeakError("unknown", "TeamSpeak connection failed", false, error);
}
+4 -6
View File
@@ -4,6 +4,8 @@ import { fileURLToPath } from "node:url";
import { loadConfig, saveConfig } from "./config.js";
import { createLogger } from "./logger.js";
import { createWebServer } from "./server/server.js";
import { APP_PORT } from "./constants.js";
import { parseTeamSpeakTargetParts } from "./domain/teamspeak-target.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -24,16 +26,12 @@ async function main() {
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
const webServer = createWebServer({
port: config.port,
trustProxy: config.trustProxy,
port: APP_PORT,
staticDir: STATIC_DIR,
certDir: hasCert ? CERT_DIR : undefined,
voiceBridgeOptions: {
tsHost: config.tsHost,
tsPort: config.tsPort,
defaultTarget: parseTeamSpeakTargetParts(config.tsHost, config.tsPort),
tsServerPassword: config.tsServerPassword,
tsServerProtocol: config.tsServerProtocol,
maxClients: config.maxClients,
},
logger,
});
+4 -8
View File
@@ -6,12 +6,12 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
import type { Logger } from "../logger.js";
import { formatTeamSpeakTarget } from "../domain/teamspeak-target.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface WebServerOptions {
port: number;
trustProxy: boolean;
staticDir?: string;
certDir?: string; // path to cert.pem + key.pem for HTTPS
voiceBridgeOptions: VoiceBridgeOptions;
@@ -38,10 +38,6 @@ 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) => {
@@ -52,9 +48,9 @@ export function createWebServer(options: WebServerOptions): WebServer {
// 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,
tsHost: options.voiceBridgeOptions.defaultTarget.host,
tsPort: options.voiceBridgeOptions.defaultTarget.port,
target: formatTeamSpeakTarget(options.voiceBridgeOptions.defaultTarget),
});
});
+152
View File
@@ -0,0 +1,152 @@
import {
Client as TeamSpeakClient,
generateIdentity,
type ClientOptions,
type Identity,
} from "@honeybbq/teamspeak-client";
import type { Logger } from "../logger.js";
import { normalizeTeamSpeakError } from "../errors.js";
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
export type TeamSpeakProtocol = "ts3" | "ts6";
interface CacheEntry {
protocol: TeamSpeakProtocol;
lastSuccessfulAt: number;
}
/** Process-local optimization; protocol is never persisted as user config. */
export class EndpointProtocolCache {
private readonly entries = new Map<string, CacheEntry>();
constructor(
private readonly ttlMs = 30 * 60 * 1000,
private readonly maxEntries = 128,
) {}
get(target: TeamSpeakTarget, now = Date.now()): TeamSpeakProtocol | undefined {
const key = teamSpeakTargetKey(target);
const entry = this.entries.get(key);
if (!entry) return undefined;
if (now - entry.lastSuccessfulAt > this.ttlMs) {
this.entries.delete(key);
return undefined;
}
return entry.protocol;
}
set(target: TeamSpeakTarget, protocol: TeamSpeakProtocol, now = Date.now()): void {
const key = teamSpeakTargetKey(target);
this.entries.delete(key);
this.entries.set(key, { protocol, lastSuccessfulAt: now });
while (this.entries.size > this.maxEntries) {
const oldest = this.entries.keys().next().value;
if (oldest === undefined) break;
this.entries.delete(oldest);
}
}
clear(): void {
this.entries.clear();
}
get size(): number {
return this.entries.size;
}
}
export const endpointProtocolCache = new EndpointProtocolCache();
export interface TeamSpeakAdapterOptions {
target: TeamSpeakTarget;
nickname: string;
identity?: Identity;
serverPassword?: string;
defaultChannel?: string;
channelPassword?: string;
}
/**
* The SDK performs the wire-level TS3/TS6 negotiation itself. This adapter is
* the only application boundary that knows about that SDK and records the
* successfully observed server generation for later connections.
*/
export class TeamSpeakAdapter {
readonly client: TeamSpeakClient;
private detectedProtocol: TeamSpeakProtocol | null = null;
constructor(
options: TeamSpeakAdapterOptions,
private readonly logger: Logger,
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
) {
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(
options.identity ?? generateIdentity(8),
formatTeamSpeakTarget(options.target),
options.nickname,
clientOptions,
);
this.target = options.target;
}
private readonly target: TeamSpeakTarget;
async connect(): Promise<void> {
const cachedProtocol = this.protocolCache.get(this.target);
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
try {
await this.client.connect();
await this.client.waitConnected();
} catch (error: unknown) {
throw normalizeTeamSpeakError(error);
}
const observedProtocol = await this.detectProtocol();
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
}
get protocol(): TeamSpeakProtocol | null {
return this.detectedProtocol;
}
async disconnect(): Promise<void> {
try {
await this.client.disconnect();
} catch {
// Teardown must remain safe when the transport has already gone away.
}
}
private async detectProtocol(): Promise<TeamSpeakProtocol | null> {
try {
const rows = await this.client.execCommandWithResponse("version", 3000);
const versionText = rows
.flatMap((row) => Object.values(row))
.filter((value): value is string => typeof value === "string")
.join(" ");
return detectTeamSpeakProtocol(versionText);
} catch {
// Version discovery is an optimization; connection success is enough to proceed.
return null;
}
}
}
export function detectTeamSpeakProtocol(versionText: string): TeamSpeakProtocol | null {
const text = versionText.trim().toLocaleLowerCase();
if (/teamspeak\s*6|(?:^|\D)6\.\d+/.test(text)) return "ts6";
if (/teamspeak\s*3|(?:^|\D)3\.\d+/.test(text)) return "ts3";
return null;
}
+19 -34
View File
@@ -1,21 +1,19 @@
import { EventEmitter } from "node:events";
import {
Client as TS3FullClient,
generateIdentity,
clientMove as tsClientMove,
type Identity,
type VoiceData,
type ChannelInfo,
type ClientInfo,
} from "@honeybbq/teamspeak-client";
import type { Logger } from "../logger.js";
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export interface TSClientOptions {
host: string;
port: number;
target: TeamSpeakTarget;
nickname: string;
serverPassword?: string;
serverProtocol?: "ts3" | "ts6";
defaultChannel?: string;
channelPassword?: string;
}
@@ -33,36 +31,25 @@ export interface TSDirectorySnapshot {
export class TSClient extends EventEmitter {
private client: TS3FullClient | null = null;
private identity: Identity;
private adapter: TeamSpeakAdapter | null = null;
private logger: Logger;
private clientId = 0;
private connected = false;
constructor(
private options: TSClientOptions,
logger: Logger,
) {
constructor(private options: TSClientOptions, logger: Logger) {
super();
this.logger = logger.child({ nickname: options.nickname });
this.identity = generateIdentity(8);
}
async connect(): Promise<void> {
const addr = `${this.options.host}:${this.options.port}`;
this.logger.info({ addr }, "Connecting to TeamSpeak");
this.client = new TS3FullClient(this.identity, addr, this.options.nickname, {
this.adapter = new TeamSpeakAdapter({
target: this.options.target,
nickname: 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),
},
});
channelPassword: this.options.channelPassword,
}, this.logger);
this.client = this.adapter.client;
this.client.on("voiceData", (data: VoiceData) => {
this.emit("voiceData", {
@@ -110,8 +97,7 @@ export class TSClient extends EventEmitter {
this.emit("clientMoved", info);
});
await this.client.connect();
await this.client.waitConnected();
await this.adapter.connect();
this.clientId = this.client.clientID();
try {
@@ -164,6 +150,10 @@ export class TSClient extends EventEmitter {
return this.client?.clientID() ?? this.clientId;
}
getProtocol(): TeamSpeakProtocol | null {
return this.adapter?.protocol ?? null;
}
getChannelId(): bigint {
if (!this.client) return 0n;
const sdkClient = this.client as unknown as { channelID?: () => bigint };
@@ -176,14 +166,9 @@ export class TSClient extends EventEmitter {
async disconnect(): Promise<void> {
this.connected = false;
if (this.client) {
try {
await this.client.disconnect();
} catch {
// ignore
}
this.client = null;
}
if (this.adapter) await this.adapter.disconnect();
this.adapter = null;
this.client = null;
this.clientId = 0;
}
}
+31 -30
View File
@@ -4,6 +4,14 @@ import type { Server } from "node:http";
import { createRequire } from "node:module";
import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js";
import type { Logger as LoggerType } from "../logger.js";
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js";
import { normalizeTeamSpeakError } from "../errors.js";
import {
formatTeamSpeakTarget,
parseTeamSpeakTarget,
parseTeamSpeakTargetParts,
type TeamSpeakTarget,
} from "../domain/teamspeak-target.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
@@ -11,11 +19,8 @@ const { OpusEncoder } = require("@discordjs/opus") as {
};
export interface VoiceBridgeOptions {
tsHost: string;
tsPort: number;
defaultTarget: TeamSpeakTarget;
tsServerPassword: string;
tsServerProtocol?: "ts3" | "ts6";
maxClients: number;
}
interface ChannelMember {
@@ -28,8 +33,7 @@ interface WebClientEntry {
tsClient: TSClient;
ws: WebSocket;
nickname: string;
tsHost: string;
tsPort: number;
target: TeamSpeakTarget;
channelTree: unknown[];
members: Map<number, ChannelMember>;
opusEncoder: { encode(pcm: Buffer): Buffer };
@@ -56,33 +60,36 @@ export class VoiceBridge {
const url = new URL(req.url ?? "/", `https://${req.headers.host ?? "localhost"}`);
const channelName = url.searchParams.get("channel") ?? undefined;
const nickname = (url.searchParams.get("nickname") ?? "WebUser").trim().slice(0, 30) || "WebUser";
const tsHost = normalizeHost(url.searchParams.get("tsHost") ?? this.options.tsHost);
const parsedPort = Number.parseInt(url.searchParams.get("tsPort") ?? String(this.options.tsPort), 10);
const tsPort = Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535
? parsedPort
: this.options.tsPort;
if (!tsHost) {
this.logger.warn({ nickname }, "Invalid TeamSpeak host");
ws.close(4002, "Invalid TeamSpeak host");
let target: TeamSpeakTarget;
try {
const rawTarget = url.searchParams.get("target");
target = rawTarget?.trim()
? parseTeamSpeakTarget(rawTarget)
: parseTeamSpeakTargetParts(
url.searchParams.get("tsHost") ?? this.options.defaultTarget.host,
url.searchParams.get("tsPort") ?? undefined,
this.options.defaultTarget.port,
);
} catch (error: unknown) {
this.logger.warn({ nickname, err: error instanceof Error ? error.message : String(error) }, "Invalid TeamSpeak target");
ws.close(4002, "Invalid TeamSpeak target");
return;
}
if (this.clients.size >= this.options.maxClients) {
this.logger.warn({ max: this.options.maxClients }, "Max clients reached");
if (!canAcceptSession(this.clients.size)) {
this.logger.warn({ max: MAX_ACTIVE_SESSIONS }, "Max clients reached");
ws.close(4004, "Server full");
return;
}
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
this.logger.info({ entryId, nickname, channel: channelName, tsHost, tsPort }, "WebClient connecting");
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting");
const tsClient = new TSClient({
host: tsHost,
port: tsPort,
target,
nickname,
serverPassword: this.options.tsServerPassword,
serverProtocol: this.options.tsServerProtocol,
defaultChannel: channelName,
}, this.logger);
@@ -91,8 +98,7 @@ export class VoiceBridge {
tsClient,
ws,
nickname,
tsHost,
tsPort,
target,
channelTree: [],
members: new Map(),
opusEncoder: new OpusEncoder(48000, 1),
@@ -241,8 +247,9 @@ export class VoiceBridge {
sendInitialState();
})
.catch((error: Error) => {
this.logger.error({ err: error, entryId }, "TS connect failed");
if (ws.readyState === WebSocket.OPEN) ws.close(4003, `Connection failed: ${error.message}`);
const normalized = normalizeTeamSpeakError(error);
this.logger.error({ code: normalized.code, entryId }, "TS connect failed");
if (ws.readyState === WebSocket.OPEN) ws.close(4003, normalized.code);
else this.cleanup(entryId);
});
});
@@ -305,12 +312,6 @@ async function handleCommand(entry: WebClientEntry, command: { type: string; [ke
}
}
function normalizeHost(value: string): string | null {
const host = value.trim();
if (!host || host.length > 255 || /[\s/\\]/.test(host)) return null;
return host;
}
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { migrateConfig, saveConfig } from "../src/config.js";
describe("bootstrap config migration", () => {
it("drops deprecated runtime controls while preserving the TeamSpeak target", () => {
assert.deepEqual(migrateConfig({
port: 3999,
tsHost: "TS.Example.COM",
tsPort: "9988",
tsServerPassword: "secret",
tsServerProtocol: "ts6",
maxClients: 3,
trustProxy: true,
}), {
tsHost: "ts.example.com",
tsPort: 9988,
tsServerPassword: "secret",
});
});
it("accepts a host with an embedded port during migration", () => {
assert.deepEqual(migrateConfig({ tsHost: "[2001:db8::1]:9988" }), {
tsHost: "2001:db8::1",
tsPort: 9988,
tsServerPassword: "",
});
});
it("falls back safely for malformed legacy targets", () => {
assert.deepEqual(migrateConfig({ tsHost: "bad host", tsPort: 0 }), {
tsHost: "127.0.0.1",
tsPort: 9987,
tsServerPassword: "",
});
});
it("writes the migrated shape without deprecated runtime controls", () => {
const directory = mkdtempSync(join(tmpdir(), "webspeak-m000-config-"));
const path = join(directory, "config.json");
try {
writeFileSync(path, JSON.stringify({
port: 3999,
tsHost: "example.com",
tsPort: 9988,
tsServerProtocol: "ts3",
maxClients: 2,
trustProxy: true,
}), "utf8");
saveConfig(path, migrateConfig(JSON.parse(readFileSync(path, "utf8"))));
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), {
tsHost: "example.com",
tsPort: 9988,
tsServerPassword: "",
});
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
});
+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { normalizeTeamSpeakError } from "../src/errors.js";
describe("normalized connection errors", () => {
it("classifies authentication failures as non-retryable", () => {
const error = normalizeTeamSpeakError(new Error("invalid server password"));
assert.equal(error.code, "authentication_failed");
assert.equal(error.retryable, false);
});
it("classifies network and timeout failures", () => {
assert.equal(normalizeTeamSpeakError(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })).code, "unreachable");
assert.equal(normalizeTeamSpeakError(new Error("ack timeout")).code, "timeout");
});
});
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../src/constants.js";
describe("session safety limit", () => {
it("uses the fixed 100-session product limit", () => {
assert.equal(MAX_ACTIVE_SESSIONS, 100);
assert.equal(canAcceptSession(99), true);
assert.equal(canAcceptSession(100), false);
assert.equal(canAcceptSession(101), false);
});
});
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { EndpointProtocolCache, detectTeamSpeakProtocol } from "../src/server/teamspeak-adapter.js";
describe("TeamSpeak protocol adapter", () => {
it("detects TS3 and TS6 from the normal version response", () => {
assert.equal(detectTeamSpeakProtocol("version=3.13.7 build=12345"), "ts3");
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6 version 6.0.0"), "ts6");
assert.equal(detectTeamSpeakProtocol("unknown"), null);
});
it("remembers a successful endpoint only for its bounded TTL", () => {
const cache = new EndpointProtocolCache(1000, 2);
const target = { host: "example.com", port: 9987 };
cache.set(target, "ts6", 1000);
assert.equal(cache.get(target, 1500), "ts6");
assert.equal(cache.get(target, 2001), undefined);
});
it("evicts the oldest endpoint when bounded", () => {
const cache = new EndpointProtocolCache(60_000, 2);
cache.set({ host: "one.example", port: 9987 }, "ts3", 1);
cache.set({ host: "two.example", port: 9987 }, "ts3", 2);
cache.set({ host: "three.example", port: 9987 }, "ts6", 3);
assert.equal(cache.size, 2);
assert.equal(cache.get({ host: "one.example", port: 9987 }, 4), undefined);
});
});
+40
View File
@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
InvalidTeamSpeakTargetError,
formatTeamSpeakTarget,
parseTeamSpeakTarget,
parseTeamSpeakTargetParts,
teamSpeakTargetKey,
} from "../src/domain/teamspeak-target.js";
describe("TeamSpeak target parser", () => {
it("uses 9987 when the port is omitted", () => {
assert.deepEqual(parseTeamSpeakTarget("Example.COM"), { host: "example.com", port: 9987 });
});
it("parses a custom port", () => {
assert.deepEqual(parseTeamSpeakTarget("ts.example.com:9988"), { host: "ts.example.com", port: 9988 });
});
it("supports bracketed IPv6", () => {
const target = parseTeamSpeakTarget("[2001:DB8::1]:9987");
assert.deepEqual(target, { host: "2001:db8::1", port: 9987 });
assert.equal(formatTeamSpeakTarget(target), "[2001:db8::1]:9987");
});
it("accepts legacy split fields", () => {
assert.deepEqual(parseTeamSpeakTargetParts("[::1]", "9988"), { host: "::1", port: 9988 });
assert.deepEqual(parseTeamSpeakTargetParts("ts.example.com", undefined), { host: "ts.example.com", port: 9987 });
});
it("rejects ambiguous raw IPv6 and invalid ports", () => {
assert.throws(() => parseTeamSpeakTarget("2001:db8::1"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:0"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:65536"), InvalidTeamSpeakTargetError);
});
it("creates a stable case-insensitive cache key", () => {
assert.equal(teamSpeakTargetKey({ host: "TS.Example.COM", port: 9987 }), "ts.example.com:9987");
});
});
+4 -20
View File
@@ -171,7 +171,7 @@
<article><span>2</span><div><strong>{{ t('configStepEditTitle') }}</strong><p>{{ t('configStepEditLead') }}</p></div></article>
<article><span>3</span><div><strong>{{ t('configStepRestartTitle') }}</strong><p>{{ t('configStepRestartLead') }}</p><code>node dist/index.js</code></div></article>
</div>
<section class="config-editor"><div class="config-editor-heading"><div><span class="section-kicker">{{ t('configPreview') }}</span><strong>{{ t('configPreviewLead') }}</strong></div><button class="copy-config-button" type="button" @click="copyConfigTemplate"><Icon name="copy" :size="15" /> {{ t('copyConfig') }}</button></div><div class="config-guide-fields"><label><span>{{ t('webPort') }}</span><input v-model="guideWebPort" type="number" min="1" max="65535" /></label><label><span>{{ t('protocol') }}</span><select v-model="guideProtocol"><option value="">{{ t('autoDetect') }}</option><option value="ts3">TeamSpeak 3</option><option value="ts6">TeamSpeak 6</option></select></label><label class="config-guide-wide"><span>{{ t('serverPassword') }}</span><input v-model="guideServerPassword" type="password" :placeholder="t('optionalPassword')" /></label></div><pre>{{ configTemplate }}</pre></section>
<section class="config-editor"><div class="config-editor-heading"><div><span class="section-kicker">{{ t('configPreview') }}</span><strong>{{ t('configPreviewLead') }}</strong></div><button class="copy-config-button" type="button" @click="copyConfigTemplate"><Icon name="copy" :size="15" /> {{ t('copyConfig') }}</button></div><div class="config-guide-fields"><label class="config-guide-wide"><span>{{ t('serverPassword') }}</span><input v-model="guideServerPassword" type="password" :placeholder="t('optionalPassword')" /></label></div><pre>{{ configTemplate }}</pre></section>
<div class="config-guide-note"><Icon name="help" :size="16" /><span>{{ t('configGuideNote') }}</span></div>
</div>
<footer class="config-guide-footer"><button class="text-button" type="button" @click="configGuideOpen = false">{{ t('close') }}</button><button class="primary-button save-button" type="button" @click="copyConfigTemplate"><Icon name="copy" :size="16" /> {{ t('copyConfig') }}</button></footer>
@@ -246,8 +246,6 @@ const messageDraft = ref("");
const selectedChannelId = ref("");
const settingsOpen = ref(false);
const configGuideOpen = ref(false);
const guideWebPort = ref(location.port || "3040");
const guideProtocol = ref<"" | "ts3" | "ts6">("ts6");
const guideServerPassword = ref("");
const audioSettingsError = ref("");
const pttActive = ref(false);
@@ -310,7 +308,7 @@ const translations: Record<Language, Record<string, string>> = {
configStepCopyTitle: "复制配置模板",
configStepCopyLead: "在项目根目录执行命令,创建服务端配置文件。",
configStepEditTitle: "确认连接参数",
configStepEditLead: "在下方预览中填写 WebSpeak 端口、TeamSpeak 协议和密码;地址与语音端口取自当前连接表单。",
configStepEditLead: "在下方预览中确认 TeamSpeak 服务器地址、语音端口和密码;应用端口固定为 3040,协议会自动检测。",
configStepRestartTitle: "保存并重启服务",
configStepRestartLead: "保存 config.json 后重新启动 WebSpeak 服务,新的默认配置才会生效。",
configPreview: "配置预览",
@@ -319,9 +317,6 @@ const translations: Record<Language, Record<string, string>> = {
configGuideNote: "浏览器不能直接写入服务器文件;复制后请在运行 WebSpeak 的服务器上保存 config.json。",
configCopiedToast: "配置 JSON 已复制",
configCopyFailedToast: "复制失败,请手动复制配置内容",
webPort: "WebSpeak 端口",
protocol: "TeamSpeak 协议",
autoDetect: "自动检测",
serverPassword: "服务器密码",
optionalPassword: "没有密码可留空",
switchChannel: "切换频道",
@@ -464,7 +459,7 @@ const translations: Record<Language, Record<string, string>> = {
configStepCopyTitle: "Copy the template",
configStepCopyLead: "Run the command in the project root to create the server configuration file.",
configStepEditTitle: "Confirm connection settings",
configStepEditLead: "Set the WebSpeak port, TeamSpeak protocol, and password below; the server address and voice port come from the connection form.",
configStepEditLead: "Confirm the TeamSpeak address, voice port, and password below; WebSpeak listens on fixed port 3040 and detects the protocol automatically.",
configStepRestartTitle: "Save and restart",
configStepRestartLead: "Save config.json and restart WebSpeak for the new default settings to take effect.",
configPreview: "CONFIG PREVIEW",
@@ -473,9 +468,6 @@ const translations: Record<Language, Record<string, string>> = {
configGuideNote: "A browser cannot write files on the server. Copy this content, then save config.json on the machine running WebSpeak.",
configCopiedToast: "Config JSON copied",
configCopyFailedToast: "Copy failed. Copy the configuration manually",
webPort: "WebSpeak port",
protocol: "TeamSpeak protocol",
autoDetect: "Auto-detect",
serverPassword: "Server password",
optionalPassword: "Leave blank if not required",
switchChannel: "Switch channel",
@@ -739,17 +731,12 @@ const validServerPort = computed(() => {
});
const configTemplate = computed(() => {
const webPort = Number.parseInt(guideWebPort.value, 10);
const tsPort = Number.parseInt(serverPort.value, 10);
const config: Record<string, unknown> = {
port: Number.isInteger(webPort) && webPort > 0 && webPort <= 65535 ? webPort : 3040,
tsHost: serverHost.value.trim() || "127.0.0.1",
tsPort: Number.isInteger(tsPort) && tsPort > 0 && tsPort <= 65535 ? tsPort : 9987,
tsServerPassword: guideServerPassword.value,
maxClients: 20,
trustProxy: false,
};
if (guideProtocol.value) config.tsServerProtocol = guideProtocol.value;
return JSON.stringify(config, null, 2);
});
@@ -767,16 +754,13 @@ async function loadPublicConfig() {
try {
const response = await fetch("/api/public-config", { headers: { accept: "application/json" } });
if (!response.ok) return;
const config = await response.json() as { tsHost?: unknown; tsPort?: unknown; tsServerProtocol?: unknown };
const config = await response.json() as { tsHost?: unknown; tsPort?: unknown };
if (!query.has("tsHost") && !localStorage.getItem("webspeak:ts-host") && typeof config.tsHost === "string" && config.tsHost.trim()) {
serverHost.value = config.tsHost.trim();
}
if (!query.has("tsPort") && !localStorage.getItem("webspeak:ts-port") && Number.isInteger(config.tsPort)) {
serverPort.value = String(config.tsPort);
}
if (config.tsServerProtocol === "ts3" || config.tsServerProtocol === "ts6") {
guideProtocol.value = config.tsServerProtocol;
}
} catch {
// The sensible browser-host/9987 defaults remain usable when the API is unavailable.
} finally {