Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

fix(media): remove participant-wide TURN capability (#72)

AAA57d6e8982b6c
diff --git a/.env.example b/.env.example
index 63d71d29..5e10814e 100644
--- a/.env.example
+++ b/.env.example
@@ -35,14 +35,6 @@ MAX_SFU_ROOTS_PER_ROOM=2
# Separate multiple URLs with commas.
STUN_URLS=
-# Optional exact-room Web peer ICE compatibility. All three values are required
-# together and also require PEER_ASSISTED_MEDIA=true. The canary accepts one
-# explicit UDP TURN URI; the shared secret must be independent and 32-128 bytes.
-# Credential TTL is bounded to 300-1800 seconds. Leave absent/empty to disable.
-PEER_ICE_TURN_URLS=
-PEER_ICE_TURN_SHARED_SECRET=
-PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS=
-
# Minimal production example (use independent untracked secrets):
# HOST_ADMISSION_PASSWORD=replace-with-an-independent-access-key
# ROOM_DATABASE_PATH=/var/lib/screener/rooms.sqlite
@@ -54,7 +46,3 @@ PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS=
# LIVEKIT_API_KEY=replace-with-a-livekit-api-key
# LIVEKIT_API_SECRET=replace-with-at-least-32-independent-random-bytes
# MAX_SFU_ROOTS_PER_ROOM=2
-# Optional built-in Peer ICE TURN canary for the same exact rooms:
-# PEER_ICE_TURN_URLS=turn:turn.example.com:3478?transport=udp
-# PEER_ICE_TURN_SHARED_SECRET=replace-with-32-to-128-independent-random-bytes
-# PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS=600
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 4d566c21..eeb85616 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -78,16 +78,15 @@ tuple and remains a controller-owned transport attempt, never a topology choice.
Merged PR #17 implements this controller on top of merged PR #13, and PR #20
adds the bounded standby prewarm below. Production enables them only for
persistent room `1`; other rooms stay ordinary P2P, and production remains
-STUN-only. The current source still contains the rejected default-off built-in
-TURN canary, but it is not deployed and must be removed or replaced before any
-future TURN canary.
+STUN-only. The current source no longer contains the rejected participant-wide
+TURN config, issuer, capability, refresh wire, or client propagation. Stale
+`PEER_ICE_TURN_*` keys fail startup even when blank. Selected-edge TURN remains
+unimplemented and undeployed.
The current runtime removes the old all-room coturn contract. Production
requires STUN and authenticated ICE snapshots contain only STUN servers in
-production. The participant-wide TURN group, capability, and refresh messages
-in source belong only to the rejected candidate and are not the accepted target.
-The tracked
-LiveKit sample explicitly sets `tcp_port: 0`, disables TCP fallback, supplies
+production. The tracked LiveKit sample explicitly sets `tcp_port: 0`, disables
+TCP fallback, supplies
the deployment-owned STUN server, and configures no TURN service. The SFU controller still
activates only after a peer edge exhausts recovery. Public participant entry has
been observed, but retained media and route admission remain unverified. The old
@@ -226,13 +225,12 @@ embedded TURN remains participant-wide ICE configuration for a LiveKit
publisher or subscriber and is not the selected peer-edge grant.
The ordinary authenticated `iceConfig` contains only `iceServers` populated
-from `STUN_URLS`. The rejected built-in candidate still exists in source behind
-a complete default-off tuple, but its first production canary failed before the
-forced-relay phase and it is not an accepted deployment path. The replacement
-selected-edge slice must remove participant-wide issuance and refresh state;
-only its controller-selected rebuild may receive a short-lived relay-only
-configuration. No credential may enter a URL, log, browser persistence, room
-data, or SQLite.
+from `STUN_URLS`. The rejected participant-wide tuple, issuer, capability,
+refresh messages, and client propagation are removed, and stale
+`PEER_ICE_TURN_*` keys fail startup. A future selected-edge slice must add its
+controller consumer and one-use rebuild atomically; only that selected rebuild
+may receive a short-lived relay-only configuration. No credential may enter a
+URL, log, browser persistence, room data, or SQLite.
Authentication carries the current participant assignment and room revision,
plus the non-secret standby URL when fallback is configured. It never carries a
@@ -409,9 +407,10 @@ Healthy direct/peer UDP stays distributed. When no such path can satisfy
admission or recovery, one SFU publication feeds one or two roots, which keep
their bounded peer descendants. Only an edge that also cannot use SFU/UDP may
receive a controller-selected authenticated TURN attempt. Production currently
-ends in bounded failure and has no application TURN config. The default-off
-built-in participant-wide candidate in source is rejected after its first
-direct acceptance failed; it must not be enabled or treated as the target.
+ends in bounded failure and has no application TURN config. Source also has no
+participant-wide TURN path: the rejected candidate is removed and its stale
+environment keys fail startup. Selected-edge config, wire, and rebuild remain
+unimplemented and undeployed.
LiveKit participant-wide embedded/external TURN remains a separate ICE domain.
The bounded cost model, privacy-safe ICE fields, and exact-room A/B sequence
diff --git a/docs/deployment.md b/docs/deployment.md
index 1da2a9a3..4873a650 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -12,9 +12,10 @@ A deployment may additionally provide one single-node LiveKit process as the
current controller's automatic final media fallback. This capacity is dormant unless the complete
`LIVEKIT_URL`/key/secret tuple is configured. It does not replace the P2P path,
the peer-assisted experiment, or required STUN discovery. LiveKit remains
-ICE/UDP only. Source still contains a rejected default-off built-in Peer ICE
-TURN/UDP candidate. Its first production canary was no-go and fully rolled
-back; it must not be configured. Production advertises STUN-only ICE and the tracked coturn example remains
+ICE/UDP only. Source no longer contains the rejected participant-wide Peer ICE TURN
+candidate; stale `PEER_ICE_TURN_*` keys fail startup even when blank, and
+selected-edge TURN is not implemented or deployed. Production advertises
+STUN-only ICE and the tracked coturn example remains
`stun-only`. The shared host still retains its older authenticated-relay daemon
configuration and firewall range, but the application advertises no credential.
@@ -22,9 +23,9 @@ Production `31bee238bc1e` runs this candidate for exact room `1` on the existing
shared public IP. Immediate rollback to `7fea60ef6f2` uses the current v2
database and environment. Rolling back the admission-policy cutover requires
`89e6d7649169` plus the environment backup recorded below; only deeper
-pre-access `9610032fc5f5` may restore matching v1 state. Application TURN
-issuance is disabled and the failed canary backup is inactive. This is a
-bounded smoke, not broad-rollout acceptance.
+pre-access `9610032fc5f5` may restore matching v1 state. The production
+application TURN tuple is absent and the failed canary backup is inactive. This
+is a bounded smoke, not broad-rollout acceptance.
## Topology and prerequisites
@@ -188,10 +189,11 @@ LIVEKIT_API_SECRET=<INDEPENDENT_SECRET_OF_AT_LEAST_32_BYTES>
MAX_SFU_ROOTS_PER_ROOM=2
```
-Do not configure the rejected `PEER_ICE_TURN_*` participant-wide tuple. A future
-selected-edge release must introduce a distinct complete default-off tuple in
-the same coherent change as its controller consumer, strict schema and rollback
-tests; deployment documentation will name it only after that change lands. It
+The rejected `PEER_ICE_TURN_*` participant-wide tuple is removed; supplying any
+stale key, even blank, fails startup. A future selected-edge release must
+introduce a distinct complete default-off tuple in the same coherent change as
+its controller consumer, strict schema and rollback tests; deployment
+documentation will name it only after that change lands. It
must accept one explicit TURN/UDP URI, use an independent secret and bounded TTL,
and issue credentials only for a current one-use route attempt. Credentials
never enter URLs, logs, browser persistence, room rows, or SQLite.
@@ -415,9 +417,9 @@ compatibility.
The rejected candidate names `PEER_ICE_TURN_URLS`,
`PEER_ICE_TURN_SHARED_SECRET`, and
-`PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS` must remain absent from production. They
-are not aliases for the future selected-edge tuple; partial presence must fail
-closed until the source removal/migration lands.
+`PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS` must remain absent from production and
+now fail startup even when blank. They are not aliases for the future
+selected-edge tuple, which is not implemented or deployed.
## HTTPS and WSS ingress
diff --git a/docs/project-memory.md b/docs/project-memory.md
index 76b27e93..3475ff50 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -40,7 +40,7 @@ Last updated: 2026-08-20
- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
- Production `31bee238bc1e901e823f34e50737e202dc4b04bf` deployed at 2026-08-20 15:33:21 +08 to `https://share.bonfire.icu`. Room `1` alone enables peer/SFU routing, C+B local reparenting, and admission rescue; unlisted rooms remain ordinary P2P. Immediate rollback is `7fea60ef6f2a` with the current v2 DB/env.
-- Production ICE is STUN-only. Source still contains the default-off rejected built-in TURN candidate, but no room or client receives it. Room `1` may feed two LiveKit roots with peer descendants; selected-edge TURN is not implemented. Real rescue/relay/SFU media and game quality remain unverified.
+- Production ICE is STUN-only. Source no longer contains the rejected participant-wide TURN config, issuer, capability, refresh wire, or client propagation; stale `PEER_ICE_TURN_*` keys fail startup even when blank. Room `1` may feed two LiveKit roots with peer descendants; selected-edge TURN is not implemented or deployed. Real rescue/relay/SFU media and game quality remain unverified.
- Production requires an independent `HOST_ADMISSION_PASSWORD` only for creation/Host role. Default private fragment grants and explicit public-watch authorize Viewers; four anonymous Chrome routes stayed neutral until authorization. There are no accounts/JWT/session rows; SQLite v2 still contains all four rooms, including room `1`.
- Production uses nginx, Node.js 24.19.0, coturn 4.17.2, and pinned LiveKit 1.13.5 on UDP 7882 with TCP fallback disabled. The application TURN tuple is absent; coturn retains the old authenticated-relay config and TCP/UDP 3478 plus UDP 49152-49251 rules but receives no advertised credential. All services are active with zero automatic restarts; Screener used 38,031,360 bytes with zero cgroup events at 15:39:07.
- Old all-room application TURN wire/config remains absent. Canary release `a11a73dfa79d-r4` is inactive after rollback to `7fea60e`; final health/config/firewall/SQLite passed with zero allocations.
diff --git a/docs/research/built-in-peer-ice-turn.md b/docs/research/built-in-peer-ice-turn.md
index c93aca2f..bca9a033 100644
--- a/docs/research/built-in-peer-ice-turn.md
+++ b/docs/research/built-in-peer-ice-turn.md
@@ -23,6 +23,11 @@ This supersedes this document's former recommendation to place STUN plus TURN on
every capable exact-room Web peer connection. Git history retains that analysis;
the durable findings that still apply are summarized below.
+The current source no longer contains the rejected participant-wide config,
+issuer, authentication capability, refresh wire, or client propagation. Supplying any
+stale `PEER_ICE_TURN_*` key, even blank, fails startup. Selected-edge TURN config,
+wire, and rebuild remain unimplemented and undeployed.
+
## Production Canary
The first exact-room canary used source `a11a73dfa79d`, immutable release
diff --git a/docs/research/low-server-media-routes.md b/docs/research/low-server-media-routes.md
index 7946704e..78b9cd2d 100644
--- a/docs/research/low-server-media-routes.md
+++ b/docs/research/low-server-media-routes.md
@@ -190,10 +190,11 @@ SFU, not ordinary peer PCs. Selected-edge coturn uses independent configuration
and credentials. LiveKit TURN cannot rescue an unavailable SFU; the application
controller selects whether independent coturn may rebuild one failed peer edge.
-Production remains STUN-only. Current source still contains the rejected
-default-off `PEER_ICE_TURN_*` participant-wide candidate; it must not be
-configured and will be removed or replaced with its selected-edge consumer.
-Every ordinary room, Web peer and Native-shaped client remains STUN-only. The tracked coturn example is UDP
+Production and current source remain STUN-only. The participant-wide TURN
+config, capability and refresh wire are removed; any stale `PEER_ICE_TURN_*`
+key, including an empty value, fails startup. Selected-edge TURN remains
+unimplemented and undeployed. Every ordinary room, Web peer and Native-shaped
+client remains STUN-only. The tracked coturn example is UDP
`stun-only`; the LiveKit example exposes only ICE/UDP mux 7882, explicitly sets
`tcp_port: 0` and `allow_tcp_fallback: false`, supplies the self-hosted STUN
endpoint, and configures no external or embedded TURN. Candidate validation and rollback use isolated
diff --git a/docs/status.md b/docs/status.md
index 9e0c1f9f..ceb67df9 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -63,9 +63,12 @@ Next gate exactly-two/Dynacast-off BWE on a zero-child SFU leaf, then root
evacuation. Native needs separate authorization; its next run gates Go RTP on
the first bridge send.
Audio A/B/C may proceed without displacing P0.
-Ordinary Peer ICE stays STUN-only. Remove participant-wide issuance; after
-SFU/UDP fails, bind one selected parent/child rebuild to current generations and
-run one forced-relay canary. Do not repeat the built-in direct canary.
+Ordinary Peer ICE stays STUN-only. Participant-wide TURN code and wire are
+removed; stale `PEER_ICE_TURN_*` keys fail startup even when blank. Selected-edge
+TURN remains unimplemented and undeployed. After SFU/UDP fails, the next
+independent slice must bind one selected parent/child rebuild to current
+generations before one forced-relay canary. Do not repeat the built-in direct
+canary.
ADR-0004 still requires a full-resolution 30-minute `1/3/5/8` network,
resource, quality, latency, recovery, and browser/mobile-leaf matrix. A separate
diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
index 94d99b4a..aa2d8fb2 100644
--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"
@@ -229,13 +229,14 @@ fixed-`HIGH` -> 现有 WebRTC/一至两名 Web Viewer 的 P2 窄实验。硬件
## 媒体传输配置
-当前仓库已经删除旧全房 TURN contract,`ServerConfig` 必须配置 `STUN_URLS`。
-Source 仍含 `PEER_ICE_TURN_*`、participant capability、`refresh-ice` 与
-`ice-config` 的 default-off built-in canary;其真实 direct acceptance 失败并完整
-回滚,因此这些字段不得配置、部署或作为 accepted target。后续 selected-edge
-实现应以新的完整 default-off tuple 替换这组 participant-wide contract,部分配置、
-非法 UDP TURN URI、弱或复用 secret、越界 TTL 仍必须启动失败。旧 `TURN_URLS`、
-`TURN_SHARED_SECRET`、`TURN_CREDENTIAL_TTL_SECONDS` 继续 fail-fast,绝不作为 alias。
+当前仓库已经删除旧全房 TURN contract 和被拒绝的 participant-wide built-in
+config、issuer、capability、`refresh-ice`/`ice-config` wire 与客户端传播。
+Production `ServerConfig` 必须配置 `STUN_URLS`;旧 `PEER_ICE_TURN_*` 即使为空也
+启动失败,且绝不是后续 selected-edge tuple 的 alias。Selected-edge TURN 仍未实现或
+部署;后续必须在同一 coherent change 中加入新的完整 default-off tuple 和 controller
+consumer,部分配置、非法 UDP TURN URI、弱或复用 secret、越界 TTL 都必须启动失败。
+旧 `TURN_URLS`、`TURN_SHARED_SECRET`、`TURN_CREDENTIAL_TTL_SECONDS` 继续
+fail-fast,绝不作为 alias。
普通 direct/peer `RTCPeerConnection` 的 authenticated snapshot 只含 STUN。
Controller 先完成一次 ICE restart、一次同 parent rebuild、一个 alternate peer,随后
@@ -385,7 +386,7 @@ fail-open。未命中房间不得进入
不接收 TURN config。命中房间的 ordinary peer PC 与 Native v2 同样保持 STUN-only;
只有 controller-selected edge 可接收一次短期 grant。该边界不增加 UI、用户选择或百分比框架。
-产品硬目标是任一非服务器节点任何时刻最多两条下游媒体边。系统按一个或两个观看者直接 P2P、更多观看者 peer-assisted、部署 SFU 中央兜底、最后 selected-edge TURN 的顺序自动分配和恢复,分享者与观看者不选择拓扑。默认媒体 transport 只使用 UDP;SFU 作为 virtual parent 正常只送一至两个 roots,roots 之后仍优先沿受限 peer descendants 扩散;多个无法挂到健康 root 的极端 viewers 只可使用另设上限的中央 edge。Production 已把普通 ICE 收敛为 STUN-only、删除旧全房 TURN wire并只为 room `1` 开启 failure-only controller;source 中失败的 optional built-in Peer ICE TURN 仍默认关闭且不得部署,replacement selected-edge 尚未实现。exact-room 公网 SFU media、selected relay 与资源仍未验收,旧 release/coturn 仅作回滚。ADR-0004/0005 的 broad-rollout 验收尚未完成。
+产品硬目标是任一非服务器节点任何时刻最多两条下游媒体边。系统按一个或两个观看者直接 P2P、更多观看者 peer-assisted、部署 SFU 中央兜底、最后 selected-edge TURN 的顺序自动分配和恢复,分享者与观看者不选择拓扑。默认媒体 transport 只使用 UDP;SFU 作为 virtual parent 正常只送一至两个 roots,roots 之后仍优先沿受限 peer descendants 扩散;多个无法挂到健康 root 的极端 viewers 只可使用另设上限的中央 edge。Production 已把普通 ICE 收敛为 STUN-only、删除旧全房 TURN wire并只为 room `1` 开启 failure-only controller;source 也已删除失败的 participant-wide built-in code/wire,旧 `PEER_ICE_TURN_*` 配置启动失败,replacement selected-edge 尚未实现或部署。exact-room 公网 SFU media、selected relay 与资源仍未验收,旧 release/coturn 仅作回滚。ADR-0004/0005 的 broad-rollout 验收尚未完成。
恢复目标按证据和成本逐级升级:短暂 `disconnected` 先观察同代 bytes/stats,`failed` 才执行一次 ICE restart;仍失败时重建一次相同 parent,再尝试不同的合格 peer parent,peer 候选耗尽后才申请 SFU。每个动作最多一次且成功即停,不实现“三次相同重试”。初始 `connecting`/`checking` 的软提示和硬窗口尚未实现;硬窗口必须先用移动网络实测确定,不能直接复用现有 3 秒恢复常量。已实现的 SFU active 失败只刷新一次短期 grant,第二次失败回到新 peer baseline。Host 只保留当前 route revision 的 `connect | source | video-publish | sender-config | audio-publish | transport` 枚举阶段作为本地事件提示,不上传原始错误、URL、token、candidate 或地址。
diff --git a/native/sender/internal/remote/wire_test.go b/native/sender/internal/remote/wire_test.go
index 914bd8d4..7da0589e 100644
--- a/native/sender/internal/remote/wire_test.go
+++ b/native/sender/internal/remote/wire_test.go
@@ -51,24 +51,6 @@ func TestMarshalHostSignalShapes(t *testing.T) {
}
}
-func TestMarshalNativeAuthenticationDoesNotOptIntoWebPeerICETURN(t *testing.T) {
- encoded, err := json.Marshal(authenticateMessage{
- Type: "authenticate",
- Protocol: signalingProtocol,
- RoomID: "1",
- Role: "host",
- Token: strings.Repeat("a", 32),
- ClientID: "native-client",
- ShareGeneration: "native-generation",
- })
- if err != nil {
- t.Fatal(err)
- }
- if strings.Contains(string(encoded), "capabilities") || strings.Contains(string(encoded), "peerIceTurn") {
- t.Fatalf("native authentication opted into Web-only Peer ICE TURN: %s", encoded)
- }
-}
-
func TestDecodeOrdinaryHostAuthentication(t *testing.T) {
message, err := decodeServerMessage([]byte(validHostAuthenticated))
if err != nil {
@@ -118,10 +100,10 @@ func TestDecodeOrdinaryHostAuthenticationRejectsInvalidVariants(t *testing.T) {
}
}
-func TestDecodeServerMessageRejectsWebOnlyICERefresh(t *testing.T) {
+func TestDecodeServerMessageRejectsRemovedICERefresh(t *testing.T) {
payload := []byte(`{"type":"ice-config","iceConfig":{"iceServers":[]}}`)
if _, err := decodeServerMessage(payload); err == nil {
- t.Fatal("Web-only ICE refresh message was accepted")
+ t.Fatal("removed ICE refresh message was accepted")
}
}
diff --git a/src/client/lib/signaling.ts b/src/client/lib/signaling.ts
index dc9a3e1a..99595187 100644
--- a/src/client/lib/signaling.ts
+++ b/src/client/lib/signaling.ts
@@ -36,8 +36,6 @@ const INVALID_MESSAGE_CLOSE_CODE = 1008;
const VIEWER_ACCESS_REVOKED_CLOSE_CODE = 4004;
const PROTOCOL_REFRESH_MESSAGE = "页面版本已更新,请刷新后重试";
const TERMINAL_SEND_TIMEOUT_MS = 15_000;
-const PEER_ICE_TURN_REFRESH_LEAD_MS = 2 * 60 * 1_000;
-const PEER_ICE_TURN_REFRESH_MIN_DELAY_MS = 30_000;
export function shouldReconnectSignaling(code: number): boolean {
return (
@@ -61,7 +59,6 @@ export class SignalingClient {
private reconnectTimer: number | null = null;
private authenticationTimer: number | null = null;
private terminalTimer: number | null = null;
- private iceRefreshTimer: number | null = null;
private terminalMessage: ClientMessage | null = null;
constructor(
@@ -144,7 +141,6 @@ export class SignalingClient {
type: "authenticate",
protocol: SIGNALING_PROTOCOL,
...this.identity,
- capabilities: { peerIceTurn: true },
};
socket.send(JSON.stringify(authenticate));
this.authenticationTimer = window.setTimeout(() => {
@@ -198,9 +194,6 @@ export class SignalingClient {
}
this.events.onStatus("connected");
}
- if (message.type === "authenticated" || message.type === "ice-config") {
- this.scheduleIceRefresh(message.iceConfig.turnCredentialsExpiresAt);
- }
this.events.onMessage(message);
});
@@ -211,7 +204,6 @@ export class SignalingClient {
this.socket = null;
this.authenticated = false;
this.clearAuthenticationTimer();
- this.clearIceRefreshTimer();
if (!this.stopped && shouldReconnectSignaling(event.code)) {
this.scheduleReconnect();
} else if (!this.stopped) {
@@ -249,28 +241,6 @@ export class SignalingClient {
this.events.onTerminated(PROTOCOL_REFRESH_MESSAGE);
}
- private scheduleIceRefresh(expiresAt: string | undefined): void {
- this.clearIceRefreshTimer();
- if (!expiresAt) {
- return;
- }
- const refreshAtMs = Date.parse(expiresAt) - PEER_ICE_TURN_REFRESH_LEAD_MS;
- this.iceRefreshTimer = window.setTimeout(
- () => {
- this.iceRefreshTimer = null;
- this.send({ type: "refresh-ice" });
- },
- Math.max(PEER_ICE_TURN_REFRESH_MIN_DELAY_MS, refreshAtMs - Date.now()),
- );
- }
-
- private clearIceRefreshTimer(): void {
- if (this.iceRefreshTimer !== null) {
- window.clearTimeout(this.iceRefreshTimer);
- this.iceRefreshTimer = null;
- }
- }
-
private clearAuthenticationTimer(): void {
if (this.authenticationTimer !== null) {
window.clearTimeout(this.authenticationTimer);
@@ -280,7 +250,6 @@ export class SignalingClient {
private clearTimers(): void {
this.clearAuthenticationTimer();
- this.clearIceRefreshTimer();
if (this.reconnectTimer !== null) {
window.clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index efb167fd..7b49bd07 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -1074,11 +1074,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
expiresAt: message.roomExpiresAt,
});
setPhase("live");
- } else if (message.type === "ice-config") {
- iceConfigRef.current = message.iceConfig;
- peersRef.current.forEach((peer) =>
- peer.updateIceConfig(message.iceConfig),
- );
}
handleSignalMessage(message, generation, activeRoom.roomId);
},
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index bf9eaf91..8bb9ed01 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -596,12 +596,6 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
}
return;
}
- if (message.type === "ice-config") {
- currentIceConfig = message.iceConfig;
- peerRef.current?.updateIceConfig(message.iceConfig);
- viewerRelay?.updateIceConfig(message.iceConfig);
- return;
- }
if (message.type === "route-update") {
if (peerAssisted) {
if (message.phase === "active") {
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index 27abcc9f..9c04ac3e 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -86,7 +86,6 @@ export class HostPeer {
) {
this.connection = new RTCPeerConnection({
iceServers: iceConfig.iceServers,
- iceTransportPolicy: "all",
});
this.snapshot = {
peerId,
@@ -257,7 +256,6 @@ export class HostPeer {
try {
this.connection.setConfiguration({
iceServers: iceConfig.iceServers,
- iceTransportPolicy: "all",
});
} catch (error) {
this.setError(error, "更新 ICE 配置失败");
diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.ts
index 27f90998..a4d4d7c1 100644
--- a/src/client/webrtc/viewer-peer.ts
+++ b/src/client/webrtc/viewer-peer.ts
@@ -174,7 +174,6 @@ export class ViewerPeer {
try {
this.connection.setConfiguration({
iceServers: iceConfig.iceServers,
- iceTransportPolicy: "all",
});
} catch (error) {
this.setError(error, "更新 ICE 配置失败");
@@ -238,7 +237,6 @@ export class ViewerPeer {
const connection = new RTCPeerConnection({
iceServers: this.currentIceConfig.iceServers,
- iceTransportPolicy: "all",
});
this.connection = connection;
this.snapshot = {
diff --git a/src/server/app.ts b/src/server/app.ts
index 60e5d2f9..2680cc33 100644
--- a/src/server/app.ts
+++ b/src/server/app.ts
@@ -113,7 +113,6 @@ export async function createScreenerServer(
peerAssistedMedia: config.peerAssistedMedia,
peerAssistedRoomIds: config.peerAssistedRoomIds,
...(sfuFallback ? { sfuFallback } : {}),
- ...(config.peerIceTurn ? { peerIceTurn: config.peerIceTurn } : {}),
ice: iceOptions,
allowedOrigins: config.allowedOrigins,
hostAdmissionAtUpgrade: (request) =>
diff --git a/src/server/config.ts b/src/server/config.ts
index 8b774e0b..d78fbb5b 100644
--- a/src/server/config.ts
+++ b/src/server/config.ts
@@ -3,7 +3,6 @@ import {
MAX_VIEWERS_PER_ROOM_LIMIT,
roomCodeSchema,
stunUrlSchema,
- turnUrlSchema,
} from "../shared/protocol.js";
export type RuntimeEnvironment = "development" | "test" | "production";
@@ -11,11 +10,6 @@ export type RuntimeEnvironment = "development" | "test" | "production";
const MIN_HOST_ADMISSION_PASSWORD_BYTES = 8;
const MAX_HOST_ADMISSION_PASSWORD_BYTES = 128;
const MIN_LIVEKIT_API_SECRET_BYTES = 32;
-const MIN_PEER_ICE_TURN_SECRET_BYTES = 32;
-const MAX_PEER_ICE_TURN_SECRET_BYTES = 128;
-const MIN_PEER_ICE_TURN_TTL_SECONDS = 5 * 60;
-const MAX_PEER_ICE_TURN_TTL_SECONDS = 30 * 60;
-const MAX_PEER_ICE_TURN_URLS = 1;
const MAX_PEER_ASSISTED_VIEWERS = 8;
const DEFAULT_MAX_VIEWERS_PER_ROOM = 8;
const DEFAULT_MAX_SFU_ROOTS_PER_ROOM = 2;
@@ -25,6 +19,9 @@ const REMOVED_TURN_ENVIRONMENT_VARIABLES = [
"TURN_URLS",
"TURN_SHARED_SECRET",
"TURN_CREDENTIAL_TTL_SECONDS",
+ "PEER_ICE_TURN_URLS",
+ "PEER_ICE_TURN_SHARED_SECRET",
+ "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",
] as const;
export interface LiveKitFallbackConfig {
@@ -34,12 +31,6 @@ export interface LiveKitFallbackConfig {
maxSfuRootsPerRoom: number;
}
-export interface PeerIceTurnConfig {
- urls: readonly string[];
- sharedSecret: string;
- credentialTtlSeconds: number;
-}
-
export interface ServerConfig {
nodeEnv: RuntimeEnvironment;
port: number;
@@ -54,7 +45,6 @@ export interface ServerConfig {
peerAssistedMedia: boolean;
peerAssistedRoomIds?: ReadonlySet<string>;
livekitFallback?: LiveKitFallbackConfig;
- peerIceTurn?: PeerIceTurnConfig;
stunUrls: readonly string[];
}
@@ -200,66 +190,6 @@ function parseStunUrlList(value: string | undefined): string[] {
});
}
-function parsePeerIceTurn(
- environment: NodeJS.ProcessEnv,
-): PeerIceTurnConfig | undefined {
- const names = [
- "PEER_ICE_TURN_URLS",
- "PEER_ICE_TURN_SHARED_SECRET",
- "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",
- ] as const;
- const configuredNames = names.filter((name) => environment[name]?.trim());
- if (configuredNames.length === 0) {
- return undefined;
- }
- if (configuredNames.length !== names.length) {
- throw new Error(
- "PEER_ICE_TURN_URLS, PEER_ICE_TURN_SHARED_SECRET, and PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS must be configured together",
- );
- }
-
- const urls = parseUrlList(environment.PEER_ICE_TURN_URLS, "PEER_ICE_TURN_URLS");
- if (urls.length > MAX_PEER_ICE_TURN_URLS) {
- throw new Error(
- `PEER_ICE_TURN_URLS must contain at most ${MAX_PEER_ICE_TURN_URLS} URL`,
- );
- }
- if (new Set(urls).size !== urls.length) {
- throw new Error("PEER_ICE_TURN_URLS must not contain duplicate URLs");
- }
- for (const url of urls) {
- if (!turnUrlSchema.safeParse(url).success) {
- throw new Error(
- "PEER_ICE_TURN_URLS must contain UDP TURN URLs with transport=udp",
- );
- }
- }
-
- const sharedSecret = environment.PEER_ICE_TURN_SHARED_SECRET!;
- const sharedSecretBytes = Buffer.byteLength(sharedSecret);
- if (
- !VISIBLE_ASCII_PATTERN.test(sharedSecret) ||
- sharedSecretBytes < MIN_PEER_ICE_TURN_SECRET_BYTES ||
- sharedSecretBytes > MAX_PEER_ICE_TURN_SECRET_BYTES
- ) {
- throw new Error(
- "PEER_ICE_TURN_SHARED_SECRET must contain 32 to 128 visible ASCII bytes",
- );
- }
-
- return {
- urls,
- sharedSecret,
- credentialTtlSeconds: parseBoundedInteger(
- environment.PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS,
- MIN_PEER_ICE_TURN_TTL_SECONDS,
- "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",
- MIN_PEER_ICE_TURN_TTL_SECONDS,
- MAX_PEER_ICE_TURN_TTL_SECONDS,
- ),
- };
-}
-
function parseOrigins(value: string | undefined, fallback: string): Set<string> {
const origins = parseUrlList(value, "ALLOWED_ORIGINS");
return new Set((origins.length > 0 ? origins : [fallback]).map(toOrigin));
@@ -369,7 +299,6 @@ export function loadConfig(
environment.PEER_ASSISTED_ROOM_IDS,
);
const livekitFallback = parseLiveKitFallback(environment, nodeEnv);
- const peerIceTurn = parsePeerIceTurn(environment);
if (peerAssistedRoomIds && !peerAssistedMedia) {
throw new Error(
@@ -384,20 +313,14 @@ export function loadConfig(
if (livekitFallback && !peerAssistedMedia) {
throw new Error("LiveKit fallback requires PEER_ASSISTED_MEDIA=true");
}
- if (peerIceTurn && !peerAssistedMedia) {
- throw new Error("Peer ICE TURN requires PEER_ASSISTED_MEDIA=true");
- }
const configuredSecrets = [
hostAdmissionPassword,
livekitFallback?.apiKey,
livekitFallback?.apiSecret,
- peerIceTurn?.sharedSecret,
].filter((secret): secret is string => secret !== undefined);
if (new Set(configuredSecrets).size !== configuredSecrets.length) {
throw new Error(
- peerIceTurn
- ? "HOST_ADMISSION_PASSWORD, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, and PEER_ICE_TURN_SHARED_SECRET must use independent values"
- : "HOST_ADMISSION_PASSWORD, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must use independent values",
+ "HOST_ADMISSION_PASSWORD, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must use independent values",
);
}
if (
@@ -449,7 +372,6 @@ export function loadConfig(
peerAssistedMedia,
peerAssistedRoomIds,
livekitFallback,
- peerIceTurn,
stunUrls,
};
}
diff --git a/src/server/ice.ts b/src/server/ice.ts
index 642fd4a6..5bc44aad 100644
--- a/src/server/ice.ts
+++ b/src/server/ice.ts
@@ -4,34 +4,9 @@ export interface IceConfigOptions {
stunUrls: readonly string[];
}
-export interface PeerIceTurnGrantOptions {
- urls: readonly string[];
- username: string;
- credential: string;
- expiresAt: string;
-}
-
-export function createIceConfig(
- options: IceConfigOptions,
- peerIceTurn?: PeerIceTurnGrantOptions,
-): IceConfig {
+export function createIceConfig(options: IceConfigOptions): IceConfig {
return {
- iceServers: [
- ...(options.stunUrls.length > 0
- ? [{ urls: [...options.stunUrls] }]
- : []),
- ...(peerIceTurn
- ? [
- {
- urls: [...peerIceTurn.urls],
- username: peerIceTurn.username,
- credential: peerIceTurn.credential,
- },
- ]
- : []),
- ],
- ...(peerIceTurn
- ? { turnCredentialsExpiresAt: peerIceTurn.expiresAt }
- : {}),
+ iceServers:
+ options.stunUrls.length > 0 ? [{ urls: [...options.stunUrls] }] : [],
};
}
diff --git a/src/server/peer-ice-turn.ts b/src/server/peer-ice-turn.ts
deleted file mode 100644
index 6d029acf..00000000
--- a/src/server/peer-ice-turn.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { createHmac } from "node:crypto";
-
-import type { Role } from "../shared/protocol.js";
-import type { PeerIceTurnConfig } from "./config.js";
-
-export interface PeerIceTurnIdentity {
- roomId: string;
- role: Role;
- peerId: string;
- sessionId: string;
-}
-
-export interface PeerIceTurnGrant {
- urls: readonly string[];
- username: string;
- credential: string;
- expiresAt: string;
- expiresAtMs: number;
-}
-
-export function issuePeerIceTurnGrant(
- config: PeerIceTurnConfig,
- identity: PeerIceTurnIdentity,
- nowMs: number,
-): PeerIceTurnGrant {
- if (!Number.isFinite(nowMs) || nowMs < 0) {
- throw new Error("Peer ICE TURN grant time is invalid");
- }
-
- const expiresAtSeconds =
- Math.floor(nowMs / 1_000) + config.credentialTtlSeconds;
- const opaqueIdentity = createHmac("sha256", config.sharedSecret)
- .update(
- JSON.stringify([
- "screener-peer-ice-turn-v1",
- identity.roomId,
- identity.role,
- identity.peerId,
- identity.sessionId,
- expiresAtSeconds,
- ]),
- )
- .digest("base64url")
- .slice(0, 32);
- const username = `${expiresAtSeconds}:${opaqueIdentity}`;
- const credential = createHmac("sha1", config.sharedSecret)
- .update(username)
- .digest("base64");
- const expiresAtMs = expiresAtSeconds * 1_000;
-
- return {
- urls: [...config.urls],
- username,
- credential,
- expiresAt: new Date(expiresAtMs).toISOString(),
- expiresAtMs,
- };
-}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index aa6a1f30..5b090a57 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -30,19 +30,12 @@ import {
type SfuFallbackOptions,
} from "./hybrid-media-router.js";
import { createIceConfig, type IceConfigOptions } from "./ice.js";
-import type { PeerIceTurnConfig } from "./config.js";
-import {
- issuePeerIceTurnGrant,
- type PeerIceTurnGrant,
-} from "./peer-ice-turn.js";
type ErrorCode = Extract<ServerMessage, { type: "error" }>["code"];
const MAX_BUFFERED_SIGNAL_BYTES = 256 * 1024;
const DEFAULT_MAX_SIGNAL_CONNECTIONS = 2_048;
const DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS = 256;
-const PEER_ICE_TURN_REFRESH_LEAD_MS = 2 * 60 * 1_000;
-const PEER_ICE_TURN_REFRESH_MIN_INTERVAL_MS = 5_000;
interface AuthenticatedSession {
roomId: string;
@@ -52,7 +45,6 @@ interface AuthenticatedSession {
shareGeneration: string | null;
displayName: string | null;
viewerPresence: boolean;
- peerIceTurnCapable: boolean;
}
interface SocketState {
@@ -62,8 +54,6 @@ interface SocketState {
hostAdmissionAuthenticated: boolean;
revoked?: boolean;
authenticated?: AuthenticatedSession;
- peerIceTurnGrant?: PeerIceTurnGrant;
- lastPeerIceTurnRefreshAtMs?: number;
}
interface ViewerQualityEvidenceGate {
@@ -83,7 +73,6 @@ export interface SignalingOptions {
peerAssistedMedia: boolean;
peerAssistedRoomIds?: ReadonlySet<string>;
sfuFallback?: SfuFallbackOptions;
- peerIceTurn?: PeerIceTurnConfig;
ice: IceConfigOptions;
allowedOrigins: ReadonlySet<string>;
hostAdmissionAtUpgrade: (request: IncomingMessage) => boolean;
@@ -147,9 +136,6 @@ export class SignalingServer {
if (options.sfuFallback && !options.peerAssistedMedia) {
throw new Error("SFU fallback requires peer-assisted media");
}
- if (options.peerIceTurn && !options.peerAssistedMedia) {
- throw new Error("Peer ICE TURN requires peer-assisted media");
- }
if (options.peerAssistedRoomIds && !options.peerAssistedMedia) {
throw new Error("Peer-assisted room IDs require peer-assisted media");
}
@@ -424,7 +410,6 @@ export class SignalingServer {
? (message.displayName ?? DEFAULT_VIEWER_DISPLAY_NAME)
: null,
viewerPresence: false,
- peerIceTurnCapable: message.capabilities?.peerIceTurn === true,
};
if (participant.role === "viewer") {
this.viewerQualityEvidenceGates.delete(
@@ -470,7 +455,7 @@ export class SignalingServer {
hostOnline: participant.hostOnline,
connectionId,
viewerPeerIds: [...participant.viewerPeerIds],
- iceConfig: this.iceConfig(state),
+ iceConfig: this.iceConfig(),
viewerPolicy: participant.viewerPolicy,
viewerAuthorizationGeneration:
participant.viewerAuthorizationGeneration,
@@ -654,32 +639,6 @@ export class SignalingServer {
message.revision,
);
return;
- case "refresh-ice": {
- const state = this.socketStates.get(socket);
- if (
- !state ||
- state.authenticated !== authenticated ||
- !this.isPeerIceTurnEligible(authenticated)
- ) {
- this.sendError(socket, "FORBIDDEN", "Peer ICE refresh is not enabled");
- return;
- }
- const nowMs = this.now();
- if (
- state.lastPeerIceTurnRefreshAtMs !== undefined &&
- nowMs - state.lastPeerIceTurnRefreshAtMs <
- PEER_ICE_TURN_REFRESH_MIN_INTERVAL_MS
- ) {
- this.sendError(socket, "FORBIDDEN", "Peer ICE refresh is rate limited");
- return;
- }
- state.lastPeerIceTurnRefreshAtMs = nowMs;
- this.send(socket, {
- type: "ice-config",
- iceConfig: this.iceConfig(state),
- });
- return;
- }
case "viewer-quality-evidence":
this.handleViewerQualityEvidence(socket, authenticated, message);
return;
@@ -1329,38 +1288,8 @@ export class SignalingServer {
);
}
- private iceConfig(state: SocketState) {
- const authenticated = state.authenticated;
- if (!authenticated || !this.isPeerIceTurnEligible(authenticated)) {
- return createIceConfig(this.options.ice);
- }
-
- const nowMs = this.now();
- let grant = state.peerIceTurnGrant;
- if (!grant || nowMs >= grant.expiresAtMs - PEER_ICE_TURN_REFRESH_LEAD_MS) {
- grant = issuePeerIceTurnGrant(
- this.options.peerIceTurn!,
- {
- roomId: authenticated.roomId,
- role: authenticated.role,
- peerId: authenticated.peerId,
- sessionId: state.sessionId,
- },
- nowMs,
- );
- state.peerIceTurnGrant = grant;
- }
- return createIceConfig(this.options.ice, grant);
- }
-
- private isPeerIceTurnEligible(
- authenticated: AuthenticatedSession,
- ): boolean {
- return Boolean(
- this.options.peerIceTurn &&
- authenticated.peerIceTurnCapable &&
- this.isPeerAssistedRoom(authenticated.roomId),
- );
+ private iceConfig() {
+ return createIceConfig(this.options.ice);
}
private viewerInviteUrl(roomId: string, viewerGrant: string | null): string {
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 23a3dec6..eda76f1d 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -9,7 +9,6 @@ export const ROOM_CODE_LENGTH = 12;
export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
export const MAX_SFU_TOKEN_LENGTH = 8 * 1024;
export const MAX_ICE_SERVER_URLS = 8;
-export const MAX_TURN_CREDENTIAL_LENGTH = 256;
export const MAX_VIEWER_QUALITY_EVIDENCE_BYTES = 2 * 1024;
export const MAX_PARENT_EDGE_QUALITY_EVIDENCE_BYTES = 2 * 1024;
export const VIEWER_QUALITY_EVIDENCE_INTERVAL_MS = 2_000;
@@ -193,53 +192,7 @@ export const stunUrlSchema = z
.max(512)
.refine(isValidStunUrl, { message: "Invalid STUN URL" });
-function isValidTurnUrl(value: string): boolean {
- const schemeSeparator = value.indexOf(":");
- if (
- schemeSeparator <= 0 ||
- value.slice(0, schemeSeparator).toLowerCase() !== "turn"
- ) {
- return false;
- }
-
- const turnUri = value.slice(schemeSeparator + 1);
- const querySeparator = turnUri.indexOf("?");
- const authorityText =
- querySeparator === -1 ? turnUri : turnUri.slice(0, querySeparator);
- const query = querySeparator === -1 ? "" : turnUri.slice(querySeparator + 1);
- if (
- !authorityText ||
- /[\\/\s#]/.test(authorityText) ||
- authorityText.endsWith(":") ||
- query !== "transport=udp"
- ) {
- return false;
- }
-
- let authority: URL;
- try {
- authority = new URL(`http://${authorityText}`);
- } catch {
- return false;
- }
- return Boolean(
- authority.hostname &&
- !authority.username &&
- !authority.password &&
- authority.pathname === "/" &&
- !authority.search &&
- !authority.hash &&
- (!authority.port || Number(authority.port) > 0),
- );
-}
-
-export const turnUrlSchema = z
- .string()
- .min(1)
- .max(512)
- .refine(isValidTurnUrl, { message: "Invalid TURN URL" });
-
-const stunIceServerSchema = z
+const iceServerSchema = z
.object({
urls: z.union([
stunUrlSchema,
@@ -248,58 +201,12 @@ const stunIceServerSchema = z
})
.strict();
-const turnIceServerSchema = z
- .object({
- urls: z.union([
- turnUrlSchema,
- z.array(turnUrlSchema).min(1).max(MAX_ICE_SERVER_URLS),
- ]),
- username: z
- .string()
- .min(1)
- .max(128)
- .regex(/^[1-9]\d{0,12}:[A-Za-z0-9_-]{16,64}$/),
- credential: z.string().min(1).max(MAX_TURN_CREDENTIAL_LENGTH),
- })
- .strict();
-
-const iceServerSchema = z.union([stunIceServerSchema, turnIceServerSchema]);
-
export const iceConfigSchema = z
.object({
iceServers: z.array(iceServerSchema).max(8),
- turnCredentialsExpiresAt: z.string().datetime().optional(),
- })
- .strict()
- .superRefine((config, context) => {
- const turnServers = config.iceServers.filter(
- (server) => "username" in server,
- );
- if (turnServers.length > 1) {
- context.addIssue({
- code: "custom",
- message: "ICE configuration has more than one TURN server group",
- path: ["iceServers"],
- });
- }
- if (
- (turnServers.length === 1) !==
- (config.turnCredentialsExpiresAt !== undefined)
- ) {
- context.addIssue({
- code: "custom",
- message: "TURN credentials and expiry must be present together",
- path: ["turnCredentialsExpiresAt"],
- });
- }
- });
-export type IceConfig = z.infer<typeof iceConfigSchema>;
-
-const webClientCapabilitiesSchema = z
- .object({
- peerIceTurn: z.literal(true),
})
.strict();
+export type IceConfig = z.infer<typeof iceConfigSchema>;
const sessionDescriptionSchema = z
.object({
@@ -518,7 +425,6 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
clientId: opaqueIdSchema,
shareGeneration: opaqueIdSchema.optional(),
viewerPresence: z.literal(true).optional(),
- capabilities: webClientCapabilitiesSchema.optional(),
})
.strict(),
z
@@ -530,7 +436,6 @@ const authenticateMessageSchema = z.discriminatedUnion("role", [
clientId: opaqueIdSchema,
viewerGrant: viewerGrantSchema.optional(),
displayName: displayNameSchema.optional(),
- capabilities: webClientCapabilitiesSchema.optional(),
})
.strict(),
]);
@@ -585,7 +490,6 @@ export const clientMessageSchema = z.union([
revision: mediaRouteRevisionSchema,
})
.strict(),
- z.object({ type: z.literal("refresh-ice") }).strict(),
viewerQualityEvidenceMessageSchema,
parentEdgeQualityEvidenceMessageSchema,
z
@@ -703,12 +607,6 @@ export const serverMessageSchema = z.union([
token: z.string().min(1).max(MAX_SFU_TOKEN_LENGTH),
})
.strict(),
- z
- .object({
- type: z.literal("ice-config"),
- iceConfig: iceConfigSchema,
- })
- .strict(),
z
.object({
type: z.literal("quality-settings"),
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 3c05e340..14a3e560 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -30,7 +30,6 @@ import { qualityEvidenceWindowFromMetrics } from "../src/client/media/viewer-qua
import { createStatsAccumulator, collectConnectionMetrics } from "../src/client/webrtc/stats.ts";
afterEach(() => {
- vi.useRealTimers();
vi.unstubAllGlobals();
});
@@ -440,110 +439,6 @@ describe("client signaling recovery policy", () => {
expect(shouldReconnectSignaling(1006)).toBe(true);
});
- it("opts into Peer ICE TURN and refreshes credentials two minutes before expiry", () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-08-20T12:00:00.000Z"));
- const sockets: FakeWebSocket[] = [];
- class FakeWebSocket extends EventTarget {
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- readyState = FakeWebSocket.OPEN;
- readonly send = vi.fn();
- readonly close = vi.fn();
-
- constructor(readonly url: string) {
- super();
- sockets.push(this);
- }
- }
- vi.stubGlobal("WebSocket", FakeWebSocket);
- vi.stubGlobal("window", {
- location: new URL("https://share.test/r/123456789012"),
- setTimeout,
- clearTimeout,
- });
- const signal = new SignalingClient(
- {
- roomId: "123456789012",
- role: "viewer",
- clientId: "viewer-client",
- },
- {
- onMessage: () => undefined,
- onStatus: () => undefined,
- onTerminated: () => undefined,
- onAccessRequired: () => undefined,
- },
- );
-
- signal.start();
- sockets[0]!.dispatchEvent(new Event("open"));
- expect(JSON.parse(String(sockets[0]!.send.mock.calls[0]![0]))).toMatchObject({
- type: "authenticate",
- capabilities: { peerIceTurn: true },
- });
- const authenticated = new Event("message");
- Object.defineProperty(authenticated, "data", {
- value: JSON.stringify({
- type: "authenticated",
- protocol: "screener-v2",
- role: "viewer",
- peerId: "viewer_12345678",
- roomExpiresAt: null,
- maxViewers: 8,
- hostOnline: true,
- connectionId: null,
- viewerPeerIds: [],
- iceConfig: {
- iceServers: [
- {
- urls: "turn:relay.test:3478?transport=udp",
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:05:00.000Z",
- },
- viewerPolicy: "private-link",
- viewerAuthorizationGeneration: "viewer_generation_12345678",
- }),
- });
- sockets[0]!.dispatchEvent(authenticated);
-
- vi.advanceTimersByTime(179_999);
- expect(sockets[0]!.send).toHaveBeenCalledTimes(1);
- vi.advanceTimersByTime(1);
- expect(JSON.parse(String(sockets[0]!.send.mock.calls[1]![0]))).toEqual({
- type: "refresh-ice",
- });
-
- const refreshed = new Event("message");
- Object.defineProperty(refreshed, "data", {
- value: JSON.stringify({
- type: "ice-config",
- iceConfig: {
- iceServers: [
- {
- urls: "turn:relay.test:3478?transport=udp",
- username: `1787076180:${"b".repeat(32)}`,
- credential: "next-temporary-credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:08:00.000Z",
- },
- }),
- });
- sockets[0]!.dispatchEvent(refreshed);
- vi.advanceTimersByTime(180_000);
- expect(JSON.parse(String(sockets[0]!.send.mock.calls[2]![0]))).toEqual({
- type: "refresh-ice",
- });
-
- signal.stop();
- vi.advanceTimersByTime(300_000);
- expect(sockets[0]!.send).toHaveBeenCalledTimes(3);
- });
-
it.each([
JSON.stringify({
type: "error",
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index 8ecdefbe..3ef997df 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -4,6 +4,7 @@ import { QUALITY_PROFILES } from "../src/client/media/quality.ts";
import type { PeerSnapshot } from "../src/client/types.ts";
import { HostPeer } from "../src/client/webrtc/host-peer.ts";
import { ViewerRelay } from "../src/client/webrtc/viewer-relay.ts";
+import type { IceConfig } from "../src/shared/protocol.ts";
const statsCallbacks: Array<() => void> = [];
@@ -269,10 +270,11 @@ function createStream(
function createPeer(
stream: MediaStream,
onUpdate: (snapshot: PeerSnapshot) => void = () => undefined,
+ iceConfig: IceConfig = { iceServers: [] },
): HostPeer {
return new HostPeer(
"viewer-peer",
- { iceServers: [] },
+ iceConfig,
stream,
QUALITY_PROFILES["720p30"],
{
@@ -305,35 +307,35 @@ afterEach(() => {
});
describe("HostPeer source replacement", () => {
- it("keeps standard ICE direct-first while refreshing future gathering", () => {
- const peer = createPeer(createStream(createTrack("video", "video"), null));
+ it("applies STUN-only ICE configuration at creation and update", () => {
+ const peer = createPeer(
+ createStream(createTrack("video", "video"), null),
+ () => undefined,
+ { iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }] },
+ );
const connection = FakePeerConnection.latest!;
- expect(connection.configurations).toEqual([
- { iceServers: [], iceTransportPolicy: "all" },
- ]);
peer.updateIceConfig({
- iceServers: [
- {
- urls: ["turn:relay.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:00:00.000Z",
+ iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }],
});
+ expect(connection.configurations).toEqual([
+ { iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }] },
+ { iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }] },
+ ]);
expect(connection.setConfiguration).toHaveBeenCalledOnce();
- expect(connection.configurations[1]).toEqual({
- iceServers: [
- {
- urls: ["turn:relay.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- iceTransportPolicy: "all",
- });
+ for (const configuration of connection.configurations) {
+ expect(
+ configuration.iceServers?.every(
+ (server) =>
+ !Reflect.has(server, "username") &&
+ !Reflect.has(server, "credential") &&
+ (typeof server.urls === "string"
+ ? server.urls.startsWith("stun:")
+ : server.urls.every((url) => url.startsWith("stun:"))),
+ ),
+ ).toBe(true);
+ }
});
it("reserves send-only video and audio senders and replaces both tracks", async () => {
diff --git a/tests/ice.test.ts b/tests/ice.test.ts
index 4c80b8ce..56347061 100644
--- a/tests/ice.test.ts
+++ b/tests/ice.test.ts
@@ -26,28 +26,4 @@ describe("ordinary ICE configuration", () => {
it("keeps local development explicit when STUN is absent", () => {
expect(createIceConfig({ stunUrls: [] })).toEqual({ iceServers: [] });
});
-
- it("adds one authenticated TURN group and its bounded expiry", () => {
- expect(
- createIceConfig(
- { stunUrls: ["stun:stun.example.test:3478"] },
- {
- urls: ["turn:relay.example.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- expiresAt: "2026-08-20T12:00:00.000Z",
- },
- ),
- ).toEqual({
- iceServers: [
- { urls: ["stun:stun.example.test:3478"] },
- {
- urls: ["turn:relay.example.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:00:00.000Z",
- });
- });
});
diff --git a/tests/peer-ice-turn.test.ts b/tests/peer-ice-turn.test.ts
deleted file mode 100644
index 70e4d50a..00000000
--- a/tests/peer-ice-turn.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { createHmac } from "node:crypto";
-
-import { describe, expect, it } from "vitest";
-
-import { issuePeerIceTurnGrant } from "../src/server/peer-ice-turn.ts";
-
-const config = {
- urls: ["turn:relay.example.test:3478?transport=udp"],
- sharedSecret: "turn-test-secret-that-is-at-least-32-bytes",
- credentialTtlSeconds: 300,
-} as const;
-
-describe("Peer ICE TURN credential issuer", () => {
- it("issues coturn REST credentials with an opaque participant-session bearer", () => {
- const nowMs = Date.parse("2026-08-20T12:00:00.500Z");
- const grant = issuePeerIceTurnGrant(
- config,
- {
- roomId: "123456789012",
- role: "viewer",
- peerId: "viewer_12345678",
- sessionId: "session_12345678",
- },
- nowMs,
- );
-
- expect(grant.urls).toEqual(config.urls);
- expect(grant.expiresAtMs).toBe(
- Math.floor(nowMs / 1_000) * 1_000 + 300_000,
- );
- expect(grant.expiresAt).toBe(new Date(grant.expiresAtMs).toISOString());
- expect(grant.username).toMatch(/^[1-9]\d{9}:[A-Za-z0-9_-]{32}$/);
- expect(grant.username).not.toContain("123456789012");
- expect(grant.username).not.toContain("viewer_12345678");
- expect(grant.credential).toBe(
- createHmac("sha1", config.sharedSecret)
- .update(grant.username)
- .digest("base64"),
- );
- });
-
- it("changes the opaque bearer across sessions and issuance windows", () => {
- const identity = {
- roomId: "1",
- role: "host" as const,
- peerId: "host_12345678",
- sessionId: "session_12345678",
- };
- const first = issuePeerIceTurnGrant(config, identity, 1_000_000);
- const otherSession = issuePeerIceTurnGrant(
- config,
- { ...identity, sessionId: "session_87654321" },
- 1_000_000,
- );
- const later = issuePeerIceTurnGrant(config, identity, 1_001_000);
-
- expect(otherSession.username).not.toBe(first.username);
- expect(later.username).not.toBe(first.username);
- expect(() => issuePeerIceTurnGrant(config, identity, Number.NaN)).toThrow(
- "grant time is invalid",
- );
- });
-});
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 6fd38d00..8e93c931 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -88,13 +88,10 @@ describe("client signaling protocol", () => {
}
});
- it("accepts the capability-gated ICE refresh request", () => {
+ it("rejects the removed all-room ICE refresh request", () => {
expect(clientMessageSchema.safeParse({ type: "refresh-ice" }).success).toBe(
- true,
+ false,
);
- expect(
- clientMessageSchema.safeParse({ type: "refresh-ice", roomId }).success,
- ).toBe(false);
});
it("accepts a bounded authentication message", () => {
@@ -121,18 +118,6 @@ describe("client signaling protocol", () => {
}),
),
).toMatchObject({ viewerGrant });
- expect(
- decodeClientMessage(
- JSON.stringify({
- type: "authenticate",
- protocol: SIGNALING_PROTOCOL,
- roomId,
- role: "viewer",
- clientId: "client_12345678",
- capabilities: { peerIceTurn: true },
- }),
- ),
- ).toMatchObject({ capabilities: { peerIceTurn: true } });
expect(
clientMessageSchema.safeParse({
type: "authenticate",
@@ -140,7 +125,7 @@ describe("client signaling protocol", () => {
roomId,
role: "viewer",
clientId: "client_12345678",
- capabilities: { peerIceTurn: false },
+ capabilities: { peerIceTurn: true },
}).success,
).toBe(false);
expect(
@@ -615,22 +600,13 @@ describe("client signaling protocol", () => {
});
describe("server signaling protocol", () => {
- it("accepts only authenticated UDP TURN credentials paired with expiry", () => {
+ it("rejects the removed all-room TURN credential wire", () => {
expect(
serverMessageSchema.safeParse({
type: "ice-config",
- iceConfig: {
- iceServers: [
- {
- urls: "turn:relay.example.test:3478?transport=udp",
- username: `1787076000:${"a".repeat(32)}`,
- credential: "credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:00:00.000Z",
- },
+ iceConfig: { iceServers: [] },
}).success,
- ).toBe(true);
+ ).toBe(false);
expect(
serverMessageSchema.safeParse({
...authenticatedMessage(8),
diff --git a/tests/server-config.test.ts b/tests/server-config.test.ts
index 19e419d5..82321413 100644
--- a/tests/server-config.test.ts
+++ b/tests/server-config.test.ts
@@ -14,96 +14,6 @@ describe("server configuration", () => {
expect(config.peerAssistedMedia).toBe(false);
expect(config.peerAssistedRoomIds).toBeUndefined();
expect(config.livekitFallback).toBeUndefined();
- expect(config.peerIceTurn).toBeUndefined();
- expect(
- loadConfig({
- PEER_ICE_TURN_URLS: "",
- PEER_ICE_TURN_SHARED_SECRET: "",
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "",
- }).peerIceTurn,
- ).toBeUndefined();
- });
-
- it("enables Peer ICE TURN only from a complete exact-room tuple", () => {
- const config = loadConfig({
- PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
- PEER_ICE_TURN_URLS: "turn:relay-a.test:3478?transport=udp",
- PEER_ICE_TURN_SHARED_SECRET: "t".repeat(32),
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "300",
- });
-
- expect(config.peerIceTurn).toEqual({
- urls: ["turn:relay-a.test:3478?transport=udp"],
- sharedSecret: "t".repeat(32),
- credentialTtlSeconds: 300,
- });
- });
-
- it.each([
- { PEER_ICE_TURN_URLS: "turn:relay.test:3478?transport=udp" },
- { PEER_ICE_TURN_SHARED_SECRET: "t".repeat(32) },
- { PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "300" },
- {
- PEER_ICE_TURN_URLS: "",
- PEER_ICE_TURN_SHARED_SECRET: "t".repeat(32),
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "300",
- },
- ])("rejects a partial Peer ICE TURN tuple", (partial) => {
- expect(() => loadConfig(partial)).toThrow(
- "PEER_ICE_TURN_URLS, PEER_ICE_TURN_SHARED_SECRET, and PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS must be configured together",
- );
- });
-
- it("bounds Peer ICE TURN transport, secret, TTL, and feature ownership", () => {
- const tuple = {
- PEER_ICE_TURN_URLS: "turn:relay.test:3478?transport=udp",
- PEER_ICE_TURN_SHARED_SECRET: "t".repeat(32),
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "300",
- };
- expect(() => loadConfig(tuple)).toThrow(
- "Peer ICE TURN requires PEER_ASSISTED_MEDIA=true",
- );
- for (const url of [
- "turn:relay.test:3478",
- "turn:relay.test:3478?transport=tcp",
- "turns:relay.test:5349?transport=udp",
- ]) {
- expect(() =>
- loadConfig({ ...tuple, PEER_ICE_TURN_URLS: url }),
- ).toThrow("PEER_ICE_TURN_URLS");
- }
- for (const ttl of ["299", "1801", "1.5"]) {
- expect(() =>
- loadConfig({
- ...tuple,
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: ttl,
- }),
- ).toThrow("PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS");
- }
- expect(() =>
- loadConfig({ ...tuple, PEER_ICE_TURN_SHARED_SECRET: "short" }),
- ).toThrow("PEER_ICE_TURN_SHARED_SECRET");
- expect(() =>
- loadConfig({
- ...tuple,
- PEER_ICE_TURN_URLS:
- "turn:relay-a.test:3478?transport=udp,turn:relay-b.test:3478?transport=udp",
- }),
- ).toThrow("PEER_ICE_TURN_URLS must contain at most 1 URL");
- });
-
- it("requires an independent Peer ICE TURN shared secret", () => {
- expect(() =>
- loadConfig({
- HOST_ADMISSION_PASSWORD: "x".repeat(32),
- PEER_ASSISTED_MEDIA: "true",
- PEER_ASSISTED_ROOM_IDS: "1",
- PEER_ICE_TURN_URLS: "turn:relay.test:3478?transport=udp",
- PEER_ICE_TURN_SHARED_SECRET: "x".repeat(32),
- PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS: "300",
- }),
- ).toThrow("PEER_ICE_TURN_SHARED_SECRET must use independent values");
});
it("enables LiveKit fallback only for a complete credential tuple", () => {
@@ -414,6 +324,9 @@ describe("server configuration", () => {
"TURN_URLS",
"TURN_SHARED_SECRET",
"TURN_CREDENTIAL_TTL_SECONDS",
+ "PEER_ICE_TURN_URLS",
+ "PEER_ICE_TURN_SHARED_SECRET",
+ "PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS",
] as const)("rejects removed TURN configuration even when %s is blank", (name) => {
expect(() => loadConfig({ [name]: "" })).toThrow(
`${name} is no longer supported`,
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 647c3bc0..a8fc4804 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -19,10 +19,7 @@ import {
createScreenerServer,
type ScreenerServer,
} from "../src/server/app.ts";
-import type {
- PeerIceTurnConfig,
- ServerConfig,
-} from "../src/server/config.ts";
+import type { ServerConfig } from "../src/server/config.ts";
import { RoomDatabase } from "../src/server/room-database.ts";
import { RoomStore, type CreatedRoom } from "../src/server/room-store.ts";
import { SignalingServer } from "../src/server/signaling.ts";
@@ -170,7 +167,6 @@ async function startHarness(
persistent?: boolean;
provisionalHostClaimSeconds?: number;
peerAssistedMedia?: boolean;
- peerIceTurn?: PeerIceTurnConfig;
stunUrls?: readonly string[];
now?: () => number;
} = {},
@@ -178,7 +174,6 @@ async function startHarness(
const config = testConfig();
config.hostAdmissionPassword = overrides.hostAdmissionPassword;
config.peerAssistedMedia = overrides.peerAssistedMedia ?? false;
- config.peerIceTurn = overrides.peerIceTurn;
config.stunUrls = overrides.stunUrls ?? [];
const maxViewersPerRoom = overrides.maxViewersPerRoom ?? 8;
config.maxViewersPerRoom = maxViewersPerRoom;
@@ -439,7 +434,6 @@ async function authenticate(
relayCapacity: 0 | 1 | null = 1,
shareGeneration?: string,
presence: { displayName?: string; viewerPresence?: true } = {},
- peerIceTurnCapable = false,
) {
client.socket.send(
JSON.stringify(
@@ -453,9 +447,6 @@ async function authenticate(
clientId,
...(shareGeneration ? { shareGeneration } : {}),
...(presence.viewerPresence ? { viewerPresence: true } : {}),
- ...(peerIceTurnCapable
- ? { capabilities: { peerIceTurn: true } }
- : {}),
}
: {
type: "authenticate",
@@ -467,9 +458,6 @@ async function authenticate(
...(presence.displayName
? { displayName: presence.displayName }
: {}),
- ...(peerIceTurnCapable
- ? { capabilities: { peerIceTurn: true } }
- : {}),
},
),
);
@@ -1583,137 +1571,6 @@ describe("WebSocket signaling", () => {
await viewer.inbox.expectNone(30);
});
- it("scopes Peer ICE TURN to capable sessions in the exact room and refreshes once per window", async () => {
- let nowMs = Date.parse("2026-08-20T12:00:00.000Z");
- const harness = await startHarness({
- peerAssistedMedia: true,
- stunUrls: ["stun:stun.example.test:3478"],
- peerIceTurn: {
- urls: ["turn:relay.example.test:3478?transport=udp"],
- sharedSecret: "turn-test-secret-that-is-at-least-32-bytes",
- credentialTtlSeconds: 300,
- },
- now: () => nowMs,
- });
-
- const host = await openClient(harness.webSocketUrl);
- const hostAuth = peerAssisted(
- await authenticate(
- host,
- harness.room,
- "host",
- "peer-turn-host",
- 1,
- undefined,
- {},
- true,
- ),
- );
- const firstTurn = hostAuth.iceConfig.iceServers.find(
- (server) => "username" in server,
- );
- expect(firstTurn).toBeDefined();
- expect(hostAuth.iceConfig.turnCredentialsExpiresAt).toBe(
- "2026-08-20T12:05:00.000Z",
- );
-
- host.socket.send(JSON.stringify({ type: "refresh-ice" }));
- const reused = await host.inbox.next("ice-config");
- expect(reused.iceConfig).toEqual(hostAuth.iceConfig);
- host.socket.send(JSON.stringify({ type: "refresh-ice" }));
- expect(await host.inbox.next("error")).toMatchObject({
- code: "FORBIDDEN",
- message: "Peer ICE refresh is rate limited",
- });
-
- nowMs += 180_000;
- host.socket.send(JSON.stringify({ type: "refresh-ice" }));
- const rotated = await host.inbox.next("ice-config");
- expect(rotated.iceConfig.turnCredentialsExpiresAt).toBe(
- "2026-08-20T12:08:00.000Z",
- );
- expect(
- rotated.iceConfig.iceServers.find((server) => "username" in server),
- ).not.toEqual(firstTurn);
-
- const legacyViewer = await openClient(harness.webSocketUrl);
- const legacyAuth = await authenticate(
- legacyViewer,
- harness.room,
- "viewer",
- "native-shaped-viewer",
- );
- expect(
- legacyAuth.iceConfig.iceServers.some((server) => "username" in server),
- ).toBe(false);
- expect(legacyAuth.iceConfig.turnCredentialsExpiresAt).toBeUndefined();
- legacyViewer.socket.send(JSON.stringify({ type: "refresh-ice" }));
- expect((await legacyViewer.inbox.next("error")).code).toBe("FORBIDDEN");
-
- const ordinaryRoom = harness.roomStore.createRoom();
- const ordinaryHost = await openClient(harness.webSocketUrl);
- const ordinaryAuth = await authenticate(
- ordinaryHost,
- ordinaryRoom,
- "host",
- "ordinary-capable-host",
- 1,
- undefined,
- {},
- true,
- );
- expect(
- ordinaryAuth.iceConfig.iceServers.some((server) => "username" in server),
- ).toBe(false);
- ordinaryHost.socket.send(JSON.stringify({ type: "refresh-ice" }));
- expect((await ordinaryHost.inbox.next("error")).code).toBe("FORBIDDEN");
- });
-
- it("issues a new participant-session bearer after session replacement", async () => {
- const harness = await startHarness({
- peerAssistedMedia: true,
- peerIceTurn: {
- urls: ["turn:relay.example.test:3478?transport=udp"],
- sharedSecret: "turn-test-secret-that-is-at-least-32-bytes",
- credentialTtlSeconds: 300,
- },
- now: () => Date.parse("2026-08-20T12:00:00.000Z"),
- });
- const first = await openClient(harness.webSocketUrl);
- const firstAuth = await authenticate(
- first,
- harness.room,
- "viewer",
- "replaceable-turn-viewer",
- 1,
- undefined,
- {},
- true,
- );
- const replaced = new Promise<number>((resolve) => {
- first.socket.once("close", (code) => resolve(code));
- });
-
- const second = await openClient(harness.webSocketUrl);
- const secondAuth = await authenticate(
- second,
- harness.room,
- "viewer",
- "replaceable-turn-viewer",
- 1,
- undefined,
- {},
- true,
- );
-
- expect(await replaced).toBe(4001);
- expect(
- secondAuth.iceConfig.iceServers.find((server) => "username" in server),
- ).not.toEqual(
- firstAuth.iceConfig.iceServers.find((server) => "username" in server),
- );
- });
-
it("isolates the routing allowlist while ordinary ICE stays STUN-only", async () => {
const harness = await startSfuHarness({
tokenIssuer: { issueToken: async () => "unused-test-token" },
diff --git a/tests/viewer-peer-generation.test.ts b/tests/viewer-peer-generation.test.ts
index f75f798b..3979e085 100644
--- a/tests/viewer-peer-generation.test.ts
+++ b/tests/viewer-peer-generation.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { SignalPayload } from "../src/shared/protocol.ts";
+import type { IceConfig, SignalPayload } from "../src/shared/protocol.ts";
import type { PeerSnapshot } from "../src/client/types.ts";
import { ViewerPeer } from "../src/client/webrtc/viewer-peer.ts";
@@ -138,9 +138,10 @@ function createPeer(
signals: SignalPayload[],
snapshots: PeerSnapshot[],
signalPeers: string[] = [],
+ iceConfig: IceConfig = { iceServers: [] },
): ViewerPeer {
return new ViewerPeer(
- { iceServers: [] },
+ iceConfig,
{
sendSignal: (peerId, payload) => {
signalPeers.push(peerId);
@@ -193,36 +194,34 @@ afterEach(() => {
});
describe("ViewerPeer connection generations", () => {
- it("keeps standard ICE direct-first while refreshing future gathering", async () => {
- const peer = createPeer([], []);
- await peer.acceptSignal("host", offer("turn-config"));
+ it("applies STUN-only ICE configuration at creation and update", async () => {
+ const peer = createPeer([], [], [], {
+ iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }],
+ });
+ await peer.acceptSignal("host", offer("stun-config"));
const connection = FakePeerConnection.instances[0]!;
- expect(connection.configurations).toEqual([
- { iceServers: [], iceTransportPolicy: "all" },
- ]);
peer.updateIceConfig({
- iceServers: [
- {
- urls: ["turn:relay.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- turnCredentialsExpiresAt: "2026-08-20T12:00:00.000Z",
+ iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }],
});
+ expect(connection.configurations).toEqual([
+ { iceServers: [{ urls: ["stun:stun-a.example.test:3478"] }] },
+ { iceServers: [{ urls: ["stun:stun-b.example.test:3478"] }] },
+ ]);
expect(connection.setConfiguration).toHaveBeenCalledOnce();
- expect(connection.configurations[1]).toEqual({
- iceServers: [
- {
- urls: ["turn:relay.test:3478?transport=udp"],
- username: `1787076000:${"a".repeat(32)}`,
- credential: "temporary-credential",
- },
- ],
- iceTransportPolicy: "all",
- });
+ for (const configuration of connection.configurations) {
+ expect(
+ configuration.iceServers?.every(
+ (server) =>
+ !Reflect.has(server, "username") &&
+ !Reflect.has(server, "credential") &&
+ (typeof server.urls === "string"
+ ? server.urls.startsWith("stun:")
+ : server.urls.every((url) => url.startsWith("stun:"))),
+ ),
+ ).toBe(true);
+ }
});
it("restarts ICE when an answered initial connection stays stuck", async () => {