fix(admin): correct TeamSpeak member counts and action feedback

This commit is contained in:
illusia committed 2026-10-24 18:16:00 +08:00
1 parent 88439181ae
commit 4bff2133b6
9 files changed
+196 -26

No files matched your search

+76 -2
View File
@@ -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[] = [
+32 -9
View File
@@ -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";
+15 -3
View File
@@ -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);
+1
View File
@@ -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,
});
+5 -4
View File
@@ -5,6 +5,7 @@
<div v-if="!settings.fixedMode" class="alert info admin-fixed-notice"><Icon name="info" :size="18"/><div><p>{{ tr('tsAdminFixedOnly') }}</p><RouterLink to="/admin/server">{{ tr('adminInstanceSettings') }}</RouterLink></div></div>
<template v-else>
<div v-if="noticeMessage" class="alert success" role="status">{{ noticeMessage }}</div>
<div v-if="refreshWarning" class="alert info" role="status">{{ refreshWarning }}</div>
<article v-if="!settings.enabled && !loading" class="operation-card admin-ts-setup">
<Icon name="server" :size="26"/><div><h3>{{ tr('adminTsSetupTitle') }}</h3><p>{{ tr('adminTsSetupLead') }}</p></div>
<button class="secondary-button" type="button" @click="configureConnection">{{ tr('adminTsConfigure') }}</button>
@@ -63,7 +64,7 @@
<template v-if="editor.action === 'channel.create'">
<label><span>{{ tr('tsAdminParent') }}</span><select v-model="editor.parentId"><option value="0">{{ tr('tsAdminRoot') }}</option><option v-for="channel in overview?.channels" :key="channel.id" :value="channel.id">{{ channel.name }}</option></select></label>
<label class="ts-admin-wide"><span>{{ tr('tsAdminDescription') }}</span><textarea v-model="editor.description" maxlength="8192" rows="3"></textarea></label>
<label><span>{{ tr('tsAdminPassword') }}</span><input v-model="editor.password" type="password" autocomplete="new-password" maxlength="512" /></label><label class="choice"><input v-model="editor.permanent" type="checkbox" /><span>{{ tr('tsAdminPermanent') }}</span></label>
<label><span>{{ tr('tsAdminChannelPassword') }}</span><input v-model="editor.password" type="password" autocomplete="new-password" maxlength="512" /></label><label class="choice"><input v-model="editor.permanent" type="checkbox" /><span>{{ tr('tsAdminPermanent') }}</span></label>
</template>
<label v-if="editor.action === 'client.move'"><span>{{ tr('tsAdminChannel') }}</span><select v-model="editor.channelId" required><option v-for="channel in overview?.channels" :key="channel.id" :value="channel.id">{{ channel.name }}</option></select></label>
<template v-if="editor.action === 'client.group'"><label><span>{{ tr('tsAdminGroup') }}</span><select v-model="editor.groupId" required><option v-for="group in overview?.groups" :key="group.id" :value="group.id">{{ group.name }} (#{{ group.id }})</option></select></label><label class="choice"><input v-model="editor.remove" type="checkbox" /><span>{{ tr('tsAdminRemoveGroup') }}</span></label></template>
@@ -87,12 +88,12 @@
<tr v-if="!overview.channels.length"><td colspan="4">{{ tr('tsAdminNoChannels') }}</td></tr></tbody></table></div></section>
</div>
<div v-show="activeSection === 'clients'" data-admin-section="clients" class="admin-ts-section">
<p v-if="!overview.groupsAvailable" class="field-help">{{ tr('tsAdminGroup') }}: {{ tr('tsAdminRestricted') }}</p>
<p v-if="!overview.groupsAvailable" class="field-help">{{ tr('tsAdminGroup') }}: {{ listErrorText(overview.groupsErrorCode) }}</p>
<section class="operation-card"><header><h3>{{ tr('tsAdminClients') }}</h3><strong>{{ overview.clients.length }}</strong></header><div class="table-wrap" role="region" tabindex="0" :aria-label="tr('tsAdminClients')"><table><thead><tr><th>{{ tr('nickname') }}</th><th>{{ tr('tsAdminChannel') }}</th><th>{{ tr('tsAdminGroup') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody>
<tr v-for="client in overview.clients" :key="client.id"><td><strong>{{ client.nickname }}</strong><small>#{{ client.id }}</small></td><td>{{ channelNames.get(client.channelID) || client.channelID }}</td><td>{{ client.serverGroups.map(id => groupNames.get(id) || id).join(', ') || '—' }}</td><td><div class="ts-admin-row-actions"><button type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.move', client)">{{ tr('tsAdminMove') }}</button><button type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid || !overview.groupsAvailable" @click="beginAction('client.group', client)">{{ tr('tsAdminGroupAction') }}</button><button class="danger" type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.kick', client)">{{ tr('tsAdminKick') }}</button><button class="danger" type="button" :disabled="settingsDirty || loading || saving || acting || !client.uid" @click="beginAction('client.ban', client)">{{ tr('tsAdminBan') }}</button></div></td></tr>
<tr v-if="!overview.clients.length"><td colspan="4">{{ tr('tsAdminNoClients') }}</td></tr></tbody></table></div></section>
</div>
<div v-show="activeSection === 'bans'" data-admin-section="bans" class="admin-ts-section"><section class="operation-card"><header><h3>{{ tr('tsAdminBans') }}</h3><strong>{{ overview.bans.length }}</strong></header><p v-if="!overview.bansAvailable" class="field-help">{{ tr('tsAdminRestricted') }}</p><div v-else class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }} / UID</th><th>{{ tr('tsAdminReason') }}</th><th>{{ tr('tsAdminBanDuration') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody><tr v-for="ban in overview.bans" :key="ban.id"><td>{{ ban.name || ban.uid || `#${ban.id}` }}</td><td>{{ ban.reason || '—' }}</td><td>{{ ban.durationSeconds }}</td><td><button type="button" class="secondary-button" :disabled="settingsDirty || loading || saving || acting" @click="beginAction('ban.delete', ban)">{{ tr('remove') }}</button></td></tr><tr v-if="!overview.bans.length"><td colspan="4">{{ tr('tsAdminNoBans') }}</td></tr></tbody></table></div></section></div>
<div v-show="activeSection === 'bans'" data-admin-section="bans" class="admin-ts-section"><section class="operation-card"><header><h3>{{ tr('tsAdminBans') }}</h3><strong>{{ overview.bans.length }}</strong></header><p v-if="!overview.bansAvailable" class="field-help">{{ listErrorText(overview.bansErrorCode) }}</p><div v-else class="table-wrap"><table><thead><tr><th>{{ tr('nickname') }} / UID</th><th>{{ tr('tsAdminReason') }}</th><th>{{ tr('tsAdminBanDuration') }}</th><th>{{ tr('tsAdminTitle') }}</th></tr></thead><tbody><tr v-for="ban in overview.bans" :key="ban.id"><td>{{ ban.name || ban.uid || `#${ban.id}` }}</td><td>{{ ban.reason || '—' }}</td><td>{{ ban.durationSeconds }}</td><td><button type="button" class="secondary-button" :disabled="settingsDirty || loading || saving || acting" @click="beginAction('ban.delete', ban)">{{ tr('remove') }}</button></td></tr><tr v-if="!overview.bans.length"><td colspan="4">{{ tr('tsAdminNoBans') }}</td></tr></tbody></table></div></section></div>
</template>
</article>
</template>
@@ -109,7 +110,7 @@ import type { AdminTranslationKey } from '../../i18n/admin.js';
import Icon from '../Icon.vue';
const props = defineProps<{ model: ReturnType<typeof useAdminTsAdmin>; i18n: Pick<ReturnType<typeof useAdminI18n>, 'tr' | 'formatDate'>; targetAddress: string; targetPort: string }>();
const {tr, formatDate} = props.i18n;
const {settings, form, editor, overview, settingsDirty, noticeMessage, loading, saving, connecting, acting, saveSettings, connectAndRefresh, beginAction, closeAction, runAction} = props.model;
const {settings, form, editor, overview, settingsDirty, noticeMessage, refreshWarning, listErrorText, loading, saving, connecting, acting, saveSettings, connectAndRefresh, beginAction, closeAction, runAction} = props.model;
const connectionOpen = ref(false);
const connectionPanel = ref<HTMLDetailsElement | null>(null);
async function configureConnection() {
+1
View File
@@ -50,6 +50,7 @@ const errorLabels: Record<string, AdminTranslationKey> = {
TS_ADMIN_PERMISSION_DENIED: "tsAdminPermissionError", TS_ADMIN_AUTH_FAILED: "tsAdminAuthError", TS_ADMIN_OPERATION_FAILED: "tsAdminActionError",
TS_ADMIN_CLIENT_CHANGED: "tsAdminClientChanged", TS_ADMIN_CONFIG_CHANGED: "tsAdminConfigChanged", TS_ADMIN_PARTIAL_SUCCESS: "tsAdminPartialError",
TS_ADMIN_RATE_LIMITED: "tsAdminRateError", TS_ADMIN_TLS_FAILED: "tsAdminTlsError",
TS_ADMIN_READ_FAILED: "tsAdminReadError", TS_ADMIN_TIMEOUT: "tsAdminTimeoutError",
};
const connectionErrors: Record<string, AdminTranslationKey> = {
PASSWORD_REQUIRED: "serverPasswordRequiredError", SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
+17 -7
View File
@@ -25,6 +25,7 @@ export function useAdminTsAdmin(options: Options) {
const settings = reactive(emptySettings()), form = reactive(emptyForm()), editor = reactive(emptyEditor());
const overview = ref<Awaited<ReturnType<AdminApi["tsAdminOverview"]>> | null>(null);
const noticeMessage = ref("");
const refreshWarning = ref("");
const loading = ref(false), saving = ref(false), connecting = ref(false), acting = ref(false);
const settingsDirty = computed(() => form.enabled !== settings.enabled || form.transport !== settings.transport
|| form.queryHost !== settings.queryHost || form.webQueryUrl !== settings.webQueryUrl
@@ -40,6 +41,7 @@ export function useAdminTsAdmin(options: Options) {
function cancelRequests() {
requests.reset(); loading.value = false; saving.value = false; connecting.value = false; acting.value = false;
Object.assign(editor, emptyEditor());
refreshWarning.value = "";
}
function reset() {
cancelRequests(); Object.assign(settings, emptySettings()); Object.assign(form, emptyForm()); overview.value = null; noticeMessage.value = "";
@@ -51,6 +53,7 @@ export function useAdminTsAdmin(options: Options) {
function mergeSettings(value: Awaited<ReturnType<AdminApi["tsAdminSettings"]>>, baseline: Form) {
if (settings.configurationRevision && settings.configurationRevision !== value.configurationRevision) {
requests.cancel("overview"); connecting.value = false; overview.value = null; Object.assign(editor, emptyEditor());
refreshWarning.value = "";
}
Object.assign(settings, value);
const next: Form = { enabled: value.enabled, transport: value.transport, queryHost: value.queryHost, webQueryUrl: value.webQueryUrl,
@@ -77,7 +80,7 @@ export function useAdminTsAdmin(options: Options) {
if (saving.value || acting.value) return;
requests.cancel("overview"); connecting.value = false;
const request = requests.begin("settings"), baseline = { ...form };
saving.value = true; loading.value = false; options.errorMessage.value = ""; noticeMessage.value = "";
saving.value = true; loading.value = false; options.errorMessage.value = ""; noticeMessage.value = ""; refreshWarning.value = "";
try {
const saved = await options.api.saveTsAdminSettings({ ...baseline, queryPort: Number(baseline.queryPort),
password: baseline.passwordAction === "replace" ? baseline.password : undefined,
@@ -89,12 +92,19 @@ export function useAdminTsAdmin(options: Options) {
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) saving.value = false; request.finish(); }
}
async function connectAndRefresh() {
function listErrorText(code?: string | null) { return options.errorText(code || "TS_ADMIN_READ_FAILED"); }
async function connectAndRefresh() { await readOverview(false); }
async function readOverview(afterAction: boolean) {
if (loading.value || connecting.value || saving.value || acting.value || settingsDirty.value || !settings.enabled || !settings.fixedMode) return;
const request = requests.begin("overview");
connecting.value = true; options.errorMessage.value = "";
connecting.value = true; options.errorMessage.value = ""; refreshWarning.value = "";
try { const value = await options.api.tsAdminOverview(request.signal); if (request.isCurrent()) overview.value = value; }
catch (error) { if (request.isCurrent()) report(error); }
catch (error) {
if (request.isCurrent() && !isAdminRequestCancelled(error)) {
if (afterAction) refreshWarning.value = options.tr("tsAdminRefreshError", { error: listErrorText((error as { code?: string }).code) });
else report(error);
}
}
finally { if (request.isCurrent()) connecting.value = false; request.finish(); }
}
function beginAction(action: TsAdminAction["action"], target?: { id: number | string; uid?: string; nickname?: string; name?: string; channelID?: string }) {
@@ -125,17 +135,17 @@ export function useAdminTsAdmin(options: Options) {
if (acting.value || saving.value || loading.value || settingsDirty.value || !settings.enabled || !settings.fixedMode || !editor.action || !overview.value) return;
requests.cancel("overview"); connecting.value = false;
const request = requests.begin("action"), body = { operation: actionPayload(), configurationRevision: overview.value.configurationRevision };
acting.value = true; options.errorMessage.value = ""; noticeMessage.value = "";
acting.value = true; options.errorMessage.value = ""; noticeMessage.value = ""; refreshWarning.value = "";
try {
await options.api.tsAdminAction(body, request.signal);
if (!request.isCurrent()) return;
Object.assign(editor, emptyEditor()); noticeMessage.value = options.tr("tsAdminActionSaved"); overview.value = null;
// A failed refresh must never retry the write or report that it did not happen.
acting.value = false;
await connectAndRefresh();
await readOverview(true);
} catch (error) { if (request.isCurrent()) report(error); }
finally { if (request.isCurrent()) acting.value = false; request.finish(); }
}
return { settings, form, editor, overview, settingsDirty, noticeMessage, loading, saving, connecting, acting,
return { settings, form, editor, overview, settingsDirty, noticeMessage, refreshWarning, listErrorText, loading, saving, connecting, acting,
loadSettings, saveSettings, connectAndRefresh, beginAction, closeAction, runAction, cancelRequests, reset };
}
+20
View File
@@ -17,6 +17,10 @@ const zh = {
tsAdminRemoveKey: "移除 API Key",
tsAdminKeepKey: "保留 API Key",
tsAdminActionSaved: "TeamSpeak 操作已完成。",
tsAdminRefreshError: "操作已完成,但状态刷新失败。{{error}} 请手动刷新,勿重复执行操作。",
tsAdminReadError: "无法读取 TeamSpeak 状态,请检查管理连接后手动刷新。",
tsAdminTimeoutError: "TeamSpeak 请求超时,请检查连接并稍后重试。",
tsAdminChannelPassword: "频道密码",
tsAdminServerSettings: "服务器设置",
tsAdminWelcome: "欢迎消息",
tsAdminSlots: "最大在线人数",
@@ -78,6 +82,10 @@ const en = {
tsAdminRemoveKey: "Remove API key",
tsAdminKeepKey: "Keep API key",
tsAdminActionSaved: "TeamSpeak operation completed.",
tsAdminRefreshError: "The operation completed, but refreshing the state failed. {{error}} Refresh manually; do not repeat the operation.",
tsAdminReadError: "Could not read TeamSpeak state. Check the management connection and refresh manually.",
tsAdminTimeoutError: "The TeamSpeak request timed out. Check the connection and try again later.",
tsAdminChannelPassword: "Channel password",
tsAdminServerSettings: "Server settings",
tsAdminWelcome: "Welcome message",
tsAdminSlots: "Maximum clients",
@@ -139,6 +147,10 @@ const de = {
tsAdminRemoveKey: "API-Schlüssel entfernen",
tsAdminKeepKey: "API-Schlüssel behalten",
tsAdminActionSaved: "TeamSpeak-Aktion abgeschlossen.",
tsAdminRefreshError: "Die Aktion wurde ausgeführt, aber der Status konnte nicht aktualisiert werden. {{error}} Aktualisieren Sie manuell, ohne die Aktion zu wiederholen.",
tsAdminReadError: "Der TeamSpeak-Status konnte nicht gelesen werden. Prüfen Sie die Verwaltungsverbindung und aktualisieren Sie manuell.",
tsAdminTimeoutError: "Zeitüberschreitung bei der TeamSpeak-Anfrage. Prüfen Sie die Verbindung und versuchen Sie es später erneut.",
tsAdminChannelPassword: "Kanalpasswort",
tsAdminServerSettings: "Servereinstellungen",
tsAdminWelcome: "Willkommensnachricht",
tsAdminSlots: "Maximale Clientzahl",
@@ -200,6 +212,10 @@ const ru = {
tsAdminRemoveKey: "Удалить API-ключ",
tsAdminKeepKey: "Сохранить API-ключ",
tsAdminActionSaved: "Операция TeamSpeak выполнена.",
tsAdminRefreshError: "Операция выполнена, но обновить состояние не удалось. {{error}} Обновите вручную, не повторяя операцию.",
tsAdminReadError: "Не удалось получить состояние TeamSpeak. Проверьте подключение управления и обновите вручную.",
tsAdminTimeoutError: "Время ожидания запроса TeamSpeak истекло. Проверьте соединение и повторите позже.",
tsAdminChannelPassword: "Пароль канала",
tsAdminServerSettings: "Настройки сервера",
tsAdminWelcome: "Приветствие",
tsAdminSlots: "Максимум клиентов",
@@ -261,6 +277,10 @@ const ja = {
tsAdminRemoveKey: "API キーを削除",
tsAdminKeepKey: "API キーを維持",
tsAdminActionSaved: "TeamSpeak の操作が完了しました。",
tsAdminRefreshError: "操作は完了しましたが、状態の更新に失敗しました。{{error}} 操作を繰り返さず、手動で更新してください。",
tsAdminReadError: "TeamSpeak の状態を取得できませんでした。管理接続を確認し、手動で更新してください。",
tsAdminTimeoutError: "TeamSpeak のリクエストがタイムアウトしました。接続を確認し、後で再試行してください。",
tsAdminChannelPassword: "チャンネルパスワード",
tsAdminServerSettings: "サーバー設定",
tsAdminWelcome: "ウェルカムメッセージ",
tsAdminSlots: "最大接続数",
+29 -1
View File
@@ -539,8 +539,12 @@ test("TS mutations send the selected UID once and a failed refresh never retries
const pending = model.runAction(); await model.runAction();
response.resolve(json({ ok: true })); await pending;
assert.equal(writes, 1); assert.equal(model.acting, false); assert.equal(model.editor.action, "");
assert.ok(model.noticeMessage); assert.ok(state.errorMessage);
assert.ok(model.noticeMessage); assert.equal(state.errorMessage, "");
assert.ok(model.refreshWarning.includes("操作已完成")); assert.ok(model.refreshWarning.includes("勿重复执行"));
assert.equal(model.overview, null);
handler = path => Promise.resolve(json(defaults(path)));
await model.connectAndRefresh();
assert.equal(model.refreshWarning, ""); assert.ok(model.overview);
});
test("leaving TS management discards a late response and logout clears saved credential drafts", async () => {
@@ -569,6 +573,11 @@ test("TS administration actually renders transport forms, operations and all fiv
assert.ok(html.includes("WebQuery")); assert.ok(html.includes("https://query.example"));
assert.ok(html.includes("Selected user")); assert.ok(html.includes("Lobby"));
assert.ok(!html.includes("undefined"));
readable.beginAction("channel.create");
const creating = await renderToString(createSSRApp(Component, { model, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
assert.ok(creating.includes(state.i18n.tr("tsAdminChannelPassword")));
assert.ok(!creating.includes(`<span>${state.i18n.tr("tsAdminPassword")}</span><input type="password" autocomplete="new-password" maxlength="512"`));
readable.closeAction();
}
readable.form.transport = "ssh";
let html = await renderToString(createSSRApp(Component, { model, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
@@ -580,6 +589,25 @@ test("TS administration actually renders transport forms, operations and all fiv
assert.ok(html.includes('class="operation-card ts-admin-editor"')); assert.ok(html.includes("Selected user"));
});
test("TS list warnings distinguish rate limits, permissions, timeouts and other read failures in every language", async () => {
const { createSSRApp } = await import("vue");
const { renderToString } = await import("vue/server-renderer");
const { default: Component } = await vite.ssrLoadModule("/src/components/admin/AdminTsAdmin.vue");
await mount("/admin/ts-admin");
const model = reactive(state.adminTsAdmin);
await model.connectAndRefresh();
for (const code of ["TS_ADMIN_RATE_LIMITED", "TS_ADMIN_PERMISSION_DENIED", "TS_ADMIN_TIMEOUT", "TS_ADMIN_READ_FAILED"]) {
model.overview.groupsAvailable = false; model.overview.bansAvailable = false;
model.overview.groupsErrorCode = code; model.overview.bansErrorCode = code;
for (const language of ["zh", "en", "de", "ru", "ja"]) {
state.language = language;
const html = await renderToString(createSSRApp(Component, { model: state.adminTsAdmin, i18n: state.i18n, targetAddress: "voice.example", targetPort: "9987" }));
assert.equal(html.split(state.i18n.errorText(code)).length - 1, 2);
assert.ok(!html.includes(state.i18n.tr("tsAdminRestricted")));
}
}
});
test("WebSpeak routes work in open and fixed modes without any TS management request", async () => {
for (const accessMode of ["open", "fixed"]) {