From 23e61c86b3c4d07132d987cc62bfd8c9c09d175f Mon Sep 17 00:00:00 2001 From: Moepchi Date: Sat, 3 Oct 2026 00:58:22 +0000 Subject: [PATCH] feat: optional TURN relay for screen streams TURN_URLS on the gateway is handed to the browser in "hello" and added to the STUN defaults for both watching and publishing. With TURN_SECRET (coturn's use-auth-secret) each socket gets its own credential valid for 24 h; static TURN_USERNAME/TURN_CREDENTIAL work too but are public to every visitor. Also moves GATEWAY_FEATURES above the runtime-config comment it had split. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- README.md | 1 + gateway/src/index.ts | 26 +++++++++++++++++++++----- web/src/App.tsx | 7 ++++++- web/src/publish.ts | 8 +------- web/src/stream.ts | 2 +- 5 files changed, 30 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 5996e9f..47a31f7 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ All optional; add them under `environment:` in your compose override next to `PO | `STORE_ADMIN_TOKEN` | unset | Bearer token for moderation. New submissions wait as "pending" until approved on the review page at `/api/store/admin` (enter the token there); the token holder's own submissions and the reserved author name(s) skip the queue. Without it, nothing ever gets published. Submitted CSS is also checked server-side: no `@import`/`@font-face`, no external `url()` — only inline `data:` images. | | `ALLOWED_SERVERS` | unset (any server) | Comma-separated list of server addresses this gateway is allowed to connect to (e.g. `ts.example.com,*.example.net`). A port is matched separately from the host, so listing `ts.example.com` allows any port on it. An entry starting with `*.` matches any subdomain (`*.example.com` allows `ts.example.com`, not `example.com` itself - list that separately too if it should also be reachable). Locks a self-hosted instance down to specific server(s) instead of acting as a general "connect anywhere" client; a rejected `connect` gets an error back before any connector process is even spawned. | | `ALLOW_PRIVATE_TARGETS` | off | By default the gateway refuses to connect to private/internal addresses (loopback, `10.x`, `192.168.x`, CGNAT, link-local, …), no matter how they were reached (IP, DNS, SRV, TSDNS, nickname, file-transfer redirect), so it can't be abused to probe the network it runs in. **If your TeamSpeak server is on the same LAN as the gateway, set this to `1`.** | +| `TURN_URLS` | unset | Comma-separated TURN URLs (e.g. `turn:turn.example.com:3478`) offered to browsers for screen streams, for viewers or publishers behind NATs where direct P2P fails. Pair with `TURN_SECRET` (coturn's `use-auth-secret`; each browser gets its own credential valid for 24 h) or with static `TURN_USERNAME` / `TURN_CREDENTIAL`, which every visitor can read. | | `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. | | `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `300` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. | | `TRUST_PROXY` | off | Set to `1` when the gateway is **only** reachable through a reverse proxy/tunnel (e.g. cloudflared): per-IP limits then use `CF-Connecting-IP` / `X-Forwarded-For` instead of the proxy's own address. Don't set it on a directly exposed gateway - clients could then spoof their IP. | diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 9d4b448..43a7d8c 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -2,7 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht import { createServer as createSecureServer } from "node:https"; import { readFileSync } from "node:fs"; import { readFile } from "node:fs/promises"; -import { timingSafeEqual } from "node:crypto"; +import { createHmac, timingSafeEqual } from "node:crypto"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WebSocketServer, type WebSocket } from "ws"; @@ -111,13 +111,29 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); const WEB_DIST = process.env.WEB_DIST ?? path.resolve(__dirname, "../../web/dist"); const SERVE_STATIC = process.env.WEB_STATIC !== "0"; +// Sent to every browser in the "hello" message on socket open; see there. +const GATEWAY_FEATURES = ["clientVolume"]; + +// Optional TURN relay for screen streams, also handed out in "hello". With +// TURN_SECRET (coturn's use-auth-secret) every socket gets its own credential, +// valid for a day; TURN_USERNAME/TURN_CREDENTIAL are static and so readable by +// every visitor. ponytail: a socket open longer than a day hands an expired +// credential to a stream started after that; reconnecting fixes it. +const TURN_URLS = (process.env.TURN_URLS ?? "").split(",").map((u) => u.trim()).filter(Boolean); +function turnServers() { + if (!TURN_URLS.length) return undefined; + const secret = process.env.TURN_SECRET; + if (!secret) { + return [{ urls: TURN_URLS, username: process.env.TURN_USERNAME, credential: process.env.TURN_CREDENTIAL }]; + } + const username = `${Math.floor(Date.now() / 1000) + 24 * 3600}:webspeak3`; + return [{ urls: TURN_URLS, username, credential: createHmac("sha1", secret).update(username).digest("base64") }]; +} + // Runtime counterpart of the web build's VITE_DEFAULT_SERVER/_CHANNEL (GitHub // issue #12): set on the container, these end up in the served index.html as // tags the client reads at startup, so changing them needs no rebuild. // Meta tags rather than an inline script, which CONTENT_SECURITY_POLICY forbids. -// Sent to every browser in the "hello" message on socket open; see there. -const GATEWAY_FEATURES = ["clientVolume"]; - const RUNTIME_CONFIG_META = Object.entries({ "webspeak3-default-server": process.env.DEFAULT_SERVER, "webspeak3-default-channel": process.env.DEFAULT_CHANNEL, @@ -635,7 +651,7 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { // pulled, so the browser must not assume a feature exists just because it // knows about it. A gateway without "hello" (before v0.15) supports the // v0.14 feature set, streaming included; anything newer gets a name here. - socket.send(JSON.stringify({ type: "hello", features: GATEWAY_FEATURES })); + socket.send(JSON.stringify({ type: "hello", features: GATEWAY_FEATURES, iceServers: turnServers() })); heartbeats.set(socket, { isAlive: true }); socket.on("pong", () => { diff --git a/web/src/App.tsx b/web/src/App.tsx index 2403e70..d6e9a6f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -34,7 +34,7 @@ import { type PublishState, type StreamPublishOptions, } from "./publish"; -import { StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; +import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { SOUND_EVENTS, @@ -6424,6 +6424,8 @@ function AppInner() { // What the gateway announced in its "hello" (gateway/src/index.ts). Empty for // a gateway older than the handshake, so a feature newer than it stays hidden. const [gatewayFeatures, setGatewayFeatures] = useState>(new Set()); + // TURN relay the gateway offers for screen streams (TURN_URLS), if any. + const [turnServers, setTurnServers] = useState([]); // Terms of use, own-hosted instance only (see IS_OWN_HOSTED_INSTANCE): shown // mandatorily on first visit, reopenable any time from the menu afterwards. const [tosOpen, setTosOpen] = useState(false); @@ -7290,6 +7292,7 @@ function AppInner() { } if (data.type === "hello") { setGatewayFeatures(new Set(Array.isArray(data.features) ? data.features : [])); + setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []); return; } @@ -8989,6 +8992,7 @@ function AppInner() { const viewer = new StreamViewer(info.id, info.clientId, { send: (message) => socketRef.current?.send(JSON.stringify(message)), onTrack: setStreamMedia, + iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers], onStateChange: setStreamState, onError: setStreamError, onClosed: () => { @@ -9042,6 +9046,7 @@ function AppInner() { onViewersChange: setPublishViewers, onPendingChange: setPublishPending, onError: setPublishError, + iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers], }); publisherRef.current = publisher; void publisher.start(options); diff --git a/web/src/publish.ts b/web/src/publish.ts index 28eeba4..82bd30d 100644 --- a/web/src/publish.ts +++ b/web/src/publish.ts @@ -15,7 +15,7 @@ // TS6's P2P mode is a mesh: there is no SFU in the path, so every viewer gets // its own peer connection and its own copy of the encoded media. -import type { StreamEvent } from "./stream"; +import { DEFAULT_ICE_SERVERS, type StreamEvent } from "./stream"; // The three enums below are read straight out of TS6's own UI bundle // (main.js), not inferred - see ts6-re/findings §10. @@ -44,12 +44,6 @@ export const StreamMode = { SFU: 2, } as const; -const DEFAULT_ICE_SERVERS: RTCIceServer[] = [ - { urls: "stun:turn.teamspeak.com:3478" }, - { urls: "stun:turn2.teamspeak.com:3478" }, - { urls: "stun:stun.l.google.com:19302" }, -]; - export interface StreamPublishOptions { name: string; /** Send the capture's audio track too, when the source has one. */ diff --git a/web/src/stream.ts b/web/src/stream.ts index 57474a5..e59fd27 100644 --- a/web/src/stream.ts +++ b/web/src/stream.ts @@ -62,7 +62,7 @@ export interface StreamViewerOptions { iceServers?: RTCIceServer[]; } -const DEFAULT_ICE_SERVERS: RTCIceServer[] = [ +export const DEFAULT_ICE_SERVERS: RTCIceServer[] = [ { urls: "stun:turn.teamspeak.com:3478" }, { urls: "stun:turn2.teamspeak.com:3478" }, { urls: "stun:stun.l.google.com:19302" },