peerpigeon 1.0.8 → 1.1.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.
- package/README.md +10 -2
- package/dist/peerpigeon-browser.js +60 -84
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/HUB_P2P_MESH.md +358 -0
- package/package.json +5 -1
- package/server/index.js +519 -264
- package/src/ConnectionManager.js +30 -54
- package/src/PeerConnection.js +7 -12
- package/src/PeerDiscovery.js +31 -30
- package/src/PeerPigeonMesh.js +10 -7
- package/src/SignalingHandler.js +5 -18
- package/docs/PEER_DISCOVERY_FIXES.md +0 -140
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
|
-
-
|
|
24
|
-
-
|
|
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
|
|
@@ -4397,37 +4397,34 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4397
4397
|
this.connectionAttempts.clear();
|
|
4398
4398
|
}
|
|
4399
4399
|
addDiscoveredPeer(peerId) {
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
if (wasKnown) {
|
|
4404
|
-
this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
|
|
4405
|
-
if (this.connectionAttempts.has(peerId)) {
|
|
4406
|
-
const attemptTime = this.connectionAttempts.get(peerId);
|
|
4407
|
-
if (now - attemptTime > 5e3) {
|
|
4408
|
-
this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
|
|
4409
|
-
this.connectionAttempts.delete(peerId);
|
|
4410
|
-
}
|
|
4411
|
-
}
|
|
4412
|
-
} else {
|
|
4413
|
-
this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
|
|
4414
|
-
this.emit("peerDiscovered", { peerId });
|
|
4400
|
+
if (this.discoveredPeers.has(peerId)) {
|
|
4401
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
4402
|
+
return;
|
|
4415
4403
|
}
|
|
4416
|
-
|
|
4404
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
4405
|
+
this.emit("peerDiscovered", { peerId });
|
|
4406
|
+
this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
|
|
4417
4407
|
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
4418
|
-
|
|
4419
|
-
|
|
4408
|
+
const alreadyAttempting = this.connectionAttempts.has(peerId);
|
|
4409
|
+
this.debug.log(`\u{1F50D} Connection decision for ${peerId.substring(0, 8)}...: autoDiscovery=${this.autoDiscovery}, shouldInitiate=${shouldInitiate}, alreadyAttempting=${alreadyAttempting}`);
|
|
4410
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyAttempting) {
|
|
4411
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
4420
4412
|
const canAccept = this.canAcceptMorePeers();
|
|
4413
|
+
this.debug.log(`Can accept more peers: ${canAccept}`);
|
|
4421
4414
|
if (canAccept) {
|
|
4422
|
-
this.debug.log(`\u{
|
|
4415
|
+
this.debug.log(`\u{1F680} Connecting to ${peerId.substring(0, 8)}...`);
|
|
4423
4416
|
this.emit("connectToPeer", { peerId });
|
|
4424
4417
|
} else {
|
|
4425
|
-
this.debug.log(
|
|
4418
|
+
this.debug.log(`\u274C Cannot accept more peers (at capacity)`);
|
|
4419
|
+
}
|
|
4420
|
+
} else {
|
|
4421
|
+
if (!this.autoDiscovery) {
|
|
4422
|
+
this.debug.log(`\u274C Auto-discovery disabled, not connecting to ${peerId.substring(0, 8)}...`);
|
|
4423
|
+
} else if (!shouldInitiate) {
|
|
4424
|
+
this.debug.log(`\u23F8\uFE0F Not initiating to ${peerId.substring(0, 8)}... (they should initiate to us)`);
|
|
4425
|
+
} else if (alreadyAttempting) {
|
|
4426
|
+
this.debug.log(`\u23F8\uFE0F Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
4426
4427
|
}
|
|
4427
|
-
} else if (alreadyTrying) {
|
|
4428
|
-
this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
4429
|
-
} else if (!shouldInitiate) {
|
|
4430
|
-
this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
|
|
4431
4428
|
}
|
|
4432
4429
|
this.scheduleMeshOptimization();
|
|
4433
4430
|
}
|
|
@@ -4456,6 +4453,9 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4456
4453
|
return distance;
|
|
4457
4454
|
}
|
|
4458
4455
|
shouldInitiateConnection(targetPeerId) {
|
|
4456
|
+
if (this.connectionAttempts.has(targetPeerId)) {
|
|
4457
|
+
return false;
|
|
4458
|
+
}
|
|
4459
4459
|
this.emit("checkCapacity");
|
|
4460
4460
|
const currentConnectionCount = this._currentConnectionCount || 0;
|
|
4461
4461
|
const lexicographicShouldInitiate = this.peerId > targetPeerId;
|
|
@@ -4826,18 +4826,19 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
4826
4826
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
4827
4827
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
4828
4828
|
if (hasSignaling || hasMeshConnectivity) {
|
|
4829
|
-
this.debug.log(`\
|
|
4829
|
+
this.debug.log(`\u274C ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
4830
4830
|
try {
|
|
4831
4831
|
this.restartIceViaSignaling().catch((error) => {
|
|
4832
4832
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4833
|
-
this.
|
|
4833
|
+
this.emit("disconnected", { peerId: this.peerId, reason: "ICE disconnected" });
|
|
4834
4834
|
});
|
|
4835
4835
|
} catch (error) {
|
|
4836
4836
|
this.debug.error("Failed to restart ICE after disconnection:", error);
|
|
4837
|
-
this.
|
|
4837
|
+
this.emit("disconnected", { peerId: this.peerId, reason: "ICE disconnected" });
|
|
4838
4838
|
}
|
|
4839
4839
|
} else {
|
|
4840
|
-
this.debug.log(`\
|
|
4840
|
+
this.debug.log(`\u274C ICE remained disconnected for ${this.peerId}, disconnecting`);
|
|
4841
|
+
this.emit("disconnected", { peerId: this.peerId, reason: "ICE disconnected" });
|
|
4841
4842
|
}
|
|
4842
4843
|
}
|
|
4843
4844
|
}, 5e3);
|
|
@@ -6079,30 +6080,12 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6079
6080
|
async connectToPeer(targetPeerId) {
|
|
6080
6081
|
this.debug.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
|
|
6081
6082
|
if (this.peers.has(targetPeerId)) {
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
if (status === "connected") {
|
|
6085
|
-
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
|
|
6086
|
-
return;
|
|
6087
|
-
}
|
|
6088
|
-
if (status === "connecting") {
|
|
6089
|
-
const connectionAge = Date.now() - (existingPeer.createdAt || 0);
|
|
6090
|
-
if (connectionAge < 1e4) {
|
|
6091
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1e3)}s)`);
|
|
6092
|
-
return;
|
|
6093
|
-
}
|
|
6094
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1e3)}s), will retry`);
|
|
6095
|
-
this.cleanupFailedConnection(targetPeerId);
|
|
6096
|
-
}
|
|
6083
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
|
|
6084
|
+
return;
|
|
6097
6085
|
}
|
|
6098
6086
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
6099
|
-
|
|
6100
|
-
|
|
6101
|
-
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1e3)}s ago)`);
|
|
6102
|
-
return;
|
|
6103
|
-
}
|
|
6104
|
-
this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1e3)}s ago), allowing retry`);
|
|
6105
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
6087
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
|
|
6088
|
+
return;
|
|
6106
6089
|
}
|
|
6107
6090
|
const shouldBeInitiator = this.mesh.peerId > targetPeerId;
|
|
6108
6091
|
if (!shouldBeInitiator) {
|
|
@@ -6118,22 +6101,17 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6118
6101
|
const attempts = this.connectionAttempts.get(targetPeerId) || 0;
|
|
6119
6102
|
if (attempts > 0) {
|
|
6120
6103
|
const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
|
|
6121
|
-
const
|
|
6122
|
-
const retryDelay =
|
|
6104
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
6105
|
+
const retryDelay = connectedCount === 0 ? 200 : this.retryDelay;
|
|
6123
6106
|
if (now - lastAttempt < retryDelay) {
|
|
6124
6107
|
const remaining = retryDelay - (now - lastAttempt);
|
|
6125
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}
|
|
6108
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1e3)}s remaining, isolated: ${connectedCount === 0})`);
|
|
6126
6109
|
return;
|
|
6127
6110
|
}
|
|
6128
6111
|
}
|
|
6129
|
-
|
|
6130
|
-
const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
|
|
6131
|
-
if (attempts >= maxAttempts) {
|
|
6132
|
-
this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
|
|
6112
|
+
if (attempts >= this.maxConnectionAttempts) {
|
|
6133
6113
|
this.mesh.emit("statusChanged", { type: "warning", message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
6134
|
-
this.
|
|
6135
|
-
this.lastConnectionAttempt.delete(targetPeerId);
|
|
6136
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
6114
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
|
|
6137
6115
|
return;
|
|
6138
6116
|
}
|
|
6139
6117
|
this.debug.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
|
|
@@ -6368,15 +6346,16 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6368
6346
|
}
|
|
6369
6347
|
canAcceptMorePeers() {
|
|
6370
6348
|
const connectedCount = this.getConnectedPeerCount();
|
|
6371
|
-
if (connectedCount < this.mesh.maxPeers) {
|
|
6372
|
-
return true;
|
|
6373
|
-
}
|
|
6374
|
-
const stalePeerCount = this.getStalePeerCount();
|
|
6375
6349
|
const totalPeerCount = this.peers.size;
|
|
6376
|
-
if (
|
|
6377
|
-
this.debug.log(`At capacity
|
|
6378
|
-
return
|
|
6350
|
+
if (connectedCount >= this.mesh.maxPeers) {
|
|
6351
|
+
this.debug.log(`At or over capacity: ${connectedCount}/${this.mesh.maxPeers} connected, rejecting new connections`);
|
|
6352
|
+
return false;
|
|
6353
|
+
}
|
|
6354
|
+
if (totalPeerCount >= this.mesh.maxPeers) {
|
|
6355
|
+
this.debug.log(`Total peer count at capacity: ${totalPeerCount}/${this.mesh.maxPeers}, rejecting new connections`);
|
|
6356
|
+
return false;
|
|
6379
6357
|
}
|
|
6358
|
+
return true;
|
|
6380
6359
|
this.debug.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
|
|
6381
6360
|
return false;
|
|
6382
6361
|
}
|
|
@@ -6641,6 +6620,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
6641
6620
|
this.debug.warn("Received invalid message from", fromPeerId?.substring(0, 8));
|
|
6642
6621
|
return;
|
|
6643
6622
|
}
|
|
6623
|
+
this.mesh.emit("messageReceived", {
|
|
6624
|
+
from: fromPeerId,
|
|
6625
|
+
data: message,
|
|
6626
|
+
timestamp: Date.now()
|
|
6627
|
+
});
|
|
6644
6628
|
if (message.type === "binary" && message.data instanceof Uint8Array) {
|
|
6645
6629
|
this.debug.log(`\u{1F4E6} Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
|
6646
6630
|
this.mesh.emit("binaryMessageReceived", {
|
|
@@ -7064,22 +7048,11 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
7064
7048
|
}
|
|
7065
7049
|
}
|
|
7066
7050
|
handlePeerAnnouncement(fromPeerId) {
|
|
7067
|
-
if (this.
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
|
|
7071
|
-
this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
|
|
7072
|
-
return;
|
|
7073
|
-
}
|
|
7074
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
|
|
7075
|
-
}
|
|
7076
|
-
const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
|
|
7077
|
-
if (wasKnown) {
|
|
7078
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
|
|
7079
|
-
} else {
|
|
7080
|
-
this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
|
|
7051
|
+
if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
|
|
7052
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
|
|
7053
|
+
return;
|
|
7081
7054
|
}
|
|
7082
|
-
this.mesh.emit("statusChanged", { type: "info", message: `Peer ${fromPeerId.substring(0, 8)}...
|
|
7055
|
+
this.mesh.emit("statusChanged", { type: "info", message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
|
|
7083
7056
|
this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
7084
7057
|
this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
7085
7058
|
this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map((p) => p.substring(0, 8)).join(", ")}`);
|
|
@@ -11541,9 +11514,10 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11541
11514
|
}
|
|
11542
11515
|
if (environmentDetector.isBrowser) {
|
|
11543
11516
|
try {
|
|
11517
|
+
const disableLocalhostMedia = typeof window !== "undefined" && window.DISABLE_LOCALHOST_MEDIA_REQUEST;
|
|
11544
11518
|
const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "";
|
|
11545
|
-
if (isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
11546
|
-
this.debug.log("\u{1F3A4} Requesting media permissions for localhost WebRTC...");
|
|
11519
|
+
if (!disableLocalhostMedia && isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
11520
|
+
this.debug.log("\u{1F3A4} Requesting media permissions for localhost WebRTC (not disabled)...");
|
|
11547
11521
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
11548
11522
|
audio: true,
|
|
11549
11523
|
video: false
|
|
@@ -11555,6 +11529,8 @@ ${b64.match(/.{1,64}/g).join("\n")}
|
|
|
11555
11529
|
stream.getTracks().forEach((track) => track.stop());
|
|
11556
11530
|
this.debug.log("\u2705 Media permissions granted - localhost connections will work");
|
|
11557
11531
|
}
|
|
11532
|
+
} else if (disableLocalhostMedia) {
|
|
11533
|
+
this.debug.log("\u{1F6AB} Skipping localhost media permission request (DISABLE_LOCALHOST_MEDIA_REQUEST flag set)");
|
|
11558
11534
|
}
|
|
11559
11535
|
} catch (error) {
|
|
11560
11536
|
this.debug.warn("Could not request media permissions:", error.message);
|