peerpigeon 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -1365
- package/cli.js +1382 -0
- package/dist/peerpigeon-browser.js +12290 -0
- package/dist/peerpigeon-browser.js.map +7 -0
- package/docs/API_DOCUMENTATION.md +1945 -0
- package/docs/BOOTSTRAP_HUBS.md +319 -0
- package/docs/CLI_README.md +371 -0
- package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
- package/docs/HUB_QUICK_REF.md +107 -0
- package/docs/HUB_SCRIPTS.md +331 -0
- package/docs/HUB_SYSTEM.md +552 -0
- package/docs/MIGRATION_COMPLETE.md +93 -0
- package/docs/NETWORK_NAMESPACES.md +212 -0
- package/docs/README.md +107 -0
- package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
- package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
- package/examples/bootstrap-hub-example.js +292 -0
- package/examples/browser/README.md +278 -0
- package/examples/browser/app.js +2426 -49
- package/examples/browser/index.html +482 -543
- package/examples/browser/minimal/README.md +55 -0
- package/examples/browser/minimal/index.html +75 -0
- package/examples/browser/minimal/minimal.js +234 -0
- package/examples/browser/styles.css +687 -1425
- package/examples/browser/test-bundle.html +35 -0
- package/examples/browser-2/index.html +30 -0
- package/examples/browser-2/package.json +21 -0
- package/examples/browser-2/src/App-simple.vue +21 -0
- package/examples/browser-2/src/App.vue +420 -0
- package/examples/browser-2/src/components/CryptoView.vue +1661 -0
- package/examples/browser-2/src/components/DHTView.vue +1281 -0
- package/examples/browser-2/src/components/DebugView.vue +1773 -0
- package/examples/browser-2/src/components/MediaView.vue +1048 -0
- package/examples/browser-2/src/components/MessagingView.vue +775 -0
- package/examples/browser-2/src/components/NetworkView.vue +930 -0
- package/examples/browser-2/src/components/StorageView.vue +1376 -0
- package/examples/browser-2/src/main.js +5 -0
- package/examples/browser-2/src/stores/peerpigeon.js +895 -0
- package/examples/browser-2/vite.config.js +6 -0
- package/examples/hub-example.js +186 -0
- package/examples/multi-hub-test.js +186 -0
- package/examples/node/README.md +2 -2
- package/examples/node/storage-test.js +141 -6
- package/examples/selective-streaming-demo.html +698 -0
- package/examples/standard-events-demo.js +126 -0
- package/package.json +33 -16
- package/server/index.js +1032 -98
- package/server/start.js +49 -0
- package/src/ConnectionManager.js +239 -225
- package/src/CryptoManager.js +147 -18
- package/src/DebugLogger.js +0 -7
- package/src/DistributedStorageManager.js +245 -205
- package/src/EnvironmentDetector.js +109 -2
- package/src/EventEmitter.js +79 -1
- package/src/EvictionManager.js +10 -9
- package/src/GossipManager.js +163 -11
- package/src/LexicalStorageInterface.js +332 -0
- package/src/PeerConnection.js +333 -310
- package/src/PeerPigeonMesh.js +577 -135
- package/src/SignalingClient.js +14 -243
- package/src/SignalingHandler.js +31 -10
- package/src/StorageManager.js +0 -39
- package/src/WebDHT-Simple.js +389 -0
- package/src/WebDHT.js +363 -1165
- package/src/browser-entry.js +40 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/crypto-test.html +0 -427
- package/examples/browser/ui-old.js +0 -1926
- package/examples/browser/ui.js +0 -3010
- package/websocket-server/README.md +0 -247
- package/websocket-server/server.js +0 -391
package/src/PeerConnection.js
CHANGED
|
@@ -14,10 +14,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
14
14
|
this.dataChannelReady = false;
|
|
15
15
|
this.connectionStartTime = Date.now();
|
|
16
16
|
this.pendingIceCandidates = [];
|
|
17
|
-
this.iceCheckingTimeout = null; // Timeout for ICE checking state
|
|
18
|
-
this.connectingTimeout = null; // Timeout for stuck connecting state
|
|
19
|
-
this.dataChannelHealthMonitor = null; // Health monitoring for data channel when signaling is unavailable
|
|
20
17
|
this.isClosing = false; // Flag to prevent disconnection events during intentional close
|
|
18
|
+
this.iceTimeoutId = null; // Timeout ID for ICE negotiation
|
|
21
19
|
this._forcedStatus = null; // Track forced status (e.g., failed)
|
|
22
20
|
|
|
23
21
|
// Media stream support
|
|
@@ -27,6 +25,10 @@ export class PeerConnection extends EventEmitter {
|
|
|
27
25
|
this.enableAudio = options.enableAudio || false;
|
|
28
26
|
this.audioTransceiver = null;
|
|
29
27
|
this.videoTransceiver = null;
|
|
28
|
+
|
|
29
|
+
// SECURITY: Never automatically invoke remote streams - only when user explicitly requests
|
|
30
|
+
this.allowRemoteStreams = options.allowRemoteStreams === true; // Default to false - streams must be explicitly invoked
|
|
31
|
+
this.pendingRemoteStreams = []; // Buffer remote streams until user invokes them
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
/**
|
|
@@ -50,40 +52,38 @@ export class PeerConnection extends EventEmitter {
|
|
|
50
52
|
this.connection = new RTCPeerConnection({
|
|
51
53
|
iceServers: [
|
|
52
54
|
{ urls: 'stun:stun.l.google.com:19302' },
|
|
53
|
-
{ urls: 'stun:stun1.l.google.com:19302' }
|
|
54
|
-
|
|
55
|
+
{ urls: 'stun:stun1.l.google.com:19302' },
|
|
56
|
+
{ urls: 'stun:stun2.l.google.com:19302' },
|
|
57
|
+
{ urls: 'stun:stun3.l.google.com:19302' },
|
|
58
|
+
{ urls: 'stun:stun4.l.google.com:19302' }
|
|
59
|
+
],
|
|
60
|
+
iceCandidatePoolSize: 10, // Pre-gather ICE candidates for faster connection
|
|
61
|
+
bundlePolicy: 'max-bundle', // Bundle all media on single transport for efficiency
|
|
62
|
+
rtcpMuxPolicy: 'require' // Multiplex RTP and RTCP for faster setup
|
|
55
63
|
});
|
|
56
64
|
|
|
57
65
|
this.setupConnectionHandlers();
|
|
58
66
|
|
|
59
|
-
//
|
|
60
|
-
// This ensures
|
|
61
|
-
this.debug.log('🔄
|
|
67
|
+
// CRITICAL FIX: Use addTrack() instead of pre-allocated transceivers to trigger ontrack events
|
|
68
|
+
// This ensures that ontrack events are properly fired on the receiving side
|
|
69
|
+
this.debug.log('🔄 Using addTrack() approach for proper ontrack event firing');
|
|
62
70
|
|
|
63
|
-
//
|
|
64
|
-
this.audioTransceiver = this.connection.addTransceiver('audio', {
|
|
65
|
-
direction: 'sendrecv'
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
// Always add video transceiver
|
|
69
|
-
this.videoTransceiver = this.connection.addTransceiver('video', {
|
|
70
|
-
direction: 'sendrecv'
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
// Add local media stream if provided
|
|
71
|
+
// Add local media stream if provided using addTrack()
|
|
74
72
|
if (this.localStream) {
|
|
75
|
-
this.debug.log('Adding local stream tracks
|
|
76
|
-
await this.
|
|
73
|
+
this.debug.log('Adding local stream tracks using addTrack() method');
|
|
74
|
+
await this.addLocalStreamWithAddTrack(this.localStream);
|
|
77
75
|
}
|
|
78
76
|
|
|
79
77
|
if (this.isInitiator) {
|
|
78
|
+
this.debug.log(`🚀 INITIATOR: Creating data channel for ${this.peerId.substring(0, 8)}... (WE are initiator)`);
|
|
80
79
|
this.dataChannel = this.connection.createDataChannel('messages', {
|
|
81
80
|
ordered: true
|
|
82
81
|
});
|
|
83
82
|
this.setupDataChannel();
|
|
84
83
|
} else {
|
|
84
|
+
this.debug.log(`👥 RECEIVER: Waiting for data channel from ${this.peerId.substring(0, 8)}... (THEY are initiator)`);
|
|
85
85
|
this.connection.ondatachannel = (event) => {
|
|
86
|
-
this.debug.log(
|
|
86
|
+
this.debug.log(`📨 RECEIVED: Data channel received from ${this.peerId.substring(0, 8)}...`);
|
|
87
87
|
this.dataChannel = event.channel;
|
|
88
88
|
this.setupDataChannel();
|
|
89
89
|
};
|
|
@@ -139,8 +139,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
139
139
|
});
|
|
140
140
|
|
|
141
141
|
this.debug.log('🚨 ONTRACK DEBUG: About to emit remoteStream event');
|
|
142
|
-
|
|
143
|
-
|
|
142
|
+
|
|
143
|
+
// Check if remote streams are allowed (crypto gating)
|
|
144
|
+
if (this.allowRemoteStreams) {
|
|
145
|
+
this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
|
|
146
|
+
this.debug.log('✅ ONTRACK DEBUG: remoteStream event emitted successfully');
|
|
147
|
+
} else {
|
|
148
|
+
// Buffer the stream until crypto allows it
|
|
149
|
+
this.debug.log('🔒 ONTRACK DEBUG: Buffering remote stream until crypto verification');
|
|
150
|
+
this.pendingRemoteStreams.push({ peerId: this.peerId, stream: this.remoteStream });
|
|
151
|
+
}
|
|
144
152
|
} else {
|
|
145
153
|
this.debug.error('❌ ONTRACK DEBUG: No stream in ontrack event - this should not happen');
|
|
146
154
|
}
|
|
@@ -161,36 +169,26 @@ export class PeerConnection extends EventEmitter {
|
|
|
161
169
|
}
|
|
162
170
|
|
|
163
171
|
if (this.connection.connectionState === 'connected') {
|
|
164
|
-
// Clear any pending timeouts
|
|
165
|
-
if (this.connectingTimeout) {
|
|
166
|
-
clearTimeout(this.connectingTimeout);
|
|
167
|
-
this.connectingTimeout = null;
|
|
168
|
-
}
|
|
169
172
|
this.debug.log(`✅ Connection established with ${this.peerId}`);
|
|
170
173
|
this.emit('connected', { peerId: this.peerId });
|
|
171
174
|
} else if (this.connection.connectionState === 'connecting') {
|
|
172
175
|
this.debug.log(`🔄 Connection to ${this.peerId} is connecting...`);
|
|
173
|
-
// Add timeout for stuck connecting state
|
|
174
|
-
if (this.connectingTimeout) {
|
|
175
|
-
clearTimeout(this.connectingTimeout);
|
|
176
|
-
}
|
|
177
|
-
this.connectingTimeout = setTimeout(() => {
|
|
178
|
-
if (this.connection && this.connection.connectionState === 'connecting' && !this.isClosing) {
|
|
179
|
-
this.debug.log(`⏰ Connection stuck in connecting state for ${this.peerId}, treating as failed`);
|
|
180
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'connection timeout' });
|
|
181
|
-
}
|
|
182
|
-
}, 20000); // Increased timeout to 20 seconds for better stability
|
|
183
176
|
} else if (this.connection.connectionState === 'disconnected') {
|
|
184
177
|
// Give WebRTC more time to recover - it's common for connections to briefly disconnect during renegotiation
|
|
185
178
|
this.debug.log(`⚠️ WebRTC connection disconnected for ${this.peerId}, waiting for potential recovery...`);
|
|
179
|
+
|
|
180
|
+
// Longer recovery time for disconnected state when there are multiple peers (3+)
|
|
181
|
+
// This helps prevent cascade failures when multiple renegotiations happen
|
|
182
|
+
const recoveryTime = 12000; // 12 seconds for disconnected state recovery
|
|
183
|
+
|
|
186
184
|
setTimeout(() => {
|
|
187
185
|
if (this.connection &&
|
|
188
186
|
this.connection.connectionState === 'disconnected' &&
|
|
189
187
|
!this.isClosing) {
|
|
190
|
-
this.debug.log(`❌ WebRTC connection remained disconnected for ${this.peerId}, treating as failed`);
|
|
188
|
+
this.debug.log(`❌ WebRTC connection remained disconnected for ${this.peerId} after ${recoveryTime}ms, treating as failed`);
|
|
191
189
|
this.emit('disconnected', { peerId: this.peerId, reason: 'connection disconnected' });
|
|
192
190
|
}
|
|
193
|
-
},
|
|
191
|
+
}, recoveryTime);
|
|
194
192
|
} else if (this.connection.connectionState === 'failed') {
|
|
195
193
|
if (!this.isClosing) {
|
|
196
194
|
this.debug.log(`❌ Connection failed for ${this.peerId}`);
|
|
@@ -208,41 +206,25 @@ export class PeerConnection extends EventEmitter {
|
|
|
208
206
|
this.debug.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
|
|
209
207
|
|
|
210
208
|
if (this.connection.iceConnectionState === 'connected') {
|
|
211
|
-
// Clear any pending timeout
|
|
212
|
-
if (this.iceCheckingTimeout) {
|
|
213
|
-
clearTimeout(this.iceCheckingTimeout);
|
|
214
|
-
this.iceCheckingTimeout = null;
|
|
215
|
-
}
|
|
216
209
|
this.debug.log(`✅ ICE connection established with ${this.peerId}`);
|
|
210
|
+
// Clear any existing ICE timeout
|
|
211
|
+
if (this.iceTimeoutId) {
|
|
212
|
+
clearTimeout(this.iceTimeoutId);
|
|
213
|
+
this.iceTimeoutId = null;
|
|
214
|
+
}
|
|
217
215
|
} else if (this.connection.iceConnectionState === 'checking') {
|
|
218
216
|
this.debug.log(`🔄 ICE checking for ${this.peerId}...`);
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
217
|
+
|
|
218
|
+
// Set a timeout for ICE negotiation to prevent hanging
|
|
219
|
+
if (this.iceTimeoutId) {
|
|
220
|
+
clearTimeout(this.iceTimeoutId);
|
|
222
221
|
}
|
|
223
|
-
this.
|
|
224
|
-
if (this.connection && this.connection.iceConnectionState === 'checking') {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
228
|
-
|
|
229
|
-
if (hasSignaling || hasMeshConnectivity) {
|
|
230
|
-
this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
231
|
-
try {
|
|
232
|
-
this.restartIceViaSignaling().catch(error => {
|
|
233
|
-
this.debug.error('Failed to restart ICE:', error);
|
|
234
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
|
|
235
|
-
});
|
|
236
|
-
} catch (error) {
|
|
237
|
-
this.debug.error('Failed to restart ICE:', error);
|
|
238
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
|
|
239
|
-
}
|
|
240
|
-
} else {
|
|
241
|
-
this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, but no signaling available - keeping connection alive`);
|
|
242
|
-
// Don't disconnect - peer connection may still work without signaling server
|
|
243
|
-
}
|
|
222
|
+
this.iceTimeoutId = setTimeout(() => {
|
|
223
|
+
if (this.connection && this.connection.iceConnectionState === 'checking' && !this.isClosing) {
|
|
224
|
+
this.debug.error(`❌ ICE negotiation timeout for ${this.peerId} - connection stuck in checking state`);
|
|
225
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE negotiation timeout' });
|
|
244
226
|
}
|
|
245
|
-
}, 30000); //
|
|
227
|
+
}, 30000); // 30 second timeout for ICE negotiation
|
|
246
228
|
} else if (this.connection.iceConnectionState === 'failed') {
|
|
247
229
|
// Check if signaling is available before attempting ICE restart
|
|
248
230
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
@@ -261,9 +243,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
261
243
|
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
|
|
262
244
|
}
|
|
263
245
|
} else {
|
|
264
|
-
this.debug.log(`❌ ICE connection failed for ${this.peerId},
|
|
265
|
-
|
|
266
|
-
this.monitorDataChannelHealth();
|
|
246
|
+
this.debug.log(`❌ ICE connection failed for ${this.peerId}, disconnecting`);
|
|
247
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
|
|
267
248
|
}
|
|
268
249
|
} else if (this.connection.iceConnectionState === 'disconnected') {
|
|
269
250
|
// Give more time for ICE reconnection - this is common during renegotiation
|
|
@@ -288,12 +269,11 @@ export class PeerConnection extends EventEmitter {
|
|
|
288
269
|
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
289
270
|
}
|
|
290
271
|
} else {
|
|
291
|
-
this.debug.log(`❌ ICE remained disconnected for ${this.peerId},
|
|
292
|
-
|
|
293
|
-
this.monitorDataChannelHealth();
|
|
272
|
+
this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
|
|
273
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
294
274
|
}
|
|
295
275
|
}
|
|
296
|
-
},
|
|
276
|
+
}, 5000); // Faster ICE reconnection - 5 seconds
|
|
297
277
|
}
|
|
298
278
|
};
|
|
299
279
|
|
|
@@ -355,30 +335,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
355
335
|
this.dataChannel.onmessage = (event) => {
|
|
356
336
|
try {
|
|
357
337
|
const message = JSON.parse(event.data);
|
|
358
|
-
|
|
359
|
-
// Handle internal ping messages for health monitoring
|
|
360
|
-
if (message.type === 'ping') {
|
|
361
|
-
this.debug.log(`📡 Received health ping from ${this.peerId}, responding with pong`);
|
|
362
|
-
try {
|
|
363
|
-
const pongMessage = {
|
|
364
|
-
type: 'pong',
|
|
365
|
-
timestamp: Date.now(),
|
|
366
|
-
originalTimestamp: message.timestamp,
|
|
367
|
-
from: this.mesh?.peerId || 'unknown'
|
|
368
|
-
};
|
|
369
|
-
this.dataChannel.send(JSON.stringify(pongMessage));
|
|
370
|
-
} catch (error) {
|
|
371
|
-
this.debug.error('Failed to send pong response:', error);
|
|
372
|
-
}
|
|
373
|
-
return; // Don't emit this as a regular message
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// Handle pong responses (optional logging)
|
|
377
|
-
if (message.type === 'pong') {
|
|
378
|
-
this.debug.log(`📡 Received health pong from ${this.peerId}`);
|
|
379
|
-
return; // Don't emit this as a regular message
|
|
380
|
-
}
|
|
381
|
-
|
|
382
338
|
this.emit('message', { peerId: this.peerId, message });
|
|
383
339
|
} catch (error) {
|
|
384
340
|
this.debug.error('Failed to parse message:', error);
|
|
@@ -397,10 +353,59 @@ export class PeerConnection extends EventEmitter {
|
|
|
397
353
|
};
|
|
398
354
|
}
|
|
399
355
|
|
|
356
|
+
// CRITICAL: Check and force data channel state after answer processing
|
|
357
|
+
checkDataChannelState() {
|
|
358
|
+
if (this.dataChannel) {
|
|
359
|
+
this.debug.log(`🔍 DATA CHANNEL CHECK: State for ${this.peerId.substring(0, 8)}... is ${this.dataChannel.readyState}`);
|
|
360
|
+
|
|
361
|
+
// If data channel is open but we haven't triggered the open event yet
|
|
362
|
+
if (this.dataChannel.readyState === 'open' && !this.dataChannelReady) {
|
|
363
|
+
this.debug.log(`🚀 FORCE OPEN: Triggering data channel open for ${this.peerId.substring(0, 8)}...`);
|
|
364
|
+
this.dataChannelReady = true;
|
|
365
|
+
this.emit('dataChannelOpen', { peerId: this.peerId });
|
|
366
|
+
}
|
|
367
|
+
// If data channel is connecting, set up a check in case the event doesn't fire
|
|
368
|
+
else if (this.dataChannel.readyState === 'connecting') {
|
|
369
|
+
this.debug.log(`⏳ CONNECTING: Data channel connecting for ${this.peerId.substring(0, 8)}..., setting up backup check`);
|
|
370
|
+
setTimeout(() => {
|
|
371
|
+
if (this.dataChannel && this.dataChannel.readyState === 'open' && !this.dataChannelReady) {
|
|
372
|
+
this.debug.log(`🚀 BACKUP OPEN: Backup trigger for data channel open for ${this.peerId.substring(0, 8)}...`);
|
|
373
|
+
this.dataChannelReady = true;
|
|
374
|
+
this.emit('dataChannelOpen', { peerId: this.peerId });
|
|
375
|
+
}
|
|
376
|
+
}, 100); // Short delay to allow normal event to fire first
|
|
377
|
+
} else {
|
|
378
|
+
this.debug.log(`❌ DATA CHANNEL CHECK: No data channel found for ${this.peerId.substring(0, 8)}...`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
400
383
|
async createOffer() {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
384
|
+
// Create offer with optimized settings for faster connection and timeout protection
|
|
385
|
+
try {
|
|
386
|
+
const offer = await Promise.race([
|
|
387
|
+
this.connection.createOffer({
|
|
388
|
+
offerToReceiveAudio: true,
|
|
389
|
+
offerToReceiveVideo: true,
|
|
390
|
+
iceRestart: false // Don't restart ICE unless necessary
|
|
391
|
+
}),
|
|
392
|
+
new Promise((resolve, reject) =>
|
|
393
|
+
setTimeout(() => reject(new Error('createOffer timeout')), 10000)
|
|
394
|
+
)
|
|
395
|
+
]);
|
|
396
|
+
|
|
397
|
+
await Promise.race([
|
|
398
|
+
this.connection.setLocalDescription(offer),
|
|
399
|
+
new Promise((resolve, reject) =>
|
|
400
|
+
setTimeout(() => reject(new Error('setLocalDescription timeout')), 10000)
|
|
401
|
+
)
|
|
402
|
+
]);
|
|
403
|
+
|
|
404
|
+
return offer;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
this.debug.error(`❌ Failed to create offer for ${this.peerId}:`, error);
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
404
409
|
}
|
|
405
410
|
|
|
406
411
|
async handleOffer(offer) {
|
|
@@ -442,16 +447,38 @@ export class PeerConnection extends EventEmitter {
|
|
|
442
447
|
this.debug.log(`🔄 OFFER DEBUG: State validation passed, processing offer from ${this.peerId.substring(0, 8)}... SDP length: ${offer.sdp.length}`);
|
|
443
448
|
|
|
444
449
|
try {
|
|
445
|
-
await
|
|
450
|
+
await Promise.race([
|
|
451
|
+
this.connection.setRemoteDescription(offer),
|
|
452
|
+
new Promise((resolve, reject) =>
|
|
453
|
+
setTimeout(() => reject(new Error('setRemoteDescription timeout')), 10000)
|
|
454
|
+
)
|
|
455
|
+
]);
|
|
456
|
+
|
|
446
457
|
this.remoteDescriptionSet = true;
|
|
447
458
|
this.debug.log(`✅ OFFER DEBUG: Offer processed successfully from ${this.peerId.substring(0, 8)}...`);
|
|
448
459
|
this.debug.log(`✅ OFFER DEBUG: New signaling state after offer: ${this.connection.signalingState}`);
|
|
449
460
|
await this.processPendingIceCandidates();
|
|
450
461
|
|
|
451
|
-
const answer = await
|
|
452
|
-
|
|
462
|
+
const answer = await Promise.race([
|
|
463
|
+
this.connection.createAnswer(),
|
|
464
|
+
new Promise((resolve, reject) =>
|
|
465
|
+
setTimeout(() => reject(new Error('createAnswer timeout')), 10000)
|
|
466
|
+
)
|
|
467
|
+
]);
|
|
468
|
+
|
|
469
|
+
await Promise.race([
|
|
470
|
+
this.connection.setLocalDescription(answer),
|
|
471
|
+
new Promise((resolve, reject) =>
|
|
472
|
+
setTimeout(() => reject(new Error('setLocalDescription timeout')), 10000)
|
|
473
|
+
)
|
|
474
|
+
]);
|
|
475
|
+
|
|
453
476
|
this.debug.log(`✅ OFFER DEBUG: Answer created for offer from ${this.peerId.substring(0, 8)}...`);
|
|
454
477
|
this.debug.log(`✅ OFFER DEBUG: Final signaling state after answer: ${this.connection.signalingState}`);
|
|
478
|
+
|
|
479
|
+
// CRITICAL: Force check data channel state after offer/answer processing
|
|
480
|
+
this.checkDataChannelState();
|
|
481
|
+
|
|
455
482
|
return answer;
|
|
456
483
|
} catch (error) {
|
|
457
484
|
this.debug.error(`❌ OFFER DEBUG: Failed to process offer from ${this.peerId}:`, error);
|
|
@@ -508,12 +535,21 @@ export class PeerConnection extends EventEmitter {
|
|
|
508
535
|
this.debug.log(`🔄 ANSWER DEBUG: State validation passed, processing answer from ${this.peerId.substring(0, 8)}... SDP length: ${answer.sdp.length}`);
|
|
509
536
|
|
|
510
537
|
try {
|
|
511
|
-
await
|
|
538
|
+
await Promise.race([
|
|
539
|
+
this.connection.setRemoteDescription(answer),
|
|
540
|
+
new Promise((resolve, reject) =>
|
|
541
|
+
setTimeout(() => reject(new Error('setRemoteDescription timeout')), 10000)
|
|
542
|
+
)
|
|
543
|
+
]);
|
|
544
|
+
|
|
512
545
|
this.remoteDescriptionSet = true;
|
|
513
546
|
this.debug.log(`✅ ANSWER DEBUG: Answer processed successfully from ${this.peerId.substring(0, 8)}...`);
|
|
514
547
|
this.debug.log(`✅ ANSWER DEBUG: New signaling state: ${this.connection.signalingState}`);
|
|
515
548
|
this.debug.log(`✅ ANSWER DEBUG: New connection state: ${this.connection.connectionState}`);
|
|
516
549
|
await this.processPendingIceCandidates();
|
|
550
|
+
|
|
551
|
+
// CRITICAL: Force check data channel state after answer processing
|
|
552
|
+
this.checkDataChannelState();
|
|
517
553
|
} catch (error) {
|
|
518
554
|
this.debug.error(`❌ ANSWER DEBUG: Failed to set remote description for answer from ${this.peerId}:`, error);
|
|
519
555
|
this.debug.error('ANSWER DEBUG: Answer SDP that failed:', answer.sdp);
|
|
@@ -549,7 +585,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
549
585
|
}
|
|
550
586
|
|
|
551
587
|
try {
|
|
552
|
-
await
|
|
588
|
+
await Promise.race([
|
|
589
|
+
this.connection.addIceCandidate(candidate),
|
|
590
|
+
new Promise((resolve, reject) =>
|
|
591
|
+
setTimeout(() => reject(new Error('addIceCandidate timeout')), 5000)
|
|
592
|
+
)
|
|
593
|
+
]);
|
|
553
594
|
this.debug.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
|
|
554
595
|
} catch (error) {
|
|
555
596
|
this.debug.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
@@ -566,7 +607,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
566
607
|
|
|
567
608
|
for (const candidate of this.pendingIceCandidates) {
|
|
568
609
|
try {
|
|
569
|
-
await
|
|
610
|
+
await Promise.race([
|
|
611
|
+
this.connection.addIceCandidate(candidate),
|
|
612
|
+
new Promise((resolve, reject) =>
|
|
613
|
+
setTimeout(() => reject(new Error('addIceCandidate timeout')), 5000)
|
|
614
|
+
)
|
|
615
|
+
]);
|
|
570
616
|
this.debug.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
|
|
571
617
|
} catch (error) {
|
|
572
618
|
this.debug.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
@@ -626,7 +672,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
626
672
|
this.processedTrackIds.add(track.id);
|
|
627
673
|
|
|
628
674
|
this.debug.log('🚨 TRACK CHECK: Emitting remoteStream event for new track');
|
|
629
|
-
|
|
675
|
+
|
|
676
|
+
// Check if remote streams are allowed (crypto gating)
|
|
677
|
+
if (this.allowRemoteStreams) {
|
|
678
|
+
this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
|
|
679
|
+
} else {
|
|
680
|
+
// Buffer the stream until crypto allows it
|
|
681
|
+
this.debug.log('🔒 TRACK CHECK: Buffering remote stream until crypto verification');
|
|
682
|
+
this.pendingRemoteStreams.push({ peerId: this.peerId, stream: this.remoteStream });
|
|
683
|
+
}
|
|
684
|
+
|
|
630
685
|
foundNewTracks = true;
|
|
631
686
|
}
|
|
632
687
|
}
|
|
@@ -647,6 +702,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
647
702
|
validateRemoteStream(stream, track) {
|
|
648
703
|
this.debug.log('🔍 VALIDATION: Starting remote stream validation...');
|
|
649
704
|
|
|
705
|
+
// Check 0: Ensure stream and track are valid
|
|
706
|
+
if (!stream) {
|
|
707
|
+
this.debug.error('❌ VALIDATION: Stream is null or undefined');
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
if (!track) {
|
|
711
|
+
this.debug.error('❌ VALIDATION: Track is null or undefined');
|
|
712
|
+
return false;
|
|
713
|
+
}
|
|
714
|
+
|
|
650
715
|
// Check 1: Stream ID collision (basic loopback detection)
|
|
651
716
|
if (this.localStream && stream.id === this.localStream.id) {
|
|
652
717
|
this.debug.error('❌ LOOPBACK DETECTED: Received our own local stream as remote!');
|
|
@@ -694,8 +759,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
694
759
|
}
|
|
695
760
|
}
|
|
696
761
|
|
|
697
|
-
// Check 4: Verify stream hasn't been marked as local origin
|
|
698
|
-
if (stream._peerPigeonOrigin === 'local') {
|
|
762
|
+
// Check 4: Verify stream hasn't been marked as local origin (with safe property access)
|
|
763
|
+
if (stream && stream._peerPigeonOrigin === 'local') {
|
|
699
764
|
this.debug.error('❌ Stream marked as local origin - preventing synchronization loop');
|
|
700
765
|
return false;
|
|
701
766
|
}
|
|
@@ -744,129 +809,103 @@ export class PeerConnection extends EventEmitter {
|
|
|
744
809
|
}
|
|
745
810
|
|
|
746
811
|
/**
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
async
|
|
750
|
-
if (!this.connection)
|
|
751
|
-
throw new Error('Connection not initialized');
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
this.debug.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
|
|
812
|
+
* Add local stream using addTrack() method to trigger ontrack events
|
|
813
|
+
*/
|
|
814
|
+
async addLocalStreamWithAddTrack(stream) {
|
|
815
|
+
if (!stream || !this.connection) return;
|
|
755
816
|
|
|
756
|
-
|
|
757
|
-
const transceivers = this.connection.getTransceivers();
|
|
758
|
-
this.debug.log('🔍 Current transceivers before stream change:', transceivers.map(t => ({
|
|
759
|
-
kind: t.receiver.track?.kind || 'unknown',
|
|
760
|
-
direction: t.direction,
|
|
761
|
-
hasTrack: !!t.sender.track,
|
|
762
|
-
mid: t.mid
|
|
763
|
-
})));
|
|
817
|
+
this.debug.log('🎥 Adding local stream using addTrack() for proper ontrack events');
|
|
764
818
|
|
|
765
|
-
|
|
766
|
-
|
|
819
|
+
const audioTracks = stream.getAudioTracks();
|
|
820
|
+
const videoTracks = stream.getVideoTracks();
|
|
767
821
|
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
const videoTracks = stream.getVideoTracks();
|
|
771
|
-
|
|
772
|
-
// Mark stream as local origin to prevent loopback
|
|
773
|
-
this.markStreamAsLocal(stream);
|
|
774
|
-
|
|
775
|
-
// Handle audio track using stored reference
|
|
776
|
-
if (this.audioTransceiver) {
|
|
777
|
-
if (audioTracks.length > 0) {
|
|
778
|
-
this.debug.log('🔄 Replacing audio track in stored transceiver');
|
|
779
|
-
await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
|
|
780
|
-
this.audioTransceiver.direction = 'sendrecv';
|
|
781
|
-
|
|
782
|
-
// Setup audio sending monitoring
|
|
783
|
-
this.setupAudioSendingMonitoring(audioTracks[0]);
|
|
784
|
-
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
|
|
785
|
-
} else {
|
|
786
|
-
this.debug.log('🔄 Removing audio track from stored transceiver');
|
|
787
|
-
await this.audioTransceiver.sender.replaceTrack(null);
|
|
788
|
-
this.audioTransceiver.direction = 'recvonly';
|
|
789
|
-
this.debug.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
|
|
790
|
-
}
|
|
791
|
-
}
|
|
822
|
+
// Mark stream as local origin to prevent loopback
|
|
823
|
+
this.markStreamAsLocal(stream);
|
|
792
824
|
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
this.localStream = stream;
|
|
807
|
-
this.debug.log('✅ Stream set successfully using stored transceivers');
|
|
808
|
-
} else {
|
|
809
|
-
// Remove all tracks using stored references
|
|
810
|
-
if (this.audioTransceiver) {
|
|
811
|
-
this.debug.log('🔄 Removing audio track from stored transceiver');
|
|
812
|
-
await this.audioTransceiver.sender.replaceTrack(null);
|
|
813
|
-
this.audioTransceiver.direction = 'recvonly';
|
|
825
|
+
// Add audio tracks using addTrack()
|
|
826
|
+
audioTracks.forEach((audioTrack, index) => {
|
|
827
|
+
this.debug.log(`🎤 Adding audio track ${index} using addTrack()`);
|
|
828
|
+
try {
|
|
829
|
+
const audioSender = this.connection.addTrack(audioTrack, stream);
|
|
830
|
+
this.audioTransceiver = this.connection.getTransceivers().find(t => t.sender === audioSender);
|
|
831
|
+
|
|
832
|
+
// Setup audio sending monitoring
|
|
833
|
+
this.setupAudioSendingMonitoring(audioTrack);
|
|
834
|
+
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTrack.enabled}`);
|
|
835
|
+
} catch (error) {
|
|
836
|
+
this.debug.error(`❌ Failed to add audio track ${index}:`, error);
|
|
814
837
|
}
|
|
838
|
+
});
|
|
815
839
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
840
|
+
// Add video tracks using addTrack()
|
|
841
|
+
videoTracks.forEach((videoTrack, index) => {
|
|
842
|
+
this.debug.log(`🎥 Adding video track ${index} using addTrack()`);
|
|
843
|
+
try {
|
|
844
|
+
const videoSender = this.connection.addTrack(videoTrack, stream);
|
|
845
|
+
this.videoTransceiver = this.connection.getTransceivers().find(t => t.sender === videoSender);
|
|
846
|
+
this.debug.log(`🎥 SENDING VIDEO to peer ${this.peerId.substring(0, 8)} - track enabled: ${videoTrack.enabled}`);
|
|
847
|
+
} catch (error) {
|
|
848
|
+
this.debug.error(`❌ Failed to add video track ${index}:`, error);
|
|
820
849
|
}
|
|
850
|
+
});
|
|
821
851
|
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
// DEBUG: Log final transceivers after changes
|
|
829
|
-
const finalTransceivers = this.connection.getTransceivers();
|
|
830
|
-
this.debug.log('🔍 Final transceivers after stream change:', finalTransceivers.map(t => ({
|
|
852
|
+
this.localStream = stream;
|
|
853
|
+
this.debug.log('✅ Local stream added using addTrack() method');
|
|
854
|
+
|
|
855
|
+
// DEBUG: Log transceivers after adding tracks
|
|
856
|
+
const transceivers = this.connection.getTransceivers();
|
|
857
|
+
this.debug.log('🔍 Transceivers after addTrack():', transceivers.map(t => ({
|
|
831
858
|
kind: t.receiver?.track?.kind || 'unknown',
|
|
832
859
|
direction: t.direction,
|
|
833
860
|
hasTrack: !!t.sender?.track,
|
|
834
861
|
trackId: t.sender?.track?.id?.substring(0, 8) || 'none',
|
|
835
862
|
mid: t.mid
|
|
836
863
|
})));
|
|
864
|
+
}
|
|
837
865
|
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
866
|
+
/**
|
|
867
|
+
* Add or replace local media stream
|
|
868
|
+
*/
|
|
869
|
+
async setLocalStream(stream) {
|
|
870
|
+
if (!this.connection) {
|
|
871
|
+
throw new Error('Connection not initialized');
|
|
872
|
+
}
|
|
841
873
|
|
|
842
|
-
|
|
843
|
-
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
874
|
+
this.debug.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
|
|
844
875
|
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
876
|
+
// First, remove any existing local tracks
|
|
877
|
+
const senders = this.connection.getSenders();
|
|
878
|
+
for (const sender of senders) {
|
|
879
|
+
if (sender.track) {
|
|
880
|
+
this.debug.log('�️ Removing existing track:', sender.track.kind);
|
|
881
|
+
this.connection.removeTrack(sender);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// Clear transceiver references
|
|
886
|
+
this.audioTransceiver = null;
|
|
887
|
+
this.videoTransceiver = null;
|
|
888
|
+
|
|
889
|
+
if (stream) {
|
|
890
|
+
this.debug.log('🎥 Adding new stream using addTrack() method');
|
|
891
|
+
await this.addLocalStreamWithAddTrack(stream);
|
|
854
892
|
} else {
|
|
855
|
-
|
|
856
|
-
this.debug.log('✅
|
|
857
|
-
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
893
|
+
this.localStream = null;
|
|
894
|
+
this.debug.log('✅ All tracks removed');
|
|
858
895
|
}
|
|
859
896
|
|
|
897
|
+
this.debug.log('Updated local media stream for', this.peerId);
|
|
898
|
+
|
|
860
899
|
// CRITICAL: Force renegotiation when media changes
|
|
861
900
|
this.debug.log('✅ Stream updated - forcing renegotiation for media changes');
|
|
862
901
|
this.debug.log(` Current state: connectionState=${this.connection.connectionState}, signalingState=${this.connection.signalingState}`);
|
|
863
902
|
|
|
864
|
-
// Always trigger renegotiation when stream changes
|
|
903
|
+
// Always trigger renegotiation when stream changes
|
|
865
904
|
if (stream) {
|
|
866
905
|
setTimeout(() => {
|
|
867
906
|
this.debug.log('🔄 Forcing renegotiation for media stream changes');
|
|
868
907
|
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
869
|
-
}, 200);
|
|
908
|
+
}, 200);
|
|
870
909
|
}
|
|
871
910
|
}
|
|
872
911
|
|
|
@@ -878,8 +917,19 @@ export class PeerConnection extends EventEmitter {
|
|
|
878
917
|
|
|
879
918
|
try {
|
|
880
919
|
// Create a new offer to break the stuck state
|
|
881
|
-
const offer = await
|
|
882
|
-
|
|
920
|
+
const offer = await Promise.race([
|
|
921
|
+
this.connection.createOffer({ iceRestart: true }),
|
|
922
|
+
new Promise((resolve, reject) =>
|
|
923
|
+
setTimeout(() => reject(new Error('forceConnectionRecovery createOffer timeout')), 10000)
|
|
924
|
+
)
|
|
925
|
+
]);
|
|
926
|
+
|
|
927
|
+
await Promise.race([
|
|
928
|
+
this.connection.setLocalDescription(offer),
|
|
929
|
+
new Promise((resolve, reject) =>
|
|
930
|
+
setTimeout(() => reject(new Error('forceConnectionRecovery setLocalDescription timeout')), 10000)
|
|
931
|
+
)
|
|
932
|
+
]);
|
|
883
933
|
|
|
884
934
|
// Emit recovery offer via mesh signaling
|
|
885
935
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -899,34 +949,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
899
949
|
}
|
|
900
950
|
}
|
|
901
951
|
|
|
902
|
-
/**
|
|
903
|
-
* Helper method to set local stream tracks to existing transceivers
|
|
904
|
-
*/
|
|
905
|
-
async setLocalStreamToTransceivers(stream) {
|
|
906
|
-
if (stream) {
|
|
907
|
-
const audioTracks = stream.getAudioTracks();
|
|
908
|
-
const videoTracks = stream.getVideoTracks();
|
|
909
|
-
|
|
910
|
-
// Set audio track to stored audio transceiver
|
|
911
|
-
if (this.audioTransceiver && audioTracks.length > 0) {
|
|
912
|
-
this.debug.log('🔄 Setting audio track to stored audio transceiver');
|
|
913
|
-
await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
|
|
914
|
-
this.audioTransceiver.direction = 'sendrecv';
|
|
915
|
-
|
|
916
|
-
// Setup audio sending monitoring
|
|
917
|
-
this.setupAudioSendingMonitoring(audioTracks[0]);
|
|
918
|
-
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
// Set video track to stored video transceiver
|
|
922
|
-
if (this.videoTransceiver && videoTracks.length > 0) {
|
|
923
|
-
this.debug.log('🔄 Setting video track to stored video transceiver');
|
|
924
|
-
await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
|
|
925
|
-
this.videoTransceiver.direction = 'sendrecv';
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
|
|
930
952
|
/**
|
|
931
953
|
* Setup audio data monitoring for received audio tracks
|
|
932
954
|
*/
|
|
@@ -1135,6 +1157,35 @@ export class PeerConnection extends EventEmitter {
|
|
|
1135
1157
|
return this.localStream;
|
|
1136
1158
|
}
|
|
1137
1159
|
|
|
1160
|
+
/**
|
|
1161
|
+
* Allow remote streams to be emitted (called after crypto verification)
|
|
1162
|
+
*/
|
|
1163
|
+
allowRemoteStreamEmission() {
|
|
1164
|
+
this.debug.log(`🔓 CRYPTO: Allowing remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1165
|
+
this.allowRemoteStreams = true;
|
|
1166
|
+
|
|
1167
|
+
// Emit any buffered remote streams
|
|
1168
|
+
while (this.pendingRemoteStreams.length > 0) {
|
|
1169
|
+
const streamEvent = this.pendingRemoteStreams.shift();
|
|
1170
|
+
this.debug.log(`🔓 CRYPTO: Emitting buffered remote stream from ${streamEvent.peerId.substring(0, 8)}...`);
|
|
1171
|
+
this.emit('remoteStream', streamEvent);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* Block remote streams (called when crypto is required but not verified)
|
|
1177
|
+
*/
|
|
1178
|
+
blockRemoteStreamEmission() {
|
|
1179
|
+
// Check if crypto blocking is globally disabled (for video tests)
|
|
1180
|
+
if (typeof window !== 'undefined' && window.DISABLE_CRYPTO_BLOCKING) {
|
|
1181
|
+
this.debug.log(`🔓 CRYPTO: Video test mode - NOT blocking remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1182
|
+
return; // Don't block streams in video test mode
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
this.debug.log(`🔒 CRYPTO: Blocking remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1186
|
+
this.allowRemoteStreams = false;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1138
1189
|
/**
|
|
1139
1190
|
* Check if connection has video/audio capabilities
|
|
1140
1191
|
*/
|
|
@@ -1236,48 +1287,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
1236
1287
|
return status;
|
|
1237
1288
|
}
|
|
1238
1289
|
|
|
1239
|
-
/**
|
|
1240
|
-
* Monitor data channel health when ICE connection is problematic but signaling is unavailable
|
|
1241
|
-
* This allows peer connections to survive signaling server outages
|
|
1242
|
-
*/
|
|
1243
|
-
monitorDataChannelHealth() {
|
|
1244
|
-
if (this.dataChannelHealthMonitor) {
|
|
1245
|
-
clearTimeout(this.dataChannelHealthMonitor);
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
this.debug.log(`📡 Monitoring data channel health for ${this.peerId} (signaling unavailable)`);
|
|
1249
|
-
|
|
1250
|
-
// Test data channel by sending a ping message
|
|
1251
|
-
const testDataChannel = () => {
|
|
1252
|
-
if (!this.dataChannel || this.dataChannel.readyState !== 'open' || this.isClosing) {
|
|
1253
|
-
this.debug.log(`❌ Data channel not available for ${this.peerId}, disconnecting`);
|
|
1254
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel unavailable' });
|
|
1255
|
-
return;
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
try {
|
|
1259
|
-
// Send a small ping message to test connectivity
|
|
1260
|
-
const pingMessage = {
|
|
1261
|
-
type: 'ping',
|
|
1262
|
-
timestamp: Date.now(),
|
|
1263
|
-
from: this.mesh?.peerId || 'unknown'
|
|
1264
|
-
};
|
|
1265
|
-
|
|
1266
|
-
this.dataChannel.send(JSON.stringify(pingMessage));
|
|
1267
|
-
this.debug.log(`✅ Data channel ping sent to ${this.peerId} - connection appears healthy`);
|
|
1268
|
-
|
|
1269
|
-
// Schedule next health check in 30 seconds
|
|
1270
|
-
this.dataChannelHealthMonitor = setTimeout(testDataChannel, 30000);
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
this.debug.error(`❌ Data channel ping failed for ${this.peerId}:`, error);
|
|
1273
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel ping failed' });
|
|
1274
|
-
}
|
|
1275
|
-
};
|
|
1276
|
-
|
|
1277
|
-
// Start monitoring after a short delay
|
|
1278
|
-
this.dataChannelHealthMonitor = setTimeout(testDataChannel, 5000);
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
1290
|
/**
|
|
1282
1291
|
* Restart ICE using signaling coordination (WebSocket or mesh)
|
|
1283
1292
|
* This allows ICE restart to work even when the signaling server is down
|
|
@@ -1295,8 +1304,19 @@ export class PeerConnection extends EventEmitter {
|
|
|
1295
1304
|
this.connection.restartIce();
|
|
1296
1305
|
|
|
1297
1306
|
// Create a new offer with the restarted ICE
|
|
1298
|
-
const offer = await
|
|
1299
|
-
|
|
1307
|
+
const offer = await Promise.race([
|
|
1308
|
+
this.connection.createOffer({ iceRestart: true }),
|
|
1309
|
+
new Promise((resolve, reject) =>
|
|
1310
|
+
setTimeout(() => reject(new Error('ICE restart createOffer timeout')), 10000)
|
|
1311
|
+
)
|
|
1312
|
+
]);
|
|
1313
|
+
|
|
1314
|
+
await Promise.race([
|
|
1315
|
+
this.connection.setLocalDescription(offer),
|
|
1316
|
+
new Promise((resolve, reject) =>
|
|
1317
|
+
setTimeout(() => reject(new Error('ICE restart setLocalDescription timeout')), 10000)
|
|
1318
|
+
)
|
|
1319
|
+
]);
|
|
1300
1320
|
|
|
1301
1321
|
// Send the new offer via our mesh signaling system
|
|
1302
1322
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -1327,9 +1347,26 @@ export class PeerConnection extends EventEmitter {
|
|
|
1327
1347
|
this.debug.log(`🔄 Handling ICE restart offer from ${this.peerId}`);
|
|
1328
1348
|
|
|
1329
1349
|
try {
|
|
1330
|
-
await
|
|
1331
|
-
|
|
1332
|
-
|
|
1350
|
+
await Promise.race([
|
|
1351
|
+
this.connection.setRemoteDescription(offer),
|
|
1352
|
+
new Promise((resolve, reject) =>
|
|
1353
|
+
setTimeout(() => reject(new Error('ICE restart setRemoteDescription timeout')), 10000)
|
|
1354
|
+
)
|
|
1355
|
+
]);
|
|
1356
|
+
|
|
1357
|
+
const answer = await Promise.race([
|
|
1358
|
+
this.connection.createAnswer(),
|
|
1359
|
+
new Promise((resolve, reject) =>
|
|
1360
|
+
setTimeout(() => reject(new Error('ICE restart createAnswer timeout')), 10000)
|
|
1361
|
+
)
|
|
1362
|
+
]);
|
|
1363
|
+
|
|
1364
|
+
await Promise.race([
|
|
1365
|
+
this.connection.setLocalDescription(answer),
|
|
1366
|
+
new Promise((resolve, reject) =>
|
|
1367
|
+
setTimeout(() => reject(new Error('ICE restart setLocalDescription timeout')), 10000)
|
|
1368
|
+
)
|
|
1369
|
+
]);
|
|
1333
1370
|
|
|
1334
1371
|
// Send the answer back
|
|
1335
1372
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -1358,7 +1395,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
1358
1395
|
this.debug.log(`🔄 Handling ICE restart answer from ${this.peerId}`);
|
|
1359
1396
|
|
|
1360
1397
|
try {
|
|
1361
|
-
await
|
|
1398
|
+
await Promise.race([
|
|
1399
|
+
this.connection.setRemoteDescription(answer),
|
|
1400
|
+
new Promise((resolve, reject) =>
|
|
1401
|
+
setTimeout(() => reject(new Error('ICE restart setRemoteDescription timeout')), 10000)
|
|
1402
|
+
)
|
|
1403
|
+
]);
|
|
1362
1404
|
this.debug.log(`✅ ICE restart completed for ${this.peerId}`);
|
|
1363
1405
|
} catch (error) {
|
|
1364
1406
|
this.debug.error(`Failed to handle ICE restart answer from ${this.peerId}:`, error);
|
|
@@ -1366,35 +1408,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
1366
1408
|
}
|
|
1367
1409
|
}
|
|
1368
1410
|
|
|
1369
|
-
/**
|
|
1370
|
-
* Stop data channel health monitoring
|
|
1371
|
-
*/
|
|
1372
|
-
stopDataChannelHealthMonitoring() {
|
|
1373
|
-
if (this.dataChannelHealthMonitor) {
|
|
1374
|
-
clearTimeout(this.dataChannelHealthMonitor);
|
|
1375
|
-
this.dataChannelHealthMonitor = null;
|
|
1376
|
-
this.debug.log(`📡 Stopped data channel health monitoring for ${this.peerId}`);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
1411
|
close() {
|
|
1381
1412
|
// Set flag to prevent disconnection events during intentional close
|
|
1382
1413
|
this.isClosing = true;
|
|
1383
1414
|
|
|
1384
|
-
// Clear any
|
|
1385
|
-
if (this.
|
|
1386
|
-
clearTimeout(this.
|
|
1387
|
-
this.
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
if (this.connectingTimeout) {
|
|
1391
|
-
clearTimeout(this.connectingTimeout);
|
|
1392
|
-
this.connectingTimeout = null;
|
|
1415
|
+
// Clear any existing ICE timeout
|
|
1416
|
+
if (this.iceTimeoutId) {
|
|
1417
|
+
clearTimeout(this.iceTimeoutId);
|
|
1418
|
+
this.iceTimeoutId = null;
|
|
1393
1419
|
}
|
|
1394
1420
|
|
|
1395
|
-
// Stop data channel health monitoring
|
|
1396
|
-
this.stopDataChannelHealthMonitoring();
|
|
1397
|
-
|
|
1398
1421
|
if (this.connection) {
|
|
1399
1422
|
this.connection.close();
|
|
1400
1423
|
}
|