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
@@ -17,19 +17,26 @@ async function initializeUnsea() {
17
17
  unsea = await import('unsea');
18
18
  console.log('✅ Loaded unsea from npm package (Node.js)');
19
19
  } else if (isBrowser) {
20
- // For browser environments, try CDN sources
21
- try {
22
- unsea = await import('https://cdn.jsdelivr.net/npm/unsea@latest/+esm');
23
- console.log('✅ Loaded unsea from jsDelivr CDN');
24
- } catch (jsDelivrError) {
25
- console.warn('Failed to load from jsDelivr, trying unpkg:', jsDelivrError);
20
+ // Check if we have the bundled version first (from browser bundle)
21
+ if ((typeof globalThis !== 'undefined' && globalThis.__PEERPIGEON_UNSEA__) ||
22
+ (typeof window !== 'undefined' && window.__PEERPIGEON_UNSEA__)) {
23
+ unsea = globalThis.__PEERPIGEON_UNSEA__ || window.__PEERPIGEON_UNSEA__;
24
+ console.log('✅ Using bundled unsea (self-contained)');
25
+ } else {
26
+ // Fallback to CDN sources for backwards compatibility
26
27
  try {
27
- unsea = await import('https://unpkg.com/unsea@latest/dist/unsea.esm.js');
28
- console.log('✅ Loaded unsea from unpkg CDN');
29
- } catch (unpkgError) {
30
- console.warn('Failed to load from unpkg, trying Skypack:', unpkgError);
31
- unsea = await import('https://cdn.skypack.dev/unsea');
32
- console.log('✅ Loaded unsea from Skypack CDN');
28
+ unsea = await import('https://cdn.jsdelivr.net/npm/unsea@latest/+esm');
29
+ console.log('✅ Loaded unsea from jsDelivr CDN');
30
+ } catch (jsDelivrError) {
31
+ console.warn('Failed to load from jsDelivr, trying unpkg:', jsDelivrError);
32
+ try {
33
+ unsea = await import('https://unpkg.com/unsea@latest/dist/unsea.esm.js');
34
+ console.log('✅ Loaded unsea from unpkg CDN');
35
+ } catch (unpkgError) {
36
+ console.warn('Failed to load from unpkg, trying Skypack:', unpkgError);
37
+ unsea = await import('https://cdn.skypack.dev/unsea');
38
+ console.log('✅ Loaded unsea from Skypack CDN');
39
+ }
33
40
  }
34
41
  }
35
42
  } else {
@@ -59,6 +66,7 @@ export class CryptoManager extends EventEmitter {
59
66
  this.groupKeys = new Map(); // Store group encryption keys
60
67
  this.messageNonces = new Set(); // Prevent replay attacks
61
68
  this.maxNonceAge = 300000; // 5 minutes
69
+ this.nonceCleanupInterval = null; // Track the cleanup interval
62
70
 
63
71
  // Performance metrics
64
72
  this.stats = {
@@ -76,6 +84,7 @@ export class CryptoManager extends EventEmitter {
76
84
  * @param {string} options.alias - Optional user alias for persistent identity
77
85
  * @param {string} options.password - Optional password for user account
78
86
  * @param {boolean} options.generateKeypair - Whether to generate a new keypair if no credentials
87
+ * @param {string} options.peerId - Peer ID to use for automatic key storage
79
88
  * @returns {Promise<Object>} The generated or loaded keypair
80
89
  */
81
90
  async init(options = {}) {
@@ -85,6 +94,9 @@ export class CryptoManager extends EventEmitter {
85
94
  if (options.alias && options.password) {
86
95
  // Try to create or authenticate with persistent identity
87
96
  await this.createOrAuthenticateUser(options.alias, options.password);
97
+ } else if (options.peerId) {
98
+ // Use peer ID for automatic persistent key storage
99
+ await this.initWithPeerId(options.peerId);
88
100
  } else if (options.generateKeypair !== false) {
89
101
  // Generate ephemeral keypair
90
102
  this.keypair = await this.unsea.generateRandomPair();
@@ -126,7 +138,14 @@ export class CryptoManager extends EventEmitter {
126
138
  } else {
127
139
  // Generate new keys and save them
128
140
  this.keypair = await this.unsea.generateRandomPair();
129
- await this.unsea.saveKeys(alias, this.keypair, password);
141
+ // PERFORMANCE: Defer key saving to prevent blocking WebRTC connection establishment
142
+ setTimeout(async () => {
143
+ try {
144
+ await this.unsea.saveKeys(alias, this.keypair, password);
145
+ } catch (saveError) {
146
+ this.debug.warn('Failed to save persistent keys:', saveError);
147
+ }
148
+ }, 0);
130
149
  }
131
150
  } catch (error) {
132
151
  // Fallback to generating ephemeral keys
@@ -145,6 +164,92 @@ export class CryptoManager extends EventEmitter {
145
164
  }
146
165
  }
147
166
 
167
+ /**
168
+ * Initialize with automatic key persistence using peer ID
169
+ * @param {string} peerId - The peer ID to use as storage alias
170
+ */
171
+ async initWithPeerId(peerId) {
172
+ try {
173
+ // Initialize unsea if not already done
174
+ if (!this.unsea) {
175
+ this.unsea = await initializeUnsea();
176
+ }
177
+
178
+ const keyAlias = `peerpigeon-${peerId}`;
179
+ this.debug.log(`🔐 Initializing crypto with automatic key persistence for peer ${peerId.substring(0, 8)}...`);
180
+
181
+ // Try to load existing keys first with timeout
182
+ try {
183
+ const loadKeysPromise = this.unsea.loadKeys(keyAlias);
184
+ const timeoutPromise = new Promise((resolve, reject) => {
185
+ setTimeout(() => reject(new Error('LoadKeys timeout')), 5000);
186
+ });
187
+
188
+ const existingKeys = await Promise.race([loadKeysPromise, timeoutPromise]);
189
+ if (existingKeys && existingKeys.pub && existingKeys.priv) {
190
+ this.keypair = existingKeys;
191
+ this.debug.log(`🔐 Loaded existing keypair for peer ${peerId.substring(0, 8)}...`);
192
+
193
+ // Mark as initialized and emit ready event
194
+ this.initialized = true;
195
+ this.encryptionEnabled = true;
196
+ this.emit('cryptoReady', {
197
+ hasKeypair: !!this.keypair,
198
+ publicKey: this.getPublicKey()
199
+ });
200
+ return;
201
+ }
202
+ } catch (error) {
203
+ this.debug.log(`🔐 No existing keys found for peer ${peerId.substring(0, 8)}..., will generate new ones`);
204
+ }
205
+
206
+ // Generate new keys and save them with timeout
207
+ const generateKeysPromise = this.unsea.generateRandomPair();
208
+ const generateTimeoutPromise = new Promise((resolve, reject) => {
209
+ setTimeout(() => reject(new Error('GenerateKeys timeout')), 5000);
210
+ });
211
+
212
+ this.keypair = await Promise.race([generateKeysPromise, generateTimeoutPromise]);
213
+
214
+ // PERFORMANCE: Defer key saving to prevent blocking WebRTC connection establishment
215
+ setTimeout(async () => {
216
+ try {
217
+ await this.unsea.saveKeys(keyAlias, this.keypair);
218
+ this.debug.log(`🔐 Generated and saved new keypair for peer ${peerId.substring(0, 8)}...`);
219
+ } catch (saveError) {
220
+ this.debug.warn(`🔐 Failed to save keypair for peer ${peerId.substring(0, 8)}..., using ephemeral keys:`, saveError.message);
221
+ // Continue with ephemeral keys if storage fails
222
+ }
223
+ }, 0);
224
+
225
+ // Mark as initialized and emit ready event
226
+ this.initialized = true;
227
+ this.encryptionEnabled = true;
228
+ this.emit('cryptoReady', {
229
+ hasKeypair: !!this.keypair,
230
+ publicKey: this.getPublicKey()
231
+ });
232
+
233
+ } catch (error) {
234
+ this.debug.error('Failed to initialize crypto with peer ID:', error);
235
+ // Fallback to ephemeral keypair
236
+ if (this.unsea) {
237
+ this.keypair = await this.unsea.generateRandomPair();
238
+ this.debug.log('🔐 Using ephemeral keypair as fallback');
239
+ } else {
240
+ throw error;
241
+ }
242
+ }
243
+
244
+ // Mark as initialized and emit ready event
245
+ this.initialized = true;
246
+ this.encryptionEnabled = true;
247
+ this.emit('cryptoReady', {
248
+ hasKeypair: !!this.keypair,
249
+ publicKey: this.getPublicKey()
250
+ });
251
+ }
252
+
148
253
  /**
149
254
  * Get the public key for sharing
150
255
  * @returns {string} The public key
@@ -198,6 +303,19 @@ export class CryptoManager extends EventEmitter {
198
303
  return false;
199
304
  }
200
305
 
306
+ // Check if we already have the same key for this peer to prevent duplicate key exchange events
307
+ const existingKey = this.peerKeys.get(peerId);
308
+ if (existingKey) {
309
+ // Compare both pub and epub keys to determine if this is actually a new key
310
+ const pubMatches = existingKey.pub === keyData.pub;
311
+ const epubMatches = existingKey.epub === keyData.epub;
312
+
313
+ if (pubMatches && epubMatches) {
314
+ // This is a duplicate key exchange - don't emit event or increment stats
315
+ return false;
316
+ }
317
+ }
318
+
201
319
  this.peerKeys.set(peerId, keyData);
202
320
  this.stats.keyExchanges++;
203
321
  this.emit('peerKeyAdded', { peerId, publicKey: keyData });
@@ -485,11 +603,16 @@ export class CryptoManager extends EventEmitter {
485
603
  * Start periodic cleanup of old nonces
486
604
  */
487
605
  startNonceCleanup() {
488
- setInterval(() => {
489
- // Remove old nonces (this is a simplified approach)
490
- // In a real implementation, you'd store nonces with timestamps
491
- if (this.messageNonces.size > 1000) {
492
- this.messageNonces.clear();
606
+ // Store the interval ID for cleanup
607
+ this.nonceCleanupInterval = setInterval(() => {
608
+ try {
609
+ // Remove old nonces (this is a simplified approach)
610
+ // In a real implementation, you'd store nonces with timestamps
611
+ if (this.messageNonces.size > 1000) {
612
+ this.messageNonces.clear();
613
+ }
614
+ } catch (error) {
615
+ console.error('Error during nonce cleanup:', error);
493
616
  }
494
617
  }, 60000); // Clean up every minute
495
618
  }
@@ -513,6 +636,12 @@ export class CryptoManager extends EventEmitter {
513
636
  * Clear all stored keys and reset state
514
637
  */
515
638
  reset() {
639
+ // Clear the nonce cleanup interval
640
+ if (this.nonceCleanupInterval) {
641
+ clearInterval(this.nonceCleanupInterval);
642
+ this.nonceCleanupInterval = null;
643
+ }
644
+
516
645
  this.keypair = null;
517
646
  this.peerKeys.clear();
518
647
  this.groupKeys.clear();
@@ -200,12 +200,5 @@ class DebugLogger {
200
200
  }
201
201
  }
202
202
 
203
- // Export for Node.js and browser environments
204
- if (typeof module !== 'undefined' && module.exports) {
205
- module.exports = DebugLogger;
206
- } else if (typeof window !== 'undefined') {
207
- window.DebugLogger = DebugLogger;
208
- }
209
-
210
203
  // ES6 export
211
204
  export default DebugLogger;