peerjs icon indicating copy to clipboard operation
peerjs copied to clipboard

Incoming MediaConnection prematurely flushes queued messages on Offer, throwing TypeError on null peerConnection and dropping early ICE candidates

Open codeCraft-Ritik opened this issue 1 month ago • 0 comments

Please, check for existing issues to avoid duplicates.

  • [x] No similar issues found.

What happened?

When an incoming call offer arrives, Peer._handleMessage creates a MediaConnection:

case ServerMessageType.Offer: {
    ...
    if (payload.type === ConnectionType.Media) {
        const mediaConnection = new MediaConnection(peerId, this, { ... });
        connection = mediaConnection;
        this._addConnection(peerId, connection);
        this.emit("call", mediaConnection);
    }
    ...
    // Find messages.
    const messages = this._getMessages(connectionId);
    for (const message of messages) {
        connection.handleMessage(message);
    }
    break;
}

Notice what happens:

  1. new MediaConnection is instantiated. In MediaConnection, peerConnection is not created until the callee accepts the call via mediaConnection.answer(stream).
  2. Right after emitting "call", lines 428–431 call this._getMessages(connectionId).
  3. If any ICE candidates arrived before or concurrently with the offer, they were buffered in _lostMessages.
  4. _getMessages(connectionId) drains and deletes those candidates from _lostMessages.
  5. For each message, mediaConnection.handleMessage(message) is called, which calls this._negotiator.handleCandidate(ice).
  6. Inside Negotiator.handleCandidate (lib/negotiator.ts:332):
    await this.connection.peerConnection.addIceCandidate(ice);
    
  7. Since mediaConnection.peerConnection is undefined, it throws: TypeError: Cannot read properties of undefined (reading 'addIceCandidate') and emits a spurious WebRTC error.
  8. Later, when the callee answers the call via mediaConnection.answer(), this.provider._getMessages(this.connectionId) returns an empty array [] because peer.ts already deleted them. All early ICE candidates are lost, leading to failed or delayed media connection negotiation.

How can we reproduce the issue?

  1. Alice calls Bob:
    const call = alice.call("bob", aliceStream);
    
  2. PeerServer delivers Offer followed immediately by trickle Candidate messages.
  3. Bob registers a listener:
    bob.on("call", (mediaConnection) => {
        // Do not answer synchronously (e.g. awaiting user click or getUserMedia)
        setTimeout(() => {
            mediaConnection.answer(bobStream);
        }, 500);
    });
    
  4. Observe the console error triggered before answer() is called: TypeError: Cannot read properties of undefined (reading 'addIceCandidate')
  5. Observe that when mediaConnection.answer() executes, the initial ICE candidates from Alice are never added to Bob's RTCPeerConnection.

What do you expected to happen?

Peer._handleMessage should only flush messages if connection.peerConnection is already active (like for DataConnection). For MediaConnection, messages must remain in _lostMessages until mediaConnection.answer() is called (which already has dedicated code to drain them).

Environment setup

Alice:

  • OS: Ubuntu 22.04 / macOS Sonoma
  • Platform: Browser
  • Browser: Chrome 122.0.6167.160

Bob:

  • OS: Windows 11 / iOS 17
  • Platform: Browser
  • Browser: Chrome 122.0.6167.160 / Safari 17.3

PeerJS version: 1.5.5

Is this a regression?

Is this a regression?

No, present in 1.5.5 in lib/peer.ts and lib/mediaconnection.ts.

Anything else?

Inside lib/mediaconnection.ts:143-149, answer() already implements:

// Retrieve lost messages stored because PeerConnection not set up.
const messages = this.provider._getMessages(this.connectionId);
for (const message of messages) {
    this.handleMessage(message);
}

This confirms that message replay was specifically designed to occur inside answer(), but was accidentally preempted by peer.ts.

Proposed Fix:

--- a/lib/peer.ts
+++ b/lib/peer.ts
@@ -426,9 +426,11 @@ export class Peer extends EventEmitterWithError<PeerErrorType, PeerEvents> {
 				}

-				// Find messages.
-				const messages = this._getMessages(connectionId);
-				for (const message of messages) {
-					connection.handleMessage(message);
+				// Only replay queued messages if peerConnection is initialized (e.g. DataConnection)
+				// For MediaConnection, messages are replayed inside mediaConnection.answer()
+				if (connection.peerConnection) {
+					const messages = this._getMessages(connectionId);
+					for (const message of messages) {
+						connection.handleMessage(message);
+					}
 				}

 				break;

codeCraft-Ritik avatar Oct 08 '26 04:10 codeCraft-Ritik