peerpigeon 0.0.4 โ 0.0.5
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/examples/browser/app.js +1 -0
- package/examples/browser/ui-old.js +1930 -0
- package/package.json +1 -1
- package/src/ConnectionManager.js +5 -1
- package/src/MediaManager.js +23 -0
- package/src/PeerConnection.js +217 -31
- package/src/SignalingHandler.js +5 -1
- package/websocket-server/server.js +52 -11
package/package.json
CHANGED
package/src/ConnectionManager.js
CHANGED
|
@@ -116,7 +116,11 @@ export class ConnectionManager extends EventEmitter {
|
|
|
116
116
|
|
|
117
117
|
// Get current media stream if available
|
|
118
118
|
const localStream = this.mesh.mediaManager.localStream;
|
|
119
|
-
const options = {
|
|
119
|
+
const options = {
|
|
120
|
+
localStream,
|
|
121
|
+
enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
|
|
122
|
+
enableVideo: hasMedia && localStream.getVideoTracks().length > 0
|
|
123
|
+
};
|
|
120
124
|
|
|
121
125
|
const peerConnection = new PeerConnection(targetPeerId, true, options);
|
|
122
126
|
|
package/src/MediaManager.js
CHANGED
|
@@ -111,6 +111,9 @@ export class MediaManager extends EventEmitter {
|
|
|
111
111
|
this.isVideoEnabled = video;
|
|
112
112
|
this.isAudioEnabled = audio;
|
|
113
113
|
|
|
114
|
+
// Mark stream as local origin to prevent confusion with remote streams
|
|
115
|
+
this.markStreamAsLocal(this.localStream);
|
|
116
|
+
|
|
114
117
|
console.log('Local media stream started:', {
|
|
115
118
|
video: this.isVideoEnabled,
|
|
116
119
|
audio: this.isAudioEnabled,
|
|
@@ -236,4 +239,24 @@ export class MediaManager extends EventEmitter {
|
|
|
236
239
|
return {};
|
|
237
240
|
}
|
|
238
241
|
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Mark stream as local origin to prevent confusion with remote streams
|
|
245
|
+
*/
|
|
246
|
+
markStreamAsLocal(stream) {
|
|
247
|
+
if (!stream) return;
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
251
|
+
value: 'local',
|
|
252
|
+
writable: false,
|
|
253
|
+
enumerable: false,
|
|
254
|
+
configurable: false
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
console.log(`๐ Stream ${stream.id} marked as local origin in MediaManager`);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
console.warn('Could not mark stream as local origin:', error);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
239
262
|
}
|
package/src/PeerConnection.js
CHANGED
|
@@ -22,6 +22,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
22
22
|
this.remoteStream = null;
|
|
23
23
|
this.enableVideo = options.enableVideo || false;
|
|
24
24
|
this.enableAudio = options.enableAudio || false;
|
|
25
|
+
this.audioTransceiver = null;
|
|
26
|
+
this.videoTransceiver = null;
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
/**
|
|
@@ -51,24 +53,35 @@ export class PeerConnection extends EventEmitter {
|
|
|
51
53
|
|
|
52
54
|
this.setupConnectionHandlers();
|
|
53
55
|
|
|
54
|
-
//
|
|
55
|
-
// This
|
|
56
|
-
|
|
56
|
+
// Only pre-allocate transceivers if media is actually intended to be used
|
|
57
|
+
// This prevents unnecessary WebRTC negotiations for data-only connections
|
|
58
|
+
const hasLocalMedia = this.localStream && (this.localStream.getAudioTracks().length > 0 || this.localStream.getVideoTracks().length > 0);
|
|
59
|
+
const intendToUseMedia = this.enableVideo || this.enableAudio || hasLocalMedia;
|
|
57
60
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
61
|
+
if (intendToUseMedia) {
|
|
62
|
+
console.log('๐ Pre-allocating transceivers for stable media negotiation');
|
|
63
|
+
|
|
64
|
+
// Add audio transceiver only if audio is enabled or present
|
|
65
|
+
if (this.enableAudio || (this.localStream && this.localStream.getAudioTracks().length > 0)) {
|
|
66
|
+
this.audioTransceiver = this.connection.addTransceiver('audio', {
|
|
67
|
+
direction: 'recvonly'
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Add video transceiver only if video is enabled or present
|
|
72
|
+
if (this.enableVideo || (this.localStream && this.localStream.getVideoTracks().length > 0)) {
|
|
73
|
+
this.videoTransceiver = this.connection.addTransceiver('video', {
|
|
74
|
+
direction: 'recvonly'
|
|
75
|
+
});
|
|
76
|
+
}
|
|
67
77
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
// Add local media stream if provided
|
|
79
|
+
if (this.localStream) {
|
|
80
|
+
console.log('Adding local stream tracks to existing transceivers');
|
|
81
|
+
await this.setLocalStreamToTransceivers(this.localStream);
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
console.log('๐ก Creating data-only connection (no media transceivers)');
|
|
72
85
|
}
|
|
73
86
|
|
|
74
87
|
if (this.isInitiator) {
|
|
@@ -107,12 +120,9 @@ export class PeerConnection extends EventEmitter {
|
|
|
107
120
|
|
|
108
121
|
console.log(`๐ต Track received: kind=${track.kind}, id=${track.id}, enabled=${track.enabled}, readyState=${track.readyState}`);
|
|
109
122
|
|
|
110
|
-
// CRITICAL:
|
|
111
|
-
if (this.
|
|
112
|
-
|
|
113
|
-
console.error('Local stream ID:', this.localStream.id);
|
|
114
|
-
console.error('Received stream ID:', stream.id);
|
|
115
|
-
return; // Don't process our own stream as remote
|
|
123
|
+
// CRITICAL: Enhanced loopback detection and stream validation
|
|
124
|
+
if (!this.validateRemoteStream(stream, track)) {
|
|
125
|
+
return; // Don't process invalid or looped back streams
|
|
116
126
|
}
|
|
117
127
|
|
|
118
128
|
if (stream) {
|
|
@@ -123,18 +133,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
123
133
|
console.log(`๐ต Remote stream tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
|
|
124
134
|
console.log(`๐ต Remote stream ID: ${stream.id} (vs local: ${this.localStream?.id || 'none'})`);
|
|
125
135
|
|
|
136
|
+
// Mark stream as genuinely remote to prevent future confusion
|
|
137
|
+
this.markStreamAsRemote(stream);
|
|
138
|
+
|
|
126
139
|
audioTracks.forEach((audioTrack, index) => {
|
|
127
140
|
console.log(`๐ต Audio track ${index}: enabled=${audioTrack.enabled}, readyState=${audioTrack.readyState}, muted=${audioTrack.muted}, id=${audioTrack.id}`);
|
|
128
141
|
|
|
129
|
-
// Check if this track ID matches any of our local tracks
|
|
130
|
-
if (this.localStream) {
|
|
131
|
-
const localAudioTracks = this.localStream.getAudioTracks();
|
|
132
|
-
const isOwnTrack = localAudioTracks.some(localTrack => localTrack.id === audioTrack.id);
|
|
133
|
-
if (isOwnTrack) {
|
|
134
|
-
console.error('โ LOOPBACK: This audio track is our own local track!');
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
142
|
// Add audio data monitoring
|
|
139
143
|
this.setupAudioDataMonitoring(audioTrack, index);
|
|
140
144
|
});
|
|
@@ -410,6 +414,185 @@ export class PeerConnection extends EventEmitter {
|
|
|
410
414
|
return false;
|
|
411
415
|
}
|
|
412
416
|
|
|
417
|
+
/**
|
|
418
|
+
* Enhanced validation to ensure received stream is genuinely remote
|
|
419
|
+
*/
|
|
420
|
+
validateRemoteStream(stream, track) {
|
|
421
|
+
// Check 1: Stream ID collision (basic loopback detection)
|
|
422
|
+
if (this.localStream && stream.id === this.localStream.id) {
|
|
423
|
+
console.error('โ LOOPBACK DETECTED: Received our own local stream as remote!');
|
|
424
|
+
console.error('Local stream ID:', this.localStream.id);
|
|
425
|
+
console.error('Received stream ID:', stream.id);
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Check 2: Track ID collision (more granular loopback detection)
|
|
430
|
+
if (this.localStream) {
|
|
431
|
+
const localTracks = this.localStream.getTracks();
|
|
432
|
+
const isOwnTrack = localTracks.some(localTrack => localTrack.id === track.id);
|
|
433
|
+
if (isOwnTrack) {
|
|
434
|
+
console.error('โ TRACK LOOPBACK: This track is our own local track!');
|
|
435
|
+
console.error('Local track ID:', track.id);
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Check 3: Verify track comes from remote peer transceiver
|
|
441
|
+
if (this.connection) {
|
|
442
|
+
const transceivers = this.connection.getTransceivers();
|
|
443
|
+
const sourceTransceiver = transceivers.find(t => t.receiver.track === track);
|
|
444
|
+
if (!sourceTransceiver) {
|
|
445
|
+
console.warn('โ ๏ธ Track not found in any transceiver - may be invalid');
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Ensure this is a receiving transceiver (not sending our own track back)
|
|
450
|
+
if (sourceTransceiver.direction === 'sendonly') {
|
|
451
|
+
console.error('โ Invalid direction: Receiving track from sendonly transceiver');
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Check 4: Verify stream hasn't been marked as local origin
|
|
457
|
+
if (stream._peerPigeonOrigin === 'local') {
|
|
458
|
+
console.error('โ Stream marked as local origin - preventing synchronization loop');
|
|
459
|
+
return false;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
console.log('โ
Remote stream validation passed for peer', this.peerId.substring(0, 8));
|
|
463
|
+
return true;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Mark a stream as genuinely remote to prevent future confusion
|
|
468
|
+
*/
|
|
469
|
+
markStreamAsRemote(stream) {
|
|
470
|
+
// Add internal marker to prevent future misidentification
|
|
471
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
472
|
+
value: 'remote',
|
|
473
|
+
writable: false,
|
|
474
|
+
enumerable: false,
|
|
475
|
+
configurable: false
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
Object.defineProperty(stream, '_peerPigeonSourcePeerId', {
|
|
479
|
+
value: this.peerId,
|
|
480
|
+
writable: false,
|
|
481
|
+
enumerable: false,
|
|
482
|
+
configurable: false
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
console.log(`๐ Stream ${stream.id} marked as remote from peer ${this.peerId.substring(0, 8)}`);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Mark local stream to prevent it from being treated as remote
|
|
490
|
+
*/
|
|
491
|
+
markStreamAsLocal(stream) {
|
|
492
|
+
if (!stream) return;
|
|
493
|
+
|
|
494
|
+
Object.defineProperty(stream, '_peerPigeonOrigin', {
|
|
495
|
+
value: 'local',
|
|
496
|
+
writable: false,
|
|
497
|
+
enumerable: false,
|
|
498
|
+
configurable: false
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
console.log(`๐ Stream ${stream.id} marked as local origin`);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async createOffer() {
|
|
505
|
+
const offer = await this.connection.createOffer();
|
|
506
|
+
await this.connection.setLocalDescription(offer);
|
|
507
|
+
return offer;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async handleOffer(offer) {
|
|
511
|
+
// Check if we're in the right state to handle an offer
|
|
512
|
+
if (this.connection.signalingState !== 'stable') {
|
|
513
|
+
console.log(`Cannot handle offer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: stable)`);
|
|
514
|
+
throw new Error(`Cannot handle offer in state: ${this.connection.signalingState}`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
await this.connection.setRemoteDescription(offer);
|
|
518
|
+
this.remoteDescriptionSet = true;
|
|
519
|
+
await this.processPendingIceCandidates();
|
|
520
|
+
|
|
521
|
+
const answer = await this.connection.createAnswer();
|
|
522
|
+
await this.connection.setLocalDescription(answer);
|
|
523
|
+
return answer;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async handleAnswer(answer) {
|
|
527
|
+
// Check if we're in the right state to handle an answer
|
|
528
|
+
if (this.connection.signalingState !== 'have-local-offer') {
|
|
529
|
+
console.log(`Cannot handle answer from ${this.peerId} - connection state is ${this.connection.signalingState} (expected: have-local-offer)`);
|
|
530
|
+
|
|
531
|
+
// If we're already stable, the connection might already be established
|
|
532
|
+
if (this.connection.signalingState === 'stable') {
|
|
533
|
+
console.log('Connection already stable, answer not needed');
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
throw new Error(`Cannot handle answer in state: ${this.connection.signalingState}`);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
await this.connection.setRemoteDescription(answer);
|
|
541
|
+
this.remoteDescriptionSet = true;
|
|
542
|
+
await this.processPendingIceCandidates();
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async handleIceCandidate(candidate) {
|
|
546
|
+
console.log(`๐ง Received ICE candidate for ${this.peerId.substring(0, 8)}...`, {
|
|
547
|
+
type: candidate.type,
|
|
548
|
+
protocol: candidate.protocol
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
if (!this.remoteDescriptionSet) {
|
|
552
|
+
console.log(`๐ง Buffering ICE candidate for ${this.peerId.substring(0, 8)}... (remote description not set yet)`);
|
|
553
|
+
this.pendingIceCandidates.push(candidate);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
try {
|
|
558
|
+
await this.connection.addIceCandidate(candidate);
|
|
559
|
+
console.log(`๐ง Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
|
|
560
|
+
} catch (error) {
|
|
561
|
+
console.error(`๐ง Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async processPendingIceCandidates() {
|
|
566
|
+
if (this.pendingIceCandidates.length > 0) {
|
|
567
|
+
console.log(`๐ง Processing ${this.pendingIceCandidates.length} buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
|
|
568
|
+
|
|
569
|
+
for (const candidate of this.pendingIceCandidates) {
|
|
570
|
+
try {
|
|
571
|
+
await this.connection.addIceCandidate(candidate);
|
|
572
|
+
console.log(`๐ง Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
|
|
573
|
+
} catch (error) {
|
|
574
|
+
console.error(`๐ง Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
this.pendingIceCandidates = [];
|
|
579
|
+
console.log(`๐ง Finished processing buffered ICE candidates for ${this.peerId.substring(0, 8)}...`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
sendMessage(message) {
|
|
584
|
+
if (this.dataChannel && this.dataChannel.readyState === 'open') {
|
|
585
|
+
try {
|
|
586
|
+
this.dataChannel.send(JSON.stringify(message));
|
|
587
|
+
return true;
|
|
588
|
+
} catch (error) {
|
|
589
|
+
console.error(`Failed to send message to ${this.peerId}:`, error);
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
|
|
413
596
|
/**
|
|
414
597
|
* Add or replace local media stream
|
|
415
598
|
*/
|
|
@@ -436,6 +619,9 @@ export class PeerConnection extends EventEmitter {
|
|
|
436
619
|
const audioTracks = stream.getAudioTracks();
|
|
437
620
|
const videoTracks = stream.getVideoTracks();
|
|
438
621
|
|
|
622
|
+
// Mark stream as local origin to prevent loopback
|
|
623
|
+
this.markStreamAsLocal(stream);
|
|
624
|
+
|
|
439
625
|
// Handle audio track using stored reference
|
|
440
626
|
if (this.audioTransceiver) {
|
|
441
627
|
if (audioTracks.length > 0) {
|
package/src/SignalingHandler.js
CHANGED
|
@@ -191,7 +191,11 @@ export class SignalingHandler extends EventEmitter {
|
|
|
191
191
|
// Get current media stream if available
|
|
192
192
|
const localStream = this.mesh.mediaManager.localStream;
|
|
193
193
|
const hasMedia = localStream !== null;
|
|
194
|
-
const options = {
|
|
194
|
+
const options = {
|
|
195
|
+
localStream,
|
|
196
|
+
enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
|
|
197
|
+
enableVideo: hasMedia && localStream.getVideoTracks().length > 0
|
|
198
|
+
};
|
|
195
199
|
|
|
196
200
|
console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
|
|
197
201
|
|
|
@@ -83,8 +83,8 @@ function isConnectionAlive(connection) {
|
|
|
83
83
|
const lastPong = connection.lastPong || connection.connectedAt || now;
|
|
84
84
|
const timeSinceLastPong = now - lastPong;
|
|
85
85
|
|
|
86
|
-
// Consider connection dead if no pong for more than
|
|
87
|
-
return timeSinceLastPong <
|
|
86
|
+
// Consider connection dead if no pong for more than 12 minutes (since we ping every 9 minutes)
|
|
87
|
+
return timeSinceLastPong < 720000; // 12 minutes
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
function pingConnection(peerId, connection) {
|
|
@@ -176,21 +176,62 @@ setInterval(() => {
|
|
|
176
176
|
}
|
|
177
177
|
}, 30000); // Clean up every 30 seconds
|
|
178
178
|
|
|
179
|
-
//
|
|
179
|
+
// DHT-based heartbeat ping every 9 minutes (540 seconds)
|
|
180
|
+
// Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
|
|
180
181
|
setInterval(() => {
|
|
181
|
-
|
|
182
|
-
const stalePeers = [];
|
|
182
|
+
const activePeers = Array.from(connections.keys());
|
|
183
183
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
184
|
+
if (activePeers.length === 0) {
|
|
185
|
+
console.log(`๐ No peers to ping`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Use XOR distance to select the peer closest to a deterministic target
|
|
190
|
+
// This ensures the same peer is consistently selected across intervals
|
|
191
|
+
const pingTarget = '0000000000000000000000000000000000000000'; // Deterministic target for ping selection
|
|
192
|
+
const selectedPeer = selectPeerForPing(pingTarget, activePeers);
|
|
193
|
+
|
|
194
|
+
if (selectedPeer) {
|
|
195
|
+
const connection = connections.get(selectedPeer);
|
|
196
|
+
console.log(`๐ DHT-selected peer ${selectedPeer.substring(0, 8)}... for heartbeat ping (${activePeers.length} total peers)`);
|
|
197
|
+
|
|
198
|
+
if (!pingConnection(selectedPeer, connection)) {
|
|
199
|
+
console.log(`๐งน DHT-selected peer ${selectedPeer.substring(0, 8)}... failed ping, cleaned up`);
|
|
187
200
|
}
|
|
188
201
|
}
|
|
202
|
+
}, 540000); // Ping every 9 minutes (540 seconds)
|
|
203
|
+
|
|
204
|
+
// DHT-based peer selection for ping duty
|
|
205
|
+
function selectPeerForPing(target, peerIds) {
|
|
206
|
+
if (!peerIds || peerIds.length === 0) return null;
|
|
207
|
+
|
|
208
|
+
// Use XOR distance to find the peer closest to the target
|
|
209
|
+
let closestPeer = null;
|
|
210
|
+
let closestDistance = Infinity;
|
|
189
211
|
|
|
190
|
-
|
|
191
|
-
|
|
212
|
+
for (const peerId of peerIds) {
|
|
213
|
+
const distance = calculateXORDistance(target, peerId);
|
|
214
|
+
if (distance < closestDistance) {
|
|
215
|
+
closestDistance = distance;
|
|
216
|
+
closestPeer = peerId;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return closestPeer;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// XOR distance calculation for DHT peer selection
|
|
224
|
+
function calculateXORDistance(id1, id2) {
|
|
225
|
+
let distance = 0;
|
|
226
|
+
const minLength = Math.min(id1.length, id2.length);
|
|
227
|
+
|
|
228
|
+
for (let i = 0; i < minLength; i++) {
|
|
229
|
+
const xor = parseInt(id1[i], 16) ^ parseInt(id2[i], 16);
|
|
230
|
+
distance += xor;
|
|
192
231
|
}
|
|
193
|
-
|
|
232
|
+
|
|
233
|
+
return distance;
|
|
234
|
+
}
|
|
194
235
|
|
|
195
236
|
wss.on('connection', (ws, req) => {
|
|
196
237
|
let peerId = null;
|