diff --git a/README.md b/README.md index a1be848..72d6bfe 100644 --- a/README.md +++ b/README.md @@ -193,7 +193,7 @@ docker compose pull docker compose up -d ``` -默认网页端口为 `3040/TCP`,数据保存在 Docker volume `webspeak-data`。查看状态: +Compose 使用 host 网络模式,WebSpeak 直接监听宿主机的 `3040/TCP`,并直接使用宿主机的 WebRTC UDP 端口范围;因此这里不再使用 Docker 端口映射。数据保存在 Docker volume `webspeak-data`。若反向代理也运行在容器中,上游应指向宿主机地址,而不是 `webspeak:3040`。查看状态: ```bash docker compose ps @@ -254,8 +254,8 @@ npm start | --- | --- | | 浏览器 | 建议使用最新版 Chrome、Edge 或其他支持 WebRTC 的现代浏览器。麦克风和屏幕音频通常要求 HTTPS 安全上下文。 | | TeamSpeak 网络 | WebSpeak 主机必须能够访问目标 TeamSpeak 服务器。目标默认语音端口为 `9987`,也可在网页中填写其他端口。 | -| Web 服务网络 | 服务默认监听 `3040/TCP`。公网部署建议通过 HTTPS 反向代理提供网页和 WebSocket。 | -| WebRTC | 默认使用 `40000–40099/UDP`。Docker Compose 已发布该范围,但云安全组和主机防火墙仍需放行;自定义范围时也要同步修改 Docker 端口映射。启用 WebRTC 后需先关闭它才能修改端口范围。 | +| Web 服务网络 | Docker Compose 使用 host 网络模式,服务直接监听宿主机 `3040/TCP`。公网部署建议通过 HTTPS 反向代理提供网页和 WebSocket。 | +| WebRTC | 默认使用 `40000–40099/UDP`,host 网络模式会直接使用宿主机端口;云安全组和主机防火墙仍需放行。自定义范围时只需同步放行该范围。启用 WebRTC 后需先关闭它才能修改端口范围。 | | 身份保持 | 同一浏览器身份同时只能保持一条活动连接。需要并行连接时,请取消第二条连接的“保持身份”,或使用另一个浏览器/浏览器配置文件。 | | 伴奏 | 仅桌面端提供,并要求启用 WebRTC。选择窗口或标签页时必须同时勾选共享音频;浏览器无法直接任意读取本地应用音频。 | | 数据 | Docker 数据位于 `webspeak-data` volume;发布包和源码运行的数据位于程序目录的 `data/`。升级或迁移前建议从管理后台导出数据库备份。 | @@ -361,7 +361,7 @@ docker compose pull docker compose up -d ``` -The web service uses `3040/TCP` by default. Persistent data is stored in the `webspeak-data` Docker volume. Check the service with: +Docker Compose uses host networking: WebSpeak listens directly on the host at `3040/TCP` and uses the host's WebRTC UDP range without Docker port mappings. Persistent data is stored in the `webspeak-data` Docker volume. If the reverse proxy also runs in Docker, point it to the host address rather than `webspeak:3040`. Check the service with: ```bash docker compose ps @@ -422,8 +422,8 @@ Building `@discordjs/opus` requires Python, Make, and a C/C++ toolchain. For dev | --- | --- | | Browser | Use a current Chrome, Edge, or another modern browser with WebRTC support. Microphone and shared-screen audio normally require an HTTPS secure context. | | TeamSpeak network | The WebSpeak host must be able to reach the target TeamSpeak server. The default voice port is `9987`, and other ports can be entered in the web interface. | -| Web network | The service listens on `3040/TCP` by default. Public deployments should expose the page and WebSocket through an HTTPS reverse proxy. | -| WebRTC | The default range is `40000–40099/UDP`. Docker Compose publishes it, but the cloud security group and host firewall must also allow it. A custom range must also be reflected in Docker port mappings. Disable WebRTC before changing the range. | +| Web network | Docker Compose uses host networking and the service listens directly on the host at `3040/TCP`. Public deployments should expose the page and WebSocket through an HTTPS reverse proxy. | +| WebRTC | The default range is `40000–40099/UDP`; host networking uses the host ports directly. The cloud security group and host firewall must still allow the range. For a custom range, only the firewall rules need to be updated. Disable WebRTC before changing the range. | | Remembered identity | One browser identity can hold only one active remembered connection at a time. For parallel connections, disable **Remember identity** on the second connection or use another browser/profile. | | Accompaniment | Desktop only and requires WebRTC. When selecting a window or tab, enable audio sharing as well. Browsers cannot arbitrarily capture every local application's audio. | | Data | Docker data is stored in the `webspeak-data` volume. Release packages and source installs store data in the program directory's `data/` folder. Export a database backup from the admin console before upgrades or migration. | @@ -526,7 +526,7 @@ docker compose pull docker compose up -d ``` -WebSpeak ist standardmäßig unter `3040/TCP` erreichbar. Die persistenten Daten liegen im Docker-Volume `webspeak-data`. Für WebRTC muss zusätzlich der im Adminbereich angezeigte UDP-Portbereich freigegeben werden. +Docker Compose verwendet das Host-Netzwerk: WebSpeak lauscht direkt auf dem Host unter `3040/TCP` und nutzt den WebRTC-UDP-Bereich ohne Docker-Portzuordnung. Die persistenten Daten liegen im Docker-Volume `webspeak-data`. Läuft der Reverse Proxy ebenfalls in Docker, muss er auf die Host-Adresse statt auf `webspeak:3040` zeigen. Für WebRTC muss zusätzlich der im Adminbereich angezeigte UDP-Portbereich freigegeben werden. #### Release-Pakete @@ -544,7 +544,7 @@ Lade das passende Paket von [GitHub Releases](https://github.com/EchoSixHIYA/Web | --- | --- | | Browser | Aktuelles Chrome, Edge oder ein moderner WebRTC-fähiger Browser wird empfohlen. Für Mikrofon- und Bildschirm-Audio ist normalerweise HTTPS erforderlich. | | TeamSpeak-Netzwerk | Der WebSpeak-Host muss den Zielserver erreichen können. Der Standard-Sprachport ist `9987`; andere Ports können im Webinterface eingetragen werden. | -| WebRTC | Der Standardbereich ist `40000–40099/UDP`. Firewall, Sicherheitsgruppe und Docker-Portzuordnung müssen den gesamten Bereich erlauben. | +| WebRTC | Der Standardbereich ist `40000–40099/UDP`; durch das Host-Netzwerk werden die Host-Ports direkt verwendet. Firewall und Sicherheitsgruppe müssen den gesamten Bereich erlauben. | | Gespeicherte Identität | Eine Browseridentität kann nur eine aktive gespeicherte Verbindung gleichzeitig halten. Für parallele Verbindungen die Option deaktivieren oder ein anderes Browserprofil verwenden. | | Begleitton | Nur auf Desktop-Browsern verfügbar und WebRTC erforderlich. Bei der Freigabe eines Fensters oder Tabs muss auch Audio freigegeben werden. | | Selbsthosting | WebSpeak ist kein offizielles TeamSpeak-Produkt. Namen und Marken gehören den jeweiligen Rechteinhabern. | diff --git a/docker-compose.yml b/docker-compose.yml index 66a88fd..a17ef85 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,9 +3,9 @@ services: image: ${WEBSPEAK_IMAGE:-ghcr.io/echosixhiya/webspeak:latest} pull_policy: missing restart: unless-stopped - ports: - - "${WEBSPEAK_PORT:-3040}:3040" - - "40000-40099:40000-40099/udp" + # WebSpeak needs to reach a TeamSpeak server running on the same host. + # Host networking also exposes the configured WebRTC UDP range directly. + network_mode: host volumes: - webspeak-data:/data diff --git a/src/server/server.ts b/src/server/server.ts index aab3e7e..5537fdc 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -109,10 +109,12 @@ export function createWebServer(options: WebServerOptions): WebServer { 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) : ""; - } + // Open mode must protect the gateway even when a user submits the + // same address configured as the administrator's default target. + // The default target only controls which server is prefilled; it is + // not a trust boundary and must not bypass SSRF protection. + target = await resolveSafeOpenTarget(target); + if (!isDefault) serverPassword = typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : ""; } } catch { response.status(400).json({ ok: false, code: "TARGET_NOT_ALLOWED" }); diff --git a/src/server/teamspeak-adapter.ts b/src/server/teamspeak-adapter.ts index 0543969..762a0c0 100644 --- a/src/server/teamspeak-adapter.ts +++ b/src/server/teamspeak-adapter.ts @@ -57,6 +57,8 @@ export class EndpointProtocolCache { export const endpointProtocolCache = new EndpointProtocolCache(); +const TEAM_SPEAK_CONNECT_TIMEOUT_MS = 15_000; + export interface TeamSpeakAdapterOptions { target: TeamSpeakTarget; nickname: string; @@ -109,8 +111,9 @@ export class TeamSpeakAdapter { this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter"); try { await this.client.connect(); - await this.client.waitConnected(); + await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS)); } catch (error: unknown) { + await this.client.disconnect().catch(() => undefined); throw normalizeTeamSpeakError(error); } diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 68b9de4..8871c88 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -404,8 +404,12 @@ const whisperPttActive = ref(false); const performancePanelOpen = ref(false); const performanceRunning = ref(false); const performanceSamples = ref([]); +const performanceProbeResults = ref>([]); const performanceAttempts = ref(0); -const performanceProbeCount = 4; +const PERFORMANCE_INTERVAL_MS = 3_000; +const PERFORMANCE_WINDOW_SIZE = 20; +let performanceTimer: ReturnType | null = null; +let performanceMonitorGeneration = 0; let toastTimer: ReturnType | undefined; type Language = "zh" | "en" | "de"; @@ -668,7 +672,7 @@ const translations: Record> = { gatewayToTeamSpeak: "WebSpeak → TeamSpeak", packetLoss: "丢包", measuring: "正在测量…", - measureComplete: "已完成 4 次探测", + measureComplete: "持续监测中(每 3 秒更新)", measureNow: "立即测量", measureUnavailable: "连接后可测量", langSwitch: "English", @@ -925,7 +929,7 @@ const translations: Record> = { gatewayToTeamSpeak: "WebSpeak → TeamSpeak", packetLoss: "Packet loss", measuring: "Measuring…", - measureComplete: "4 probes complete", + measureComplete: "Monitoring continuously (updates every 3s)", measureNow: "Measure now", measureUnavailable: "Available after connecting", langSwitch: "中文", @@ -1185,7 +1189,7 @@ translations.de = { gatewayToTeamSpeak: "WebSpeak → TeamSpeak", packetLoss: "Paketverlust", measuring: "Wird gemessen…", - measureComplete: "4 Messungen abgeschlossen", + measureComplete: "Laufende Messung (alle 3 Sekunden)", measureNow: "Jetzt messen", measureUnavailable: "Nach der Verbindung verfügbar", langSwitch: "中文", @@ -1354,14 +1358,15 @@ const median = (values: number[]) => { }; const performanceStats = computed(() => { const samples = performanceSamples.value; + const attempts = performanceAttempts.value; const gatewaySamples = samples.map((sample) => sample.browserRttMs); const teamSpeakSamples = samples.filter((sample) => sample.teamSpeakReachable && sample.teamSpeakLatencyMs != null).map((sample) => sample.teamSpeakLatencyMs as number); return { gatewayLatencyMs: median(gatewaySamples), - gatewayLossPercent: performanceAttempts.value >= performanceProbeCount ? Math.round(((performanceProbeCount - samples.length) / performanceProbeCount) * 100) : null, + gatewayLossPercent: attempts > 0 ? Math.round(((attempts - samples.length) / attempts) * 100) : null, teamSpeakLatencyMs: median(teamSpeakSamples), - teamSpeakLossPercent: performanceAttempts.value >= performanceProbeCount ? Math.round(((performanceProbeCount - teamSpeakSamples.length) / performanceProbeCount) * 100) : null, - ready: performanceAttempts.value >= performanceProbeCount, + teamSpeakLossPercent: attempts > 0 ? Math.round(((attempts - teamSpeakSamples.length) / attempts) * 100) : null, + ready: attempts > 0, }; }); @@ -1424,7 +1429,10 @@ watch([rememberIdentity, identityMaterial], ([remember, material]) => { if (!remember && material) identityMaterial.value = ""; }); watch(() => voiceState.connected, (connected) => { - if (!connected) return; + if (!connected) { + stopPerformanceMonitoring(); + return; + } playNotification("connected"); const address = currentServerTarget(); if (!address) return; @@ -1437,31 +1445,52 @@ watch(() => voiceState.connected, (connected) => { ...(channel.value.trim() ? { lastChannelHint: { name: channel.value.trim() } } : {}), }; void recordRecentServer(recent).then(() => listRecentServers().then((items) => { recentServers.value = items; })); + if (performancePanelOpen.value) startPerformanceMonitoring(); }); function togglePerformancePanel() { performancePanelOpen.value = !performancePanelOpen.value; - if (performancePanelOpen.value && !performanceRunning.value && !performanceStats.value.ready) void runPerformanceProbe(); + if (performancePanelOpen.value) startPerformanceMonitoring(); + else stopPerformanceMonitoring(); } -function waitForPerformanceProbe(ms: number): Promise { - return new Promise((resolve) => window.setTimeout(resolve, ms)); -} - -async function runPerformanceProbe() { - if (performanceRunning.value || !voiceState.connected) return; - performanceRunning.value = true; +function resetPerformanceSamples(): void { + performanceProbeResults.value = []; performanceSamples.value = []; performanceAttempts.value = 0; +} + +function startPerformanceMonitoring(): void { + if (performanceTimer || !voiceState.connected) return; + resetPerformanceSamples(); + const generation = ++performanceMonitorGeneration; + void runPerformanceProbe(generation); + performanceTimer = window.setInterval(() => { + void runPerformanceProbe(generation); + }, PERFORMANCE_INTERVAL_MS); +} + +function stopPerformanceMonitoring(): void { + if (performanceTimer) { + clearInterval(performanceTimer); + performanceTimer = null; + } + performanceMonitorGeneration += 1; + performanceRunning.value = false; +} + +async function runPerformanceProbe(generation = performanceMonitorGeneration): Promise { + if (performanceRunning.value || !voiceState.connected || !performancePanelOpen.value) return; + performanceRunning.value = true; try { - for (let index = 0; index < performanceProbeCount; index += 1) { - const sample = await measureLatency(); - if (sample) performanceSamples.value.push(sample); - performanceAttempts.value += 1; - if (index < performanceProbeCount - 1) await waitForPerformanceProbe(220); - } + const sample = await measureLatency(); + if (generation !== performanceMonitorGeneration || !performancePanelOpen.value) return; + performanceProbeResults.value.push(sample); + if (performanceProbeResults.value.length > PERFORMANCE_WINDOW_SIZE) performanceProbeResults.value.shift(); + performanceAttempts.value = performanceProbeResults.value.length; + performanceSamples.value = performanceProbeResults.value.filter((result): result is LatencyProbeResult => result !== null); } finally { - performanceRunning.value = false; + if (generation === performanceMonitorGeneration) performanceRunning.value = false; } } watch(() => voiceState.reconnecting, (reconnecting, wasReconnecting) => { @@ -1509,6 +1538,7 @@ onMounted(() => { viewportMediaQuery.addEventListener?.("change", viewportChangeHandler); }); onUnmounted(() => { + stopPerformanceMonitoring(); disconnect(); if (deviceChangeHandler) navigator.mediaDevices?.removeEventListener("devicechange", deviceChangeHandler); if (viewportMediaQuery && viewportChangeHandler) viewportMediaQuery.removeEventListener?.("change", viewportChangeHandler);