mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat: add managed invites and admin diagnostics backend
This commit is contained in:
1 parent
96ef77c789
commit
f5bd06fdaf
10 files changed
+562
-29
No files matched your search
@@ -1,9 +1,11 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import type { AdminSessionSummary } from "../server/voice-bridge.js";
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
@@ -11,6 +13,11 @@ export interface AdminRouterOptions {
|
||||
logger: Logger;
|
||||
getActiveSessions(): number;
|
||||
getPeakSessions(): number;
|
||||
getCreatedSessions?: () => number;
|
||||
getSessionSummaries?: () => AdminSessionSummary[];
|
||||
terminateSession?: (id: string) => Promise<boolean>;
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
@@ -97,6 +104,135 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.get("/sessions", (_request, response) => {
|
||||
response.json({ sessions: options.getSessionSummaries?.() ?? [] });
|
||||
});
|
||||
|
||||
router.post("/sessions/:id/terminate", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!options.terminateSession || !id || !(await options.terminateSession(id))) {
|
||||
response.status(404).json({ ok: false, code: "SESSION_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
options.service.database.addAudit("ADMIN_SESSION_TERMINATED", { id });
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
router.get("/invites", (_request, response) => {
|
||||
response.json({ invites: options.service.listManagedInvites() });
|
||||
});
|
||||
|
||||
router.post("/invites", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
const created = options.service.createManagedInvite({
|
||||
channel: readOptionalString(body, "channel", 100),
|
||||
expiresInHours: readOptionalNumber(body, "expiresInHours", 1),
|
||||
maxUses: readOptionalNumber(body, "maxUses", 0),
|
||||
});
|
||||
response.status(201).json({ ok: true, ...created });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/invites/:id/revoke", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
const id = typeof request.params.id === "string" ? request.params.id : "";
|
||||
if (!id) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
|
||||
if (!options.service.revokeManagedInvite(id)) {
|
||||
response.status(404).json({ ok: false, code: "INVITE_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
response.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/audit", (request, response) => {
|
||||
response.json({ events: options.service.database.recentAudit(readLimit(request.query.limit, 50)) });
|
||||
});
|
||||
|
||||
router.get("/logs", (request, response) => {
|
||||
response.json({ available: Boolean(options.logFile && existsSync(options.logFile)), entries: readRecentLogs(options.logFile, readLimit(request.query.limit, 100)) });
|
||||
});
|
||||
|
||||
router.get("/diagnostics", (_request, response) => {
|
||||
const overview = options.service.getOverview(
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
response.json({
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
version: options.version ?? "0.1.0",
|
||||
uptimeSeconds: overview.gateway.uptimeSeconds,
|
||||
node: process.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
},
|
||||
sessions: {
|
||||
active: options.getActiveSessions(),
|
||||
peak: options.getPeakSessions(),
|
||||
created: options.getCreatedSessions?.() ?? 0,
|
||||
limit: 100,
|
||||
},
|
||||
teamSpeak: overview.teamSpeak,
|
||||
database: { schemaVersion: options.service.database.schemaVersion },
|
||||
logs: { available: Boolean(options.logFile && existsSync(options.logFile)) },
|
||||
});
|
||||
});
|
||||
|
||||
router.get("/diagnostics/report", (_request, response) => {
|
||||
const overview = options.service.getOverview(
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
const report = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
version: options.version ?? "0.1.0",
|
||||
uptimeSeconds: overview.gateway.uptimeSeconds,
|
||||
node: process.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
},
|
||||
sessions: {
|
||||
active: options.getActiveSessions(),
|
||||
peak: options.getPeakSessions(),
|
||||
created: options.getCreatedSessions?.() ?? 0,
|
||||
limit: 100,
|
||||
},
|
||||
teamSpeak: {
|
||||
status: overview.teamSpeak.status,
|
||||
protocol: overview.teamSpeak.protocol,
|
||||
lastTestAt: overview.teamSpeak.lastTestAt,
|
||||
latencyMs: overview.teamSpeak.latencyMs,
|
||||
lastError: overview.teamSpeak.lastError,
|
||||
},
|
||||
database: { schemaVersion: options.service.database.schemaVersion },
|
||||
audit: options.service.database.recentAudit(50),
|
||||
};
|
||||
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
response.setHeader("Content-Disposition", `attachment; filename="webspeak-diagnostic-report.json"`);
|
||||
response.send(JSON.stringify(report, null, 2));
|
||||
});
|
||||
|
||||
router.get("/backup", (_request, response) => {
|
||||
try {
|
||||
const backup = options.service.database.exportBackup();
|
||||
options.service.database.addAudit("ADMIN_BACKUP_EXPORTED");
|
||||
response.setHeader("Content-Type", "application/octet-stream");
|
||||
response.setHeader("Content-Disposition", `attachment; filename="webspeak-backup-${new Date().toISOString().slice(0, 10)}.db"`);
|
||||
response.send(backup);
|
||||
} catch {
|
||||
response.status(500).json({ ok: false, code: "BACKUP_FAILED" });
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
|
||||
@@ -218,6 +354,70 @@ function readOptionalString(body: Record<string, unknown>, key: string, max: num
|
||||
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
|
||||
}
|
||||
|
||||
function readOptionalNumber(body: Record<string, unknown>, key: string, fallback: number): number {
|
||||
return body[key] === undefined ? fallback : typeof body[key] === "number" ? body[key] : Number.NaN;
|
||||
}
|
||||
|
||||
function readLimit(value: unknown, fallback: number): number {
|
||||
const limit = typeof value === "string" ? Number(value) : fallback;
|
||||
return Number.isFinite(limit) ? Math.max(1, Math.min(200, Math.floor(limit))) : fallback;
|
||||
}
|
||||
|
||||
interface AdminLogEntry {
|
||||
timestamp: string | null;
|
||||
level: string;
|
||||
message: string;
|
||||
context: Record<string, string | number | boolean>;
|
||||
}
|
||||
|
||||
function readRecentLogs(logFile: string | undefined, limit: number): AdminLogEntry[] {
|
||||
if (!logFile) return [];
|
||||
try {
|
||||
const lines = readFileSync(logFile, "utf8").split(/\r?\n/).filter(Boolean).slice(-limit);
|
||||
return lines.map((line) => {
|
||||
try {
|
||||
const raw = JSON.parse(line) as Record<string, unknown>;
|
||||
const context: Record<string, string | number | boolean> = {};
|
||||
for (const key of ["component", "entryId", "code", "reason", "attempt", "target", "nickname", "channel", "reconnect", "port"]) {
|
||||
const value = raw[key];
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") context[key] = value;
|
||||
}
|
||||
return {
|
||||
timestamp: typeof raw.time === "string" ? raw.time : null,
|
||||
level: logLevelName(raw.level),
|
||||
message: typeof raw.msg === "string" ? raw.msg : "",
|
||||
context,
|
||||
};
|
||||
} catch {
|
||||
return { timestamp: null, level: "INFO", message: line.slice(0, 1000), context: {} };
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
target: string;
|
||||
status: string;
|
||||
protocol: string | null;
|
||||
lastTestAt: string | null;
|
||||
latencyMs: number | null;
|
||||
lastError: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
function logLevelName(level: unknown): string {
|
||||
if (level === 10) return "DEBUG";
|
||||
if (level === 30) return "INFO";
|
||||
if (level === 40) return "WARN";
|
||||
if (level === 50) return "ERROR";
|
||||
if (level === 60) return "FATAL";
|
||||
return typeof level === "string" ? level.toUpperCase() : "INFO";
|
||||
}
|
||||
|
||||
function sendAdminError(response: Response, error: unknown): void {
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
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 { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
@@ -22,6 +23,24 @@ export interface ConnectionPolicy {
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
export interface ManagedInviteInput {
|
||||
channel: string;
|
||||
expiresInHours: number;
|
||||
maxUses: number;
|
||||
}
|
||||
|
||||
export interface ManagedInviteView {
|
||||
id: string;
|
||||
target: string;
|
||||
channel: string;
|
||||
expiresAt: string;
|
||||
maxUses: number;
|
||||
useCount: number;
|
||||
createdAt: string;
|
||||
revokedAt: string | null;
|
||||
status: "active" | "expired" | "exhausted" | "revoked";
|
||||
}
|
||||
|
||||
type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
@@ -164,6 +183,56 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
createManagedInvite(input: ManagedInviteInput): { invite: ManagedInviteView; token: string } {
|
||||
const channel = input.channel.trim();
|
||||
if (channel.length > 100) throw new AdminInputError("INVALID_INVITE_CHANNEL", "Invite channel cannot exceed 100 characters");
|
||||
if (!Number.isFinite(input.expiresInHours) || input.expiresInHours < 1 || input.expiresInHours > 720) {
|
||||
throw new AdminInputError("INVALID_INVITE_EXPIRY", "Invite expiry must be between 1 and 720 hours");
|
||||
}
|
||||
if (!Number.isInteger(input.maxUses) || input.maxUses < 0 || input.maxUses > 10000) {
|
||||
throw new AdminInputError("INVALID_INVITE_USES", "Invite max uses must be between 0 and 10000");
|
||||
}
|
||||
const settings = this.database.getSettings();
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const record = this.database.createManagedInvite({
|
||||
id: `invite-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`,
|
||||
tokenHash: hashInviteToken(token),
|
||||
targetHost: settings.tsHost,
|
||||
targetPort: settings.tsPort,
|
||||
serverPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
channel,
|
||||
expiresAt: new Date(Date.now() + input.expiresInHours * 60 * 60 * 1000).toISOString(),
|
||||
maxUses: input.maxUses,
|
||||
});
|
||||
this.database.addAudit("INVITE_CREATED", { id: record.id, channel, maxUses: input.maxUses });
|
||||
return { invite: this.toInviteView(record), token };
|
||||
}
|
||||
|
||||
listManagedInvites(): ManagedInviteView[] {
|
||||
return this.database.listManagedInvites().map((record) => this.toInviteView(record));
|
||||
}
|
||||
|
||||
revokeManagedInvite(id: string): boolean {
|
||||
if (!/^invite-[a-z0-9-]+$/i.test(id) || id.length > 100) throw new AdminInputError("INVALID_INVITE_ID", "Invite id is invalid");
|
||||
const revoked = this.database.revokeManagedInvite(id);
|
||||
if (revoked) this.database.addAudit("INVITE_REVOKED", { id });
|
||||
return revoked;
|
||||
}
|
||||
|
||||
consumeManagedInvite(token: string): { target: TeamSpeakTarget; serverPassword: string; channel: string } | null {
|
||||
if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return null;
|
||||
const record = this.database.consumeManagedInvite(hashInviteToken(token));
|
||||
if (!record) return null;
|
||||
let serverPassword = "";
|
||||
try {
|
||||
serverPassword = decryptSecret(record.serverPasswordEncrypted, this.masterSecret);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error), inviteId: record.id }, "Managed invite password could not be decrypted");
|
||||
}
|
||||
this.database.addAudit("INVITE_CONSUMED", { id: record.id });
|
||||
return { target: { host: record.targetHost, port: record.targetPort }, serverPassword, channel: record.channel };
|
||||
}
|
||||
|
||||
dismissLegacyImportNotice(): void {
|
||||
this.database.setMeta("legacy_import_notice_pending", "0");
|
||||
}
|
||||
@@ -197,6 +266,23 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
private toInviteView(record: ManagedInviteRecord): ManagedInviteView {
|
||||
const now = Date.now();
|
||||
const expired = Date.parse(record.expiresAt) <= now;
|
||||
const exhausted = record.maxUses > 0 && record.useCount >= record.maxUses;
|
||||
return {
|
||||
id: record.id,
|
||||
target: formatTeamSpeakTarget({ host: record.targetHost, port: record.targetPort }),
|
||||
channel: record.channel,
|
||||
expiresAt: record.expiresAt,
|
||||
maxUses: record.maxUses,
|
||||
useCount: record.useCount,
|
||||
createdAt: record.createdAt,
|
||||
revokedAt: record.revokedAt,
|
||||
status: record.revokedAt ? "revoked" : expired ? "expired" : exhausted ? "exhausted" : "active",
|
||||
};
|
||||
}
|
||||
|
||||
private toSettingsUpdate(settings: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
return {
|
||||
siteName: settings.siteName,
|
||||
@@ -229,6 +315,10 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
function hashInviteToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
|
||||
Reference in new issue
Block a user