mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
merge: retain dev security fixes for the 0.3.0 release
This commit is contained in:
commit
047a40ac4b
31 files changed
+449
-84
No files matched your search
+17
-11
@@ -46,6 +46,7 @@ export interface AdminRouterOptions {
|
||||
pluginStore?: PluginStore;
|
||||
pluginRuntime?: PluginRuntime;
|
||||
startedAt: number;
|
||||
clientIp?: (request: Request) => string;
|
||||
}
|
||||
|
||||
export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
@@ -92,25 +93,29 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
const peer = request.socket.remoteAddress ?? "unknown";
|
||||
const retryAfterMs = limiter.retryAfterMs(peer);
|
||||
if (retryAfterMs > 0) {
|
||||
response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
|
||||
return;
|
||||
}
|
||||
const peer = options.clientIp?.(request) ?? request.socket.remoteAddress ?? "unknown";
|
||||
const body = asRecord(request.body);
|
||||
const username = readString(body, "username", 64).trim();
|
||||
const password = readOptionalString(body, "password", 1024);
|
||||
if (!await options.service.verifyPassword(username, password)) {
|
||||
const delayMs = limiter.recordFailure(peer);
|
||||
const reservation = limiter.reserve(peer);
|
||||
if (!reservation.allowed) {
|
||||
response.setHeader("Retry-After", String(Math.ceil(reservation.retryAfterMs / 1000)));
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs: reservation.retryAfterMs });
|
||||
return;
|
||||
}
|
||||
const revision = options.service.credentialRevision;
|
||||
let verified: boolean;
|
||||
try { verified = await options.service.verifyPassword(username, password); }
|
||||
catch (error) { reservation.finish("cancelled"); sendAdminError(response, error); return; }
|
||||
if (!verified || revision !== options.service.credentialRevision) {
|
||||
const delayMs = reservation.finish("failure");
|
||||
await waitFor(delayMs);
|
||||
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
|
||||
logger.warn("Administrator login failed");
|
||||
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
|
||||
return;
|
||||
}
|
||||
limiter.recordSuccess(peer);
|
||||
reservation.finish("success");
|
||||
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
|
||||
const session = options.sessions.create(response, isSecureRequest(request));
|
||||
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
|
||||
@@ -120,6 +125,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
await options.service.changePassword(readString(body, "newPassword", 1024));
|
||||
options.sessions.revokeOthers(request);
|
||||
response.json({ ok: true, mustChangePassword: false });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
@@ -803,7 +809,7 @@ function logLevelName(level: unknown): string {
|
||||
|
||||
function sendAdminError(response: Response, error: unknown): void {
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
response.status(error.code === "AUTH_REQUIRED" ? 401 : 400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
|
||||
|
||||
@@ -45,6 +45,8 @@ type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
private readonly tsAdmin: TsAdminService;
|
||||
private revision = 0;
|
||||
get credentialRevision(): number { return this.revision; }
|
||||
constructor(
|
||||
readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
@@ -74,8 +76,9 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async verifyPassword(username: string, password: string): Promise<boolean> {
|
||||
const revision = this.revision;
|
||||
const credential = this.database.getAdminCredential();
|
||||
return credential?.username === username && await verifyAdminPassword(password, credential);
|
||||
return credential?.username === username && await verifyAdminPassword(password, credential) && revision === this.revision;
|
||||
}
|
||||
|
||||
isPasswordChangeRequired(): boolean {
|
||||
@@ -83,12 +86,15 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async changePassword(password: string): Promise<void> {
|
||||
const revision = this.revision;
|
||||
const credential = this.database.getAdminCredential();
|
||||
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
|
||||
const passwordError = validateAdminPassword(password);
|
||||
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
|
||||
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
|
||||
if (revision !== this.revision) throw new AdminInputError("AUTH_REQUIRED", "Administrator credentials changed during the request");
|
||||
this.database.updateAdminCredential(replacement);
|
||||
this.revision++;
|
||||
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,13 @@ export class AdminSessionStore {
|
||||
clear(): void {
|
||||
this.sessions.clear();
|
||||
}
|
||||
|
||||
/** A credential change retains only the authenticated session that performed it. */
|
||||
revokeOthers(request: Request): void {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
const keep = token ? hashToken(token) : null;
|
||||
for (const key of this.sessions.keys()) if (key !== keep) this.sessions.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function isSecureRequest(request: Request): boolean {
|
||||
|
||||
@@ -1,51 +1,54 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
const WINDOW_MS = 5 * 60 * 1000;
|
||||
const MAX_FAILURES = 5;
|
||||
|
||||
interface LoginAttempt {
|
||||
failures: number;
|
||||
pending: number;
|
||||
firstFailureAt: number;
|
||||
}
|
||||
|
||||
type Reservation = { allowed: false; retryAfterMs: number }
|
||||
| { allowed: true; finish(result: "success" | "failure" | "cancelled"): number };
|
||||
|
||||
export class AdminLoginRateLimiter {
|
||||
private readonly attempts = new Map<string, LoginAttempt>();
|
||||
private pending = 0;
|
||||
|
||||
constructor(private readonly maxTrackedPeers = 1024) {}
|
||||
constructor(private readonly maxTrackedPeers = 1024, private readonly maxConcurrentChecks = 8) {}
|
||||
|
||||
retryAfterMs(peer: string, now = Date.now()): number {
|
||||
const attempt = this.attempts.get(peer);
|
||||
if (!attempt) return 0;
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) {
|
||||
this.attempts.delete(peer);
|
||||
return 0;
|
||||
}
|
||||
if (attempt.failures < MAX_FAILURES) return 0;
|
||||
return WINDOW_MS - (now - attempt.firstFailureAt);
|
||||
}
|
||||
|
||||
recordFailure(peer: string, now = Date.now()): number {
|
||||
/** Reserve before hashing; pending checks count against capacity, successes are not failures. */
|
||||
reserve(peer: string, now = performance.now()): Reservation {
|
||||
this.pruneExpired(now);
|
||||
const current = this.attempts.get(peer);
|
||||
if (!current) {
|
||||
this.pruneExpired(now);
|
||||
while (this.attempts.size >= this.maxTrackedPeers) {
|
||||
const oldestPeer = this.attempts.keys().next().value;
|
||||
if (!oldestPeer) break;
|
||||
this.attempts.delete(oldestPeer);
|
||||
}
|
||||
if (current && current.failures + current.pending >= MAX_FAILURES) {
|
||||
return { allowed: false, retryAfterMs: Math.max(1000, WINDOW_MS - (now - current.firstFailureAt)) };
|
||||
}
|
||||
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
|
||||
? { failures: 1, firstFailureAt: now }
|
||||
: { ...current, failures: current.failures + 1 };
|
||||
if (this.pending >= this.maxConcurrentChecks || (!current && this.attempts.size >= this.maxTrackedPeers)) {
|
||||
// Never evict another visitor's lockout or pending check to admit a new address.
|
||||
return { allowed: false, retryAfterMs: 1000 };
|
||||
}
|
||||
const attempt = current ?? { failures: 0, pending: 0, firstFailureAt: now };
|
||||
this.attempts.set(peer, attempt);
|
||||
return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
|
||||
}
|
||||
|
||||
recordSuccess(peer: string): void {
|
||||
this.attempts.delete(peer);
|
||||
attempt.pending++;
|
||||
this.pending++;
|
||||
let finished = false;
|
||||
return { allowed: true, finish: result => {
|
||||
if (finished) return 0;
|
||||
finished = true;
|
||||
this.pending--;
|
||||
attempt.pending--;
|
||||
if (result === "success") attempt.failures = 0;
|
||||
else if (result === "failure") attempt.failures++;
|
||||
if (!attempt.failures && !attempt.pending) this.attempts.delete(peer);
|
||||
return result === "failure" ? Math.min(2000, 250 * 2 ** Math.min(3, attempt.failures - 1)) : 0;
|
||||
} };
|
||||
}
|
||||
|
||||
private pruneExpired(now: number): void {
|
||||
for (const [peer, attempt] of this.attempts) {
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
if (!attempt.pending && now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createServer } from "node:net";
|
||||
import express from "express";
|
||||
import { AdminLoginRateLimiter } from "./login-rate-limit.js";
|
||||
import { AdminService } from "./admin-service.js";
|
||||
import { AdminSessionStore } from "./admin-session.js";
|
||||
import { createAdminRouter } from "./admin-router.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { createWebServer } from "../server/server.js";
|
||||
import { JoinTicketStore } from "../server/join-ticket.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(yes => { resolve = yes; }); return { promise, resolve }; };
|
||||
|
||||
test("login reservations bound pending work, count only failures and preserve other lockouts", () => {
|
||||
const limiter = new AdminLoginRateLimiter(2, 8);
|
||||
const reserved = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(reserved.every(value => value.allowed));
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
for (const item of reserved) if (item.allowed) item.finish("failure");
|
||||
const b = limiter.reserve("b", 0); assert.ok(b.allowed); b.finish("failure");
|
||||
assert.equal(limiter.reserve("c", 0).allowed, false, "new IPs cannot evict an existing lockout");
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
assert.equal(limiter.reserve("a", 300_001).allowed, true);
|
||||
const successes = new AdminLoginRateLimiter(1);
|
||||
for (let i = 0; i < 20; i++) { const item = successes.reserve("a", 0); assert.ok(item.allowed); item.finish("success"); }
|
||||
const cap = new AdminLoginRateLimiter(10, 2);
|
||||
const first = cap.reserve("a", 0), second = cap.reserve("b", 0);
|
||||
assert.ok(first.allowed && second.allowed);
|
||||
assert.equal(cap.reserve("c", 0).allowed, false, "different IPs share the hash concurrency ceiling");
|
||||
first.finish("cancelled"); first.finish("cancelled");
|
||||
const third = cap.reserve("c", 0); assert.ok(third.allowed);
|
||||
assert.equal(cap.reserve("d", 0).allowed, false, "finishing twice cannot release another request's slot");
|
||||
second.finish("success"); third.finish("success");
|
||||
});
|
||||
|
||||
test("a pending check cannot expire out of the reservation count", () => {
|
||||
const limiter = new AdminLoginRateLimiter(1);
|
||||
const checks = Array.from({ length: 5 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(checks.every(item => item.allowed));
|
||||
assert.equal(limiter.reserve("a", 400_000).allowed, false);
|
||||
for (const item of checks) if (item.allowed) item.finish("cancelled");
|
||||
assert.equal(limiter.reserve("b", 400_000).allowed, true);
|
||||
});
|
||||
|
||||
test("a successful concurrent login cannot erase another request's reservation", () => {
|
||||
const limiter = new AdminLoginRateLimiter(1);
|
||||
const slow = limiter.reserve("a", 0), success = limiter.reserve("a", 0);
|
||||
assert.ok(slow.allowed && success.allowed);
|
||||
success.finish("success");
|
||||
const additional = Array.from({ length: 4 }, () => limiter.reserve("a", 0));
|
||||
assert.ok(additional.every(item => item.allowed));
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
slow.finish("failure");
|
||||
assert.equal(limiter.reserve("a", 0).allowed, false);
|
||||
});
|
||||
|
||||
async function availablePort() {
|
||||
const server = createServer();
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
return address.port;
|
||||
}
|
||||
|
||||
for (const trusted of [true, false]) test(`HTTP login and join limits ${trusted ? "separate trusted proxy clients" : "ignore spoofed headers from an untrusted peer"}`, async t => {
|
||||
let checks = 0;
|
||||
const gate = deferred();
|
||||
const service = { credentialRevision: 0, isInitialized: () => true,
|
||||
verifyPassword: async () => { checks++; await gate.promise; return false; },
|
||||
database: { addAudit() {} },
|
||||
getConnectionPolicy: () => ({ accessMode: "fixed", defaultTarget: "8.8.8.8#9987", serverPassword: "" }),
|
||||
isPasswordChangeRequired: () => false,
|
||||
} as unknown as AdminService;
|
||||
const port = await availablePort(), origin = `http://127.0.0.1:${port}`;
|
||||
const gateway = createWebServer({ port, logger, adminService: service, voiceBridgeOptions: {
|
||||
joinTickets: new JoinTicketStore(), trustedProxies: trusted ? ["127.0.0.1", "::1"] : ["192.0.2.1"],
|
||||
} });
|
||||
await gateway.start();
|
||||
t.after(async () => { gate.resolve(); await gateway.stop(); });
|
||||
const post = (route: string, client: string, body: unknown) => fetch(origin + route, {
|
||||
method: "POST", headers: { origin, "content-type": "application/json", "x-forwarded-for": client }, body: JSON.stringify(body),
|
||||
});
|
||||
const a = "203.0.113.9", b = "198.51.100.4";
|
||||
const logins = Array.from({ length: 12 }, () => post("/api/admin/login", a, { username: "admin", password: "bad" }));
|
||||
const results = Promise.all(logins);
|
||||
gate.resolve();
|
||||
const responses = await results;
|
||||
const statuses = responses.map(r => r.status);
|
||||
assert.equal(checks, 5);
|
||||
assert.equal(statuses.filter(s => s === 401).length, 5);
|
||||
assert.equal(statuses.filter(s => s === 429).length, 7);
|
||||
assert.ok(Number(responses.find(r => r.status === 429)!.headers.get("retry-after")) > 0);
|
||||
assert.equal((await post("/api/admin/login", b, { username: "admin", password: "bad" })).status, trusted ? 401 : 429);
|
||||
for (let i = 0; i < 30; i++) assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 201);
|
||||
assert.equal((await post("/api/join-ticket", a, { nickname: "Test" })).status, 429);
|
||||
assert.equal((await post("/api/join-ticket", b, { nickname: "Test" })).status, trusted ? 201 : 429);
|
||||
});
|
||||
|
||||
test("password-verifier exceptions release reservations without leaking their details", async t => {
|
||||
const app = express(); app.use(express.json());
|
||||
const service = { credentialRevision: 0, isInitialized: () => true,
|
||||
verifyPassword: async () => { throw new Error("secret verifier failure detail"); },
|
||||
} as unknown as AdminService;
|
||||
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise<void>(resolve => server.once("listening", resolve));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const response = await fetch(origin + "/api/admin/login", { method: "POST", headers: { origin, "content-type": "application/json" },
|
||||
body: JSON.stringify({ username: "admin", password: "irrelevant" }) });
|
||||
assert.equal(response.status, 500);
|
||||
assert.deepEqual(await response.json(), { ok: false, code: "INTERNAL_ERROR" });
|
||||
}
|
||||
});
|
||||
|
||||
async function adminFixture(t: TestContext) {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "webspeak-auth-race-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"));
|
||||
await service.initialize(); // Intentionally keep the default password for the bootstrap race.
|
||||
const app = express(); app.use(express.json());
|
||||
app.use("/api/admin", createAdminRouter({ service, sessions: new AdminSessionStore(), logger,
|
||||
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now() }));
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise<void>(resolve => server.once("listening", resolve));
|
||||
const address = server.address(); assert.ok(address && typeof address !== "string");
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); database.close(); await rm(directory, { recursive: true }); });
|
||||
const post = (route: string, body: unknown, cookie = "", csrf = "") => fetch(origin + "/api/admin" + route, {
|
||||
method: "POST", headers: { origin, cookie, "content-type": "application/json", "x-csrf-token": csrf }, body: JSON.stringify(body),
|
||||
});
|
||||
const login = async (password: string) => {
|
||||
const response = await post("/login", { username: "admin", password });
|
||||
assert.equal(response.status, 200);
|
||||
const body = await response.json() as { csrfToken: string };
|
||||
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
|
||||
};
|
||||
const authenticated = async (cookie: string) => (await (await fetch(origin + "/api/admin/session", { headers: { cookie } })).json() as { authenticated: boolean }).authenticated;
|
||||
return { service, database, post, login, authenticated };
|
||||
}
|
||||
|
||||
test("password rotation revokes other default-password sessions and a login finishing after rotation", { timeout: 15_000 }, async t => {
|
||||
const f = await adminFixture(t);
|
||||
const current = await f.login("admin"), other = await f.login("admin");
|
||||
const verified = deferred(), release = deferred();
|
||||
const verify = f.service.verifyPassword.bind(f.service);
|
||||
t.mock.method(f.service, "verifyPassword", async (username: string, password: string) => {
|
||||
const result = await verify(username, password);
|
||||
if (password === "admin") { verified.resolve(); await release.promise; }
|
||||
return result;
|
||||
});
|
||||
const pending = f.post("/login", { username: "admin", password: "admin" });
|
||||
await verified.promise;
|
||||
try {
|
||||
const changed = await f.post("/change-password", { newPassword: "new-password-for-test" }, current.cookie, current.csrf);
|
||||
assert.equal(changed.status, 200);
|
||||
assert.equal(await f.authenticated(current.cookie), true);
|
||||
assert.equal(await f.authenticated(other.cookie), false);
|
||||
} finally { release.resolve(); }
|
||||
const stale = await pending;
|
||||
assert.equal(stale.status, 401);
|
||||
assert.equal(stale.headers.get("set-cookie"), null, "an old verification cannot mint a new session");
|
||||
await f.login("new-password-for-test");
|
||||
});
|
||||
|
||||
test("failed password updates keep other sessions and concurrent rotations cannot overwrite a winner", { timeout: 15_000 }, async t => {
|
||||
const f = await adminFixture(t);
|
||||
const current = await f.login("admin"), other = await f.login("admin");
|
||||
assert.equal((await f.post("/change-password", { newPassword: "short" }, current.cookie, current.csrf)).status, 400);
|
||||
assert.equal(await f.authenticated(other.cookie), true);
|
||||
const results = await Promise.all([
|
||||
f.post("/change-password", { newPassword: "first-possible-password" }, current.cookie, current.csrf),
|
||||
f.post("/change-password", { newPassword: "second-possible-password" }, other.cookie, other.csrf),
|
||||
]);
|
||||
assert.deepEqual(results.map(r => r.status).sort(), [200, 401]);
|
||||
const winner = results[0]!.status === 200 ? current : other;
|
||||
const loser = winner === current ? other : current;
|
||||
assert.equal(await f.authenticated(winner.cookie), true);
|
||||
assert.equal(await f.authenticated(loser.cookie), false);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
test("protocol identifiers and favorite addresses keep ASCII casing under a Turkish locale", () => {
|
||||
const child = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", `
|
||||
import assert from 'node:assert/strict';
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from './src/domain/teamspeak-target.ts';
|
||||
import { quickServerTargetsEqual, mergeQuickServers } from './web/src/services/quick-servers.ts';
|
||||
import { normalizeTeamSpeakError } from './src/errors.ts';
|
||||
// Windows ignores LANG for ICU's default locale; isolate the Turkish default in this child.
|
||||
const localeLower = String.prototype.toLocaleLowerCase;
|
||||
String.prototype.toLocaleLowerCase = function(...locales) {
|
||||
return localeLower.call(this, ...(locales.length ? locales : ['tr']));
|
||||
};
|
||||
assert.equal('I'.toLocaleLowerCase(), 'ı', 'the child must actually run under Turkish casing');
|
||||
const target = parseTeamSpeakTarget('VOICE.EXAMPLE.IO#9987');
|
||||
assert.equal(target.host, 'voice.example.io');
|
||||
assert.equal(teamSpeakTargetKey({host:'VOICE.EXAMPLE.IO',port:9987}), 'voice.example.io:9987');
|
||||
assert.equal(quickServerTargetsEqual('VOICE.EXAMPLE.IO:9987', 'voice.example.io#9987'), true);
|
||||
assert.equal(mergeQuickServers([{id:'a',label:'a',address:'VOICE.EXAMPLE.IO:9987'}],
|
||||
[{id:'b',address:'voice.example.io:9987',lastConnectedAt:1}]).length, 1);
|
||||
const upper=normalizeTeamSpeakError(new Error('INVALID IDENTITY'));
|
||||
const lower=normalizeTeamSpeakError(new Error('invalid identity'));
|
||||
assert.equal(upper.code, lower.code);
|
||||
`], { env: { ...process.env, LANG: "tr_TR.UTF-8", LC_ALL: "tr_TR.UTF-8" }, encoding: "utf8" });
|
||||
assert.equal(child.status, 0, child.stderr || child.stdout);
|
||||
});
|
||||
@@ -72,11 +72,11 @@ export function formatTeamSpeakTarget(target: TeamSpeakTarget): string {
|
||||
}
|
||||
|
||||
export function teamSpeakTargetKey(target: TeamSpeakTarget): string {
|
||||
return formatTeamSpeakTarget(target).toLocaleLowerCase();
|
||||
return formatTeamSpeakTarget(target).toLowerCase();
|
||||
}
|
||||
|
||||
function createTarget(hostValue: string, portValue: string | number): TeamSpeakTarget {
|
||||
const host = hostValue.trim().toLocaleLowerCase();
|
||||
const host = hostValue.trim().toLowerCase();
|
||||
if (!host || host.length > 255 || /[\s/\\?#@\[\]]/.test(host)) {
|
||||
throw new InvalidTeamSpeakTargetError("Invalid TeamSpeak server address");
|
||||
}
|
||||
|
||||
+3
-3
@@ -186,7 +186,7 @@ function createTeamSpeakError(code: WebSpeakErrorCode, cause: unknown, diagnosti
|
||||
*/
|
||||
export function teamSpeakServerErrorCode(id: unknown): WebSpeakErrorCode | null {
|
||||
if (id === undefined || id === null) return null;
|
||||
const text = String(id).trim().toLocaleLowerCase();
|
||||
const text = String(id).trim().toLowerCase();
|
||||
if (/^\d{1,6}$/.test(text)) return TEAMSPEAK_SERVER_ERROR_IDS[String(Number(text))] ?? null;
|
||||
const hexMatch = /^(?:0x)?([0-9a-f]{4,6})$/.exec(text);
|
||||
if (hexMatch) return TEAMSPEAK_SERVER_ERROR_IDS[String(parseInt(hexMatch[1], 16))] ?? null;
|
||||
@@ -199,7 +199,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
if (error instanceof WebSpeakError) return error;
|
||||
|
||||
const diagnostics = collectDiagnostics(error);
|
||||
const text = diagnosticText(error).toLocaleLowerCase();
|
||||
const text = diagnosticText(error).toLowerCase();
|
||||
|
||||
// 1) A TeamSpeak server error id names the exact reason, so it outranks every
|
||||
// keyword heuristic below. The inline scan keeps the `id=515` shape
|
||||
@@ -258,7 +258,7 @@ export function normalizeTeamSpeakError(error: unknown): WebSpeakError {
|
||||
|
||||
// 3) SDK handshake/crypto error classes carry no numeric id at all, so match
|
||||
// the class name before falling back to the message text.
|
||||
const errorName = (diagnostics.name ?? "").toLocaleLowerCase();
|
||||
const errorName = (diagnostics.name ?? "").toLowerCase();
|
||||
if (/eaxtagmismatch|fakesignaturemismatch|cryptoinit|invalididentity|license/.test(errorName)) {
|
||||
return createTeamSpeakError("protocol_negotiation_failed", error, diagnostics);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,25 @@ const resolved = (...addresses: string[]) => async () => addresses.map((address)
|
||||
family: address.includes(":") ? 6 : 4,
|
||||
}));
|
||||
|
||||
test("open targets classify equivalent IPv6 spellings and embedded IPv4 before DNS pinning", async () => {
|
||||
const blocked = ["0:0:0:0:0:0:0:1", "0::1", "0:1234::1", "0:0:0:0:0:0:0:0", "0:0:0:0:0:ffff:a00:1",
|
||||
"::ffff:7f00:1", "0::ffff:192.168.1.1", "0:0:0:0:0:0:7f00:1", "fe80::1%1",
|
||||
"64:ff9b::808:808", "64:ff9b:1:abcd::1", "2002:0808:0808::1", "2001:0:4136:e378::1",
|
||||
"0100:0000:0:0:ffff::1", "100:0:0:1::1", "2001:0db8::1", "3fff::1"];
|
||||
for (const host of blocked) {
|
||||
assert.equal(isRestrictedAddress(host), true, host);
|
||||
await assert.rejects(resolveSafeOpenTarget({ host, port: 9987 }), { name: "UnsafeTeamSpeakTargetError" });
|
||||
await assert.rejects(resolveSafeOpenTarget({ host: "voice.example.com", port: 9987 }, {
|
||||
resolveSrv: async () => [], lookup: resolved("8.8.8.8", host),
|
||||
}), { name: "UnsafeTeamSpeakTargetError" });
|
||||
}
|
||||
for (const host of ["0:0:0:0:0:ffff:808:808", "::ffff:1.1.1.1", "2001:4860:0000:0:0:0:0:8888",
|
||||
"64:ff9b:2::1", "100:0:1::1", "2001:db9::1", "2003::1"]) {
|
||||
assert.equal(isRestrictedAddress(host), false, host);
|
||||
assert.deepEqual(await resolveSafeOpenTarget({ host, port: 9987 }), { host, port: 9987 });
|
||||
}
|
||||
});
|
||||
|
||||
test("Mihomo fake-IP DNS answers remain connectable without allowing literal or mixed fake-IP targets", async () => {
|
||||
const target = { host: "ts.twilightly.top", port: 9987 };
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isIP } from "node:net";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { lookup, resolveSrv } from "node:dns/promises";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -108,25 +108,28 @@ export async function isSafeOpenTargetForPrefill(
|
||||
}
|
||||
}
|
||||
|
||||
const restrictedIpv6 = new BlockList();
|
||||
// Match address bits, not textual compression or the case/width of hex groups.
|
||||
for (const [network, prefix] of [
|
||||
["::", 16], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
|
||||
["100::", 64], ["100:0:0:1::", 64], ["2001::", 32], ["2002::", 16],
|
||||
["2001:db8::", 32], ["3fff::", 20], ["fc00::", 7], ["fe80::", 10],
|
||||
["fec0::", 10], ["ff00::", 8],
|
||||
] as const) restrictedIpv6.addSubnet(network, prefix, "ipv6");
|
||||
|
||||
export function isRestrictedAddress(address: string): boolean {
|
||||
// Scoped destinations refer to a gateway-local interface and are never public targets.
|
||||
if (address.includes("%")) return true;
|
||||
const version = isIP(address);
|
||||
if (version === 4) return isRestrictedIpv4(address);
|
||||
if (version !== 6) return true;
|
||||
|
||||
const normalized = address.toLocaleLowerCase();
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
const normalized = new SocketAddress({ address, family: "ipv6" }).address;
|
||||
if (normalized.startsWith("::ffff:")) {
|
||||
const mapped = normalized.slice("::ffff:".length);
|
||||
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
|
||||
}
|
||||
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
|
||||
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
|
||||
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
|
||||
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
|
||||
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
|
||||
if (normalized.startsWith("2001:db8:")) return true; // documentation range
|
||||
return false;
|
||||
return restrictedIpv6.check(normalized, "ipv6");
|
||||
}
|
||||
|
||||
function isMihomoFakeIpv4(address: string): boolean {
|
||||
|
||||
@@ -110,7 +110,7 @@ export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempt
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
const lower = text.toLowerCase();
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createServer as createHttpsServer } from "node:https";
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
|
||||
@@ -69,6 +69,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
|
||||
const adminSessions = new AdminSessionStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const trustedProxies = createTrustedProxies(options.voiceBridgeOptions.trustedProxies);
|
||||
const clientIp = (request: express.Request) => resolveClientIp(request, trustedProxies);
|
||||
const startedAt = Date.now();
|
||||
|
||||
const healthHandler: express.RequestHandler = (_request, response) => {
|
||||
@@ -169,7 +171,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
|
||||
if (!joinRateLimiter.allow(clientIp(request))) {
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
|
||||
return;
|
||||
}
|
||||
@@ -287,6 +289,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
clientIp,
|
||||
}));
|
||||
|
||||
// Serve static frontend
|
||||
|
||||
@@ -35,11 +35,45 @@ function fixture() {
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
}, encoder, () => state.now, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
|
||||
}
|
||||
|
||||
test("PCM flooding is bounded before encoding while real-time, jitter and recovery remain usable", t => {
|
||||
const realtime = fixture();
|
||||
for (let i = 0; i < 1_000; i++) { realtime.state.now = i * 20; realtime.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(realtime.encoded.length, 1_000);
|
||||
const flood = fixture();
|
||||
t.mock.method(flood.encoder, "encode", () => { flood.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 1_000; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.ok(flood.encoded.length <= 50);
|
||||
assert.equal(flood.audio.ingressDroppedFrames, 1_000 - flood.encoded.length);
|
||||
assert.equal(flood.warnings.filter(w => w.code === "AUDIO_RATE_EXCEEDED").length, 1);
|
||||
assert.equal(flood.notices.length, 0);
|
||||
flood.state.now = 10_000;
|
||||
const before = flood.forwarded.length;
|
||||
for (let i = 0; i < 50; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(flood.forwarded.length - before, 50, "one-second backlog after a stall is allowed");
|
||||
const recovered = flood.forwarded.length;
|
||||
for (let i = 1; i <= 100; i++) { flood.state.now = 10_000 + i * 20; flood.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(flood.forwarded.length - recovered, 100, "flood drops do not lock out subsequent real-time audio");
|
||||
});
|
||||
|
||||
test("PCM budget uses a separate monotonic clock and cannot refill twice after a clock rollback", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { f.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 50; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = -1_000;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = 0;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 50);
|
||||
f.state.now = 100;
|
||||
for (let i = 0; i < 20; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 56);
|
||||
});
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WebSocket } from "ws";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
@@ -12,6 +13,8 @@ const MAX_BUFFERED_BYTES = 4_096;
|
||||
// frame: the reply is roughly 100x the offending payload, and the browser only
|
||||
// ever shows the first one because it writes the same error string.
|
||||
const AUDIO_ISSUE_REPORT_MS = 5_000;
|
||||
const PCM_BURST_FRAMES = 50; // One second of buffered 20 ms capture after a stall.
|
||||
const PCM_FRAMES_PER_MS = 60 / 1_000; // 50 fps capture plus 20% scheduling headroom.
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
@@ -39,8 +42,11 @@ export class SessionAudioTransport {
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now,
|
||||
private readonly rateClock: () => number = performance.now.bind(performance)) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
}
|
||||
@@ -127,6 +133,19 @@ export class SessionAudioTransport {
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
}
|
||||
const now = this.rateClock();
|
||||
if (this.pcmRefilledAt !== null) {
|
||||
this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
|
||||
}
|
||||
this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
|
||||
if (this.pcmTokens < 1) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.pcmTokens--;
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
|
||||
@@ -99,7 +99,7 @@ export async function probeTeamSpeak(
|
||||
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
|
||||
if (error instanceof TeamSpeakProbeError) return error;
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
|
||||
@@ -595,9 +595,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
getChannelId(): bigint {
|
||||
if (!this.client) return 0n;
|
||||
const sdkClient = this.client as unknown as { channelID?: () => bigint };
|
||||
return sdkClient.channelID?.() ?? 0n;
|
||||
return this.client?.channelID() ?? 0n;
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
|
||||
@@ -238,6 +238,14 @@ function ipRequest(remoteAddress: string | undefined, headers: Record<string, st
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
test("equivalent forwarded IPv6 spellings share one canonical client and rate-limit key", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
const resolve = (value: string) => resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": value }), trusted);
|
||||
assert.equal(resolve("2001:0DB9:0000:0000:0000:0000:0000:0001"), resolve("2001:db9::1"));
|
||||
assert.equal(resolve("0:0:0:0:0:ffff:cb00:7109"), "203.0.113.9");
|
||||
assert.equal(resolve("::ffff:203.0.113.9"), "203.0.113.9");
|
||||
});
|
||||
|
||||
test("a direct client cannot choose the address recorded for it", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7");
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID, randomBytes } from "node:crypto";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
@@ -1005,6 +1005,9 @@ function normalizeClientIp(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
let trimmed = value.trim();
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) trimmed = trimmed.slice(1, -1);
|
||||
const family = isIP(trimmed);
|
||||
if (!family) return undefined;
|
||||
if (family === 6) trimmed = new SocketAddress({ address: trimmed, family: "ipv6" }).address;
|
||||
if (trimmed.toLowerCase().startsWith("::ffff:")) {
|
||||
const mapped = trimmed.slice("::ffff:".length);
|
||||
if (isIP(mapped) === 4) trimmed = mapped;
|
||||
|
||||
@@ -172,7 +172,7 @@ export async function handleCommand(
|
||||
|
||||
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const normalized = text.toLocaleLowerCase();
|
||||
const normalized = text.toLowerCase();
|
||||
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
|
||||
// is consulted before the keyword rules: 781 (channel password), 2568
|
||||
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
|
||||
|
||||
Reference in new issue
Block a user