Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(native): follow peer-assisted host assignments (#105)
AAA99887381d5d0
diff --git a/docs/project-memory.md b/docs/project-memory.mdindex 32e2e101..805d1dd3 100644--- a/docs/project-memory.md+++ b/docs/project-memory.md@@ -53,7 +53,7 @@ Last updated: 2026-08-21- Chrome 151 synthetic topology/quality runs kept fanout 2/1 and decoding; one relay close recovered in 5.32 seconds. Control evidence only.- Room `1` publishes `HIGH+LOW` with Dynacast off and subscriber `HIGH` ceilings, and now has bounded local quality reparenting. Both remain unverified on real media; test zero-child leaves and calibrated C+B loss before broad rollout.- C+B uses three hard-bad pairs, one-use samples and guarded intent/cooldown. Deployed admission rescue moves the oldest childless zero-capacity Host leaf below an unassigned one-slot relay in one revision; no score/timer/global rebalance. Deployment passed, but no real room triggered it.-- Web Host name/presence and window-audio hint are deployed without changing the Native wire. Native H.264 source and Windows x64 evaluation packaging are present, but no Native release/deployment exists; VP8 remains the Web/production default. See `docs/research/native-h264-opt-in-path.md`.+- Web Host name/presence and window-audio hint are deployed. Native source accepts authenticated peer-assisted direct-child assignments, ignores presence as an edge authority, and reports unsupported SFU/selected ingress as bounded route failure; it does not implement LiveKit or TURN media. Native H.264 source and Windows x64 evaluation packaging are present, but no Native release/deployment exists; VP8 remains the Web/production default. See `docs/research/native-h264-opt-in-path.md`.## Provisional Quality Targetsdiff --git a/docs/status.md b/docs/status.mdindex 17b3e943..da776c4a 100644--- a/docs/status.md+++ b/docs/status.md@@ -18,7 +18,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo- Capture precedes room creation; source/quality changes preserve peers, while pause disables audio/video tracks together and keeps connections. Quality defaults to `maintain-resolution` with balanced/fluid options.- Production access is `screener-v2`: a valid private fragment grant enters directly; every code-only Viewer must first hold site access, after which public-watch accepts the code and private rooms still require their room password. `SITE_ACCESS_PASSWORD`, `/api/site-access`, and the site-access cookie are deployed atomically; raw credentials are never stored.- Web Hosts can set their local/session display name, and the current release advertises it through the existing presence wire. The name is not an account identity.-- Native v2 remains source-only (memory rooms, 300s reclaim); production does not run it.+- Native v2 remains source-only (memory rooms, 300s reclaim); its Host now follows authenticated peer-assisted direct-child assignments with a two-edge cap and bounded SFU/selected-ingress failure, but production does not run it.- PR #44's STUN-only/SFU-UDP router and token-free fallback prewarm are process-enabled for all normal rooms: roots <=2, browser relay <=1, bounded failure. Room `1` is historical smoke; mobile/iPad viewers are leaves, healthy edges sticky, and HTTPS/WSS stays TLS/TCP.- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.- Room `1` can publish exactly `HIGH+LOW` with Dynacast/backup codec off and subscriber `HIGH` ceilings; it has no retained real media frame.@@ -33,6 +33,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo- Chrome 151 loopbacks decoded VP8 299 and H.264 opt-in 299/298 rendered at 1280x720 without fatal/encoder errors. Hardware attribution, Pion timing, multi-viewer/endurance/public/native proof remain open; production stays VP8.- Native Win11 audio is source-only/default-off. Target isolation was 4018x; one Viewer got 495 Opus packets. Package build passes; download, game sync, Win10, and other routes are open.- Access protocol/config/HTTP/storage/SQLite/signaling focused tests pass, including commit-first teardown and v1 rollback.+- Native peer-assisted wire/session focused tests pass: authoritative direct children reconcile at no more than two, presence cannot create a third edge, stale revisions do not rebuild, and unsupported SFU/selected ingress fails once per current revision.- Source adds selected Host ingress and peer last-mile for every enabled room; focused routing/config tests pass with Peer ICE STUN-only.- Host names, the window-audio hint, all-room routing, and all-room Host selected ingress are active; the stale restart assertion is historical only.- The `5e4a367` gate preserved the SQLite hash, v3/five rooms/room `1`, selected-edge/SFU/ordinary-ICE settings, services, and local/public health plus route/asset 200s. Site access returned the unauthenticated status and the retired endpoint returned 404; no TURN/SFU session ran. Exact `c27df2235ecc0be17816f642ca49028e30380a34` is the rollback release.diff --git a/native/sender/internal/remote/session.go b/native/sender/internal/remote/session.goindex 38b9376b..99963ac3 100644--- a/native/sender/internal/remote/session.go+++ b/native/sender/internal/remote/session.go@@ -52,11 +52,11 @@ type Event struct {}type StartOptions struct {- BaseURL *url.URL- SiteAccessPassword string- Codec media.Codec- EnableAudio bool- OnEvent func(Event)+ BaseURL *url.URL+ SiteAccessPassword string+ Codec media.Codec+ EnableAudio bool+ OnEvent func(Event)}type Room struct {@@ -83,6 +83,10 @@ type Session struct {ice iceConfigpeers map[string]*peeradmission *viewerAdmission+ peerAssisted bool+ routeRevision int64+ routePhase string+ routeFailures [2]stringfanout *media.FanoutaudioFanout *media.AudioFanoutcodec media.Codec@@ -334,10 +338,25 @@ func (session *Session) connect(ctx context.Context) error {}session.mu.Lock()session.ice = message.IceConfig- session.admission = newViewerAdmission(message.MaxViewers)+ session.peerAssisted = message.PeerAssisted+ if message.PeerAssisted {+ session.routeRevision = message.RouteRevision+ session.routePhase = "active"+ } else {+ session.admission = newViewerAdmission(message.MaxViewers)+ }session.mu.Unlock()- // viewerPeerIds is a reconciliation roster and can include offline grace- // members. Only ordered peer-joined messages allocate native media edges.+ if message.PeerAssisted {+ if err = session.reconcileAuthoritativeChildren(message.MediaAssignment.ChildPeerIDs); err != nil {+ return err+ }+ publicationGeneration, _ := decodeNullableOpaqueID(message.RouteAssignment.SFUPublicationGeneration)+ if publicationGeneration != "" {+ if err = session.failUnsupportedRoute(message.RouteRevision, "active", nil); err != nil {+ return err+ }+ }+ }session.emitViewerCounts()session.emit(Event{Kind: "remote-ready"})return nil@@ -392,8 +411,14 @@ func (session *Session) completeTerminal(err error) {func (session *Session) handle(message serverMessage) error {switch message.Type {case "peer-joined":+ if session.peerAssisted {+ return nil+ }return session.addViewer(message.PeerID)case "peer-left":+ if session.peerAssisted {+ return nil+ }return session.removeViewer(message.PeerID)case "signal":peer := session.peer(message.FromPeerID)@@ -413,11 +438,29 @@ func (session *Session) handle(message serverMessage) error {} else if err := peer.restartICE(); err != nil {return fmt.Errorf("restart viewer ICE: %w", err)}+ case "media-assignment":+ if !session.peerAssisted {+ return errors.New("peer-assisted assignment arrived in ordinary media mode")+ }+ return session.reconcileAuthoritativeChildren(message.MediaAssignment.ChildPeerIDs)+ case "route-update":+ return session.handleRouteUpdate(message)+ case "sfu-config":+ return session.handleUnsupportedRouteMessage(message, nil)+ case "selected-edge-turn":+ if message.EdgeKind == "host-sfu-ingress" {+ connectionID := message.NewConnectionID+ return session.handleUnsupportedRouteMessage(message, &connectionID)+ }+ return nilcase "viewer-quality-evidence":// Fixed-HIGH observes no viewer feedback; accepting this current-wire// message must not turn it into a room-wide quality controller.return nilcase "error":+ if session.peerAssisted && message.Code == "PEER_NOT_FOUND" {+ return nil+ }return fmt.Errorf("remote signaling error %s", message.Code)case "room-closed":return fmt.Errorf("remote room closed: %s", message.Reason)@@ -513,7 +556,12 @@ func (session *Session) removeViewer(peerID string) error {func (session *Session) rebuildPeer(peerID string) error {session.mu.Lock()- if session.admission == nil || !session.admission.IsActive(peerID) {+ if session.peerAssisted {+ if session.peers[peerID] == nil {+ session.mu.Unlock()+ return nil+ }+ } else if session.admission == nil || !session.admission.IsActive(peerID) {session.mu.Unlock()return nil}@@ -524,14 +572,90 @@ func (session *Session) rebuildPeer(peerID string) error {old.close()}if err := session.activatePeer(peerID); err != nil {- session.mu.Lock()- session.admission.AbortActivation(peerID)- session.mu.Unlock()+ if !session.peerAssisted {+ session.mu.Lock()+ session.admission.AbortActivation(peerID)+ session.mu.Unlock()+ }return err}return nil}+func (session *Session) reconcileAuthoritativeChildren(peerIDs []string) error {+ desired := make(map[string]struct{}, len(peerIDs))+ for _, peerID := range peerIDs {+ desired[peerID] = struct{}{}+ }++ session.mu.Lock()+ retired := make([]*peer, 0, len(session.peers))+ for peerID, activePeer := range session.peers {+ if _, keep := desired[peerID]; !keep {+ delete(session.peers, peerID)+ retired = append(retired, activePeer)+ }+ }+ missing := make([]string, 0, len(peerIDs))+ for _, peerID := range peerIDs {+ if session.peers[peerID] == nil {+ missing = append(missing, peerID)+ }+ }+ session.mu.Unlock()+ for _, activePeer := range retired {+ activePeer.close()+ }+ for _, peerID := range missing {+ if err := session.activatePeer(peerID); err != nil {+ return fmt.Errorf("activate authoritative viewer: %w", err)+ }+ }+ session.emitViewerCounts()+ return nil+}++func (session *Session) handleRouteUpdate(message serverMessage) error {+ if !session.peerAssisted {+ return errors.New("route update arrived in ordinary media mode")+ }+ if message.RouteRevision < session.routeRevision {+ return nil+ }+ session.routeRevision = message.RouteRevision+ session.routePhase = message.RoutePhase+ publicationGeneration, _ := decodeNullableOpaqueID(message.RouteAssignment.SFUPublicationGeneration)+ if publicationGeneration != "" {+ return session.failUnsupportedRoute(message.RouteRevision, message.RoutePhase, nil)+ }+ if message.RoutePhase == "active" {+ if err := session.reconcileAuthoritativeChildren(message.RouteAssignment.ChildPeerIDs); err != nil {+ return err+ }+ }+ return session.send(map[string]any{"type": "route-ready", "revision": message.RouteRevision, "phase": message.RoutePhase})+}++func (session *Session) handleUnsupportedRouteMessage(message serverMessage, connectionID *string) error {+ if !session.peerAssisted || message.RouteRevision != session.routeRevision {+ return nil+ }+ return session.failUnsupportedRoute(message.RouteRevision, session.routePhase, connectionID)+}++func (session *Session) failUnsupportedRoute(revision int64, phase string, connectionID *string) error {+ key := fmt.Sprintf("%d/%s", revision, phase)+ reported := &session.routeFailures[0]+ if connectionID != nil {+ reported = &session.routeFailures[1]+ }+ if *reported == key {+ return nil+ }+ *reported = key+ return session.send(map[string]any{"type": "route-failed", "revision": revision, "phase": phase, "connectionId": connectionID})+}+func (session *Session) peer(peerID string) *peer {session.mu.Lock()defer session.mu.Unlock()@@ -588,7 +712,9 @@ func (session *Session) emit(event Event) {func (session *Session) emitViewerCounts() {session.mu.Lock()active, waiting := 0, 0- if session.admission != nil {+ if session.peerAssisted {+ active = len(session.peers)+ } else if session.admission != nil {active, waiting = session.admission.Counts()}session.mu.Unlock()diff --git a/native/sender/internal/remote/session_test.go b/native/sender/internal/remote/session_test.goindex d1fee0ac..34cb3d2e 100644--- a/native/sender/internal/remote/session_test.go+++ b/native/sender/internal/remote/session_test.go@@ -29,7 +29,7 @@ func TestStartUsesSiteAccessCookieAndPrivateV2Room(t *testing.T) {t.Fatal(err)}session, room, err := Start(context.Background(), StartOptions{- BaseURL: baseURL,+ BaseURL: baseURL,SiteAccessPassword: password,})if err != nil {@@ -172,7 +172,7 @@ func TestSiteAccessFailuresAreBoundedAndDoNotLeakSecrets(t *testing.T) {t.Fatal(parseErr)}_, _, startErr := Start(context.Background(), StartOptions{- BaseURL: baseURL,+ BaseURL: baseURL,SiteAccessPassword: password,})if startErr == nil {@@ -358,6 +358,117 @@ func TestSessionSendPropagatesAClosedSignalingConnection(t *testing.T) {}}+func TestPeerAssistedHostUsesOnlyAuthoritativeRoutes(t *testing.T) {+ received := make(chan []byte, 8)+ accepted := make(chan struct{})+ server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {+ connection, err := websocket.Accept(response, request, &websocket.AcceptOptions{InsecureSkipVerify: true})+ if err != nil {+ return+ }+ defer connection.CloseNow()+ close(accepted)+ for {+ _, payload, readErr := connection.Read(request.Context())+ if readErr != nil {+ return+ }+ received <- payload+ }+ }))+ defer server.Close()+ connection, _, err := websocket.Dial(context.Background(), "ws"+server.URL[len("http"):], nil)+ if err != nil {+ t.Fatal(err)+ }+ defer connection.CloseNow()+ <-accepted+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session := &Session{+ signalCtx: ctx, conn: connection, peerAssisted: true,+ peers: make(map[string]*peer), routeRevision: 7, routePhase: "active",+ }++ if err = session.handle(serverMessage{Type: "peer-joined", PeerID: "viewer-new"}); err != nil || len(session.peers) != 0 {+ t.Fatal("peer-joined created a non-authoritative edge")+ }+ direct := participantRouteAssignment{ChildPeerIDs: []string{}}+ direct.Upstream.Kind = "none"+ direct.SFUPublicationGeneration = json.RawMessage("null")+ stale := direct+ stale.ChildPeerIDs = []string{"viewer-stale"}+ if err = session.handle(serverMessage{Type: "route-update", RouteRevision: 6, RoutePhase: "active", RouteAssignment: stale}); err != nil {+ t.Fatal(err)+ }+ select {+ case payload := <-received:+ t.Fatalf("stale route emitted %s", payload)+ case <-time.After(50 * time.Millisecond):+ }++ if err = session.handle(serverMessage{Type: "route-update", RouteRevision: 8, RoutePhase: "active", RouteAssignment: direct}); err != nil {+ t.Fatal(err)+ }+ assertRouteStatus(t, receiveRouteStatus(t, received), "route-ready", 8, "active", nil)++ sfu := direct+ sfu.SFUPublicationGeneration = json.RawMessage(`"publication-1"`)+ sfuUpdate := serverMessage{Type: "route-update", RouteRevision: 9, RoutePhase: "active", RouteAssignment: sfu}+ if err = session.handle(sfuUpdate); err != nil {+ t.Fatal(err)+ }+ assertRouteStatus(t, receiveRouteStatus(t, received), "route-failed", 9, "active", nil)+ if err = session.handle(sfuUpdate); err != nil {+ t.Fatal(err)+ }+ selected := serverMessage{Type: "selected-edge-turn", EdgeKind: "host-sfu-ingress", RouteRevision: 9, NewConnectionID: "connection-new"}+ if err = session.handle(selected); err != nil {+ t.Fatal(err)+ }+ connectionID := "connection-new"+ assertRouteStatus(t, receiveRouteStatus(t, received), "route-failed", 9, "active", &connectionID)+ if err = session.handle(selected); err != nil {+ t.Fatal(err)+ }+ if err = session.handle(sfuUpdate); err != nil {+ t.Fatal(err)+ }+ if err = session.handle(serverMessage{Type: "error", Code: "PEER_NOT_FOUND"}); err != nil {+ t.Fatal("bounded selected-edge fallback became fatal")+ }+ select {+ case payload := <-received:+ t.Fatalf("duplicate route failure emitted %s", payload)+ case <-time.After(50 * time.Millisecond):+ }+}++func receiveRouteStatus(t *testing.T, received <-chan []byte) []byte {+ t.Helper()+ select {+ case payload := <-received:+ return payload+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for route status")+ return nil+ }+}++func assertRouteStatus(t *testing.T, payload []byte, messageType string, revision int64, phase string, connectionID *string) {+ t.Helper()+ var message struct {+ Type string `json:"type"`+ Revision int64 `json:"revision"`+ Phase string `json:"phase"`+ ConnectionID *string `json:"connectionId"`+ }+ if err := json.Unmarshal(payload, &message); err != nil || message.Type != messageType || message.Revision != revision || message.Phase != phase ||+ (connectionID == nil) != (message.ConnectionID == nil) || connectionID != nil && *connectionID != *message.ConnectionID {+ t.Fatalf("route status = %s", payload)+ }+}+func TestCanceledSessionContextStillAbandonsTheFreshRoomExactlyOnce(t *testing.T) {harness := newRemoteHarness(t, []string{})defer harness.Close()diff --git a/native/sender/internal/remote/wire.go b/native/sender/internal/remote/wire.goindex e0e22fa8..610b3d9b 100644--- a/native/sender/internal/remote/wire.go+++ b/native/sender/internal/remote/wire.go@@ -18,6 +18,7 @@ import (const (signalingProtocol = "screener-v2"maxProtocolViewers = 16+ maxRouteRevision = int64(1<<53 - 1)maxSignalSDPBytes = 48 << 10maxQualityEvidence = 2 << 10)@@ -75,21 +76,42 @@ type simpleMessage struct {Type string `json:"type"`}+type mediaAssignment struct {+ ParentPeerID json.RawMessage `json:"parentPeerId"`+ ChildPeerIDs []string `json:"childPeerIds"`+}++type participantRouteAssignment struct {+ Upstream struct {+ Kind string `json:"kind"`+ PeerID *string `json:"peerId,omitempty"`+ } `json:"upstream"`+ ChildPeerIDs []string `json:"childPeerIds"`+ SFUPublicationGeneration json.RawMessage `json:"sfuPublicationGeneration"`+}+type serverMessage struct {- Type string- Role string- PeerID string- FromPeerID string- ViewerPeerIDs []string- ConnectionID string- Rebuild bool- MaxViewers int- IceConfig iceConfig- ViewerPolicy string- Payload inboundSignalPayload- Code string- Message string- Reason string+ Type string+ Role string+ PeerID string+ FromPeerID string+ ViewerPeerIDs []string+ ConnectionID string+ Rebuild bool+ MaxViewers int+ IceConfig iceConfig+ ViewerPolicy string+ Payload inboundSignalPayload+ Code string+ Message string+ Reason string+ PeerAssisted bool+ MediaAssignment mediaAssignment+ RouteAssignment participantRouteAssignment+ RouteRevision int64+ RoutePhase string+ EdgeKind string+ NewConnectionID string}func readServerMessage(ctx context.Context, conn *websocket.Conn) (serverMessage, error) {@@ -148,6 +170,55 @@ func decodeServerMessage(payload []byte) (serverMessage, error) {return serverMessage{}, errors.New("viewer restart request is invalid")}return serverMessage{Type: wire.Type, FromPeerID: wire.FromPeerID, ConnectionID: wire.ConnectionID, Rebuild: *wire.Rebuild}, nil+ case "media-assignment":+ var wire struct {+ Type string `json:"type"`+ MediaAssignment json.RawMessage `json:"mediaAssignment"`+ }+ if err := decodeStrict(payload, &wire); err != nil {+ return serverMessage{}, errors.New("media assignment message is invalid")+ }+ assignment, err := decodeHostMediaAssignment(wire.MediaAssignment)+ if err != nil {+ return serverMessage{}, err+ }+ return serverMessage{Type: wire.Type, MediaAssignment: assignment}, nil+ case "route-update":+ var wire struct {+ Type string `json:"type"`+ Revision int64 `json:"revision"`+ Phase string `json:"phase"`+ Assignment json.RawMessage `json:"assignment"`+ }+ if err := decodeStrict(payload, &wire); err != nil {+ return serverMessage{}, errors.New("route update message is invalid")+ }+ assignment, assignmentErr := decodeHostRouteAssignment(wire.Assignment)+ if wire.Revision < 0 || wire.Revision > maxRouteRevision || assignmentErr != nil || wire.Phase != "prepare" && wire.Phase != "active" {+ return serverMessage{}, errors.New("route update message is invalid")+ }+ return serverMessage{Type: wire.Type, RouteRevision: wire.Revision, RoutePhase: wire.Phase, RouteAssignment: assignment}, nil+ case "sfu-config":+ var wire struct {+ Type string `json:"type"`+ Revision int64 `json:"revision"`+ }+ if err := json.Unmarshal(payload, &wire); err != nil || wire.Revision < 0 || wire.Revision > maxRouteRevision {+ return serverMessage{}, errors.New("SFU configuration message is invalid")+ }+ return serverMessage{Type: wire.Type, RouteRevision: wire.Revision}, nil+ case "selected-edge-turn":+ var wire struct {+ Type string `json:"type"`+ EdgeKind string `json:"edgeKind"`+ Revision int64 `json:"revision"`+ NewConnectionID string `json:"newConnectionId"`+ }+ if err := json.Unmarshal(payload, &wire); err != nil || wire.Revision < 0 || wire.Revision > maxRouteRevision ||+ (wire.EdgeKind != "host-sfu-ingress" && wire.EdgeKind != "peer-selected") || !validOpaqueID(wire.NewConnectionID) {+ return serverMessage{}, errors.New("selected-edge TURN message is invalid")+ }+ return serverMessage{Type: wire.Type, EdgeKind: wire.EdgeKind, RouteRevision: wire.Revision, NewConnectionID: wire.NewConnectionID}, nilcase "viewer-quality-evidence":if err := validateViewerQualityEvidence(payload); err != nil {return serverMessage{}, err@@ -262,6 +333,12 @@ func decodeAuthenticatedMessage(payload []byte) (serverMessage, error) {IceConfig json.RawMessage `json:"iceConfig"`ViewerPolicy string `json:"viewerPolicy"`ViewerAuthorizationGeneration string `json:"viewerAuthorizationGeneration"`+ MediaMode *string `json:"mediaMode,omitempty"`+ MediaAssignment json.RawMessage `json:"mediaAssignment,omitempty"`+ RouteRevision *int64 `json:"routeRevision,omitempty"`+ RouteAssignment json.RawMessage `json:"routeAssignment,omitempty"`+ QualitySettings json.RawMessage `json:"qualitySettings,omitempty"`+ SFUStandbyURL json.RawMessage `json:"sfuStandbyUrl,omitempty"`}if err := decodeStrict(payload, &wire); err != nil || wire.Type != "authenticated" ||wire.Protocol != signalingProtocol ||@@ -285,17 +362,93 @@ func decodeAuthenticatedMessage(payload []byte) (serverMessage, error) {if err != nil {return serverMessage{}, err}+ peerAssisted := wire.MediaMode != nil+ var assignment mediaAssignment+ var routeAssignment participantRouteAssignment+ var routeRevision int64+ if !peerAssisted {+ if len(wire.MediaAssignment) != 0 || wire.RouteRevision != nil || len(wire.RouteAssignment) != 0 || len(wire.QualitySettings) != 0 || len(wire.SFUStandbyURL) != 0 {+ return serverMessage{}, errors.New("host authentication response is invalid")+ }+ } else {+ if *wire.MediaMode != "peer-assisted" {+ return serverMessage{}, errors.New("host authentication response is invalid")+ }+ assignment, err = decodeHostMediaAssignment(wire.MediaAssignment)+ if err != nil {+ return serverMessage{}, errors.New("host authentication response is invalid")+ }+ routeAssignment, err = decodeHostRouteAssignment(wire.RouteAssignment)+ if err != nil || strings.Join(assignment.ChildPeerIDs, "\x00") != strings.Join(routeAssignment.ChildPeerIDs, "\x00") {+ return serverMessage{}, errors.New("host authentication response is invalid")+ }+ if wire.RouteRevision == nil || *wire.RouteRevision < 0 || *wire.RouteRevision > maxRouteRevision || len(wire.QualitySettings) == 0 {+ return serverMessage{}, errors.New("host authentication response is invalid")+ }+ routeRevision = *wire.RouteRevision+ }return serverMessage{- Type: wire.Type,- Role: wire.Role,- PeerID: wire.PeerID,- MaxViewers: *wire.MaxViewers,- ViewerPeerIDs: append([]string(nil), wire.ViewerPeerIDs...),- IceConfig: config,- ViewerPolicy: wire.ViewerPolicy,+ Type: wire.Type,+ Role: wire.Role,+ PeerID: wire.PeerID,+ MaxViewers: *wire.MaxViewers,+ ViewerPeerIDs: append([]string(nil), wire.ViewerPeerIDs...),+ IceConfig: config,+ ViewerPolicy: wire.ViewerPolicy,+ PeerAssisted: peerAssisted,+ MediaAssignment: assignment,+ RouteAssignment: routeAssignment,+ RouteRevision: routeRevision,}, nil}+func decodeHostMediaAssignment(payload []byte) (mediaAssignment, error) {+ var assignment mediaAssignment+ if err := decodeStrict(payload, &assignment); err != nil || !bytes.Equal(bytes.TrimSpace(assignment.ParentPeerID), []byte("null")) || !validChildPeerIDs(assignment.ChildPeerIDs) {+ return mediaAssignment{}, errors.New("host media assignment is invalid")+ }+ return assignment, nil+}++func decodeHostRouteAssignment(payload []byte) (participantRouteAssignment, error) {+ var assignment participantRouteAssignment+ if err := decodeStrict(payload, &assignment); err != nil || assignment.Upstream.Kind != "none" || assignment.Upstream.PeerID != nil || !validChildPeerIDs(assignment.ChildPeerIDs) {+ return participantRouteAssignment{}, errors.New("host route assignment is invalid")+ }+ if _, err := decodeNullableOpaqueID(assignment.SFUPublicationGeneration); err != nil {+ return participantRouteAssignment{}, errors.New("host route assignment is invalid")+ }+ return assignment, nil+}++func decodeNullableOpaqueID(payload []byte) (string, error) {+ if bytes.Equal(bytes.TrimSpace(payload), []byte("null")) {+ return "", nil+ }+ var value string+ if len(payload) == 0 || json.Unmarshal(payload, &value) != nil || !validOpaqueID(value) {+ return "", errors.New("nullable opaque ID is invalid")+ }+ return value, nil+}++func validChildPeerIDs(peerIDs []string) bool {+ if peerIDs == nil || len(peerIDs) > maxHostEdges {+ return false+ }+ seen := make(map[string]struct{}, len(peerIDs))+ for _, peerID := range peerIDs {+ if !validOpaqueID(peerID) {+ return false+ }+ if _, duplicate := seen[peerID]; duplicate {+ return false+ }+ seen[peerID] = struct{}{}+ }+ return true+}+func decodeInboundSignalPayload(payload []byte) (inboundSignalPayload, error) {var discriminator struct {Kind string `json:"kind"`diff --git a/native/sender/internal/remote/wire_test.go b/native/sender/internal/remote/wire_test.goindex 7da0589e..ff7f5700 100644--- a/native/sender/internal/remote/wire_test.go+++ b/native/sender/internal/remote/wire_test.go@@ -8,6 +8,8 @@ import (const validHostAuthenticated = `{"type":"authenticated","protocol":"screener-v2","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":[],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678"}`+const validPeerAssistedHostAuthenticated = `{"type":"authenticated","protocol":"screener-v2","role":"host","peerId":"host-peer","roomExpiresAt":null,"maxViewers":3,"hostOnline":true,"connectionId":null,"viewerPeerIds":["viewer-1","viewer-2"],"iceConfig":{"iceServers":[{"urls":["stun:example.test"]}]},"viewerPolicy":"private-link","viewerAuthorizationGeneration":"viewer_generation_12345678","mediaMode":"peer-assisted","mediaAssignment":{"parentPeerId":null,"childPeerIds":["viewer-1","viewer-2"]},"routeRevision":7,"routeAssignment":{"upstream":{"kind":"none"},"childPeerIds":["viewer-1","viewer-2"],"sfuPublicationGeneration":null},"qualitySettings":{"resolution":"1080p","maxFramerate":60,"maxBitrate":8000000,"degradationPreference":"maintain-resolution"}}`+func TestMarshalHostSignalShapes(t *testing.T) {mid := "0"line := uint16(0)@@ -62,6 +64,78 @@ func TestDecodeOrdinaryHostAuthentication(t *testing.T) {}}+func TestDecodePeerAssistedHostAuthentication(t *testing.T) {+ message, err := decodeServerMessage([]byte(validPeerAssistedHostAuthenticated))+ if err != nil {+ t.Fatal(err)+ }+ if !message.PeerAssisted || message.RouteRevision != 7 || len(message.MediaAssignment.ChildPeerIDs) != 2 {+ t.Fatalf("peer-assisted authentication = %+v", message)+ }+}++func TestDecodePeerAssistedHostAuthenticationRejectsInvalidAuthority(t *testing.T) {+ tests := map[string]func(map[string]any){+ "third-child": func(message map[string]any) {+ children := []any{"viewer-1", "viewer-2", "viewer-3"}+ message["mediaAssignment"].(map[string]any)["childPeerIds"] = children+ message["routeAssignment"].(map[string]any)["childPeerIds"] = children+ },+ "duplicate-child": func(message map[string]any) {+ children := []any{"viewer-1", "viewer-1"}+ message["mediaAssignment"].(map[string]any)["childPeerIds"] = children+ message["routeAssignment"].(map[string]any)["childPeerIds"] = children+ },+ "host-parent": func(message map[string]any) {+ message["mediaAssignment"].(map[string]any)["parentPeerId"] = "viewer-1"+ },+ "host-upstream": func(message map[string]any) {+ message["routeAssignment"].(map[string]any)["upstream"] = map[string]any{"kind": "peer", "peerId": "viewer-1"}+ },+ "extra-upstream-field": func(message map[string]any) {+ message["routeAssignment"].(map[string]any)["upstream"] = map[string]any{"kind": "none", "peerId": ""}+ },+ "mismatched-children": func(message map[string]any) {+ message["routeAssignment"].(map[string]any)["childPeerIds"] = []any{"viewer-2", "viewer-1"}+ },+ "missing-quality": func(message map[string]any) { delete(message, "qualitySettings") },+ }+ for name, mutate := range tests {+ t.Run(name, func(t *testing.T) {+ var candidate map[string]any+ if err := json.Unmarshal([]byte(validPeerAssistedHostAuthenticated), &candidate); err != nil {+ t.Fatal(err)+ }+ mutate(candidate)+ payload, err := json.Marshal(candidate)+ if err != nil {+ t.Fatal(err)+ }+ if _, err = decodeServerMessage(payload); err == nil {+ t.Fatal("invalid peer-assisted authority was accepted")+ }+ })+ }+}++func TestDecodePeerAssistedRouteMessages(t *testing.T) {+ tests := []struct {+ payload string+ typeName string+ }{+ {`{"type":"media-assignment","mediaAssignment":{"parentPeerId":null,"childPeerIds":["viewer-1"]}}`, "media-assignment"},+ {`{"type":"route-update","revision":8,"phase":"active","assignment":{"upstream":{"kind":"none"},"childPeerIds":["viewer-1"],"sfuPublicationGeneration":null}}`, "route-update"},+ {`{"type":"sfu-config","revision":8,"url":"wss://example.test","token":"opaque"}`, "sfu-config"},+ {`{"type":"selected-edge-turn","edgeKind":"host-sfu-ingress","revision":8,"hostPeerId":"host-peer","publicationGeneration":"publication-1","oldConnectionId":"connection-old","newConnectionId":"connection-new","expiresAt":"2030-01-01T00:00:00Z","iceServer":{"urls":["turn:example.test?transport=udp"],"username":"1:abcdefghijklmnop","credential":"opaque"}}`, "selected-edge-turn"},+ }+ for _, test := range tests {+ message, err := decodeServerMessage([]byte(test.payload))+ if err != nil || message.Type != test.typeName {+ t.Fatalf("decode %s = %+v, %v", test.typeName, message, err)+ }+ }+}+func TestDecodeOrdinaryHostAuthenticationRejectsInvalidVariants(t *testing.T) {tests := map[string]func(map[string]any){"missing-protocol": func(message map[string]any) { delete(message, "protocol") },