diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d2f49e..0b6a5d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer. ### Added - Optional WebRTC audio transport for deployments that need lower and more stable realtime voice latency. -- WebRTC configuration through environment variables, including the public host and a bounded UDP port range. +- WebRTC configuration in the administrator console, including the public host and a bounded UDP port range. - Migrated the TeamSpeak integration to the maintained `EchoSixHIYA/teamspeak-js` fork, including live directory snapshots and member/channel synchronization. ### Changed diff --git a/README.md b/README.md index 056c191..e8dd9b4 100644 --- a/README.md +++ b/README.md @@ -197,18 +197,9 @@ WebSpeak 的 HTTP 端口固定为 `3040`,TeamSpeak 默认语音端口为 `9987 #### 可选 WebRTC 语音传输 -`v0.1.3` 提供实验性的 WebRTC 语音通道,默认关闭。它适合已经能够为 WebSpeak 发布一段 UDP 端口范围的部署;普通 Docker 部署无需额外配置,继续使用默认语音链路即可。 +`v0.1.3` 提供实验性的 WebRTC 语音通道,默认关闭。管理员登录 `/admin`,打开“服务器”页面的“WebRTC 语音”卡片即可启用,并填写浏览器可访问的公网地址与 UDP 端口范围;保存后对新语音会话生效。 -启用时设置: - -```bash -WEBSPEAK_WEBRTC=true -WEBSPEAK_WEBRTC_PUBLIC_HOST=<公网 IP 或可解析的公网主机名> -WEBSPEAK_WEBRTC_UDP_START=40000 -WEBSPEAK_WEBRTC_UDP_END=40099 -``` - -同时需要将 `40000-40099/udp` 发布到 WebSpeak 容器。若网络或浏览器不支持 WebRTC,客户端会自动回退到兼容性语音链路。 +Docker、服务器防火墙和云安全组仍需发布、放行管理员配置的 UDP 端口范围。普通 Docker 部署不启用 WebRTC 时无需额外配置,继续使用默认语音链路即可。若网络或浏览器不支持 WebRTC,客户端会自动回退到兼容性语音链路。 ### 数据与安全边界 @@ -482,18 +473,9 @@ Device labels are controlled by the browser permission model. The first device s #### Optional WebRTC audio transport -`v0.1.3` includes an experimental WebRTC audio path that is disabled by default. It is intended for deployments that can publish a UDP port range for WebSpeak; a normal Docker deployment needs no extra configuration and continues to use the default voice path. +`v0.1.3` includes an experimental WebRTC audio path that is disabled by default. An administrator can enable it from `/admin` → “Server” → “WebRTC audio”, then enter the public address reachable by browsers and the UDP port range. Saved settings apply to new voice sessions. -Set these variables when enabling it: - -```bash -WEBSPEAK_WEBRTC=true -WEBSPEAK_WEBRTC_PUBLIC_HOST= -WEBSPEAK_WEBRTC_UDP_START=40000 -WEBSPEAK_WEBRTC_UDP_END=40099 -``` - -Publish `40000-40099/udp` to the WebSpeak container as well. If WebRTC is unavailable because of the network or browser, the client automatically falls back to the compatibility voice path. +The configured UDP range still needs to be published and allowed in Docker, the server firewall, and the cloud security group. A standard Docker deployment needs no extra configuration while WebRTC is disabled and continues to use the default voice path. If WebRTC is unavailable because of the network or browser, the client automatically falls back to the compatibility voice path. ### Data and Security Boundary diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index 1c17636..0675812 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -332,6 +332,10 @@ function readSettingsInput(body: Record): AdminSettingsInput { accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never, siteName: readString(body, "siteName", 80), welcomeText: readOptionalString(body, "welcomeText", 500), + webRtcEnabled: body.webRtcEnabled === true, + webRtcPublicHost: readOptionalString(body, "webRtcPublicHost", 253), + webRtcUdpStart: readOptionalNumber(body, "webRtcUdpStart", 40000), + webRtcUdpEnd: readOptionalNumber(body, "webRtcUdpEnd", 40099), }; } diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.ts index 72defb7..10e4bf8 100644 --- a/src/admin/admin-service.ts +++ b/src/admin/admin-service.ts @@ -7,6 +7,9 @@ import { type AccessMode, type ManagedInviteRecord, type SettingsUpdate, WebSpea 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"; +import type { WebRtcAudioOptions } from "../server/webrtc-audio.js"; + +const MAX_WEBRTC_UDP_PORTS = 100; export interface AdminSettingsInput { target: string; @@ -15,6 +18,10 @@ export interface AdminSettingsInput { accessMode: AccessMode; siteName: string; welcomeText: string; + webRtcEnabled: boolean; + webRtcPublicHost: string; + webRtcUdpStart: number; + webRtcUdpEnd: number; } export interface ConnectionPolicy { @@ -108,11 +115,24 @@ export class AdminService { lastTestAt: settings.lastTestAt, lastTestLatencyMs: settings.lastTestLatencyMs, lastTestError: settings.lastTestError, + webRtcEnabled: settings.webRtcEnabled, + webRtcPublicHost: settings.webRtcPublicHost, + webRtcUdpStart: settings.webRtcUdpStart, + webRtcUdpEnd: settings.webRtcUdpEnd, internalPort: 3040, updatedAt: settings.updatedAt, }; } + getWebRtcAudioOptions(): WebRtcAudioOptions { + const settings = this.database.getSettings(); + return { + enabled: settings.webRtcEnabled, + ...(settings.webRtcPublicHost ? { publicHost: settings.webRtcPublicHost } : {}), + icePortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd], + }; + } + updateSettings(input: AdminSettingsInput): void { const current = this.database.getSettings(); const settings = this.normalizeSettings(input, current); @@ -252,6 +272,21 @@ export class AdminService { if (input.accessMode !== "fixed" && input.accessMode !== "open") { throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid"); } + if (typeof input.webRtcEnabled !== "boolean") { + throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid"); + } + const webRtcPublicHost = input.webRtcPublicHost.trim(); + if (webRtcPublicHost.length > 253 || /[\s/\\]/.test(webRtcPublicHost)) { + throw new AdminInputError("INVALID_WEBRTC_HOST", "WebRTC public host is invalid"); + } + if ( + !Number.isInteger(input.webRtcUdpStart) || input.webRtcUdpStart < 1 || input.webRtcUdpStart > 65_535 + || !Number.isInteger(input.webRtcUdpEnd) || input.webRtcUdpEnd < 1 || input.webRtcUdpEnd > 65_535 + || input.webRtcUdpStart > input.webRtcUdpEnd + || input.webRtcUdpEnd - input.webRtcUdpStart + 1 > MAX_WEBRTC_UDP_PORTS + ) { + throw new AdminInputError("INVALID_WEBRTC_PORTS", "WebRTC UDP port range is invalid"); + } let encryptedPassword = current.tsPasswordEncrypted; const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace"); @@ -264,6 +299,10 @@ export class AdminService { tsHost: target.host, tsPort: target.port, tsPasswordEncrypted: encryptedPassword, + webRtcEnabled: input.webRtcEnabled, + webRtcPublicHost, + webRtcUdpStart: input.webRtcUdpStart, + webRtcUdpEnd: input.webRtcUdpEnd, }; } @@ -292,6 +331,10 @@ export class AdminService { tsHost: settings.tsHost, tsPort: settings.tsPort, tsPasswordEncrypted: settings.tsPasswordEncrypted, + webRtcEnabled: settings.webRtcEnabled, + webRtcPublicHost: settings.webRtcPublicHost, + webRtcUdpStart: settings.webRtcUdpStart, + webRtcUdpEnd: settings.webRtcUdpEnd, }; } @@ -307,6 +350,10 @@ export class AdminService { tsHost: legacy.tsHost, tsPort: legacy.tsPort, tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null, + webRtcEnabled: current.webRtcEnabled, + webRtcPublicHost: current.webRtcPublicHost, + webRtcUdpStart: current.webRtcUdpStart, + webRtcUdpEnd: current.webRtcUdpEnd, }, "LEGACY_CONFIG_IMPORTED"); this.database.setMeta("legacy_config_imported", "1"); this.database.setMeta("legacy_import_notice_pending", "1"); diff --git a/src/index.ts b/src/index.ts index 8faa161..e962de1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,6 @@ import { WebSpeakDatabase } from "./persistence/database.js"; import { loadOrCreateMasterSecret } from "./security/master-secret.js"; import { AdminService } from "./admin/admin-service.js"; import { JoinTicketStore } from "./server/join-ticket.js"; -import type { WebRtcAudioOptions } from "./server/webrtc-audio.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.resolve(__dirname, ".."); @@ -20,7 +19,6 @@ const DATA_DIR = process.env.WEBSPEAK_DATA_DIR?.trim() || path.join(ROOT_DIR, "d const LOG_DIR = path.join(DATA_DIR, "logs"); const STATIC_DIR = path.join(ROOT_DIR, "web", "dist"); const APP_VERSION = readPackageVersion(); -const WEBRTC_OPTIONS = readWebRtcOptions(); async function main() { const logger = createLogger(LOG_DIR); @@ -50,7 +48,7 @@ async function main() { certDir: hasCert ? CERT_DIR : undefined, voiceBridgeOptions: { joinTickets, - webRtc: WEBRTC_OPTIONS, + webRtc: () => adminService.getWebRtcAudioOptions(), }, adminService, logger, @@ -86,23 +84,6 @@ function removeObsoleteBootstrapFile(): void { } } -function readWebRtcOptions(): WebRtcAudioOptions { - const enabled = /^(1|true|yes)$/i.test(process.env.WEBSPEAK_WEBRTC?.trim() ?? ""); - const publicHost = process.env.WEBSPEAK_WEBRTC_PUBLIC_HOST?.trim() || undefined; - const start = parsePort(process.env.WEBSPEAK_WEBRTC_UDP_START, 40_000); - const end = parsePort(process.env.WEBSPEAK_WEBRTC_UDP_END, 40_099); - return { - enabled, - ...(publicHost ? { publicHost } : {}), - ...(start <= end ? { icePortRange: [start, end] as [number, number] } : {}), - }; -} - -function parsePort(value: string | undefined, fallback: number): number { - const port = Number(value); - return Number.isInteger(port) && port >= 1 && port <= 65_535 ? port : fallback; -} - main().catch((err) => { console.error("Fatal error:", err); process.exit(1); diff --git a/src/persistence/database.ts b/src/persistence/database.ts index 8e0517a..c94e25e 100644 --- a/src/persistence/database.ts +++ b/src/persistence/database.ts @@ -5,7 +5,7 @@ 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 = 2; +export const DATABASE_SCHEMA_VERSION = 3; export type AccessMode = "fixed" | "open"; export interface PersistedSettings { @@ -19,6 +19,10 @@ export interface PersistedSettings { lastTestAt: string | null; lastTestLatencyMs: number | null; lastTestError: string | null; + webRtcEnabled: boolean; + webRtcPublicHost: string; + webRtcUdpStart: number; + webRtcUdpEnd: number; updatedAt: string; } @@ -29,6 +33,10 @@ export interface SettingsUpdate { tsHost: string; tsPort: number; tsPasswordEncrypted: string | null; + webRtcEnabled: boolean; + webRtcPublicHost: string; + webRtcUdpStart: number; + webRtcUdpEnd: number; } export interface ManagedInviteRecord { @@ -70,6 +78,10 @@ interface SettingsRow extends Record { last_test_at: string | null; last_test_latency_ms: number | null; last_test_error: string | null; + webrtc_enabled: number; + webrtc_public_host: string; + webrtc_udp_start: number; + webrtc_udp_end: number; updated_at: string; } @@ -140,6 +152,10 @@ export class WebSpeakDatabase { lastTestAt: row.last_test_at, lastTestLatencyMs: row.last_test_latency_ms, lastTestError: row.last_test_error, + webRtcEnabled: row.webrtc_enabled === 1, + webRtcPublicHost: row.webrtc_public_host, + webRtcUdpStart: row.webrtc_udp_start, + webRtcUdpEnd: row.webrtc_udp_end, updatedAt: row.updated_at, }; } @@ -349,6 +365,18 @@ export class WebSpeakDatabase { `); this.database.exec("PRAGMA user_version = 2"); }); + version = 2; + } + if (version === 2) { + this.transaction(() => { + this.database.exec(` + ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1)); + ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT ''; + ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535); + ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535); + `); + this.database.exec("PRAGMA user_version = 3"); + }); } } @@ -356,7 +384,8 @@ export class WebSpeakDatabase { this.database.prepare( `UPDATE settings SET site_name = ?, welcome_text = ?, access_mode = ?, ts_host = ?, ts_port = ?, - ts_password_encrypted = ?, updated_at = ? + ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, + webrtc_udp_start = ?, webrtc_udp_end = ?, updated_at = ? WHERE id = 1`, ).run( settings.siteName, @@ -365,6 +394,10 @@ export class WebSpeakDatabase { settings.tsHost, settings.tsPort, settings.tsPasswordEncrypted, + settings.webRtcEnabled ? 1 : 0, + settings.webRtcPublicHost, + settings.webRtcUdpStart, + settings.webRtcUdpEnd, now, ); } diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 30a8932..394162b 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -30,7 +30,7 @@ const MAX_SERVER_AUDIO_BUFFERED_BYTES = 4_096; export interface VoiceBridgeOptions { joinTickets: JoinTicketStore; - webRtc?: WebRtcAudioOptions; + webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions); } export interface AdminSessionSummary { @@ -267,7 +267,7 @@ export class VoiceBridge { serverEventLog: entry!.eventLog, whisperTargetIds: [...entry!.whisperTargetIds], whisperActive: entry!.whisperActive, - webrtcAvailable: this.options.webRtc?.enabled === true, + webrtcAvailable: this.getWebRtcOptions()?.enabled === true, ...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}), }); sendJson({ type: "channelList", channels: entry!.channelTree }); @@ -515,7 +515,7 @@ export class VoiceBridge { const rawMessage = typeof data === "string" ? data : data.toString("utf-8"); const webRtcOffer = parseWebRtcOffer(rawMessage); if (webRtcOffer) { - if (this.options.webRtc?.enabled !== true) { + if (this.getWebRtcOptions()?.enabled !== true) { sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用"); return; } @@ -683,6 +683,11 @@ export class VoiceBridge { return token ? this.options.joinTickets.consume(token) : null; } + private getWebRtcOptions(): WebRtcAudioOptions | undefined { + const configured = this.options.webRtc; + return typeof configured === "function" ? configured() : configured; + } + private async handleWebRtcOffer( entry: WebClientEntry, offer: WebRtcSessionDescription, @@ -692,7 +697,7 @@ export class VoiceBridge { try { await entry.webrtc.close(); } catch { /* replace a retried offer */ } entry.webrtc = null; } - const config = this.options.webRtc; + const config = this.getWebRtcOptions(); if (!config?.enabled) return; const peer = new WebRtcAudioSession({ connectionId: entry.id, diff --git a/test/admin-api.test.ts b/test/admin-api.test.ts index 88ac3e5..40700a8 100644 --- a/test/admin-api.test.ts +++ b/test/admin-api.test.ts @@ -111,11 +111,19 @@ test("admin API requires the default password to be changed before administratio accessMode: "open", siteName: "Changed", welcomeText: "Open access", + webRtcEnabled: true, + webRtcPublicHost: "voice.example.com", + webRtcUdpStart: 40000, + webRtcUdpEnd: 40099, }, }); assert.equal(saved.body.ok, true); assert.equal(saved.body.settings.accessMode, "open"); assert.equal(saved.body.settings.hasPassword, false); + assert.equal(saved.body.settings.webRtcEnabled, true); + assert.equal(saved.body.settings.webRtcPublicHost, "voice.example.com"); + assert.equal(saved.body.settings.webRtcUdpStart, 40000); + assert.equal(saved.body.settings.webRtcUdpEnd, 40099); const invite = await request(origin, "/api/admin/invites", { method: "POST", @@ -137,7 +145,7 @@ test("admin API requires the default password to be changed before administratio const sessions = await request(origin, "/api/admin/sessions", { cookie }); assert.deepEqual(sessions.body.sessions, []); const diagnostics = await request(origin, "/api/admin/diagnostics", { cookie }); - assert.equal(diagnostics.body.database.schemaVersion, 2); + assert.equal(diagnostics.body.database.schemaVersion, 3); assert.equal("target" in diagnostics.body.teamSpeak, true); assert.equal("protocol" in diagnostics.body.teamSpeak, false); diff --git a/test/admin-service.test.ts b/test/admin-service.test.ts index 3604e38..5200256 100644 --- a/test/admin-service.test.ts +++ b/test/admin-service.test.ts @@ -54,6 +54,10 @@ test("legacy config imports once, seeds the default admin, and allows password r accessMode: "open", siteName: "Open WebSpeak", welcomeText: "Public gateway", + webRtcEnabled: true, + webRtcPublicHost: "voice.example.com", + webRtcUdpStart: 40000, + webRtcUdpEnd: 40099, }); const publicConfig = service.getPublicConfig(); assert.equal(publicConfig.target, "public.example.com:9987"); @@ -61,6 +65,8 @@ test("legacy config imports once, seeds the default admin, and allows password r assert.equal("serverPassword" in service.getAdminSettings(), false); assert.equal(service.getAdminSettings().hasPassword, true); assert.equal(service.getConnectionPolicy().serverPassword, "replacement-secret"); + assert.equal(service.getAdminSettings().webRtcEnabled, true); + assert.deepEqual(service.getWebRtcAudioOptions(), { enabled: true, publicHost: "voice.example.com", icePortRange: [40000, 40099] }); database.close(); }); @@ -106,7 +112,7 @@ test("managed invites are opaque, bounded, revocable, and included in database b assert.ok(backup.length > 100); database.close(); const reopened = new WebSpeakDatabase(path.join(directory, "webspeak.db")); - assert.equal(reopened.schemaVersion, 2); + assert.equal(reopened.schemaVersion, 3); assert.equal(reopened.listManagedInvites().length, 3); reopened.close(); }); diff --git a/test/persistence.test.ts b/test/persistence.test.ts index 6562f43..0d98617 100644 --- a/test/persistence.test.ts +++ b/test/persistence.test.ts @@ -23,6 +23,10 @@ test("SQLite persistence initializes schema and stores the single admin/settings tsHost: "voice.example.com", tsPort: 9988, tsPasswordEncrypted: "v1:ciphertext", + webRtcEnabled: true, + webRtcPublicHost: "voice.example.com", + webRtcUdpStart: 40000, + webRtcUdpEnd: 40099, }); assert.equal(database.hasAdmin(), true); assert.equal(database.getAdminCredential()?.hash, credential.hash); @@ -37,6 +41,10 @@ test("SQLite persistence initializes schema and stores the single admin/settings lastTestAt: null, lastTestLatencyMs: null, lastTestError: null, + webRtcEnabled: true, + webRtcPublicHost: "voice.example.com", + webRtcUdpStart: 40000, + webRtcUdpEnd: 40099, updatedAt: database.getSettings().updatedAt, }); assert.equal(database.recentAudit()[0]?.event, "ADMIN_INITIALIZED"); @@ -48,7 +56,7 @@ test("SQLite persistence initializes schema and stores the single admin/settings reopened.close(); }); -test("SQLite schema v1 upgrades to v2 with a migration copy", () => { +test("SQLite schema v1 upgrades to v3 with a migration copy", () => { const directory = mkdtempSync(path.join(tmpdir(), "webspeak-db-migration-")); const dbPath = path.join(directory, "webspeak.db"); const legacy = new DatabaseSync(dbPath); @@ -68,7 +76,10 @@ test("SQLite schema v1 upgrades to v2 with a migration copy", () => { legacy.close(); const upgraded = new WebSpeakDatabase(dbPath); - assert.equal(upgraded.schemaVersion, 2); + assert.equal(upgraded.schemaVersion, 3); + assert.equal(upgraded.getSettings().webRtcEnabled, false); + assert.equal(upgraded.getSettings().webRtcUdpStart, 40000); + assert.equal(upgraded.getSettings().webRtcUdpEnd, 40099); assert.equal(upgraded.listManagedInvites().length, 0); assert.equal(existsSync(`${dbPath}.schema-1.bak`), true); upgraded.close(); diff --git a/web/src/views/AdminView.vue b/web/src/views/AdminView.vue index 98e3ec4..d60fb2c 100644 --- a/web/src/views/AdminView.vue +++ b/web/src/views/AdminView.vue @@ -36,6 +36,7 @@

{{ tr('teamSpeakTarget') }}

{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}{{ testResultText }}

{{ tr('accessAndIdentity') }}

{{ tr('accessMode') }}
+

{{ tr('webrtcSettings') }}

{{ tr('webrtcLead') }}

{{ tr('webrtcUdpHint') }}
{{ tr('webrtcApplyHint') }}

{{ tr('runtimeFacts') }}

{{ tr('lastTest') }}
{{ formatDate(serverForm.lastTestAt) }}
{{ tr('latency') }}
{{ serverForm.lastTestLatencyMs == null ? '—' : `${serverForm.lastTestLatencyMs} ms` }}
{{ tr('internalPort') }}
3040
@@ -91,7 +92,7 @@ const newPassword = ref(""); const confirmNewPassword = ref(""); const testResult = ref(null); -const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", lastTestAt: null as string | null, lastTestLatencyMs: null as number | null }); +const serverForm = reactive({ address: "", port: "9987", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", webRtcEnabled: false, webRtcPublicHost: "", webRtcUdpStart: "40000", webRtcUdpEnd: "40099", lastTestAt: null as string | null, lastTestLatencyMs: null as number | null }); const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false }); interface AdminSession { id: string; nickname: string; target: string; state: string; createdAt: string; ageSeconds: number; tsClientId: number | null; channelId: string | null; memberCount: number } interface ManagedInvite { id: string; target: string; channel: string; expiresAt: string; maxUses: number; useCount: number; createdAt: string; revokedAt: string | null; status: "active" | "expired" | "exhausted" | "revoked" } @@ -150,6 +151,17 @@ const copy = { connectionReady: "连接成功", connectionFailed: "连接失败", accessAndIdentity: "访问与站点信息", + webrtcSettings: "WebRTC 语音", + webrtcLead: "可选的低延迟语音传输,默认关闭;保存后对新语音会话生效。", + webrtcEnabled: "启用 WebRTC", + webrtcEnabledLead: "使用实时语音通道;浏览器或网络不支持时自动回退。", + webrtcPublicHost: "WebRTC 公网地址", + webrtcPublicHostPlaceholder: "例如:203.0.113.20 或 voice.example.com", + webrtcPublicHostHint: "填写浏览器能够访问到的 WebSpeak 公网地址,不要填写容器内网地址。", + webrtcUdpStart: "UDP 起始端口", + webrtcUdpEnd: "UDP 结束端口", + webrtcUdpHint: "需在 Docker、服务器防火墙和云安全组中放行此范围。", + webrtcApplyHint: "保存后对新连接生效;已连接用户重新进入语音空间后使用新设置。", accessMode: "访客访问模式", fixedMode: "仅限此 TeamSpeak 服务器", fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。", @@ -186,6 +198,8 @@ const copy = { invalidPassword: "管理员密码错误。", rateLimited: "尝试次数过多,请稍后再试。", requestFailed: "请求失败,请检查输入后重试。", + invalidWebRtcHost: "WebRTC 公网地址格式无效。", + invalidWebRtcPorts: "WebRTC UDP 端口范围无效;请填写 1–65535 且最多 100 个连续端口。", loginEvent: "管理员登录成功", logoutEvent: "管理员退出登录", settingsEvent: "服务器设置已更新", @@ -291,6 +305,17 @@ const copy = { connectionReady: "Connection ready", connectionFailed: "Connection failed", accessAndIdentity: "Access and site identity", + webrtcSettings: "WebRTC audio", + webrtcLead: "Optional low-latency voice transport, disabled by default and applied to new voice sessions.", + webrtcEnabled: "Enable WebRTC", + webrtcEnabledLead: "Use the realtime voice path; unsupported browsers or networks fall back automatically.", + webrtcPublicHost: "WebRTC public host", + webrtcPublicHostPlaceholder: "e.g. 203.0.113.20 or voice.example.com", + webrtcPublicHostHint: "Use a public WebSpeak address reachable by browsers, not the container's private address.", + webrtcUdpStart: "UDP start port", + webrtcUdpEnd: "UDP end port", + webrtcUdpHint: "Publish and allow this range in Docker, the server firewall, and the cloud security group.", + webrtcApplyHint: "Saved settings apply to new connections; connected users must re-enter the voice space.", accessMode: "Guest access mode", fixedMode: "Only this TeamSpeak server", fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.", @@ -327,6 +352,8 @@ const copy = { invalidPassword: "The admin password is incorrect.", rateLimited: "Too many attempts. Try again later.", requestFailed: "The request failed. Check the fields and try again.", + invalidWebRtcHost: "The WebRTC public host is invalid.", + invalidWebRtcPorts: "The WebRTC UDP range is invalid. Use 1–65535 and no more than 100 consecutive ports.", loginEvent: "Administrator signed in", logoutEvent: "Administrator signed out", settingsEvent: "Server settings changed", @@ -402,7 +429,7 @@ async function login() { submitting.value = true; errorMessage.value = ""; try { async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } } async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); } -async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep" }); } +async function loadServerSettings() { const value = await getJson("/api/admin/server"); const target = splitTeamSpeakTarget(value.target); Object.assign(serverForm, value, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: value.webRtcEnabled === true, webRtcPublicHost: String(value.webRtcPublicHost || ""), webRtcUdpStart: String(value.webRtcUdpStart ?? 40000), webRtcUdpEnd: String(value.webRtcUdpEnd ?? 40099) }); } async function loadOperations() { operationsLoading.value = true; try { const [sessions, invites, diagnostics, logs, audit] = await Promise.all([getJson("/api/admin/sessions"), getJson("/api/admin/invites"), getJson("/api/admin/diagnostics"), getJson("/api/admin/logs?limit=100"), getJson("/api/admin/audit?limit=50")]); operations.sessions = Array.isArray(sessions.sessions) ? sessions.sessions : []; operations.invites = Array.isArray(invites.invites) ? invites.invites : []; operations.diagnostics = { version: String(diagnostics.gateway?.version || ""), node: String(diagnostics.gateway?.node || ""), platform: String(diagnostics.gateway?.platform || ""), arch: String(diagnostics.gateway?.arch || ""), schemaVersion: Number(diagnostics.database?.schemaVersion || 0), createdSessions: Number(diagnostics.sessions?.created || 0) }; operations.logs = { available: Boolean(logs.available), entries: Array.isArray(logs.entries) ? logs.entries : [] }; operations.audit = Array.isArray(audit.events) ? audit.events : []; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { operationsLoading.value = false; } } async function terminateSession(session: AdminSession) { if (!window.confirm(tr('confirmTerminate', { nickname: session.nickname }))) return; terminatingSession.value = session.id; errorMessage.value = ""; try { await sendJson(`/api/admin/sessions/${encodeURIComponent(session.id)}/terminate`, "POST", {}); await Promise.all([loadOperations(), loadOverview()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { terminatingSession.value = ""; } } async function createInvite() { submitting.value = true; errorMessage.value = ""; createdInvite.value = null; try { const result = await sendJson("/api/admin/invites", "POST", { channel: inviteForm.channel, expiresInHours: inviteForm.expiresInHours, maxUses: inviteForm.maxUses }); if (typeof result.token !== "string") throw new Error("INVITE_CREATE_FAILED"); createdInvite.value = { token: result.token, link: `${location.origin}/?invite=${encodeURIComponent(result.token)}` }; inviteForm.channel = ""; await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } @@ -410,9 +437,9 @@ async function revokeInvite(invite: ManagedInvite) { if (!window.confirm(tr('con async function copyInviteLink() { if (!createdInvite.value) return; try { await navigator.clipboard.writeText(createdInvite.value.link); showOperationNotice(tr('copiedLink')); } catch { errorMessage.value = tr('operationFailed'); } } function showOperationNotice(message: string) { errorMessage.value = message; window.setTimeout(() => { if (errorMessage.value === message) errorMessage.value = ""; }, 2200); } async function downloadBackup() { try { const response = await fetch("/api/admin/backup", { headers: { accept: "application/octet-stream" } }); if (!response.ok) throw new Error("BACKUP_FAILED"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url; anchor.download = `webspeak-backup-${new Date().toISOString().slice(0, 10)}.db`; anchor.click(); URL.revokeObjectURL(url); await loadOperations(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } } -async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep" }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } +async function saveServerSettings() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/server", "PUT", serverPayload()); const target = splitTeamSpeakTarget(result.settings?.target); Object.assign(serverForm, result.settings, { address: target.address, port: target.port, serverPassword: "", passwordAction: "keep", webRtcEnabled: result.settings.webRtcEnabled === true, webRtcPublicHost: String(result.settings.webRtcPublicHost || ""), webRtcUdpStart: String(result.settings.webRtcUdpStart ?? 40000), webRtcUdpEnd: String(result.settings.webRtcUdpEnd ?? 40099) }); await loadOverview(); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function testServerConnection() { await runTest("/api/admin/server/test", { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction }); if (testResult.value?.ok) { await loadOverview(); serverForm.lastTestAt = new Date().toISOString(); serverForm.lastTestLatencyMs = testResult.value.latencyMs ?? null; } } -function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText }; } +function serverPayload() { return { target: combineTeamSpeakTarget(serverForm.address, serverForm.port), serverPassword: serverForm.passwordAction === "replace" ? serverForm.serverPassword : undefined, passwordAction: serverForm.passwordAction, accessMode: serverForm.accessMode, siteName: serverForm.siteName, welcomeText: serverForm.welcomeText, webRtcEnabled: serverForm.webRtcEnabled, webRtcPublicHost: serverForm.webRtcPublicHost, webRtcUdpStart: Number(serverForm.webRtcUdpStart), webRtcUdpEnd: Number(serverForm.webRtcUdpEnd) }; } async function runTest(url: string, body: Record) { testing.value = true; errorMessage.value = ""; testResult.value = null; try { testResult.value = await sendJson(url, "POST", body, url.includes("/server/test")); } catch (error) { testResult.value = { ok: false, code: (error as ApiError).code }; } finally { testing.value = false; } } async function dismissLegacyNotice() { await sendJson("/api/admin/legacy-import/dismiss", "POST", {}); overview.legacyConfigImported = false; } function toggleLanguage() { language.value = language.value === "zh" ? "en" : "zh"; localStorage.setItem("webspeak:language", language.value); } @@ -424,7 +451,7 @@ function sessionStateLabel(state: string) { const names: Record = { active: "active", expired: "expired", exhausted: "exhausted", revoked: "revoked" }; return tr(names[status]); } function formatContext(context: Record) { return Object.entries(context).map(([key, value]) => `${key}=${value}`).join(" · "); } function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : "Connection test failed"; const names: Record = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); } -function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); const probe: Record = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); } +function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); if (code === "INVALID_WEBRTC_HOST") return tr('invalidWebRtcHost'); if (code === "INVALID_WEBRTC_PORTS") return tr('invalidWebRtcPorts'); const probe: Record = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); } interface ApiError extends Error { code?: string } async function getJson(url: string): Promise { const response = await fetch(url, { headers: { accept: "application/json" } }); return parseResponse(response); } @@ -450,6 +477,7 @@ async function parseResponse(response: Response) { const value = await response. @media(max-width:850px){.operations-grid{grid-template-columns:1fr}.operation-wide{overflow:hidden}} @media(max-width:520px){.operation-card{padding:18px}.table-wrap{margin-left:-18px;margin-right:-18px;margin-bottom:-18px}.invite-form-grid,.diagnostic-list{grid-template-columns:1fr}.generated-link{display:grid}.invite-row{align-items:flex-start;flex-direction:column}.invite-row-meta{width:100%;justify-content:flex-end}.lower-operations{margin-top:14px}} .target-fields{display:grid;grid-template-columns:minmax(0,1fr) 132px;gap:12px} +.webrtc-card .card-help{margin:5px 0 0;color:#7e8c88;font-size:10px;line-height:1.5}.webrtc-fields{display:grid;gap:14px}.toggle-choice{margin:0}.webrtc-card>.field-help{margin-top:-8px}.webrtc-port-fields{grid-template-columns:1fr 1fr} @media(max-width:520px){.target-fields{grid-template-columns:1fr}} /* Keep administration inside the browser viewport. Long data sets scroll in