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);
|
||||
|
||||
@@ -41,6 +41,7 @@ async function main() {
|
||||
const webServer = createWebServer({
|
||||
port: APP_PORT,
|
||||
version: APP_VERSION,
|
||||
logFile: path.join(LOG_DIR, "webspeak.log"),
|
||||
staticDir: STATIC_DIR,
|
||||
certDir: hasCert ? CERT_DIR : undefined,
|
||||
voiceBridgeOptions: {
|
||||
|
||||
+157
-9
@@ -1,10 +1,11 @@
|
||||
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
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 const DATABASE_SCHEMA_VERSION = 2;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -30,6 +31,34 @@ export interface SettingsUpdate {
|
||||
tsPasswordEncrypted: string | null;
|
||||
}
|
||||
|
||||
export interface ManagedInviteRecord {
|
||||
id: string;
|
||||
tokenHash: string;
|
||||
targetHost: string;
|
||||
targetPort: number;
|
||||
serverPasswordEncrypted: string | null;
|
||||
channel: string;
|
||||
expiresAt: string;
|
||||
maxUses: number;
|
||||
useCount: number;
|
||||
createdAt: string;
|
||||
revokedAt: string | null;
|
||||
}
|
||||
|
||||
interface ManagedInviteRow extends Record<string, unknown> {
|
||||
id: string;
|
||||
token_hash: string;
|
||||
target_host: string;
|
||||
target_port: number;
|
||||
server_password_encrypted: string | null;
|
||||
channel: string;
|
||||
expires_at: string;
|
||||
max_uses: number;
|
||||
use_count: number;
|
||||
created_at: string;
|
||||
revoked_at: string | null;
|
||||
}
|
||||
|
||||
interface SettingsRow extends Record<string, unknown> {
|
||||
site_name: string;
|
||||
welcome_text: string;
|
||||
@@ -141,6 +170,87 @@ export class WebSpeakDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
createManagedInvite(record: Omit<ManagedInviteRecord, "createdAt" | "revokedAt" | "useCount">): ManagedInviteRecord {
|
||||
const now = new Date().toISOString();
|
||||
this.transaction(() => {
|
||||
this.database.prepare(
|
||||
`INSERT INTO managed_invites (
|
||||
id, token_hash, target_host, target_port, server_password_encrypted,
|
||||
channel, expires_at, max_uses, use_count, created_at, revoked_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NULL)`,
|
||||
).run(
|
||||
record.id,
|
||||
record.tokenHash,
|
||||
record.targetHost,
|
||||
record.targetPort,
|
||||
record.serverPasswordEncrypted,
|
||||
record.channel,
|
||||
record.expiresAt,
|
||||
record.maxUses,
|
||||
now,
|
||||
);
|
||||
});
|
||||
return { ...record, useCount: 0, createdAt: now, revokedAt: null };
|
||||
}
|
||||
|
||||
listManagedInvites(): ManagedInviteRecord[] {
|
||||
const rows = this.database.prepare(
|
||||
"SELECT * FROM managed_invites ORDER BY created_at DESC",
|
||||
).all() as ManagedInviteRow[];
|
||||
return rows.map(mapManagedInviteRow);
|
||||
}
|
||||
|
||||
revokeManagedInvite(id: string): boolean {
|
||||
const result = this.database.prepare(
|
||||
"UPDATE managed_invites SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
|
||||
).run(new Date().toISOString(), id) as { changes?: number | bigint };
|
||||
return Number(result.changes ?? 0) === 1;
|
||||
}
|
||||
|
||||
consumeManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
|
||||
const nowIso = new Date(now).toISOString();
|
||||
this.database.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
const row = this.database.prepare(
|
||||
`SELECT * FROM managed_invites
|
||||
WHERE token_hash = ?
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > ?
|
||||
AND (max_uses = 0 OR use_count < max_uses)`,
|
||||
).get(tokenHash, nowIso) as ManagedInviteRow | undefined;
|
||||
if (!row) {
|
||||
this.database.exec("COMMIT");
|
||||
return null;
|
||||
}
|
||||
const result = this.database.prepare(
|
||||
`UPDATE managed_invites
|
||||
SET use_count = use_count + 1
|
||||
WHERE id = ? AND revoked_at IS NULL AND expires_at > ?
|
||||
AND (max_uses = 0 OR use_count < max_uses)`,
|
||||
).run(row.id, nowIso) as { changes?: number | bigint };
|
||||
if (Number(result.changes ?? 0) !== 1) {
|
||||
this.database.exec("COMMIT");
|
||||
return null;
|
||||
}
|
||||
this.database.exec("COMMIT");
|
||||
return { ...mapManagedInviteRow(row), useCount: row.use_count + 1 };
|
||||
} catch (error) {
|
||||
this.database.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
exportBackup(): Buffer {
|
||||
const exportPath = `${this.path}.export-${randomBytes(8).toString("hex")}.db`;
|
||||
try {
|
||||
const escapedPath = exportPath.replaceAll("'", "''");
|
||||
this.database.exec(`VACUUM INTO '${escapedPath}'`);
|
||||
return readFileSync(exportPath);
|
||||
} finally {
|
||||
try { unlinkSync(exportPath); } catch { /* best effort cleanup */ }
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -165,16 +275,15 @@ export class WebSpeakDatabase {
|
||||
}
|
||||
|
||||
private migrate(existed: boolean): void {
|
||||
const version = this.schemaVersion;
|
||||
let 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) {
|
||||
if (version === 0) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE metadata (
|
||||
key TEXT PRIMARY KEY,
|
||||
@@ -215,9 +324,32 @@ export class WebSpeakDatabase {
|
||||
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}`);
|
||||
}
|
||||
});
|
||||
this.database.exec("PRAGMA user_version = 1");
|
||||
});
|
||||
version = 1;
|
||||
}
|
||||
if (version === 1) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
CREATE TABLE managed_invites (
|
||||
id TEXT PRIMARY KEY,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
target_host TEXT NOT NULL,
|
||||
target_port INTEGER NOT NULL CHECK (target_port BETWEEN 1 AND 65535),
|
||||
server_password_encrypted TEXT,
|
||||
channel TEXT NOT NULL DEFAULT '',
|
||||
expires_at TEXT NOT NULL,
|
||||
max_uses INTEGER NOT NULL CHECK (max_uses >= 0),
|
||||
use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0),
|
||||
created_at TEXT NOT NULL,
|
||||
revoked_at TEXT
|
||||
);
|
||||
CREATE INDEX managed_invites_token_idx ON managed_invites(token_hash);
|
||||
CREATE INDEX managed_invites_expiry_idx ON managed_invites(expires_at);
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 2");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private writeSettings(settings: SettingsUpdate, now: string): void {
|
||||
@@ -254,3 +386,19 @@ export class WebSpeakDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function mapManagedInviteRow(row: ManagedInviteRow): ManagedInviteRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
tokenHash: row.token_hash,
|
||||
targetHost: row.target_host,
|
||||
targetPort: row.target_port,
|
||||
serverPasswordEncrypted: row.server_password_encrypted,
|
||||
channel: row.channel,
|
||||
expiresAt: row.expires_at,
|
||||
maxUses: row.max_uses,
|
||||
useCount: row.use_count,
|
||||
createdAt: row.created_at,
|
||||
revokedAt: row.revoked_at,
|
||||
};
|
||||
}
|
||||
+29
-14
@@ -15,6 +15,7 @@ import { identityFromString } from "@honeybbq/teamspeak-client";
|
||||
export interface WebServerOptions {
|
||||
port: number;
|
||||
version?: string;
|
||||
logFile?: string;
|
||||
staticDir?: string;
|
||||
certDir?: string; // path to cert.pem + key.pem for HTTPS
|
||||
voiceBridgeOptions: VoiceBridgeOptions;
|
||||
@@ -71,7 +72,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
}
|
||||
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) : "";
|
||||
const requestedChannel = typeof body.channel === "string" ? body.channel.trim().slice(0, 100) : "";
|
||||
const inviteToken = typeof body.invite === "string" ? body.invite.trim().slice(0, 128) : "";
|
||||
const requestedIdentity = typeof body.identity === "string" && body.identity.length <= 8192 ? body.identity : "";
|
||||
let identity: string | undefined;
|
||||
if (requestedIdentity) {
|
||||
@@ -88,21 +90,29 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
}
|
||||
|
||||
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" });
|
||||
const managedInvite = inviteToken ? options.adminService.consumeManagedInvite(inviteToken) : null;
|
||||
if (inviteToken && !managedInvite) {
|
||||
response.status(400).json({ ok: false, code: "INVITE_INVALID" });
|
||||
return;
|
||||
}
|
||||
let target = managedInvite?.target ?? policy.defaultTarget;
|
||||
let serverPassword = managedInvite?.serverPassword ?? policy.serverPassword;
|
||||
const channel = requestedChannel || managedInvite?.channel || "";
|
||||
if (!managedInvite) {
|
||||
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,
|
||||
@@ -120,6 +130,11 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
logger,
|
||||
getActiveSessions: () => voiceBridge.getActiveCount(),
|
||||
getPeakSessions: () => voiceBridge.getPeakCount(),
|
||||
getCreatedSessions: () => voiceBridge.getCreatedCount(),
|
||||
getSessionSummaries: () => voiceBridge.getSessionSummaries(),
|
||||
terminateSession: (id) => voiceBridge.terminateSession(id),
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
}));
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ export type SessionTeardownReason =
|
||||
| "teamSpeak-disconnect"
|
||||
| "teamSpeak-connect-failed"
|
||||
| "heartbeat-timeout"
|
||||
| "admin-terminated"
|
||||
| "gateway-shutdown";
|
||||
|
||||
const ALLOWED_TRANSITIONS: Record<ConnectionState, readonly ConnectionState[]> = {
|
||||
|
||||
@@ -24,6 +24,18 @@ export interface VoiceBridgeOptions {
|
||||
joinTickets: JoinTicketStore;
|
||||
}
|
||||
|
||||
export interface AdminSessionSummary {
|
||||
id: string;
|
||||
nickname: string;
|
||||
target: string;
|
||||
state: string;
|
||||
createdAt: string;
|
||||
ageSeconds: number;
|
||||
tsClientId: number | null;
|
||||
channelId: string | null;
|
||||
memberCount: number;
|
||||
}
|
||||
|
||||
interface ChannelMember {
|
||||
id: number;
|
||||
nickname: string;
|
||||
@@ -501,6 +513,38 @@ export class VoiceBridge {
|
||||
return this.sessionManager.createdCount;
|
||||
}
|
||||
|
||||
getSessionSummaries(): AdminSessionSummary[] {
|
||||
const now = Date.now();
|
||||
return [...this.entries.values()]
|
||||
.sort((left, right) => left.session.createdAt - right.session.createdAt)
|
||||
.map((entry) => {
|
||||
let tsClientId: number | null = null;
|
||||
let channelId: string | null = null;
|
||||
try { tsClientId = entry.tsClient.getClientId() || null; } catch { /* still connecting */ }
|
||||
try {
|
||||
const id = entry.tsClient.getChannelId();
|
||||
channelId = id === 0n ? null : id.toString();
|
||||
} catch { /* still connecting */ }
|
||||
return {
|
||||
id: entry.id,
|
||||
nickname: entry.nickname,
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
state: entry.session.state,
|
||||
createdAt: new Date(entry.session.createdAt).toISOString(),
|
||||
ageSeconds: Math.max(0, Math.floor((now - entry.session.createdAt) / 1000)),
|
||||
tsClientId,
|
||||
channelId,
|
||||
memberCount: entry.members.size,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async terminateSession(entryId: string): Promise<boolean> {
|
||||
if (!this.entries.has(entryId)) return false;
|
||||
await this.sessionManager.teardown(entryId, "admin-terminated");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async teardown(entryId: string, reason: SessionTeardownReason): Promise<void> {
|
||||
await this.sessionManager.teardown(entryId, reason);
|
||||
}
|
||||
|
||||
@@ -63,3 +63,35 @@ test("legacy config imports once, seeds the default admin, and allows password r
|
||||
assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret");
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("managed invites are opaque, bounded, revocable, and included in database backups", async () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-invites-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const service = new AdminService(
|
||||
database,
|
||||
loadOrCreateMasterSecret(path.join(directory, "master.key")),
|
||||
silentLogger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
);
|
||||
await service.initialize();
|
||||
|
||||
const created = service.createManagedInvite({ channel: "Lobby", expiresInHours: 2, maxUses: 1 });
|
||||
assert.match(created.token, /^[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(created.invite.channel, "Lobby");
|
||||
assert.equal(created.invite.status, "active");
|
||||
assert.equal("token" in created.invite, false);
|
||||
|
||||
const consumed = service.consumeManagedInvite(created.token);
|
||||
assert.deepEqual(consumed?.target, { host: "127.0.0.1", port: 9987 });
|
||||
assert.equal(consumed?.channel, "Lobby");
|
||||
assert.equal(service.consumeManagedInvite(created.token), null);
|
||||
assert.equal(service.listManagedInvites()[0]?.status, "exhausted");
|
||||
|
||||
const backup = database.exportBackup();
|
||||
assert.ok(backup.length > 100);
|
||||
database.close();
|
||||
const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
assert.equal(reopened.schemaVersion, 2);
|
||||
assert.equal(reopened.listManagedInvites().length, 1);
|
||||
reopened.close();
|
||||
});
|
||||
@@ -552,7 +552,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
}
|
||||
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false): void {
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
|
||||
disconnect(true);
|
||||
lastConnection = { target, channel, nickname, serverPassword, ...(identity ? { identity } : {}), rememberIdentity };
|
||||
identityMaterial.value = identity;
|
||||
@@ -563,15 +563,15 @@ export function useVoiceWebSocket() {
|
||||
state.reconnecting = false;
|
||||
state.reconnectAttempt = 0;
|
||||
state.reconnectFailed = false;
|
||||
void openTicketedConnection(sequence, target, channel, nickname, serverPassword);
|
||||
void openTicketedConnection(sequence, target, channel, nickname, serverPassword, inviteToken);
|
||||
}
|
||||
|
||||
async function openTicketedConnection(sequence: number, target: string, channel: string, nickname: string, serverPassword: string): Promise<void> {
|
||||
async function openTicketedConnection(sequence: number, target: string, channel: string, nickname: string, serverPassword: string, inviteToken: string): Promise<void> {
|
||||
try {
|
||||
const response = await fetch("/api/join-ticket", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", accept: "application/json" },
|
||||
body: JSON.stringify({ target, nickname, channel, serverPassword, ...(lastConnection?.rememberIdentity && lastConnection.identity ? { identity: lastConnection.identity } : {}), ...(lastConnection?.rememberIdentity ? { rememberIdentity: true } : {}) }),
|
||||
body: JSON.stringify({ target, nickname, channel, serverPassword, ...(inviteToken ? { invite: inviteToken } : {}), ...(lastConnection?.rememberIdentity && lastConnection.identity ? { identity: lastConnection.identity } : {}), ...(lastConnection?.rememberIdentity ? { rememberIdentity: true } : {}) }),
|
||||
});
|
||||
const result = await response.json().catch(() => ({})) as { ticket?: unknown; code?: unknown };
|
||||
if (!response.ok || typeof result.ticket !== "string") {
|
||||
@@ -631,6 +631,7 @@ export function useVoiceWebSocket() {
|
||||
if (code === "NOT_INITIALIZED") return "WebSpeak 尚未完成首次配置";
|
||||
if (code === "TARGET_NOT_ALLOWED") return "此 TeamSpeak 服务器地址不允许连接";
|
||||
if (code === "INVALID_NICKNAME") return "请输入有效的昵称";
|
||||
if (code === "INVITE_INVALID") return "邀请链接已失效或已被撤销";
|
||||
return "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
}
|
||||
|
||||
|
||||
@@ -306,6 +306,7 @@ const {
|
||||
|
||||
const query = new URLSearchParams(location.search);
|
||||
const initialChannel = query.get("channel") ?? "";
|
||||
const inviteToken = query.get("invite") ?? "";
|
||||
const nickname = ref(localStorage.getItem("webspeak:nickname") ?? "");
|
||||
const channel = ref(initialChannel);
|
||||
const serverAddress = ref(initialServerAddress());
|
||||
@@ -1061,7 +1062,7 @@ function doConnect() {
|
||||
serverAddress.value = serverAddress.value.trim();
|
||||
}
|
||||
selectedChannelId.value = "";
|
||||
connect(serverAddress.value, channel.value.trim(), nickname.value, accessMode.value === "open" ? serverPassword.value : "", rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value);
|
||||
connect(serverAddress.value, channel.value.trim(), nickname.value, accessMode.value === "open" ? serverPassword.value : "", rememberIdentity.value ? identityMaterial.value : "", rememberIdentity.value, inviteToken);
|
||||
}
|
||||
|
||||
function doDisconnect() {
|
||||
|
||||
Reference in new issue
Block a user