Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(media): add restricted host SFU selected-edge TURN
AAA4b52aadda71e
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 8d842e67..687cf48a 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -83,6 +83,9 @@ TURN config, issuer, capability, refresh wire, or client propagation. Stale`PEER_ICE_TURN_*` keys fail startup even when blank. The source candidate nowimplements a complete default-off selected-edge tuple and one post-SFUrelay-only rebuild; it remains undeployed and lacks real TURN/media evidence.+The wire has two explicit edge kinds: `peer-selected` for the last-mile failed+peer edge and `host-sfu-ingress` for an exact-room-`1` restricted Host-to-SFU+retry. Ordinary Peer ICE remains STUN-only.The current runtime removes the old all-room coturn contract. Productionrequires STUN and authenticated ICE snapshots contain only STUN servers in@@ -290,10 +293,13 @@ complete LiveKit tuple.8. An active Viewer SFU root may request one fresh short-lived grant. If its nextfailure, or the initial SFU prepare, is exhausted, the router grants at most- one relay-only rebuild of that Viewer's original failed peer edge. Failure is+ one relay-only rebuild of that Viewer's original failed peer edge. An active+ Host-to-SFU route may instead receive one `host-sfu-ingress` relay-only grant+ when the explicit restricted-source decision applies to exact room `1`; the+ grant is bound to the host session and publication generation. Failure isterminal for that attempt; stop, session replacement, topology revision or a- new sharing generation clears it. Host publisher/global SFU failure retains- the existing bounded peer failback.+ new sharing generation clears it, then the existing bounded peer failback+ remains available.Production logs on 2026-08-20 observed two root participants for about 4.6seconds and two short Host participants (about 0.46 and 0.27 seconds), all ending@@ -411,9 +417,13 @@ their bounded peer descendants. Only an edge that also cannot use SFU/UDP mayreceive a controller-selected authenticated TURN attempt. Production currentlyends in bounded failure and has no application TURN config. Source has noparticipant-wide TURN path: the rejected candidate is removed and its stale-environment keys fail startup. The default-off selected-edge source candidate-uses a short coturn REST bearer and one server-generated connection identity for-the exact failed parent/Viewer pair. It is undeployed and has no real relay-media evidence.+environment keys fail startup. The default-off selected-edge source candidate uses+a short coturn REST bearer and one server-generated connection identity per explicit+edge kind. `peer-selected` binds the failed parent/Viewer pair; `host-sfu-ingress`+binds exact room `1`, the host session, the SFU publication generation, and the+old/new connection identities. The Host client applies that grant only to a+relay-only LiveKit publisher `RTCConfiguration`. It is undeployed and has no real+relay-media evidence.LiveKit participant-wide embedded/external TURN remains a separate ICE domain.The bounded cost model, privacy-safe ICE fields, and exact-room A/B sequencediff --git a/docs/status.md b/docs/status.mdindex 7580d03e..f00210f9 100644--- a/docs/status.md+++ b/docs/status.md@@ -1,6 +1,6 @@# Current Status-Last updated: 2026-08-20+Last updated: 2026-08-21## Phase@@ -38,7 +38,7 @@ automatic peer/SFU-UDP controller with at most two SFU roots. The old- The `a11a73d` built-in TURN canary is rejected: local allocation passed, but direct Host/Pion Viewer failed before forced relay. Full rollback restored STUN-only client ICE and zero allocations.- Native VP8 loopback (Chrome 151) reached one Viewer: 30 sender frames, 85 source RTP packets, 877 inbound packets, 299 decoded/rendered at 1280x720, no fatal. Pion outbound delta missed a 2s refresh; hardware/multi-viewer/FIFO/endurance/public/native proof remains open.- Access protocol/config/HTTP/storage/SQLite/signaling focused tests pass, including commit-first teardown and v1 rollback.-- Selected-edge typecheck and 131 focused control tests pass; no TURN allocation/media evidence exists.+- Source adds room-1 Host ingress + peer last-mile; Peer ICE STUN-only; 160 tests pass.- Prepared artifact `screener-61a87ae47e38abc943cef47b3d7318bb51bf86d6-20260820T143538Z.tar.gz` (883597 bytes, SHA-256 `d5b4d6cc567ba96ce37f8eb9934dd5822c64dc084796047d5f6d6217e2e74acb`) was the sole Host-name cutover candidate. Its prepare-to-release and health gates passed before the stale restart-count assertion caused automatic rollback; `fdd14ba` is healthy with all four service restart counts at 0, and Host display-name remains source-only. Selected-edge TURN is disabled.## Unverified Boundaries@@ -68,8 +68,8 @@ duration; one VP8 Viewer decode/render run is recorded. Next prove fresh Pionoutbound diagnostics before viewer 2/FIFO/hardware/endurance/deploy.Audio A/B/C may proceed without displacing P0.Ordinary Peer ICE stays STUN-only; participant-wide TURN is removed. Selected-edge-is source-complete/default-off/undeployed. Next run one isolated forced-relay-canary; retained performance/resource benchmarks follow functional landing.+is source-complete/default-off/undeployed; Host ingress still needs one forced-relay+canary before activation. Retained performance/resource benchmarks follow landing.ADR-0004 still requires a full-resolution 30-minute `1/3/5/8` network,resource, quality, latency, recovery, and browser/mobile-leaf matrix. A separatediff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.tsindex f4f41097..9adaf268 100644--- a/src/client/media/host-sfu-route.ts+++ b/src/client/media/host-sfu-route.ts@@ -40,6 +40,8 @@ interface HostPublisherSlot {active: boolean;failed: boolean;acknowledgeActive: boolean;+ connectionId: string;+ selectedEdgeTurn: boolean;}interface HostSfuRouteEvents {@@ -60,6 +62,12 @@ export class HostSfuRoute {private resyncGeneration = 0;private resyncing = false;private closed = false;+ private lastConfig: Extract<ServerMessage, { type: "sfu-config" }> | null =+ null;+ private selectedEdgeTurn: Extract<+ ServerMessage,+ { type: "selected-edge-turn"; edgeKind: "host-sfu-ingress" }+ > | null = null;constructor(private readonly events: HostSfuRouteEvents) {}@@ -75,6 +83,8 @@ export class HostSfuRoute {if (previousRevision !== update.revision) {this.recovery = null;this.lastFailureStage = null;+ this.lastConfig = null;+ this.selectedEdgeTurn = null;}if (update.phase === "prepare") {if (@@ -170,6 +180,7 @@ export class HostSfuRoute {if (!token || !phase || !assignment || !publicationGeneration) {return;}+ this.lastConfig = message;if (this.active?.publicationGeneration === publicationGeneration) {this.active.revision = message.revision;@@ -196,6 +207,13 @@ export class HostSfuRoute {const publisher =this.events.createPublisher?.(() => this.handleFailure(slot)) ??new SfuPublisher({ onDisconnected: () => this.handleFailure(slot) });+ const selectedEdgeTurn =+ this.selectedEdgeTurn?.revision === message.revision &&+ this.selectedEdgeTurn.publicationGeneration === publicationGeneration &&+ this.selectedEdgeTurn.oldConnectionId === publicationGeneration+ ? this.selectedEdgeTurn+ : null;+ this.selectedEdgeTurn = null;slot = {revision: message.revision,publicationGeneration,@@ -204,12 +222,22 @@ export class HostSfuRoute {active: false,failed: false,acknowledgeActive: false,+ connectionId: selectedEdgeTurn?.newConnectionId ?? publicationGeneration,+ selectedEdgeTurn: selectedEdgeTurn !== null,};this.pending = slot;try {const connected = await publisher.connect({url: message.url,token: message.token,+ ...(selectedEdgeTurn+ ? {+ rtcConfig: {+ iceServers: [selectedEdgeTurn.iceServer],+ iceTransportPolicy: "relay",+ },+ }+ : {}),});if (!connected) {if (this.pending === slot && this.route.owns(token)) {@@ -234,6 +262,37 @@ export class HostSfuRoute {}}+ /** Apply one controller-selected TURN grant to the next SFU publisher PC. */+ startSelectedEdgeTurn(+ message: Extract<+ ServerMessage,+ { type: "selected-edge-turn"; edgeKind: "host-sfu-ingress" }+ >,+ ): boolean {+ if (+ this.closed ||+ this.active !== null ||+ !this.route.acceptsConfig(message.revision) ||+ Date.parse(message.expiresAt) <= Date.now()+ ) {+ return false;+ }+ const assignment = this.route.getPlannedAssignment();+ const publicationGeneration = assignment?.sfuPublicationGeneration;+ if (+ !publicationGeneration ||+ publicationGeneration !== message.publicationGeneration ||+ message.oldConnectionId !== publicationGeneration ||+ !this.lastConfig ||+ this.lastConfig.revision !== message.revision+ ) {+ return false;+ }+ this.selectedEdgeTurn = message;+ void this.acceptConfig(this.lastConfig);+ return true;+ }+updateProfile(profile: QualityProfile): Promise<boolean> {return this.active?.active? this.active.publisher.updateProfile(profile).catch(() => false)@@ -282,6 +341,8 @@ export class HostSfuRoute {this.resyncing = false;this.route.reset();this.recovery = null;+ this.lastConfig = null;+ this.selectedEdgeTurn = null;await this.queueTransition(async () => {const pending = this.pending;const active = this.active;@@ -516,17 +577,22 @@ export class HostSfuRoute {}if (phase === "prepare") {if (matchesPlannedRoute || wasActive) {- this.routeFailed(revision, "prepare");+ // Selected-edge ingress is only issued for an active SFU route.+ // Prepare failures retain the existing null connection contract.+ this.routeFailed(revision, "prepare", null);}return;}if (!matchesPlannedRoute) {return;}- this.requestRecovery(revision);+ this.requestRecovery(revision, slot);}- private requestRecovery(revision: number): void {+ private requestRecovery(+ revision: number,+ failedSlot?: HostPublisherSlot,+ ): void {if (!this.recovery || this.recovery.revision !== revision) {this.recovery = { revision, refreshed: false };}@@ -536,15 +602,23 @@ export class HostSfuRoute {return;}}- this.routeFailed(revision, "active");+ this.routeFailed(+ revision,+ "active",+ failedSlot?.selectedEdgeTurn ? failedSlot.connectionId : null,+ );}- private routeFailed(revision: number, phase: MediaRoutePhase): void {+ private routeFailed(+ revision: number,+ phase: MediaRoutePhase,+ connectionId: string | null,+ ): void {this.events.send({type: "route-failed",revision,phase,- connectionId: null,+ connectionId,});}diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex 8900d289..74d0d01e 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -97,7 +97,10 @@ type ViewerQualityEvidence = Extract<ServerMessage,{ type: "viewer-quality-evidence" }>;-type SelectedEdgeTurn = Extract<ServerMessage, { type: "selected-edge-turn" }>;+type SelectedEdgeTurn = Extract<+ ServerMessage,+ { type: "selected-edge-turn"; edgeKind: "peer-selected" }+>;interface CaptureDetails {resolution: string;@@ -889,6 +892,18 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {return;}if (message.type === "selected-edge-turn") {+ if (message.edgeKind === "host-sfu-ingress") {+ if (+ peerAssistedRef.current &&+ message.hostPeerId === hostPeerIdRef.current &&+ message.revision === activeRouteRevisionRef.current &&+ Date.parse(message.expiresAt) > Date.now()+ ) {+ const route = ensureHostSfuRoute(generation);+ route.startSelectedEdgeTurn(message);+ }+ return;+ }const current = peersRef.current.get(message.viewerPeerId);const oldConnectionId =current?.connectionId ??diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex 4ea0dee6..d49785b5 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -75,7 +75,10 @@ type ViewerQualityEvidence = Extract<ServerMessage,{ type: "viewer-quality-evidence" }>;-type SelectedEdgeTurn = Extract<ServerMessage, { type: "selected-edge-turn" }>;+type SelectedEdgeTurn = Extract<+ ServerMessage,+ { type: "selected-edge-turn"; edgeKind: "peer-selected" }+>;export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const [accessState, setAccessState] = useState<@@ -646,6 +649,9 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {return;}if (message.type === "selected-edge-turn") {+ if (message.edgeKind !== "peer-selected") {+ return;+ }if (!peerAssisted ||message.revision !== currentRouteRevision ||diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.tsindex 1520ad8e..9a2ca1af 100644--- a/src/client/sfu/publisher.ts+++ b/src/client/sfu/publisher.ts@@ -18,6 +18,8 @@ import {export interface SfuConnectionConfig {url: string;token: string;+ /** Optional controller-selected ICE override for this one publisher PC. */+ rtcConfig?: RTCConfiguration;}interface PublisherEvents {@@ -97,7 +99,10 @@ export class SfuPublisher {}});- await room.connect(config.url, config.token, { autoSubscribe: false });+ await room.connect(config.url, config.token, {+ autoSubscribe: false,+ ...(config.rtcConfig ? { rtcConfig: config.rtcConfig } : {}),+ });if (!this.owns(room, generation)) {await safeDisconnect(room);return false;diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.tsindex 1f17d0a4..e29b2ddb 100644--- a/src/client/webrtc/viewer-relay.ts+++ b/src/client/webrtc/viewer-relay.ts@@ -11,7 +11,10 @@ interface ViewerRelayEvents {sendSignal: (peerId: string, payload: SignalPayload) => boolean;onUpdate?: (snapshot: PeerSnapshot | null) => void;}-type SelectedEdgeTurn = Extract<ServerMessage, { type: "selected-edge-turn" }>;+type SelectedEdgeTurn = Extract<+ ServerMessage,+ { type: "selected-edge-turn"; edgeKind: "peer-selected" }+>;export class ViewerRelay {private childPeerId: string | null = null;diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsindex 9b856d9c..cefa6c00 100644--- a/src/server/hybrid-media-router.ts+++ b/src/server/hybrid-media-router.ts@@ -72,6 +72,19 @@ interface SelectedEdgeTurnAttempt {timer: NodeJS.Timeout;}+interface SelectedSfuIngressAttempt {+ roomId: string;+ revision: number;+ shareGeneration: string;+ hostPeerId: string;+ hostSessionId: string;+ publicationGeneration: string;+ oldConnectionId: string;+ newConnectionId: string;+ answered: boolean;+ timer: NodeJS.Timeout;+}+interface QualityRouteIntentGuard {viewerSessionId: string;connectionId: string;@@ -171,6 +184,10 @@ export class HybridMediaRouter {string,SelectedEdgeTurnAttempt>();+ private readonly selectedSfuIngressAttempts = new Map<+ string,+ SelectedSfuIngressAttempt+ >();private readonly relayCapacitySessionsByRoom = new Map<string,Map<string, string>@@ -215,6 +232,10 @@ export class HybridMediaRouter {clearTimeout(attempt.timer);}this.selectedEdgeTurnAttempts.clear();+ for (const attempt of this.selectedSfuIngressAttempts.values()) {+ clearTimeout(attempt.timer);+ }+ this.selectedSfuIngressAttempts.clear();this.mediaRouteControllers.clear();this.failedParentPeerIdsByViewer.clear();this.viewerRouteIntentsByRoom.clear();@@ -672,6 +693,14 @@ export class HybridMediaRouter {active.revision === message.revision &&active.assignments.has(participant.peerId)) {+ if (participant.role === "host") {+ this.markSelectedSfuIngressAnswered(+ participant.roomId,+ participant.peerId,+ participant.sessionId,+ message.revision,+ );+ }return;}return;@@ -736,6 +765,17 @@ export class HybridMediaRouter {);return;}+ if (+ hostOwnsGeneration &&+ this.startSelectedSfuIngressTurn(+ participant.roomId,+ participant.peerId,+ participant.sessionId,+ active.revision,+ )+ ) {+ return;+ }if (isSfuRoot &&participant.role === "viewer" &&@@ -993,6 +1033,7 @@ export class HybridMediaRouter {credential = issueSelectedEdgeTurnCredential(config,{+ edgeKind: "peer-selected",roomId,shareGeneration,revision: active.revision,@@ -1042,6 +1083,7 @@ export class HybridMediaRouter {this.selectedEdgeTurnAttempts.set(key, attempt);const message: Extract<ServerMessage, { type: "selected-edge-turn" }> = {type: "selected-edge-turn",+ edgeKind: "peer-selected",revision: attempt.revision,parentPeerId: attempt.parentPeerId,viewerPeerId,@@ -1057,10 +1099,159 @@ export class HybridMediaRouter {return true;}+ /**+ * Restricted source-side fallback for the exact room-1 canary. This is a+ * LiveKit publisher ICE override, not an ordinary peer candidate and not a+ * participant-wide TURN grant.+ */+ private startSelectedSfuIngressTurn(+ roomId: string,+ hostPeerId: string,+ hostSessionId: string,+ revision: number,+ ): boolean {+ const config = this.options.selectedEdgeTurn;+ const fallback = this.options.sfuFallback;+ const controller = this.mediaRouteControllers.get(roomId);+ const active = controller?.getActiveRoute();+ const key = roomId;+ if (+ roomId !== "1" ||+ !config ||+ !fallback ||+ !active ||+ active.revision !== revision ||+ this.selectedSfuIngressAttempts.has(key)+ ) {+ return false;+ }+ const publicationGeneration = active.sfu.publicationGeneration;+ const assignment = active.assignments.get(hostPeerId);+ const host = this.connectedPeer(roomId, hostPeerId);+ const shareGeneration = this.options.getShareGeneration(roomId);+ if (+ !publicationGeneration ||+ assignment?.sfuPublicationGeneration !== publicationGeneration ||+ !host ||+ host.sessionId !== hostSessionId ||+ !shareGeneration+ ) {+ return false;+ }++ const oldConnectionId = publicationGeneration;+ const newConnectionId = randomBytes(16).toString("base64url");+ let credential;+ try {+ credential = issueSelectedEdgeTurnCredential(+ config,+ {+ edgeKind: "host-sfu-ingress",+ roomId,+ shareGeneration,+ revision,+ hostPeerId,+ hostSessionId,+ publicationGeneration,+ oldConnectionId,+ newConnectionId,+ },+ this.options.now?.() ?? Date.now(),+ );+ } catch {+ console.error("Selected-edge TURN credential issuance failed");+ return false;+ }++ const timer = setTimeout(() => {+ const current = this.selectedSfuIngressAttempts.get(key);+ if (+ !current ||+ current.newConnectionId !== newConnectionId ||+ current.answered+ ) {+ return;+ }+ this.selectedSfuIngressAttempts.delete(key);+ this.sendError(+ current.hostSessionId,+ "PEER_NOT_FOUND",+ "Selected SFU relay ingress timed out",+ );+ }, SELECTED_EDGE_TURN_ATTEMPT_TIMEOUT_MS);+ timer.unref();+ const attempt: SelectedSfuIngressAttempt = {+ roomId,+ revision,+ shareGeneration,+ hostPeerId,+ hostSessionId,+ publicationGeneration,+ oldConnectionId,+ newConnectionId,+ answered: false,+ timer,+ };+ this.selectedSfuIngressAttempts.set(key, attempt);+ this.options.sendToSession(hostSessionId, {+ type: "selected-edge-turn",+ edgeKind: "host-sfu-ingress",+ revision,+ hostPeerId,+ publicationGeneration,+ oldConnectionId,+ newConnectionId,+ expiresAt: credential.expiresAt,+ iceServer: credential.iceServer,+ });+ return true;+ }++ private markSelectedSfuIngressAnswered(+ roomId: string,+ hostPeerId: string,+ hostSessionId: string,+ revision: number,+ ): void {+ const attempt = this.selectedSfuIngressAttempts.get(roomId);+ if (+ !attempt ||+ attempt.hostPeerId !== hostPeerId ||+ attempt.hostSessionId !== hostSessionId ||+ attempt.revision !== revision+ ) {+ return;+ }+ attempt.answered = true;+ clearTimeout(attempt.timer);+ this.selectedSfuIngressAttempts.delete(roomId);+ }+private finishSelectedEdgeTurnFailure(participant: AuthenticatedRouteParticipant,message: Extract<ClientMessage, { type: "route-failed" }>,): boolean {+ if (participant.role === "host" && message.connectionId !== null) {+ const attempt = this.selectedSfuIngressAttempts.get(participant.roomId);+ if (+ !attempt ||+ attempt.hostPeerId !== participant.peerId ||+ attempt.hostSessionId !== participant.sessionId ||+ attempt.revision !== message.revision ||+ attempt.newConnectionId !== message.connectionId+ ) {+ return false;+ }+ clearTimeout(attempt.timer);+ this.selectedSfuIngressAttempts.delete(participant.roomId);+ this.sendError(+ participant.sessionId,+ "PEER_NOT_FOUND",+ "Selected SFU relay ingress failed",+ );+ this.failBackToPeerBaseline(participant.roomId);+ return true;+ }if (participant.role !== "viewer" || message.connectionId === null) {return false;}@@ -2051,6 +2242,12 @@ export class HybridMediaRouter {this.selectedEdgeTurnAttempts.delete(key);}}+ for (const [key, attempt] of this.selectedSfuIngressAttempts) {+ if (attempt.roomId === roomId && attempt.revision !== route.revision) {+ clearTimeout(attempt.timer);+ this.selectedSfuIngressAttempts.delete(key);+ }+ }this.clearRoomViewerQualityEvidenceStates(roomId);for (const [peerId, assignment] of route.assignments) {if (peerId === excludedPeerId) {@@ -2192,6 +2389,11 @@ export class HybridMediaRouter {this.selectedEdgeTurnAttempts.delete(key);}}+ const ingress = this.selectedSfuIngressAttempts.get(roomId);+ if (ingress) {+ clearTimeout(ingress.timer);+ this.selectedSfuIngressAttempts.delete(roomId);+ }this.consumedSfuRefreshesByRoom.delete(roomId);this.sfuDisabledRoomIds.delete(roomId);this.clearRoomViewerQualityEvidenceStates(roomId);@@ -2211,6 +2413,11 @@ export class HybridMediaRouter {this.selectedEdgeTurnAttempts.delete(key);}}+ const ingress = this.selectedSfuIngressAttempts.get(roomId);+ if (ingress?.hostPeerId === peerId) {+ clearTimeout(ingress.timer);+ this.selectedSfuIngressAttempts.delete(roomId);+ }}private clearSfuRefreshesForPeer(roomId: string, peerId: string): void {diff --git a/src/server/selected-edge-turn.ts b/src/server/selected-edge-turn.tsindex 1fa18362..9986b521 100644--- a/src/server/selected-edge-turn.ts+++ b/src/server/selected-edge-turn.ts@@ -2,7 +2,8 @@ import { createHmac } from "node:crypto";import type { SelectedEdgeTurnConfig } from "./config.js";-export interface SelectedEdgeTurnIdentity {+export interface PeerSelectedEdgeTurnIdentity {+ edgeKind: "peer-selected";roomId: string;shareGeneration: string;revision: number;@@ -14,6 +15,22 @@ export interface SelectedEdgeTurnIdentity {newConnectionId: string;}+export interface HostSfuIngressTurnIdentity {+ edgeKind: "host-sfu-ingress";+ roomId: string;+ shareGeneration: string;+ revision: number;+ hostPeerId: string;+ hostSessionId: string;+ publicationGeneration: string;+ oldConnectionId: string;+ newConnectionId: string;+}++export type SelectedEdgeTurnIdentity =+ | PeerSelectedEdgeTurnIdentity+ | HostSfuIngressTurnIdentity;+export function issueSelectedEdgeTurnCredential(config: SelectedEdgeTurnConfig,identity: SelectedEdgeTurnIdentity,@@ -24,22 +41,36 @@ export function issueSelectedEdgeTurnCredential(}const expiresAtSeconds =Math.floor(nowMs / 1_000) + config.credentialTtlSeconds;+ const opaquePayload =+ identity.edgeKind === "peer-selected"+ ? [+ "screener-selected-edge-turn-v1",+ identity.roomId,+ identity.shareGeneration,+ identity.revision,+ identity.parentPeerId,+ identity.parentSessionId,+ identity.viewerPeerId,+ identity.viewerSessionId,+ identity.oldConnectionId,+ identity.newConnectionId,+ expiresAtSeconds,+ ]+ : [+ "screener-selected-edge-turn-v2",+ identity.edgeKind,+ identity.roomId,+ identity.shareGeneration,+ identity.revision,+ identity.hostPeerId,+ identity.hostSessionId,+ identity.publicationGeneration,+ identity.oldConnectionId,+ identity.newConnectionId,+ expiresAtSeconds,+ ];const opaqueIdentity = createHmac("sha256", config.sharedSecret)- .update(- JSON.stringify([- "screener-selected-edge-turn-v1",- identity.roomId,- identity.shareGeneration,- identity.revision,- identity.parentPeerId,- identity.parentSessionId,- identity.viewerPeerId,- identity.viewerSessionId,- identity.oldConnectionId,- identity.newConnectionId,- expiresAtSeconds,- ]),- )+ .update(JSON.stringify(opaquePayload)).digest("base64url").slice(0, 32);const username = `${expiresAtSeconds}:${opaqueIdentity}`;diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex 0eda4d69..07d5e7e6 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -692,18 +692,34 @@ export const serverMessageSchema = z.union([token: z.string().min(1).max(MAX_SFU_TOKEN_LENGTH),}).strict(),- z- .object({- type: z.literal("selected-edge-turn"),- revision: mediaRouteRevisionSchema,- parentPeerId: opaqueIdSchema,- viewerPeerId: opaqueIdSchema,- oldConnectionId: opaqueIdSchema,- newConnectionId: opaqueIdSchema,- expiresAt: z.string().datetime(),- iceServer: selectedEdgeTurnIceServerSchema,- })- .strict(),+ z.discriminatedUnion("edgeKind", [+ z+ .object({+ type: z.literal("selected-edge-turn"),+ edgeKind: z.literal("peer-selected"),+ revision: mediaRouteRevisionSchema,+ parentPeerId: opaqueIdSchema,+ viewerPeerId: opaqueIdSchema,+ oldConnectionId: opaqueIdSchema,+ newConnectionId: opaqueIdSchema,+ expiresAt: z.string().datetime(),+ iceServer: selectedEdgeTurnIceServerSchema,+ })+ .strict(),+ z+ .object({+ type: z.literal("selected-edge-turn"),+ edgeKind: z.literal("host-sfu-ingress"),+ revision: mediaRouteRevisionSchema,+ hostPeerId: opaqueIdSchema,+ publicationGeneration: opaqueIdSchema,+ oldConnectionId: opaqueIdSchema,+ newConnectionId: opaqueIdSchema,+ expiresAt: z.string().datetime(),+ iceServer: selectedEdgeTurnIceServerSchema,+ })+ .strict(),+ ]),z.object({type: z.literal("quality-settings"),diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex f23d99b2..956178d3 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -840,6 +840,7 @@ describe("ViewerRelay downstream ownership", () => {expect(relay.startSelectedEdgeTurn({type: "selected-edge-turn",+ edgeKind: "peer-selected",revision: 7,parentPeerId: "selected-parent",viewerPeerId: "selected-child",diff --git a/tests/protocol.test.ts b/tests/protocol.test.tsindex e992dcb2..bfc94698 100644--- a/tests/protocol.test.ts+++ b/tests/protocol.test.ts@@ -946,6 +946,54 @@ describe("server signaling protocol", () => {).toBe(false);});+ it("accepts only explicitly classified selected-edge grants", () => {+ const iceServer = {+ urls: ["turn:relay.example.test:3478?transport=udp"],+ username: `1787076000:${"a".repeat(32)}`,+ credential: "credential",+ };+ expect(+ serverMessageSchema.safeParse({+ type: "selected-edge-turn",+ edgeKind: "peer-selected",+ revision: 1,+ parentPeerId: "parent_12345678",+ viewerPeerId: "viewer_12345678",+ oldConnectionId: "old_12345678",+ newConnectionId: "new_12345678",+ expiresAt: "2026-08-20T12:00:00.000Z",+ iceServer,+ }).success,+ ).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ type: "selected-edge-turn",+ edgeKind: "host-sfu-ingress",+ revision: 1,+ hostPeerId: "host_12345678",+ publicationGeneration: "publication_12345678",+ oldConnectionId: "publication_12345678",+ newConnectionId: "new_12345678",+ expiresAt: "2026-08-20T12:00:00.000Z",+ iceServer,+ }).success,+ ).toBe(true);+ expect(+ serverMessageSchema.safeParse({+ type: "selected-edge-turn",+ edgeKind: "host-sfu-ingress",+ revision: 1,+ hostPeerId: "host_12345678",+ publicationGeneration: "publication_12345678",+ oldConnectionId: "publication_12345678",+ newConnectionId: "new_12345678",+ parentPeerId: "unexpected_12345678",+ expiresAt: "2026-08-20T12:00:00.000Z",+ iceServer,+ }).success,+ ).toBe(false);+ });+it("accepts every bounded hybrid upstream shape", () => {for (const upstream of [{ kind: "none" },diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.tsindex 575780dc..570709eb 100644--- a/tests/route-transition.test.ts+++ b/tests/route-transition.test.ts@@ -245,6 +245,73 @@ describe("HostSfuRoute", () => {]);});+ it("applies a host-SFU selected grant only to a relay-only publisher", async () => {+ const messages: ClientMessage[] = [];+ const publishers: ReturnType<typeof createFakePublisher>[] = [];+ const failures: Array<() => void> = [];+ const route = new HostSfuRoute({+ getStream: () => ({}) as MediaStream,+ getProfile: () => QUALITY_PROFILES["720p30"],+ reconcileChildren: () => undefined,+ send: (message) => {+ messages.push(message);+ return true;+ },+ createPublisher: (onDisconnected) => {+ const publisher = createFakePublisher([], `publisher-${publishers.length + 1}`);+ publishers.push(publisher);+ failures.push(onDisconnected);+ if (publishers.length === 1) {+ publisher.connect.mockResolvedValue(false);+ }+ return publisher;+ },+ });+ const assignment = hostAssignment("generation-a");+ route.accept({ revision: 1, phase: "prepare", assignment });+ await route.acceptConfig(sfuConfig(1));+ expect(messages).toContainEqual({+ type: "route-failed",+ revision: 1,+ phase: "prepare",+ connectionId: null,+ });++ expect(+ route.startSelectedEdgeTurn({+ type: "selected-edge-turn",+ edgeKind: "host-sfu-ingress",+ revision: 1,+ hostPeerId: "host_12345678",+ publicationGeneration: "generation-a",+ oldConnectionId: "generation-a",+ newConnectionId: "selected-connection-new",+ expiresAt: "2030-01-01T00:00:00.000Z",+ iceServer: {+ urls: ["turn:turn.example.test:3478?transport=udp"],+ username: "1787230000:opaque_identity_12345678",+ credential: "short-lived-credential",+ },+ }),+ ).toBe(true);+ await vi.waitFor(() => expect(publishers).toHaveLength(2));+ expect(publishers[1].connect).toHaveBeenCalledWith({+ url: "wss://sfu.example.test",+ token: "token-1",+ rtcConfig: {+ iceServers: [+ {+ urls: ["turn:turn.example.test:3478?transport=udp"],+ username: "1787230000:opaque_identity_12345678",+ credential: "short-lived-credential",+ },+ ],+ iceTransportPolicy: "relay",+ },+ });+ expect(failures).toHaveLength(2);+ });+it("surfaces a bounded publisher stage after active fallback fails", async () => {const publisher = {...createFakePublisher([], "publisher"),diff --git a/tests/selected-edge-turn.test.ts b/tests/selected-edge-turn.test.tsindex 73e40847..5982c7cf 100644--- a/tests/selected-edge-turn.test.ts+++ b/tests/selected-edge-turn.test.ts@@ -7,6 +7,7 @@ const config = {credentialTtlSeconds: 120,};const identity = {+ edgeKind: "peer-selected" as const,roomId: "123456789012",shareGeneration: "share_generation_12345678",revision: 7,@@ -39,4 +40,43 @@ describe("selected-edge TURN", () => {).iceServer.username,).not.toBe(grant.iceServer.username);});++ it("binds a Host-to-SFU ingress grant to its publication generation", () => {+ const grant = issueSelectedEdgeTurnCredential(+ config,+ {+ edgeKind: "host-sfu-ingress",+ roomId: "1",+ shareGeneration: "share_generation_12345678",+ revision: 7,+ hostPeerId: "host_peer_12345678",+ hostSessionId: "host_session_12345678",+ publicationGeneration: "publication_generation_12345678",+ oldConnectionId: "publication_generation_12345678",+ newConnectionId: "new_connection_12345678",+ },+ 1_700_000_000_000,+ );++ expect(grant.iceServer.username).toMatch(+ /^1700000120:[A-Za-z0-9_-]{32}$/,+ );+ expect(+ issueSelectedEdgeTurnCredential(+ config,+ {+ edgeKind: "host-sfu-ingress",+ roomId: "1",+ shareGeneration: "share_generation_12345678",+ revision: 7,+ hostPeerId: "host_peer_12345678",+ hostSessionId: "host_session_12345678",+ publicationGeneration: "publication_generation_87654321",+ oldConnectionId: "publication_generation_87654321",+ newConnectionId: "new_connection_12345678",+ },+ 1_700_000_000_000,+ ).iceServer.username,+ ).not.toBe(grant.iceServer.username);+ });});diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex 056c31df..96ed034c 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -4062,6 +4062,9 @@ describe("WebSocket signaling", () => {prepared.rootViewer.inbox.next("selected-edge-turn"),]);expect(parentGrant).toEqual(childGrant);+ if (childGrant.edgeKind !== "peer-selected") {+ throw new Error("expected a peer-selected grant");+ }expect(childGrant.parentPeerId).toBe(prepared.rootAuth.peerId);prepared.rootViewer.socket.send(JSON.stringify({type: "signal",diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.tsindex 7239046c..74423c12 100644--- a/tests/sfu-client.test.ts+++ b/tests/sfu-client.test.ts@@ -314,6 +314,37 @@ describe("SfuPublisher", () => {expect(room.disconnect).toHaveBeenCalledWith(false);});+ it("passes a controller-selected relay-only RTC configuration to LiveKit", async () => {+ const iceServer = {+ urls: ["turn:relay.example.test:3478?transport=udp"],+ username: `1787076000:${"a".repeat(32)}`,+ credential: "short-lived-credential",+ };+ const publisher = new SfuPublisher();++ await expect(+ publisher.connect({+ ...connection,+ rtcConfig: {+ iceServers: [iceServer],+ iceTransportPolicy: "relay",+ },+ }),+ ).resolves.toBe(true);++ expect(livekit.state.rooms[0].connect).toHaveBeenCalledWith(+ connection.url,+ connection.token,+ {+ autoSubscribe: false,+ rtcConfig: {+ iceServers: [iceServer],+ iceTransportPolicy: "relay",+ },+ },+ );+ });+it("retains the bounded stage after connection setup fails", async () => {livekit.state.connectGate = Promise.reject(new Error("connect failed"));const publisher = new SfuPublisher();