mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
fix(admin): correct TeamSpeak member counts and action feedback
This commit is contained in:
1 parent
88439181ae
commit
4bff2133b6
9 files changed
+196
-26
No files matched your search
@@ -32,6 +32,8 @@ async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
|
||||
const clients: QueryClient[] = [];
|
||||
const clientOptions: QueryClientOptions[] = [];
|
||||
let httpStatus = 200;
|
||||
let httpCommand: string | undefined;
|
||||
let jsonErrors = false;
|
||||
let reply: (command: string, params: Record<string, string>) => Reply | Promise<Reply> = command => {
|
||||
switch (command) {
|
||||
case "version": return ok([{ version: family === "ts3" ? "3.13.7" : "6.0.0-beta13" }]);
|
||||
@@ -54,8 +56,8 @@ async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
|
||||
calls.push({ path, command, params, key: String(req.headers["x-api-key"]) });
|
||||
const answer = await reply(command, params);
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.statusCode = httpStatus;
|
||||
res.end(httpStatus === 200 ? JSON.stringify(answer) : "Access denied");
|
||||
res.statusCode = httpCommand === undefined || httpCommand === command ? httpStatus : 200;
|
||||
res.end(res.statusCode === 200 || jsonErrors ? JSON.stringify(answer) : "Access denied");
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
@@ -75,6 +77,8 @@ async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
|
||||
return { service, database, master, settings, calls, policy, logs, clientOptions,
|
||||
action: (operation: unknown) => service.action({ operation, configurationRevision: service.settings().configurationRevision }),
|
||||
set httpStatus(value: number) { httpStatus = value; },
|
||||
set httpCommand(value: string) { httpCommand = value; },
|
||||
set jsonErrors(value: boolean) { jsonErrors = value; },
|
||||
get reply() { return reply; }, set reply(value) { reply = value; } };
|
||||
}
|
||||
|
||||
@@ -136,6 +140,7 @@ test("limited list permissions preserve the rest of the overview and error detai
|
||||
f.reply = (command, params) => ["servergrouplist", "banlist"].includes(command) ? denied() : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.bansAvailable, false);
|
||||
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED"); assert.equal(result.bansErrorCode, "TS_ADMIN_PERMISSION_DENIED");
|
||||
assert.equal(result.channels.length, 1); assert.equal(result.clients.length, 1);
|
||||
f.reply = (command, params) => command === "serverinfo" ? denied() : original(command, params);
|
||||
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_PERMISSION_DENIED"));
|
||||
@@ -143,6 +148,75 @@ test("limited list permissions preserve the rest of the overview and error detai
|
||||
assert.ok(!JSON.stringify(f.logs).includes(f.settings.apiKey));
|
||||
});
|
||||
|
||||
test("Query connections never appear in member lists or channel and server member counts", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => {
|
||||
if (command === "clientlist") return ok([member, { ...member, clid: "99", client_type: "1", client_nickname: "serveradmin" }]);
|
||||
if (command === "channellist") return ok([{ ...channel, total_clients: "2" }, { ...channel, cid: "2", channel_name: "Empty" }]);
|
||||
return original(command, params);
|
||||
};
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.clientCount, 1); assert.deepEqual(result.clients.map(entry => entry.id), [42]);
|
||||
assert.deepEqual(result.channels.map(entry => entry.totalClients), [1, 0]);
|
||||
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, clid: "99", client_type: "1" }]) : original(command, params);
|
||||
const empty = await f.service.overview();
|
||||
assert.equal(empty.clientCount, 0); assert.deepEqual(empty.clients, []); assert.equal(empty.channels[0].totalClients, 0);
|
||||
});
|
||||
|
||||
for (const [code, expected] of [[524, "TS_ADMIN_RATE_LIMITED"], [2568, "TS_ADMIN_PERMISSION_DENIED"], [1538, "TS_ADMIN_READ_FAILED"]] as const) {
|
||||
test(`optional list error ${code} retains its cause rather than inventing a permission failure`, async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => command === "servergrouplist" ? { body: [], status: { code, message: "private-error-detail" } } : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
|
||||
assert.equal(result.bansAvailable, true); assert.equal(result.bansErrorCode, null);
|
||||
assert.equal(result.clients.length, 1); assert.ok(!JSON.stringify(result).includes("private-error-detail"));
|
||||
});
|
||||
}
|
||||
|
||||
for (const state of ["disconnected", "reused-id"] as const) test(`a successful UID ban with ${state} does not kick another connection or report partial failure`, async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
let banned = false;
|
||||
f.reply = (command, params) => {
|
||||
if (command === "banadd") banned = true;
|
||||
if (command === "clientlist" && banned) return ok(state === "disconnected" ? [] : [{ ...member, client_unique_identifier: "replacement-identity=" }]);
|
||||
return original(command, params);
|
||||
};
|
||||
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
|
||||
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
|
||||
assert.ok(!f.calls.some(call => call.command === "clientkick"));
|
||||
assert.ok(!f.database.recentAudit(50).some(entry => entry.event === "TS_ADMIN_ACTION_PARTIAL"));
|
||||
});
|
||||
|
||||
test("a banned client leaving between the fresh identity check and kick is successful", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.reply = (command, params) => command === "clientkick" ? { body: [], status: { code: 512, message: "invalid clientID" } } : original(command, params);
|
||||
assert.deepEqual(await f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID only", durationSeconds: 120 }), { ok: true });
|
||||
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
|
||||
});
|
||||
|
||||
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [408, "TS_ADMIN_TIMEOUT"], [504, "TS_ADMIN_TIMEOUT"]] as const) test(`HTTP ${status} has a specific safe Query failure`, async t => {
|
||||
const f = await fixture(t);
|
||||
f.httpStatus = status;
|
||||
await assert.rejects(f.service.overview(), hasCode(expected));
|
||||
});
|
||||
|
||||
for (const [status, expected] of [[429, "TS_ADMIN_RATE_LIMITED"], [503, "TS_ADMIN_READ_FAILED"]] as const) test(`HTTP ${status} cannot become a successful list through a JSON status.code=0 body`, async t => {
|
||||
const f = await fixture(t);
|
||||
f.httpStatus = status; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsAvailable, false); assert.equal(result.groupsErrorCode, expected);
|
||||
assert.equal(result.bansAvailable, true); assert.equal(result.clientCount, 1);
|
||||
});
|
||||
|
||||
test("HTTP errors carrying genuine TS permission errors keep the SDK error classification", async t => {
|
||||
const f = await fixture(t), original = f.reply;
|
||||
f.httpStatus = 403; f.httpCommand = "servergrouplist"; f.jsonErrors = true;
|
||||
f.reply = (command, params) => command === "servergrouplist" ? denied() : original(command, params);
|
||||
const result = await f.service.overview();
|
||||
assert.equal(result.groupsErrorCode, "TS_ADMIN_PERMISSION_DENIED");
|
||||
});
|
||||
|
||||
test("administrator actions use typed SDK commands, escaping and UID-only bans", async t => {
|
||||
const f = await fixture(t);
|
||||
const actions: TsAdminAction[] = [
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
addBan, addClientToServerGroup, asBanID, asChannelID, asClientID, asServerGroupID,
|
||||
createChannel, deleteBan, deleteChannel, editChannel, editServer, getServerInfo, kickClient,
|
||||
listBans, listChannels, listClients, listServerGroups, moveClient, Reason,
|
||||
removeClientFromServerGroup, ServerError, type CommandOptions,
|
||||
removeClientFromServerGroup, ServerError, ErrorCode, CommandTimeoutError, type CommandOptions,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import { QueryClient, WebQueryHttpError, type QueryClientOptions } from "@honeybbq/teamspeak/query";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -81,23 +81,31 @@ export class TsAdminService {
|
||||
]);
|
||||
const [groups, bans] = await Promise.allSettled([listServerGroups(client, options), listBans(client, options)]);
|
||||
assertCurrent();
|
||||
this.database.addAudit("TS_ADMIN_OVERVIEW_READ", { channels: channels.length, clients: clients.length });
|
||||
const voiceClients = clients.filter(entry => entry.type === 0);
|
||||
const channelMembers = new Map<string, number>();
|
||||
for (const entry of voiceClients) {
|
||||
const id = String(entry.channelID);
|
||||
channelMembers.set(id, (channelMembers.get(id) ?? 0) + 1);
|
||||
}
|
||||
this.database.addAudit("TS_ADMIN_OVERVIEW_READ", { channels: channels.length, clients: voiceClients.length });
|
||||
return {
|
||||
configurationRevision: this.configuration(),
|
||||
serverName: server.virtualserver_name ?? "", serverVersion: client.serverVersion, serverFamily: client.serverFamily,
|
||||
welcomeMessage: server.virtualserver_welcomemessage ?? "", maxClients: numeric(server.virtualserver_maxclients),
|
||||
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: clients.length,
|
||||
uptimeSeconds: numeric(server.virtualserver_uptime), channelCount: channels.length, clientCount: voiceClients.length,
|
||||
channels: channels.map(channel => ({ id: String(channel.id), parentID: String(channel.parentID), name: channel.name,
|
||||
description: channel.description, totalClients: channel.totalClients ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: clients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
description: channel.description, totalClients: channelMembers.get(String(channel.id)) ?? 0, hasPassword: channel.hasPassword })),
|
||||
clients: voiceClients.map(entry => ({ id: Number(entry.id), uid: entry.uid, nickname: entry.nickname, channelID: String(entry.channelID),
|
||||
serverGroups: entry.serverGroups.map(String), away: entry.isAway, inputMuted: entry.isInputMuted ?? false, outputMuted: entry.isOutputMuted ?? false })),
|
||||
groups: groups.status === "fulfilled" ? groups.value.filter(group => group.type === 1).map(group => ({ id: String(group.id), name: group.name })) : [],
|
||||
bans: bans.status === "fulfilled" ? bans.value.map(ban => ({ id: String(ban.id), name: ban.name || ban.lastNickname,
|
||||
uid: ban.uid, reason: ban.reason, durationSeconds: ban.durationMs / 1000, createdAt: ban.createdAt?.toISOString() ?? null })) : [],
|
||||
groupsAvailable: groups.status === "fulfilled", bansAvailable: bans.status === "fulfilled",
|
||||
groupsErrorCode: groups.status === "fulfilled" ? null : classifyError(groups.reason, "TS_ADMIN_READ_FAILED"),
|
||||
bansErrorCode: bans.status === "fulfilled" ? null : classifyError(bans.reason, "TS_ADMIN_READ_FAILED"),
|
||||
observedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
}, undefined, "TS_ADMIN_READ_FAILED");
|
||||
}
|
||||
|
||||
/** Serialize writes, then revalidate live client identities immediately before changing them. */
|
||||
@@ -136,7 +144,19 @@ export class TsAdminService {
|
||||
} else {
|
||||
// Banning the gateway's IP would disconnect unrelated WebSpeak users.
|
||||
await addBan(client, { uid: current.uid, reason: action.reason, durationMs: action.durationSeconds * 1000 }, options);
|
||||
try { assertCurrent(); await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason }); }
|
||||
try {
|
||||
assertCurrent();
|
||||
// TS may disconnect the banned identity itself. Never kick a replacement that reused its ID.
|
||||
const remaining = (await listClients(client, { ...options, uid: true })).find(entry => entry.id === current.id);
|
||||
assertCurrent();
|
||||
if (remaining?.uid === current.uid && remaining.type === 0) {
|
||||
try { await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason }); }
|
||||
catch (error) {
|
||||
// The same client can leave between the fresh list and the kick.
|
||||
if (!(error instanceof ServerError && error.code === ErrorCode.ClientInvalidID)) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { this.database.addAudit("TS_ADMIN_ACTION_PARTIAL", { action: action.action }); fail("TS_ADMIN_PARTIAL_SUCCESS"); }
|
||||
}
|
||||
}
|
||||
@@ -155,7 +175,7 @@ export class TsAdminService {
|
||||
return createHash("sha256").update(JSON.stringify([this.policy(), this.database.getTsAdminSettings()])).digest("hex");
|
||||
}
|
||||
|
||||
private async withClient<T>(run: (client: QueryClient, options: CommandOptions, assertCurrent: () => void) => Promise<T>, expected?: string): Promise<T> {
|
||||
private async withClient<T>(run: (client: QueryClient, options: CommandOptions, assertCurrent: () => void) => Promise<T>, expected?: string, failureCode = "TS_ADMIN_OPERATION_FAILED"): Promise<T> {
|
||||
this.assertFixed();
|
||||
if (expected !== undefined && this.configuration() !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
|
||||
const settings = this.database.getTsAdminSettings();
|
||||
@@ -196,7 +216,7 @@ export class TsAdminService {
|
||||
return await run(client, { signal, timeoutMs: 8_000 }, assertCurrent);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminInputError) throw error;
|
||||
const code = classifyError(error, connected ? "TS_ADMIN_OPERATION_FAILED" : "TS_ADMIN_CONNECTION_FAILED");
|
||||
const code = classifyError(error, connected ? failureCode : "TS_ADMIN_CONNECTION_FAILED");
|
||||
this.logger.warn({ code, transport: settings.transport }, "TeamSpeak administrator request failed");
|
||||
return fail(code);
|
||||
} finally {
|
||||
@@ -267,6 +287,9 @@ function classifyError(error: unknown, fallback: string): string {
|
||||
seen.add(error);
|
||||
if (error.message === "TS_ADMIN_HOST_KEY_MISMATCH") return error.message;
|
||||
if (error instanceof WebQueryHttpError && [401, 403].includes(error.status)) return "TS_ADMIN_AUTH_FAILED";
|
||||
if (error instanceof WebQueryHttpError && error.status === 429) return "TS_ADMIN_RATE_LIMITED";
|
||||
if (error instanceof CommandTimeoutError || ["TimeoutError", "AbortError"].includes(error.name)
|
||||
|| error instanceof WebQueryHttpError && [408, 504].includes(error.status)) return "TS_ADMIN_TIMEOUT";
|
||||
if (error instanceof ServerError) {
|
||||
if ([2568, 2569, 2570, 5120].includes(error.code)) return "TS_ADMIN_PERMISSION_DENIED";
|
||||
if ([520, 5122, 5124].includes(error.code)) return "TS_ADMIN_AUTH_FAILED";
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { request as httpRequest } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
import { WebQueryHttpError } from "@honeybbq/teamspeak/query";
|
||||
|
||||
/** Keep the SDK's WebQuery protocol, but bound HTTP requests to this admin operation.
|
||||
* Node's global fetch blocks WebQuery's default port 10080. */
|
||||
@@ -18,9 +19,20 @@ export function webQueryFetch(lifetime: AbortSignal): typeof fetch {
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on("error", reject);
|
||||
res.on("end", () => resolve(new Response(Buffer.concat(chunks), {
|
||||
status: res.statusCode ?? 502, statusText: res.statusMessage ?? "",
|
||||
})));
|
||||
res.on("end", () => {
|
||||
const body = Buffer.concat(chunks), status = res.statusCode ?? 502;
|
||||
if (status < 200 || status >= 300) {
|
||||
// SDK beta.19 accepts status.code=0 even on HTTP failures. Keep genuine TS errors,
|
||||
// but never turn a proxy's failed HTTP response into a successful empty result.
|
||||
let tsError = false;
|
||||
try {
|
||||
const code: unknown = JSON.parse(body.toString("utf8"))?.status?.code;
|
||||
tsError = typeof code === "number" && Number.isSafeInteger(code) && code > 0;
|
||||
} catch { /* HTTP status is authoritative when no TS error is present. */ }
|
||||
if (!tsError) { reject(new WebQueryHttpError(status, res.statusMessage ?? "")); return; }
|
||||
}
|
||||
resolve(new Response(body, { status, statusText: res.statusMessage ?? "" }));
|
||||
});
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.end(init.body as string);
|
||||
|
||||
@@ -87,6 +87,7 @@ const tsAdminOverview = object({
|
||||
channels: array(object({ id: text, parentID: text, name: text, description: text, totalClients: number, hasPassword: boolean })),
|
||||
clients: array(object({ id: number, uid: text, nickname: text, channelID: text, serverGroups: array(text), away: boolean, inputMuted: boolean, outputMuted: boolean })),
|
||||
groups: array(object({ id: text, name: text })), groupsAvailable: boolean, bansAvailable: boolean,
|
||||
groupsErrorCode: optional(nullable(text)), bansErrorCode: optional(nullable(text)),
|
||||
bans: array(object({ id: text, name: text, uid: text, reason: text, durationSeconds: number, createdAt: nullable(text) })),
|
||||
observedAt: text,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user