feat(kaak): show channel occupancy limits

This commit is contained in:
Corrupted ILLUSIA committed 2026-10-10 22:25:01 +08:00
1 parent 387462d89a
commit a3bf476db6
23 files changed
+244 -20

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { applyChannelCapacityNotification, parseChannelCapacities } from "./channel-capacity.js";
test("channel capacity rows keep finite limits and distinguish unlimited channels", () => {
const capacities = parseChannelCapacities([
{ cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0" },
{ cid: "2", channel_maxclients: "0", channel_flag_maxclients_unlimited: "1" },
{ cid: "3", channel_maxclients: "65536", channel_flag_maxclients_unlimited: "0" },
{ cid: "4", channel_maxclients: "12" },
{ cid: "18446744073709551616", channel_maxclients: "4", channel_flag_maxclients_unlimited: "0" },
]);
assert.deepEqual(capacities.get(1n), { maxClients: 10, maxClientsLimited: true });
assert.deepEqual(capacities.get(2n), { maxClients: 0, maxClientsLimited: false });
assert.equal(capacities.has(3n), false);
assert.equal(capacities.has(4n), false);
assert.equal(capacities.size, 2);
});
test("channel capacity notifications merge edits and remove deleted channels", () => {
const capacities = new Map([[1n, { maxClients: 10, maxClientsLimited: true }]]);
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_maxclients: "16" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneledited", { cid: "1", channel_flag_maxclients_unlimited: "1" }, capacities);
assert.deepEqual(capacities.get(1n), { maxClients: 16, maxClientsLimited: false });
applyChannelCapacityNotification("notifychannelcreated", {
cid: "2", channel_maxclients: "8", channel_flag_maxclients_unlimited: "0",
}, capacities);
assert.deepEqual(capacities.get(2n), { maxClients: 8, maxClientsLimited: true });
applyChannelCapacityNotification("notifychanneldeleted", { cid: "2" }, capacities);
assert.equal(capacities.has(2n), false);
});
+63
View File
@@ -0,0 +1,63 @@
export interface ChannelCapacity {
maxClients: number;
maxClientsLimited: boolean;
}
const UINT64_MAX = 18_446_744_073_709_551_615n;
function parseChannelId(value: string | undefined): bigint | null {
if (!value || !/^\d{1,20}$/.test(value)) return null;
try {
const id = BigInt(value);
return id > 0n && id <= UINT64_MAX ? id : null;
} catch {
return null;
}
}
export function parseChannelCapacity(row: Record<string, string>): ChannelCapacity | null {
const maxClientsRaw = row.channel_maxclients;
const unlimitedRaw = row.channel_flag_maxclients_unlimited;
if (!maxClientsRaw || !/^\d{1,5}$/.test(maxClientsRaw) || (unlimitedRaw !== "0" && unlimitedRaw !== "1")) return null;
const maxClients = Number(maxClientsRaw);
if (!Number.isSafeInteger(maxClients) || maxClients > 65_535) return null;
return { maxClients, maxClientsLimited: unlimitedRaw === "0" };
}
export function parseChannelCapacities(rows: readonly Record<string, string>[]): Map<bigint, ChannelCapacity> {
const capacities = new Map<bigint, ChannelCapacity>();
for (const row of rows) {
const id = parseChannelId(row.cid);
const capacity = parseChannelCapacity(row);
if (id !== null && capacity) capacities.set(id, capacity);
}
return capacities;
}
/** Keep capacity metadata in step with TeamSpeak's incremental channel events. */
export function applyChannelCapacityNotification(
name: string,
params: Record<string, string>,
capacities: Map<bigint, ChannelCapacity>,
): void {
const id = parseChannelId(params.cid);
if (id === null) return;
if (name === "notifychanneldeleted") {
capacities.delete(id);
return;
}
if (name !== "notifychannelcreated" && name !== "notifychanneledited") return;
const current = name === "notifychanneledited" ? capacities.get(id) : undefined;
const maxClientsRaw = params.channel_maxclients;
const unlimitedRaw = params.channel_flag_maxclients_unlimited;
const maxClients = maxClientsRaw !== undefined && /^\d{1,5}$/.test(maxClientsRaw) && Number(maxClientsRaw) <= 65_535
? Number(maxClientsRaw)
: current?.maxClients;
const unlimited = unlimitedRaw === "0" || unlimitedRaw === "1"
? unlimitedRaw === "1"
: current ? !current.maxClientsLimited : undefined;
if (maxClients === undefined || unlimited === undefined) return;
capacities.set(id, { maxClients, maxClientsLimited: !unlimited });
}
+3 -1
View File
@@ -5,7 +5,7 @@ import { mapChannelTree, normalizeDirectorySnapshot } from "./directory-view.js"
import { parseServerMessage } from "../shared/server-messages.js";
const directory = (): TSDirectorySnapshot => ({
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "" }],
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "" }, { id: 18446744073709551615n, parentID: 1n, order: 1n, name: "Room", description: "", maxClients: 10, maxClientsLimited: true }],
clients: [{ id: 2, channelID: 1n, nickname: "Member", uid: "uid-2", type: 0, serverGroups: [], away: true, inputMuted: true }],
});
@@ -36,5 +36,7 @@ test("directory presentation survives JSON transport with large IDs, member flag
assert.equal(decoded.channels[0]?.members?.[0]?.inputMuted, true);
assert.equal(decoded.channels[0]?.members?.[0]?.away, true);
assert.equal(decoded.channels[0]?.members?.[0]?.avatar, "data:image/png;base64,test");
assert.equal(decoded.channels[1]?.maxClients, 10);
assert.equal(decoded.channels[1]?.maxClientsLimited, true);
assert.deepEqual(decoded.channels[1]?.members, []);
});
+3
View File
@@ -8,6 +8,9 @@ export function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new
order: String(channel.order),
name: channel.name || "未命名频道",
description: channel.description || "",
...(typeof channel.maxClients === "number" && typeof channel.maxClientsLimited === "boolean"
? { maxClients: channel.maxClients, maxClientsLimited: channel.maxClientsLimited }
: {}),
members: snapshot.clients
.filter((client) => client.channelID === channel.id)
.map((client) => {
+32
View File
@@ -258,6 +258,38 @@ test("a current avatar download preserves its bytes and rejects a mismatched ide
assert.equal(f.sdk.downloaded, 1);
});
test("public channel capacity survives directory snapshots and follows channel edits", () => {
const f = fixture();
const snapshots: Array<{ channels: Array<{ id: bigint; maxClients?: number; maxClientsLimited?: boolean }>; clients: unknown[] }> = [];
f.client.on("directorySnapshot", snapshot => snapshots.push(snapshot));
f.sdk.emit("rawNotification", {
name: "notifychannelcreated",
params: { cid: "1", channel_maxclients: "10", channel_flag_maxclients_unlimited: "0" },
});
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 10);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
f.sdk.emit("rawNotification", { name: "notifychanneledited", params: { cid: "1", channel_maxclients: "12" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 12);
assert.equal(snapshots.at(-1)?.channels[0]?.maxClientsLimited, true);
f.sdk.emit("rawNotification", { name: "notifychanneldeleted", params: { cid: "1" } });
f.sdk.emit("directorySnapshot", {
channels: [{ id: 1n, parentID: 0n, order: 0n, name: "Room", description: "" }],
clients: [],
});
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, undefined);
});
test("a retired SDK client's disconnect cannot invalidate a current avatar request", async () => {
const f = fixture();
const replacement = new SdkStub();
+22 -3
View File
@@ -20,6 +20,7 @@ import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKick
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
import { createAccelerationRelayClient, type AccelerationRelayClient, type AccelerationRelayOptions } from "./acceleration-relay.js";
import { applyChannelCapacityNotification, parseChannelCapacities, type ChannelCapacity } from "./channel-capacity.js";
export interface TSClientOptions {
target: TeamSpeakTarget;
@@ -48,7 +49,8 @@ export interface TSClientAvatar {
// so every avatar silently fell back to its initial letter.
const MAX_CLIENT_AVATAR_BYTES = 256 * 1024;
export type TSDirectorySnapshot = DirectorySnapshot;
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity>;
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
export type TSDirectoryClient = DirectoryClientInfo;
export type TSRawNotification = RawNotification;
@@ -92,6 +94,7 @@ export class TSClient extends EventEmitter {
private inputStateQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
private readonly channelCapacities = new Map<bigint, ChannelCapacity>();
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
// tell a plain kick (4) from a kick with ban (5). The SDK only forwards the
// reason message to its `kicked` handler, not the reason id.
@@ -109,6 +112,7 @@ export class TSClient extends EventEmitter {
this.syncedInputMuted = null;
this.inputStateQueue = Promise.resolve();
this.selfLeaveReasonId = null;
this.channelCapacities.clear();
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
if (this.options.acceleration && !this.accelerationClient) {
@@ -163,7 +167,20 @@ export class TSClient extends EventEmitter {
tsListChannels(client),
tsListClients(client),
]);
this.emit("directorySnapshot", { channels, clients });
try {
// The high-level SDK directory type intentionally omits channel limit
// metadata. Its raw client-protocol rows still include the public
// maximum-client properties, so retain those without another SDK API.
const rows = await client.execCommandWithResponse("channellist", 5_000);
const capacities = parseChannelCapacities(rows);
for (const [id, capacity] of capacities) this.channelCapacities.set(id, capacity);
} catch (error: unknown) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not read TeamSpeak channel limits");
}
this.emit("directorySnapshot", {
channels: channels.map((channel) => ({ ...channel, ...this.channelCapacities.get(channel.id) })),
clients,
});
} catch (error: unknown) {
this.logger.warn({
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
@@ -273,13 +290,14 @@ export class TSClient extends EventEmitter {
client.on("directorySnapshot", (snapshot) => {
if (this.client !== client) return;
this.emit("directorySnapshot", {
channels: snapshot.channels.slice(),
channels: snapshot.channels.map((channel) => ({ ...channel, ...this.channelCapacities.get(channel.id) })),
clients: snapshot.clients.slice(),
});
});
client.on("rawNotification", (notification: RawNotification) => {
if (this.client !== client) return;
applyChannelCapacityNotification(notification.name, notification.params, this.channelCapacities);
this.emit("rawNotification", {
name: notification.name,
params: { ...notification.params },
@@ -310,6 +328,7 @@ export class TSClient extends EventEmitter {
}
this.connected = false;
this.clientId = 0;
this.channelCapacities.clear();
this.emit("disconnected", err);
});
+3 -1
View File
@@ -12,7 +12,7 @@ const samples: Record<ServerMessage["type"], ServerMessage> = {
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" },
channelList: { type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", members: [{ id: 1, nickname: "Owner" }] }] },
channelList: { type: "channelList", channels: [{ id: "1", parentID: "0", name: "Lobby", maxClients: 10, maxClientsLimited: true, members: [{ id: 1, nickname: "Owner" }] }] },
chatMessage: { type: "chatMessage", scope: "channel", targetId: "1", invokerId: 2, message: "hello" },
pokeReceived: { type: "pokeReceived", invokerId: 2, message: "poke" },
serverEvent: { type: "serverEvent", event },
@@ -61,6 +61,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: "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 }] },
{ type: "memberEnter", id: 65536, nickname: "bad id" },
{ type: "memberEnter", id: 1, nickname: "bad flag", inputMuted: "false" },
{ type: "serverEvent", event: { ...event, timestamp: Infinity } },
+3
View File
@@ -60,6 +60,9 @@ function member(value: unknown): value is ChannelMember {
function channel(value: unknown): value is ChannelInfo {
return isRecord(value) && text(value.id) && channelId(value.id) && text(value.parentID) && channelId(value.parentID)
&& text(value.name) && optional(value.order, text) && optional(value.description, text)
&& optional(value.maxClients, maximum => finite(maximum) && Number.isInteger(maximum) && maximum >= 0 && maximum <= 65_535)
&& optional(value.maxClientsLimited, boolean)
&& (value.maxClients === undefined) === (value.maxClientsLimited === undefined)
&& optional(value.members, members => arrayOf(members, member));
}
+1 -1
View File
@@ -216,7 +216,7 @@ const COLLECTION_PERMISSION: Record<string, SkinPluginPermission> = {
"screenShare.streams": "voice.screenShare.read",
};
const COLLECTION_FIELDS: Record<string, ReadonlySet<string>> = {
"session.channels": new Set(["id", "name", "parentId", "depth", "memberCount", "current"]),
"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"]),
+18 -2
View File
@@ -9,7 +9,7 @@ test("runtime context exposes only fields covered by declared read permissions",
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
session: {
status: { connected: true, serverLabel: "voice.internal.example:9987" },
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, current: true, address: "voice.internal.example:9987", members: [{ name: "private nested member" }] }],
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, memberCountLabel: "02", maxClients: 10, maxClientsLimited: true, current: true, address: "voice.internal.example:9987", members: [{ name: "private nested member" }] }],
members: [{ id: "member-1", name: "private member" }],
},
favorites: { items: [{ id: "opaque-1", label: "Saved", address: "secret.example:9987" }] },
@@ -17,7 +17,7 @@ test("runtime context exposes only fields covered by declared read permissions",
assert.deepEqual(JSON.parse(JSON.stringify(projected)), {
session: {
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, current: true }],
channels: [{ id: "channel-1", name: "Lobby", parentId: null, depth: 0, memberCount: 2, memberCountLabel: "02", maxClients: 10, maxClientsLimited: true, current: true }],
},
});
assert.equal(JSON.stringify(projected).includes("voice.internal.example"), false);
@@ -50,6 +50,22 @@ test("runtime context redacts connection targets from quick-list labels and drop
assert.equal(JSON.stringify(projected).includes("2001:db8::1"), false);
});
test("runtime channel limits are bounded public metadata and do not admit neighboring fields", () => {
const projected = projectSkinRuntimePluginContext(["session.channels.read"], {
session: {
channels: [{
id: "channel-1", name: "Lobby", memberCount: 2, memberCountLabel: "02",
maxClients: 65_536, maxClientsLimited: true, address: "voice.internal.example:9987",
}],
},
});
assert.deepEqual(JSON.parse(JSON.stringify(projected)), {
session: { channels: [{ id: "channel-1", name: "Lobby", memberCount: 2, memberCountLabel: "02", maxClientsLimited: true }] },
});
assert.equal(JSON.stringify(projected).includes("voice.internal.example"), false);
});
test("profile-picture display permission does not expose image data to declarative or Wasm contexts", () => {
const context = {
session: {
+5 -4
View File
@@ -25,7 +25,7 @@ interface CollectionProjection {
}
const COLLECTIONS: readonly CollectionProjection[] = Object.freeze([
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "parentId", "depth", "memberCount", "current"]), maxItems: 128 },
{ path: ["session", "channels"], permission: "session.channels.read", fields: new Set(["id", "name", "parentId", "depth", "memberCount", "memberCountLabel", "maxClients", "maxClientsLimited", "current"]), maxItems: 128 },
{ path: ["session", "members"], permission: "session.members.read", fields: new Set(["id", "name", "channelId", "status", "speaking", "self"]), maxItems: 256 },
{ path: ["favorites", "items"], permission: "favorites.read", fields: new Set(["id", "label", "current", "kind"]), maxItems: 100 },
{ path: ["servers", "quickList"], permission: "servers.quickList.read", fields: new Set(["id", "label", "current", "kind", "favorite"]), maxItems: 100 },
@@ -46,8 +46,8 @@ const CONTEXTS: readonly ContextProjection[] = Object.freeze([
{ path: ["screenShare", "status"], permission: "voice.screenShare.status.read", fields: new Set(["active", "starting", "viewing"]) },
]);
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "audio", "microphoneMuted", "outputMuted", "active", "starting", "viewing"]);
const NUMBER_FIELDS = new Set(["depth", "memberCount", "targetCount", "ownerClientId", "viewerCount"]);
const BOOLEAN_FIELDS = new Set(["connected", "connecting", "current", "favorite", "speaking", "self", "audio", "microphoneMuted", "outputMuted", "active", "starting", "viewing", "maxClientsLimited"]);
const NUMBER_FIELDS = new Set(["depth", "memberCount", "targetCount", "ownerClientId", "viewerCount", "maxClients"]);
const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
id: 128,
streamId: 128,
@@ -63,6 +63,7 @@ const TEXT_LIMITS: Readonly<Record<string, number>> = Object.freeze({
source: 48,
kind: 48,
time: 48,
memberCountLabel: 12,
text: 1_024,
});
@@ -86,7 +87,7 @@ function readPath(value: unknown, path: readonly string[]): unknown {
function boundedValue(field: string, value: unknown): string | number | boolean | null | undefined {
if (value === null) return field === "parentId" ? null : undefined;
if (BOOLEAN_FIELDS.has(field)) return typeof value === "boolean" ? value : undefined;
if (NUMBER_FIELDS.has(field)) return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 1_000_000_000
if (NUMBER_FIELDS.has(field)) return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= (field === "maxClients" ? 65_535 : 1_000_000_000)
? value
: undefined;
if (typeof value !== "string") return undefined;
+4
View File
@@ -19,6 +19,10 @@ export interface ChannelInfo {
order?: string;
name: string;
description?: string;
/** Maximum clients for this channel, when TeamSpeak reports a finite or unlimited setting. */
maxClients?: number;
/** False means the channel has no individual client limit. */
maxClientsLimited?: boolean;
members?: ChannelMember[];
}