fix: gate member moves by TeamSpeak permissions

This commit is contained in:
illusia committed 2026-09-18 17:36:45 +08:00
1 parent 883703dd0c
commit 010b8ef072
5 files changed
+311 -6

No files matched your search

+22
View File
@@ -277,6 +277,28 @@ export class TSClient extends EventEmitter {
this.preferredChannelId = channelId;
}
/** Move another visible TeamSpeak client; the server enforces both move powers. */
async moveClient(clientId: number, channelId: bigint, password?: string): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
await tsClientMove(this.client, clientId, channelId, password);
}
/**
* Probe whether this identity may move a visible client into a channel.
*
* The browser client protocol does not expose ServerQuery's `permget`, so
* the only authoritative capability check available through this session is
* the same `clientmove` operation the UI will use. The bridge calls this
* with the client's current channel, making the probe a no-op when accepted;
* TeamSpeak still evaluates both move-power permissions.
*/
async probeMovePermission(clientId: number, channelId: bigint): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
await tsClientMove(this.client, clientId, channelId);
}
getClientId(): number {
// The SDK learns the real client id during the welcome sequence, before
// TSClient.connect() resumes. Reading it from the SDK prevents the first
+83 -1
View File
@@ -23,6 +23,7 @@ const { OpusEncoder } = require("@discordjs/opus") as {
};
const HEARTBEAT_INTERVAL_MS = 30_000;
const MOVE_PERMISSION_PROBE_INTERVAL_MS = 30_000;
const AUDIO_FRAME_BYTES = 1_920;
// A browser audio frame is 20 ms of mono 48 kHz PCM. Keep the server-side
// WebSocket egress queue small enough that a slow browser cannot turn old
@@ -149,6 +150,8 @@ interface WebClientEntry {
audio: AudioFlowStats;
webrtc: WebRtcAudioSession | null;
lastLatencyProbeAt: number;
canMoveClients: boolean;
movePermissionProbeTimer: ReturnType<typeof setInterval> | null;
connectionFailureCode?: string;
}
@@ -265,6 +268,8 @@ export class VoiceBridge {
audio: createAudioFlowStats(),
webrtc: null,
lastLatencyProbeAt: 0,
canMoveClients: false,
movePermissionProbeTimer: null,
};
this.entries.set(entryId, entry!);
try {
@@ -374,17 +379,55 @@ export class VoiceBridge {
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
accelerated: Boolean(entry!.acceleration),
canMoveClients: entry!.canMoveClients,
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
});
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
};
let movePermissionProbeInFlight = false;
const refreshMoveCapability = async (): Promise<void> => {
if (!entry || !tsReady || session.state !== "connected" || movePermissionProbeInFlight) return;
const probeTarget = findMovePermissionProbeTarget(entry, selfId);
if (!probeTarget) return;
movePermissionProbeInFlight = true;
try {
// Probe by moving a visible client to the channel it is already in.
// A successful request has no observable state change, while the
// server still evaluates i_client_move_power and the target channel's
// i_client_needed_move_power. This avoids using ServerQuery-only
// `permget`, which is not available on the browser client protocol.
await tsClient.probeMovePermission(probeTarget.clientId, BigInt(probeTarget.channelId));
if (!entry.canMoveClients) {
entry.canMoveClients = true;
sendJson({ type: "capabilities", canMoveClients: true });
}
} catch (error: unknown) {
const operation = classifyOperationError(error, "OPERATION_FAILED", "操作失败");
if (operation.code === "PERMISSION_DENIED" && entry.canMoveClients) {
entry.canMoveClients = false;
sendJson({ type: "capabilities", canMoveClients: false });
}
this.logger.debug({
entryId,
clientId: probeTarget.clientId,
channelId: probeTarget.channelId,
code: operation.code,
}, "TeamSpeak move capability probe completed");
} finally {
movePermissionProbeInFlight = false;
}
};
entry!.movePermissionProbeTimer = setInterval(() => { void refreshMoveCapability(); }, MOVE_PERMISSION_PROBE_INTERVAL_MS);
entry!.movePermissionProbeTimer.unref?.();
const resetDirectoryForReconnect = () => {
tsReady = false;
initialStateSent = false;
selfId = 0;
selfChannelId = 0n;
entry!.canMoveClients = false;
directory.clear();
entry!.channelTree = [];
entry!.members.clear();
@@ -455,6 +498,7 @@ export class VoiceBridge {
refreshDirectory();
}
sendInitialState();
void refreshMoveCapability();
} catch (error: unknown) {
const normalized = normalizeTeamSpeakError(error);
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
@@ -518,6 +562,7 @@ export class VoiceBridge {
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 || "未知用户"} 加入了服务器`);
void refreshMoveCapability();
}
});
@@ -822,6 +867,10 @@ export class VoiceBridge {
clearTimeout(entry.reconnectTimer);
entry.reconnectTimer = null;
}
if (entry.movePermissionProbeTimer) {
clearInterval(entry.movePermissionProbeTimer);
entry.movePermissionProbeTimer = null;
}
entry.opusEncoder = null;
const webRtc = entry.webrtc;
entry.webrtc = null;
@@ -1044,7 +1093,29 @@ async function handleCommand(
}
try {
if (command.type === "sendTextMessage") {
if (command.type === "moveClient") {
const clientId = command.payload.clientId as number;
const channelId = command.payload.channelId as string;
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
if (clientId === entry.tsClient.getClientId()) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CANNOT_MOVE_SELF", message: "不能移动自己的客户端", recoverable: false } });
return;
}
if (!entry.members.has(clientId)) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CLIENT_NOT_FOUND", message: "成员已离线或当前不可见", recoverable: false } });
return;
}
const targetExists = entry.channelTree.some((channel) => isRecord(channel) && channel.id === channelId);
if (!targetExists) {
sendJson({ type: "error", requestId: command.requestId, error: { code: "CHANNEL_NOT_FOUND", message: "目标频道不可用", recoverable: false } });
return;
}
// TeamSpeak evaluates i_client_move_power against the target's
// i_client_needed_move_power inside clientmove. Do not duplicate that
// policy in the gateway; forwarding the authoritative command keeps TS3
// and TS6 permission behavior aligned.
await entry.tsClient.moveClient(clientId, BigInt(channelId), channelPassword || undefined);
} else 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") {
@@ -1241,6 +1312,17 @@ function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
}));
}
function findMovePermissionProbeTarget(entry: Pick<WebClientEntry, "channelTree" | "members">, selfId: number): { clientId: number; channelId: string } | null {
for (const rawChannel of entry.channelTree) {
if (!isRecord(rawChannel) || typeof rawChannel.id !== "string" || !Array.isArray(rawChannel.members)) continue;
for (const rawMember of rawChannel.members) {
if (!isRecord(rawMember) || typeof rawMember.id !== "number" || rawMember.id === selfId) continue;
if (entry.members.has(rawMember.id)) return { clientId: rawMember.id, channelId: rawChannel.id };
}
}
return null;
}
function normalizeDirectorySnapshot(
snapshot: TSDirectorySnapshot,
selfId: number,
+11 -2
View File
@@ -1,5 +1,5 @@
export interface ClientCommand {
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
requestId?: string;
payload: Record<string, unknown>;
}
@@ -19,7 +19,7 @@ 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: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
@@ -32,6 +32,15 @@ export function parseClientCommand(raw: string): ClientCommandResult {
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 === "moveClient" && (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 === "moveClient" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "moveClient" && 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: "文字消息无效" } };
}