mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
M001: add secure admin foundation
This commit is contained in:
1 parent
960be106bb
commit
31f320d4c1
32 files changed
+2518
-679
No files matched your search
@@ -0,0 +1,250 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
sessions: AdminSessionStore;
|
||||
logger: Logger;
|
||||
getActiveSessions(): number;
|
||||
getPeakSessions(): number;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
const router = Router();
|
||||
const limiter = new AdminLoginRateLimiter();
|
||||
const logger = options.logger.child({ component: "admin-api" });
|
||||
|
||||
router.use((_request, response, next) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
|
||||
router.get("/status", (_request, response) => {
|
||||
response.json({ initialized: options.service.isInitialized() });
|
||||
});
|
||||
|
||||
router.get("/session", (request, response) => {
|
||||
const session = options.sessions.get(request);
|
||||
response.json({
|
||||
initialized: options.service.isInitialized(),
|
||||
authenticated: Boolean(session),
|
||||
...(session ? { csrfToken: session.csrfToken, expiresAt: session.expiresAt } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
router.post("/setup/test", requireSameOrigin, async (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
if (!options.service.verifyBootstrap(readString(body, "bootstrapCode", 128))) {
|
||||
response.status(403).json({ ok: false, code: "INVALID_BOOTSTRAP" });
|
||||
return;
|
||||
}
|
||||
const action = readPasswordAction(body.passwordAction);
|
||||
const password = action === "remove"
|
||||
? ""
|
||||
: action === "replace"
|
||||
? readOptionalString(body, "serverPassword", 512)
|
||||
: options.service.getConnectionPolicy().serverPassword;
|
||||
await runProbe(options.service, response, readString(body, "target", 300), password, false);
|
||||
});
|
||||
|
||||
router.post("/setup/defaults", requireSameOrigin, (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
if (!options.service.verifyBootstrap(readString(body, "bootstrapCode", 128))) {
|
||||
response.status(403).json({ ok: false, code: "INVALID_BOOTSTRAP" });
|
||||
return;
|
||||
}
|
||||
response.json(options.service.getSetupDefaults());
|
||||
});
|
||||
|
||||
router.post("/setup", requireSameOrigin, async (request, response) => {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
await options.service.setup({
|
||||
bootstrapCode: readString(body, "bootstrapCode", 128),
|
||||
adminPassword: readString(body, "adminPassword", 1024),
|
||||
...readSettingsInput(body),
|
||||
});
|
||||
const session = options.sessions.create(response, isSecureRequest(request));
|
||||
response.status(201).json({ ok: true, csrfToken: session.csrfToken });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/login", requireSameOrigin, async (request, response) => {
|
||||
if (!options.service.isInitialized()) {
|
||||
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 body = asRecord(request.body);
|
||||
const password = readOptionalString(body, "password", 1024);
|
||||
if (!await options.service.verifyPassword(password)) {
|
||||
const delayMs = limiter.recordFailure(peer);
|
||||
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);
|
||||
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 });
|
||||
});
|
||||
|
||||
router.use(requireAdmin(options.sessions));
|
||||
|
||||
router.get("/overview", (_request, response) => {
|
||||
response.json(options.service.getOverview(
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
));
|
||||
});
|
||||
|
||||
router.get("/server", (_request, response) => {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
|
||||
response.json({ ok: true, settings: options.service.getAdminSettings() });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/server/test", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
const action = readPasswordAction(body.passwordAction);
|
||||
const password = action === "remove"
|
||||
? ""
|
||||
: typeof body.serverPassword === "string"
|
||||
? body.serverPassword.slice(0, 512)
|
||||
: options.service.getConnectionPolicy().serverPassword;
|
||||
await runProbe(options.service, response, readString(body, "target", 300), password, true);
|
||||
});
|
||||
|
||||
router.post("/legacy-import/dismiss", requireSameOrigin, requireCsrf(options.sessions), (_request, response) => {
|
||||
options.service.dismissLegacyImportNotice();
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
router.post("/logout", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
options.sessions.destroy(request, response, isSecureRequest(request));
|
||||
options.service.database.addAudit("ADMIN_LOGOUT");
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
router.use((error: unknown, _request: Request, response: Response, _next: NextFunction) => {
|
||||
sendAdminError(response, error);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function requireAdmin(sessions: AdminSessionStore) {
|
||||
return (request: Request, response: Response, next: NextFunction): void => {
|
||||
if (!sessions.get(request)) {
|
||||
response.status(401).json({ ok: false, code: "AUTH_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function requireCsrf(sessions: AdminSessionStore) {
|
||||
return (request: Request, response: Response, next: NextFunction): void => {
|
||||
const session = sessions.get(request);
|
||||
const csrf = request.header("x-csrf-token");
|
||||
if (!session || !csrf || csrf !== session.csrfToken) {
|
||||
response.status(403).json({ ok: false, code: "CSRF_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function requireSameOrigin(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/json")) {
|
||||
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
|
||||
} catch {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
service: AdminService,
|
||||
response: Response,
|
||||
target: string,
|
||||
password: string,
|
||||
persistResult: boolean,
|
||||
): Promise<void> {
|
||||
try {
|
||||
response.json(await service.testConnection(target, password, persistResult));
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof TeamSpeakProbeError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
}
|
||||
|
||||
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
return {
|
||||
target: readString(body, "target", 300),
|
||||
serverPassword: typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : undefined,
|
||||
passwordAction: readPasswordAction(body.passwordAction),
|
||||
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
};
|
||||
}
|
||||
|
||||
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new AdminInputError("INVALID_REQUEST", "Request body is invalid");
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
if (typeof body[key] !== "string" || body[key].length > max) throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
|
||||
}
|
||||
|
||||
function sendAdminError(response: Response, error: unknown): void {
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { loadConfig } from "../config.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { type AccessMode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { BootstrapManager } from "../security/bootstrap.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
serverPassword?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
}
|
||||
|
||||
export interface SetupInput extends AdminSettingsInput {
|
||||
bootstrapCode: string;
|
||||
adminPassword: string;
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
constructor(
|
||||
readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
private readonly bootstrap: BootstrapManager,
|
||||
private readonly logger: Logger,
|
||||
private readonly legacyConfigPath: string,
|
||||
private readonly probe: ProbeFunction = probeTeamSpeak,
|
||||
) {}
|
||||
|
||||
initialize(): void {
|
||||
this.importLegacyConfigOnce();
|
||||
if (!this.database.hasAdmin()) {
|
||||
const code = this.bootstrap.ensure();
|
||||
this.logger.warn(`WebSpeak is not initialized. Open /admin/setup and enter bootstrap code: ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.database.hasAdmin();
|
||||
}
|
||||
|
||||
verifyBootstrap(code: string): boolean {
|
||||
return !this.isInitialized() && this.bootstrap.verify(code);
|
||||
}
|
||||
|
||||
async setup(input: SetupInput): Promise<void> {
|
||||
if (this.isInitialized()) throw new AdminInputError("ALREADY_INITIALIZED", "WebSpeak is already initialized");
|
||||
if (!this.bootstrap.verify(input.bootstrapCode)) {
|
||||
throw new AdminInputError("INVALID_BOOTSTRAP", "Bootstrap code is invalid");
|
||||
}
|
||||
const passwordError = validateAdminPassword(input.adminPassword);
|
||||
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
|
||||
const credential = await hashAdminPassword(input.adminPassword);
|
||||
const settings = this.normalizeSettings(input, this.database.getSettings());
|
||||
this.database.initializeAdmin(credential, settings);
|
||||
this.bootstrap.consume();
|
||||
this.logger.info("WebSpeak administrator initialized");
|
||||
}
|
||||
|
||||
async verifyPassword(password: string): Promise<boolean> {
|
||||
const credential = this.database.getAdminCredential();
|
||||
return credential ? verifyAdminPassword(password, credential) : false;
|
||||
}
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
accessMode: settings.accessMode,
|
||||
...(settings.accessMode === "open" ? {
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
getSetupDefaults(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
hasPassword: Boolean(settings.tsPasswordEncrypted),
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
legacyConfigImported: this.database.getMeta("legacy_config_imported") === "1",
|
||||
};
|
||||
}
|
||||
|
||||
getAdminSettings(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
hasPassword: Boolean(settings.tsPasswordEncrypted),
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
detectedProtocol: settings.detectedProtocol,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const settings = this.normalizeSettings(input, current);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
|
||||
this.database.updateSettings(settings);
|
||||
if (targetChanged) this.database.clearConnectionTest();
|
||||
}
|
||||
|
||||
getConnectionPolicy(): ConnectionPolicy {
|
||||
const settings = this.database.getSettings();
|
||||
let serverPassword = "";
|
||||
try {
|
||||
serverPassword = decryptSecret(settings.tsPasswordEncrypted, this.masterSecret);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TeamSpeak password could not be decrypted");
|
||||
}
|
||||
return {
|
||||
defaultTarget: { host: settings.tsHost, port: settings.tsPort },
|
||||
serverPassword,
|
||||
accessMode: settings.accessMode,
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<TeamSpeakProbeResult> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
const result = await this.probe(target, password, this.logger);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
|
||||
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
|
||||
}
|
||||
return result;
|
||||
} catch (error: unknown) {
|
||||
const probeError = error instanceof TeamSpeakProbeError
|
||||
? error
|
||||
: new TeamSpeakProbeError("INTERNAL_ERROR", "Connection test failed", error);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: null, error: probeError.code });
|
||||
this.database.addAudit("CONNECTION_TEST_FAILED", { code: probeError.code });
|
||||
}
|
||||
throw probeError;
|
||||
}
|
||||
}
|
||||
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
gateway: {
|
||||
status: "running",
|
||||
version: "0.1.0",
|
||||
uptimeSeconds: Math.max(0, Math.floor((Date.now() - startedAt) / 1000)),
|
||||
},
|
||||
teamSpeak: {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
|
||||
protocol: settings.detectedProtocol,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
latencyMs: settings.lastTestLatencyMs,
|
||||
lastError: settings.lastTestError,
|
||||
},
|
||||
sessions: { active: activeSessions, peak: peakSessions, limit: 100 },
|
||||
recentEvents: this.database.recentAudit(),
|
||||
legacyConfigImported: this.database.getMeta("legacy_import_notice_pending") === "1",
|
||||
};
|
||||
}
|
||||
|
||||
dismissLegacyImportNotice(): void {
|
||||
this.database.setMeta("legacy_import_notice_pending", "0");
|
||||
}
|
||||
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(input.target);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
|
||||
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
|
||||
let encryptedPassword = current.tsPasswordEncrypted;
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
if (action === "remove") encryptedPassword = null;
|
||||
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
};
|
||||
}
|
||||
|
||||
private importLegacyConfigOnce(): void {
|
||||
if (this.database.getMeta("legacy_config_checked") === "1") return;
|
||||
if (existsSync(this.legacyConfigPath)) {
|
||||
const legacy = loadConfig(this.legacyConfigPath);
|
||||
const current = this.database.getSettings();
|
||||
this.database.updateSettings({
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
}, "LEGACY_CONFIG_IMPORTED");
|
||||
this.database.setMeta("legacy_config_imported", "1");
|
||||
this.database.setMeta("legacy_import_notice_pending", "1");
|
||||
this.logger.info("Legacy config imported; WebSpeak settings are now managed from /admin");
|
||||
}
|
||||
this.database.setMeta("legacy_config_checked", "1");
|
||||
}
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "AdminInputError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import type { Request, Response } from "express";
|
||||
import type { TLSSocket } from "node:tls";
|
||||
|
||||
const COOKIE_NAME = "webspeak_admin";
|
||||
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
|
||||
|
||||
interface AdminSession {
|
||||
csrfToken: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export class AdminSessionStore {
|
||||
private readonly sessions = new Map<string, AdminSession>();
|
||||
|
||||
create(response: Response, secure: boolean, now = Date.now()): { csrfToken: string; expiresAt: number } {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const csrfToken = randomBytes(24).toString("base64url");
|
||||
const expiresAt = now + SESSION_TTL_MS;
|
||||
this.sessions.set(hashToken(token), { csrfToken, expiresAt });
|
||||
response.cookie(COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure,
|
||||
path: "/",
|
||||
maxAge: SESSION_TTL_MS,
|
||||
});
|
||||
return { csrfToken, expiresAt };
|
||||
}
|
||||
|
||||
get(request: Request, now = Date.now()): AdminSession | null {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
if (!token) return null;
|
||||
const key = hashToken(token);
|
||||
const session = this.sessions.get(key);
|
||||
if (!session) return null;
|
||||
if (session.expiresAt <= now) {
|
||||
this.sessions.delete(key);
|
||||
return null;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
destroy(request: Request, response: Response, secure: boolean): void {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
if (token) this.sessions.delete(hashToken(token));
|
||||
response.clearCookie(COOKIE_NAME, { httpOnly: true, sameSite: "strict", secure, path: "/" });
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.sessions.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function isSecureRequest(request: Request): boolean {
|
||||
return (request.socket as TLSSocket).encrypted === true;
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("base64url");
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(";")) {
|
||||
const separator = part.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
if (part.slice(0, separator).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(separator + 1).trim());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
const WINDOW_MS = 5 * 60 * 1000;
|
||||
const MAX_FAILURES = 5;
|
||||
|
||||
interface LoginAttempt {
|
||||
failures: number;
|
||||
firstFailureAt: number;
|
||||
}
|
||||
|
||||
export class AdminLoginRateLimiter {
|
||||
private readonly attempts = new Map<string, LoginAttempt>();
|
||||
|
||||
constructor(private readonly maxTrackedPeers = 1024) {}
|
||||
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
|
||||
? { failures: 1, firstFailureAt: now }
|
||||
: { ...current, failures: current.failures + 1 };
|
||||
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);
|
||||
}
|
||||
|
||||
private pruneExpired(now: number): void {
|
||||
for (const [peer, attempt] of this.attempts) {
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function waitFor(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
+20
-8
@@ -1,11 +1,14 @@
|
||||
import path from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadConfig, saveConfig } from "./config.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { createWebServer } from "./server/server.js";
|
||||
import { APP_PORT } from "./constants.js";
|
||||
import { parseTeamSpeakTargetParts } from "./domain/teamspeak-target.js";
|
||||
import { WebSpeakDatabase } from "./persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "./security/master-secret.js";
|
||||
import { BootstrapManager } from "./security/bootstrap.js";
|
||||
import { AdminService } from "./admin/admin-service.js";
|
||||
import { JoinTicketStore } from "./server/join-ticket.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT_DIR = path.resolve(__dirname, "..");
|
||||
@@ -16,12 +19,20 @@ const LOG_DIR = path.join(DATA_DIR, "logs");
|
||||
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig(CONFIG_PATH);
|
||||
saveConfig(CONFIG_PATH, config);
|
||||
|
||||
const logger = createLogger(LOG_DIR);
|
||||
const database = new WebSpeakDatabase(path.join(DATA_DIR, "webspeak.db"));
|
||||
const masterSecret = loadOrCreateMasterSecret(path.join(DATA_DIR, "master.key"));
|
||||
const adminService = new AdminService(
|
||||
database,
|
||||
masterSecret,
|
||||
new BootstrapManager(path.join(DATA_DIR, "bootstrap")),
|
||||
logger,
|
||||
CONFIG_PATH,
|
||||
);
|
||||
adminService.initialize();
|
||||
const joinTickets = new JoinTicketStore();
|
||||
|
||||
logger.info({ config }, "Starting WebSpeak server");
|
||||
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
|
||||
|
||||
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
|
||||
|
||||
@@ -30,9 +41,9 @@ async function main() {
|
||||
staticDir: STATIC_DIR,
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
voiceBridgeOptions: {
|
||||
defaultTarget: parseTeamSpeakTargetParts(config.tsHost, config.tsPort),
|
||||
tsServerPassword: config.tsServerPassword,
|
||||
joinTickets,
|
||||
},
|
||||
adminService,
|
||||
logger,
|
||||
});
|
||||
|
||||
@@ -42,6 +53,7 @@ async function main() {
|
||||
const shutdown = async (signal: string) => {
|
||||
logger.info({ signal }, "Shutting down");
|
||||
await webServer.stop();
|
||||
database.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 1;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
detectedProtocol: TeamSpeakProtocol | null;
|
||||
lastTestAt: string | null;
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SettingsUpdate {
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
accessMode: AccessMode;
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
}
|
||||
|
||||
interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
access_mode: string;
|
||||
ts_host: string;
|
||||
ts_port: number;
|
||||
ts_password_encrypted: string | null;
|
||||
detected_protocol: string | null;
|
||||
last_test_at: string | null;
|
||||
last_test_latency_ms: number | null;
|
||||
last_test_error: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export class WebSpeakDatabase {
|
||||
private readonly database: DatabaseSync;
|
||||
|
||||
constructor(private readonly path: string) {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const existed = existsSync(path);
|
||||
this.database = new DatabaseSync(path);
|
||||
this.database.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL;");
|
||||
this.migrate(existed);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.database.close();
|
||||
}
|
||||
|
||||
get schemaVersion(): number {
|
||||
return Number((this.database.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
|
||||
}
|
||||
|
||||
hasAdmin(): boolean {
|
||||
return Boolean(this.database.prepare("SELECT 1 AS present FROM admin_credentials WHERE id = 1").get());
|
||||
}
|
||||
|
||||
getAdminCredential(): AdminCredential | null {
|
||||
const row = this.database.prepare("SELECT credential_json FROM admin_credentials WHERE id = 1").get() as { credential_json?: string } | undefined;
|
||||
if (!row?.credential_json) return null;
|
||||
return JSON.parse(row.credential_json) as AdminCredential;
|
||||
}
|
||||
|
||||
initializeAdmin(credential: AdminCredential, settings: SettingsUpdate): void {
|
||||
this.transaction(() => {
|
||||
if (this.hasAdmin()) throw new Error("WebSpeak is already initialized");
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
"INSERT INTO admin_credentials (id, credential_json, created_at, updated_at) VALUES (1, ?, ?, ?)",
|
||||
).run(JSON.stringify(credential), now, now);
|
||||
this.writeSettings(settings, now);
|
||||
this.insertAudit("ADMIN_INITIALIZED", { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
|
||||
});
|
||||
}
|
||||
|
||||
getSettings(): PersistedSettings {
|
||||
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
|
||||
return {
|
||||
siteName: row.site_name,
|
||||
welcomeText: row.welcome_text,
|
||||
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
||||
tsHost: row.ts_host,
|
||||
tsPort: row.ts_port,
|
||||
tsPasswordEncrypted: row.ts_password_encrypted,
|
||||
detectedProtocol: row.detected_protocol === "ts3" || row.detected_protocol === "ts6" ? row.detected_protocol : null,
|
||||
lastTestAt: row.last_test_at,
|
||||
lastTestLatencyMs: row.last_test_latency_ms,
|
||||
lastTestError: row.last_test_error,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.writeSettings(settings, now);
|
||||
this.insertAudit(auditEvent, { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
|
||||
});
|
||||
}
|
||||
|
||||
recordConnectionTest(result: {
|
||||
protocol: TeamSpeakProtocol | null;
|
||||
latencyMs: number | null;
|
||||
error: string | null;
|
||||
}): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings
|
||||
SET detected_protocol = ?, last_test_at = ?, last_test_latency_ms = ?, last_test_error = ?
|
||||
WHERE id = 1`,
|
||||
).run(result.protocol, new Date().toISOString(), result.latencyMs, result.error);
|
||||
}
|
||||
|
||||
clearConnectionTest(): void {
|
||||
this.database.exec(
|
||||
"UPDATE settings SET detected_protocol = NULL, last_test_at = NULL, last_test_latency_ms = NULL, last_test_error = NULL WHERE id = 1",
|
||||
);
|
||||
}
|
||||
|
||||
getMeta(key: string): string | null {
|
||||
const row = this.database.prepare("SELECT value FROM metadata WHERE key = ?").get(key) as { value?: string } | undefined;
|
||||
return row?.value ?? null;
|
||||
}
|
||||
|
||||
setMeta(key: string, value: string): void {
|
||||
this.database.prepare(
|
||||
"INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
).run(key, value);
|
||||
}
|
||||
|
||||
addAudit(event: string, details: Record<string, unknown> = {}): void {
|
||||
this.insertAudit(event, details, new Date().toISOString());
|
||||
}
|
||||
|
||||
recentAudit(limit = 8): Array<{ event: string; createdAt: string }> {
|
||||
const normalizedLimit = Math.max(1, Math.min(50, Math.floor(limit)));
|
||||
const rows = this.database.prepare(
|
||||
"SELECT event, created_at FROM audit_events ORDER BY id DESC LIMIT ?",
|
||||
).all(normalizedLimit) as Array<{ event: string; created_at: string }>;
|
||||
return rows.map((row) => ({ event: row.event, createdAt: row.created_at }));
|
||||
}
|
||||
|
||||
private migrate(existed: boolean): void {
|
||||
const version = this.schemaVersion;
|
||||
if (version > DATABASE_SCHEMA_VERSION) {
|
||||
throw new Error(`Database schema ${version} is newer than this WebSpeak build`);
|
||||
}
|
||||
if (version === DATABASE_SCHEMA_VERSION) return;
|
||||
if (existed && version > 0) {
|
||||
copyFileSync(this.path, `${this.path}.schema-${version}.bak`);
|
||||
}
|
||||
this.transaction(() => {
|
||||
if (version === 0) {
|
||||
this.database.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 CHECK (ts_port BETWEEN 1 AND 65535),
|
||||
ts_password_encrypted TEXT,
|
||||
detected_protocol TEXT CHECK (detected_protocol IS NULL OR detected_protocol IN ('ts3', 'ts6')),
|
||||
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
|
||||
);
|
||||
`);
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
`INSERT INTO settings (
|
||||
id, site_name, welcome_text, access_mode, ts_host, ts_port,
|
||||
ts_password_encrypted, detected_protocol, last_test_at,
|
||||
last_test_latency_ms, last_test_error, updated_at
|
||||
) VALUES (1, 'WebSpeak', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, ?)`,
|
||||
).run(now);
|
||||
this.database.exec(`PRAGMA user_version = ${DATABASE_SCHEMA_VERSION}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
).run(
|
||||
settings.siteName,
|
||||
settings.welcomeText,
|
||||
settings.accessMode,
|
||||
settings.tsHost,
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
private insertAudit(event: string, details: Record<string, unknown>, now: string): void {
|
||||
this.database.prepare(
|
||||
"INSERT INTO audit_events (event, details_json, created_at) VALUES (?, ?, ?)",
|
||||
).run(event, JSON.stringify(details), now);
|
||||
}
|
||||
|
||||
private transaction(action: () => void): void {
|
||||
this.database.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
action();
|
||||
this.database.exec("COMMIT");
|
||||
} catch (error) {
|
||||
this.database.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const KEY_LENGTH = 64;
|
||||
const SCRYPT_PARAMETERS = Object.freeze({ N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
|
||||
|
||||
export interface AdminCredential {
|
||||
version: 1;
|
||||
salt: string;
|
||||
hash: string;
|
||||
parameters: {
|
||||
N: number;
|
||||
r: number;
|
||||
p: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function validateAdminPassword(password: string): string | null {
|
||||
if (password.length < 12) return "Admin password must contain at least 12 characters";
|
||||
if (password.length > 1024) return "Admin password is too long";
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function hashAdminPassword(password: string): Promise<AdminCredential> {
|
||||
const validationError = validateAdminPassword(password);
|
||||
if (validationError) throw new Error(validationError);
|
||||
const salt = randomBytes(16);
|
||||
const hash = await derive(password, salt, SCRYPT_PARAMETERS);
|
||||
return {
|
||||
version: 1,
|
||||
salt: salt.toString("base64url"),
|
||||
hash: hash.toString("base64url"),
|
||||
parameters: {
|
||||
N: SCRYPT_PARAMETERS.N,
|
||||
r: SCRYPT_PARAMETERS.r,
|
||||
p: SCRYPT_PARAMETERS.p,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function verifyAdminPassword(password: string, credential: AdminCredential): Promise<boolean> {
|
||||
if (credential.version !== 1 || typeof password !== "string" || password.length > 1024) return false;
|
||||
try {
|
||||
const expected = Buffer.from(credential.hash, "base64url");
|
||||
const actual = await derive(password, Buffer.from(credential.salt, "base64url"), {
|
||||
...credential.parameters,
|
||||
maxmem: 64 * 1024 * 1024,
|
||||
});
|
||||
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function derive(
|
||||
password: string,
|
||||
salt: Buffer,
|
||||
parameters: { N: number; r: number; p: number; maxmem: number },
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
scrypt(password, salt, KEY_LENGTH, parameters, (error, result) => {
|
||||
if (error) reject(error);
|
||||
else resolve(Buffer.from(result));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { chmodSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export class BootstrapManager {
|
||||
private code: string | null = null;
|
||||
|
||||
constructor(private readonly path: string) {}
|
||||
|
||||
ensure(): string {
|
||||
if (this.code) return this.code;
|
||||
try {
|
||||
const stored = readFileSync(this.path, "utf8").trim();
|
||||
if (normalize(stored).length >= 20) {
|
||||
this.code = stored;
|
||||
return stored;
|
||||
}
|
||||
} catch {
|
||||
// A missing or invalid bootstrap file is replaced below.
|
||||
}
|
||||
|
||||
const raw = randomBytes(16).toString("hex").toUpperCase();
|
||||
this.code = raw.match(/.{1,4}/g)!.join("-");
|
||||
mkdirSync(dirname(this.path), { recursive: true });
|
||||
writeFileSync(this.path, `${this.code}\n`, { encoding: "utf8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(this.path, 0o600);
|
||||
} catch {
|
||||
// POSIX permissions are best-effort on non-POSIX filesystems.
|
||||
}
|
||||
return this.code;
|
||||
}
|
||||
|
||||
verify(candidate: string): boolean {
|
||||
const expected = normalize(this.ensure());
|
||||
const actual = normalize(candidate);
|
||||
const expectedBytes = Buffer.from(expected, "utf8");
|
||||
const actualBytes = Buffer.from(actual, "utf8");
|
||||
return expectedBytes.length === actualBytes.length && timingSafeEqual(expectedBytes, actualBytes);
|
||||
}
|
||||
|
||||
consume(): void {
|
||||
this.code = null;
|
||||
try {
|
||||
unlinkSync(this.path);
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
chmodSync,
|
||||
closeSync,
|
||||
mkdirSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
const MASTER_KEY_BYTES = 32;
|
||||
|
||||
/** Create or load the installation-local key used to protect secrets at rest. */
|
||||
export function loadOrCreateMasterSecret(path: string): Buffer {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
try {
|
||||
const descriptor = openSync(path, "wx", 0o600);
|
||||
try {
|
||||
writeFileSync(descriptor, randomBytes(MASTER_KEY_BYTES));
|
||||
} finally {
|
||||
closeSync(descriptor);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (!isAlreadyExistsError(error)) throw error;
|
||||
}
|
||||
|
||||
const key = readFileSync(path);
|
||||
if (key.length !== MASTER_KEY_BYTES) {
|
||||
throw new Error(`Invalid WebSpeak master secret: expected ${MASTER_KEY_BYTES} bytes`);
|
||||
}
|
||||
try {
|
||||
chmodSync(path, 0o600);
|
||||
} catch {
|
||||
// Windows and some container filesystems do not expose POSIX permissions.
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function isAlreadyExistsError(error: unknown): boolean {
|
||||
return error instanceof Error && "code" in error && error.code === "EEXIST";
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { isIP } from "node:net";
|
||||
import { lookup } from "node:dns/promises";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export class UnsafeTeamSpeakTargetError extends Error {
|
||||
constructor(message = "This TeamSpeak target is not allowed in open mode") {
|
||||
super(message);
|
||||
this.name = "UnsafeTeamSpeakTargetError";
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve and reject addresses that could turn a public gateway into an internal network probe. */
|
||||
export async function assertSafeOpenTarget(target: TeamSpeakTarget): Promise<void> {
|
||||
await resolveSafeOpenTarget(target);
|
||||
}
|
||||
|
||||
export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<TeamSpeakTarget> {
|
||||
const literalVersion = isIP(target.host);
|
||||
const addresses = literalVersion
|
||||
? [{ address: target.host, family: literalVersion }]
|
||||
: await lookup(target.host, { all: true, verbatim: true });
|
||||
if (!addresses.length || addresses.some(({ address }) => isRestrictedAddress(address))) {
|
||||
throw new UnsafeTeamSpeakTargetError();
|
||||
}
|
||||
// Use the address that was actually validated so a second DNS lookup cannot
|
||||
// rebind the gateway connection to a private network.
|
||||
return { host: addresses[0]!.address, port: target.port };
|
||||
}
|
||||
|
||||
export function isRestrictedAddress(address: string): boolean {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
function isRestrictedIpv4(address: string): boolean {
|
||||
const parts = address.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
|
||||
const [a, b] = parts as [number, number, number, number];
|
||||
return a === 0
|
||||
|| a === 10
|
||||
|| a === 127
|
||||
|| (a === 100 && b >= 64 && b <= 127)
|
||||
|| (a === 169 && b === 254)
|
||||
|| (a === 172 && b >= 16 && b <= 31)
|
||||
|| (a === 192 && b === 0)
|
||||
|| (a === 192 && b === 168)
|
||||
|| (a === 192 && b === 0 && parts[2] === 2)
|
||||
|| (a === 198 && (b === 18 || b === 19))
|
||||
|| (a === 198 && b === 51 && parts[2] === 100)
|
||||
|| (a === 203 && b === 0 && parts[2] === 113)
|
||||
|| a >= 224;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
|
||||
const ALGORITHM = "aes-256-gcm";
|
||||
const VERSION = "v1";
|
||||
const AAD = Buffer.from("webspeak:teamspeak-password:v1", "utf8");
|
||||
|
||||
export function encryptSecret(value: string, masterKey: Buffer): string {
|
||||
if (!value) return "";
|
||||
assertMasterKey(masterKey);
|
||||
const nonce = randomBytes(12);
|
||||
const cipher = createCipheriv(ALGORITHM, masterKey, nonce);
|
||||
cipher.setAAD(AAD);
|
||||
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return [VERSION, nonce.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(":");
|
||||
}
|
||||
|
||||
export function decryptSecret(payload: string | null | undefined, masterKey: Buffer): string {
|
||||
if (!payload) return "";
|
||||
assertMasterKey(masterKey);
|
||||
const [version, nonceText, tagText, ciphertextText, ...extra] = payload.split(":");
|
||||
if (version !== VERSION || !nonceText || !tagText || ciphertextText === undefined || extra.length) {
|
||||
throw new Error("Unsupported encrypted secret format");
|
||||
}
|
||||
const decipher = createDecipheriv(ALGORITHM, masterKey, Buffer.from(nonceText, "base64url"));
|
||||
decipher.setAAD(AAD);
|
||||
decipher.setAuthTag(Buffer.from(tagText, "base64url"));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(ciphertextText, "base64url")),
|
||||
decipher.final(),
|
||||
]).toString("utf8");
|
||||
}
|
||||
|
||||
function assertMasterKey(masterKey: Buffer): void {
|
||||
if (masterKey.length !== 32) throw new Error("Invalid master key length");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export interface JoinTicketPayload {
|
||||
target: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
nickname: string;
|
||||
channel?: string;
|
||||
}
|
||||
|
||||
interface StoredTicket {
|
||||
payload: JoinTicketPayload;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export class JoinTicketStore {
|
||||
private readonly tickets = new Map<string, StoredTicket>();
|
||||
|
||||
constructor(private readonly ttlMs = 30_000, private readonly maxTickets = 256) {}
|
||||
|
||||
create(payload: JoinTicketPayload, now = Date.now()): string {
|
||||
this.prune(now);
|
||||
while (this.tickets.size >= this.maxTickets) {
|
||||
const oldest = this.tickets.keys().next().value;
|
||||
if (!oldest) break;
|
||||
this.tickets.delete(oldest);
|
||||
}
|
||||
const token = randomBytes(24).toString("base64url");
|
||||
this.tickets.set(token, { payload, expiresAt: now + this.ttlMs });
|
||||
return token;
|
||||
}
|
||||
|
||||
consume(token: string, now = Date.now()): JoinTicketPayload | null {
|
||||
const stored = this.tickets.get(token);
|
||||
this.tickets.delete(token);
|
||||
if (!stored || stored.expiresAt <= now) return null;
|
||||
return stored.payload;
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [token, stored] of this.tickets) {
|
||||
if (stored.expiresAt <= now) this.tickets.delete(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
+84
-15
@@ -3,18 +3,20 @@ 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 { fileURLToPath } from "node:url";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { formatTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-target.js";
|
||||
import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
staticDir?: string;
|
||||
certDir?: string; // path to cert.pem + key.pem for HTTPS
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
adminService: AdminService;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
@@ -40,20 +42,74 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
|
||||
app.use(express.json({ limit: "100kb" }));
|
||||
|
||||
app.get("/api/health", (_req, res) => {
|
||||
res.json({ status: "ok", version: "0.1.0" });
|
||||
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
|
||||
const adminSessions = new AdminSessionStore();
|
||||
const startedAt = Date.now();
|
||||
|
||||
const healthHandler: express.RequestHandler = (_request, response) => {
|
||||
response.json({ status: "ok", version: "0.1.0" });
|
||||
};
|
||||
app.get("/health", healthHandler);
|
||||
app.get("/api/health", healthHandler);
|
||||
|
||||
app.get("/api/public-config", (_request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.json(options.adminService.getPublicConfig());
|
||||
});
|
||||
|
||||
// The browser needs the gateway's default target so a user can edit it in
|
||||
// the join form. No credentials are exposed here.
|
||||
app.get("/api/public-config", (_req, res) => {
|
||||
res.json({
|
||||
tsHost: options.voiceBridgeOptions.defaultTarget.host,
|
||||
tsPort: options.voiceBridgeOptions.defaultTarget.port,
|
||||
target: formatTeamSpeakTarget(options.voiceBridgeOptions.defaultTarget),
|
||||
app.post("/api/join-ticket", async (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json") || !isSameOrigin(request)) {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
if (!options.adminService.isInitialized()) {
|
||||
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
const body = isRecord(request.body) ? request.body : {};
|
||||
const nickname = typeof body.nickname === "string" ? body.nickname.trim().slice(0, 30) : "";
|
||||
const channel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
|
||||
if (!nickname) {
|
||||
response.status(400).json({ ok: false, code: "INVALID_NICKNAME" });
|
||||
return;
|
||||
}
|
||||
|
||||
const policy = options.adminService.getConnectionPolicy();
|
||||
let target = policy.defaultTarget;
|
||||
let serverPassword = policy.serverPassword;
|
||||
try {
|
||||
if (policy.accessMode === "open" && typeof body.target === "string" && body.target.trim()) {
|
||||
target = parseTeamSpeakTarget(body.target);
|
||||
const isDefault = teamSpeakTargetKey(target) === teamSpeakTargetKey(policy.defaultTarget);
|
||||
if (!isDefault) {
|
||||
target = await resolveSafeOpenTarget(target);
|
||||
serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : "";
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" });
|
||||
return;
|
||||
}
|
||||
|
||||
const ticket = options.voiceBridgeOptions.joinTickets.create({
|
||||
target,
|
||||
serverPassword,
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
|
||||
app.use("/api/admin", createAdminRouter({
|
||||
service: options.adminService,
|
||||
sessions: adminSessions,
|
||||
logger,
|
||||
getActiveSessions: () => voiceBridge.getActiveCount(),
|
||||
getPeakSessions: () => voiceBridge.getPeakCount(),
|
||||
startedAt,
|
||||
}));
|
||||
|
||||
// Serve static frontend
|
||||
if (options.staticDir) {
|
||||
app.use(express.static(options.staticDir));
|
||||
@@ -62,8 +118,6 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
});
|
||||
}
|
||||
|
||||
// Voice bridge WebSocket at /ws/voice
|
||||
const voiceBridge = new VoiceBridge(options.voiceBridgeOptions, logger);
|
||||
voiceBridge.attach(server);
|
||||
|
||||
return {
|
||||
@@ -77,9 +131,24 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
},
|
||||
async stop(): Promise<void> {
|
||||
voiceBridge.shutdown();
|
||||
adminSessions.clear();
|
||||
return new Promise((resolve) => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSameOrigin(request: express.Request): boolean {
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
return Boolean(origin && host && new URL(origin).host === host);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError, type WebSpeakErrorCode } from "../errors.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
|
||||
export type ProbeErrorCode =
|
||||
| "HOST_NOT_FOUND"
|
||||
| "UNREACHABLE"
|
||||
| "TIMEOUT"
|
||||
| "INVALID_PASSWORD"
|
||||
| "PROTOCOL_NEGOTIATION_FAILED"
|
||||
| "SERVER_REJECTED"
|
||||
| "INTERNAL_ERROR";
|
||||
|
||||
export interface TeamSpeakProbeResult {
|
||||
ok: true;
|
||||
protocol: TeamSpeakProtocol | null;
|
||||
latencyMs: number;
|
||||
serverName: string | null;
|
||||
requiresPassword: boolean;
|
||||
}
|
||||
|
||||
export class TeamSpeakProbeError extends Error {
|
||||
constructor(readonly code: ProbeErrorCode, message: string, readonly cause?: unknown) {
|
||||
super(message);
|
||||
this.name = "TeamSpeakProbeError";
|
||||
}
|
||||
}
|
||||
|
||||
interface ProbeAdapter {
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
readonly protocol: TeamSpeakProtocol | null;
|
||||
readonly client: {
|
||||
execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]>;
|
||||
};
|
||||
}
|
||||
|
||||
export type ProbeAdapterFactory = (input: {
|
||||
target: TeamSpeakTarget;
|
||||
password: string;
|
||||
logger: Logger;
|
||||
}) => ProbeAdapter;
|
||||
|
||||
export async function probeTeamSpeak(
|
||||
target: TeamSpeakTarget,
|
||||
password: string,
|
||||
logger: Logger,
|
||||
factory: ProbeAdapterFactory = ({ target: probeTarget, password: probePassword, logger: probeLogger }) =>
|
||||
new TeamSpeakAdapter({ target: probeTarget, nickname: "WebSpeak Probe", serverPassword: probePassword }, probeLogger),
|
||||
): Promise<TeamSpeakProbeResult> {
|
||||
const startedAt = Date.now();
|
||||
const adapter = factory({ target, password, logger: logger.child({ component: "teamspeak-probe" }) });
|
||||
try {
|
||||
await adapter.connect();
|
||||
let serverName: string | null = null;
|
||||
try {
|
||||
const rows = await adapter.client.execCommandWithResponse("serverinfo", 3000);
|
||||
const first = rows[0] ?? {};
|
||||
serverName = first.virtualserver_name ?? first.server_name ?? first.name ?? null;
|
||||
} catch {
|
||||
// A connected server can restrict serverinfo; reachability is still proven.
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
protocol: adapter.protocol,
|
||||
latencyMs: Math.max(0, Date.now() - startedAt),
|
||||
serverName,
|
||||
requiresPassword: Boolean(password),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
throw toProbeError(error);
|
||||
} finally {
|
||||
try {
|
||||
await adapter.disconnect();
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ err: extractErrorText(error) }, "TeamSpeak probe cleanup failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function toProbeError(error: unknown): TeamSpeakProbeError {
|
||||
if (error instanceof TeamSpeakProbeError) return error;
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
const mapping: Record<WebSpeakErrorCode, ProbeErrorCode> = {
|
||||
invalid_target: "INTERNAL_ERROR",
|
||||
unreachable: "UNREACHABLE",
|
||||
timeout: "TIMEOUT",
|
||||
authentication_failed: "INVALID_PASSWORD",
|
||||
protocol_negotiation_failed: "PROTOCOL_NEGOTIATION_FAILED",
|
||||
server_full: "SERVER_REJECTED",
|
||||
unknown: "SERVER_REJECTED",
|
||||
};
|
||||
return new TeamSpeakProbeError(mapping[normalized.code] ?? "INTERNAL_ERROR", normalized.message, error);
|
||||
}
|
||||
|
||||
function extractErrorText(error: unknown): string {
|
||||
if (!error || typeof error !== "object") return String(error ?? "");
|
||||
const candidate = error as { code?: unknown; message?: unknown };
|
||||
return `${typeof candidate.code === "string" ? candidate.code : ""} ${typeof candidate.message === "string" ? candidate.message : ""}`;
|
||||
}
|
||||
+20
-22
@@ -8,10 +8,9 @@ import { canAcceptSession, MAX_ACTIVE_SESSIONS } from "../constants.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import {
|
||||
formatTeamSpeakTarget,
|
||||
parseTeamSpeakTarget,
|
||||
parseTeamSpeakTargetParts,
|
||||
type TeamSpeakTarget,
|
||||
} from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -19,8 +18,7 @@ const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
};
|
||||
|
||||
export interface VoiceBridgeOptions {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
tsServerPassword: string;
|
||||
joinTickets: JoinTicketStore;
|
||||
}
|
||||
|
||||
interface ChannelMember {
|
||||
@@ -45,6 +43,7 @@ export class VoiceBridge {
|
||||
private clients = new Map<string, WebClientEntry>();
|
||||
private wss: WebSocketServer | null = null;
|
||||
private logger: LoggerType;
|
||||
private peakClients = 0;
|
||||
|
||||
constructor(
|
||||
private options: VoiceBridgeOptions,
|
||||
@@ -54,28 +53,17 @@ export class VoiceBridge {
|
||||
}
|
||||
|
||||
attach(server: Server): void {
|
||||
this.wss = new WebSocketServer({ server, path: "/ws/voice" });
|
||||
this.wss = new WebSocketServer({ server, path: "/ws/voice", maxPayload: 256 * 1024 });
|
||||
|
||||
this.wss.on("connection", (ws: WebSocket, req: IncomingMessage) => {
|
||||
const url = new URL(req.url ?? "/", `https://${req.headers.host ?? "localhost"}`);
|
||||
const channelName = url.searchParams.get("channel") ?? undefined;
|
||||
const nickname = (url.searchParams.get("nickname") ?? "WebUser").trim().slice(0, 30) || "WebUser";
|
||||
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
const rawTarget = url.searchParams.get("target");
|
||||
target = rawTarget?.trim()
|
||||
? parseTeamSpeakTarget(rawTarget)
|
||||
: parseTeamSpeakTargetParts(
|
||||
url.searchParams.get("tsHost") ?? this.options.defaultTarget.host,
|
||||
url.searchParams.get("tsPort") ?? undefined,
|
||||
this.options.defaultTarget.port,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ nickname, err: error instanceof Error ? error.message : String(error) }, "Invalid TeamSpeak target");
|
||||
ws.close(4002, "Invalid TeamSpeak target");
|
||||
const connection = this.resolveConnection(url);
|
||||
if (!connection) {
|
||||
ws.close(4001, "Join ticket required");
|
||||
return;
|
||||
}
|
||||
const { target, serverPassword, nickname } = connection;
|
||||
const channelName = connection.channel;
|
||||
|
||||
if (!canAcceptSession(this.clients.size)) {
|
||||
this.logger.warn({ max: MAX_ACTIVE_SESSIONS }, "Max clients reached");
|
||||
@@ -89,7 +77,7 @@ export class VoiceBridge {
|
||||
const tsClient = new TSClient({
|
||||
target,
|
||||
nickname,
|
||||
serverPassword: this.options.tsServerPassword,
|
||||
serverPassword,
|
||||
defaultChannel: channelName,
|
||||
}, this.logger);
|
||||
|
||||
@@ -104,6 +92,7 @@ export class VoiceBridge {
|
||||
opusEncoder: new OpusEncoder(48000, 1),
|
||||
};
|
||||
this.clients.set(entryId, entry);
|
||||
this.peakClients = Math.max(this.peakClients, this.clients.size);
|
||||
|
||||
let tsReady = false;
|
||||
let selfId = 0;
|
||||
@@ -269,6 +258,10 @@ export class VoiceBridge {
|
||||
return this.clients.size;
|
||||
}
|
||||
|
||||
getPeakCount(): number {
|
||||
return this.peakClients;
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
for (const [id, entry] of this.clients) {
|
||||
this.clients.delete(id);
|
||||
@@ -277,6 +270,11 @@ export class VoiceBridge {
|
||||
}
|
||||
this.wss?.close();
|
||||
}
|
||||
|
||||
private resolveConnection(url: URL): JoinTicketPayload | null {
|
||||
const token = url.searchParams.get("ticket");
|
||||
return token ? this.options.joinTickets.consume(token) : null;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCommand(entry: WebClientEntry, command: { type: string; [key: string]: unknown }) {
|
||||
|
||||
Reference in new issue
Block a user