fix: expose server identity and refine KAAK client

This commit is contained in:
illusia committed 2026-10-11 17:14:56 +08:00
1 parent e8164abafe
commit 17fb27b89a
28 files changed
+1504 -334

No files matched your search

+27 -2
View File
@@ -17,6 +17,8 @@ const transfer = { size: 6n };
class SdkStub extends EventEmitter {
inputCommands: string[] = [];
fileTransfers: Array<{ channelId: bigint; path: string; password: string }> = [];
serverInfo: { name: string; iconId: number | null } | null = { name: "兄弟们的teamspeak", iconId: 123456 };
inputUpdate = async (_command: string): Promise<void> => {};
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
initialized = 0;
@@ -24,8 +26,12 @@ class SdkStub extends EventEmitter {
metadata = async () => rows;
transfer = async () => transfer;
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
execCommandWithResponse() { return this.metadata(); }
async fileTransferInitDownload() { this.initialized++; return this.transfer(); }
execCommandWithResponse(command = "") { this.inputCommands.push(command); return this.metadata(); }
async fileTransferInitDownload(channelId: bigint, path: string, password: string) {
this.initialized++;
this.fileTransfers.push({ channelId, path, password });
return this.transfer();
}
async downloadFileData(_host: string, _transfer: unknown, destination: Writable) { this.downloaded++; await this.download(destination); }
}
@@ -53,6 +59,25 @@ test("stream commands wait for server acknowledgement and propagate refusals", a
await assert.rejects(f.client.sendProtocolCommand("removeclientfromstream id=test"), /missing required parameter/);
});
test("server info uses the name and icon id captured by the SDK handshake", async () => {
const f = fixture();
assert.deepEqual(await f.client.getServerInfo(), { name: "兄弟们的teamspeak", iconId: 123456 });
assert.deepEqual(f.sdk.inputCommands, [], "server identity does not issue a ServerQuery-only command over the client session");
f.sdk.serverInfo = { name: "No icon", iconId: null };
assert.deepEqual(await f.client.getServerInfo(), { name: "No icon", iconId: null });
});
test("server icons use the TeamSpeak file transfer path and enforce the download limit", async () => {
const f = fixture();
assert.equal((await f.client.getServerIcon(123456))?.toString(), "GIF89a");
assert.deepEqual(f.sdk.fileTransfers, [{ channelId: 0n, path: "/icon_123456", password: "" }]);
assert.equal(f.sdk.downloaded, 1);
f.sdk.transfer = async () => ({ size: 128n * 1024n + 1n });
assert.equal(await f.client.getServerIcon(123456), null);
assert.equal(f.sdk.downloaded, 1);
});
test("stream cleanup flood retries back off and stop after two retries", async t => {
const f = fixture();
t.mock.timers.enable({ apis: ["setTimeout"] });
+43
View File
@@ -44,10 +44,16 @@ export interface TSClientAvatar {
data: Buffer;
}
export interface TSClientServerInfo {
name: string;
iconId: number | null;
}
// Keep enough room for avatars produced by the native client. The previous
// 120 KiB limit rejected the 134 KiB PNG used by the Shanghai test account,
// so every avatar silently fell back to its initial letter.
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
const MAX_SERVER_ICON_BYTES = 128 * 1024;
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity>;
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
@@ -274,6 +280,43 @@ export class TSClient extends EventEmitter {
return { cacheKey, data };
}
/** Read the public virtual-server name and icon marker from the active session. */
async getServerInfo(): Promise<TSClientServerInfo> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
const generation = this.connectionGeneration;
if (this.client !== client || !this.connected || this.connectionGeneration !== generation) {
throw new Error("TeamSpeak session changed while reading server information");
}
return client.serverInfo ?? { name: "", iconId: null };
}
/** Download the public virtual-server icon using TeamSpeak's normal file-transfer port. */
async getServerIcon(iconId: number): Promise<Buffer | null> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
if (!Number.isSafeInteger(iconId) || iconId === 0) return null;
const generation = this.connectionGeneration;
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
const transfer = await client.fileTransferInitDownload(0n, `/icon_${iconId}`, "");
if (!isCurrent()) return null;
const size = Number(transfer.size);
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_SERVER_ICON_BYTES) return null;
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer | string, _encoding, callback) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
callback();
},
});
await client.downloadFileData(this.options.target.host, transfer, destination);
if (!isCurrent()) return null;
const data = Buffer.concat(chunks);
if (data.length === 0 || data.length > MAX_SERVER_ICON_BYTES) return null;
return data;
}
private attachClientListeners(client: TS3FullClient): void {
client.on("voiceData", (data: VoiceData) => {
if (this.client !== client) return;
+30 -2
View File
@@ -20,11 +20,16 @@ class TeamSpeakStub extends EventEmitter {
sent: Buffer[] = [];
directory: TSDirectorySnapshot = { channels: [], clients: [] };
avatarRequest: (id: number, uid: string) => Promise<TSClientAvatar | null> = async () => null;
async connect() { this.disconnected = false; this.emit("directorySnapshot", this.directory); }
emitDirectorySnapshotOnConnect = true;
connectCalls = 0;
serverInfoCalls = 0;
async connect() { this.connectCalls++; this.disconnected = false; if (this.emitDirectorySnapshotOnConnect) this.emit("directorySnapshot", this.directory); }
async disconnect() { this.disconnected = true; }
getClientId() { return 1; }
getChannelId() { return 1n; }
isConnected() { return !this.disconnected; }
async getServerInfo() { this.serverInfoCalls++; return { name: "兄弟们的teamspeak", iconId: null }; }
async getServerIcon() { return null; }
async sendProtocolCommand() {}
async setAccompanimentActive() {}
sendVoice(data: Buffer) { this.sent.push(data); this.emit("sent", data); }
@@ -36,6 +41,7 @@ async function fixture(t: TestContext, overrides: {
createTeamSpeakClient?: () => TSClient;
createEncoder?: () => Pick<OpusEncoder, "encode" | "dispose">;
configureSdk?: (sdk: TeamSpeakStub) => void;
waitForFirstMessage?: boolean;
} = {}) {
const sdk = new TeamSpeakStub();
overrides.configureSdk?.(sdk);
@@ -65,7 +71,7 @@ async function fixture(t: TestContext, overrides: {
await bridge.shutdown();
await new Promise<void>(resolve => server.close(() => resolve()));
});
await first;
if (overrides.waitForFirstMessage !== false) await first;
const entries = (bridge as unknown as { entries: Map<string, {
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
isAlive: boolean; avatarCache: Map<string, string | null>;
@@ -82,6 +88,28 @@ test("a TeamSpeak constructor failure releases the admitted gateway slot", { tim
assert.equal(f.bridge.getActiveCount(), 0);
});
test("server identity lookup waits until the directory sync publishes the connected state", { timeout: 5_000 }, async t => {
const f = await fixture(t, { waitForFirstMessage: false, configureSdk(sdk) { sdk.emitDirectorySnapshotOnConnect = false; } });
while (!f.sdk.connectCalls) await nextTurn();
await nextTurn();
assert.equal(f.sdk.serverInfoCalls, 0);
const serverInfo = new Promise<Record<string, unknown>>(resolve => {
f.socket.on("message", (data, binary) => {
if (binary) return;
const message = JSON.parse(data.toString()) as Record<string, unknown>;
if (message.type === "serverInfo") resolve(message);
});
});
f.sdk.emit("directorySnapshot", f.sdk.directory);
assert.deepEqual(await serverInfo, { type: "serverInfo", name: "兄弟们的teamspeak", icon: null });
const publishedTypes = f.messages.filter(message => !message.binary).map(message => (JSON.parse(message.data.toString()) as { type: string }).type);
assert.ok(publishedTypes.indexOf("connected") >= 0);
assert.ok(publishedTypes.indexOf("serverInfo") > publishedTypes.indexOf("connected"));
assert.equal(f.sdk.serverInfoCalls, 1);
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a codec disposal failure cannot abandon TeamSpeak or the browser socket", { timeout: 5_000 }, async t => {
const encoder = new OpusEncoder(48000, 1);
t.mock.method(encoder, "dispose", () => { throw new Error("Codec already disposed"); });
+22
View File
@@ -26,6 +26,7 @@ import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioSessionOpt
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
import { OpusEncoder } from "./opus-codec.js";
import { avatarDataUrl } from "./directory-view.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
@@ -242,6 +243,7 @@ export class VoiceBridge {
}
let initialStateSent = false;
let serverInfoGeneration = 0;
let hasConnectedOnce = false;
let reconnectStartedAt = 0;
let reconnectAttempt = 0;
@@ -290,6 +292,7 @@ export class VoiceBridge {
sendJson({ type: "channelList", channels: entry!.channelTree });
if (wasReconnecting) sendJson({ type: "reconnected" });
events.scheduleAvatars();
void publishServerInfo();
};
const resetDirectoryForReconnect = () => {
@@ -299,6 +302,25 @@ export class VoiceBridge {
initialStateSent = false;
};
const publishServerInfo = async (): Promise<void> => {
const generation = ++serverInfoGeneration;
const isCurrent = () => generation === serverInfoGeneration
&& this.entries.get(entryId) === entry && session.state === "connected";
try {
const info = await tsClient.getServerInfo();
if (!isCurrent()) return;
const name = info.name.trim().slice(0, 256);
sendJson({ type: "serverInfo", name, icon: null });
if (!info.iconId) return;
const icon = await tsClient.getServerIcon(info.iconId);
if (!icon || !isCurrent()) return;
const dataUrl = avatarDataUrl(icon);
if (dataUrl) sendJson({ type: "serverInfo", name, icon: dataUrl });
} catch (error: unknown) {
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server icon unavailable");
}
};
const failReconnect = (normalized: ReturnType<typeof normalizeTeamSpeakError>) => {
if (entry!.reconnectTimer) {
clearTimeout(entry!.reconnectTimer);
+2
View File
@@ -9,6 +9,7 @@ const stream = {
const event = { id: "event-1", kind: "joined", message: "Member joined", timestamp: 1_000 };
const samples: Record<ServerMessage["type"], ServerMessage> = {
connected: { type: "connected", tsClientId: 1, members: [{ id: 1, nickname: "Owner" }], serverEventLog: [event] },
serverInfo: { type: "serverInfo", name: "兄弟们的teamspeak", icon: "data:image/png;base64,iVBORw0KGgo=" },
memberEnter: { type: "memberEnter", id: 2, nickname: "Visitor", uid: "uid-2", isSelf: false },
memberLeave: { type: "memberLeave", id: 2 },
memberAvatar: { type: "memberAvatar", id: 2, avatar: "data:image/png;base64,test" },
@@ -60,6 +61,7 @@ test("malformed nested directory and event data is rejected before client state
{ type: "connected", tsClientId: 1, members: [null] },
{ type: "connected", tsClientId: 1, members: [{ id: "1", nickname: "bad id" }] },
{ type: "connected", tsClientId: 1, serverEventLog: [{ id: "incomplete" }] },
{ type: "serverInfo", name: "TeamSpeak", icon: "https://example.com/icon.png" },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", members: [{}] }] },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 10 }] },
{ type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 65536, maxClientsLimited: true }] },
+4
View File
@@ -13,6 +13,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
export type ServerMessage =
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"serverInfo", { name: string; icon?: string | null }>
| Message<"memberEnter", ChannelMember>
| Message<"memberLeave", { id: number }>
| Message<"memberAvatar", { id: number; uid?: string; avatar?: string }>
@@ -115,6 +116,9 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
connected: m => clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
serverInfo: m => text(m.name) && m.name.length <= 256
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
&& /^data:image\/(?:png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(v))),
memberEnter: member,
memberLeave: m => clientId(m.id),
memberAvatar: m => clientId(m.id) && optional(m.uid, text) && optional(m.avatar, text),
+19
View File
@@ -119,6 +119,25 @@ test("custom surfaces can safely render and switch unified favorite and recent s
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
});
test("server list skins may display only the host-provided TeamSpeak icon image", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].permissions = ["servers.quickList.read"];
document.components[0].root = {
tag: "nav",
repeat: { path: "servers.quickList", as: "server" },
children: [{ tag: "img", attributes: { src: "{{server.icon}}", alt: "" } }],
};
assert.equal(parseSkinPluginDocument(document).components[0].root.children?.[0].attributes?.src, "{{server.icon}}");
document.components[0].root.children![0].attributes!.src = "https://example.com/icon.png";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
document.components[0].root.children![0].attributes!.src = "{{server.icon}}";
document.components[0].root.children![0].tag = "span";
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_ATTRIBUTE_INVALID");
});
test("host widget references stay allowlisted and cannot be used on the demo page", () => {
const unknownWidget = validDocument();
unknownWidget.schemaVersion = 2;
+4 -3
View File
@@ -22,7 +22,7 @@ export const SKIN_PLUGIN_PERMISSIONS = Object.freeze({
"chat.channel.send": Object.freeze({ policyVersion: 1, description: "Send to the current public text channel; the demo page only simulates this action." }),
"favorites.read": Object.freeze({ policyVersion: 1, description: "Read favorite labels and opaque local identifiers, without server addresses or credentials." }),
"favorites.switch": Object.freeze({ policyVersion: 1, description: "Select a saved TeamSpeak server using the host's connection flow." }),
"servers.quickList.read": Object.freeze({ policyVersion: 1, description: "Read favorite and recent server labels and opaque local identifiers, without server addresses or credentials." }),
"servers.quickList.read": Object.freeze({ policyVersion: 1, description: "Read favorite and recent server labels, public server icons, and opaque local identifiers, without server addresses or credentials." }),
"servers.quickList.switch": Object.freeze({ policyVersion: 1, description: "Switch to a user-selected favorite or recent server through the host connection flow." }),
"session.channel.join": Object.freeze({ policyVersion: 1, description: "Request joining a visible TeamSpeak channel through the host; the demo page only changes simulated state." }),
"audio.status.read": Object.freeze({ policyVersion: 1, description: "Read the user's own microphone and speaker mute states." }),
@@ -168,7 +168,7 @@ const VOID_ELEMENTS = new Set(["br", "circle", "hr", "img", "input", "line", "pa
const ATTRIBUTES = new Set([
"alt", "aria-current", "aria-expanded", "aria-hidden", "aria-label", "aria-pressed", "aria-selected", "autocomplete", "checked", "class", "colspan", "disabled", "draggable", "fill", "height", "inputmode", "max", "maxlength", "min",
"minlength", "multiple", "name", "open", "placeholder", "required", "role", "rows", "rowspan", "step", "stroke", "stroke-linecap", "stroke-linejoin",
"stroke-width", "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2",
"src", "stroke-width", "tabindex", "title", "type", "value", "viewbox", "width", "x", "x1", "x2", "y", "y1", "y2",
]);
const EVENTS = new Set<string>([
"click", "dblclick", "change", "input", "submit", "keydown", "keyup", "contextmenu", "focus", "blur", "pointerdown", "pointerup",
@@ -240,7 +240,7 @@ const COLLECTION_FIELDS: Record<string, ReadonlySet<string>> = {
"session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]),
"session.members": new Set(["id", "name", "avatarInitial", "channelId", "status", "speaking", "self"]),
"favorites.items": new Set(["id", "label", "current", "kind"]),
"servers.quickList": new Set(["id", "label", "monogram", "tone", "current", "kind", "favorite"]),
"servers.quickList": new Set(["id", "label", "monogram", "icon", "tone", "current", "kind", "favorite"]),
"chat.messages": new Set(["id", "author", "text", "time", "kind", "channelId"]),
"screenShare.streams": new Set(["streamId", "source", "ownerClientId", "ownerNickname", "name", "audio", "viewerCount"]),
};
@@ -481,6 +481,7 @@ export function parseSkinPluginDocument(input: unknown): SkinPluginDocument {
const isAriaOrData = inputSchemaVersion >= 3 && /^(?:aria|data)-[a-z][a-z0-9-]{0,47}$/.test(lowerKey);
if ((!ATTRIBUTES.has(lowerKey) && !isAriaOrData) || lowerKey.startsWith("on") || key !== lowerKey) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "The component uses an unsupported or executable attribute.");
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Component attributes must be scalar values.");
if (lowerKey === "src" && (node.tag !== "img" || value !== "{{server.icon}}")) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "Image sources may only bind to a TeamSpeak server icon.");
if (typeof value === "string" && ["fill", "stroke"].includes(lowerKey) && /\burl\s*\(|javascript\s*:/i.test(value)) fail("SKIN_PLUGIN_ATTRIBUTE_INVALID", "SVG paint attributes cannot load external or executable resources.");
if (typeof value === "string") {
for (const permission of bindingPermissions(value, aliases, stateKeys)) {