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.
Files changed (72) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +482 -543
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/node/storage-test.js +141 -6
  44. package/examples/selective-streaming-demo.html +698 -0
  45. package/examples/standard-events-demo.js +126 -0
  46. package/package.json +33 -16
  47. package/server/index.js +1032 -98
  48. package/server/start.js +49 -0
  49. package/src/ConnectionManager.js +239 -225
  50. package/src/CryptoManager.js +147 -18
  51. package/src/DebugLogger.js +0 -7
  52. package/src/DistributedStorageManager.js +245 -205
  53. package/src/EnvironmentDetector.js +109 -2
  54. package/src/EventEmitter.js +79 -1
  55. package/src/EvictionManager.js +10 -9
  56. package/src/GossipManager.js +163 -11
  57. package/src/LexicalStorageInterface.js +332 -0
  58. package/src/PeerConnection.js +333 -310
  59. package/src/PeerPigeonMesh.js +577 -135
  60. package/src/SignalingClient.js +14 -243
  61. package/src/SignalingHandler.js +31 -10
  62. package/src/StorageManager.js +0 -39
  63. package/src/WebDHT-Simple.js +389 -0
  64. package/src/WebDHT.js +363 -1165
  65. package/src/browser-entry.js +40 -0
  66. package/examples/browser/assets/images/favicon.png +0 -0
  67. package/examples/browser/assets/images/pigeon.png +0 -0
  68. package/examples/browser/crypto-test.html +0 -427
  69. package/examples/browser/ui-old.js +0 -1926
  70. package/examples/browser/ui.js +0 -3010
  71. package/websocket-server/README.md +0 -247
  72. package/websocket-server/server.js +0 -391
@@ -19,17 +19,6 @@ export class SignalingClient extends EventEmitter {
19
19
  this.connectionPromise = null;
20
20
  this.reconnectTimeout = null;
21
21
  this.isReconnecting = false;
22
-
23
- // Add keep-alive ping to prevent WebSocket timeout
24
- this.keepAliveInterval = null;
25
- this.keepAliveIntervalMs = 9 * 60 * 1000; // Ping every 9 minutes for large safety margin
26
-
27
- // Health monitoring
28
- this.lastPingTime = null;
29
- this.lastPongTime = null;
30
- this.pingTimeout = null;
31
- this.healthCheckInterval = null;
32
- this.connectionQualityTimeout = 10000; // 10 seconds to consider connection unhealthy
33
22
  }
34
23
 
35
24
  setConnectionType(type) {
@@ -71,7 +60,7 @@ export class SignalingClient extends EventEmitter {
71
60
  }
72
61
 
73
62
  async sendSignalingMessage(message) {
74
- // Check connection health before sending
63
+ // Check connection status before sending
75
64
  if (!this.isConnected()) {
76
65
  this.debug.log('WebSocket not connected, attempting to reconnect...');
77
66
  if (!this.isReconnecting) {
@@ -84,12 +73,13 @@ export class SignalingClient extends EventEmitter {
84
73
  type: message.type,
85
74
  data: message.data,
86
75
  maxPeers: this.maxPeers,
76
+ networkName: this.mesh ? this.mesh.networkName : 'global', // Include network namespace
87
77
  ...(message.targetPeerId && { targetPeerId: message.targetPeerId })
88
78
  };
89
79
 
90
80
  try {
91
81
  this.websocket.send(JSON.stringify(payload));
92
- this.debug.log('Sent WebSocket message:', payload.type);
82
+ this.debug.log(`Sent WebSocket message: ${payload.type} (network: ${payload.networkName})`);
93
83
  return { success: true };
94
84
  } catch (error) {
95
85
  this.debug.error('Failed to send WebSocket message:', error);
@@ -169,14 +159,10 @@ export class SignalingClient extends EventEmitter {
169
159
  type: 'announce',
170
160
  data: { peerId: this.peerId }
171
161
  }).then(() => {
172
- this.startKeepAlive();
173
- // Removed health monitoring - keep-alive pings are sufficient
174
162
  this.emit('connected');
175
163
  resolve();
176
164
  }).catch(error => {
177
165
  this.debug.error('Failed to send announce message:', error);
178
- this.startKeepAlive();
179
- // Removed health monitoring - keep-alive pings are sufficient
180
166
  this.emit('connected'); // Still emit connected even if announce fails
181
167
  resolve();
182
168
  });
@@ -185,17 +171,22 @@ export class SignalingClient extends EventEmitter {
185
171
  this.websocket.onmessage = (event) => {
186
172
  try {
187
173
  const message = JSON.parse(event.data);
188
- this.debug.log('Received WebSocket message:', message.type);
174
+ this.debug.log(`Received WebSocket message: ${message.type} (network: ${message.networkName || 'unknown'})`);
189
175
 
190
176
  if (message.type === 'connected') {
191
177
  // Connection confirmation from server
192
178
  this.debug.log('WebSocket connection confirmed by server');
193
- } else if (message.type === 'pong') {
194
- // Handle pong response for health monitoring
195
- this.handlePong();
196
179
  } else {
197
- // Forward signaling message to mesh
198
- this.emit('signalingMessage', message);
180
+ // Filter messages by network namespace
181
+ const currentNetwork = this.mesh ? this.mesh.networkName : 'global';
182
+ const messageNetwork = message.networkName || 'global';
183
+
184
+ if (messageNetwork === currentNetwork) {
185
+ // Forward signaling message to mesh
186
+ this.emit('signalingMessage', message);
187
+ } else {
188
+ this.debug.log(`Filtered message from different network: ${messageNetwork} (current: ${currentNetwork})`);
189
+ }
199
190
  }
200
191
  } catch (error) {
201
192
  this.debug.error('Failed to parse WebSocket message:', error);
@@ -206,8 +197,6 @@ export class SignalingClient extends EventEmitter {
206
197
  clearTimeout(connectTimeout);
207
198
  this.connected = false;
208
199
  this.connectionPromise = null;
209
- this.stopKeepAlive();
210
- // Removed health monitoring stop - not using health monitoring
211
200
 
212
201
  this.debug.log('WebSocket closed:', event.code, event.reason);
213
202
 
@@ -316,8 +305,6 @@ export class SignalingClient extends EventEmitter {
316
305
  // The sendGoodbyeMessage is often called from an unload handler,
317
306
  // so we don't want to make it part of the standard disconnect flow here.
318
307
  // The CleanupManager handles sending goodbye on unload.
319
- this.stopKeepAlive();
320
- this.stopHealthMonitoring(); // FIX: Stop health monitoring to prevent memory leaks
321
308
 
322
309
  this.connected = false;
323
310
  this.connectionPromise = null;
@@ -376,227 +363,11 @@ export class SignalingClient extends EventEmitter {
376
363
  }
377
364
  }
378
365
 
379
- startKeepAlive() {
380
- if (this.keepAliveInterval) return;
381
-
382
- this.debug.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
383
-
384
- const keepAliveCallback = () => {
385
- if (this.connected) {
386
- // Check if this peer should send the ping
387
- if (this.shouldSendKeepAlivePing()) {
388
- this.debug.log('Sending keep-alive ping (designated peer)');
389
- this.sendSignalingMessage({
390
- type: 'ping',
391
- data: { peerId: this.peerId }
392
- }).catch(error => {
393
- this.debug.error('Keep-alive ping failed:', error);
394
- });
395
- } else {
396
- this.debug.log('Skipping keep-alive ping (not designated peer)');
397
- }
398
- }
399
- };
400
-
401
- if (environmentDetector.isBrowser || environmentDetector.isNativeScript) {
402
- this.keepAliveInterval = (typeof window !== 'undefined' ? window.setInterval : setInterval)(keepAliveCallback, this.keepAliveIntervalMs);
403
- } else {
404
- this.keepAliveInterval = setInterval(keepAliveCallback, this.keepAliveIntervalMs);
405
- }
406
- }
407
-
408
- /**
409
- * Determine if this peer should send the keep-alive ping.
410
- * Only one peer should send it when there are multiple peers connected.
411
- * The peer with the lexicographically smallest ID becomes the designated sender.
412
- */
413
- shouldSendKeepAlivePing() {
414
- // If no mesh reference available, always send (fallback)
415
- if (!this.mesh) {
416
- return true;
417
- }
418
-
419
- // Get all connected peers
420
- const connectedPeers = this.mesh.connectionManager.getConnectedPeers();
421
-
422
- // If no peers connected, always send
423
- if (connectedPeers.length === 0) {
424
- return true;
425
- }
426
-
427
- // Get all peer IDs including this one
428
- const allPeerIds = [this.peerId, ...connectedPeers.map(peer => peer.peerId)];
429
-
430
- // Sort lexicographically and check if this peer is the smallest
431
- allPeerIds.sort();
432
- const designatedPeer = allPeerIds[0];
433
-
434
- const isDesignated = designatedPeer === this.peerId;
435
- this.debug.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
436
-
437
- return isDesignated;
438
- }
439
-
440
- stopKeepAlive() {
441
- if (this.keepAliveInterval) {
442
- clearInterval(this.keepAliveInterval);
443
- this.keepAliveInterval = null;
444
- this.debug.log('Stopped keep-alive pings');
445
- }
446
- }
447
-
448
- startHealthMonitoring() {
449
- if (this.healthCheckInterval) return;
450
-
451
- this.debug.log('Starting connection health monitoring');
452
-
453
- const healthCheckCallback = () => {
454
- // Check WebSocket state first
455
- if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
456
- this.debug.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
457
- this.handleUnhealthyConnection();
458
- return;
459
- }
460
-
461
- if (this.connected) {
462
- const now = Date.now();
463
-
464
- // Only check for pong timeout if we have a pending ping
465
- if (this.pingTimeout) {
466
- // There's already a ping waiting for pong, don't send another
467
- this.debug.log('Ping already pending, waiting for pong...');
468
- return;
469
- }
470
-
471
- // Check if we have an old pong that indicates connection issues
472
- if (this.lastPingTime && this.lastPongTime &&
473
- (this.lastPingTime > this.lastPongTime) &&
474
- (now - this.lastPingTime > this.connectionQualityTimeout)) {
475
- this.debug.warn('Connection unhealthy - ping/pong timeout');
476
- this.handleUnhealthyConnection();
477
- return;
478
- }
479
-
480
- // Send health ping
481
- this.sendHealthPing();
482
- }
483
- };
484
-
485
- if (environmentDetector.isBrowser || environmentDetector.isNativeScript) {
486
- this.healthCheckInterval = (typeof window !== 'undefined' ? window.setInterval : setInterval)(healthCheckCallback, 30000);
487
- } else {
488
- this.healthCheckInterval = setInterval(healthCheckCallback, 30000);
489
- }
490
- }
491
-
492
- stopHealthMonitoring() {
493
- if (this.healthCheckInterval) {
494
- clearInterval(this.healthCheckInterval);
495
- this.healthCheckInterval = null;
496
- this.debug.log('Stopped connection health monitoring');
497
- }
498
-
499
- if (this.pingTimeout) {
500
- clearTimeout(this.pingTimeout);
501
- this.pingTimeout = null;
502
- }
503
- }
504
-
505
- sendHealthPing() {
506
- if (!this.isConnected()) return;
507
-
508
- try {
509
- this.lastPingTime = Date.now();
510
-
511
- // Set timeout for pong response
512
- if (this.pingTimeout) {
513
- clearTimeout(this.pingTimeout);
514
- }
515
-
516
- this.pingTimeout = setTimeout(() => {
517
- this.debug.warn('Health ping timeout - connection may be unhealthy');
518
- this.handleUnhealthyConnection();
519
- }, this.connectionQualityTimeout);
520
-
521
- // Send ping as a regular message (server will handle it)
522
- this.websocket.send(JSON.stringify({
523
- type: 'ping',
524
- data: { peerId: this.peerId, timestamp: this.lastPingTime }
525
- }));
526
-
527
- this.debug.log('Sent health ping');
528
- } catch (error) {
529
- this.debug.error('Failed to send health ping:', error);
530
- this.handleUnhealthyConnection();
531
- }
532
- }
533
-
534
- handlePong() {
535
- this.lastPongTime = Date.now();
536
-
537
- if (this.pingTimeout) {
538
- clearTimeout(this.pingTimeout);
539
- this.pingTimeout = null;
540
- }
541
-
542
- this.debug.log('Received pong - connection healthy');
543
- }
544
-
545
- handleUnhealthyConnection() {
546
- this.debug.warn('Detected unhealthy WebSocket connection, forcing reconnection');
547
- this.emit('statusChanged', { type: 'warning', message: 'Connection health degraded - reconnecting...' });
548
-
549
- // Force close and reconnect
550
- this.connected = false;
551
- if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
552
- this.websocket.close(3000, 'Health check failed'); // Use valid close code 3000-4999
553
- }
554
-
555
- if (!this.isReconnecting) {
556
- this.attemptReconnect();
557
- }
558
- }
559
-
560
- forceHealthCheck() {
561
- if (!this.isConnected()) {
562
- this.debug.log('Connection not healthy, triggering reconnection');
563
- if (!this.isReconnecting) {
564
- this.attemptReconnect();
565
- }
566
- return false;
567
- }
568
-
569
- this.sendHealthPing();
570
- return true;
571
- }
572
-
573
- /**
574
- * Force an immediate keep-alive ping check when peer topology changes.
575
- * This ensures quick takeover when the designated ping sender disconnects.
576
- */
577
- triggerKeepAlivePingCheck() {
578
- if (!this.connected) return;
579
-
580
- if (this.shouldSendKeepAlivePing()) {
581
- this.debug.log('Topology changed - sending immediate keep-alive ping as new designated peer');
582
- this.sendSignalingMessage({
583
- type: 'ping',
584
- data: { peerId: this.peerId }
585
- }).catch(error => {
586
- this.debug.error('Immediate keep-alive ping failed:', error);
587
- });
588
- } else {
589
- this.debug.log('Topology changed - not designated for keep-alive pings');
590
- }
591
- }
592
-
593
366
  getConnectionStats() {
594
367
  return {
595
368
  connected: this.connected,
596
369
  isReconnecting: this.isReconnecting,
597
370
  reconnectAttempts: this.reconnectAttempts,
598
- lastPingTime: this.lastPingTime,
599
- lastPongTime: this.lastPongTime,
600
371
  websocketState: this.websocket ? this.websocket.readyState : 'not created'
601
372
  };
602
373
  }
@@ -54,11 +54,6 @@ export class SignalingHandler extends EventEmitter {
54
54
  return;
55
55
  }
56
56
 
57
- // Ignore ping messages - they are for keepalive, not peer signaling
58
- if (type === 'ping' || type === 'pong') {
59
- return;
60
- }
61
-
62
57
  this.debug.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
63
58
 
64
59
  switch (type) {
@@ -146,6 +141,30 @@ export class SignalingHandler extends EventEmitter {
146
141
  return;
147
142
  }
148
143
 
144
+ // INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
145
+ // Only accept offers if we should NOT be the initiator (i.e., the other peer should initiate)
146
+ const shouldWeInitiate = this.mesh.peerId > fromPeerId;
147
+ if (shouldWeInitiate) {
148
+ this.debug.log(`🔄 INITIATOR LOGIC: Rejecting offer from ${fromPeerId.substring(0, 8)}... because we should be the initiator (our ID: ${this.mesh.peerId.substring(0, 8)}... > their ID)`);
149
+
150
+ // Send a polite rejection so they know we expect to be the initiator
151
+ try {
152
+ await this.mesh.sendSignalingMessage({
153
+ type: 'connection-rejected',
154
+ data: {
155
+ reason: 'initiator_role_conflict',
156
+ details: 'Peer should wait for us to initiate based on peer ID comparison',
157
+ shouldInitiate: false
158
+ }
159
+ }, fromPeerId);
160
+ } catch (error) {
161
+ this.debug.warn('Failed to send initiator rejection:', error);
162
+ }
163
+ return;
164
+ }
165
+
166
+ this.debug.log(`🔄 INITIATOR LOGIC: Accepting offer from ${fromPeerId.substring(0, 8)}... because they should be the initiator (their ID: ${fromPeerId.substring(0, 8)}... > our ID: ${this.mesh.peerId.substring(0, 8)}...)`);
167
+
149
168
  // If we already have a connection or are connecting, handle gracefully
150
169
  if (this.connectionManager.hasPeer(fromPeerId)) {
151
170
  const existingPeer = this.connectionManager.getPeer(fromPeerId);
@@ -160,6 +179,8 @@ export class SignalingHandler extends EventEmitter {
160
179
  // IMPROVED RACE CONDITION HANDLING:
161
180
  // Instead of ignoring offers based on initiator flags, resolve race conditions intelligently
162
181
  const weShouldInitiate = this.mesh.peerId > fromPeerId;
182
+ this.debug.log(`🔄 INITIATOR LOGIC: ${this.mesh.peerId.substring(0, 8)}... vs ${fromPeerId.substring(0, 8)}... → weShouldInitiate: ${weShouldInitiate}`);
183
+ this.debug.log(`🔄 EXISTING PEER: isInitiator: ${existingPeer.isInitiator}, status: ${existingStatus}`);
163
184
 
164
185
  // If both peers are trying to initiate (mutual initiation race condition)
165
186
  if (weShouldInitiate && existingPeer.isInitiator) {
@@ -263,18 +284,18 @@ export class SignalingHandler extends EventEmitter {
263
284
  await this.mesh.evictionManager.evictPeer(evictPeerId, 'incoming closer peer');
264
285
  }
265
286
  try {
266
- // Get current media stream if available
267
- const localStream = this.mesh.mediaManager.localStream;
268
- const hasMedia = localStream !== null;
287
+ // SECURITY: NO automatic media sharing - all media must be manually invoked
269
288
  const options = {
270
- localStream,
289
+ localStream: null, // Always null - media must be manually added later
271
290
  // ALWAYS enable both audio and video transceivers for maximum compatibility
272
291
  // This allows peers to receive media even if they don't have media when connecting
273
292
  enableAudio: true,
274
293
  enableVideo: true
294
+ // allowRemoteStreams defaults to false - streams only invoked when user explicitly enables them
275
295
  };
276
296
 
277
- this.debug.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
297
+ this.debug.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (no automatic media sharing)`);
298
+ this.debug.log(`🔄 RECEIVER SETUP: Creating PeerConnection(${fromPeerId.substring(0, 8)}..., isInitiator=false)`);
278
299
 
279
300
  const peerConnection = new PeerConnection(fromPeerId, false, options);
280
301
 
@@ -74,45 +74,6 @@ export class StorageManager extends EventEmitter {
74
74
  return this.loadSignalingUrlFromStorage();
75
75
  }
76
76
 
77
- async generatePeerId() {
78
- const array = new Uint8Array(20);
79
-
80
- // Environment-aware random value generation
81
- if (environmentDetector.hasRandomValues) {
82
- if (environmentDetector.isBrowser || environmentDetector.isWorker || environmentDetector.isNativeScript) {
83
- crypto.getRandomValues(array);
84
- } else if (environmentDetector.isNodeJS) {
85
- // In Node.js, use crypto module (handle both CommonJS and ES modules)
86
- try {
87
- if (typeof require !== 'undefined') {
88
- const crypto = require('crypto');
89
- const randomBytes = crypto.randomBytes(20);
90
- array.set(randomBytes);
91
- } else {
92
- // ES module approach - import crypto dynamically
93
- const crypto = await import('crypto');
94
- const randomBytes = crypto.randomBytes(20);
95
- array.set(randomBytes);
96
- }
97
- } catch (e) {
98
- this.debug.warn('Could not use Node.js crypto, falling back to Math.random');
99
- // Fallback to Math.random
100
- for (let i = 0; i < array.length; i++) {
101
- array[i] = Math.floor(Math.random() * 256);
102
- }
103
- }
104
- }
105
- } else {
106
- // Fallback to less secure random generation
107
- this.debug.warn('Secure random values not available, using fallback method');
108
- for (let i = 0; i < array.length; i++) {
109
- array[i] = Math.floor(Math.random() * 256);
110
- }
111
- }
112
-
113
- return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
114
- }
115
-
116
77
  validatePeerId(peerId) {
117
78
  return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
118
79
  }