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

+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),