feat: add STUN candidates for screen sharing

This commit is contained in:
illusia committed 2026-09-21 22:24:24 +08:00
1 parent de8f6a11c9
commit 8ed3e788be
10 files changed
+174 -8

No files matched your search

+10
View File
@@ -62,6 +62,16 @@ WebRTC verwendet für Browser-Sprache einen Echtzeit-Medienpfad und ermöglicht
Der Portbereich ist bei aktiviertem WebRTC gesperrt. Zum Ändern WebRTC zuerst deaktivieren und speichern, danach die Firewall-Regeln anpassen. Für öffentliche Bereitstellungen ist HTTPS erforderlich.
### ICE-Kandidaten für Bildschirmfreigabe
Die Medien der Bildschirmfreigabe versuchen weiterhin eine direkte Browser-zu-Browser-Verbindung; WebSpeak leitet nur die Signalisierung weiter. Standardmäßig werden die öffentlichen TeamSpeak-STUN-Dienste zur Ermittlung öffentlicher Kandidaten verwendet. STUN überträgt keine Medien. Ein autorisierter externer TURN-Dienst kann über `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` als JSON-Array konfiguriert werden, zum Beispiel:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
Mit TURN kann die Medienübertragung diesen externen Dienst verwenden, aber niemals das WebSpeak-Gateway. Ohne TURN werden nur direkte ICE-Pfade und STUN verwendet.
### 2. Relay-Modus
Ein Relay hilft, wenn ein TeamSpeak-Server Verbindungen aus einer anderen Region ablehnt oder der direkte Weg instabil ist. Es ist kein VPN, sondern leitet nur den TeamSpeak-Verkehr der aktuellen WebSpeak-Sitzung weiter.
+10
View File
@@ -62,6 +62,16 @@ WebRTC moves browser voice to a realtime media path and also enables desktop acc
The port range is locked while WebRTC is enabled. Disable and save WebRTC before changing it, then update the firewall rules. Public deployments also need HTTPS.
### Screen-share ICE candidates
Screen-share media still prefers a direct browser-to-browser path; WebSpeak only relays negotiation signaling. By default it uses TeamSpeak's public STUN services to discover server-reflexive candidates; STUN does not carry media. If the deployment has an authorized external TURN service, set `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` before starting WebSpeak with a JSON array, for example:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
With TURN configured, media may use that external TURN service but never the WebSpeak gateway; without it, only direct ICE paths and STUN are used.
### 2. Relay mode
Use a relay when a TeamSpeak server rejects connections from another region or when the direct path is unstable. It is not a VPN: it forwards only the TeamSpeak traffic of the current WebSpeak session, while the visitor still chooses the target server in the web page.
+10
View File
@@ -58,6 +58,16 @@
**管理コンソール → サーバー → 詳細設定** で有効にします。無効の状態で UDP ポート範囲(初期値 `40000–40099`)を設定し、ファイアウォールで許可して保存してください。有効中は範囲がロックされ、新しい接続で WebRTC を使用します。非対応のブラウザは互換トランスポートに戻ります。公開サイトでは HTTPS が必要です。
### 画面共有の ICE 候補
画面共有のメディアは引き続きブラウザ間の直接接続を優先し、WebSpeak はシグナリングだけを中継します。初期状態では TeamSpeak の公開 STUN サービスで外部候補を検出します。STUN はメディアを運びません。認可済みの外部 TURN を使う場合は、起動前に `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` を JSON 配列で設定できます。
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
TURN を設定した場合、メディアは外部 TURN サービスを経由することがありますが、WebSpeak ゲートウェイは経由しません。未設定時は直接接続と STUN のみを使用します。
### 中継サーバー
中継は現在の WebSpeak セッションの TeamSpeak 通信だけを転送し、VPN ではありません。管理コンソールで複数のノードに名前、アドレス、トークンを設定すると、ユーザーは直接接続または中継を選択できます。中継モードは専用の転送サービスとして動作し、ゲスト画面や管理コンソールを提供しません。
+10
View File
@@ -58,6 +58,16 @@
Включается в **Панель администратора → Сервер → Расширенные настройки**. До включения задайте диапазон UDP-портов (по умолчанию `40000–40099`), откройте его в firewall и сохраните. При включённом WebRTC диапазон заблокирован; новые подключения используют WebRTC, а неподдерживаемые браузеры переходят на совместимый транспорт. Для публичного доступа нужен HTTPS.
### ICE для демонстрации экрана
Медиа демонстрации экрана по-прежнему предпочитает прямое соединение между браузерами; WebSpeak только передаёт сигнальные сообщения. По умолчанию используются публичные STUN-серверы TeamSpeak для поиска внешних кандидатов, STUN не передаёт медиаданные. Авторизованный внешний TURN можно задать через `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` в виде JSON-массива, например:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
При настроенном TURN медиа может идти через этот внешний сервис, но не через шлюз WebSpeak. Без TURN используются только прямые ICE-пути и STUN.
### Ретрансляторы
Ретранслятор передаёт только TeamSpeak-трафик текущей сессии и не является VPN. В панели администратора добавьте один или несколько узлов, задайте имя, адрес и токен. Пользователь сможет выбрать прямое подключение или настроенный ретранслятор. Режим ретранслятора запускается отдельно и не предоставляет страницу посетителя или панель администратора.
+10
View File
@@ -62,6 +62,16 @@ WebRTC 将浏览器语音切换到实时媒体通道,也支持桌面端伴奏
WebRTC 启用后端口范围会锁定。要修改端口,先关闭 WebRTC 并保存,再修改端口并同步防火墙规则。公网使用还需要 HTTPS。
### 屏幕共享的 ICE 候选
屏幕共享媒体仍优先走浏览器之间的直连,WebSpeak 只转发协商信令。默认使用 TeamSpeak 官方 STUN 服务发现公网候选地址;STUN 不承载媒体。若部署者有合规的外部 TURN 服务,可在启动 WebSpeak 前设置 `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS`,值为 JSON 数组,例如:
```json
[{"urls":"stun:turn.teamspeak.com:3478"},{"urls":"turns:turn.example.com:5349","username":"<username>","credential":"<credential>"}]
```
配置 TURN 后,媒体可能经过该外部 TURN 服务,但不会经过 WebSpeak 网关;未配置时只使用直连和 STUN。
### 2. 中继模式
中继适用于 TeamSpeak 拒绝境外连接或直连不稳定的情况。它不是 VPN,只转发当前 WebSpeak 会话的 TeamSpeak 数据;目标服务器仍由用户在网页中选择。
+15
View File
@@ -2,6 +2,7 @@ import path from "node:path";
import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -13,6 +14,7 @@ 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 SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
async function main() {
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
@@ -56,6 +58,7 @@ async function main() {
voiceBridgeOptions: {
joinTickets,
webRtc: () => adminService.getWebRtcAudioOptions(),
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
// The public gateway only uses the relay configuration explicitly
// saved in the admin console. Environment variables belong to the
// standalone relay process and must never make the relay option appear
@@ -123,6 +126,18 @@ function parseBoolean(value: string | undefined): boolean {
return value === "1" || value?.toLowerCase() === "true";
}
function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] {
const raw = value?.trim();
if (!raw) return normalizeScreenShareIceServers();
try {
const parsed: unknown = JSON.parse(raw);
return normalizeScreenShareIceServers(Array.isArray(parsed) ? parsed : undefined);
} catch {
// A simple comma/space-separated list is convenient for STUN-only setups.
return normalizeScreenShareIceServers(raw.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
}
}
main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
+59 -3
View File
@@ -2,11 +2,67 @@
* Screen-share signaling for browser peers and native TeamSpeak peers.
*
* Media never passes through this module. The gateway only authenticates the
* connected TeamSpeak session and relays SDP/ICE messages. The browser peers
* are deliberately created without STUN/TURN servers; a failed host-candidate
* connection is reported to the user instead of silently becoming a relay.
* connected TeamSpeak session and relays SDP/ICE messages. Browser peers use
* the configured ICE servers only for candidate discovery/negotiation; this
* module never handles the resulting media packets.
*/
export interface ScreenShareIceServer {
urls: string | string[];
username?: string;
credential?: string;
}
/** TeamSpeak's public ICE services are STUN-only, so media remains peer-to-peer. */
export const DEFAULT_SCREEN_SHARE_ICE_SERVERS: readonly ScreenShareIceServer[] = [
{ urls: "stun:turn.teamspeak.com:3478" },
{ urls: "stun:turn2.teamspeak.com:3478" },
];
const SCREEN_SHARE_ICE_URL_PATTERN = /^(?:stun|stuns|turn|turns):/i;
const MAX_ICE_SERVER_COUNT = 8;
const MAX_ICE_URL_LENGTH = 512;
const MAX_ICE_CREDENTIAL_LENGTH = 512;
/**
* Keep ICE configuration server-owned and bounded before exposing it to a
* browser. TURN is accepted only as an explicitly configured external server;
* the WebSpeak gateway is never inserted into this list.
*/
export function normalizeScreenShareIceServers(value?: readonly unknown[]): ScreenShareIceServer[] {
const source: readonly unknown[] = value ?? DEFAULT_SCREEN_SHARE_ICE_SERVERS;
const normalized: ScreenShareIceServer[] = [];
const seen = new Set<string>();
for (const raw of source) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
const candidate = raw as Record<string, unknown>;
const rawUrls = candidate.urls;
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
.filter((url): url is string => typeof url === "string" && url.trim().length > 0 && url.trim().length <= MAX_ICE_URL_LENGTH)
.map((url) => url.trim())
.filter((url) => SCREEN_SHARE_ICE_URL_PATTERN.test(url));
const uniqueUrls = [...new Set(urls)];
if (!uniqueUrls.length) continue;
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.username
: undefined;
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.credential
: undefined;
const key = JSON.stringify([uniqueUrls, username ?? ""]);
if (seen.has(key)) continue;
seen.add(key);
normalized.push({
urls: uniqueUrls.length === 1 ? uniqueUrls[0] : uniqueUrls,
...(username !== undefined ? { username } : {}),
...(credential !== undefined ? { credential } : {}),
});
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
}
if (normalized.length) return normalized;
return DEFAULT_SCREEN_SHARE_ICE_SERVERS.map((server) => ({ ...server }));
}
export type ScreenSharePeerSignal =
| {
kind: "offer" | "answer";
+9 -1
View File
@@ -17,7 +17,7 @@ import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnec
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js";
import { pingTeamSpeakSession } from "./network-probe.js";
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
import { parseScreenShareMessage, type ScreenShareClientMessage, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareClientMessage, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
const require = createRequire(import.meta.url);
const { OpusEncoder } = require("@discordjs/opus") as {
@@ -46,6 +46,7 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
export interface VoiceBridgeOptions {
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
accelerationName?: string | (() => string | undefined);
}
@@ -462,6 +463,7 @@ export class VoiceBridge {
whisperTargetIds: [...entry!.whisperTargetIds],
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
screenShareIceServers: this.getScreenShareIceServers(),
accelerated: Boolean(entry!.acceleration),
canMoveClients: entry!.canMoveClients,
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
@@ -1053,6 +1055,12 @@ export class VoiceBridge {
return typeof configured === "function" ? configured() : configured;
}
private getScreenShareIceServers(): ScreenShareIceServer[] {
const configured = this.options.screenShareIceServers;
const servers = typeof configured === "function" ? configured() : configured;
return normalizeScreenShareIceServers(servers);
}
private getAccelerationOptions(relayId = ""): ConfiguredAccelerationRelay | undefined {
const configured = this.options.acceleration;
const relays = typeof configured === "function" ? configured() : configured;
+39 -2
View File
@@ -7,6 +7,40 @@ import { loadLocalPreferences, saveLocalPreferences } from "../services/local-pe
const micCaptureWorkletUrl = "/mic-capture-worklet.js";
const SCREEN_SHARE_NEGOTIATION_TIMEOUT_MS = 15_000;
const DEFAULT_SCREEN_SHARE_ICE_SERVERS: RTCIceServer[] = [
{ urls: "stun:turn.teamspeak.com:3478" },
{ urls: "stun:turn2.teamspeak.com:3478" },
];
let screenShareIceServers: RTCIceServer[] = DEFAULT_SCREEN_SHARE_ICE_SERVERS;
function normalizeScreenShareIceServers(raw: unknown): RTCIceServer[] {
if (!Array.isArray(raw)) return DEFAULT_SCREEN_SHARE_ICE_SERVERS;
const normalized: RTCIceServer[] = [];
const seen = new Set<string>();
for (const item of raw) {
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const value = item as Record<string, unknown>;
const rawUrls = value.urls;
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
.filter((url): url is string => typeof url === "string" && /^(?:stun|stuns|turn|turns):/i.test(url.trim()))
.map((url) => url.trim())
.filter(Boolean);
const uniqueUrls = [...new Set(urls)];
if (!uniqueUrls.length) continue;
const username = typeof value.username === "string" ? value.username : undefined;
const credential = typeof value.credential === "string" ? value.credential : undefined;
const key = JSON.stringify([uniqueUrls, username ?? ""]);
if (seen.has(key)) continue;
seen.add(key);
normalized.push({
urls: uniqueUrls.length === 1 ? uniqueUrls[0] : uniqueUrls,
...(username !== undefined ? { username } : {}),
...(credential !== undefined ? { credential } : {}),
});
if (normalized.length >= 8) break;
}
return normalized.length ? normalized : DEFAULT_SCREEN_SHARE_ICE_SERVERS;
}
export interface VoiceState {
connected: boolean;
@@ -1694,8 +1728,10 @@ export function useVoiceWebSocket() {
function createScreenSharePeer(streamId: string, peerId: string, role: "owner" | "viewer"): RTCPeerConnection {
const existing = screenSharePeers.get(peerId);
if (existing) return existing;
// Deliberately no STUN/TURN: this feature is direct host-candidate P2P only.
const peer = new RTCPeerConnection({ iceServers: [] });
// STUN discovers server-reflexive candidates; it does not carry media.
// TURN is accepted only when explicitly configured by the deployment, and
// would use that external TURN service rather than the WebSpeak gateway.
const peer = new RTCPeerConnection({ iceServers: screenShareIceServers });
screenSharePeers.set(peerId, peer);
if (role === "owner") {
for (const track of screenShareLocalStream?.getTracks() ?? []) peer.addTrack(track, screenShareLocalStream!);
@@ -2031,6 +2067,7 @@ export function useVoiceWebSocket() {
state.channelSwitchedChannelId = "";
state.tsClientId = Number(msg.tsClientId) || 0;
state.canMoveClients = msg.canMoveClients === true;
screenShareIceServers = normalizeScreenShareIceServers(msg.screenShareIceServers);
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
if (Array.isArray(msg.members)) {
members.length = 0;
+2 -2
View File
@@ -614,7 +614,7 @@ const translations: Record<string, Record<string, string>> = {
teamSpeakSource: "TeamSpeak 客户端来源",
sharedAudio: "含共享音频",
noScreenShares: "当前没有正在进行的屏幕共享",
directP2POnly: "直连 P2P · 不使用 STUN/TURN",
directP2POnly: "直连 P2P · STUN 仅用于发现公网地址",
screenShareNativeUnavailable: "原生 TeamSpeak 屏幕共享暂不支持网页观看",
watching: "观看中",
serverPassword: "服务器密码",
@@ -920,7 +920,7 @@ const translations: Record<string, Record<string, string>> = {
teamSpeakSource: "TeamSpeak client source",
sharedAudio: "with shared audio",
noScreenShares: "No active screen shares",
directP2POnly: "Direct P2P · no STUN/TURN",
directP2POnly: "Direct P2P · STUN for public candidate discovery",
screenShareNativeUnavailable: "Native TeamSpeak screen sharing is not available to web viewers yet",
watching: "Watching",
serverPassword: "Server password",