peerpigeon 1.0.9 → 1.1.1

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 CHANGED
@@ -20,8 +20,9 @@ PeerPigeon is a production-ready library for building decentralized applications
20
20
  - **🗄️ Distributed Storage** - Encrypted, CRDT-enabled storage across the mesh
21
21
  - **🎥 Selective Streaming** - Efficient audio/video streaming with bandwidth management
22
22
  - **📦 Binary Messages** - Native support for efficient binary data transfer (Uint8Array/ArrayBuffer)
23
- - **� Stream API** - Transfer large files with ReadableStream/WritableStream (memory-efficient, backpressure handling)
24
- - **�🏢 Hub System** - Connect multiple signaling servers for global peer discovery
23
+ - **🌊 Stream API** - Transfer large files with ReadableStream/WritableStream (memory-efficient, backpressure handling)
24
+ - **🏢 Hub System** - Connect multiple signaling servers for global peer discovery
25
+ - **🔗 Hub P2P Mesh** - Hubs form WebRTC mesh with XOR routing, auto-migrate from WebSocket to P2P
25
26
  - **🔐 End-to-End Encryption** - Built-in crypto for secure communication
26
27
  - **💰 Cost Optimized** - Smart routing reduces server costs by ~95%
27
28
  - **📱 Multi-Platform** - Browser, Node.js, NativeScript support
@@ -197,9 +198,16 @@ const hub2 = new PeerPigeonServer({
197
198
  });
198
199
  await hub2.start();
199
200
 
201
+ // Hubs automatically form P2P mesh with XOR routing
202
+ // WebSocket connections are closed once P2P mesh is established
203
+ // Clients connect via WebSocket, hub-to-hub uses P2P for efficiency
204
+
200
205
  // Peers on hub2 can discover peers on hub1!
201
206
  ```
202
207
 
208
+ **New in v1.1**: Hubs now form a true P2P mesh network using WebRTC with XOR-based routing. WebSocket connections between hubs are automatically closed once the P2P mesh is established, significantly reducing server load. See [docs/HUB_P2P_MESH.md](docs/HUB_P2P_MESH.md) for details.
209
+ ```
210
+
203
211
  ## 📖 Documentation
204
212
 
205
213
  ### Core Guides
@@ -4224,15 +4224,16 @@ ${b64.match(/.{1,64}/g).join("\n")}
4224
4224
  };
4225
4225
  this.websocket.onclose = (event) => {
4226
4226
  clearTimeout(connectTimeout);
4227
+ const wasConnected = this.connected;
4227
4228
  this.connected = false;
4228
4229
  this.connectionPromise = null;
4230
+ this.isReconnecting = false;
4229
4231
  this.debug.log("WebSocket closed:", event.code, event.reason);
4230
- this.emit("disconnected");
4232
+ if (wasConnected) {
4233
+ this.emit("disconnected");
4234
+ }
4231
4235
  if (!this.deliberateDisconnect) {
4232
- this.emit("statusChanged", { type: "warning", message: "WebSocket connection lost - reconnecting..." });
4233
- if (!this.isReconnecting) {
4234
- this.attemptReconnect();
4235
- }
4236
+ this.attemptReconnect();
4236
4237
  } else {
4237
4238
  this.deliberateDisconnect = false;
4238
4239
  }
@@ -4274,6 +4275,14 @@ ${b64.match(/.{1,64}/g).join("\n")}
4274
4275
  this.debug.log("Max reconnection attempts reached, using exponential backoff");
4275
4276
  const baseExtendedDelay = hasHealthyPeers ? 6e5 : this.maxReconnectDelay * 2;
4276
4277
  const extendedDelay = Math.min(baseExtendedDelay, 6e5);
4278
+ this.emit("statusChanged", {
4279
+ type: "reconnecting",
4280
+ message: `Max attempts reached. Retrying in ${Math.round(extendedDelay / 1e3)}s...`,
4281
+ delay: extendedDelay,
4282
+ attempt: this.reconnectAttempts,
4283
+ maxAttempts: this.maxReconnectAttempts,
4284
+ extendedBackoff: true
4285
+ });
4277
4286
  this.reconnectTimeout = setTimeout(() => {
4278
4287
  this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2);
4279
4288
  this.attemptReconnect();
@@ -4286,18 +4295,21 @@ ${b64.match(/.{1,64}/g).join("\n")}
4286
4295
  const delayMultiplier = hasHealthyPeers ? 3 : 1;
4287
4296
  const delay = Math.min(baseDelay * delayMultiplier, hasHealthyPeers ? 3e5 : this.maxReconnectDelay);
4288
4297
  this.debug.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts}, healthy peers: ${hasHealthyPeers})`);
4298
+ this.emit("statusChanged", {
4299
+ type: "reconnecting",
4300
+ message: `Reconnecting in ${Math.round(delay / 1e3)}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`,
4301
+ delay,
4302
+ attempt: this.reconnectAttempts,
4303
+ maxAttempts: this.maxReconnectAttempts
4304
+ });
4289
4305
  this.reconnectTimeout = setTimeout(async () => {
4290
4306
  if (!this.connected && this.signalingUrl) {
4291
4307
  try {
4292
4308
  await this.connect(this.signalingUrl);
4293
4309
  this.emit("statusChanged", { type: "info", message: "WebSocket reconnected successfully" });
4294
4310
  } catch (error) {
4295
- this.debug.error("Reconnection failed:", error);
4296
- this.isReconnecting = false;
4297
- this.attemptReconnect();
4311
+ this.debug.error("Reconnection attempt failed:", error);
4298
4312
  }
4299
- } else {
4300
- this.isReconnecting = false;
4301
4313
  }
4302
4314
  }, delay);
4303
4315
  }
@@ -4393,6 +4405,10 @@ ${b64.match(/.{1,64}/g).join("\n")}
4393
4405
  clearTimeout(this.meshOptimizationTimeout);
4394
4406
  this.meshOptimizationTimeout = null;
4395
4407
  }
4408
+ }
4409
+ // Full cleanup method for deliberate disconnects
4410
+ cleanup() {
4411
+ this.stop();
4396
4412
  this.discoveredPeers.clear();
4397
4413
  this.connectionAttempts.clear();
4398
4414
  }
@@ -4404,12 +4420,26 @@ ${b64.match(/.{1,64}/g).join("\n")}
4404
4420
  this.discoveredPeers.set(peerId, Date.now());
4405
4421
  this.emit("peerDiscovered", { peerId });
4406
4422
  this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
4407
- if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
4423
+ const shouldInitiate = this.shouldInitiateConnection(peerId);
4424
+ const alreadyAttempting = this.connectionAttempts.has(peerId);
4425
+ this.debug.log(`\u{1F50D} Connection decision for ${peerId.substring(0, 8)}...: autoDiscovery=${this.autoDiscovery}, shouldInitiate=${shouldInitiate}, alreadyAttempting=${alreadyAttempting}`);
4426
+ if (this.autoDiscovery && shouldInitiate && !alreadyAttempting) {
4408
4427
  this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
4409
4428
  const canAccept = this.canAcceptMorePeers();
4429
+ this.debug.log(`Can accept more peers: ${canAccept}`);
4410
4430
  if (canAccept) {
4411
- this.debug.log(`Connecting to ${peerId.substring(0, 8)}...`);
4431
+ this.debug.log(`\u{1F680} Connecting to ${peerId.substring(0, 8)}...`);
4412
4432
  this.emit("connectToPeer", { peerId });
4433
+ } else {
4434
+ this.debug.log(`\u274C Cannot accept more peers (at capacity)`);
4435
+ }
4436
+ } else {
4437
+ if (!this.autoDiscovery) {
4438
+ this.debug.log(`\u274C Auto-discovery disabled, not connecting to ${peerId.substring(0, 8)}...`);
4439
+ } else if (!shouldInitiate) {
4440
+ this.debug.log(`\u23F8\uFE0F Not initiating to ${peerId.substring(0, 8)}... (they should initiate to us)`);
4441
+ } else if (alreadyAttempting) {
4442
+ this.debug.log(`\u23F8\uFE0F Already attempting connection to ${peerId.substring(0, 8)}...`);
4413
4443
  }
4414
4444
  }
4415
4445
  this.scheduleMeshOptimization();
@@ -6075,8 +6105,14 @@ ${b64.match(/.{1,64}/g).join("\n")}
6075
6105
  }
6076
6106
  const shouldBeInitiator = this.mesh.peerId > targetPeerId;
6077
6107
  if (!shouldBeInitiator) {
6078
- this.debug.log(`\u{1F504} INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is smaller)`);
6079
- return;
6108
+ const connectedCount = this.getConnectedPeerCount();
6109
+ const floor = this.mesh.connectivityFloor || 0;
6110
+ if (connectedCount < floor) {
6111
+ this.debug.log(`\u{1F504} INITIATOR OVERRIDE: Forcing initiation to ${targetPeerId.substring(0, 8)}... (connected ${connectedCount} < floor ${floor})`);
6112
+ } else {
6113
+ this.debug.log(`\u{1F504} INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID smaller, connected ${connectedCount} >= floor ${floor})`);
6114
+ return;
6115
+ }
6080
6116
  }
6081
6117
  this.debug.log(`\u{1F504} INITIATOR LOGIC: Becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is greater)`);
6082
6118
  if (!this.mesh.canAcceptMorePeers()) {
@@ -6137,10 +6173,44 @@ ${b64.match(/.{1,64}/g).join("\n")}
6137
6173
  this.mesh.emit("statusChanged", { type: "info", message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
6138
6174
  } catch (error) {
6139
6175
  this.debug.error("Failed to connect to peer:", error);
6140
- this.mesh.emit("statusChanged", { type: "error", message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
6176
+ const isConnectionTimeout = error.message?.includes("timeout");
6177
+ if (!isConnectionTimeout) {
6178
+ this.mesh.emit("statusChanged", {
6179
+ type: "error",
6180
+ message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}`
6181
+ });
6182
+ }
6141
6183
  this.cleanupFailedConnection(targetPeerId);
6142
6184
  }
6143
6185
  }
6186
+ /**
6187
+ * Force connection attempt ignoring standard initiator lexicographic rule (used for connectivity floor).
6188
+ */
6189
+ async connectToPeerOverride(targetPeerId) {
6190
+ if (this.peers.has(targetPeerId)) return;
6191
+ const connectedCount = this.getConnectedPeerCount();
6192
+ const floor = this.mesh.connectivityFloor || 0;
6193
+ if (connectedCount >= floor) return;
6194
+ this.debug.log(`\u26A1 OVERRIDE CONNECT: initiating to ${targetPeerId.substring(0, 8)}... (connected ${connectedCount} < floor ${floor})`);
6195
+ this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
6196
+ const options = {
6197
+ localStream: null,
6198
+ enableAudio: true,
6199
+ enableVideo: true
6200
+ };
6201
+ const peerConnection = new PeerConnection(targetPeerId, true, options);
6202
+ this.setupPeerConnectionHandlers(peerConnection);
6203
+ this.peers.set(targetPeerId, peerConnection);
6204
+ try {
6205
+ await peerConnection.createConnection();
6206
+ const offer = await peerConnection.createOffer();
6207
+ await this.mesh.sendSignalingMessage({ type: "offer", data: offer }, targetPeerId);
6208
+ } catch (e) {
6209
+ this.debug.warn(`Override connection failed to ${targetPeerId.substring(0, 8)}...: ${e.message}`);
6210
+ this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
6211
+ this.peers.delete(targetPeerId);
6212
+ }
6213
+ }
6144
6214
  cleanupFailedConnection(peerId) {
6145
6215
  this.debug.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
6146
6216
  let peerRemoved = false;
@@ -6332,15 +6402,16 @@ ${b64.match(/.{1,64}/g).join("\n")}
6332
6402
  }
6333
6403
  canAcceptMorePeers() {
6334
6404
  const connectedCount = this.getConnectedPeerCount();
6335
- if (connectedCount < this.mesh.maxPeers) {
6336
- return true;
6337
- }
6338
- const stalePeerCount = this.getStalePeerCount();
6339
6405
  const totalPeerCount = this.peers.size;
6340
- if (stalePeerCount > 0 && totalPeerCount >= this.mesh.maxPeers) {
6341
- this.debug.log(`At capacity (${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) but have ${stalePeerCount} stale peers that can be evicted`);
6342
- return true;
6406
+ if (connectedCount >= this.mesh.maxPeers) {
6407
+ this.debug.log(`At or over capacity: ${connectedCount}/${this.mesh.maxPeers} connected, rejecting new connections`);
6408
+ return false;
6343
6409
  }
6410
+ if (totalPeerCount >= this.mesh.maxPeers) {
6411
+ this.debug.log(`Total peer count at capacity: ${totalPeerCount}/${this.mesh.maxPeers}, rejecting new connections`);
6412
+ return false;
6413
+ }
6414
+ return true;
6344
6415
  this.debug.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
6345
6416
  return false;
6346
6417
  }
@@ -6605,6 +6676,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
6605
6676
  this.debug.warn("Received invalid message from", fromPeerId?.substring(0, 8));
6606
6677
  return;
6607
6678
  }
6679
+ this.mesh.emit("messageReceived", {
6680
+ from: fromPeerId,
6681
+ data: message,
6682
+ timestamp: Date.now()
6683
+ });
6608
6684
  if (message.type === "binary" && message.data instanceof Uint8Array) {
6609
6685
  this.debug.log(`\u{1F4E6} Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
6610
6686
  this.mesh.emit("binaryMessageReceived", {
@@ -7958,7 +8034,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
7958
8034
  this.seenMessages = /* @__PURE__ */ new Map();
7959
8035
  this.messageHistory = /* @__PURE__ */ new Map();
7960
8036
  this.processedKeyExchanges = /* @__PURE__ */ new Map();
7961
- this.maxTTL = 10;
8037
+ this.maxTTL = 40;
7962
8038
  this.messageExpiryTime = 5 * 60 * 1e3;
7963
8039
  this.cleanupInterval = 60 * 1e3;
7964
8040
  this.cleanupTimer = null;
@@ -8012,6 +8088,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
8012
8088
  }
8013
8089
  return messageId;
8014
8090
  }
8091
+ /**
8092
+ * Attempt adaptive resend of recent broadcasts to peers that connected
8093
+ * after initial propagation window.
8094
+ */
8095
+ // (Rollback) attemptAdaptiveResends removed
8015
8096
  /**
8016
8097
  * Send a direct message to a specific peer using gossip routing (DM)
8017
8098
  * @param {string} targetPeerId - The destination peer's ID
@@ -11284,6 +11365,8 @@ ${b64.match(/.{1,64}/g).join("\n")}
11284
11365
  this.originalNetworkName = this.networkName;
11285
11366
  this.maxPeers = options.maxPeers !== void 0 ? options.maxPeers : 3;
11286
11367
  this.minPeers = options.minPeers !== void 0 ? options.minPeers : 2;
11368
+ const defaultFloor = Math.min(3, this.maxPeers ?? 3);
11369
+ this.connectivityFloor = options.connectivityFloor !== void 0 ? options.connectivityFloor : defaultFloor;
11287
11370
  this.autoConnect = options.autoConnect !== false;
11288
11371
  this.autoDiscovery = options.autoDiscovery !== false;
11289
11372
  this.evictionStrategy = options.evictionStrategy !== false;
@@ -11314,6 +11397,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
11314
11397
  this.setupManagerEventHandlers();
11315
11398
  this.cleanupManager.setupUnloadHandlers();
11316
11399
  this.storageManager.loadSignalingUrlFromStorage();
11400
+ this._connectivityEnforcementTimer = null;
11317
11401
  }
11318
11402
  setupManagerEventHandlers() {
11319
11403
  this.connectionManager.addEventListener("peersUpdated", () => {
@@ -11494,9 +11578,10 @@ ${b64.match(/.{1,64}/g).join("\n")}
11494
11578
  }
11495
11579
  if (environmentDetector.isBrowser) {
11496
11580
  try {
11581
+ const disableLocalhostMedia = typeof window !== "undefined" && window.DISABLE_LOCALHOST_MEDIA_REQUEST;
11497
11582
  const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "";
11498
- if (isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
11499
- this.debug.log("\u{1F3A4} Requesting media permissions for localhost WebRTC...");
11583
+ if (!disableLocalhostMedia && isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
11584
+ this.debug.log("\u{1F3A4} Requesting media permissions for localhost WebRTC (not disabled)...");
11500
11585
  const stream = await navigator.mediaDevices.getUserMedia({
11501
11586
  audio: true,
11502
11587
  video: false
@@ -11508,6 +11593,8 @@ ${b64.match(/.{1,64}/g).join("\n")}
11508
11593
  stream.getTracks().forEach((track) => track.stop());
11509
11594
  this.debug.log("\u2705 Media permissions granted - localhost connections will work");
11510
11595
  }
11596
+ } else if (disableLocalhostMedia) {
11597
+ this.debug.log("\u{1F6AB} Skipping localhost media permission request (DISABLE_LOCALHOST_MEDIA_REQUEST flag set)");
11511
11598
  }
11512
11599
  } catch (error) {
11513
11600
  this.debug.warn("Could not request media permissions:", error.message);
@@ -11548,6 +11635,7 @@ ${b64.match(/.{1,64}/g).join("\n")}
11548
11635
  maxPeers: this.maxPeers
11549
11636
  });
11550
11637
  this.setupDiscoveryHandlers();
11638
+ this.startConnectivityEnforcement();
11551
11639
  if (this.cryptoManager) {
11552
11640
  try {
11553
11641
  this.debug.log("\u{1F510} Initializing crypto manager with automatic key persistence...");
@@ -11653,7 +11741,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
11653
11741
  this.signalingClient.disconnect();
11654
11742
  }
11655
11743
  if (this.peerDiscovery) {
11656
- this.peerDiscovery.stop();
11744
+ this.peerDiscovery.cleanup();
11745
+ }
11746
+ if (this._connectivityEnforcementTimer) {
11747
+ clearInterval(this._connectivityEnforcementTimer);
11748
+ this._connectivityEnforcementTimer = null;
11657
11749
  }
11658
11750
  this.connectionManager.disconnectAllPeers();
11659
11751
  this.connectionManager.cleanup();
@@ -11662,6 +11754,35 @@ ${b64.match(/.{1,64}/g).join("\n")}
11662
11754
  this.gossipManager.cleanup();
11663
11755
  this.emit("statusChanged", { type: "disconnected" });
11664
11756
  }
11757
+ /**
11758
+ * Periodically attempt extra connections for under-connected peers until reaching connectivityFloor.
11759
+ */
11760
+ startConnectivityEnforcement() {
11761
+ if (this._connectivityEnforcementTimer) return;
11762
+ const intervalMs = 4e3;
11763
+ this._connectivityEnforcementTimer = setInterval(() => {
11764
+ if (!this.connected || !this.peerDiscovery) return;
11765
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
11766
+ if (connectedCount >= this.connectivityFloor) return;
11767
+ const discovered = this.peerDiscovery.getDiscoveredPeers().map((p) => p.peerId);
11768
+ const notConnected = discovered.filter(
11769
+ (pid) => !this.connectionManager.hasPeer(pid) && !this.peerDiscovery.isAttemptingConnection(pid)
11770
+ );
11771
+ if (notConnected.length === 0) return;
11772
+ const prioritized = notConnected.sort((a, b) => {
11773
+ const distA = this.peerDiscovery.calculateXorDistance(this.peerId, a);
11774
+ const distB = this.peerDiscovery.calculateXorDistance(this.peerId, b);
11775
+ return distA < distB ? -1 : 1;
11776
+ });
11777
+ const needed = this.connectivityFloor - connectedCount;
11778
+ const attemptLimit = Math.min(prioritized.length, Math.max(1, needed));
11779
+ const batch = prioritized.slice(0, attemptLimit);
11780
+ batch.forEach((pid) => {
11781
+ this.debug.log(`\u{1F527} CONNECTIVITY FLOOR (${connectedCount}/${this.connectivityFloor}) attempting extra connection to ${pid.substring(0, 8)}...`);
11782
+ this.connectionManager.connectToPeer(pid);
11783
+ });
11784
+ }, intervalMs);
11785
+ }
11665
11786
  // Configuration methods
11666
11787
  setMaxPeers(maxPeers) {
11667
11788
  this.maxPeers = Math.max(1, Math.min(50, maxPeers));