feat: add GitHub skin store and organize instance administration

Adopt the pinned published TeamSpeak SDK and direct relay routing.
Add optional TeamSpeak Query administration with encrypted credentials
and separate WebSpeak access, site, operations and skin management.
Distribute Discord Voice through the GitHub skin index, preserve skin
state during updates, and correct KAAK scaling and screen fullscreen.

Validation: 831 tests; backend and frontend builds; five-language UI
checks from narrow screens through 4K and local Query fixture actions.
This commit is contained in:
illusia committed 2026-10-24 12:52:59 +08:00
1 parent 180bfeb52f
commit 0af3236c30
95 files changed
+7678 -709

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
export class AdminInputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "AdminInputError";
}
}
+95 -5
View File
@@ -1,12 +1,13 @@
import { Router, raw as expressRaw, type NextFunction, type Request, type Response } from "express";
import { existsSync, readFileSync } from "node:fs";
import type { Logger } from "../logger.js";
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput } from "./admin-service.js";
import { AdminInputError, AdminService, type AdminSettingsInput, type RelayNodeInput, type TsAdminSettingsInput } from "./admin-service.js";
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
import type { AdminSessionSummary } from "../server/voice-bridge.js";
import { SkinRegistry, SkinRegistryError } from "./skin-registry.js";
import { SkinStore } from "./skin-store.js";
export interface AdminConnectionRecord {
id: string;
@@ -36,6 +37,7 @@ export interface AdminRouterOptions {
version?: string;
logFile?: string;
skinRegistry?: SkinRegistry;
skinStore?: SkinStore;
startedAt: number;
}
@@ -43,6 +45,21 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
const router = Router();
const limiter = new AdminLoginRateLimiter();
const logger = options.logger.child({ component: "admin-api" });
const skinStore = options.skinStore ?? new SkinStore(options.version ?? "0.0.0");
// Include uploads, enable/default changes and deletion in the same queue as store installs.
let skinMutation: Promise<unknown> = Promise.resolve();
function mutateSkins<T>(run: () => Promise<T>): Promise<T> {
const next = skinMutation.then(run, run);
skinMutation = next.catch(() => undefined);
return next;
}
function sendStoreError(response: Response, error: unknown) {
if (error instanceof SkinRegistryError) {
const status = error.code === "SKIN_STORE_UNAVAILABLE" ? 502 : error.code === "SKIN_STORE_NOT_FOUND" ? 404
: ["SKIN_STORE_CHANGED", "SKIN_STORE_INSTALLED_CHANGED", "SKIN_STORE_NOT_NEWER", "SKIN_STORE_INCOMPATIBLE"].includes(error.code) ? 409 : 400;
response.status(status).json({ ok: false, code: error.code });
} else sendAdminError(response, error);
}
router.use((_request, response, next) => {
response.setHeader("Cache-Control", "no-store");
@@ -122,6 +139,32 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
response.json(options.service.getAdminSettings());
});
router.get("/ts-admin/settings", (_request, response) => {
response.json(options.service.getTsAdminSettings());
});
router.put("/ts-admin/settings", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
options.service.saveTsAdminSettings(readTsAdminSettingsInput(asRecord(request.body)));
response.json({ ok: true, settings: options.service.getTsAdminSettings() });
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/ts-admin/overview", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
try {
response.json(await options.service.getTsAdminOverview());
} catch (error: unknown) {
sendAdminError(response, error);
}
});
router.post("/ts-admin/action", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try { response.json(await options.service.runTsAdminAction(request.body)); }
catch (error: unknown) { sendAdminError(response, error); }
});
router.get("/skins", async (_request, response) => {
response.json({
skins: await options.skinRegistry?.list() ?? [],
@@ -129,11 +172,32 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
});
});
router.get("/skin-store", async (_request, response) => {
try { response.json(await skinStore.list()); }
catch (error) { sendStoreError(response, error); }
});
router.post("/skin-store/refresh", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
try { response.json(await skinStore.list(true)); }
catch (error) { sendStoreError(response, error); }
});
router.post("/skin-store/install", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
const registry = options.skinRegistry;
const skin = await mutateSkins(() => skinStore.install(registry, request.body));
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version, source: "github-store" });
response.status(201).json({ ok: true, skin });
} catch (error) { sendStoreError(response, error); }
});
router.put("/skins/default", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
try {
if (!options.skinRegistry) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
const id = typeof asRecord(request.body).id === "string" ? (asRecord(request.body).id as string).trim() : "";
const settings = await options.skinRegistry.setDefaultSkin(id);
const registry = options.skinRegistry;
const settings = await mutateSkins(() => registry.setDefaultSkin(id));
response.json({ ok: true, defaultSkinId: settings.defaultSkinId });
} catch (error: unknown) {
if (error instanceof SkinRegistryError) {
@@ -149,7 +213,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
const id = typeof request.params.id === "string" ? request.params.id : "";
const body = asRecord(request.body);
if (!options.skinRegistry || typeof body.enabled !== "boolean") throw new SkinRegistryError("A skin and boolean enabled value are required.", "SKIN_ENABLE_INVALID");
const skin = await options.skinRegistry.setEnabled(id, body.enabled);
const registry = options.skinRegistry, enabled = body.enabled;
const skin = await mutateSkins(() => registry.setEnabled(id, enabled));
options.service.database.addAudit(body.enabled ? "ADMIN_SKIN_ENABLED" : "ADMIN_SKIN_DISABLED", { id });
response.json({ ok: true, skin, defaultSkinId: await options.skinRegistry.getDefaultSkinId() });
} catch (error: unknown) {
@@ -166,7 +231,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
try {
const id = typeof request.params.id === "string" ? request.params.id : "";
if (!options.skinRegistry || !Buffer.isBuffer(request.body)) throw new SkinRegistryError("Skin storage is unavailable.", "SKIN_STORAGE_UNAVAILABLE");
const skin = await options.skinRegistry.save(request.body, id);
const registry = options.skinRegistry, bytes = request.body;
const skin = await mutateSkins(() => registry.save(bytes, id));
options.service.database.addAudit("ADMIN_SKIN_INSTALLED", { id: skin.id, version: skin.version });
response.status(201).json({ ok: true, skin });
} catch (error: unknown) {
@@ -182,7 +248,8 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
router.delete("/skins/:id", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
const id = typeof request.params.id === "string" ? request.params.id : "";
try {
if (!options.skinRegistry || !await options.skinRegistry.remove(id)) {
const registry = options.skinRegistry;
if (!registry || !await mutateSkins(() => registry.remove(id))) {
response.status(404).json({ ok: false, code: "SKIN_NOT_FOUND" });
return;
}
@@ -446,6 +513,7 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
id: typeof node.id === "string" ? node.id.slice(0, 110) : undefined,
name: typeof node.name === "string" ? node.name.slice(0, 80) : "",
target: typeof node.target === "string" ? node.target.slice(0, 300) : "",
voiceEndpoint: typeof node.voiceEndpoint === "string" ? node.voiceEndpoint.slice(0, 300) : undefined,
enabled: node.enabled === true,
token: typeof node.token === "string" ? node.token.slice(0, 512) : undefined,
tokenAction: readPasswordAction(node.tokenAction),
@@ -479,6 +547,28 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
};
}
function readTsAdminSettingsInput(body: Record<string, unknown>): TsAdminSettingsInput {
if (typeof body.enabled !== "boolean") throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Expected enabled flag");
if (body.transport !== undefined && !["web", "ssh", "tcp"].includes(String(body.transport))) throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Invalid transport");
for (const key of ["apiKeyAction", "passwordAction"]) {
if (body[key] !== undefined && !["keep", "replace", "remove"].includes(String(body[key]))) throw new AdminInputError("INVALID_TS_ADMIN_SETTINGS", "Invalid credential action");
}
return {
enabled: body.enabled === true,
transport: body.transport as TsAdminSettingsInput["transport"],
queryHost: body.queryHost === undefined ? undefined : readString(body, "queryHost", 253),
webQueryUrl: body.webQueryUrl === undefined ? undefined : readString(body, "webQueryUrl", 2048),
apiKey: body.apiKey === undefined ? undefined : readString(body, "apiKey", 4096),
apiKeyAction: readPasswordAction(body.apiKeyAction),
serverId: body.serverId === undefined ? undefined : readOptionalNumber(body, "serverId", 0),
queryPort: readOptionalNumber(body, "queryPort", 10022),
username: readOptionalString(body, "username", 128),
password: readOptionalString(body, "password", 1024),
passwordAction: readPasswordAction(body.passwordAction),
hostKeyFingerprint: readOptionalString(body, "hostKeyFingerprint", 128),
};
}
function readRelaySettingsAction(value: unknown): "keep" | "replace" | "remove" {
return value === "replace" || value === "remove" ? value : "keep";
}
+49 -12
View File
@@ -1,8 +1,9 @@
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput, TsAdminSettingsInput } from "../shared/admin-inputs.js";
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
import { createHash, randomBytes } from "node:crypto";
import { existsSync } from "node:fs";
import { isIP } from "node:net";
import type { Logger } from "../logger.js";
import { loadConfig } from "../config.js";
import { DEFAULT_TEAM_SPEAK_PORT, formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
@@ -18,6 +19,9 @@ import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
import { TsAdminService, type TsAdminQueryClientFactory } from "./ts-admin-service.js";
import { AdminInputError } from "./admin-errors.js";
export { AdminInputError } from "./admin-errors.js";
export interface ConnectionPolicy {
defaultTarget: string;
@@ -40,6 +44,7 @@ export interface ManagedInviteView {
type ProbeFunction = typeof probeTeamSpeak;
export class AdminService {
private readonly tsAdmin: TsAdminService;
constructor(
readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
@@ -47,7 +52,13 @@ export class AdminService {
private readonly legacyConfigPath: string,
private readonly probe: ProbeFunction = probeTeamSpeak,
private readonly version = "0.1.0",
) {}
tsAdminClientFactory?: TsAdminQueryClientFactory,
) {
this.tsAdmin = new TsAdminService(database, masterSecret, logger, () => {
const settings = database.getSettings();
return { mode: settings.accessMode, target: settings.tsTarget || formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }) };
}, tsAdminClientFactory);
}
async initialize(): Promise<void> {
this.importLegacyConfigOnce();
@@ -154,7 +165,7 @@ export class AdminService {
if (!node.enabled || !node.host || !node.tokenEncrypted) continue;
try {
const token = decryptSecret(node.tokenEncrypted, this.masterSecret);
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token });
relays.push({ id: node.id, name: node.name, relayHost: node.host, relayPort: node.port, token, voiceEndpoint: node.voiceEndpoint || defaultRelayVoiceEndpoint(node.host) });
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error), relayId: node.id }, "Stored acceleration relay token could not be decrypted");
}
@@ -172,6 +183,10 @@ export class AdminService {
const settings = this.normalizeSettings(input, current, relayNodes);
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort || current.tsTarget !== settings.tsTarget;
this.database.updateSettings(settings);
if (settings.accessMode === "open") {
const tsAdmin = this.database.getTsAdminSettings();
if (tsAdmin.enabled) this.database.updateTsAdminSettings({ ...tsAdmin, enabled: false });
}
if (relayNodes !== undefined) {
this.database.replaceRelayNodes(relayNodes);
} else if (input.relaySettingsAction && input.relaySettingsAction !== "keep") {
@@ -311,6 +326,11 @@ export class AdminService {
return revoked;
}
getTsAdminSettings() { return this.tsAdmin.settings(); }
saveTsAdminSettings(input: TsAdminSettingsInput): void { this.tsAdmin.save(input); }
getTsAdminOverview() { return this.tsAdmin.overview(); }
runTsAdminAction(input: unknown) { return this.tsAdmin.action(input); }
getManagedInvite(token: string): { target: string; channel: string } | null {
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
const record = this.database.getManagedInvite(hashInviteToken(token));
@@ -482,6 +502,8 @@ export class AdminService {
if (seen.has(id)) throw new AdminInputError("INVALID_RELAY_ID", "Relay id must be unique");
seen.add(id);
const previous = current.get(id);
const voiceEndpointInput = typeof input.voiceEndpoint === "string" ? input.voiceEndpoint.trim() : previous?.voiceEndpoint ?? "";
const voiceEndpoint = normalizeRelayVoiceEndpoint(voiceEndpointInput, target.host);
const tokenAction = input.tokenAction ?? (input.token === undefined ? "keep" : "replace");
let tokenEncrypted = previous?.tokenEncrypted ?? null;
if (tokenAction === "remove") tokenEncrypted = null;
@@ -498,6 +520,7 @@ export class AdminService {
enabled: input.enabled === true,
host: target.host,
port: target.port,
voiceEndpoint,
tokenEncrypted,
createdAt: previous?.createdAt ?? now,
updatedAt: now,
@@ -513,12 +536,13 @@ export class AdminService {
}
}
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; hasToken: boolean }> {
private getRelayNodeViews(): Array<{ id: string; name: string; enabled: boolean; target: string; voiceEndpoint: string; hasToken: boolean }> {
return this.database.listRelayNodes().map((node) => ({
id: node.id,
name: node.name,
enabled: node.enabled,
target: formatRelayTarget(node.host, node.port),
voiceEndpoint: node.voiceEndpoint || defaultRelayVoiceEndpoint(node.host),
hasToken: Boolean(node.tokenEncrypted),
}));
}
@@ -533,6 +557,7 @@ export class AdminService {
enabled: settings.relayEnabled,
host: settings.relayHost,
port: settings.relayPort || DEFAULT_ACCELERATION_RELAY_PORT,
voiceEndpoint: defaultRelayVoiceEndpoint(settings.relayHost),
tokenEncrypted: settings.relayTokenEncrypted,
createdAt: previous?.createdAt ?? now,
updatedAt: now,
@@ -630,13 +655,25 @@ function settingsTarget(settings: { tsHost: string; tsPort: number; tsTarget?: s
return settings.tsTarget ?? formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort });
}
function defaultRelayVoiceEndpoint(host: string): string {
const formattedHost = isIP(host) === 6 ? `[${host}]` : host;
return `https://${formattedHost}`;
}
function normalizeRelayVoiceEndpoint(value: string, relayHost: string): string {
const endpoint = value || defaultRelayVoiceEndpoint(relayHost);
let parsed: URL;
try { parsed = new URL(endpoint); }
catch { throw new AdminInputError("INVALID_RELAY_VOICE_ENDPOINT", "Relay voice gateway address must be an HTTP(S) origin"); }
const hostname = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
const local = hostname === "localhost" || hostname === "::1" || hostname === "127.0.0.1" || hostname.startsWith("127.");
if ((parsed.protocol !== "https:" && !(parsed.protocol === "http:" && local))
|| parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
throw new AdminInputError("INVALID_RELAY_VOICE_ENDPOINT", "Relay voice gateway must use HTTPS and contain only an origin");
}
return parsed.origin;
}
function formatRelayTarget(host: string, port: number): string {
return `${host.includes(":") ? `[${host}]` : host}#${port}`;
}
export class AdminInputError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "AdminInputError";
}
}
+1 -1
View File
@@ -214,7 +214,7 @@ async function writeAtomicJson(filename: string, value: unknown): Promise<void>
}
}
function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
export function validateSkinArchive(bytes: Buffer, expectedId?: string): { manifest: ParsedSkinManifest; previewBytes?: Buffer; previewMime?: string } {
const entries = inspectArchive(bytes);
const regularEntries = entries.filter((entry) => !entry.isDirectory);
const rootPrefix = singleRootPrefix(regularEntries.map((entry) => entry.path));
+142
View File
@@ -0,0 +1,142 @@
import { createHash } from "node:crypto";
import { SkinRegistry, SkinRegistryError, validateSkinArchive, isBuiltinSkinId } from "./skin-registry.js";
import {
SKIN_STORE_INDEX_URL, SKIN_STORE_REPOSITORY, compareSkinVersions, isSkinStoreVersion,
type SkinStoreCatalog, type SkinStoreEntry, type SkinStoreMetadata, type SkinStoreInstallInput,
} from "../shared/skin-store.js";
const MAX_PACK_BYTES = 20 * 1024 * 1024;
const MAX_INDEX_BYTES = 128 * 1024;
const MAX_METADATA_BYTES = 16 * 1024;
const CACHE_MS = 5 * 60 * 1000;
const ID = /^[a-z0-9][a-z0-9.-]{0,79}$/;
const SHA = /^[a-f0-9]{64}$/;
const fail = (code: string): never => { throw new SkinRegistryError(code, code); };
const record = (value: unknown): Record<string, unknown> => {
if (!value || typeof value !== "object" || Array.isArray(value)) return fail("SKIN_STORE_INVALID");
return value as Record<string, unknown>;
};
export function skinRepository(value: unknown): string {
if (typeof value !== "string" || !/^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/.test(value)
|| value.endsWith("/.") || value.endsWith("/..") || value.endsWith(".git")) return fail("SKIN_STORE_INVALID");
return value;
}
function parseIndex(value: unknown): { id: string; repository: string }[] {
const root = record(value);
if (root.schemaVersion !== 1 || !Array.isArray(root.skins) || root.skins.length > 50) return fail("SKIN_STORE_INVALID");
const seen = new Set<string>();
return root.skins.map(item => {
const entry = record(item);
if (typeof entry.id !== "string" || !ID.test(entry.id) || isBuiltinSkinId(entry.id) || entry.id.startsWith("builtin.") || seen.has(entry.id)) return fail("SKIN_STORE_INVALID");
seen.add(entry.id);
return { id: entry.id, repository: skinRepository(entry.repository) };
});
}
function parseMetadata(value: unknown, id: string): SkinStoreMetadata {
const root = record(value), pack = record(root.package);
const field = (key: string, max: number, empty = false): string => {
const value = root[key];
if (typeof value !== "string" || value.length > max || (!empty && !value.trim()) || /[\u0000-\u001f\u007f]/.test(value)) return fail("SKIN_STORE_INVALID");
return value;
};
if (root.schemaVersion !== 1 || root.id !== id || !isSkinStoreVersion(root.version) || !isSkinStoreVersion(root.minAppVersion)
|| typeof pack.ref !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(pack.ref)
|| typeof pack.path !== "string" || !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+\.wskin$/.test(pack.path) || pack.path.length > 200
|| typeof pack.sha256 !== "string" || !SHA.test(pack.sha256)) return fail("SKIN_STORE_INVALID");
return { schemaVersion: 1, id, name: field("name", 80), author: field("author", 80), license: field("license", 80),
description: field("description", 400, true), version: root.version, minAppVersion: root.minAppVersion,
package: { ref: pack.ref, path: pack.path, sha256: pack.sha256 } };
}
export class SkinStore {
private cached: SkinStoreCatalog | null = null;
private loading: Promise<SkinStoreCatalog> | null = null;
constructor(private readonly appVersion: string, private readonly fetcher: typeof fetch = fetch) {}
/** No arbitrary URLs, redirects, credentials, or unbounded downloads enter the server. */
private async download(url: string, limit: number): Promise<Buffer> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 20_000);
try {
const parsed = new URL(url);
if (parsed.origin !== "https://raw.githubusercontent.com" || parsed.username || parsed.password) return fail("SKIN_STORE_INVALID");
const response = await this.fetcher(url, { redirect: "error", signal: controller.signal, headers: { accept: "application/octet-stream" }, credentials: "omit" });
if (!response.ok || !response.body) return fail("SKIN_STORE_UNAVAILABLE");
const declared = response.headers.get("content-length");
if (declared && Number(declared) > limit) { await response.body.cancel(); return fail("SKIN_STORE_TOO_LARGE"); }
const reader = response.body.getReader(), chunks: Uint8Array[] = [];
let size = 0;
try {
while (true) {
const part = await reader.read();
if (part.done) break;
size += part.value.byteLength;
if (size > limit) { await reader.cancel(); return fail("SKIN_STORE_TOO_LARGE"); }
chunks.push(part.value);
}
} finally { reader.releaseLock(); }
return Buffer.concat(chunks, size);
} catch (error) {
if (error instanceof SkinRegistryError) throw error;
return fail("SKIN_STORE_UNAVAILABLE");
} finally { clearTimeout(timeout); }
}
private async json(url: string, limit: number): Promise<unknown> {
const bytes = await this.download(url, limit);
try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
catch { return fail("SKIN_STORE_INVALID"); }
}
private async entry(source: { id: string; repository: string }): Promise<SkinStoreEntry> {
const metadata = parseMetadata(await this.json(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/HEAD/skin.json`, MAX_METADATA_BYTES), source.id);
return { ...source, metadata, revision: createHash("sha256").update(JSON.stringify({ ...source, metadata })).digest("hex"),
compatible: isSkinStoreVersion(this.appVersion) && compareSkinVersions(this.appVersion, metadata.minAppVersion) >= 0, error: null };
}
async list(refresh = false): Promise<SkinStoreCatalog> {
if (this.loading) return this.loading;
if (!refresh && this.cached && Date.now() - this.cached.fetchedAt < CACHE_MS) return this.cached;
const pending = this.readCatalog();
this.loading = pending;
try { this.cached = await pending; return this.cached; }
finally { this.loading = null; }
}
private async readCatalog(): Promise<SkinStoreCatalog> {
const sources = parseIndex(await this.json(SKIN_STORE_INDEX_URL, MAX_INDEX_BYTES));
const entries: SkinStoreEntry[] = new Array(sources.length);
let cursor = 0;
await Promise.all(Array.from({ length: Math.min(4, sources.length) }, async () => {
while (cursor < sources.length) {
const index = cursor++;
try { entries[index] = await this.entry(sources[index]); }
catch (error) { entries[index] = { ...sources[index], metadata: null, revision: "", compatible: false,
error: error instanceof SkinRegistryError ? error.code : "SKIN_STORE_UNAVAILABLE" }; }
}
}));
return { repository: SKIN_STORE_REPOSITORY, appVersion: this.appVersion, fetchedAt: Date.now(), entries };
}
/** Caller serializes this with all other registry mutations. */
async install(registry: SkinRegistry, value: unknown) {
const input = record(value) as unknown as SkinStoreInstallInput;
if (typeof input.id !== "string" || !ID.test(input.id) || typeof input.revision !== "string" || !SHA.test(input.revision)
|| !(input.installedVersion === null || isSkinStoreVersion(input.installedVersion))) return fail("SKIN_STORE_INVALID");
const sources = parseIndex(await this.json(SKIN_STORE_INDEX_URL, MAX_INDEX_BYTES));
const source = sources.find(entry => entry.id === input.id);
if (!source) return fail("SKIN_STORE_NOT_FOUND");
const entry = await this.entry(source);
if (entry.revision !== input.revision) return fail("SKIN_STORE_CHANGED");
if (!entry.compatible) return fail("SKIN_STORE_INCOMPATIBLE");
const installed = (await registry.list()).find(item => item.id === input.id);
if ((installed?.version ?? null) !== input.installedVersion) return fail("SKIN_STORE_INSTALLED_CHANGED");
const metadata = entry.metadata!;
if (installed && compareSkinVersions(metadata.version, installed.version) <= 0) return fail("SKIN_STORE_NOT_NEWER");
const bytes = await this.download(`${source.repository.replace("https://github.com/", "https://raw.githubusercontent.com/")}/${metadata.package.ref}/${metadata.package.path}`, MAX_PACK_BYTES);
if (createHash("sha256").update(bytes).digest("hex") !== metadata.package.sha256) return fail("SKIN_STORE_CHECKSUM");
const { manifest } = validateSkinArchive(bytes, input.id);
for (const key of ["id", "name", "version", "author", "license", "minAppVersion"] as const) {
if (manifest[key] !== metadata[key]) return fail("SKIN_STORE_PACKAGE_MISMATCH");
}
return registry.save(bytes, input.id);
}
}
+250
View File
@@ -0,0 +1,250 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { createServer } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { QueryClient, type QueryClientOptions } from "@honeybbq/teamspeak/query";
import { WebSpeakDatabase } from "../persistence/database.js";
import { decryptSecret } from "../security/secret-crypto.js";
import type { TsAdminAction } from "../shared/admin-inputs.js";
import type { Logger } from "../logger.js";
import { TsAdminService } from "./ts-admin-service.js";
import { webQueryFetch } from "./webquery-fetch.js";
const uid = "a-real-voice-identity=";
const channel = { cid: "1", cpid: "0", channel_name: "Lobby", total_clients: "1", channel_flag_password: "0" };
const member = { clid: "42", client_database_id: "77", client_unique_identifier: uid, client_nickname: "Guest", cid: "1", client_type: "0", client_servergroups: "6,7" };
type Reply = { body: Record<string, string>[]; status: { code: number; message: string } };
const ok = (body: Reply["body"] = []): Reply => ({ body, status: { code: 0, message: "ok" } });
const denied = (): Reply => ({ body: [], status: { code: 2568, message: "insufficient permissions: secret-value-must-not-escape" } });
function deferred() { let resolve!: () => void; const promise = new Promise<void>(done => { resolve = done; }); return { resolve, promise }; }
const hasCode = (code: string) => (error: any) => error.code === code && error.message === code;
/** Real published QueryClient + WebQuery transport, with a disposable HTTP server. */
async function fixture(t: TestContext, family: "ts3" | "ts6" = "ts6") {
const directory = mkdtempSync(join(tmpdir(), "webspeak-ts-admin-"));
const database = new WebSpeakDatabase(join(directory, "test.sqlite"));
const master = Buffer.alloc(32, 5), logs: unknown[] = [];
const logger: Logger = { debug() {}, info() {}, error() {}, warn(...args: unknown[]) { logs.push(args); }, child() { return this; } };
const policy = { mode: "fixed" as "fixed" | "open", target: "127.0.0.1:9987" };
const calls: Array<{ path: string; command: string; params: Record<string, string>; key: string }> = [];
const clients: QueryClient[] = [];
const clientOptions: QueryClientOptions[] = [];
let httpStatus = 200;
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" }]);
case "whoami": return ok([{ client_id: "99" }]);
case "serverinfo": return ok([{ virtualserver_name: "Test TeamSpeak", virtualserver_welcomemessage: "Welcome", virtualserver_maxclients: "32", virtualserver_uptime: "123" }]);
case "channellist": return ok([channel]);
case "clientlist": return ok([member]);
case "servergrouplist": return ok([{ sgid: "6", name: "Member", type: "1" }, { sgid: "1", name: "Query template", type: "0" }]);
case "banlist": return ok([{ banid: "8", uid, lastnickname: "Guest", reason: "Test", duration: "3600", created: "1700000000" }]);
case "channelcreate": return ok([{ cid: "2" }]);
case "banadd": return ok([{ banid: "9" }]);
default: return ok();
}
};
const server = createServer(async (req, res) => {
let body = "";
for await (const chunk of req) body += String(chunk);
const path = req.url!, command = path.split("/").at(-1)!;
const params = JSON.parse(body || "{}");
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");
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address(); assert.ok(address && typeof address !== "string");
const service = new TsAdminService(database, master, logger, () => policy, options => {
clientOptions.push(options);
const client = new QueryClient(options); clients.push(client); return client;
});
const settings = { enabled: true, transport: "web" as const, queryPort: 10022, queryHost: "", username: "", hostKeyFingerprint: "",
webQueryUrl: `http://127.0.0.1:${address.port}/query`, serverId: 7, apiKey: "secret-local-fixture-api-key", apiKeyAction: "replace" as const };
service.save(settings);
t.after(async () => {
await Promise.all(clients.map(client => client.disconnect()));
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
database.close(); rmSync(directory, { recursive: true, force: true });
});
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; },
get reply() { return reply; }, set reply(value) { reply = value; } };
}
for (const family of ["ts3", "ts6"] as const) test(`WebQuery ${family} selects the virtual server, parses typed data and sends no login or notifications`, async t => {
const f = await fixture(t, family);
const result = await f.service.overview();
assert.equal(result.serverFamily, family); assert.equal(result.serverName, "Test TeamSpeak");
assert.equal(result.welcomeMessage, "Welcome"); assert.equal(result.maxClients, 32);
assert.equal(result.channels[0].id, "1"); assert.equal(result.clients[0].uid, uid);
assert.deepEqual(result.groups, [{ id: "6", name: "Member" }]);
assert.equal(result.bans[0].durationSeconds, 3600);
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/") && call.key === f.settings.apiKey));
assert.ok(!f.calls.some(call => /login|notify|clientupdate/.test(call.command)));
assert.equal(f.clientOptions[0].events, undefined, "WebQuery rejects even an explicit events:false option");
assert.equal(f.clientOptions[0].reconnect, undefined);
f.service.save({ ...f.settings, serverId: 0, apiKeyAction: "keep", apiKey: undefined });
f.calls.length = 0;
await f.service.overview();
assert.ok(f.calls.every(call => call.path.startsWith("/query/byport/9987/")));
});
test("Query credentials are encrypted separately, projected out, and keep/remove is explicit", async t => {
const f = await fixture(t);
f.service.save({ ...f.settings, passwordAction: "replace", password: "local-query-password" });
const stored = f.database.getTsAdminSettings();
assert.notEqual(stored.apiKeyEncrypted, f.settings.apiKey);
assert.equal(decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-webquery-api-key:v1"), f.settings.apiKey);
assert.equal(decryptSecret(stored.passwordEncrypted, f.master, "webspeak:ts-admin-query-password:v1"), "local-query-password");
assert.throws(() => decryptSecret(stored.apiKeyEncrypted, f.master, "webspeak:ts-admin-query-password:v1"));
const shown = f.service.settings();
assert.equal(shown.hasApiKey, true); assert.equal(shown.hasPassword, true);
assert.ok(!("apiKeyEncrypted" in shown) && !("passwordEncrypted" in shown));
f.service.save({ ...f.settings, apiKey: "ignored", apiKeyAction: "keep" });
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted);
assert.throws(() => f.service.save({ ...f.settings, apiKeyAction: "remove" }), hasCode("INVALID_TS_ADMIN_API_KEY"));
assert.equal(f.database.getTsAdminSettings().apiKeyEncrypted, stored.apiKeyEncrypted, "invalid settings must be atomic");
f.service.save({ ...f.settings, enabled: false, apiKeyAction: "remove", passwordAction: "remove" });
assert.equal(f.service.settings().hasApiKey, false);
assert.equal(f.service.settings().hasPassword, false);
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_NOT_CONFIGURED"));
assert.equal(f.calls.length, 0);
});
test("invalid endpoints and selectors are rejected without changing stored settings", async t => {
const f = await fixture(t), stored = f.database.getTsAdminSettings();
for (const webQueryUrl of ["file:///etc/passwd", "https://user:password@example.com", "https://example.com?api_key=secret", "https://example.com/#fragment", "no-url"]) {
assert.throws(() => f.service.save({ ...f.settings, webQueryUrl }), hasCode("INVALID_TS_ADMIN_URL"));
}
for (const serverId of [-1, 1.2, 4_294_967_296]) assert.throws(() => f.service.save({ ...f.settings, serverId }), hasCode("INVALID_TS_ADMIN_SERVER_ID"));
assert.throws(() => f.service.save({ ...f.settings, queryHost: "host:10022" }), hasCode("INVALID_TS_ADMIN_HOST"));
assert.deepEqual(f.database.getTsAdminSettings(), stored);
f.policy.mode = "open";
assert.throws(() => f.service.save(f.settings), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_FIXED_MODE_REQUIRED"));
});
test("limited list permissions preserve the rest of the overview and error details stay private", async t => {
const f = await fixture(t), original = f.reply;
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.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"));
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
assert.ok(!JSON.stringify(f.logs).includes(f.settings.apiKey));
});
test("administrator actions use typed SDK commands, escaping and UID-only bans", async t => {
const f = await fixture(t);
const actions: TsAdminAction[] = [
{ action: "server.update", name: "A | name", welcomeMessage: "Hello\nworld", maxClients: 48 },
{ action: "channel.create", name: "Channel | special", parentId: "1", description: "Line1\nLine2", permanent: true, password: "test password" },
{ action: "channel.update", channelId: "2", name: "New name" },
{ action: "channel.delete", channelId: "2" },
{ action: "client.move", clientId: 42, clientUid: uid, channelId: "1" },
{ action: "client.kick", clientId: 42, clientUid: uid, reason: "Test reason" },
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: false },
{ action: "client.group", clientId: 42, clientUid: uid, groupId: "6", remove: true },
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "UID ban", durationSeconds: 3600 },
{ action: "ban.delete", banId: "9" },
];
for (const action of actions) assert.deepEqual(await f.action(action), { ok: true });
const command = (name: string) => f.calls.find(call => call.command === name)!.params;
assert.deepEqual(command("serveredit"), { virtualserver_name: "A | name", virtualserver_welcomemessage: "Hello\nworld", virtualserver_maxclients: "48" });
assert.equal(command("channelcreate").channel_description, "Line1\nLine2");
assert.equal(command("channelcreate").channel_password, "test password");
assert.deepEqual(command("channeledit"), { cid: "2", channel_name: "New name" }, "rename must preserve unread channel metadata");
assert.equal(command("channeldelete").force, "0");
assert.deepEqual(command("clientmove"), { clid: "42", cid: "1" });
assert.equal(command("clientkick").reasonid, "5");
assert.deepEqual(command("servergroupaddclient"), { sgid: "6", cldbid: "77" });
assert.deepEqual(command("servergroupdelclient"), { sgid: "6", cldbid: "77" });
assert.deepEqual(command("banadd"), { uid, time: "3600", banreason: "UID ban" });
assert.equal(command("bandel").banid, "9");
});
test("stale client identities never receive a mutation, and failed writes are not retried", async t => {
const f = await fixture(t), original = f.reply;
f.reply = (command, params) => command === "clientlist" ? ok([{ ...member, client_unique_identifier: "replacement-identity=" }]) : original(command, params);
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_CLIENT_CHANGED"));
assert.ok(!f.calls.some(call => call.command === "clientkick"));
f.reply = (command, params) => command === "clientkick" ? denied() : original(command, params);
await assert.rejects(f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" }), hasCode("TS_ADMIN_PERMISSION_DENIED"));
assert.equal(f.calls.filter(call => call.command === "clientkick").length, 1);
await assert.rejects(f.action({ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: 0 }), hasCode("TS_ADMIN_PARTIAL_SUCCESS"));
assert.equal(f.calls.filter(call => call.command === "banadd").length, 1);
assert.equal(f.calls.find(call => call.command === "banadd")!.params.time, undefined, "permanent UID ban has no expiry");
});
test("configuration changes cancel in-flight and queued writes instead of targeting another server", async t => {
const f = await fixture(t), original = f.reply, entered = deferred(), release = deferred();
f.reply = async (command, params) => {
if (command === "clientlist") { entered.resolve(); await release.promise; }
return original(command, params);
};
const first = f.action({ action: "client.kick", clientId: 42, clientUid: uid, reason: "" });
const queued = f.action({ action: "channel.delete", channelId: "1" });
const firstCheck = assert.rejects(first, hasCode("TS_ADMIN_CONFIG_CHANGED"));
const queuedCheck = assert.rejects(queued, hasCode("TS_ADMIN_CONFIG_CHANGED"));
await entered.promise;
f.service.save({ ...f.settings, serverId: 8 });
release.resolve();
await Promise.all([firstCheck, queuedCheck]);
assert.ok(!f.calls.some(call => ["clientkick", "channeldelete"].includes(call.command)));
assert.ok(f.calls.every(call => call.path.startsWith("/query/7/")));
f.reply = original;
assert.deepEqual(await f.action({ action: "channel.delete", channelId: "2" }), { ok: true }, "failed queue entries must not block later work");
});
test("an old browser snapshot cannot mutate a newly configured management server", async t => {
const f = await fixture(t);
const snapshot = await f.service.overview();
const operation: TsAdminAction = { action: "channel.delete", channelId: "1" };
f.service.save({ ...f.settings, serverId: 8 });
f.calls.length = 0;
assert.throws(() => f.service.action({ operation, configurationRevision: snapshot.configurationRevision }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
assert.throws(() => f.service.action({ operation }), hasCode("TS_ADMIN_CONFIG_CHANGED"));
assert.equal(f.calls.length, 0, "stale UI must fail before connecting to the new server");
});
test("administrator command whitelist rejects arbitrary commands and invalid object identifiers", async t => {
const f = await fixture(t);
for (const action of [null, [], { action: "serverstop" }, { action: "channel.delete", channelId: "0" },
{ action: "channel.delete", channelId: "1|serverstop" }, { action: "channel.delete", channelId: "18446744073709551616" },
{ action: "client.kick", clientId: 42, clientUid: "", reason: "" },
{ action: "client.ban", clientId: 42, clientUid: uid, reason: "", durationSeconds: -1 },
{ action: "server.update", name: "", welcomeMessage: "", maxClients: 32 },
]) assert.throws(() => f.action(action), hasCode("INVALID_TS_ADMIN_ACTION"));
assert.equal(f.calls.length, 0);
});
test("WebQuery HTTP and TS API-key authentication failures have a useful safe error", async t => {
const f = await fixture(t);
for (const status of [401, 403]) {
f.httpStatus = status;
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
}
f.httpStatus = 200;
f.reply = () => ({ body: [], status: { code: 5122, message: "invalid API key: secret-value-must-not-escape" } });
await assert.rejects(f.service.overview(), hasCode("TS_ADMIN_AUTH_FAILED"));
assert.ok(!JSON.stringify(f.logs).includes("secret-value-must-not-escape"));
});
test("disposing an administrator request cancels its underlying WebQuery HTTP request", async t => {
const f = await fixture(t), entered = deferred(), release = deferred(), controller = new AbortController();
f.reply = async () => { entered.resolve(); await release.promise; return ok(); };
const pending = webQueryFetch(controller.signal)(`${f.settings.webQueryUrl}/7/version`, { method: "POST", body: "{}" });
const check = assert.rejects(pending, (error: any) => error.name === "AbortError");
await entered.promise;
controller.abort(); await check;
release.resolve();
});
+279
View File
@@ -0,0 +1,279 @@
import { isIP } from "node:net";
import { createHash } from "node:crypto";
import {
addBan, addClientToServerGroup, asBanID, asChannelID, asClientID, asServerGroupID,
createChannel, deleteBan, deleteChannel, editChannel, editServer, getServerInfo, kickClient,
listBans, listChannels, listClients, listServerGroups, moveClient, Reason,
removeClientFromServerGroup, ServerError, type CommandOptions,
} from "@honeybbq/teamspeak";
import { QueryClient, WebQueryHttpError, type QueryClientOptions } from "@honeybbq/teamspeak/query";
import type { Logger } from "../logger.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { encryptSecret, decryptSecret } from "../security/secret-crypto.js";
import type { TsAdminAction, TsAdminSettingsInput } from "../shared/admin-inputs.js";
import { resolveTeamSpeakTarget } from "../server/teamspeak-alias.js";
import { AdminInputError } from "./admin-errors.js";
import { webQueryFetch } from "./webquery-fetch.js";
const PASSWORD_PURPOSE = "webspeak:ts-admin-query-password:v1";
const API_KEY_PURPOSE = "webspeak:ts-admin-webquery-api-key:v1";
export type TsAdminQueryClientFactory = (options: QueryClientOptions) => QueryClient;
type Policy = { mode: "fixed" | "open"; target: string };
/** Optional administrator access. Guest voice and WebSpeak management never use these credentials. */
export class TsAdminService {
private actions: Promise<unknown> = Promise.resolve();
constructor(
private readonly database: WebSpeakDatabase,
private readonly masterSecret: Buffer,
private readonly logger: Logger,
private readonly policy: () => Policy,
private readonly createClient: TsAdminQueryClientFactory = options => new QueryClient(options),
) {}
settings() {
const { passwordEncrypted, apiKeyEncrypted, ...settings } = this.database.getTsAdminSettings();
return { ...settings, configurationRevision: this.configuration(), fixedMode: this.policy().mode === "fixed", hasPassword: Boolean(passwordEncrypted), hasApiKey: Boolean(apiKeyEncrypted) };
}
save(input: TsAdminSettingsInput): void {
this.assertFixed();
const current = this.database.getTsAdminSettings();
const transport = input.transport ?? current.transport;
if (!["web", "ssh", "tcp"].includes(transport) || typeof input.enabled !== "boolean") fail("INVALID_TS_ADMIN_SETTINGS");
const queryPort = input.queryPort;
if (!Number.isInteger(queryPort) || queryPort < 1 || queryPort > 65535) fail("INVALID_TS_ADMIN_QUERY_PORT");
const username = text(input.username, 128).trim();
const hostKeyFingerprint = text(input.hostKeyFingerprint, 128).trim();
const queryHost = text(input.queryHost ?? current.queryHost, 253).trim();
if (queryHost && !isIP(queryHost) && !/^(?=.{1,253}$)[a-z\d](?:[a-z\d.-]*[a-z\d])?$/i.test(queryHost)) fail("INVALID_TS_ADMIN_HOST");
let webQueryUrl = text(input.webQueryUrl ?? current.webQueryUrl, 2048).trim();
if (webQueryUrl) {
try {
const url = new URL(webQueryUrl);
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash) throw new Error();
webQueryUrl = url.toString().replace(/\/+$/, "");
} catch { fail("INVALID_TS_ADMIN_URL"); }
}
const serverId = input.serverId ?? current.serverId;
if (!Number.isSafeInteger(serverId) || serverId < 0 || serverId > 4_294_967_295) fail("INVALID_TS_ADMIN_SERVER_ID");
const passwordEncrypted = this.secret(input.password, input.passwordAction, current.passwordEncrypted, PASSWORD_PURPOSE, 1024);
const apiKeyEncrypted = this.secret(input.apiKey, input.apiKeyAction, current.apiKeyEncrypted, API_KEY_PURPOSE, 4096);
if (input.enabled) {
if (transport === "web") {
if (!webQueryUrl) fail("INVALID_TS_ADMIN_URL");
if (!apiKeyEncrypted) fail("INVALID_TS_ADMIN_API_KEY");
} else {
if (!username) fail("INVALID_TS_ADMIN_USERNAME");
if (!passwordEncrypted) fail("INVALID_TS_ADMIN_PASSWORD");
if (transport === "ssh" && !/^SHA256:[A-Za-z0-9+/]{43}$/.test(hostKeyFingerprint)) fail("INVALID_TS_ADMIN_HOST_KEY");
}
}
this.database.updateTsAdminSettings({ enabled: input.enabled, transport, queryHost, queryPort, username,
passwordEncrypted, apiKeyEncrypted, webQueryUrl, serverId, hostKeyFingerprint });
}
async overview() {
return this.withClient(async (client, options, assertCurrent) => {
const [server, channels, clients] = await Promise.all([
getServerInfo(client, options), listChannels(client, options),
listClients(client, { ...options, uid: true, away: true, voice: true, groups: true }),
]);
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 });
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,
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),
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",
observedAt: new Date().toISOString(),
};
});
}
/** Serialize writes, then revalidate live client identities immediately before changing them. */
action(raw: unknown): Promise<{ ok: true }> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
const request = raw as Record<string, unknown>;
const action = readAction(request.operation);
// Bind queued work to the configuration the administrator reviewed.
const expected = this.configuration();
if (request.configurationRevision !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
const operation = this.actions.then(() => this.withClient(async (client, options, assertCurrent) => {
assertCurrent();
switch (action.action) {
case "server.update":
await editServer(client, { virtualserver_name: action.name, virtualserver_welcomemessage: action.welcomeMessage,
virtualserver_maxclients: String(action.maxClients) }, options); break;
case "channel.create":
await createChannel(client, { name: action.name, parentID: asChannelID(BigInt(action.parentId)),
description: action.description, isPermanent: action.permanent, password: action.password }, options); break;
case "channel.update":
await editChannel(client, asChannelID(BigInt(action.channelId)), { name: action.name }, options); break;
case "channel.delete":
await deleteChannel(client, asChannelID(BigInt(action.channelId)), { ...options, force: false }); break;
case "ban.delete":
await deleteBan(client, asBanID(BigInt(action.banId)), options); break;
default: {
const current = (await listClients(client, { ...options, uid: true, groups: true })).find(entry => Number(entry.id) === action.clientId);
if (!current || !current.uid || current.uid !== action.clientUid || current.type !== 0) fail("TS_ADMIN_CLIENT_CHANGED");
assertCurrent();
if (action.action === "client.move") await moveClient(client, current.id, asChannelID(BigInt(action.channelId)), options);
else if (action.action === "client.kick") await kickClient(client, current.id, Reason.KickServer, { ...options, reasonMessage: action.reason });
else if (action.action === "client.group") {
if (!current.databaseID) fail("TS_ADMIN_CLIENT_CHANGED");
const change = action.remove ? removeClientFromServerGroup : addClientToServerGroup;
await change(client, asServerGroupID(BigInt(action.groupId)), current.databaseID, options);
} 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 }); }
catch { this.database.addAudit("TS_ADMIN_ACTION_PARTIAL", { action: action.action }); fail("TS_ADMIN_PARTIAL_SUCCESS"); }
}
}
}
this.database.addAudit("TS_ADMIN_ACTION_SUCCEEDED", { action: action.action });
return { ok: true as const };
}, expected)).catch(error => {
this.database.addAudit("TS_ADMIN_ACTION_FAILED", { action: action.action });
throw error;
});
this.actions = operation.catch(() => undefined);
return operation;
}
private configuration(): string {
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> {
this.assertFixed();
if (expected !== undefined && this.configuration() !== expected) fail("TS_ADMIN_CONFIG_CHANGED");
const settings = this.database.getTsAdminSettings();
if (!settings.enabled) fail("TS_ADMIN_NOT_CONFIGURED");
const policy = this.policy();
const captured = JSON.stringify(settings);
const assertCurrent = () => {
this.assertFixed();
if (this.policy().target !== policy.target || JSON.stringify(this.database.getTsAdminSettings()) !== captured) fail("TS_ADMIN_CONFIG_CHANGED");
};
let target: { host: string; port: number } | undefined;
if (!settings.serverId || settings.transport !== "web" && !settings.queryHost) {
try { target = await resolveTeamSpeakTarget(policy.target); } catch { fail("TS_ADMIN_TARGET_UNAVAILABLE"); }
}
const lifetime = new AbortController();
let transport: QueryClientOptions["transport"];
if (settings.transport === "web") {
if (!settings.webQueryUrl || !settings.apiKeyEncrypted) fail("TS_ADMIN_NOT_CONFIGURED");
transport = { kind: "web", url: settings.webQueryUrl, apiKey: this.decrypt(settings.apiKeyEncrypted, API_KEY_PURPOSE), fetch: webQueryFetch(lifetime.signal) };
} else {
if (!settings.passwordEncrypted || !settings.username) fail("TS_ADMIN_NOT_CONFIGURED");
const host = settings.queryHost || target!.host;
const password = this.decrypt(settings.passwordEncrypted, PASSWORD_PURPOSE);
transport = settings.transport === "tcp"
? { kind: "tcp", host, port: settings.queryPort, login: { name: settings.username, password } }
: { kind: "ssh", host, port: settings.queryPort, username: settings.username, password, hostKey: key => {
if (key.fingerprint !== settings.hostKeyFingerprint) fail("TS_ADMIN_HOST_KEY_MISMATCH");
} };
}
assertCurrent();
let client: QueryClient | undefined;
let connected = false;
try {
client = this.createClient({ transport, server: settings.serverId ? { id: settings.serverId } : { port: target!.port },
nickname: "WebSpeak Admin", ...(settings.transport === "web" ? {} : { events: false }) });
const signal = AbortSignal.timeout(20_000);
await client.connect({ signal }); connected = true; assertCurrent();
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");
this.logger.warn({ code, transport: settings.transport }, "TeamSpeak administrator request failed");
return fail(code);
} finally {
lifetime.abort();
try { await client?.disconnect(); } catch { /* no connection can outlive its request */ }
}
}
private assertFixed(): void { if (this.policy().mode !== "fixed") fail("TS_ADMIN_FIXED_MODE_REQUIRED"); }
private decrypt(value: string, purpose: string): string {
try { return decryptSecret(value, this.masterSecret, purpose); } catch { fail("TS_ADMIN_CREDENTIALS_UNAVAILABLE"); }
}
private secret(value: string | undefined, action: "keep" | "replace" | "remove" | undefined, current: string | null, purpose: string, max: number): string | null {
if (action === "remove") return null;
if (action === "replace" || action === undefined && value !== undefined) {
const secret = text(value ?? "", max);
return secret ? encryptSecret(secret, this.masterSecret, purpose) : null;
}
if (action !== undefined && action !== "keep") fail("INVALID_TS_ADMIN_SETTINGS");
return current;
}
}
function fail(code: string): never { throw new AdminInputError(code, code); }
function text(value: unknown, max: number, required = false): string {
if (typeof value !== "string" || value.length > max || /[\0]/.test(value) || required && !value.trim()) fail("INVALID_TS_ADMIN_ACTION");
return value;
}
function numeric(value: string | undefined): number { const n = Number(value); return Number.isFinite(n) && n >= 0 ? n : 0; }
function id(value: unknown, zero = false): string {
const v = text(value, 20, true);
if (!/^\d+$/.test(v) || BigInt(v) > 18_446_744_073_709_551_615n || !zero && BigInt(v) === 0n) fail("INVALID_TS_ADMIN_ACTION");
return v;
}
function readAction(raw: unknown): TsAdminAction {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("INVALID_TS_ADMIN_ACTION");
const r = raw as Record<string, unknown>;
const action = r.action;
if (action === "server.update") {
if (!Number.isInteger(r.maxClients) || Number(r.maxClients) < 1 || Number(r.maxClients) > 65535) fail("INVALID_TS_ADMIN_ACTION");
return { action, name: text(r.name, 64, true), welcomeMessage: text(r.welcomeMessage, 4096), maxClients: Number(r.maxClients) };
}
if (action === "channel.create") {
if (typeof r.permanent !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
return { action, name: text(r.name, 40, true), parentId: id(r.parentId, true), description: text(r.description, 8192),
permanent: r.permanent, ...(r.password === undefined ? {} : { password: text(r.password, 512) }) };
}
if (action === "channel.update") return { action, channelId: id(r.channelId), name: text(r.name, 40, true) };
if (action === "channel.delete") return { action, channelId: id(r.channelId) };
if (action === "ban.delete") return { action, banId: id(r.banId) };
if (!Number.isInteger(r.clientId) || Number(r.clientId) < 1 || Number(r.clientId) > 65535) fail("INVALID_TS_ADMIN_ACTION");
const member = { clientId: Number(r.clientId), clientUid: text(r.clientUid, 128, true) };
if (action === "client.move") return { action, ...member, channelId: id(r.channelId) };
if (action === "client.kick") return { action, ...member, reason: text(r.reason, 200) };
if (action === "client.group") {
if (typeof r.remove !== "boolean") fail("INVALID_TS_ADMIN_ACTION");
return { action, ...member, groupId: id(r.groupId), remove: r.remove };
}
if (action === "client.ban") {
if (!Number.isSafeInteger(r.durationSeconds) || Number(r.durationSeconds) < 0 || Number(r.durationSeconds) > 31_536_000) fail("INVALID_TS_ADMIN_ACTION");
return { action, ...member, reason: text(r.reason, 200), durationSeconds: Number(r.durationSeconds) };
}
fail("INVALID_TS_ADMIN_ACTION");
}
function classifyError(error: unknown, fallback: string): string {
const seen = new Set<unknown>();
while (error instanceof Error && !seen.has(error)) {
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 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";
if (error.code === 524) return "TS_ADMIN_RATE_LIMITED";
}
if (/CERT|SELF_SIGNED|UNABLE_TO_VERIFY/i.test(String((error as NodeJS.ErrnoException).code ?? ""))) return "TS_ADMIN_TLS_FAILED";
error = error.cause;
}
return fallback;
}
+28
View File
@@ -0,0 +1,28 @@
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
/** Keep the SDK's WebQuery protocol, but bound HTTP requests to this admin operation.
* Node's global fetch blocks WebQuery's default port 10080. */
export function webQueryFetch(lifetime: AbortSignal): typeof fetch {
return ((url: string, init: RequestInit) => new Promise<Response>((resolve, reject) => {
const request = new URL(url).protocol === "https:" ? httpsRequest : httpRequest;
const req = request(url, {
method: init.method, headers: init.headers as Record<string, string>,
signal: AbortSignal.any([lifetime, AbortSignal.timeout(8_000)]),
}, res => {
const chunks: Buffer[] = [];
let size = 0;
res.on("data", (chunk: Buffer) => {
size += chunk.length;
if (size > 8 * 1024 * 1024) { res.destroy(new Error("WebQuery response too large")); return; }
chunks.push(chunk);
});
res.on("error", reject);
res.on("end", () => resolve(new Response(Buffer.concat(chunks), {
status: res.statusCode ?? 502, statusText: res.statusMessage ?? "",
})));
});
req.on("error", reject);
req.end(init.body as string);
})) as typeof fetch;
}