peerpigeon 1.0.2 → 1.0.3

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.
@@ -0,0 +1,135 @@
1
+ # Local Testing Guide
2
+
3
+ ## WebRTC Local Connection Requirements
4
+
5
+ When testing PeerPigeon locally (localhost), **WebRTC connections require media permissions** due to browser security restrictions.
6
+
7
+ ### Why This Happens
8
+
9
+ Chrome and other browsers restrict ICE candidate gathering (especially mDNS/local network discovery) unless:
10
+
11
+ 1. **Media permissions are granted** (microphone or camera access)
12
+ 2. **TURN server is configured** for relaying connections
13
+ 3. **Connection is over HTTPS** (not applicable for localhost)
14
+
15
+ ### Solution: Grant Media Permissions
16
+
17
+ Before testing peer connections locally:
18
+
19
+ #### Option 1: Use the Media Tab
20
+ 1. Open the browser example at `http://localhost:8080/`
21
+ 2. Go to the **"Media"** tab
22
+ 3. Click **"Start Media"** button
23
+ 4. Allow microphone/camera access when prompted
24
+ 5. Now peer connections will work!
25
+
26
+ #### Option 2: Manual Permission Grant
27
+ 1. Open Chrome settings: `chrome://settings/content/microphone`
28
+ 2. Add `http://localhost:8080` to allowed sites
29
+ 3. Refresh the page
30
+
31
+ ### Symptoms of Missing Permissions
32
+
33
+ If you see these symptoms, you need to grant media permissions:
34
+
35
+ - ✅ Peers discover each other
36
+ - ✅ Offers and answers are exchanged
37
+ - ✅ ICE candidates are being sent
38
+ - ❌ Connection fails after 15-30 seconds
39
+ - ❌ Console shows "connection failed" or "ICE failed"
40
+
41
+ ### Why Only Local Testing?
42
+
43
+ This issue **only affects localhost testing**. In production:
44
+ - HTTPS automatically enables WebRTC without media permissions
45
+ - Public STUN/TURN servers handle NAT traversal
46
+ - Connections work normally without requiring media access
47
+
48
+ ### Alternative: Use TURN Server
49
+
50
+ Configure a TURN server for local testing without media:
51
+
52
+ ```javascript
53
+ const mesh = new PeerPigeon.PeerPigeonMesh({
54
+ iceServers: [
55
+ { urls: 'stun:stun.l.google.com:19302' },
56
+ {
57
+ urls: 'turn:your-turn-server.com:3478',
58
+ username: 'user',
59
+ credential: 'pass'
60
+ }
61
+ ]
62
+ });
63
+ ```
64
+
65
+ ### Quick Test Script
66
+
67
+ Run this in the browser console to test if you have the necessary permissions:
68
+
69
+ ```javascript
70
+ // Test media permissions
71
+ navigator.mediaDevices.getUserMedia({ audio: true, video: false })
72
+ .then(() => console.log('✅ Media permissions granted - connections will work'))
73
+ .catch(() => console.log('❌ Media permissions denied - connections may fail on localhost'));
74
+ ```
75
+
76
+ ## Testing Workflow
77
+
78
+ ### Recommended Testing Flow
79
+
80
+ 1. **Start the servers:**
81
+ ```bash
82
+ npm run dev
83
+ ```
84
+
85
+ 2. **Open two browser tabs:**
86
+ - Tab 1: `http://localhost:8080/`
87
+ - Tab 2: `http://localhost:8080/`
88
+
89
+ 3. **Grant media permissions in BOTH tabs:**
90
+ - Click "Media" tab
91
+ - Click "Start Media"
92
+ - Allow microphone access
93
+ - You can mute/stop after permissions are granted
94
+
95
+ 4. **Connect to the signaling server:**
96
+ - Click "Connect" button in Connection tab
97
+ - Wait for "Connected to signaling server" message
98
+
99
+ 5. **Watch peers connect automatically:**
100
+ - Peers will discover each other
101
+ - Connections should establish within 2-3 seconds
102
+ - Check "Connected Peers" section
103
+
104
+ ### Production Deployment
105
+
106
+ For production deployment on HTTPS, media permissions are **not required** for data-only connections. WebRTC works normally with just signaling.
107
+
108
+ ## Troubleshooting
109
+
110
+ ### Connection Still Fails After Granting Media
111
+
112
+ 1. **Check browser console** for detailed errors
113
+ 2. **Verify signaling server** is running (`ws://localhost:3000`)
114
+ 3. **Check ICE candidates** are being generated (look for host candidates)
115
+ 4. **Try reloading** both browser tabs
116
+
117
+ ### ICE Candidates Not Generated
118
+
119
+ If you don't see any ICE candidates with `typ host`:
120
+ - Media permissions were not granted
121
+ - Browser is blocking local network discovery
122
+ - Try using a TURN server
123
+
124
+ ### Firewall Issues
125
+
126
+ Even on localhost, some corporate firewalls block WebRTC:
127
+ - Try disabling firewall temporarily
128
+ - Check if WebRTC is blocked by enterprise policy
129
+ - Test on a different network
130
+
131
+ ## Reference Links
132
+
133
+ - [WebRTC Security](https://webrtc-security.github.io/)
134
+ - [ICE Candidate Gathering](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidate_event)
135
+ - [Chrome WebRTC Permissions](https://developer.chrome.com/docs/web-platform/webrtc-permissions)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerpigeon",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "WebRTC-based peer-to-peer mesh networking library with intelligent routing and signaling server",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -19,11 +19,13 @@
19
19
  "cli": "node cli.js",
20
20
  "cli:server": "node cli.js server",
21
21
  "cli:interactive": "node cli.js interactive",
22
- "dev": "npm run build && node dev-runner.js",
23
- "dev:http": "node dev-server.js",
22
+ "dev": "npm run build && concurrently -n \"HUB,HTTP\" -c \"cyan,green\" \"npm run hub\" \"npm run http\"",
23
+ "dev:hub": "npm run build && node scripts/start-hub.js",
24
+ "dev:http": "npm run build && node dev-server.js",
24
25
  "start": "node server/start.js",
25
26
  "server": "node server/start.js",
26
27
  "hub": "node scripts/start-hub.js",
28
+ "http": "node dev-server.js",
27
29
  "lint": "node -c src/*.js examples/**/*.js server/*.js",
28
30
  "lint:fix": "eslint --cache --cache-location .eslintcache src/ examples/ server/ --ext .js --fix",
29
31
  "test": "node test/browser-integration-test.js",
@@ -1043,8 +1043,9 @@ export class ConnectionManager extends EventEmitter {
1043
1043
  if (peerConnection.connection?.signalingState === 'have-local-offer') {
1044
1044
  const connectionAge = Date.now() - peerConnection.connectionStartTime;
1045
1045
 
1046
- // If connection has been stuck in "have-local-offer" for more than 2 seconds, fix it
1047
- if (connectionAge > 2000) {
1046
+ // If connection has been stuck in "have-local-offer" for more than 10 seconds, fix it
1047
+ // This timeout balances between allowing time for signaling and detecting truly stuck connections
1048
+ if (connectionAge > 10000) {
1048
1049
  stuckConnections.push(peerId);
1049
1050
  }
1050
1051
  }
@@ -1052,6 +1053,13 @@ export class ConnectionManager extends EventEmitter {
1052
1053
 
1053
1054
  if (stuckConnections.length > 0) {
1054
1055
  this.debug.log(`🚨 STUCK MONITOR: Found ${stuckConnections.length} stuck connections - forcing recovery`);
1056
+
1057
+ // Log a warning about local testing requirements
1058
+ if (typeof window !== 'undefined' && window.location?.hostname === 'localhost') {
1059
+ console.warn('⚠️ LOCAL TESTING: WebRTC connections on localhost require media permissions!');
1060
+ console.warn(' Go to the Media tab and click "Start Media" to grant permissions.');
1061
+ console.warn(' See docs/LOCAL_TESTING.md for details.');
1062
+ }
1055
1063
 
1056
1064
  for (const peerId of stuckConnections) {
1057
1065
  this.forceConnectionRecovery(peerId).catch(error => {
@@ -319,6 +319,38 @@ export class PeerPigeonMesh extends EventEmitter {
319
319
  this.debug.warn('PigeonRTC initialization failed:', error.message);
320
320
  }
321
321
 
322
+ // Request media permissions for localhost WebRTC to work
323
+ // This is required for Chrome to gather ICE candidates on localhost
324
+ if (environmentDetector.isBrowser) {
325
+ try {
326
+ const isLocalhost = window.location.hostname === 'localhost' ||
327
+ window.location.hostname === '127.0.0.1' ||
328
+ window.location.hostname === '';
329
+
330
+ if (isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
331
+ this.debug.log('🎤 Requesting media permissions for localhost WebRTC...');
332
+
333
+ // Request minimal audio permission (no video to reduce intrusiveness)
334
+ const stream = await navigator.mediaDevices.getUserMedia({
335
+ audio: true,
336
+ video: false
337
+ }).catch(err => {
338
+ this.debug.warn('Media permission denied - connections may fail on localhost:', err.message);
339
+ return null;
340
+ });
341
+
342
+ // Immediately stop all tracks - we only needed the permission
343
+ if (stream) {
344
+ stream.getTracks().forEach(track => track.stop());
345
+ this.debug.log('✅ Media permissions granted - localhost connections will work');
346
+ }
347
+ }
348
+ } catch (error) {
349
+ this.debug.warn('Could not request media permissions:', error.message);
350
+ // Continue anyway - non-localhost environments don't need this
351
+ }
352
+ }
353
+
322
354
  // Use provided peer ID if valid, otherwise generate one
323
355
  if (this.providedPeerId) {
324
356
  if (PeerPigeonMesh.validatePeerId(this.providedPeerId)) {
@@ -410,9 +410,18 @@ export class SignalingHandler extends EventEmitter {
410
410
  // CRITICAL DEBUG: Check if we have a peer connection for this answer
411
411
  const peerConnection = this.connectionManager.getPeer(fromPeerId);
412
412
  this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Found peer connection: ${!!peerConnection}`);
413
+
414
+ // DEBUG: Log all current peers
415
+ const allPeerIds = Array.from(this.connectionManager.peers.keys());
416
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: All current peers (${allPeerIds.length}): ${allPeerIds.map(p => p.substring(0, 8)).join(', ')}`);
417
+
413
418
  if (peerConnection) {
414
419
  this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Peer connection state: ${peerConnection.connection?.signalingState}`);
415
420
  this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Is initiator: ${peerConnection.isInitiator}`);
421
+ this.debug.log(`🔄 ANSWER RECEIVE DEBUG: Connection age: ${Date.now() - peerConnection.connectionStartTime}ms`);
422
+ } else {
423
+ this.debug.error(`🔄 ANSWER RECEIVE DEBUG: NO PEER CONNECTION - Was expecting peer ${fromPeerId.substring(0, 8)}...`);
424
+ this.debug.error(`🔄 ANSWER RECEIVE DEBUG: This means the peer connection was cleaned up or never created!`);
416
425
  }
417
426
 
418
427
  if (peerConnection) {
@@ -433,7 +442,8 @@ export class SignalingHandler extends EventEmitter {
433
442
  }
434
443
  }
435
444
  } else {
436
- this.debug.log('❌ ANSWER RECEIVE DEBUG: No peer connection found for answer from', fromPeerId);
445
+ this.debug.error('❌ ANSWER RECEIVE DEBUG: No peer connection found for answer from', fromPeerId);
446
+ this.debug.error('❌ ANSWER RECEIVE DEBUG: Peer connection may have been cleaned up prematurely - check connection timeout/cleanup logic');
437
447
  }
438
448
  }
439
449