feat(kaak): render TeamSpeak server banner

This commit is contained in:
illusia committed 2026-10-11 19:50:35 +08:00
1 parent 766a9b9b5a
commit 398a4d6c7f
24 files changed
+335 -27

No files matched your search

+26 -1
View File
@@ -19,6 +19,7 @@ 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 };
serverPresentationRows: Array<Record<string, string>> = [];
inputUpdate = async (_command: string): Promise<void> => {};
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
initialized = 0;
@@ -26,7 +27,10 @@ class SdkStub extends EventEmitter {
metadata = async () => rows;
transfer = async () => transfer;
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
execCommandWithResponse(command = "") { this.inputCommands.push(command); return this.metadata(); }
execCommandWithResponse(command = "") {
this.inputCommands.push(command);
return command === "serverinfo" ? Promise.resolve(this.serverPresentationRows) : this.metadata();
}
async fileTransferInitDownload(channelId: bigint, path: string, password: string) {
this.initialized++;
this.fileTransfers.push({ channelId, path, password });
@@ -67,6 +71,27 @@ test("server info uses the name and icon id captured by the SDK handshake", asyn
assert.deepEqual(await f.client.getServerInfo(), { name: "No icon", iconId: null });
});
test("server presentation reads bounded public banner and welcome fields", async () => {
const f = fixture();
f.sdk.serverPresentationRows = [{
virtualserver_hostbanner_gfx_url: "https://assets.example.invalid/teamspeak/banner.png",
virtualserver_welcomemessage: "欢迎来到服务器!\n请遵守频道规则。",
}];
assert.deepEqual(await f.client.getServerPresentation(), {
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png",
welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
});
assert.deepEqual(f.sdk.inputCommands, ["serverinfo"]);
f.sdk.serverPresentationRows = [{
virtualserver_hostbanner_gfx_url: "javascript:alert(1)",
virtualserver_welcomemessage: "x".repeat(5_000),
}];
const sanitized = await f.client.getServerPresentation();
assert.equal(sanitized.bannerUrl, null);
assert.equal(sanitized.welcomeMessage.length, 4_096);
});
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");
+48
View File
@@ -49,11 +49,18 @@ export interface TSClientServerInfo {
iconId: number | null;
}
export interface TSClientServerPresentation {
bannerUrl: string | null;
welcomeMessage: string;
}
// 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;
const MAX_SERVER_BANNER_URL_LENGTH = 2_048;
const MAX_SERVER_WELCOME_MESSAGE_LENGTH = 4_096;
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity>;
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
@@ -291,6 +298,29 @@ export class TSClient extends EventEmitter {
return client.serverInfo ?? { name: "", iconId: null };
}
/** Read only the public banner and welcome message from the active virtual server. */
async getServerPresentation(): Promise<TSClientServerPresentation> {
const client = this.client;
if (!client || !this.connected) throw new Error("TeamSpeak session is not ready");
const generation = this.connectionGeneration;
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
const empty: TSClientServerPresentation = { bannerUrl: null, welcomeMessage: "" };
try {
const rows = await client.execCommandWithResponse("serverinfo", 5_000);
if (!isCurrent()) throw new Error("TeamSpeak session changed while reading server presentation");
const row = rows[0] ?? {};
return {
bannerUrl: normalizeTeamSpeakBannerUrl(row.virtualserver_hostbanner_gfx_url),
welcomeMessage: normalizeTeamSpeakWelcomeMessage(row.virtualserver_welcomemessage),
};
} catch (error: unknown) {
if (!isCurrent()) throw error;
// Some servers restrict serverinfo. Keep the voice connection usable and
// omit the optional presentation when the fields cannot be read.
return empty;
}
}
/** Download the public virtual-server icon using TeamSpeak's normal file-transfer port. */
async getServerIcon(iconId: number): Promise<Buffer | null> {
const client = this.client;
@@ -569,6 +599,24 @@ export class TSClient extends EventEmitter {
}
}
function normalizeTeamSpeakBannerUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
const candidate = value.trim();
if (!candidate || candidate.length > MAX_SERVER_BANNER_URL_LENGTH) return null;
try {
const url = new URL(candidate);
if ((url.protocol !== "https:" && url.protocol !== "http:") || url.username || url.password) return null;
return url.toString();
} catch {
return null;
}
}
function normalizeTeamSpeakWelcomeMessage(value: unknown): string {
if (typeof value !== "string") return "";
return value.replace(/\0/g, "").replace(/\r\n?/g, "\n").slice(0, MAX_SERVER_WELCOME_MESSAGE_LENGTH).trim();
}
function escapeTeamSpeakValue(value: string): string {
return value
.replace(/\\/g, "\\\\")
+19 -2
View File
@@ -23,12 +23,17 @@ class TeamSpeakStub extends EventEmitter {
emitDirectorySnapshotOnConnect = true;
connectCalls = 0;
serverInfoCalls = 0;
serverPresentationCalls = 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 getServerPresentation() {
this.serverPresentationCalls++;
return { bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。" };
}
async getServerIcon() { return null; }
async sendProtocolCommand() {}
async setAccompanimentActive() {}
@@ -98,15 +103,27 @@ test("server identity lookup waits until the directory sync publishes the connec
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);
if (message.type === "serverInfo" && message.bannerUrl === null) resolve(message);
});
});
const serverPresentation = 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" && message.bannerUrl === "https://assets.example.invalid/teamspeak/banner.png") resolve(message);
});
});
f.sdk.emit("directorySnapshot", f.sdk.directory);
assert.deepEqual(await serverInfo, { type: "serverInfo", name: "兄弟们的teamspeak", icon: null });
assert.deepEqual(await serverInfo, { type: "serverInfo", name: "兄弟们的teamspeak", icon: null, bannerUrl: null, welcomeMessage: "" });
assert.deepEqual(await serverPresentation, {
type: "serverInfo", name: "兄弟们的teamspeak", icon: null,
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
});
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.equal(f.sdk.serverPresentationCalls, 1);
assert.ok(f.bridge.getActiveCount() > 0);
});
+14 -6
View File
@@ -310,12 +310,20 @@ export class VoiceBridge {
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 });
const publicInfo = { name, icon: null as string | null, bannerUrl: null as string | null, welcomeMessage: "" };
sendJson({ type: "serverInfo", ...publicInfo });
const [presentation, icon] = await Promise.all([
tsClient.getServerPresentation().catch((error: unknown) => {
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server presentation unavailable");
return { bannerUrl: null, welcomeMessage: "" };
}),
info.iconId ? tsClient.getServerIcon(info.iconId).catch(() => null) : Promise.resolve(null),
]);
if (!isCurrent()) return;
publicInfo.bannerUrl = presentation.bannerUrl;
publicInfo.welcomeMessage = presentation.welcomeMessage;
publicInfo.icon = icon ? avatarDataUrl(icon) : null;
sendJson({ type: "serverInfo", ...publicInfo });
} catch (error: unknown) {
if (isCurrent()) this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "TeamSpeak server icon unavailable");
}
+6 -1
View File
@@ -9,7 +9,10 @@ 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=" },
serverInfo: {
type: "serverInfo", name: "兄弟们的teamspeak", icon: "data:image/png;base64,iVBORw0KGgo=",
bannerUrl: "https://assets.example.invalid/teamspeak/banner.png", welcomeMessage: "欢迎来到服务器!\n请遵守频道规则。",
},
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" },
@@ -62,6 +65,8 @@ test("malformed nested directory and event data is rejected before client state
{ 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: "serverInfo", name: "TeamSpeak", bannerUrl: "javascript:alert(1)" },
{ type: "serverInfo", name: "TeamSpeak", welcomeMessage: "x".repeat(4_097) },
{ 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 }] },
+13 -2
View File
@@ -13,7 +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<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
| Message<"memberEnter", ChannelMember>
| Message<"memberLeave", { id: number }>
| Message<"memberAvatar", { id: number; uid?: string; avatar?: string }>
@@ -51,6 +51,15 @@ const identifier = (value: unknown): value is string => text(value) && value.len
const channelId = (value: unknown): value is string | number => (text(value) && /^\d{1,20}$/.test(value)) || (finite(value) && Number.isSafeInteger(value) && value >= 0);
const optional = (value: unknown, check: (value: unknown) => boolean): boolean => value === undefined || check(value);
const arrayOf = (value: unknown, check: (value: unknown) => boolean): boolean => Array.isArray(value) && value.every(check);
const safeHttpUrl = (value: unknown): boolean => {
if (!text(value) || value.length > 2_048) return false;
try {
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
} catch {
return false;
}
};
function member(value: unknown): value is ChannelMember {
return isRecord(value) && clientId(value.id) && text(value.nickname)
@@ -118,7 +127,9 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
&& 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))),
&& /^data:image\/(?:png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(v)))
&& optional(m.bannerUrl, v => v === null || safeHttpUrl(v))
&& optional(m.welcomeMessage, v => text(v) && v.length <= 4_096),
memberEnter: member,
memberLeave: m => clientId(m.id),
memberAvatar: m => clientId(m.id) && optional(m.uid, text) && optional(m.avatar, text),
+1
View File
@@ -44,6 +44,7 @@ test("the stable layout registry covers public skin hooks and excludes the admin
assert.equal(micStatus?.category, "core");
assert.equal(micStatus?.editable, true);
assert.ok(micStatus?.layoutModes.includes("visibility"));
assert.equal(getSkinLayoutComponent("voice.server-banner", "voice")?.editable, true);
for (const part of interactiveParts) {
const component = SKIN_LAYOUT_COMPONENTS.find((entry) => entry.id === part);
assert.ok(component, "Interactive public hook must have its own component metadata: " + part);
+6
View File
@@ -189,6 +189,12 @@ const PUBLIC_PART_IDS = new Set<string>([
"voice.channel-tree.node",
"voice.channel-tree.row",
"voice.server-switcher",
"voice.server-banner",
"voice.server-banner.body",
"voice.server-banner.icon",
"voice.server-banner.image",
"voice.server-banner.title",
"voice.server-banner.welcome",
"voice.server-switcher.current",
"voice.server-switcher.empty",
"voice.server-switcher.icon",
+15 -3
View File
@@ -151,7 +151,7 @@ test("host widget references stay allowlisted and cannot be used on the demo pag
errorCode(() => parseSkinPluginDocument(demoWidget), "SKIN_PLUGIN_WIDGET_INVALID");
});
test("starting screen share from a skin host widget requires its own permission", () => {
test("starting screen share from a skin host widget requires its own permission", () => {
const document = validDocument();
document.schemaVersion = 2;
document.components[0].root = { tag: "main", children: [{ widget: "voice.screen-share-start" }] };
@@ -160,8 +160,20 @@ test("starting screen share from a skin host widget requires its own permission"
document.components[0].permissions = ["voice.screenShare.control"];
document.components[0].actions = {};
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.screen-share-start");
});
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.screen-share-start");
});
test("server banner host widget only exposes public session status fields", () => {
const document = validDocument();
document.schemaVersion = 3;
document.components[0].actions = {};
document.components[0].root = { tag: "main", children: [{ widget: "voice.server-banner" }] };
errorCode(() => parseSkinPluginDocument(document), "SKIN_PLUGIN_PERMISSION_MISSING");
document.components[0].permissions = ["session.status.read"];
const parsed = parseSkinPluginDocument(document);
assert.equal(parsed.components[0].root.children?.[0].widget, "voice.server-banner");
});
test("schema v3 host audio controls require read and control permissions while v2 remains compatible", () => {
const document = validDocument();
+2
View File
@@ -46,6 +46,7 @@ export const SKIN_PLUGIN_HOST_WIDGETS = Object.freeze([
"app.language-switcher",
"voice.server-switcher",
"voice.server-header",
"voice.server-banner",
"voice.channel-tree",
"voice.channel-panel",
"voice.member-cards",
@@ -72,6 +73,7 @@ export const SKIN_PLUGIN_HOST_WIDGET_PERMISSIONS: Partial<Record<SkinPluginHostW
"voice.channel-tree": widgetPermissions("session.channels.read", "session.members.read", "session.memberAvatars.read", "session.channel.join"),
"voice.server-switcher": widgetPermissions("servers.quickList.read", "servers.quickList.switch"),
"voice.server-header": widgetPermissions("session.status.read", "servers.quickList.read", "servers.quickList.switch"),
"voice.server-banner": widgetPermissions("session.status.read"),
"voice.audio-controls": widgetPermissions("audio.status.read", "audio.microphone.control", "audio.output.control"),
"voice.chat-panel": widgetPermissions("chat.channel.read", "chat.channel.send"),
"voice.connection-controls": widgetPermissions("voice.disconnect"),