Configure self-hosted STUN for remote WebRTC

This commit is contained in:
Xin Wang
2026-08-05 14:05:22 +08:00
parent 16156028c9
commit 0456d2b4ae
7 changed files with 53 additions and 36 deletions
+3 -2
View File
@@ -23,7 +23,8 @@ KNOWLEDGE_TOP_K=5
# ---- WebRTC TURN(公网跨网语音预览;本地开发留空) ----
# 与 docker compose --profile remote 的 coturn 配套。云安全组需放行 UDP 3478 与 49152-49200。
# PUBLIC_IP 填云主机公网 IP(compose 里给 coturn --external-ip 用,见项目根 .env)。
# TURN_URLS=turn:182.92.86.220:3478?transport=udp,turn:182.92.86.220:3478?transport=tcp
# Docker Compose 部署请在项目根 .env 设置这些变量;此处适用于宿主机直接运行 uvicorn。
# STUN_URL=stun:118.89.89.89:3478
# TURN_URLS=turn:118.89.89.89:3478?transport=udp,turn:118.89.89.89:3478?transport=tcp
# TURN_SECRET=your-turn-secret
# TURN_CREDENTIAL_TTL=86400
+2 -4
View File
@@ -9,8 +9,6 @@ import time
import settings
STUN_URL = "stun:stun.l.google.com:19302"
def _turn_credentials() -> tuple[str, str] | None:
"""Return (username, credential) for TURN, or None when TURN is not configured."""
@@ -34,7 +32,7 @@ def _turn_credentials() -> tuple[str, str] | None:
def client_ice_servers() -> list[dict]:
"""ICE servers for browser RTCPeerConnection (JSON-serializable)."""
servers: list[dict] = [{"urls": STUN_URL}]
servers: list[dict] = [{"urls": settings.STUN_URL}]
creds = _turn_credentials()
if not creds:
return servers
@@ -48,7 +46,7 @@ def aiortc_ice_servers() -> list:
"""ICE servers for backend SmallWebRTCConnection / aiortc."""
from aiortc import RTCIceServer
servers = [RTCIceServer(urls=STUN_URL)]
servers = [RTCIceServer(urls=settings.STUN_URL)]
creds = _turn_credentials()
if not creds:
return servers
+6 -2
View File
@@ -38,9 +38,13 @@ AUTH_TOKEN_EXPIRE_MINUTES = int(os.getenv("AUTH_TOKEN_EXPIRE_MINUTES", "1440"))
AUTH_COOKIE_SECURE = os.getenv("AUTH_COOKIE_SECURE", "false").lower() == "true"
AUTH_COOKIE_SAMESITE = os.getenv("AUTH_COOKIE_SAMESITE", "lax")
# ---- WebRTC TURN ----
# ---- WebRTC STUN / TURN ----
# Override STUN_URL in remote deployments to use the colocated coturn server
# instead of waiting for a public STUN service that may be unreachable.
STUN_URL = os.getenv("STUN_URL", "stun:stun.l.google.com:19302")
# TURN_URLS example:
# turn:182.92.86.220:3478?transport=udp,turn:182.92.86.220:3478?transport=tcp
# turn:118.89.89.89:3478?transport=udp,turn:118.89.89.89:3478?transport=tcp
TURN_URLS = _split(os.getenv("TURN_URLS", ""))
TURN_SECRET = os.getenv("TURN_SECRET", "")
TURN_USERNAME = os.getenv("TURN_USERNAME", "")