chore: remove repository test sources

This commit is contained in:
illusia committed 2026-09-10 10:54:18 +08:00
1 parent a041ba90bb
commit 324213de14
25 files changed
+1 -1200

No files matched your search

+1 -2
View File
@@ -26,9 +26,8 @@ jobs:
npm run prepare:sdk
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
npm --prefix web ci --no-audit --no-fund
- name: Test and build
- name: Build application
run: |
npm test
npm run build
npm --prefix web run build
-1
View File
@@ -11,7 +11,6 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "tsx --test \"test/**/*.test.ts\"",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
"web:build": "cd web && npx vite build",
-244
View File
@@ -1,244 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { createServer } from "node:http";
import test from "node:test";
import express from "express";
import { createAdminRouter } from "../src/admin/admin-router.js";
import { AdminService } from "../src/admin/admin-service.js";
import { AdminSessionStore } from "../src/admin/admin-session.js";
import { WebSpeakDatabase } from "../src/persistence/database.js";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { silentLogger } from "./helpers/logger.js";
test("admin API requires the default password to be changed before administration", async (context) => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-api-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
path.join(directory, "missing-config.json"),
async (_target, password) => ({ ok: true, protocol: "ts6", latencyMs: 7, serverName: "Mock Server", requiresPassword: Boolean(password) }),
);
await service.initialize();
const app = express();
app.use(express.json());
app.use("/api/admin", createAdminRouter({
service,
sessions: new AdminSessionStore(),
logger: silentLogger,
getActiveSessions: () => 2,
getPeakSessions: () => 4,
startedAt: Date.now() - 5000,
}));
const server = createServer(app);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
context.after(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
database.close();
});
const address = server.address();
assert.ok(address && typeof address === "object");
const origin = `http://127.0.0.1:${address.port}`;
const status = await request(origin, "/api/admin/status");
assert.equal(status.response.status, 200);
assert.equal(status.response.headers.get("cache-control"), "no-store");
assert.equal(status.body.initialized, true);
assert.equal("setupDefaults" in status.body, false);
const login = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "admin" },
});
assert.equal(login.response.status, 200);
assert.equal(login.body.mustChangePassword, true);
assert.equal(typeof login.body.csrfToken, "string");
const cookie = login.response.headers.get("set-cookie")?.split(";", 1)[0];
assert.ok(cookie?.startsWith("webspeak_admin="));
assert.match(login.response.headers.get("set-cookie") ?? "", /HttpOnly/i);
assert.match(login.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i);
const session = await request(origin, "/api/admin/session", { cookie });
assert.equal(session.body.authenticated, true);
assert.equal(session.body.mustChangePassword, true);
const blockedOverview = await request(origin, "/api/admin/overview", { cookie });
assert.equal(blockedOverview.response.status, 403);
assert.equal(blockedOverview.body.code, "PASSWORD_CHANGE_REQUIRED");
const shortPassword = await request(origin, "/api/admin/change-password", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { newPassword: "too-short" },
});
assert.equal(shortPassword.response.status, 400);
assert.equal(shortPassword.body.code, "INVALID_ADMIN_PASSWORD");
const changed = await request(origin, "/api/admin/change-password", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { newPassword: "integration-admin-password" },
});
assert.equal(changed.response.status, 200);
assert.equal(changed.body.mustChangePassword, false);
const updatedSession = await request(origin, "/api/admin/session", { cookie });
assert.equal(updatedSession.body.mustChangePassword, false);
const overview = await request(origin, "/api/admin/overview", { cookie });
assert.deepEqual(overview.body.sessions, { active: 2, peak: 4, limit: 100 });
const rejectedMutation = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
body: { target: "voice.example.com:9988", accessMode: "open", siteName: "Changed", welcomeText: "" },
});
assert.equal(rejectedMutation.response.status, 403);
assert.equal(rejectedMutation.body.code, "CSRF_REJECTED");
const saved = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
csrf: login.body.csrfToken,
body: {
target: "voice.example.com:9988",
passwordAction: "remove",
accessMode: "open",
siteName: "Changed",
welcomeText: "Open access",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
},
});
assert.equal(saved.body.ok, true);
assert.equal(saved.body.settings.accessMode, "open");
assert.equal(saved.body.settings.hasPassword, false);
assert.equal(saved.body.settings.webRtcEnabled, true);
assert.equal(saved.body.settings.webRtcUdpStart, 41000);
assert.equal(saved.body.settings.webRtcUdpEnd, 41099);
const lockedPorts = await request(origin, "/api/admin/server", {
method: "PUT",
cookie,
csrf: login.body.csrfToken,
body: {
target: "voice.example.com:9988",
passwordAction: "keep",
accessMode: "open",
siteName: "Changed",
welcomeText: "Open access",
webRtcEnabled: true,
webRtcUdpStart: 42000,
webRtcUdpEnd: 42099,
},
});
assert.equal(lockedPorts.response.status, 400);
assert.equal(lockedPorts.body.code, "WEBRTC_PORT_LOCKED");
const invite = await request(origin, "/api/admin/invites", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { channel: "Lobby", expiresInHours: 4, maxUses: 2 },
});
assert.equal(invite.response.status, 201);
assert.equal(invite.body.ok, true);
assert.match(invite.body.token, /^[A-Za-z0-9_-]{43}$/);
assert.equal(invite.body.invite.channel, "Lobby");
assert.equal("token" in invite.body.invite, false);
const invites = await request(origin, "/api/admin/invites", { cookie });
assert.equal(invites.body.invites.length, 1);
assert.equal(invites.body.invites[0].status, "active");
assert.equal(invites.body.invites[0].target, "voice.example.com:9988");
const sessions = await request(origin, "/api/admin/sessions", { cookie });
assert.deepEqual(sessions.body.sessions, []);
const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie });
assert.equal(diagnostics.body.database.schemaVersion, 4);
assert.equal("target" in diagnostics.body.teamSpeak, true);
assert.equal("protocol" in diagnostics.body.teamSpeak, false);
const report = await request(origin, "/api/admin/diagnostics/report", { cookie });
assert.equal(report.response.status, 200);
assert.match(report.response.headers.get("content-disposition") ?? "", /diagnostic-report\.json/);
assert.equal("target" in report.body.teamSpeak, false);
assert.equal("protocol" in report.body.teamSpeak, false);
assert.equal("serverPassword" in report.body, false);
const revoked = await request(origin, `/api/admin/invites/${encodeURIComponent(invite.body.invite.id)}/revoke`, {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: {},
});
assert.equal(revoked.body.ok, true);
const revokedList = await request(origin, "/api/admin/invites", { cookie });
assert.equal(revokedList.body.invites[0].status, "revoked");
const backup = await download(origin, "/api/admin/backup", cookie);
assert.equal(backup.response.status, 200);
assert.equal(backup.response.headers.get("content-type"), "application/octet-stream");
assert.ok(backup.bytes.length > 100);
assert.equal("serverPassword" in saved.body.settings, false);
const probe = await request(origin, "/api/admin/server/test", {
method: "POST",
cookie,
csrf: login.body.csrfToken,
body: { target: "voice.example.com:9988", passwordAction: "remove" },
});
assert.equal("protocol" in probe.body, false);
const settings = await request(origin, "/api/admin/server", { cookie });
assert.equal("detectedProtocol" in settings.body, false);
assert.equal(settings.body.lastTestLatencyMs, 7);
const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} });
assert.equal(logout.body.ok, true);
const denied = await request(origin, "/api/admin/overview", { cookie });
assert.equal(denied.response.status, 401);
const oldPassword = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "admin" },
});
assert.equal(oldPassword.response.status, 401);
const newPassword = await request(origin, "/api/admin/login", {
method: "POST",
body: { username: "admin", password: "integration-admin-password" },
});
assert.equal(newPassword.response.status, 200);
assert.equal(newPassword.body.mustChangePassword, false);
});
async function request(
origin: string,
pathname: string,
options: { method?: string; body?: unknown; cookie?: string; csrf?: string } = {},
): Promise<{ response: Response; body: any }> {
const method = options.method ?? "GET";
const response = await fetch(`${origin}${pathname}`, {
method,
headers: {
accept: "application/json",
...(method !== "GET" ? { "content-type": "application/json", origin } : {}),
...(options.cookie ? { cookie: options.cookie } : {}),
...(options.csrf ? { "x-csrf-token": options.csrf } : {}),
},
...(method !== "GET" ? { body: JSON.stringify(options.body ?? {}) } : {}),
});
return { response, body: await response.json() };
}
async function download(origin: string, pathname: string, cookie?: string): Promise<{ response: Response; bytes: Uint8Array }> {
const response = await fetch(`${origin}${pathname}`, {
headers: { accept: "application/octet-stream", ...(cookie ? { cookie } : {}) },
});
return { response, bytes: new Uint8Array(await response.arrayBuffer()) };
}
-37
View File
@@ -1,37 +0,0 @@
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { readConnectionHistory } from "../src/admin/admin-router.js";
test("admin log history groups a user's connection lifecycle", () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-log-history-"));
const logFile = path.join(directory, "webspeak.log");
const connectedAt = new Date(Date.now() - 8_000).toISOString();
const disconnectedAt = new Date(Date.now() - 2_000).toISOString();
const lines = [
{ time: new Date(Date.now() - 9_000).toISOString(), msg: "WebClient connecting", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
{ time: connectedAt, msg: "Web client connected to TeamSpeak", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987" },
{ time: disconnectedAt, msg: "Client session torn down", entryId: "entry-a", nickname: "Alice", target: "voice.example.com:9987", reason: "websocket-close", durationSeconds: 6 },
{ time: new Date(Date.now() - 1_000).toISOString(), msg: "WebClient connecting", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
{ time: new Date(Date.now() - 500).toISOString(), msg: "Web client connected to TeamSpeak", entryId: "entry-b", nickname: "Bob", target: "voice.example.com:9987" },
{ time: new Date(Date.now() - 250).toISOString(), msg: "WebClient connecting", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987" },
{ time: new Date(Date.now() - 100).toISOString(), msg: "Client session torn down", entryId: "entry-c", nickname: "Carol", target: "voice.example.com:9987", reason: "teamSpeak-connect-failed", durationSeconds: 0 },
].map((entry) => JSON.stringify(entry));
writeFileSync(logFile, `${lines.join("\n")}\n`);
const history = readConnectionHistory(logFile, 10);
assert.equal(history.length, 3);
const alice = history.find((entry) => entry.id === "entry-a");
const bob = history.find((entry) => entry.id === "entry-b");
const carol = history.find((entry) => entry.id === "entry-c");
assert.equal(alice?.status, "disconnected");
assert.equal(alice?.durationSeconds, 6);
assert.equal(alice?.disconnectedAt, disconnectedAt);
assert.equal(bob?.status, "active");
assert.equal(bob?.disconnectedAt, null);
assert.ok((bob?.durationSeconds ?? 0) >= 0);
assert.equal(carol?.status, "failed");
assert.equal(carol?.durationSeconds, null);
});
-128
View File
@@ -1,128 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import { AdminService } from "../src/admin/admin-service.js";
import { WebSpeakDatabase } from "../src/persistence/database.js";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { silentLogger } from "./helpers/logger.js";
test("legacy config imports once, seeds the default admin, and allows password rotation", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-service-"));
const legacyPath = path.join(directory, "config.json");
const legacyText = JSON.stringify({
tsHost: "legacy.example.com",
tsPort: 9988,
tsServerPassword: "legacy-secret-value",
tsServerProtocol: "ts6",
maxClients: 9000,
port: 9999,
trustProxy: true,
}, null, 2);
writeFileSync(legacyPath, legacyText);
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
legacyPath,
async () => ({ ok: true, protocol: "ts6", latencyMs: 4, serverName: "Mock TS", requiresPassword: true }),
);
await service.initialize();
assert.equal(readFileSync(legacyPath, "utf8"), legacyText);
assert.equal(database.getSettings().tsHost, "legacy.example.com");
assert.equal(database.getSettings().tsPort, 9988);
assert.equal(service.getConnectionPolicy().serverPassword, "legacy-secret-value");
assert.equal(readFileSync(path.join(directory, "webspeak.db")).includes(Buffer.from("legacy-secret-value")), false);
assert.equal(service.isInitialized(), true);
assert.equal(await service.verifyPassword("admin", "admin"), true);
assert.equal(await service.verifyPassword("wrong-user", "admin"), false);
assert.equal(service.isPasswordChangeRequired(), true);
await service.changePassword("a-secure-admin-password");
assert.equal(await service.verifyPassword("admin", "a-secure-admin-password"), true);
assert.equal(await service.verifyPassword("admin", "admin"), false);
assert.equal(service.isPasswordChangeRequired(), false);
assert.equal(service.getPublicConfig().accessMode, "fixed");
assert.equal(service.getPublicConfig().target, "legacy.example.com:9988");
service.updateSettings({
target: "public.example.com:9987",
serverPassword: "replacement-secret",
passwordAction: "replace",
accessMode: "open",
siteName: "Open WebSpeak",
welcomeText: "Public gateway",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
});
const publicConfig = service.getPublicConfig();
assert.equal(publicConfig.target, "public.example.com:9987");
assert.equal(publicConfig.accessMode, "open");
assert.equal("serverPassword" in service.getAdminSettings(), false);
assert.equal(service.getAdminSettings().hasPassword, true);
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
assert.equal(service.getAdminSettings().webRtcEnabled, true);
assert.equal(service.getAdminSettings().webRtcUdpStart, 41000);
assert.equal(service.getAdminSettings().webRtcUdpEnd, 41099);
assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, udpPortRange: [41000, 41099] });
assert.throws(() => service.updateSettings({
target: "public.example.com:9987",
accessMode: "open",
siteName: "Open WebSpeak",
welcomeText: "Public gateway",
webRtcEnabled: true,
webRtcUdpStart: 42000,
webRtcUdpEnd: 42099,
}), /Disable WebRTC/);
database.close();
});
test("managed invites are opaque, bounded, revocable, and included in database backups", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-invites-"));
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
const service = new AdminService(
database,
loadOrCreateMasterSecret(path.join(directory, "master.key")),
silentLogger,
path.join(directory, "missing-config.json"),
);
await service.initialize();
const created = service.createManagedInvite({ channel: "Lobby", expiresInHours: 2, maxUses: 1 });
assert.match(created.token, /^[A-Za-z0-9_-]{43}$/);
assert.equal(created.invite.channel, "Lobby");
assert.equal(created.invite.status, "active");
assert.equal("token" in created.invite, false);
const consumed = service.consumeManagedInvite(created.token);
assert.deepEqual(consumed?.target, { host: "127.0.0.1", port: 9987 });
assert.equal(consumed?.channel, "Lobby");
assert.equal(service.consumeManagedInvite(created.token), null);
assert.equal(service.listManagedInvites()[0]?.status, "exhausted");
database.createManagedInvite({
id: "invite-expired-test",
tokenHash: "expired-token-hash",
targetHost: "127.0.0.1",
targetPort: 9987,
serverPasswordEncrypted: null,
channel: "Expired",
expiresAt: new Date(Date.now() - 1).toISOString(),
maxUses: 0,
});
assert.equal(database.consumeManagedInvite("expired-token-hash"), null);
const revocable = service.createManagedInvite({ channel: "Revocable", expiresInHours: 2, maxUses: 0 });
assert.equal(service.revokeManagedInvite(revocable.invite.id), true);
assert.equal(service.listManagedInvites().find((invite) => invite.id === revocable.invite.id)?.status, "revoked");
const backup = database.exportBackup();
assert.ok(backup.length > 100);
database.close();
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
assert.equal(reopened.schemaVersion, 4);
assert.equal(reopened.listManagedInvites().length, 3);
reopened.close();
});
-71
View File
@@ -1,71 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { migrateConfig, saveConfig } from "../src/config.js";
describe("legacy config migration", () => {
it("drops deprecated runtime controls while preserving the TeamSpeak target", () => {
assert.deepEqual(migrateConfig({
port: 3999,
tsHost: "TS.Example.COM",
tsPort: "9988",
tsServerPassword: "secret",
tsServerProtocol: "ts6",
maxClients: 3,
trustProxy: true,
}), {
tsHost: "ts.example.com",
tsPort: 9988,
tsServerPassword: "secret",
});
});
it("accepts a host with an embedded port during migration", () => {
assert.deepEqual(migrateConfig({ tsHost: "[2001:db8::1]:9988" }), {
tsHost: "2001:db8::1",
tsPort: 9988,
tsServerPassword: "",
});
});
it("accepts the address#port form during migration", () => {
assert.deepEqual(migrateConfig({ tsHost: "voice.example.com#9988" }), {
tsHost: "voice.example.com",
tsPort: 9988,
tsServerPassword: "",
});
});
it("falls back safely for malformed legacy targets", () => {
assert.deepEqual(migrateConfig({ tsHost: "bad host", tsPort: 0 }), {
tsHost: "127.0.0.1",
tsPort: 9987,
tsServerPassword: "",
});
});
it("writes the migrated shape without deprecated runtime controls", () => {
const directory = mkdtempSync(join(tmpdir(), "webspeak-m000-config-"));
const path = join(directory, "config.json");
try {
writeFileSync(path, JSON.stringify({
port: 3999,
tsHost: "example.com",
tsPort: 9988,
tsServerProtocol: "ts3",
maxClients: 2,
trustProxy: true,
}), "utf8");
saveConfig(path, migrateConfig(JSON.parse(readFileSync(path, "utf8"))));
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), {
tsHost: "example.com",
tsPort: 9988,
tsServerPassword: "",
});
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
});
-46
View File
@@ -1,46 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { ChannelInfo, ClientInfo } from "@echosixhiya/teamspeak-client";
import { DirectorySynchronizer } from "../src/server/directory-sync.js";
const root: ChannelInfo = { id: 1n, parentID: 0n, name: "Lobby", description: "", };
const games: ChannelInfo = { id: 2n, parentID: 1n, name: "Games", description: "", };
function client(id: number, nickname: string, channelID: bigint): ClientInfo {
return { id, nickname, uid: `uid-${id}`, channelID, type: 1, serverGroups: [] };
}
test("directory synchronizer merges welcome events that arrive before the snapshot", () => {
const sync = new DirectorySynchronizer();
sync.applyClientEnter(client(7, "Alice", 1n));
sync.applyClientMoved(7, 2n);
sync.applySnapshot({ channels: [root, games], clients: [client(3, "Bob", 1n)] });
assert.equal(sync.ready, true);
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n], [7, 2n]]);
});
test("directory state and movement events remain isolated per session", () => {
const first = new DirectorySynchronizer();
const second = new DirectorySynchronizer();
const snapshot = { channels: [root, games], clients: [client(3, "Bob", 1n)] };
first.applySnapshot(snapshot);
second.applySnapshot(snapshot);
first.applyClientEnter(client(7, "Alice", 2n));
first.applyClientMoved(3, 2n);
first.applyClientLeave(7);
assert.deepEqual(first.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 2n]]);
assert.deepEqual(second.getSnapshot()?.clients.map((item) => [item.id, item.channelID]), [[3, 1n]]);
});
test("directory synchronizer keeps clients across staged partial snapshots", () => {
const sync = new DirectorySynchronizer();
const alice = client(7, "Alice", 1n);
const bob = client(8, "Bob", 1n);
sync.applySnapshot({ channels: [root], clients: [alice, bob] });
sync.applySnapshot({ channels: [root], clients: [bob] });
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [7, 8]);
sync.applyClientLeave(alice.id);
assert.deepEqual(sync.getSnapshot()?.clients.map((item) => item.id), [8]);
});
-16
View File
@@ -1,16 +0,0 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { normalizeTeamSpeakError } from "../src/errors.js";
describe("normalized connection errors", () => {
it("classifies authentication failures as non-retryable", () => {
const error = normalizeTeamSpeakError(new Error("invalid server password"));
assert.equal(error.code, "authentication_failed");
assert.equal(error.retryable, false);
});
it("classifies network and timeout failures", () => {
assert.equal(normalizeTeamSpeakError(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })).code, "unreachable");
assert.equal(normalizeTeamSpeakError(new Error("ack timeout")).code, "timeout");
});
});
-9
View File
@@ -1,9 +0,0 @@
import type { Logger } from "../../src/logger.js";
export const silentLogger: Logger = {
debug: () => undefined,
info: () => undefined,
warn: () => undefined,
error: () => undefined,
child: () => silentLogger,
};
-13
View File
@@ -1,13 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { IdentityLeaseStore } from "../src/server/identity-lease.js";
test("an identity lease rejects a second live owner and ignores a release from another owner", () => {
const store = new IdentityLeaseStore();
assert.equal(store.acquire("target:identity", "first"), true);
assert.equal(store.acquire("target:identity", "second"), false);
store.release("target:identity", "second");
assert.equal(store.acquire("target:identity", "second"), false);
store.release("target:identity", "first");
assert.equal(store.acquire("target:identity", "second"), true);
});
-13
View File
@@ -1,13 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { JoinRateLimiter } from "../src/server/join-rate-limit.js";
test("join ticket creation is bounded per peer and resets after its window", () => {
const limiter = new JoinRateLimiter(2);
let now = 10_000;
for (let attempt = 0; attempt < 30; attempt++) assert.equal(limiter.allow("peer-a", now), true);
assert.equal(limiter.allow("peer-a", now), false);
assert.equal(limiter.allow("peer-b", now), true);
now += 60_000;
assert.equal(limiter.allow("peer-a", now), true);
});
-24
View File
@@ -1,24 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@echosixhiya/teamspeak-client";
import { JoinTicketStore } from "../src/server/join-ticket.js";
test("join tickets are opaque, one-time, and expire", () => {
const store = new JoinTicketStore(1000, 2);
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest" };
const token = store.create(payload, 100);
assert.equal(token.includes("secret"), false);
assert.deepEqual(store.consume(token, 101), payload);
assert.equal(store.consume(token, 102), null);
const expired = store.create(payload, 200);
assert.equal(store.consume(expired, 1201), null);
});
test("join tickets carry identity only in memory and never expose it in the opaque token", () => {
const store = new JoinTicketStore();
const identity = generateIdentity(8).toString();
const payload = { target: { host: "example.com", port: 9987 }, serverPassword: "secret", nickname: "Guest", identity, rememberIdentity: true };
const token = store.create(payload);
assert.equal(token.includes(identity), false);
assert.deepEqual(store.consume(token), payload);
});
-12
View File
@@ -1,12 +0,0 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../src/constants.js";
describe("session safety limit", () => {
it("uses the fixed 100-session product limit", () => {
assert.equal(MAX_ACTIVE_SESSIONS, 100);
assert.equal(canAcceptSession(99), true);
assert.equal(canAcceptSession(100), false);
assert.equal(canAcceptSession(101), false);
});
});
-20
View File
@@ -1,20 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { AdminLoginRateLimiter } from "../src/admin/login-rate-limit.js";
test("admin login limiter blocks repeated failures for one peer", () => {
const limiter = new AdminLoginRateLimiter();
const start = 1_000_000;
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("peer-a", start + attempt);
assert.ok(limiter.retryAfterMs("peer-a", start + 5) > 0);
assert.equal(limiter.retryAfterMs("peer-a", start + 5 * 60 * 1000), 0);
});
test("admin login limiter evicts old peers when its bounded table is full", () => {
const limiter = new AdminLoginRateLimiter(2);
for (let attempt = 0; attempt < 5; attempt += 1) limiter.recordFailure("oldest", 10 + attempt);
limiter.recordFailure("second", 20);
limiter.recordFailure("newest", 30);
assert.equal(limiter.retryAfterMs("oldest", 31), 0);
assert.equal(limiter.retryAfterMs("second", 31), 0);
});
-19
View File
@@ -1,19 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRestrictedAddress, resolveSafeOpenTarget } from "../src/security/open-target-policy.js";
test("open mode blocks loopback, private, link-local, multicast and reserved ranges", () => {
for (const address of [
"0.0.0.0", "10.1.2.3", "100.64.0.1", "127.0.0.1", "169.254.1.2",
"172.16.0.1", "192.168.1.2", "224.0.0.1", "255.255.255.255",
"::", "::1", "::7f00:1", "fc00::1", "fe80::1", "fec0::1", "ff02::1", "2001:db8::1",
]) assert.equal(isRestrictedAddress(address), true, address);
assert.equal(isRestrictedAddress("8.8.8.8"), false);
assert.equal(isRestrictedAddress("2606:4700:4700::1111"), false);
});
test("validated literal target is returned for the actual connection", async () => {
assert.deepEqual(await resolveSafeOpenTarget({ host: "8.8.8.8", port: 9987 }), { host: "8.8.8.8", port: 9987 });
assert.deepEqual(await resolveSafeOpenTarget({ host: "2606:4700:4700::1111", port: 9987 }), { host: "2606:4700:4700::1111", port: 9987 });
await assert.rejects(resolveSafeOpenTarget({ host: "127.0.0.1", port: 9987 }));
});
-84
View File
@@ -1,84 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { collectTeamSpeakPings, pingTeamSpeakHost, pingTeamSpeakSession, summarizeTeamSpeakPings } from "../src/server/network-probe.js";
test("TeamSpeak latency probe uses the protocol command channel", async () => {
let command = "";
const result = await pingTeamSpeakSession(async (value) => {
command = value;
return [];
});
assert.equal(command, "version");
assert.equal(result.ok, true);
assert.equal(result.errorCode, undefined);
assert.equal(typeof result.latencyMs, "number");
});
test("TeamSpeak protocol probe classifies a timeout and aggregates packet loss", async () => {
const timeout = await pingTeamSpeakSession(async () => {
throw new Error("packet ack timeout");
});
assert.deepEqual(timeout, { ok: false, latencyMs: null, errorCode: "TIMEOUT" });
let calls = 0;
const result = await collectTeamSpeakPings(async () => {
calls += 1;
return calls === 2
? { ok: false, latencyMs: null, errorCode: "TIMEOUT" }
: { ok: true, latencyMs: calls };
}, { attempts: 4 });
assert.equal(calls, 4);
assert.equal(result.ok, true);
assert.equal(result.packetLossPercent, 25);
assert.equal(result.successfulAttempts, 3);
assert.deepEqual(result.samples, [1, 3, 4]);
});
test("TeamSpeak ping summary reports complete loss without fake latency", () => {
const result = summarizeTeamSpeakPings([
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
{ ok: false, latencyMs: null, errorCode: "UNREACHABLE" },
]);
assert.deepEqual(result, {
ok: false,
latencyMs: null,
packetLossPercent: 100,
attempts: 2,
successfulAttempts: 0,
samples: [],
errorCode: "UNREACHABLE",
});
});
test("admin host ping measures the route without opening a TeamSpeak client", async () => {
const calls: Array<[string, number]> = [];
let attempt = 0;
const result = await pingTeamSpeakHost("203.0.113.10", {
attempts: 4,
timeoutMs: 900,
execute: async (host, timeoutMs) => {
calls.push([host, timeoutMs]);
attempt += 1;
if (attempt === 3) throw new Error("ping timeout");
return attempt * 2;
},
});
assert.deepEqual(calls, [
["203.0.113.10", 900],
["203.0.113.10", 900],
["203.0.113.10", 900],
["203.0.113.10", 900],
]);
assert.equal(result.ok, true);
assert.equal(result.packetLossPercent, 25);
assert.equal(result.latencyMs, 4);
});
test("admin host ping reports a missing runtime ping tool separately from packet loss", async () => {
const result = await pingTeamSpeakHost("203.0.113.20", {
attempts: 1,
execute: async () => { throw new Error("spawn ping ENOENT"); },
});
assert.equal(result.ok, false);
assert.equal(result.errorCode, "PING_UNAVAILABLE");
});
-87
View File
@@ -1,87 +0,0 @@
import assert from "node:assert/strict";
import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import test from "node:test";
import { WebSpeakDatabase, DATABASE_SCHEMA_VERSION } from "../src/persistence/database.js";
import { hashAdminPassword } from "../src/security/admin-password.js";
test("SQLite persistence initializes schema and stores the single admin/settings model", async () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-"));
const dbPath = path.join(directory, "webspeak.db");
const database = new WebSpeakDatabase(dbPath);
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
assert.equal(database.hasAdmin(), false);
assert.equal(database.getSettings().accessMode, "fixed");
const credential = await hashAdminPassword("database-admin-password");
database.initializeAdmin(credential, {
siteName: "Private Voice",
welcomeText: "Welcome",
welcomeTextEn: "",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
});
assert.equal(database.hasAdmin(), true);
assert.equal(database.getAdminCredential()?.hash, credential.hash);
assert.deepEqual(database.getSettings(), {
siteName: "Private Voice",
welcomeText: "Welcome",
welcomeTextEn: "",
accessMode: "open",
tsHost: "voice.example.com",
tsPort: 9988,
tsPasswordEncrypted: "v1:ciphertext",
detectedProtocol: null,
lastTestAt: null,
lastTestLatencyMs: null,
lastTestError: null,
webRtcEnabled: true,
webRtcUdpStart: 41000,
webRtcUdpEnd: 41099,
updatedAt: database.getSettings().updatedAt,
});
assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED");
database.close();
const reopened = new WebSpeakDatabase(dbPath);
assert.equal(reopened.hasAdmin(), true);
assert.equal(reopened.getSettings().siteName, "Private Voice");
reopened.close();
});
test("SQLite schema v1 upgrades to v4 with a migration copy", () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-"));
const dbPath = path.join(directory, "webspeak.db");
const legacy = new DatabaseSync(dbPath);
legacy.exec(`
CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE admin_credentials (id INTEGER PRIMARY KEY CHECK (id = 1), credential_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE settings (
id INTEGER PRIMARY KEY CHECK (id = 1), site_name TEXT NOT NULL, welcome_text TEXT NOT NULL,
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')), ts_host TEXT NOT NULL,
ts_port INTEGER NOT NULL, ts_password_encrypted TEXT, detected_protocol TEXT,
last_test_at TEXT, last_test_latency_ms INTEGER, last_test_error TEXT, updated_at TEXT NOT NULL
);
CREATE TABLE audit_events (id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT NOT NULL, details_json TEXT NOT NULL, created_at TEXT NOT NULL);
INSERT INTO settings VALUES (1, 'Legacy', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, '2026-01-01T00:00:00.000Z');
PRAGMA user_version = 1;
`);
legacy.close();
const upgraded = new WebSpeakDatabase(dbPath);
assert.equal(upgraded.schemaVersion, 4);
assert.equal(upgraded.getSettings().webRtcEnabled, false);
assert.equal(upgraded.getSettings().webRtcUdpStart, 40000);
assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099);
assert.equal(upgraded.getSettings().welcomeTextEn, "");
assert.equal(upgraded.listManagedInvites().length, 0);
assert.equal(existsSync(`${dbPath}.schema-1.bak`), true);
upgraded.close();
});
-49
View File
@@ -1,49 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { probeTeamSpeak, toProbeError } from "../src/server/teamspeak-probe.js";
import { silentLogger } from "./helpers/logger.js";
test("connection probe reports protocol/server and always tears down", async () => {
let disconnected = false;
const result = await probeTeamSpeak({ host: "example.com", port: 9987 }, "", silentLogger, () => ({
protocol: "ts6",
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Example TS" }] },
connect: async () => undefined,
disconnect: async () => { disconnected = true; },
}));
assert.equal(result.ok, true);
assert.equal(result.protocol, "ts6");
assert.equal(result.serverName, "Example TS");
assert.equal(disconnected, true);
});
test("connection probe normalizes DNS errors and tears down failures", async () => {
let disconnected = false;
await assert.rejects(
probeTeamSpeak({ host: "missing.invalid", port: 9987 }, "", silentLogger, () => ({
protocol: null,
client: { execCommandWithResponse: async () => [] },
connect: async () => { throw Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" }); },
disconnect: async () => { disconnected = true; },
})),
(error: unknown) => Boolean(error && typeof error === "object" && "code" in error && error.code === "HOST_NOT_FOUND"),
);
assert.equal(disconnected, true);
assert.equal(toProbeError(new Error("authentication invalid password")).code, "INVALID_PASSWORD");
});
test("connection probe keeps a successful result when cleanup reports an error", async () => {
const result = await probeTeamSpeak(
{ host: "voice.example.com", port: 9987 },
"",
silentLogger,
() => ({
protocol: "ts6",
client: { execCommandWithResponse: async () => [{ virtualserver_name: "Cleanup Test" }] },
connect: async () => {},
disconnect: async () => { throw new Error("already disconnected"); },
}),
);
assert.equal(result.ok, true);
assert.equal(result.serverName, "Cleanup Test");
});
-28
View File
@@ -1,28 +0,0 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { EndpointProtocolCache, detectTeamSpeakProtocol } from "../src/server/teamspeak-adapter.js";
describe("TeamSpeak protocol adapter", () => {
it("detects TS3 and TS6 from the normal version response", () => {
assert.equal(detectTeamSpeakProtocol("version=3.13.7 build=12345"), "ts3");
assert.equal(detectTeamSpeakProtocol("TeamSpeak 6 version 6.0.0"), "ts6");
assert.equal(detectTeamSpeakProtocol("unknown"), null);
});
it("remembers a successful endpoint only for its bounded TTL", () => {
const cache = new EndpointProtocolCache(1000, 2);
const target = { host: "example.com", port: 9987 };
cache.set(target, "ts6", 1000);
assert.equal(cache.get(target, 1500), "ts6");
assert.equal(cache.get(target, 2001), undefined);
});
it("evicts the oldest endpoint when bounded", () => {
const cache = new EndpointProtocolCache(60_000, 2);
cache.set({ host: "one.example", port: 9987 }, "ts3", 1);
cache.set({ host: "two.example", port: 9987 }, "ts3", 2);
cache.set({ host: "three.example", port: 9987 }, "ts6", 3);
assert.equal(cache.size, 2);
assert.equal(cache.get({ host: "one.example", port: 9987 }, 4), undefined);
});
});
-19
View File
@@ -1,19 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { WebSpeakError } from "../src/errors.js";
import { RECONNECT_WINDOW_MS, isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "../src/server/reconnect-policy.js";
test("reconnect backoff follows the bounded policy and applies deterministic jitter", () => {
assert.deepEqual([1, 2, 3, 4, 5, 6, 8].map((attempt) => reconnectDelayMs(attempt, () => 0.5)), [1000, 2000, 4000, 8000, 15000, 30000, 30000]);
assert.equal(reconnectDelayMs(1, () => 0), 900);
assert.equal(reconnectDelayMs(1, () => 1), 1100);
assert.equal(reconnectDelayMs(0, () => 0.5), 1000);
});
test("reconnect eligibility distinguishes transient failures from authentication failures", () => {
assert.equal(isRecoverable(new WebSpeakError("unreachable", "offline", true)), true);
assert.equal(isRecoverable(new WebSpeakError("authentication_failed", "bad password", false)), false);
assert.equal(isRecoverable(null), true);
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS - 1), true);
assert.equal(reconnectWindowOpen(10_000, 10_000 + RECONNECT_WINDOW_MS), false);
});
-38
View File
@@ -1,38 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
import { loadOrCreateMasterSecret } from "../src/security/master-secret.js";
import { decryptSecret, encryptSecret } from "../src/security/secret-crypto.js";
import { hashAdminPassword, verifyAdminPassword } from "../src/security/admin-password.js";
test("master secret is stable and protects authenticated ciphertext", () => {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-secret-"));
const secretPath = path.join(directory, "master.key");
const first = loadOrCreateMasterSecret(secretPath);
const second = loadOrCreateMasterSecret(secretPath);
assert.equal(first.length, 32);
assert.deepEqual(first, second);
const encrypted = encryptSecret("never-store-this-password", first);
assert.equal(encrypted.includes("never-store-this-password"), false);
assert.equal(decryptSecret(encrypted, first), "never-store-this-password");
const [version, nonce, tag, ciphertext] = encrypted.split(":") as [string, string, string, string];
const tamperedTag = `${tag[0] === "A" ? "B" : "A"}${tag.slice(1)}`;
assert.throws(() => decryptSecret([version, nonce, tamperedTag, ciphertext].join(":"), first));
});
test("admin password uses a salted scrypt credential", async () => {
const first = await hashAdminPassword("a-long-admin-password");
const second = await hashAdminPassword("a-long-admin-password");
assert.notEqual(first.salt, second.salt);
assert.notEqual(first.hash, second.hash);
assert.equal(await verifyAdminPassword("a-long-admin-password", first), true);
assert.equal(await verifyAdminPassword("wrong-password-value", first), false);
assert.equal(JSON.stringify(first).includes("a-long-admin-password"), false);
const pending = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
assert.equal(pending.username, "admin");
assert.equal(pending.mustChangePassword, true);
});
-59
View File
@@ -1,59 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ConnectionStateMachine, SessionManager } from "../src/server/session-manager.js";
test("connection state machine accepts the normal lifecycle and rejects illegal jumps", () => {
const machine = new ConnectionStateMachine();
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("syncing");
machine.transition("connected");
machine.transition("interrupted");
machine.transition("reconnecting");
machine.transition("connecting");
assert.throws(() => machine.transition("connected"), /Illegal connection state transition/);
});
test("connection state machine can retry a transient authentication phase", () => {
const machine = new ConnectionStateMachine();
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("reconnecting");
machine.transition("connecting");
machine.transition("authenticating");
machine.transition("syncing");
machine.transition("connected");
assert.equal(machine.state, "connected");
});
test("managed session teardown is idempotent and reaches idle even when cleanup fails", async () => {
const manager = new SessionManager();
let cleanupCalls = 0;
const session = manager.admit("session-a", async () => {
cleanupCalls++;
throw new Error("already closed");
});
assert.ok(session);
session.transition("connecting");
await Promise.all([session.teardown("websocket-close"), session.teardown("websocket-error")]);
assert.equal(cleanupCalls, 1);
assert.equal(session.state, "idle");
assert.equal(manager.activeCount, 1);
await manager.teardown("session-a", "websocket-close");
assert.equal(manager.activeCount, 0);
});
test("session manager admits 100 active sessions and rejects the 101st", async () => {
const manager = new SessionManager();
for (let index = 0; index < 100; index++) {
assert.ok(manager.admit(`session-${index}`, async () => undefined));
}
assert.equal(manager.activeCount, 100);
assert.equal(manager.admit("session-100", async () => undefined), null);
assert.equal(manager.peakCount, 100);
assert.equal(manager.createdCount, 100);
await manager.shutdown();
assert.equal(manager.activeCount, 0);
assert.equal(manager.isAccepting, false);
assert.equal(manager.admit("after-shutdown", async () => undefined), null);
});
-45
View File
@@ -1,45 +0,0 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
InvalidTeamSpeakTargetError,
formatTeamSpeakTarget,
parseTeamSpeakTarget,
parseTeamSpeakTargetParts,
teamSpeakTargetKey,
} from "../src/domain/teamspeak-target.js";
describe("TeamSpeak target parser", () => {
it("uses 9987 when the port is omitted", () => {
assert.deepEqual(parseTeamSpeakTarget("Example.COM"), { host: "example.com", port: 9987 });
});
it("parses a custom port", () => {
assert.deepEqual(parseTeamSpeakTarget("ts.example.com:9988"), { host: "ts.example.com", port: 9988 });
});
it("parses the address#port form used by the web fields", () => {
assert.deepEqual(parseTeamSpeakTarget("ts.example.com#9988"), { host: "ts.example.com", port: 9988 });
assert.deepEqual(parseTeamSpeakTarget("[2001:DB8::1]#9988"), { host: "2001:db8::1", port: 9988 });
});
it("supports bracketed IPv6", () => {
const target = parseTeamSpeakTarget("[2001:DB8::1]:9987");
assert.deepEqual(target, { host: "2001:db8::1", port: 9987 });
assert.equal(formatTeamSpeakTarget(target), "[2001:db8::1]:9987");
});
it("accepts legacy split fields", () => {
assert.deepEqual(parseTeamSpeakTargetParts("[::1]", "9988"), { host: "::1", port: 9988 });
assert.deepEqual(parseTeamSpeakTargetParts("ts.example.com", undefined), { host: "ts.example.com", port: 9987 });
});
it("rejects ambiguous raw IPv6 and invalid ports", () => {
assert.throws(() => parseTeamSpeakTarget("2001:db8::1"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:0"), InvalidTeamSpeakTargetError);
assert.throws(() => parseTeamSpeakTarget("example.com:65536"), InvalidTeamSpeakTargetError);
});
it("creates a stable case-insensitive cache key", () => {
assert.equal(teamSpeakTargetKey({ host: "TS.Example.COM", port: 9987 }), "ts.example.com:9987");
});
});
-28
View File
@@ -1,28 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { generateIdentity } from "@echosixhiya/teamspeak-client";
import { parseTeamSpeakTarget } from "../src/domain/teamspeak-target.js";
import { TSClient, toTSChatMessage } from "../src/server/ts-client.js";
import { silentLogger } from "./helpers/logger.js";
test("TSClient keeps the supplied identity material for reconnects", () => {
const identity = generateIdentity(8);
const client = new TSClient({ target: parseTeamSpeakTarget("example.com:9987"), nickname: "Guest", identity }, silentLogger);
assert.equal(client.getIdentityString(), identity.toString());
});
test("TSClient preserves the TeamSpeak target id for private chat events", () => {
const message = toTSChatMessage({
invokerName: "Alice",
invokerUID: "uid-alice",
message: "hello",
invokerGroups: [],
targetMode: 1,
targetID: 42n,
invokerID: 7,
});
assert.equal(message.targetId, 42n);
assert.equal(message.invokerId, 7);
assert.equal(message.invokerUid, "uid-alice");
});
-108
View File
@@ -1,108 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseClientCommand } from "../src/server/voice-protocol.js";
test("voice protocol accepts the versioned command payload", () => {
const command = parseClientCommand(JSON.stringify({
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
}));
assert.deepEqual(command, {
type: "switchChannel",
requestId: "switch-1",
payload: { channelId: "42" },
});
});
test("voice protocol rejects malformed and unsupported commands", () => {
assert.deepEqual(parseClientCommand("not-json"), {
error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" },
});
assert.equal("error" in parseClientCommand(JSON.stringify({ type: "unknown", payload: {} })), true);
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage" })), {
error: { code: "INVALID_PAYLOAD", message: "消息参数无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendTextMessage", payload: { message: "x".repeat(501) } })), {
error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" },
});
});
test("voice protocol keeps chat scopes and status actions explicit", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "sendPrivateMessage", requestId: "pm-1", payload: { clientId: 7, message: "hello" } })), {
type: "sendPrivateMessage",
requestId: "pm-1",
payload: { clientId: 7, message: "hello" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: true, message: "back soon" } })), {
type: "setAway",
payload: { away: true, message: "back soon" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "secret" } })), {
type: "switchChannel",
payload: { channelId: "42", password: "secret" },
});
});
test("voice protocol rejects unsafe client and away payloads", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "poke", payload: { clientId: 0, message: "hi" } })), {
error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAway", payload: { away: "yes" } })), {
error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "switchChannel", payload: { channelId: "42", password: "x".repeat(513) } })), {
error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" },
});
});
test("voice protocol validates whisper targets and its independent push state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", requestId: "whisper-1", payload: { targetIds: [7, 9] } })), {
type: "setWhisperTargets",
requestId: "whisper-1",
payload: { targetIds: [7, 9] },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: true } })), {
type: "setWhisperActive",
payload: { active: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperTargets", payload: { targetIds: [7, 7] } })), {
error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setWhisperActive", payload: { active: "yes" } })), {
error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" },
});
});
test("voice protocol accepts and validates the microphone mute state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: true } })), {
type: "setMicrophoneMuted",
payload: { muted: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMicrophoneMuted", payload: { muted: "yes" } })), {
error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" },
});
});
test("voice protocol accepts and validates the accompaniment state", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: true } })), {
type: "setAccompanimentActive",
payload: { active: true },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: "yes" } })), {
error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" },
});
});
test("voice protocol accepts and validates per-member volume", () => {
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 1.5 } })), {
type: "setMemberVolume",
payload: { clientId: 7, volume: 1.5 },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 4.1 } })), {
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
});
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: Number.NaN } })), {
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
});
});