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] 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")