diff --git a/README.md b/README.md index 4f8230a..fd051ae 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关 - 完整频道/成员树、频道切换、频道文字聊天和成员实时移动。 - PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。 - 发言成员头像显示绿色动态边框。 +- 频道、服务器和私聊独立标签;成员菜单支持私聊、Poke、复制昵称,频道密码按次输入且不持久化。 +- Away、成员状态图标、Session 内服务器事件日志和人类可读的 TeamSpeak 权限错误。 - 中英文访客页面和中英文管理控制台。 - Web 管理闭环:默认账号首次登录强制改密、单管理员登录、概览、服务器设置和真实连接测试。 - `fixed` 与 `open` 两种访问模式。 @@ -227,6 +229,8 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser - Temporary TeamSpeak failures recover with bounded jittered backoff for up to five minutes; authentication failures are not retried forever, and the previous channel is restored when possible. - Channel/member directory, channel switching, channel text chat, and live member movement. - PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls. +- Independent channel, server, and private chat tabs; member actions for private message, poke, and nickname copy; channel passwords are entered per session only. +- Away, member status icons, a session-local server event log, and readable TeamSpeak permission errors. - Bilingual guest UI and bilingual admin console. - Browser-based admin login, mandatory first-login password change, Overview, server settings, and a real short-lived connection test. - Fixed and open guest access modes. diff --git a/scripts/patch-teamspeak-sdk.mjs b/scripts/patch-teamspeak-sdk.mjs index 37849b1..b2d2f05 100644 --- a/scripts/patch-teamspeak-sdk.mjs +++ b/scripts/patch-teamspeak-sdk.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const packageRoot = path.join(root, "node_modules", "@honeybbq", "teamspeak-client"); -const marker = "webspeak-directory-snapshot"; +const marker = "webspeak-directory-snapshot-v2"; const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8")); if (packageJson.version !== "0.2.2") { @@ -26,12 +26,12 @@ await Promise.all([ ]); function patchCjs(source) { - if (source.includes(marker)) return source; + if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source; const helper = `/* ${marker} */ function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}} function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}} -function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}} +function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}} function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}} `; source = source.replace("var K=class", `${helper}var K=class`); @@ -86,12 +86,12 @@ function webSpeakDirectoryChannelNotification(name,params,decode,channels){const } function patchMjs(source) { - if (source.includes(marker)) return source; + if (source.includes(marker) || source.includes("webspeak-directory-snapshot")) return source; const helper = `/* ${marker} */ function webSpeakDirectoryBigInt(value){try{return BigInt(value??"0")}catch{return 0n}} function webSpeakDirectoryChannel(params,decode){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return null;return{id,parentID:webSpeakDirectoryBigInt(params.pid??params.cpid??"0"),name:decode(params.channel_name??""),description:decode(params.channel_topic??params.channel_description??"")}} -function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[]}} +function webSpeakDirectoryClient(params,decode){const id=parseInt(params.clid??"0",10);if(!Number.isInteger(id)||id<=0)return null;const groups=params.client_servergroups??"";return{id,nickname:decode(params.client_nickname??""),uid:params.client_unique_identifier??"",channelID:webSpeakDirectoryBigInt(params.cid),type:parseInt(params.client_type??"0",10),serverGroups:groups?groups.split(","):[],away:params.client_away==="1",awayMessage:decode(params.client_away_message??""),inputMuted:params.client_input_muted==="1",outputMuted:params.client_output_muted==="1",channelCommander:params.client_is_channel_commander==="1"}} function webSpeakDirectoryChannelNotification(name,params,decode,channels){const id=webSpeakDirectoryBigInt(params.cid);if(id===0n)return false;switch(name){case"notifychannelcreated":{const channel=webSpeakDirectoryChannel(params,decode);if(!channel)return false;channels.set(id,channel);return true}case"notifychanneledited":{const current=channels.get(id);if(!current)return false;const next={...current};if(params.channel_name!==undefined)next.name=decode(params.channel_name);if(params.channel_topic!==undefined)next.description=decode(params.channel_topic);if(params.cpid!==undefined||params.pid!==undefined)next.parentID=webSpeakDirectoryBigInt(params.cpid??params.pid);channels.set(id,next);return true}case"notifychannelmoved":{const current=channels.get(id);if(!current)return false;channels.set(id,{...current,parentID:webSpeakDirectoryBigInt(params.cpid??params.pid)});return true}case"notifychanneldeleted":return channels.delete(id);default:return false}} `; source = source.replace("var k = class", `${helper}var k = class`); diff --git a/src/server/ts-client.ts b/src/server/ts-client.ts index fdbe7f3..98bbf32 100644 --- a/src/server/ts-client.ts +++ b/src/server/ts-client.ts @@ -2,6 +2,8 @@ import { EventEmitter } from "node:events"; import { Client as TS3FullClient, clientMove as tsClientMove, + poke as tsPoke, + sendTextMessage as tsSendTextMessage, generateIdentity, type Identity, type VoiceData, @@ -29,9 +31,19 @@ export interface TSVoiceData { export interface TSDirectorySnapshot { channels: ChannelInfo[]; - clients: ClientInfo[]; + clients: TSDirectoryClient[]; } +export interface TSDirectoryClient extends ClientInfo { + away?: boolean; + awayMessage?: string; + inputMuted?: boolean; + outputMuted?: boolean; + channelCommander?: boolean; +} + +export type TSChatScope = "channel" | "server" | "private"; + export class TSClient extends EventEmitter { private client: TS3FullClient | null = null; private adapter: TeamSpeakAdapter | null = null; @@ -134,6 +146,10 @@ export class TSClient extends EventEmitter { }); }); + client.on("poked", (event) => { + this.emit("poked", event); + }); + client.on("disconnected", (err) => { this.logger.warn({ err: err?.message }, "Disconnected from TS"); this.connected = false; @@ -160,15 +176,21 @@ export class TSClient extends EventEmitter { this.client.sendVoice(data, codec); } - sendTextMessage(message: string): void { - // We use execCommand for simplicity — the client API has higher-level wrappers - if (!this.client || !this.connected) return; - const escaped = message - .replace(/\\/g, "\\\\") - .replace(/ /g, "\\s") - .replace(/\//g, "\\/"); - this.client.execCommand(`sendtextmessage targetmode=2 target=0 msg=${escaped}`) - .catch((err: Error) => this.logger.error({ err }, "sendTextMessage failed")); + async sendTextMessage(scope: TSChatScope, message: string, targetId = 0n): Promise { + if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); + const targetMode = scope === "private" ? 1 : scope === "server" ? 3 : 2; + await tsSendTextMessage(this.client, targetMode, targetId, message); + } + + async poke(clientId: number, message: string): Promise { + if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); + await tsPoke(this.client, clientId, message); + } + + async setAway(away: boolean, message = ""): Promise { + if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready"); + const escaped = escapeTeamSpeakValue(message); + await this.client.execCommand(`clientupdate client_away=${away ? 1 : 0} client_away_message=${escaped}`); } async switchChannel(channelId: bigint, password?: string): Promise { @@ -210,3 +232,13 @@ export class TSClient extends EventEmitter { this.clientId = 0; } } + +function escapeTeamSpeakValue(value: string): string { + return value + .replace(/\\/g, "\\\\") + .replace(/ /g, "\\s") + .replace(/\//g, "\\/") + .replace(/\|/g, "\\p") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r"); +} diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 2178548..ee6ba38 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -28,6 +28,18 @@ interface ChannelMember { id: number; nickname: string; uid: string; + away?: boolean; + awayMessage?: string; + inputMuted?: boolean; + outputMuted?: boolean; + channelCommander?: boolean; +} + +interface ServerEvent { + id: string; + kind: "joined" | "left" | "moved" | "poke" | "connection"; + message: string; + timestamp: number; } interface WebClientEntry { @@ -40,6 +52,7 @@ interface WebClientEntry { target: TeamSpeakTarget; channelTree: unknown[]; members: Map; + eventLog: ServerEvent[]; opusEncoder: { encode(pcm: Buffer): Buffer } | null; isAlive: boolean; reconnectTimer: ReturnType | null; @@ -111,6 +124,7 @@ export class VoiceBridge { target, channelTree: [], members: new Map(), + eventLog: [], opusEncoder: null, isAlive: true, reconnectTimer: null, @@ -138,6 +152,17 @@ export class VoiceBridge { const sendJson = (message: Record) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message)); }; + const addServerEvent = (kind: ServerEvent["kind"], message: string) => { + const event: ServerEvent = { + id: `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`, + kind, + message, + timestamp: Date.now(), + }; + entry!.eventLog.push(event); + if (entry!.eventLog.length > 200) entry!.eventLog.splice(0, entry!.eventLog.length - 200); + if (initialStateSent) sendJson({ type: "serverEvent", event }); + }; const refreshDirectory = () => { const snapshot = directory.getSnapshot(); if (!snapshot) return; @@ -148,9 +173,28 @@ export class VoiceBridge { entry!.channelTree = mapChannelTree(normalizedSnapshot); entry!.members.clear(); for (const client of normalizedSnapshot.clients) { - entry!.members.set(client.id, { id: client.id, nickname: client.nickname, uid: client.uid }); + entry!.members.set(client.id, { + id: client.id, + nickname: client.nickname, + uid: client.uid, + away: client.away, + awayMessage: client.awayMessage, + inputMuted: client.inputMuted, + outputMuted: client.outputMuted, + channelCommander: client.channelCommander, + }); } }; + const trackChannelEvents = (previous: unknown[], next: unknown[]) => { + if (!initialStateSent) return; + const before = new Map(previous.filter(isChannelRecord).map((channel) => [channel.id, channel])); + const after = new Map(next.filter(isChannelRecord).map((channel) => [channel.id, channel])); + for (const channel of after.values()) { + if (!before.has(channel.id)) addServerEvent("joined", `频道「${channel.name}」已创建`); + else if (before.get(channel.id)?.name !== channel.name) addServerEvent("moved", `频道已重命名为「${channel.name}」`); + } + for (const channel of before.values()) if (!after.has(channel.id)) addServerEvent("left", `频道「${channel.name}」已删除`); + }; const sendInitialState = () => { if (initialStateSent || !tsReady || !directory.ready || !realtimeReady || !audioReady || session.state !== "syncing") return; initialStateSent = true; @@ -158,11 +202,15 @@ export class VoiceBridge { hasConnectedOnce = true; reconnectAttempt = 0; reconnectStartedAt = 0; + if (!wasReconnecting) { + entry!.eventLog.push({ id: `event-${Date.now().toString(36)}-connected`, kind: "connection", message: "已连接到服务器", timestamp: Date.now() }); + } session.transition("connected"); sendJson({ type: "connected", tsClientId: selfId, members: Array.from(entry!.members.values()), + serverEventLog: entry!.eventLog, ...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}), }); sendJson({ type: "channelList", channels: entry!.channelTree }); @@ -266,8 +314,10 @@ export class VoiceBridge { // snapshot establishes the baseline. realtimeReady = true; tsClient.on("directorySnapshot", (snapshot: TSDirectorySnapshot) => { + const previousChannels = entry!.channelTree; directory.applySnapshot(snapshot); refreshDirectory(); + trackChannelEvents(previousChannels, entry!.channelTree); sendInitialState(); if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree }); }); @@ -284,25 +334,32 @@ export class VoiceBridge { if (tsReady && initialStateSent) { sendJson({ type: "channelList", channels: entry!.channelTree }); if (!wasKnown) sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === selfId }); + if (!wasKnown && info.id !== selfId) addServerEvent("joined", `${info.nickname || "未知用户"} 加入了服务器`); } }); tsClient.on("clientLeave", (info) => { const wasKnown = entry!.members.has(info.id); + const leavingMember = entry!.members.get(info.id); directory.applyClientLeave(info.id); refreshDirectory(); if (tsReady && initialStateSent && wasKnown) { sendJson({ type: "memberLeave", id: info.id }); sendJson({ type: "channelList", channels: entry!.channelTree }); + if (info.id !== selfId) addServerEvent("left", `${leavingMember?.nickname || "用户"} 离开了服务器`); } }); tsClient.on("clientMoved", (info) => { if (info.targetChannelID === undefined || info.targetChannelID === 0n) return; + const movedMember = entry!.members.get(info.id); if (info.id === selfId) selfChannelId = info.targetChannelID; directory.applyClientMoved(info.id, info.targetChannelID); refreshDirectory(); - if (tsReady && initialStateSent) sendJson({ type: "channelList", channels: entry!.channelTree }); + if (tsReady && initialStateSent) { + sendJson({ type: "channelList", channels: entry!.channelTree }); + if (info.id !== selfId) addServerEvent("moved", `${movedMember?.nickname || "用户"} 移动到了其他频道`); + } }); tsClient.on("voiceData", (data: TSVoiceData) => { @@ -315,14 +372,24 @@ export class VoiceBridge { }); tsClient.on("textMessage", (message) => { + const scope = message.targetMode === 1 ? "private" : message.targetMode === 3 ? "server" : message.targetMode === 2 ? "channel" : "server"; sendJson({ type: "chatMessage", + scope, + targetId: message.targetID.toString(), + senderUid: message.invokerUID, + timestamp: Date.now(), invokerName: message.invokerName, invokerId: message.invokerId, message: message.message, }); }); + tsClient.on("poked", (event) => { + sendJson({ type: "pokeReceived", invokerId: event.invokerID, invokerUid: event.invokerUID, invokerName: event.invokerName, message: event.message, timestamp: Date.now() }); + addServerEvent("poke", `${event.invokerName || "用户"} 戳了你一下`); + }); + tsClient.on("disconnected", (error?: Error) => { if (!hasConnectedOnce || session.state !== "connected") return; resetDirectoryForReconnect(); @@ -466,28 +533,75 @@ async function handleCommand( ): Promise { if (command.type === "switchChannel") { const rawId = command.payload.channelId as string; + const channelPassword = typeof command.payload.password === "string" ? command.payload.password : ""; try { - await entry.tsClient.switchChannel(BigInt(rawId)); + await entry.tsClient.switchChannel(BigInt(rawId), channelPassword || undefined); } catch (error: unknown) { - const message = error instanceof Error ? error.message : String(error); - if (!message.includes("already member")) { - sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_SWITCH_FAILED", message: "频道切换失败", recoverable: false } }); + const rawMessage = error instanceof Error ? error.message : String(error); + if (/already member/i.test(rawMessage)) { + sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); return; } + const operation = classifyOperationError(error, "CHANNEL_SWITCH_FAILED", "频道切换失败"); + sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); + return; } sendJson({ type: "channelSwitched", requestId: command.requestId, channelId: rawId }); sendJson({ type: "channelList", channels: entry.channelTree }); return; } - const message = (command.payload.message as string).trim(); - if (message) entry.tsClient.sendTextMessage(message); + try { + if (command.type === "sendTextMessage") { + const message = (command.payload.message as string).trim(); + if (message) await entry.tsClient.sendTextMessage("channel", message, entry.tsClient.getChannelId()); + } else if (command.type === "sendServerMessage") { + const message = (command.payload.message as string).trim(); + if (message) await entry.tsClient.sendTextMessage("server", message); + } else if (command.type === "sendPrivateMessage") { + const clientId = command.payload.clientId as number; + if (!entry.members.has(clientId)) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); + return; + } + const message = (command.payload.message as string).trim(); + if (message) await entry.tsClient.sendTextMessage("private", message, BigInt(clientId)); + } else if (command.type === "poke") { + const clientId = command.payload.clientId as number; + if (!entry.members.has(clientId)) { + sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线", recoverable: false } }); + return; + } + await entry.tsClient.poke(clientId, (command.payload.message as string).trim()); + } else if (command.type === "setAway") { + await entry.tsClient.setAway(command.payload.away as boolean, typeof command.payload.message === "string" ? command.payload.message.trim() : ""); + } + if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId }); + } catch (error: unknown) { + const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败"); + sendJson({ type: "error", requestId: command.requestId, error: { code: operation.code, message: operation.message, recoverable: false } }); + } +} + +function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } { + const text = error instanceof Error ? error.message : String(error); + const normalized = text.toLocaleLowerCase(); + if (/permission|not permitted|insufficient|i_permission|2568/.test(normalized)) return { code: "PERMISSION_DENIED", message: "你没有执行此操作的权限" }; + if (/channel.*(password|password.*required)|invalid.*(channel|password)|i_channel_password|1794/.test(normalized)) return { code: "CHANNEL_PASSWORD_REQUIRED", message: "该频道需要密码" }; + if (/already member/.test(normalized)) return { code: "ALREADY_IN_CHANNEL", message: "你已经在该频道中" }; + if (/full|maximum.*clients/.test(normalized)) return { code: "CHANNEL_FULL", message: "该频道已满" }; + if (/not found|unknown client|invalid client/.test(normalized)) return { code: "CLIENT_NOT_FOUND", message: "成员已离线" }; + return { code: fallbackCode, message: fallbackMessage }; } function sendProtocolError(sendJson: (message: Record) => void, code: string, message: string): void { sendJson({ type: "error", error: { code, message, recoverable: false } }); } +function isChannelRecord(value: unknown): value is { id: string; name: string } { + return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string"; +} + function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] { return snapshot.channels.map((channel) => ({ id: String(channel.id), @@ -496,7 +610,16 @@ function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] { description: channel.description || "", members: snapshot.clients .filter((client) => client.channelID === channel.id) - .map((client) => ({ id: client.id, nickname: client.nickname || "未知用户", uid: client.uid })), + .map((client) => ({ + id: client.id, + nickname: client.nickname || "未知用户", + uid: client.uid, + away: client.away, + awayMessage: client.awayMessage, + inputMuted: client.inputMuted, + outputMuted: client.outputMuted, + channelCommander: client.channelCommander, + })), })); } diff --git a/src/server/voice-protocol.ts b/src/server/voice-protocol.ts index 155f584..4f44808 100644 --- a/src/server/voice-protocol.ts +++ b/src/server/voice-protocol.ts @@ -1,5 +1,5 @@ export interface ClientCommand { - type: "switchChannel" | "sendTextMessage"; + type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway"; requestId?: string; payload: Record; } @@ -19,7 +19,8 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) { return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } }; } - if (value.type !== "switchChannel" && value.type !== "sendTextMessage") { + const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway"]); + if (!supportedTypes.has(value.type)) { return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } }; } if (!isRecord(value.payload)) { @@ -28,11 +29,26 @@ export function parseClientCommand(raw: string): ClientCommandResult { if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) { return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } }; } + if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) { + return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } }; + } if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) { return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } }; } + if ((value.type === "sendServerMessage" || value.type === "sendPrivateMessage") && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) { + return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } }; + } + if ((value.type === "sendPrivateMessage" || value.type === "poke") && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) { + return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } }; + } + if (value.type === "poke" && (typeof value.payload.message !== "string" || value.payload.message.length > 200)) { + return { error: { code: "INVALID_POKE_MESSAGE", message: "戳一戳消息无效" } }; + } + if (value.type === "setAway" && (typeof value.payload.away !== "boolean" || (value.payload.message !== undefined && (typeof value.payload.message !== "string" || value.payload.message.length > 200)))) { + return { error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" } }; + } return { - type: value.type, + type: value.type as ClientCommand["type"], ...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}), payload: value.payload, }; diff --git a/test/voice-protocol.test.ts b/test/voice-protocol.test.ts index fefd56b..2f1f97d 100644 --- a/test/voice-protocol.test.ts +++ b/test/voice-protocol.test.ts @@ -27,3 +27,31 @@ test("voice protocol rejects malformed and unsupported commands", () => { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" }, }); }); + +test("voice protocol keeps chat scopes and status actions explicit", () => { + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), { + type: "sendPrivateMessage", + requestId: "pm-1", + payload: { clientId: 7, message: "hello" }, + }); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), { + type: "setAway", + payload: { away: true, message: "back soon" }, + }); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), { + type: "switchChannel", + payload: { channelId: "42", password: "secret" }, + }); +}); + +test("voice protocol rejects unsafe client and away payloads", () => { + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), { + error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" }, + }); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), { + error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" }, + }); + assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), { + error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" }, + }); +}); diff --git a/web/src/components/Icon.vue b/web/src/components/Icon.vue index ed42173..5dfc81b 100644 --- a/web/src/components/Icon.vue +++ b/web/src/components/Icon.vue @@ -39,6 +39,7 @@ +