mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 20:12:52 +08:00
M000: normalize configuration and TeamSpeak adapter
This commit is contained in:
1 parent
8d9b8d5627
commit
960be106bb
18 files changed
+587
-161
No files matched your search
+45
-36
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** The HTTP port is part of the WebSpeak deployment contract. */
|
||||
export const APP_PORT = 3040;
|
||||
|
||||
/** Hard safety ceiling for independently connected browser sessions. */
|
||||
export const MAX_ACTIVE_SESSIONS = 100;
|
||||
|
||||
export function canAcceptSession(activeSessionCount: number): boolean {
|
||||
return Number.isInteger(activeSessionCount) && activeSessionCount >= 0 && activeSessionCount < MAX_ACTIVE_SESSIONS;
|
||||
}
|
||||
@@ -0,0 +1,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 };
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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),
|
||||
|
||||
Reference in new issue
Block a user