From 263c1ba6da10ce01d074e8b76719921e20c63d71 Mon Sep 17 00:00:00 2001 From: Dr1mH4X <102709153+Dr1mH4X@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:43:00 +0800 Subject: [PATCH 1/5] feat(open-protocol): add OpenProtocol v1 discovery and slash-command support --- package-lock.json | 37 +- package.json | 2 +- src/bot/commands.test.ts | 35 +- src/bot/commands.ts | 17 + src/bot/instance.test.ts | 112 ++++++ src/bot/instance.ts | 50 ++- src/bot/profile.test.ts | 12 +- src/ts-protocol/client-groups.test.ts | 6 +- src/ts-protocol/client-voice.test.ts | 169 +++++--- src/ts-protocol/client.ts | 225 +++++++---- src/ts-protocol/open-protocol.test.ts | 293 ++++++++++++++ src/ts-protocol/open-protocol.ts | 527 +++++++++++++++++++++++++ src/ts-protocol/text-message.test.ts | 29 +- src/ts-protocol/voice-endpoint.test.ts | 2 +- src/ts-protocol/voice-endpoint.ts | 11 +- test-visible.ts | 15 +- 16 files changed, 1359 insertions(+), 183 deletions(-) create mode 100644 src/ts-protocol/open-protocol.test.ts create mode 100644 src/ts-protocol/open-protocol.ts diff --git a/package-lock.json b/package-lock.json index ef03200..1ef2061 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "MIT", "dependencies": { "@discordjs/opus": "^0.10.0", - "@honeybbq/teamspeak-client": "^0.2.1", + "@honeybbq/teamspeak": "^1.0.0-beta.31", "@koa/router": "^15.4.0", "@sansenjian/qq-music-api": "~2.4.0", "axios": "^1.14.0", @@ -42,6 +42,9 @@ "tsx": "^4.21.0", "typescript": "^6.0.2", "vitest": "^4.1.2" + }, + "engines": { + "node": "^22.12.0 || >=24.0.0" } }, "node_modules/@derhuerst/http-basic": { @@ -575,16 +578,24 @@ "integrity": "sha512-Waj1cwPXJDucOib4a3bAISsKJVb15MKi9IvmTI/7ssVEm6sywXGjVJDhl6/umt1pK1ZS7PacXU3A1PmFKHEZ2w==", "license": "BSD-3-Clause" }, - "node_modules/@honeybbq/teamspeak-client": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz", - "integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==", + "node_modules/@honeybbq/teamspeak": { + "version": "1.0.0-beta.31", + "resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.31.tgz", + "integrity": "sha512-rOTnUVJdSmBruIA0UGLaUbat6iRCB64Ztuj7mCtyPif7vWnXzUA1FypjNWGorFLOrACgzEYCw+nfy2VQW8GudA==", "license": "MIT", "dependencies": { "@noble/curves": "^2.0.1" }, "engines": { - "node": ">=20.19" + "node": ">=22.12" + }, + "peerDependencies": { + "ssh2": "^1.17.0" + }, + "peerDependenciesMeta": { + "ssh2": { + "optional": true + } } }, "node_modules/@jridgewell/sourcemap-codec": { @@ -637,12 +648,12 @@ } }, "node_modules/@noble/curves": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.0.1.tgz", - "integrity": "sha512-vs1Az2OOTBiP4q0pwjW5aF0xp9n4MxVrmkFBxc6EKZc6ddYx5gaZiAsZoq0uRRXWbi3AT/sBqn05eRPtn1JCPw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", "license": "MIT", "dependencies": { - "@noble/hashes": "2.0.1" + "@noble/hashes": "2.4.0" }, "engines": { "node": ">= 20.19.0" @@ -652,9 +663,9 @@ } }, "node_modules/@noble/hashes": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", - "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", "license": "MIT", "engines": { "node": ">= 20.19.0" diff --git a/package.json b/package.json index 0c52047..ccc4cff 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "license": "MIT", "dependencies": { "@discordjs/opus": "^0.10.0", - "@honeybbq/teamspeak-client": "^0.2.1", + "@honeybbq/teamspeak": "^1.0.0-beta.31", "@koa/router": "^15.4.0", "@sansenjian/qq-music-api": "~2.4.0", "axios": "^1.14.0", diff --git a/src/bot/commands.test.ts b/src/bot/commands.test.ts index 8a6fb41..729bdf8 100644 --- a/src/bot/commands.test.ts +++ b/src/bot/commands.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from "vitest"; -import { parseCommand, canRunCommand, isAdminCommand } from "./commands.js"; +import { + parseCommand, + parseCommandWithFallback, + canRunCommand, + isAdminCommand, +} from "./commands.js"; describe("Command Parser", () => { it("parses simple command", () => { @@ -93,3 +98,31 @@ describe("canRunCommand", () => { expect(canRunCommand("clear", [], [6])).toBe(false); }); }); + +describe("parseCommandWithFallback", () => { + it("accepts both the configured primary prefix and slash fallback", () => { + expect(parseCommandWithFallback("!play 晴天", "!")).toEqual({ + name: "play", + args: "晴天", + rawArgs: ["晴天"], + flags: new Set(), + }); + expect(parseCommandWithFallback("/play 晴天", "!")).toEqual({ + name: "play", + args: "晴天", + rawArgs: ["晴天"], + flags: new Set(), + }); + }); + + it("applies aliases on slash fallback and ignores bare slash", () => { + expect(parseCommandWithFallback("/p 稻香", "!", { p: "play" })).toEqual({ + name: "play", + args: "稻香", + rawArgs: ["稻香"], + flags: new Set(), + }); + expect(parseCommandWithFallback("/", "!")).toBeNull(); + expect(parseCommandWithFallback("plain chat", "!")).toBeNull(); + }); +}); diff --git a/src/bot/commands.ts b/src/bot/commands.ts index 41e2209..7558432 100644 --- a/src/bot/commands.ts +++ b/src/bot/commands.ts @@ -55,6 +55,23 @@ export function parseCommand( }; } +export function parseCommandWithFallback( + message: string, + primaryPrefix: string, + aliases: Record = {}, + fallbackPrefixes: readonly string[] = ["/"], +): ParsedCommand | null { + const direct = parseCommand(message, primaryPrefix, aliases); + if (direct) return direct; + + for (const fallback of fallbackPrefixes) { + if (!fallback || fallback === primaryPrefix) continue; + const parsed = parseCommand(message, fallback, aliases); + if (parsed) return parsed; + } + return null; +} + export function isAdminCommand(commandName: string): boolean { return ADMIN_COMMANDS.has(commandName); } diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 685a1e7..e0752b5 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1948,3 +1948,115 @@ describe("BotInstance trackEnd — stale playback sessions", () => { expect(ctx.advances).toEqual([]); }); }); + +describe("BotInstance — OpenProtocol & slash command routing", () => { + it("accepts / commands when commandPrefix is '!' and routes private replies to invokerId", async () => { + const ctx = makeGateCtx({ adminGroups: [] }); + ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) => + `ok:${parsed.name}:${parsed.args}`, + ); + + const dm: TS3TextMessage = { + invokerName: "FlSpeakUser", + invokerId: "12", + invokerUid: "uid-fl", + message: "/play 晴天", + targetMode: 1, + invokerGroups: [], + }; + await handleTextMessage.call(ctx, dm); + + expect(ctx.executeCommand).toHaveBeenCalledTimes(1); + expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1); + expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12); + + ctx.tsClient.sendTextMessage.mockClear(); + await handleTextMessage.call(ctx, makeMsg("/now")); + expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:"); + }); + + it("routes permission denied and execution errors privately when triggered via DM", async () => { + const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] }); + const dmStop: TS3TextMessage = { + invokerName: "Guest", + invokerId: "22", + invokerUid: "uid-guest", + message: "/stop", + targetMode: 1, + invokerGroups: [], + }; + await handleTextMessage.call(ctx, dmStop); + expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22); + + ctx.tsClient.sendTextMessage.mockClear(); + const okCtx = makeGateCtx({ adminGroups: [] }); + okCtx.executeCommand = vi.fn(async () => { + throw new Error("boom"); + }); + await handleTextMessage.call(okCtx, { ...dmStop, message: "/play x" }); + expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22); + }); + + it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => { + const tsClient = new EventEmitter() as EventEmitter & { + getClientId(): number; + }; + tsClient.getClientId = () => 99; + const openProtocol = { + scheduleAnnounce: vi.fn(), + handlePluginCommand: vi.fn(async () => {}), + reset: vi.fn(), + }; + const ctx = { + tsClient, + openProtocol, + connected: true, + lifecycleGeneration: 0, + autoPaused: false, + idleTimer: null, + idlePollTimer: null, + jellyfinPollTimer: null, + snapshotTimer: null, + currentSourceIsSpotify: false, + disconnectEmitted: false, + _cancelIdleTimer: vi.fn(), + _startIdlePoller: vi.fn(), + _startJellyfinReportPoller: vi.fn(), + unregisterManagedVoiceClient: vi.fn(), + voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() }, + spotifyController: { stop: vi.fn() }, + player: { stop: vi.fn() }, + jellyfinReporter: undefined, + queue: { clear: vi.fn() }, + sweepLocalAudio: vi.fn(), + emit: vi.fn(), + refreshOccupancy: vi.fn(async () => {}), + profileManager: { onChannelMoved: vi.fn(async () => {}) }, + logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }, + } as Record; + + (BotInstance.prototype as any).setupTsEvents.call(ctx); + + tsClient.emit("connected"); + expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1); + + tsClient.emit("clientMoved", { id: 5, targetChannelID: 10n }); + expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1); + + tsClient.emit("clientMoved", { id: 99, targetChannelID: 10n }); + expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(2); + + const pluginCmd = { + name: "tsclient:commands", + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 5, + invokerName: "User", + invokerUid: "uid-user", + }; + tsClient.emit("pluginCommand", pluginCmd); + expect(openProtocol.handlePluginCommand).toHaveBeenCalledWith(pluginCmd); + + tsClient.emit("disconnected"); + expect(openProtocol.reset).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/bot/instance.ts b/src/bot/instance.ts index b2412cb..2449f9d 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -2,15 +2,17 @@ import { EventEmitter } from "node:events"; import { TS3Client, type TS3ClientOptions, + type TS3PluginCommand, type TS3TextMessage, type TS3VoiceActivity, type TS3VoiceSendFailure, } from "../ts-protocol/client.js"; +import { OpenProtocolManager } from "../ts-protocol/open-protocol.js"; import { AudioPlayer } from "../audio/player.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; import type { MusicProvider, Platform, Song } from "../music/provider.js"; import { - parseCommand, + parseCommandWithFallback, canRunCommand, type ParsedCommand, } from "./commands.js"; @@ -154,11 +156,27 @@ export interface BotStatus { effectiveDuration?: number; } +async function sendTextReply( + tsClient: Pick, + msg: TS3TextMessage, + text: string, +): Promise { + if (msg.targetMode === 1) { + const targetClientId = Number(msg.invokerId); + if (Number.isInteger(targetClientId) && targetClientId > 0) { + await tsClient.sendTextMessage(text, 1, targetClientId); + } + return; + } + await tsClient.sendTextMessage(text); +} + export class BotInstance extends EventEmitter { readonly id: string; name: string; private tsClient: TS3Client; + private openProtocol: OpenProtocolManager; private player: AudioPlayer; private voiceDucking: VoiceDuckingController; private managedVoiceClients: ManagedVoiceClientRegistry; @@ -230,6 +248,14 @@ export class BotInstance extends EventEmitter { this.avatarStore = options.avatarStore; this.tsClient = new TS3Client(options.tsOptions, this.logger); + this.openProtocol = new OpenProtocolManager({ + transport: this.tsClient, + getConfig: () => ({ + locale: this.config.locale, + commandPrefix: this.config.commandPrefix, + }), + logger: this.logger, + }); this.player = new AudioPlayer(this.logger); this.voiceDucking = new VoiceDuckingController( this.player, @@ -446,6 +472,12 @@ export class BotInstance extends EventEmitter { }); }); + this.tsClient.on("pluginCommand", (cmd: TS3PluginCommand) => { + this.openProtocol?.handlePluginCommand(cmd).catch((err) => { + this.logger.debug({ err }, "OpenProtocol plugin command handler failed"); + }); + }); + this.tsClient.on("disconnected", () => { // Always reset local state — covers the case where connect() never // completed (hanging handshake → 60s library idle timeout) and @@ -453,6 +485,7 @@ export class BotInstance extends EventEmitter { // short-circuited on !this.connected, leaving player stuck as "playing". this.lifecycleGeneration++; this.connected = false; + this.openProtocol?.reset(); this._cancelIdleTimer(); this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS); this.voiceDucking.reset(true); @@ -487,6 +520,7 @@ export class BotInstance extends EventEmitter { this.autoPaused = false; this._startIdlePoller(); this._startJellyfinReportPoller(); + this.openProtocol?.scheduleAnnounce(); }); this.tsClient.on("voiceActivity", (activity: TS3VoiceActivity) => { @@ -525,6 +559,7 @@ export class BotInstance extends EventEmitter { this.profileManager.onChannelMoved(event.targetChannelID).catch((err) => { this.logger.warn({ err }, "Channel description move update failed"); }); + this.openProtocol?.scheduleAnnounce(); } else { this.voiceDucking.removeSpeaker(event.id); } @@ -667,6 +702,7 @@ export class BotInstance extends EventEmitter { this.disconnectEmitted = true; this.emit("disconnected"); } + this.openProtocol?.reset(); this.tsClient.disconnect(); // Stop outbound PCM and initiate the TeamSpeak disconnect before removing // our id from the shared registry, minimizing the window in which another @@ -787,10 +823,10 @@ export class BotInstance extends EventEmitter { } private async handleTextMessage(msg: TS3TextMessage): Promise { - const parsed = parseCommand( + const parsed = parseCommandWithFallback( msg.message, this.config.commandPrefix, - this.config.commandAliases + this.config.commandAliases, ); if (!parsed) return; @@ -800,7 +836,7 @@ export class BotInstance extends EventEmitter { "Command denied: invoker not in adminGroups" ); try { - await this.tsClient.sendTextMessage(COMMAND_DENIED_MESSAGE); + await sendTextReply(this.tsClient, msg, COMMAND_DENIED_MESSAGE); } catch (sendErr) { this.logger.error({ err: sendErr }, "Failed to send permission-denied message to chat"); } @@ -818,15 +854,13 @@ export class BotInstance extends EventEmitter { // A single long reply (e.g. full lyrics) would exceed TeamSpeak's // per-message byte cap, so split it and send the chunks in order. for (const chunk of splitTextIntoChunks(response)) { - await this.tsClient.sendTextMessage(chunk); + await sendTextReply(this.tsClient, msg, chunk); } } } catch (err) { this.logger.error({ err, command: parsed.name }, "Command execution error"); try { - await this.tsClient.sendTextMessage( - `Error: ${(err as Error).message}` - ); + await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`); } catch (sendErr) { this.logger.error({ err: sendErr }, "Failed to send error message to chat"); } diff --git a/src/bot/profile.test.ts b/src/bot/profile.test.ts index ad6433b..58bef23 100644 --- a/src/bot/profile.test.ts +++ b/src/bot/profile.test.ts @@ -1,5 +1,4 @@ import { describe, it, expect, beforeEach, vi } from "vitest"; -import { Client, generateIdentity } from "@honeybbq/teamspeak-client"; import { BotProfileManager } from "./profile.js"; import { TS6HttpQuery } from "../ts-protocol/http-query.js"; import type { TS3Client } from "../ts-protocol/client.js"; @@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => { it("checks self clientupdate permission responses and retries only after reconnect", async () => { const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true }); - const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot"); const commands: string[] = []; - client.handler.sendPacket = vi.fn((_type, data: Buffer) => { - const command = data.toString(); + ts.execCommand.mockImplementation(async (command: string) => { commands.push(command); - const returnCode = command.match(/return_code=(\d+)/)?.[1]; - client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) }); + throw new Error("insufficient client permissions (error id=2568)"); }); - ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command)); - ts.execCommand.mockImplementation((command: string) => client.execCommand(command)); await pm.onSongChange(null); await pm.onSongChange(null); expect(commands).toHaveLength(1); - expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/); + expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放"); expect(request).not.toHaveBeenCalled(); expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false); pm.onConnect(); diff --git a/src/ts-protocol/client-groups.test.ts b/src/ts-protocol/client-groups.test.ts index 1981982..f2ca185 100644 --- a/src/ts-protocol/client-groups.test.ts +++ b/src/ts-protocol/client-groups.test.ts @@ -29,7 +29,11 @@ function withFakeClient( ): string[] { const calls: string[] = []; const fake = { - execCommandWithResponse: vi.fn(async (cmd: string) => { + send: vi.fn(async (req: { command: string; params?: readonly (readonly [string, unknown])[] }) => { + const paramPairs = (req.params ?? []) + .filter(([, v]) => v !== undefined) + .map(([k, v]) => `${k}=${String(v)}`); + const cmd = paramPairs.length > 0 ? `${req.command} ${paramPairs.join(" ")}` : req.command; calls.push(cmd); return respond(cmd); }), diff --git a/src/ts-protocol/client-voice.test.ts b/src/ts-protocol/client-voice.test.ts index feb0122..a2f1e98 100644 --- a/src/ts-protocol/client-voice.test.ts +++ b/src/ts-protocol/client-voice.test.ts @@ -1,34 +1,77 @@ +import { EventEmitter } from "node:events"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { Client as SDKClient, type ResolvedAddr } from "@honeybbq/teamspeak-client"; -import { Resolver } from "@honeybbq/teamspeak-client/discovery"; +import { Resolver, type Client as SDKClient, type ClientOptions as SDKClientOptions, type ResolvedAddr } from "@honeybbq/teamspeak/client"; import { TS3Client, type TS3VoiceSendFailure } from "./client.js"; import type { TrackingVoiceEndpointResolver } from "./voice-endpoint.js"; import type { Logger } from "../logger.js"; +class FakeSdkClient extends EventEmitter { + clientID = 0; + channelID = 1n; + uid = "fake-uid"; + readonly addr: string; + readonly options: SDKClientOptions; + + constructor(addr: string, options: SDKClientOptions) { + super(); + this.addr = addr; + this.options = options; + } + + async connect(): Promise { + this.clientID = 42; + } + + async disconnect(): Promise { + this.emit("disconnected", { error: undefined, willReconnect: false }); + } + + async send(_request: { command: string; params?: Record }): Promise[]> { + return []; + } + + sendVoice(_data: Uint8Array, _codec: number): void {} + + emitDisconnected(error?: Error): void { + this.emit("disconnected", { error, willReconnect: false }); + } +} + type Failure = TS3VoiceSendFailure; -type Harness = { client: SDKClient | null; voiceFramesSent: number }; +type Harness = { client: FakeSdkClient | null; voiceFramesSent: number }; describe("TS3Client voice send failure lifecycle", () => { let client: TS3Client; - let sdk: SDKClient; + let sdk: FakeSdkClient; let logger: Logger; let records: Array<{ level: string; args: unknown[] }>; + let onCreateSdk: ((sdk: FakeSdkClient) => void) | undefined; + + const createClient = (extra: Partial[0]> = {}) => + new TS3Client( + { + host: "localhost", + port: 9987, + queryPort: 10011, + nickname: "VoiceTest", + serverProtocol: "ts3", + sdkClientFactory: (_identity, addr, _nickname, sdkOptions) => { + const fake = new FakeSdkClient(addr, sdkOptions); + onCreateSdk?.(fake); + return fake as unknown as SDKClient; + }, + ...extra, + }, + logger, + ); beforeEach(async () => { vi.useFakeTimers(); - // Keep the real SDK object, logger bridge and event dispatch. Replace only - // its network handshake and explicit shutdown so no UDP socket is opened. - vi.spyOn(SDKClient.prototype, "connect").mockImplementation(async function (this: SDKClient) { - this.clid = 42; - this._markConnected(); - }); - vi.spyOn(SDKClient.prototype, "disconnect").mockImplementation(async function (this: SDKClient) { - this.handler.onClosed?.(null); - }); records = []; + onCreateSdk = undefined; const capture = (level: string) => (...args: unknown[]) => records.push({ level, args }); logger = { info: capture("info"), warn: capture("warn"), error: capture("error"), debug() {} } as unknown as Logger; - client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3" }, logger); + client = createClient(); await client.connect(); sdk = (client as unknown as Harness).client!; }); @@ -141,7 +184,7 @@ describe("TS3Client voice send failure lifecycle", () => { client.sendVoiceData(Buffer.from([1])); send.mockImplementation(() => { throw { code: "EPIPE" }; }); client.sendVoiceData(Buffer.from([1])); - sdk.handler.onClosed?.(new Error("synthetic connection loss")); + sdk.emitDisconnected(new Error("synthetic connection loss")); await vi.advanceTimersByTimeAsync(3000); expect(terminal).toEqual([]); expect((client as unknown as Harness).voiceFramesSent).toBe(0); @@ -152,22 +195,21 @@ describe("TS3Client voice send failure lifecycle", () => { it("does not revive a connection whose handshake was cancelled", async () => { let finishHandshake!: () => void; - vi.spyOn(SDKClient.prototype, "connect").mockImplementationOnce(function (this: SDKClient) { - return new Promise(resolve => { + onCreateSdk = (fake) => { + vi.spyOn(fake, "connect").mockImplementationOnce(() => new Promise(resolve => { finishHandshake = () => { - this.clid = 99; - this._markConnected(); + fake.clientID = 99; resolve(); }; - }); - }); + })); + }; const connected = vi.fn(); client.on("connected", connected); const pending = client.connect(); await Promise.resolve(); expect(finishHandshake).toBeTypeOf("function"); const connectingSdk = (client as unknown as Harness).client!; - const close = vi.spyOn(connectingSdk.handler, "close"); + const close = vi.spyOn(connectingSdk, "disconnect"); const send = vi.spyOn(connectingSdk, "sendVoice"); client.disconnect(); finishHandshake(); @@ -188,7 +230,7 @@ describe("TS3Client voice send failure lifecycle", () => { await client.connect(); // Old disconnect dispatch is queued; old socket callbacks may follow it. const before = records.length; - sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" })); + sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" })); await vi.advanceTimersByTimeAsync(3000); expect(client.getClientId()).toBe(42); expect(records.slice(before).filter(record => record.level === "warn")).toEqual([]); @@ -198,28 +240,44 @@ describe("TS3Client voice send failure lifecycle", () => { it("does not let an older named-channel lookup move the replacement connection", async () => { client.disconnect(); await vi.advanceTimersByTimeAsync(0); - client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3", defaultChannel: "Music" }, logger); + client = createClient({ defaultChannel: "Music" }); let nextClientId = 101; - vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) { - this.clid = nextClientId++; - this._markConnected(); - }); let finishOlderLookup!: (rows: Record[]) => void; - vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockImplementation(function (this: SDKClient) { - if (this.clid === 101) return new Promise(resolve => { finishOlderLookup = resolve; }); - return Promise.resolve([{ cid: "20", channel_name: "Music" }]); - }); - const moves: Array<{ clientId: number; command: string }> = []; - vi.spyOn(SDKClient.prototype, "execCommand").mockImplementation(async function (this: SDKClient, command: string) { - moves.push({ clientId: this.clid, command }); - }); + const moves: Array<{ clientId: number; command: string; params: Record | undefined }> = []; + onCreateSdk = (fake) => { + vi.spyOn(fake, "connect").mockImplementation(async () => { + fake.clientID = nextClientId++; + }); + vi.spyOn(fake, "send").mockImplementation(async (req) => { + if (req.command === "channellist") { + if (fake.clientID === 101) { + return new Promise(resolve => { finishOlderLookup = resolve; }); + } + return [{ cid: "20", channel_name: "Music", pid: "0", channel_order: "0" }]; + } + if (req.command === "clientmove") { + moves.push({ clientId: fake.clientID, command: req.command, params: req.params }); + } + return []; + }); + }; const first = client.connect(); for (let i = 0; i < 8; i++) await Promise.resolve(); expect(finishOlderLookup).toBeTypeOf("function"); await client.connect(); - finishOlderLookup([{ cid: "10", channel_name: "Music" }]); + finishOlderLookup([{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }]); await first; - expect(moves).toEqual([{ clientId: 102, command: "clientmove clid=102 cid=20" }]); + expect(moves).toEqual([ + { + clientId: 102, + command: "clientmove", + params: [ + ["clid", 102], + ["cid", 20n], + ["cpw", undefined], + ], + }, + ]); expect(records.filter(record => record.args[1] === "Joined channel").map(record => record.args[0])).toEqual([{ channelName: "Music", cid: "20" }]); expect(client.getClientId()).toBe(102); }); @@ -230,13 +288,14 @@ describe("TS3Client voice send failure lifecycle", () => { vi.spyOn(Resolver.prototype, "resolve").mockImplementationOnce(() => new Promise(resolve => { finishOlderResolution = resolve; })) .mockResolvedValue([row("192.0.2.2:9987")]); let sequence = 0; - vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) { - const clientId = 101 + sequence++; - const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver; - await resolver.resolve("voice.test:9987"); - this.clid = clientId; - this._markConnected(); - }); + onCreateSdk = (fake) => { + vi.spyOn(fake, "connect").mockImplementation(async () => { + const clientId = 101 + sequence++; + const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver; + await resolver.resolve("voice.test:9987"); + fake.clientID = clientId; + }); + }; const first = client.connect(); for (let i = 0; i < 8; i++) await Promise.resolve(); expect(finishOlderResolution).toBeTypeOf("function"); @@ -249,12 +308,20 @@ describe("TS3Client voice send failure lifecycle", () => { }); it.each(["10", "Music"])("does not report an old %s channel move after connection replacement", async channel => { - vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockResolvedValue([{ cid: "10", channel_name: "Music" }]); let finishMove!: () => void; - const move = vi.spyOn(sdk, "execCommand").mockImplementation(() => new Promise(resolve => { finishMove = resolve; })); + const moveSpy = vi.fn(() => new Promise(resolve => { finishMove = resolve; })); + vi.spyOn(sdk, "send").mockImplementation(async (req) => { + if (req.command === "channellist") { + return [{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }]; + } + if (req.command === "clientmove") { + await moveSpy(); + } + return []; + }); const joining = client.joinChannel(channel); for (let i = 0; i < 8; i++) await Promise.resolve(); - expect(move).toHaveBeenCalledWith("clientmove clid=42 cid=10", 10000); + expect(moveSpy).toHaveBeenCalledTimes(1); await client.connect(); finishMove(); await joining; @@ -263,7 +330,7 @@ describe("TS3Client voice send failure lifecycle", () => { it("does not report a stale channel lookup failure against the new connection", async () => { let failLookup!: (error: Error) => void; - vi.spyOn(sdk, "execCommandWithResponse").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; })); + vi.spyOn(sdk, "send").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; })); const joining = client.joinChannel("Music"); await client.connect(); failLookup(new Error("old credential-secret failure")); @@ -275,7 +342,7 @@ describe("TS3Client voice send failure lifecycle", () => { it("keeps safe async UDP error detail while throttling without terminalizing it", async () => { const terminal: Failure[] = []; client.on("voiceSendFailed", event => terminal.push(event)); - for (let i = 0; i < 100; i++) sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" })); + for (let i = 0; i < 100; i++) sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" })); await vi.advanceTimersByTimeAsync(2000); const warnings = records.filter(record => record.level === "warn"); expect(warnings).toHaveLength(2); @@ -286,7 +353,7 @@ describe("TS3Client voice send failure lifecycle", () => { }); it("discards unsafe async UDP codes and cancels their summary on disconnect", async () => { - sdk.logger.warn("udp send error", { code: "credential-secret", message: "credential-secret" }); + sdk.options.logger?.warn?.("udp send error", { code: "credential-secret", message: "credential-secret" }); client.disconnect(); await vi.advanceTimersByTimeAsync(3000); expect(records.filter(record => record.level === "warn").filter(record => String(record.args[1]).includes("udp send error"))).toHaveLength(1); diff --git a/src/ts-protocol/client.ts b/src/ts-protocol/client.ts index aded62a..866776f 100644 --- a/src/ts-protocol/client.ts +++ b/src/ts-protocol/client.ts @@ -1,24 +1,39 @@ import { EventEmitter } from "node:events"; import { Readable } from "node:stream"; import { - Client as TS3FullClient, - generateIdentity as genTS3Identity, - getUidFromPublicKey, - identityFromString, - sendTextMessage, + asChannelID, + asClientID, + Codec, + deleteFile, + getClientProperties, + initFileUpload, listChannels, listClients, - clientMove, - getClientInfo, - fileTransferDeleteFile, - type Identity, - type TextMessage, - type ClientInfo, - type ClientLeftViewEvent, + moveClient, + sendChannelMessage, + sendPluginCommand as sdkSendPluginCommand, + sendPrivateMessage, + sendServerMessage, + type ChannelID, + type ClientEnterEvent, + type ClientEntry, + type ClientLeaveEvent, type ClientMovedEvent, - type VoiceData, + type DisconnectedEvent, type FileUploadInfo, -} from "@honeybbq/teamspeak-client"; + type PluginCommandEvent, + type PluginCommandTarget, + type TextMessageEvent, + type VoiceDataEvent, +} from "@honeybbq/teamspeak"; +import { + Client as TS3FullClient, + generateIdentitySync as genTS3Identity, + parseIdentity, + UIDAlgorithm, + type ClientOptions as SDKClientOptions, + type Identity, +} from "@honeybbq/teamspeak/client"; import type { Logger } from "../logger.js"; import { detectServerProtocol, @@ -32,7 +47,7 @@ import { export { CODEC_OPUS_MUSIC } from "./voice.js"; export type { ServerProtocol } from "./protocol-detect.js"; -export type { FileUploadInfo } from "@honeybbq/teamspeak-client"; +export type { FileUploadInfo, PluginCommandTarget } from "@honeybbq/teamspeak"; /** Escape a string for use in TS3 ServerQuery-style commands. */ export function escapeTS3(str: string): string { @@ -60,6 +75,13 @@ export interface TS3ClientOptions { serverProtocol?: ServerProtocol; /** API key for TS6 HTTP Query authentication. */ ts6ApiKey?: string; + /** @internal Test seam to substitute the underlying SDK Client instance. */ + sdkClientFactory?: ( + identity: Identity, + addr: string, + nickname: string, + options: SDKClientOptions, + ) => TS3FullClient; } export interface TS3TextMessage { @@ -71,6 +93,14 @@ export interface TS3TextMessage { invokerGroups: string[]; // sender's TS server-group ids; [] when not in view cache } +export interface TS3PluginCommand { + name: string; + data: string; + invokerId: number; + invokerName: string; + invokerUid: string; +} + /** Lightweight voice-packet signal used for activity detection. The encoded * payload is intentionally not forwarded beyond this protocol wrapper. */ export interface TS3VoiceActivity { @@ -115,26 +145,36 @@ function safeSocketErrorCode(error: unknown): string | undefined { const VISIBLE_CLIENT_UID_RELEASE_GRACE_MS = 1_000; /** - * Map the library's TextMessage to our wrapper. Preserves invokerGroups (the + * Map the library's TextMessageEvent to our wrapper. Preserves invokerGroups (the * sender's TS server groups), which the library populates only when the sender * is in the bot's client-view cache; otherwise it is []. Used by the chat * command permission gate. */ -export function toTS3TextMessage(msg: TextMessage): TS3TextMessage { +export function toTS3TextMessage(msg: TextMessageEvent): TS3TextMessage { return { invokerName: msg.invokerName, invokerId: String(msg.invokerID), invokerUid: msg.invokerUID, message: msg.message, targetMode: msg.targetMode, - invokerGroups: msg.invokerGroups ?? [], + invokerGroups: (msg.invokerGroups ?? []).map((groupId) => String(groupId)), + }; +} + +export function toTS3PluginCommand(ev: PluginCommandEvent): TS3PluginCommand { + return { + name: ev.name, + data: ev.data, + invokerId: Number(ev.invokerID), + invokerName: ev.invokerName, + invokerUid: ev.invokerUID, }; } export class TS3Client extends EventEmitter { private client: TS3FullClient | null = null; private identity: Identity; - private readonly clientUid: string; + private clientUid: string; private clientId = 0; private readonly visibleClientUids = new Map(); private readonly visibleClientUidReleaseTimers = new Map< @@ -156,11 +196,11 @@ export class TS3Client extends EventEmitter { this.logger = logger; if (options.identity) { - this.identity = identityFromString(options.identity); + this.identity = parseIdentity(options.identity); } else { this.identity = genTS3Identity(8); } - this.clientUid = getUidFromPublicKey(this.identity.publicKeyBase64()); + this.clientUid = this.identity.uid(UIDAlgorithm.SHA1); } /** The detected (or forced) server protocol after connect(). */ @@ -275,43 +315,52 @@ export class TS3Client extends EventEmitter { this.logger.warn(msg); }; - sdkClient = new TS3FullClient(this.identity, addr, this.options.nickname, { + const sdkOptions: SDKClientOptions = { // Forward server password to the protocol library so it can be // included in clientinit for password-protected servers serverPassword: this.options.serverPassword, resolver: voiceEndpointResolver, logger: { - debug: (msg) => { if (isCurrent()) this.logger.debug(msg); }, - info: (msg) => { if (isCurrent()) this.logger.info(msg); }, + debug: (msg: string) => { if (isCurrent()) this.logger.debug(msg); }, + info: (msg: string) => { if (isCurrent()) this.logger.info(msg); }, warn: throttledWarn, - error: (msg) => { if (isCurrent()) this.logger.error(msg); }, + error: (msg: string) => { if (isCurrent()) this.logger.error(msg); }, }, - }); + }; + sdkClient = this.options.sdkClientFactory + ? this.options.sdkClientFactory(this.identity, addr, this.options.nickname, sdkOptions) + : new TS3FullClient(this.identity, addr, this.options.nickname, sdkOptions); this.client = sdkClient; - sdkClient.on("textMessage", (msg: TextMessage) => { + sdkClient.on("textMessage", (msg: TextMessageEvent) => { if (!isCurrent()) return; if (msg.invokerID === this.clientId) return; this.emit("textMessage", toTS3TextMessage(msg)); }); - sdkClient.on("voiceData", (voice: VoiceData) => { + sdkClient.on("pluginCommand", (ev: PluginCommandEvent) => { + if (!isCurrent()) return; + this.emit("pluginCommand", toTS3PluginCommand(ev)); + }); + + sdkClient.on("voiceData", (voice: VoiceDataEvent) => { if (!isCurrent()) return; // The library normally suppresses our own packets; retain the explicit // guard so a future protocol change cannot make a bot duck itself. - if (voice.clientId === this.clientId) return; - const clientUid = this.visibleClientUids.get(voice.clientId); + const voiceClientId = Number(voice.clientID); + if (voiceClientId === this.clientId) return; + const clientUid = this.visibleClientUids.get(voiceClientId); const activity: TS3VoiceActivity = { - clientId: voice.clientId, + clientId: voiceClientId, codec: voice.codec, ...(clientUid ? { clientUid } : {}), }; this.emit("voiceActivity", activity); }); - sdkClient.on("disconnected", (err) => { + sdkClient.on("disconnected", (ev: DisconnectedEvent) => { if (!isCurrent()) return; - const code = safeSocketErrorCode(err); + const code = safeSocketErrorCode(ev.error); this.logger.warn(code ? { code } : {}, "Connection closed"); ++this.connectionGeneration; this.resetVoiceSendState(); @@ -321,48 +370,44 @@ export class TS3Client extends EventEmitter { this.emit("disconnected"); }); - sdkClient.on("clientEnter", (info: ClientInfo) => { + sdkClient.on("clientEnter", (info: ClientEnterEvent) => { if (!isCurrent()) return; - this.rememberVisibleClientUid(info.id, info.uid); + this.rememberVisibleClientUid(Number(info.id), info.uid ?? ""); this.logger.debug( - { nickname: info.nickname, id: info.id }, + { nickname: info.nickname, id: Number(info.id) }, "Client entered" ); this.emit("clientEnter", info); }); - sdkClient.on("clientLeave", (ev: ClientLeftViewEvent) => { + sdkClient.on("clientLeave", (ev: ClientLeaveEvent) => { if (!isCurrent()) return; - this.releaseVisibleClientUid(ev.id); - this.logger.debug({ id: ev.id }, "Client left"); - this.emit("clientLeave", ev); + const id = Number(ev.clientID); + this.releaseVisibleClientUid(id); + this.logger.debug({ id }, "Client left"); + this.emit("clientLeave", { ...ev, id }); }); sdkClient.on("clientMoved", (ev: ClientMovedEvent) => { if (!isCurrent()) return; + const id = Number(ev.clientID); this.logger.debug( - { id: ev.id, targetChannelID: ev.targetChannelID.toString() }, + { id, targetChannelID: ev.targetChannelID.toString() }, "Client moved" ); - this.emit("clientMoved", ev); + this.emit("clientMoved", { ...ev, id }); }); await sdkClient.connect(); if (!isCurrent()) { - // DNS/socket setup may finish after disconnect() closed the transport. - // Close it again without waiting on command replies from a stale session. - sdkClient.handler.close(); + // Handshake may finish after disconnect() or a newer connect() superseded it. + await sdkClient.disconnect().catch(() => {}); return; } - // Note: @honeybbq/teamspeak-client 0.2.x ships a universal clientinit - // (client_version "3.?.? [Build: 5680278000]" + matching signature) - // that works against both TS3 and TS6 servers. The old 3.6.2 monkey- - // patch on handler.sendPacket was removed when we bumped to 0.2.1 — it - // would have replaced the library's new correct version with a stale - // signature and made TS6 handshakes fail. - await sdkClient.waitConnected(); - if (!isCurrent()) return; - this.clientId = sdkClient.clientID(); + this.clientId = Number(sdkClient.clientID); + if (sdkClient.uid) { + this.clientUid = sdkClient.uid; + } this.voiceFramesSent = 0; this.logger.info( { clientId: this.clientId, protocol: this.detectedProtocol }, @@ -393,7 +438,12 @@ export class TS3Client extends EventEmitter { const isNumeric = /^\d+$/.test(channelName); if (isNumeric) { try { - await clientMove(client, clientId, BigInt(channelName), password); + await moveClient( + client, + asClientID(clientId), + asChannelID(BigInt(channelName)), + password ? { password } : undefined, + ); if (!isCurrent()) return; this.logger.info({ channelName }, "Joined channel"); } catch (err) { @@ -412,7 +462,12 @@ export class TS3Client extends EventEmitter { return; } - await clientMove(client, clientId, channel.id, password); + await moveClient( + client, + asClientID(clientId), + channel.id, + password ? { password } : undefined, + ); if (!isCurrent()) return; this.logger.info( { channelName, cid: channel.id.toString() }, @@ -425,19 +480,38 @@ export class TS3Client extends EventEmitter { async sendTextMessage( message: string, - targetMode: number = 2 + targetMode: number = 2, + targetClientId?: number, ): Promise { if (!this.client) return; - // targetMode 2 = channel, target 0 = current channel - const target = targetMode === 2 ? BigInt(0) : BigInt(this.clientId); - await sendTextMessage(this.client, targetMode, target, message); + if (targetMode === 1) { + if (targetClientId === undefined) return; + await sendPrivateMessage(this.client, asClientID(targetClientId), message); + return; + } + if (targetMode === 3) { + await sendServerMessage(this.client, message); + return; + } + await sendChannelMessage(this.client, message); } - async getClientsInChannel(): Promise { + async sendPluginCommand( + name: string, + data: string, + target: PluginCommandTarget | number = "channel", + ): Promise { + if (!this.client) throw new Error("Not connected"); + const resolvedTarget: PluginCommandTarget = + typeof target === "number" ? { clientID: asClientID(target) } : target; + await sdkSendPluginCommand(this.client, name, data, resolvedTarget); + } + + async getClientsInChannel(): Promise { if (!this.client) return []; try { const allClients = await listClients(this.client); - const myChannelId = this.client.channelID(); + const myChannelId = this.client.channelID; return allClients.filter((c) => c.channelID === myChannelId); } catch { return []; @@ -454,9 +528,7 @@ export class TS3Client extends EventEmitter { async getClientServerGroups(clid: number): Promise { if (!this.client) return []; try { - const info = await getClientInfo(this.client, clid); - // `client_servergroups`: comma-separated server-group ids (verified in - // @honeybbq/teamspeak-client dist/index.mjs; listClients parses the same). + const info = await getClientProperties(this.client, asClientID(clid)); const raw = info.client_servergroups ?? ""; return raw ? raw.split(",") : []; } catch { @@ -468,29 +540,32 @@ export class TS3Client extends EventEmitter { async execCommand(cmd: string): Promise { if (!this.client) throw new Error("Not connected"); - await this.client.execCommand(cmd); + await this.client.exec(cmd); } /** Fire a command without waiting for the server's response. */ async sendCommandNoWait(cmd: string): Promise { if (!this.client) throw new Error("Not connected"); - await this.client.sendCommandNoWait(cmd); + await this.client.execNoWait(cmd); } async execCommandWithResponse(cmd: string): Promise[]> { if (!this.client) throw new Error("Not connected"); - return this.client.execCommandWithResponse(cmd); + return this.client.exec(cmd); } async fileTransferInitUpload( - channelID: bigint, + channelID: bigint | ChannelID, path: string, password: string, size: bigint, overwrite = true, ): Promise { if (!this.client) throw new Error("Not connected"); - return this.client.fileTransferInitUpload(channelID, path, password, size, overwrite); + return initFileUpload(this.client, asChannelID(channelID), path, size, { + password, + overwrite, + }); } async uploadFileData(host: string, info: FileUploadInfo, data: Readable): Promise { @@ -498,9 +573,9 @@ export class TS3Client extends EventEmitter { await this.client.uploadFileData(host, info, data); } - async fileTransferDeleteFile(channelID: bigint, paths: string[]): Promise { + async fileTransferDeleteFile(channelID: bigint | ChannelID, paths: string[]): Promise { if (!this.client) throw new Error("Not connected"); - await fileTransferDeleteFile(this.client, channelID, paths); + await deleteFile(this.client, asChannelID(channelID), paths); } /** The server host (needed for file transfer TCP connections). */ @@ -511,7 +586,7 @@ export class TS3Client extends EventEmitter { /** The current channel ID of this client. */ getChannelId(): bigint { if (!this.client) return 0n; - return this.client.channelID(); + return this.client.channelID; } private voiceFramesSent = 0; @@ -520,7 +595,7 @@ export class TS3Client extends EventEmitter { const client = this.client; if (!client || this.disconnecting) return "unavailable"; try { - client.sendVoice(opusFrame, 5); + client.sendVoice(opusFrame, Codec.OpusMusic); } catch (err) { if (this.voiceFailure) { this.voiceFailure.consecutiveFailures++; @@ -581,7 +656,7 @@ export class TS3Client extends EventEmitter { } getIdentityExport(): string { - return this.identity.toString(); + return this.identity.export(); } getClientId(): number { diff --git a/src/ts-protocol/open-protocol.test.ts b/src/ts-protocol/open-protocol.test.ts new file mode 100644 index 0000000..bffd5ec --- /dev/null +++ b/src/ts-protocol/open-protocol.test.ts @@ -0,0 +1,293 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import pino from "pino"; +import { + ACK_GLOBAL_BURST, + ANNOUNCE_DEBOUNCE_MS, + ANNOUNCE_RETRY_DELAY_MS, + APP_NAME, + APP_VERSION, + BOT_CAPABILITIES, + COMMANDS_LIST_REQ_COOLDOWN_MS, + COMMANDS_PLUGIN, + IDENTITY_ANNOUNCE_COOLDOWN_MS, + IDENTITY_PLUGIN, + IDENTITY_QUERY_COOLDOWN_MS, + MAX_CMD_ARGS_CHARS, + MAX_CMD_DESC_CHARS, + MAX_CMD_NAME_CHARS, + MAX_COMMANDS, + MAX_PAYLOAD_BYTES, + OPEN_PROTOCOL_VERSION, + OpenProtocolManager, + buildCommandsListAckJson, + buildIdentityPayloadJson, + buildOpenProtocolCommands, + type OpenProtocolRuntimeConfig, + type OpenProtocolTransport, +} from "./open-protocol.js"; +import type { TS3PluginCommand } from "./client.js"; + +function makeCmd(overrides: Partial = {}): TS3PluginCommand { + return { + name: IDENTITY_PLUGIN, + data: JSON.stringify({ v: 1, action: "announce" }), + invokerId: 7, + invokerName: "Alice", + invokerUid: "uid-alice", + ...overrides, + }; +} + +describe("OpenProtocol payload builders", () => { + it("builds valid v1 identity payloads with package version and command_prefix under 1024 bytes", () => { + const raw = buildIdentityPayloadJson("announce", "!"); + expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); + expect(JSON.parse(raw)).toEqual({ + v: OPEN_PROTOCOL_VERSION, + action: "announce", + client_type: "bot", + app_name: APP_NAME, + app_version: APP_VERSION, + capabilities: [...BOT_CAPABILITIES], + command_prefix: "!", + }); + + const ack = JSON.parse(buildIdentityPayloadJson("announce_ack", "?")); + expect(ack.action).toBe("announce_ack"); + expect(ack.command_prefix).toBe("?"); + }); + + it("drops command_prefix if an oversized value would exceed 1024 bytes", () => { + const raw = buildIdentityPayloadJson("announce", "p".repeat(1200)); + expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); + expect(JSON.parse(raw).app_name).toBe(APP_NAME); + }); + + it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => { + for (const locale of ["zh", "en"] as const) { + const cmds = buildOpenProtocolCommands(locale); + expect(cmds.length).toBeGreaterThan(0); + expect(cmds.length).toBeLessThanOrEqual(MAX_COMMANDS); + + for (const cmd of cmds) { + expect(Array.from(cmd.name).length).toBeLessThanOrEqual(MAX_CMD_NAME_CHARS); + expect(Array.from(cmd.desc).length).toBeLessThanOrEqual(MAX_CMD_DESC_CHARS); + if (cmd.args !== undefined) { + expect(Array.from(cmd.args).length).toBeLessThanOrEqual(MAX_CMD_ARGS_CHARS); + } + } + + const raw = buildCommandsListAckJson(locale, "!"); + expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); + const parsed = JSON.parse(raw) as { + v: number; + action: string; + prefix: string; + commands: unknown[]; + }; + expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION); + expect(parsed.action).toBe("list_ack"); + expect(parsed.prefix).toBe("!"); + expect(parsed.commands.length).toBe(cmds.length); + } + }); +}); + +describe("OpenProtocolManager", () => { + let nowMs: number; + let clientId: number; + let config: OpenProtocolRuntimeConfig; + let sendPluginCommand: ReturnType; + let manager: OpenProtocolManager; + + beforeEach(() => { + vi.useFakeTimers(); + nowMs = 100_000; + clientId = 42; + config = { locale: "zh", commandPrefix: "!" }; + sendPluginCommand = vi.fn(async () => {}); + const transport: OpenProtocolTransport = { + getClientId: () => clientId, + sendPluginCommand: sendPluginCommand as OpenProtocolTransport["sendPluginCommand"], + }; + manager = new OpenProtocolManager({ + transport, + getConfig: () => config, + logger: pino({ level: "silent" }), + now: () => nowMs, + }); + }); + + afterEach(() => { + manager.reset(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("ignores unrelated plugins, self-sent commands, malformed JSON, and non-v1 versions", async () => { + await manager.handlePluginCommand(makeCmd({ name: "other:plugin" })); + await manager.handlePluginCommand(makeCmd({ invokerId: 42 })); + await manager.handlePluginCommand(makeCmd({ data: "{not-json" })); + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 2, action: "query" }) })); + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce_ack" }) })); + await manager.handlePluginCommand( + makeCmd({ name: COMMANDS_PLUGIN, data: JSON.stringify({ v: 1, action: "list_ack" }) }), + ); + expect(sendPluginCommand).not.toHaveBeenCalled(); + }); + + it("replies with unicast announce_ack to announce and query, with separate cooldowns", async () => { + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), 7); + expect(JSON.parse(sendPluginCommand.mock.calls[0][1] as string).action).toBe("announce_ack"); + + // Repeated announce within 10s cooldown is suppressed + nowMs += 3_000; + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + + // query uses an independent 5s cooldown bucket, so it succeeds immediately + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(2); + + // Repeated query within 5s is suppressed, then allowed after 5s + nowMs += IDENTITY_QUERY_COOLDOWN_MS - 1; + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(2); + nowMs += 1; + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(3); + + // announce still respects its 10s cooldown until elapsed + nowMs += 1_000; // total 9_000ms since first announce + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(3); + nowMs += IDENTITY_ANNOUNCE_COOLDOWN_MS; + await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) })); + expect(sendPluginCommand).toHaveBeenCalledTimes(4); + }); + + it("replies with localized unicast list_ack on commands list_req using dynamic config", async () => { + config = { locale: "en", commandPrefix: "?" }; + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 11, + invokerUid: "", + }), + ); + + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + expect(sendPluginCommand).toHaveBeenCalledWith(COMMANDS_PLUGIN, expect.any(String), 11); + const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string); + expect(payload.v).toBe(1); + expect(payload.action).toBe("list_ack"); + expect(payload.prefix).toBe("?"); + expect(payload.commands[0]).toEqual({ name: "play", args: "", desc: "Play song" }); + + // Cooldown falls back to invokerId when invokerUid is empty + nowMs += COMMANDS_LIST_REQ_COOLDOWN_MS - 10; + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 11, + invokerUid: "", + }), + ); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + }); + + it("enforces global token bucket across peers and rolls back cooldown/token on send failure", async () => { + for (let i = 1; i <= ACK_GLOBAL_BURST; i++) { + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: i, + invokerUid: `peer-${i}`, + }), + ); + } + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST); + + // 5th distinct peer in same millisecond is throttled by global burst + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 99, + invokerUid: "peer-99", + }), + ); + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST); + + // After 500ms, 1 token refills (2/sec) + nowMs += 500; + sendPluginCommand.mockRejectedValueOnce(new Error("transient send failure")); + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 99, + invokerUid: "peer-99", + }), + ); + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1); + + // Because send failed, both peer-99 cooldown and global token were rolled back + await manager.handlePluginCommand( + makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 99, + invokerUid: "peer-99", + }), + ); + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 2); + }); + + it("debounces self-announce over 2s window and emits at most one trailing announce", async () => { + manager.scheduleAnnounce(); + await Promise.resolve(); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), "channel"); + + // Two calls inside 2s window coalesce into a single trailing broadcast + nowMs += 400; + manager.scheduleAnnounce(); + nowMs += 600; + manager.scheduleAnnounce(); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + + nowMs += ANNOUNCE_DEBOUNCE_MS - 1_000; + await vi.advanceTimersByTimeAsync(ANNOUNCE_DEBOUNCE_MS - 400); + expect(sendPluginCommand).toHaveBeenCalledTimes(2); + }); + + it("retries failed announce once after 500ms and cancels pending timers on reset", async () => { + sendPluginCommand.mockRejectedValueOnce(new Error("channel broadcast error")); + manager.scheduleAnnounce(); + await Promise.resolve(); + await Promise.resolve(); + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + + nowMs += ANNOUNCE_RETRY_DELAY_MS; + await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS); + expect(sendPluginCommand).toHaveBeenCalledTimes(2); + + // Trigger another failure then reset before retry fires + nowMs += ANNOUNCE_DEBOUNCE_MS; + sendPluginCommand.mockRejectedValueOnce(new Error("error before disconnect")); + manager.scheduleAnnounce(); + await Promise.resolve(); + await Promise.resolve(); + expect(sendPluginCommand).toHaveBeenCalledTimes(3); + + manager.reset(); + await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS); + expect(sendPluginCommand).toHaveBeenCalledTimes(3); + }); +}); diff --git a/src/ts-protocol/open-protocol.ts b/src/ts-protocol/open-protocol.ts new file mode 100644 index 0000000..b7c5722 --- /dev/null +++ b/src/ts-protocol/open-protocol.ts @@ -0,0 +1,527 @@ +import { readFileSync } from "node:fs"; +import type { Logger } from "../logger.js"; +import type { PluginCommandTarget, TS3PluginCommand } from "./client.js"; + +export const OPEN_PROTOCOL_VERSION = 1; +export const IDENTITY_PLUGIN = "tsclient:identity"; +export const COMMANDS_PLUGIN = "tsclient:commands"; +export const MAX_PAYLOAD_BYTES = 1024; + +export const APP_NAME = "TSMusicBot"; +export const BOT_CAPABILITIES = ["chat:slash_commands"] as const; + +export const ANNOUNCE_DEBOUNCE_MS = 2_000; +export const ANNOUNCE_RETRY_DELAY_MS = 500; + +export const IDENTITY_ANNOUNCE_COOLDOWN_MS = 10_000; +export const IDENTITY_QUERY_COOLDOWN_MS = 5_000; +export const COMMANDS_LIST_REQ_COOLDOWN_MS = 5_000; + +export const ACK_GLOBAL_BURST = 4; +export const ACK_GLOBAL_RATE_PER_SEC = 2; + +export const MAX_COMMANDS = 16; +export const MAX_CMD_NAME_CHARS = 24; +export const MAX_CMD_ARGS_CHARS = 32; +export const MAX_CMD_DESC_CHARS = 64; +export const MAX_APP_META_CHARS = 32; +const MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE = 128; + +export interface OpenProtocolCommandSpec { + name: string; + args?: string; + desc: string; +} + +export interface OpenProtocolIdentityPayload { + v: 1; + action: "announce" | "announce_ack"; + client_type: "bot"; + app_name: string; + app_version: string; + capabilities: string[]; + command_prefix?: string; +} + +export interface OpenProtocolCommandsListAckPayload { + v: 1; + action: "list_ack"; + prefix?: string; + commands: OpenProtocolCommandSpec[]; +} + +export interface OpenProtocolRuntimeConfig { + locale: "zh" | "en"; + commandPrefix: string; +} + +export interface OpenProtocolTransport { + getClientId(): number; + sendPluginCommand( + name: string, + data: string, + target?: PluginCommandTarget | number, + ): Promise; +} + +interface CommandCatalogEntry { + name: string; + args?: string; + descZh: string; + descEn: string; +} + +const CORE_COMMAND_CATALOG: readonly CommandCatalogEntry[] = [ + { name: "play", args: "<歌曲>", descZh: "点歌并立即播放", descEn: "Play song" }, + { name: "add", args: "<歌曲>", descZh: "添加到队列", descEn: "Add to queue" }, + { name: "search", args: "<关键词>", descZh: "搜索歌曲", descEn: "Search songs" }, + { name: "pause", descZh: "暂停播放", descEn: "Pause playback" }, + { name: "resume", descZh: "恢复播放", descEn: "Resume playback" }, + { name: "next", descZh: "下一首", descEn: "Next track" }, + { name: "prev", descZh: "上一首", descEn: "Previous track" }, + { name: "stop", descZh: "停止并清空队列", descEn: "Stop & clear" }, + { name: "now", descZh: "当前播放", descEn: "Current track" }, + { name: "queue", descZh: "查看队列", descEn: "Show queue" }, + { name: "vol", args: "<0-100>", descZh: "调节音量", descEn: "Set volume" }, + { name: "mode", args: "", descZh: "切换播放模式", descEn: "Set play mode" }, + { name: "clear", descZh: "清空队列", descEn: "Clear queue" }, + { name: "remove", args: "<序号>", descZh: "移除指定曲目", descEn: "Remove track" }, + { name: "playlist", args: "<歌单>", descZh: "导入歌单", descEn: "Load playlist" }, + { name: "help", descZh: "命令帮助", descEn: "Command help" }, +]; + +const CORE_COMMAND_ARGS_EN: Readonly> = { + play: "", + add: "", + search: "", + vol: "<0-100>", + mode: "", + remove: "", + playlist: "", +}; + +function loadAppVersion(): string { + try { + const raw = readFileSync(new URL("../../package.json", import.meta.url), "utf8"); + const parsed = JSON.parse(raw) as { version?: unknown }; + if (typeof parsed.version === "string" && parsed.version.trim().length > 0) { + return truncateChars(parsed.version.trim(), MAX_APP_META_CHARS); + } + } catch { + // Fallback below if package.json is unavailable in a custom bundle + } + return "0.1.0"; +} + +export const APP_VERSION = loadAppVersion(); + +function truncateChars(value: string, maxChars: number): string { + const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, ""); + const chars = Array.from(sanitized); + if (chars.length <= maxChars) return sanitized; + return chars.slice(0, maxChars).join(""); +} + +export function buildIdentityPayloadJson( + action: "announce" | "announce_ack", + commandPrefix?: string, + appVersion: string = APP_VERSION, +): string { + const normalizedPrefix = + typeof commandPrefix === "string" && commandPrefix.trim().length > 0 + ? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS) + : undefined; + + const payload: OpenProtocolIdentityPayload = { + v: OPEN_PROTOCOL_VERSION, + action, + client_type: "bot", + app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS), + app_version: truncateChars(appVersion, MAX_APP_META_CHARS), + capabilities: [...BOT_CAPABILITIES], + ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), + }; + + const json = JSON.stringify(payload); + if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) { + return json; + } + + delete payload.command_prefix; + return JSON.stringify(payload); +} + +export function buildOpenProtocolCommands(locale: "zh" | "en"): OpenProtocolCommandSpec[] { + return CORE_COMMAND_CATALOG.slice(0, MAX_COMMANDS).map((entry) => { + const rawArgs = locale === "zh" ? entry.args : (CORE_COMMAND_ARGS_EN[entry.name] ?? entry.args); + const rawDesc = locale === "zh" ? entry.descZh : entry.descEn; + const spec: OpenProtocolCommandSpec = { + name: truncateChars(entry.name, MAX_CMD_NAME_CHARS), + desc: truncateChars(rawDesc, MAX_CMD_DESC_CHARS), + }; + if (rawArgs) { + spec.args = truncateChars(rawArgs, MAX_CMD_ARGS_CHARS); + } + return spec; + }); +} + +export function buildCommandsListAckJson( + locale: "zh" | "en", + commandPrefix?: string, +): string { + const normalizedPrefix = + typeof commandPrefix === "string" && commandPrefix.trim().length > 0 + ? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS) + : undefined; + + const commands = buildOpenProtocolCommands(locale); + while (commands.length > 0) { + const payload: OpenProtocolCommandsListAckPayload = { + v: OPEN_PROTOCOL_VERSION, + action: "list_ack", + ...(normalizedPrefix ? { prefix: normalizedPrefix } : {}), + commands, + }; + const json = JSON.stringify(payload); + if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) { + return json; + } + commands.pop(); + } + + return JSON.stringify({ + v: OPEN_PROTOCOL_VERSION, + action: "list_ack", + ...(normalizedPrefix ? { prefix: normalizedPrefix } : {}), + commands: [], + } satisfies OpenProtocolCommandsListAckPayload); +} + +interface RateLimitToken { + key: string; + cooldownMs: number; + previousTimestamp: number | undefined; +} + +class AckRateLimiter { + private readonly lastSent = new Map(); + private tokens = ACK_GLOBAL_BURST; + private lastRefillMs: number | null = null; + + private refill(nowMs: number): void { + if (this.lastRefillMs === null) { + this.lastRefillMs = nowMs; + return; + } + const elapsedMs = Math.max(0, nowMs - this.lastRefillMs); + this.tokens = Math.min( + ACK_GLOBAL_BURST, + this.tokens + (elapsedMs / 1000) * ACK_GLOBAL_RATE_PER_SEC, + ); + this.lastRefillMs = nowMs; + } + + private prune(nowMs: number): void { + if (this.lastSent.size <= MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE) return; + const maxAgeMs = Math.max( + IDENTITY_ANNOUNCE_COOLDOWN_MS, + IDENTITY_QUERY_COOLDOWN_MS, + COMMANDS_LIST_REQ_COOLDOWN_MS, + ); + for (const [key, ts] of this.lastSent) { + if (nowMs - ts >= maxAgeMs) { + this.lastSent.delete(key); + } + } + } + + tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): RateLimitToken | null { + this.prune(nowMs); + const key = `${peerKey}:${actionKey}`; + const prev = this.lastSent.get(key); + if (prev !== undefined && nowMs - prev < cooldownMs) { + return null; + } + + this.refill(nowMs); + if (this.tokens < 1) { + return null; + } + + this.tokens -= 1; + this.lastSent.set(key, nowMs); + return { key, cooldownMs, previousTimestamp: prev }; + } + + rollback(token: RateLimitToken): void { + this.tokens = Math.min(ACK_GLOBAL_BURST, this.tokens + 1); + if (token.previousTimestamp === undefined) { + this.lastSent.delete(token.key); + } else { + this.lastSent.set(token.key, token.previousTimestamp); + } + } + + clear(): void { + this.lastSent.clear(); + this.tokens = ACK_GLOBAL_BURST; + this.lastRefillMs = null; + } +} + +export interface OpenProtocolManagerOptions { + transport: OpenProtocolTransport; + getConfig: () => OpenProtocolRuntimeConfig; + logger: Logger; + now?: () => number; +} + +export class OpenProtocolManager { + private readonly transport: OpenProtocolTransport; + private readonly getConfig: () => OpenProtocolRuntimeConfig; + private readonly logger: Logger; + private readonly now: () => number; + private readonly rateLimiter = new AckRateLimiter(); + + private generation = 0; + private announceSeq = 0; + private lastSuccessSeq = 0; + private lastAnnounceAttemptMs: number | null = null; + private trailingAnnounceTimer: ReturnType | null = null; + private retryAnnounceTimer: ReturnType | null = null; + + constructor(options: OpenProtocolManagerOptions) { + this.transport = options.transport; + this.getConfig = options.getConfig; + this.logger = options.logger; + this.now = options.now ?? (() => Date.now()); + } + + /** Reset timers and rate-limit state on disconnect or teardown. */ + reset(): void { + this.generation += 1; + this.announceSeq = 0; + this.lastSuccessSeq = 0; + this.lastAnnounceAttemptMs = null; + this.clearTimers(); + this.rateLimiter.clear(); + } + + /** Schedule or send a debounced channel broadcast announcing this bot's identity. */ + scheduleAnnounce(): void { + const clientId = this.transport.getClientId(); + if (clientId <= 0) return; + + const nowMs = this.now(); + if ( + this.lastAnnounceAttemptMs !== null && + nowMs - this.lastAnnounceAttemptMs < ANNOUNCE_DEBOUNCE_MS + ) { + if (!this.trailingAnnounceTimer) { + const delayMs = Math.max( + 0, + ANNOUNCE_DEBOUNCE_MS - (nowMs - this.lastAnnounceAttemptMs), + ); + const gen = this.generation; + this.trailingAnnounceTimer = setTimeout(() => { + this.trailingAnnounceTimer = null; + if (gen !== this.generation) return; + this.dispatchAnnounce(gen); + }, delayMs); + this.trailingAnnounceTimer.unref?.(); + } + return; + } + + this.clearTimers(); + this.dispatchAnnounce(this.generation); + } + + /** Handle an incoming TeamSpeak plugin command. */ + async handlePluginCommand(cmd: TS3PluginCommand): Promise { + if (cmd.name !== IDENTITY_PLUGIN && cmd.name !== COMMANDS_PLUGIN) { + return; + } + + const selfClientId = this.transport.getClientId(); + if (selfClientId <= 0 || cmd.invokerId === selfClientId) { + return; + } + + let parsed: Record; + try { + const value = JSON.parse(cmd.data) as unknown; + if (!value || typeof value !== "object" || Array.isArray(value)) { + return; + } + parsed = value as Record; + } catch { + this.logger.debug( + { name: cmd.name, invokerId: cmd.invokerId }, + "Ignoring malformed OpenProtocol JSON payload", + ); + return; + } + + if (parsed.v !== OPEN_PROTOCOL_VERSION || typeof parsed.action !== "string") { + return; + } + + const peerKey = cmd.invokerUid.trim() || String(cmd.invokerId); + + if (cmd.name === IDENTITY_PLUGIN) { + await this.handleIdentityAction(parsed.action, peerKey, cmd.invokerId); + return; + } + + if (cmd.name === COMMANDS_PLUGIN) { + await this.handleCommandsAction(parsed.action, peerKey, cmd.invokerId); + } + } + + private async handleIdentityAction( + action: string, + peerKey: string, + invokerId: number, + ): Promise { + let cooldownMs: number; + if (action === "announce") { + cooldownMs = IDENTITY_ANNOUNCE_COOLDOWN_MS; + } else if (action === "query") { + cooldownMs = IDENTITY_QUERY_COOLDOWN_MS; + } else { + return; + } + + const token = this.rateLimiter.tryAcquire( + peerKey, + `${IDENTITY_PLUGIN}:${action}`, + cooldownMs, + this.now(), + ); + if (!token) return; + + const { commandPrefix } = this.getConfig(); + const payload = buildIdentityPayloadJson("announce_ack", commandPrefix); + await this.sendAck(IDENTITY_PLUGIN, payload, invokerId, token); + } + + private async handleCommandsAction( + action: string, + peerKey: string, + invokerId: number, + ): Promise { + if (action !== "list_req") return; + + const token = this.rateLimiter.tryAcquire( + peerKey, + `${COMMANDS_PLUGIN}:list_req`, + COMMANDS_LIST_REQ_COOLDOWN_MS, + this.now(), + ); + if (!token) return; + + const { locale, commandPrefix } = this.getConfig(); + const payload = buildCommandsListAckJson(locale, commandPrefix); + await this.sendAck(COMMANDS_PLUGIN, payload, invokerId, token); + } + + private async sendAck( + pluginName: string, + payload: string, + invokerId: number, + token: RateLimitToken, + ): Promise { + if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) { + this.rateLimiter.rollback(token); + this.logger.debug({ pluginName }, "OpenProtocol payload exceeded size limit"); + return; + } + + const gen = this.generation; + try { + await this.transport.sendPluginCommand(pluginName, payload, invokerId); + } catch (err) { + if (gen === this.generation) { + this.rateLimiter.rollback(token); + } + this.logger.debug( + { err, pluginName, invokerId }, + "Failed to send OpenProtocol response", + ); + } + } + + private dispatchAnnounce(expectedGen: number): void { + if (expectedGen !== this.generation || this.transport.getClientId() <= 0) { + return; + } + + this.lastAnnounceAttemptMs = this.now(); + const seq = ++this.announceSeq; + const { commandPrefix } = this.getConfig(); + const payload = buildIdentityPayloadJson("announce", commandPrefix); + + if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) { + this.logger.debug("OpenProtocol announce payload exceeded size limit"); + return; + } + + this.transport + .sendPluginCommand(IDENTITY_PLUGIN, payload, "channel") + .then(() => { + if (expectedGen !== this.generation) return; + this.lastSuccessSeq = Math.max(this.lastSuccessSeq, seq); + }) + .catch((err: unknown) => { + if (expectedGen !== this.generation) return; + this.logger.debug({ err }, "OpenProtocol announce broadcast failed"); + this.scheduleAnnounceRetry(expectedGen, seq); + }); + } + + private scheduleAnnounceRetry(expectedGen: number, failedSeq: number): void { + if (this.retryAnnounceTimer) { + clearTimeout(this.retryAnnounceTimer); + this.retryAnnounceTimer = null; + } + + this.retryAnnounceTimer = setTimeout(() => { + this.retryAnnounceTimer = null; + if ( + expectedGen !== this.generation || + this.lastSuccessSeq >= failedSeq || + this.transport.getClientId() <= 0 + ) { + return; + } + const retrySeq = ++this.announceSeq; + const { commandPrefix } = this.getConfig(); + const payload = buildIdentityPayloadJson("announce", commandPrefix); + this.lastAnnounceAttemptMs = this.now(); + this.transport + .sendPluginCommand(IDENTITY_PLUGIN, payload, "channel") + .then(() => { + if (expectedGen !== this.generation) return; + this.lastSuccessSeq = Math.max(this.lastSuccessSeq, retrySeq); + }) + .catch((err: unknown) => { + if (expectedGen !== this.generation) return; + this.logger.debug({ err }, "OpenProtocol announce retry failed"); + }); + }, ANNOUNCE_RETRY_DELAY_MS); + this.retryAnnounceTimer.unref?.(); + } + + private clearTimers(): void { + if (this.trailingAnnounceTimer) { + clearTimeout(this.trailingAnnounceTimer); + this.trailingAnnounceTimer = null; + } + if (this.retryAnnounceTimer) { + clearTimeout(this.retryAnnounceTimer); + this.retryAnnounceTimer = null; + } + } +} diff --git a/src/ts-protocol/text-message.test.ts b/src/ts-protocol/text-message.test.ts index e83e30b..8c0ceb5 100644 --- a/src/ts-protocol/text-message.test.ts +++ b/src/ts-protocol/text-message.test.ts @@ -1,16 +1,21 @@ import { describe, it, expect } from "vitest"; import { toTS3TextMessage } from "./client.js"; -import type { TextMessage } from "@honeybbq/teamspeak-client"; +import { + asClientID, + asServerGroupID, + asUID, + type TextMessageEvent, +} from "@honeybbq/teamspeak"; -function makeMsg(over: Partial = {}): TextMessage { +function makeMsg(over: Partial = {}): TextMessageEvent { return { invokerName: "Alice", - invokerUID: "uid-abc", + invokerUID: asUID("uid-abc"), message: "!stop", - invokerGroups: ["6", "8"], + invokerGroups: [asServerGroupID(6n), asServerGroupID(8n)], targetMode: 2, - targetID: 0n, - invokerID: 5, + targetID: asClientID(0), + invokerID: asClientID(5), ...over, }; } @@ -26,18 +31,20 @@ describe("toTS3TextMessage", () => { }); it("preserves the sender's server groups", () => { - expect(toTS3TextMessage(makeMsg({ invokerGroups: ["6"] })).invokerGroups).toEqual(["6"]); + expect( + toTS3TextMessage(makeMsg({ invokerGroups: [asServerGroupID(6n)] })).invokerGroups, + ).toEqual(["6"]); }); it("defaults missing invokerGroups to an empty array", () => { const partial = { invokerName: "Bob", - invokerUID: "u", + invokerUID: asUID("u"), message: "!stop", targetMode: 1, - targetID: 0n, - invokerID: 7, - } as unknown as TextMessage; + targetID: asClientID(0), + invokerID: asClientID(7), + } as unknown as TextMessageEvent; expect(toTS3TextMessage(partial).invokerGroups).toEqual([]); }); }); diff --git a/src/ts-protocol/voice-endpoint.test.ts b/src/ts-protocol/voice-endpoint.test.ts index 52dfad3..7a2b7a9 100644 --- a/src/ts-protocol/voice-endpoint.test.ts +++ b/src/ts-protocol/voice-endpoint.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak-client"; +import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak/client"; import { TrackingVoiceEndpointResolver } from "./voice-endpoint.js"; function result(addr: string): ResolvedAddr { diff --git a/src/ts-protocol/voice-endpoint.ts b/src/ts-protocol/voice-endpoint.ts index 3f92fed..aaf0bd4 100644 --- a/src/ts-protocol/voice-endpoint.ts +++ b/src/ts-protocol/voice-endpoint.ts @@ -1,10 +1,10 @@ import { lookup } from "node:dns/promises"; import { isIP } from "node:net"; -import { Resolver } from "@honeybbq/teamspeak-client/discovery"; +import { Resolver } from "@honeybbq/teamspeak/client"; import type { AddrResolver, ResolvedAddr, -} from "@honeybbq/teamspeak-client"; +} from "@honeybbq/teamspeak/client"; export interface ResolvedVoiceEndpoint { host: string; @@ -66,9 +66,12 @@ export class TrackingVoiceEndpointResolver implements AddrResolver { private readonly resolveHost: ResolveIpv4 = resolveIpv4, ) {} - async resolve(input: string, signal?: AbortSignal): Promise { + async resolve( + input: string, + options?: { readonly signal?: AbortSignal }, + ): Promise { this.endpoint = null; - const candidates = await this.delegate.resolve(input, signal); + const candidates = await this.delegate.resolve(input, options); const selected = candidates[0]; if (!selected) return candidates; diff --git a/test-visible.ts b/test-visible.ts index c6a7b19..c4f0e3e 100644 --- a/test-visible.ts +++ b/test-visible.ts @@ -10,12 +10,12 @@ import { QQMusicProvider } from "./src/music/qq.js"; import { BotManager } from "./src/bot/manager.js"; import { createWebServer } from "./src/web/server.js"; import { - Client as TS3FullClient, - generateIdentity, listClients, - sendTextMessage, - consoleLogger, -} from "@honeybbq/teamspeak-client"; +} from "@honeybbq/teamspeak"; +import { + Client as TS3FullClient, + generateIdentitySync, +} from "@honeybbq/teamspeak/client"; const logger = createLogger(); let passed = 0; @@ -83,7 +83,7 @@ async function main() { // ═══ Test 2: Verify bot is visible using a second client ═══ log("\n═══ Test 2: Verify Bot Visibility ═══"); - const verifyIdentity = generateIdentity(8); + const verifyIdentity = generateIdentitySync(8); const verifyClient = new TS3FullClient( verifyIdentity, "127.0.0.1:9987", @@ -92,8 +92,7 @@ async function main() { ); await verifyClient.connect(); - await verifyClient.waitConnected(); - log(` Verification client connected (id=${verifyClient.clientID()})`); + log(` Verification client connected (id=${verifyClient.clientID})`); try { const clients = await listClients(verifyClient); From 69b311283a57f51eeb515e99af3d3be83c32b566 Mon Sep 17 00:00:00 2001 From: Dr1mH4X <102709153+Dr1mH4X@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:14:05 +0800 Subject: [PATCH 2/5] fix(open-protocol): restore prefix-only command parsing and declare command_prefix in list_ack --- src/bot/commands.test.ts | 29 ------------------------ src/bot/commands.ts | 17 -------------- src/bot/instance.test.ts | 15 ++++++++----- src/bot/instance.ts | 4 ++-- src/ts-protocol/open-protocol.test.ts | 21 ++++++------------ src/ts-protocol/open-protocol.ts | 32 +++++++-------------------- 6 files changed, 26 insertions(+), 92 deletions(-) diff --git a/src/bot/commands.test.ts b/src/bot/commands.test.ts index 729bdf8..e4d5493 100644 --- a/src/bot/commands.test.ts +++ b/src/bot/commands.test.ts @@ -1,7 +1,6 @@ import { describe, it, expect } from "vitest"; import { parseCommand, - parseCommandWithFallback, canRunCommand, isAdminCommand, } from "./commands.js"; @@ -98,31 +97,3 @@ describe("canRunCommand", () => { expect(canRunCommand("clear", [], [6])).toBe(false); }); }); - -describe("parseCommandWithFallback", () => { - it("accepts both the configured primary prefix and slash fallback", () => { - expect(parseCommandWithFallback("!play 晴天", "!")).toEqual({ - name: "play", - args: "晴天", - rawArgs: ["晴天"], - flags: new Set(), - }); - expect(parseCommandWithFallback("/play 晴天", "!")).toEqual({ - name: "play", - args: "晴天", - rawArgs: ["晴天"], - flags: new Set(), - }); - }); - - it("applies aliases on slash fallback and ignores bare slash", () => { - expect(parseCommandWithFallback("/p 稻香", "!", { p: "play" })).toEqual({ - name: "play", - args: "稻香", - rawArgs: ["稻香"], - flags: new Set(), - }); - expect(parseCommandWithFallback("/", "!")).toBeNull(); - expect(parseCommandWithFallback("plain chat", "!")).toBeNull(); - }); -}); diff --git a/src/bot/commands.ts b/src/bot/commands.ts index 7558432..41e2209 100644 --- a/src/bot/commands.ts +++ b/src/bot/commands.ts @@ -55,23 +55,6 @@ export function parseCommand( }; } -export function parseCommandWithFallback( - message: string, - primaryPrefix: string, - aliases: Record = {}, - fallbackPrefixes: readonly string[] = ["/"], -): ParsedCommand | null { - const direct = parseCommand(message, primaryPrefix, aliases); - if (direct) return direct; - - for (const fallback of fallbackPrefixes) { - if (!fallback || fallback === primaryPrefix) continue; - const parsed = parseCommand(message, fallback, aliases); - if (parsed) return parsed; - } - return null; -} - export function isAdminCommand(commandName: string): boolean { return ADMIN_COMMANDS.has(commandName); } diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index e0752b5..cd1e877 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1949,18 +1949,21 @@ describe("BotInstance trackEnd — stale playback sessions", () => { }); }); -describe("BotInstance — OpenProtocol & slash command routing", () => { - it("accepts / commands when commandPrefix is '!' and routes private replies to invokerId", async () => { +describe("BotInstance — OpenProtocol & command routing", () => { + it("ignores / commands when commandPrefix is '!' and routes private replies to invokerId", async () => { const ctx = makeGateCtx({ adminGroups: [] }); ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) => `ok:${parsed.name}:${parsed.args}`, ); + await handleTextMessage.call(ctx, makeMsg("/play 晴天")); + expect(ctx.executeCommand).not.toHaveBeenCalled(); + const dm: TS3TextMessage = { invokerName: "FlSpeakUser", invokerId: "12", invokerUid: "uid-fl", - message: "/play 晴天", + message: "!play 晴天", targetMode: 1, invokerGroups: [], }; @@ -1971,7 +1974,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => { expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12); ctx.tsClient.sendTextMessage.mockClear(); - await handleTextMessage.call(ctx, makeMsg("/now")); + await handleTextMessage.call(ctx, makeMsg("!now")); expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:"); }); @@ -1981,7 +1984,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => { invokerName: "Guest", invokerId: "22", invokerUid: "uid-guest", - message: "/stop", + message: "!stop", targetMode: 1, invokerGroups: [], }; @@ -1993,7 +1996,7 @@ describe("BotInstance — OpenProtocol & slash command routing", () => { okCtx.executeCommand = vi.fn(async () => { throw new Error("boom"); }); - await handleTextMessage.call(okCtx, { ...dmStop, message: "/play x" }); + await handleTextMessage.call(okCtx, { ...dmStop, message: "!play x" }); expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22); }); diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 2449f9d..232cd53 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -12,7 +12,7 @@ import { AudioPlayer } from "../audio/player.js"; import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js"; import type { MusicProvider, Platform, Song } from "../music/provider.js"; import { - parseCommandWithFallback, + parseCommand, canRunCommand, type ParsedCommand, } from "./commands.js"; @@ -823,7 +823,7 @@ export class BotInstance extends EventEmitter { } private async handleTextMessage(msg: TS3TextMessage): Promise { - const parsed = parseCommandWithFallback( + const parsed = parseCommand( msg.message, this.config.commandPrefix, this.config.commandAliases, diff --git a/src/ts-protocol/open-protocol.test.ts b/src/ts-protocol/open-protocol.test.ts index bffd5ec..da17e5b 100644 --- a/src/ts-protocol/open-protocol.test.ts +++ b/src/ts-protocol/open-protocol.test.ts @@ -39,8 +39,8 @@ function makeCmd(overrides: Partial = {}): TS3PluginCommand { } describe("OpenProtocol payload builders", () => { - it("builds valid v1 identity payloads with package version and command_prefix under 1024 bytes", () => { - const raw = buildIdentityPayloadJson("announce", "!"); + it("builds valid v1 identity payloads with package version under 1024 bytes", () => { + const raw = buildIdentityPayloadJson("announce"); expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); expect(JSON.parse(raw)).toEqual({ v: OPEN_PROTOCOL_VERSION, @@ -49,18 +49,11 @@ describe("OpenProtocol payload builders", () => { app_name: APP_NAME, app_version: APP_VERSION, capabilities: [...BOT_CAPABILITIES], - command_prefix: "!", }); - const ack = JSON.parse(buildIdentityPayloadJson("announce_ack", "?")); + const ack = JSON.parse(buildIdentityPayloadJson("announce_ack")); expect(ack.action).toBe("announce_ack"); - expect(ack.command_prefix).toBe("?"); - }); - - it("drops command_prefix if an oversized value would exceed 1024 bytes", () => { - const raw = buildIdentityPayloadJson("announce", "p".repeat(1200)); - expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); - expect(JSON.parse(raw).app_name).toBe(APP_NAME); + expect(ack.command_prefix).toBeUndefined(); }); it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => { @@ -82,12 +75,12 @@ describe("OpenProtocol payload builders", () => { const parsed = JSON.parse(raw) as { v: number; action: string; - prefix: string; + command_prefix: string; commands: unknown[]; }; expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION); expect(parsed.action).toBe("list_ack"); - expect(parsed.prefix).toBe("!"); + expect(parsed.command_prefix).toBe("!"); expect(parsed.commands.length).toBe(cmds.length); } }); @@ -184,7 +177,7 @@ describe("OpenProtocolManager", () => { const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string); expect(payload.v).toBe(1); expect(payload.action).toBe("list_ack"); - expect(payload.prefix).toBe("?"); + expect(payload.command_prefix).toBe("?"); expect(payload.commands[0]).toEqual({ name: "play", args: "", desc: "Play song" }); // Cooldown falls back to invokerId when invokerUid is empty diff --git a/src/ts-protocol/open-protocol.ts b/src/ts-protocol/open-protocol.ts index b7c5722..150e3de 100644 --- a/src/ts-protocol/open-protocol.ts +++ b/src/ts-protocol/open-protocol.ts @@ -21,6 +21,7 @@ export const ACK_GLOBAL_BURST = 4; export const ACK_GLOBAL_RATE_PER_SEC = 2; export const MAX_COMMANDS = 16; +export const MAX_CMD_PREFIX_CHARS = 8; export const MAX_CMD_NAME_CHARS = 24; export const MAX_CMD_ARGS_CHARS = 32; export const MAX_CMD_DESC_CHARS = 64; @@ -40,13 +41,12 @@ export interface OpenProtocolIdentityPayload { app_name: string; app_version: string; capabilities: string[]; - command_prefix?: string; } export interface OpenProtocolCommandsListAckPayload { v: 1; action: "list_ack"; - prefix?: string; + command_prefix?: string; commands: OpenProtocolCommandSpec[]; } @@ -124,14 +124,8 @@ function truncateChars(value: string, maxChars: number): string { export function buildIdentityPayloadJson( action: "announce" | "announce_ack", - commandPrefix?: string, appVersion: string = APP_VERSION, ): string { - const normalizedPrefix = - typeof commandPrefix === "string" && commandPrefix.trim().length > 0 - ? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS) - : undefined; - const payload: OpenProtocolIdentityPayload = { v: OPEN_PROTOCOL_VERSION, action, @@ -139,15 +133,8 @@ export function buildIdentityPayloadJson( app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS), app_version: truncateChars(appVersion, MAX_APP_META_CHARS), capabilities: [...BOT_CAPABILITIES], - ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), }; - const json = JSON.stringify(payload); - if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) { - return json; - } - - delete payload.command_prefix; return JSON.stringify(payload); } @@ -172,7 +159,7 @@ export function buildCommandsListAckJson( ): string { const normalizedPrefix = typeof commandPrefix === "string" && commandPrefix.trim().length > 0 - ? truncateChars(commandPrefix.trim(), MAX_CMD_NAME_CHARS) + ? truncateChars(commandPrefix.trim(), MAX_CMD_PREFIX_CHARS) : undefined; const commands = buildOpenProtocolCommands(locale); @@ -180,7 +167,7 @@ export function buildCommandsListAckJson( const payload: OpenProtocolCommandsListAckPayload = { v: OPEN_PROTOCOL_VERSION, action: "list_ack", - ...(normalizedPrefix ? { prefix: normalizedPrefix } : {}), + ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), commands, }; const json = JSON.stringify(payload); @@ -193,7 +180,7 @@ export function buildCommandsListAckJson( return JSON.stringify({ v: OPEN_PROTOCOL_VERSION, action: "list_ack", - ...(normalizedPrefix ? { prefix: normalizedPrefix } : {}), + ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), commands: [], } satisfies OpenProtocolCommandsListAckPayload); } @@ -402,8 +389,7 @@ export class OpenProtocolManager { ); if (!token) return; - const { commandPrefix } = this.getConfig(); - const payload = buildIdentityPayloadJson("announce_ack", commandPrefix); + const payload = buildIdentityPayloadJson("announce_ack"); await this.sendAck(IDENTITY_PLUGIN, payload, invokerId, token); } @@ -460,8 +446,7 @@ export class OpenProtocolManager { this.lastAnnounceAttemptMs = this.now(); const seq = ++this.announceSeq; - const { commandPrefix } = this.getConfig(); - const payload = buildIdentityPayloadJson("announce", commandPrefix); + const payload = buildIdentityPayloadJson("announce"); if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) { this.logger.debug("OpenProtocol announce payload exceeded size limit"); @@ -497,8 +482,7 @@ export class OpenProtocolManager { return; } const retrySeq = ++this.announceSeq; - const { commandPrefix } = this.getConfig(); - const payload = buildIdentityPayloadJson("announce", commandPrefix); + const payload = buildIdentityPayloadJson("announce"); this.lastAnnounceAttemptMs = this.now(); this.transport .sendPluginCommand(IDENTITY_PLUGIN, payload, "channel") From 066f12d91fdc9705aca53f51c668ac6f2cdd7158 Mon Sep 17 00:00:00 2001 From: Dr1mH4X <102709153+Dr1mH4X@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:20:00 +0800 Subject: [PATCH 3/5] test(open-protocol): remove leftover slash assertion and formatting diff for PR --- src/bot/commands.test.ts | 6 +----- src/bot/instance.test.ts | 5 +---- src/bot/instance.ts | 2 +- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/bot/commands.test.ts b/src/bot/commands.test.ts index e4d5493..8a6fb41 100644 --- a/src/bot/commands.test.ts +++ b/src/bot/commands.test.ts @@ -1,9 +1,5 @@ import { describe, it, expect } from "vitest"; -import { - parseCommand, - canRunCommand, - isAdminCommand, -} from "./commands.js"; +import { parseCommand, canRunCommand, isAdminCommand } from "./commands.js"; describe("Command Parser", () => { it("parses simple command", () => { diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index cd1e877..5b02d0f 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1950,15 +1950,12 @@ describe("BotInstance trackEnd — stale playback sessions", () => { }); describe("BotInstance — OpenProtocol & command routing", () => { - it("ignores / commands when commandPrefix is '!' and routes private replies to invokerId", async () => { + it("routes private DM command replies to invokerId and channel replies to the channel", async () => { const ctx = makeGateCtx({ adminGroups: [] }); ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) => `ok:${parsed.name}:${parsed.args}`, ); - await handleTextMessage.call(ctx, makeMsg("/play 晴天")); - expect(ctx.executeCommand).not.toHaveBeenCalled(); - const dm: TS3TextMessage = { invokerName: "FlSpeakUser", invokerId: "12", diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 232cd53..484c408 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -826,7 +826,7 @@ export class BotInstance extends EventEmitter { const parsed = parseCommand( msg.message, this.config.commandPrefix, - this.config.commandAliases, + this.config.commandAliases ); if (!parsed) return; From 4f026aa65f116ca3fafa951590b17dc42012fe51 Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:47:49 +0800 Subject: [PATCH 4/5] fix(open-protocol): verify advertised commands and bound replies --- README.md | 4 +- src/ts-protocol/open-protocol.test.ts | 54 +++++++++++++--- src/ts-protocol/open-protocol.ts | 93 ++++++++++----------------- 3 files changed, 81 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 6544b48..5aa3a78 100644 --- a/README.md +++ b/README.md @@ -583,7 +583,7 @@ teamspeak-music-bot/ | **后端框架** | Express 4, WebSocket (ws) | | **数据库** | better-sqlite3 (SQLite) | | **音频处理** | FFmpeg (ffmpeg-static 内置), @discordjs/opus | -| **TS 协议** | @honeybbq/teamspeak-client(完整客户端协议)+ 自研 TS6 协议适配层 | +| **TS 协议** | @honeybbq/teamspeak(TS3 / TS6 完整客户端协议,支持 OpenProtocol v1) | | **Jellyfin** | Jellyfin REST API(可选音源,直连,无额外 npm 依赖) | | **网易云 API** | NeteaseCloudMusicApi | | **QQ 音乐 API** | @sansenjian/qq-music-api(锁定 `~2.4.0`,需 Node ≥ 20.17) | @@ -1246,7 +1246,7 @@ A:本项目内置 `/login` 限流(每 IP 每分钟 5 次),但生产部 | [NeteaseCloudMusicApi](https://github.com/Binaryify/NeteaseCloudMusicApi) | 网易云音乐 API 项目 | | [QQMusicApi](https://github.com/jsososo/QQMusicApi) | QQ 音乐 API 项目 | | [@sansenjian/qq-music-api](https://github.com/sansenjian/qq-music-api) | QQ 音乐 API 活跃维护版本 | -| [@honeybbq/teamspeak-client](https://www.npmjs.com/package/@honeybbq/teamspeak-client) | TS3 完整客户端协议实现 | +| [@honeybbq/teamspeak](https://www.npmjs.com/package/@honeybbq/teamspeak) | TS3 / TS6 完整客户端协议实现 | | [bilibili-API-collect](https://github.com/SocialSisterYi/bilibili-API-collect) | 哔哩哔哩 API 文档 | | [MakcRe/KuGouMusicApi](https://github.com/MakcRe/KuGouMusicApi) | 酷狗音乐 API 参考(请求签名 / KRC 歌词解码 / 设备注册移植来源,MIT 许可) | diff --git a/src/ts-protocol/open-protocol.test.ts b/src/ts-protocol/open-protocol.test.ts index da17e5b..9a3d6f3 100644 --- a/src/ts-protocol/open-protocol.test.ts +++ b/src/ts-protocol/open-protocol.test.ts @@ -56,6 +56,13 @@ describe("OpenProtocol payload builders", () => { expect(ack.command_prefix).toBeUndefined(); }); + it("advertises only playback mode values supported by the bot", () => { + for (const locale of ["zh", "en"] as const) { + expect(buildOpenProtocolCommands(locale).find(({ name }) => name === "mode")?.args) + .toBe(""); + } + }); + it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => { for (const locale of ["zh", "en"] as const) { const cmds = buildOpenProtocolCommands(locale); @@ -71,6 +78,7 @@ describe("OpenProtocol payload builders", () => { } const raw = buildCommandsListAckJson(locale, "!"); + if (raw === null) throw new Error("Expected a command list for a valid prefix"); expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES); const parsed = JSON.parse(raw) as { v: number; @@ -193,7 +201,27 @@ describe("OpenProtocolManager", () => { expect(sendPluginCommand).toHaveBeenCalledTimes(1); }); - it("enforces global token bucket across peers and rolls back cooldown/token on send failure", async () => { + it("does not advertise command discovery with a prefix too long to send unchanged", async () => { + config.commandPrefix = "musicbot!!"; + manager.scheduleAnnounce(); + await manager.handlePluginCommand(makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + })); + + expect(sendPluginCommand).toHaveBeenCalledTimes(1); + const identity = JSON.parse(sendPluginCommand.mock.calls[0][1] as string); + expect(identity.capabilities).not.toContain("chat:slash_commands"); + }); + + it("ignores inbound payloads beyond the protocol byte limit", async () => { + await manager.handlePluginCommand(makeCmd({ + data: JSON.stringify({ v: 1, action: "query", padding: "中".repeat(MAX_PAYLOAD_BYTES / 2) }), + })); + expect(sendPluginCommand).not.toHaveBeenCalled(); + }); + + it("enforces global and peer cooldowns when sending replies fails", async () => { for (let i = 1; i <= ACK_GLOBAL_BURST; i++) { await manager.handlePluginCommand( makeCmd({ @@ -230,15 +258,21 @@ describe("OpenProtocolManager", () => { ); expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1); - // Because send failed, both peer-99 cooldown and global token were rolled back - await manager.handlePluginCommand( - makeCmd({ - name: COMMANDS_PLUGIN, - data: JSON.stringify({ v: 1, action: "list_req" }), - invokerId: 99, - invokerUid: "peer-99", - }), - ); + // A rejected reply still consumes the global allowance for other peers. + const otherRequest = makeCmd({ + name: COMMANDS_PLUGIN, + data: JSON.stringify({ v: 1, action: "list_req" }), + invokerId: 98, + invokerUid: "peer-98", + }); + await manager.handlePluginCommand(otherRequest); + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1); + + // Once a global slot refills, the original peer is still cooling down. + nowMs += 500; + await manager.handlePluginCommand({ ...otherRequest, invokerId: 99, invokerUid: "peer-99" }); + expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1); + await manager.handlePluginCommand(otherRequest); expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 2); }); diff --git a/src/ts-protocol/open-protocol.ts b/src/ts-protocol/open-protocol.ts index 150e3de..128ceaf 100644 --- a/src/ts-protocol/open-protocol.ts +++ b/src/ts-protocol/open-protocol.ts @@ -1,4 +1,5 @@ import { readFileSync } from "node:fs"; +import { PlayMode } from "../audio/queue.js"; import type { Logger } from "../logger.js"; import type { PluginCommandTarget, TS3PluginCommand } from "./client.js"; @@ -46,7 +47,7 @@ export interface OpenProtocolIdentityPayload { export interface OpenProtocolCommandsListAckPayload { v: 1; action: "list_ack"; - command_prefix?: string; + command_prefix: string; commands: OpenProtocolCommandSpec[]; } @@ -83,7 +84,7 @@ const CORE_COMMAND_CATALOG: readonly CommandCatalogEntry[] = [ { name: "now", descZh: "当前播放", descEn: "Current track" }, { name: "queue", descZh: "查看队列", descEn: "Show queue" }, { name: "vol", args: "<0-100>", descZh: "调节音量", descEn: "Set volume" }, - { name: "mode", args: "", descZh: "切换播放模式", descEn: "Set play mode" }, + { name: "mode", args: `<${Object.values(PlayMode).join("|")}>`, descZh: "切换播放模式", descEn: "Set play mode" }, { name: "clear", descZh: "清空队列", descEn: "Clear queue" }, { name: "remove", args: "<序号>", descZh: "移除指定曲目", descEn: "Remove track" }, { name: "playlist", args: "<歌单>", descZh: "导入歌单", descEn: "Load playlist" }, @@ -95,7 +96,6 @@ const CORE_COMMAND_ARGS_EN: Readonly> = { add: "", search: "", vol: "<0-100>", - mode: "", remove: "", playlist: "", }; @@ -122,9 +122,17 @@ function truncateChars(value: string, maxChars: number): string { return chars.slice(0, maxChars).join(""); } +function isDiscoverablePrefix(prefix: string): boolean { + return typeof prefix === "string" + && prefix.length > 0 + && prefix.trim() === prefix + && truncateChars(prefix, MAX_CMD_PREFIX_CHARS) === prefix; +} + export function buildIdentityPayloadJson( action: "announce" | "announce_ack", appVersion: string = APP_VERSION, + commandPrefix = "!", ): string { const payload: OpenProtocolIdentityPayload = { v: OPEN_PROTOCOL_VERSION, @@ -132,7 +140,7 @@ export function buildIdentityPayloadJson( client_type: "bot", app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS), app_version: truncateChars(appVersion, MAX_APP_META_CHARS), - capabilities: [...BOT_CAPABILITIES], + capabilities: isDiscoverablePrefix(commandPrefix) ? [...BOT_CAPABILITIES] : [], }; return JSON.stringify(payload); @@ -155,19 +163,16 @@ export function buildOpenProtocolCommands(locale: "zh" | "en"): OpenProtocolComm export function buildCommandsListAckJson( locale: "zh" | "en", - commandPrefix?: string, -): string { - const normalizedPrefix = - typeof commandPrefix === "string" && commandPrefix.trim().length > 0 - ? truncateChars(commandPrefix.trim(), MAX_CMD_PREFIX_CHARS) - : undefined; + commandPrefix: string, +): string | null { + if (!isDiscoverablePrefix(commandPrefix)) return null; const commands = buildOpenProtocolCommands(locale); while (commands.length > 0) { const payload: OpenProtocolCommandsListAckPayload = { v: OPEN_PROTOCOL_VERSION, action: "list_ack", - ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), + command_prefix: commandPrefix, commands, }; const json = JSON.stringify(payload); @@ -180,17 +185,11 @@ export function buildCommandsListAckJson( return JSON.stringify({ v: OPEN_PROTOCOL_VERSION, action: "list_ack", - ...(normalizedPrefix ? { command_prefix: normalizedPrefix } : {}), + command_prefix: commandPrefix, commands: [], } satisfies OpenProtocolCommandsListAckPayload); } -interface RateLimitToken { - key: string; - cooldownMs: number; - previousTimestamp: number | undefined; -} - class AckRateLimiter { private readonly lastSent = new Map(); private tokens = ACK_GLOBAL_BURST; @@ -223,31 +222,22 @@ class AckRateLimiter { } } - tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): RateLimitToken | null { + tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): boolean { this.prune(nowMs); const key = `${peerKey}:${actionKey}`; const prev = this.lastSent.get(key); if (prev !== undefined && nowMs - prev < cooldownMs) { - return null; + return false; } this.refill(nowMs); if (this.tokens < 1) { - return null; + return false; } this.tokens -= 1; this.lastSent.set(key, nowMs); - return { key, cooldownMs, previousTimestamp: prev }; - } - - rollback(token: RateLimitToken): void { - this.tokens = Math.min(ACK_GLOBAL_BURST, this.tokens + 1); - if (token.previousTimestamp === undefined) { - this.lastSent.delete(token.key); - } else { - this.lastSent.set(token.key, token.previousTimestamp); - } + return true; } clear(): void { @@ -332,7 +322,8 @@ export class OpenProtocolManager { } const selfClientId = this.transport.getClientId(); - if (selfClientId <= 0 || cmd.invokerId === selfClientId) { + if (selfClientId <= 0 || cmd.invokerId === selfClientId || cmd.invokerId <= 0 + || Buffer.byteLength(cmd.data, "utf8") >= MAX_PAYLOAD_BYTES) { return; } @@ -381,16 +372,12 @@ export class OpenProtocolManager { return; } - const token = this.rateLimiter.tryAcquire( - peerKey, - `${IDENTITY_PLUGIN}:${action}`, - cooldownMs, - this.now(), - ); - if (!token) return; + if (!this.rateLimiter.tryAcquire( + peerKey, `${IDENTITY_PLUGIN}:${action}`, cooldownMs, this.now(), + )) return; - const payload = buildIdentityPayloadJson("announce_ack"); - await this.sendAck(IDENTITY_PLUGIN, payload, invokerId, token); + const payload = buildIdentityPayloadJson("announce_ack", APP_VERSION, this.getConfig().commandPrefix); + await this.sendAck(IDENTITY_PLUGIN, payload, invokerId); } private async handleCommandsAction( @@ -400,38 +387,28 @@ export class OpenProtocolManager { ): Promise { if (action !== "list_req") return; - const token = this.rateLimiter.tryAcquire( - peerKey, - `${COMMANDS_PLUGIN}:list_req`, - COMMANDS_LIST_REQ_COOLDOWN_MS, - this.now(), - ); - if (!token) return; - const { locale, commandPrefix } = this.getConfig(); + if (!isDiscoverablePrefix(commandPrefix) || !this.rateLimiter.tryAcquire( + peerKey, `${COMMANDS_PLUGIN}:list_req`, COMMANDS_LIST_REQ_COOLDOWN_MS, this.now(), + )) return; + const payload = buildCommandsListAckJson(locale, commandPrefix); - await this.sendAck(COMMANDS_PLUGIN, payload, invokerId, token); + if (payload !== null) await this.sendAck(COMMANDS_PLUGIN, payload, invokerId); } private async sendAck( pluginName: string, payload: string, invokerId: number, - token: RateLimitToken, ): Promise { if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) { - this.rateLimiter.rollback(token); this.logger.debug({ pluginName }, "OpenProtocol payload exceeded size limit"); return; } - const gen = this.generation; try { await this.transport.sendPluginCommand(pluginName, payload, invokerId); } catch (err) { - if (gen === this.generation) { - this.rateLimiter.rollback(token); - } this.logger.debug( { err, pluginName, invokerId }, "Failed to send OpenProtocol response", @@ -446,7 +423,7 @@ export class OpenProtocolManager { this.lastAnnounceAttemptMs = this.now(); const seq = ++this.announceSeq; - const payload = buildIdentityPayloadJson("announce"); + const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix); if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) { this.logger.debug("OpenProtocol announce payload exceeded size limit"); @@ -482,7 +459,7 @@ export class OpenProtocolManager { return; } const retrySeq = ++this.announceSeq; - const payload = buildIdentityPayloadJson("announce"); + const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix); this.lastAnnounceAttemptMs = this.now(); this.transport .sendPluginCommand(IDENTITY_PLUGIN, payload, "channel") From 17b092f2e404882c9705f4bf87fe8d1c6c77b864 Mon Sep 17 00:00:00 2001 From: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:53:40 +0800 Subject: [PATCH 5/5] fix(teamspeak): fence chat commands to their connection --- src/bot/instance.test.ts | 35 +++++++++++++++++++++++++++++++++++ src/bot/instance.ts | 10 +++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/bot/instance.test.ts b/src/bot/instance.test.ts index 5b02d0f..fcd8a8f 100644 --- a/src/bot/instance.test.ts +++ b/src/bot/instance.test.ts @@ -1975,6 +1975,41 @@ describe("BotInstance — OpenProtocol & command routing", () => { expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:"); }); + it("drops a private command reply when the connection changed during execution", async () => { + const ctx = makeGateCtx({}); + ctx.lifecycleGeneration = 1; + const executed = deferred(); + const reply = deferred(); + ctx.executeCommand = vi.fn(() => { + executed.resolve(); + return reply.promise; + }); + + const pending = handleTextMessage.call(ctx, { ...makeMsg("!now"), targetMode: 1 }); + await executed.promise; + ctx.lifecycleGeneration++; + reply.resolve("Prior connection's queue"); + await pending; + + expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled(); + }); + + it("drops a command from a previous connection after the group check", async () => { + const ctx = makeGateCtx({ adminGroups: [6] }); + ctx.lifecycleGeneration = 1; + const groups = deferred(); + ctx.tsClient.getClientServerGroups.mockReturnValue(groups.promise); + + const pending = handleTextMessage.call(ctx, { ...makeMsg("!stop"), targetMode: 1 }); + expect(ctx.tsClient.getClientServerGroups).toHaveBeenCalled(); + ctx.lifecycleGeneration++; + groups.resolve(["6"]); + await pending; + + expect(ctx.executeCommand).not.toHaveBeenCalled(); + expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled(); + }); + it("routes permission denied and execution errors privately when triggered via DM", async () => { const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] }); const dmStop: TS3TextMessage = { diff --git a/src/bot/instance.ts b/src/bot/instance.ts index 484c408..bcb7b8d 100755 --- a/src/bot/instance.ts +++ b/src/bot/instance.ts @@ -830,7 +830,13 @@ export class BotInstance extends EventEmitter { ); if (!parsed) return; - if (!(await this.isCommandAllowed(parsed.name, msg))) { + // A numeric invoker ID only belongs to this TeamSpeak connection. + const generation = this.lifecycleGeneration; + const isCurrent = () => this.lifecycleGeneration === generation; + const allowed = await this.isCommandAllowed(parsed.name, msg); + if (!isCurrent()) return; + + if (!allowed) { this.logger.info( { command: parsed.name, invoker: msg.invokerName }, "Command denied: invoker not in adminGroups" @@ -854,10 +860,12 @@ export class BotInstance extends EventEmitter { // A single long reply (e.g. full lyrics) would exceed TeamSpeak's // per-message byte cap, so split it and send the chunks in order. for (const chunk of splitTextIntoChunks(response)) { + if (!isCurrent()) return; await sendTextReply(this.tsClient, msg, chunk); } } } catch (err) { + if (!isCurrent()) return; this.logger.error({ err, command: parsed.name }, "Command execution error"); try { await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`);