peerpigeon 0.1.1 → 1.0.2
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 +141 -1365
- package/cli.js +1382 -0
- package/dist/peerpigeon-browser.js +12450 -0
- package/dist/peerpigeon-browser.js.map +7 -0
- package/docs/API_DOCUMENTATION.md +1976 -0
- package/docs/BOOTSTRAP_HUBS.md +319 -0
- package/docs/CLI_README.md +371 -0
- package/docs/CUSTOM_HUB_NAMESPACES.md +182 -0
- package/docs/CUSTOM_NAMESPACE_IMPLEMENTATION.md +187 -0
- package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
- package/docs/HUB_QUICK_REF.md +108 -0
- package/docs/HUB_SCRIPTS.md +341 -0
- package/docs/HUB_SYSTEM.md +599 -0
- package/docs/MIGRATION_COMPLETE.md +93 -0
- package/docs/NETWORK_NAMESPACES.md +212 -0
- package/docs/PIGEONRTC_MIGRATION.md +280 -0
- package/docs/README.md +108 -0
- package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
- package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
- package/examples/bootstrap-hub-example.js +292 -0
- package/examples/browser/README.md +278 -0
- package/examples/browser/app.js +2426 -49
- package/examples/browser/index.html +481 -630
- package/examples/browser/minimal/README.md +55 -0
- package/examples/browser/minimal/index.html +75 -0
- package/examples/browser/minimal/minimal.js +234 -0
- package/examples/browser/styles.css +687 -1425
- package/examples/browser/test-bundle.html +35 -0
- package/examples/browser-2/index.html +30 -0
- package/examples/browser-2/package.json +21 -0
- package/examples/browser-2/src/App-simple.vue +21 -0
- package/examples/browser-2/src/App.vue +420 -0
- package/examples/browser-2/src/components/CryptoView.vue +1661 -0
- package/examples/browser-2/src/components/DHTView.vue +1281 -0
- package/examples/browser-2/src/components/DebugView.vue +1773 -0
- package/examples/browser-2/src/components/MediaView.vue +1048 -0
- package/examples/browser-2/src/components/MessagingView.vue +775 -0
- package/examples/browser-2/src/components/NetworkView.vue +930 -0
- package/examples/browser-2/src/components/StorageView.vue +1376 -0
- package/examples/browser-2/src/main.js +5 -0
- package/examples/browser-2/src/stores/peerpigeon.js +895 -0
- package/examples/browser-2/vite.config.js +6 -0
- package/examples/hub-example.js +189 -0
- package/examples/multi-hub-test.js +186 -0
- package/examples/node/README.md +2 -2
- package/examples/programmatic-namespace-example.js +108 -0
- package/examples/selective-streaming-demo.html +698 -0
- package/examples/standard-events-demo.js +126 -0
- package/index.js +7 -1
- package/package.json +34 -16
- package/server/index.js +1058 -98
- package/server/start.js +52 -0
- package/src/ConnectionManager.js +239 -225
- package/src/CryptoManager.js +147 -18
- package/src/DebugLogger.js +0 -7
- package/src/DistributedStorageManager.js +224 -205
- package/src/EnvironmentDetector.js +88 -4
- package/src/EventEmitter.js +79 -1
- package/src/EvictionManager.js +10 -9
- package/src/GossipManager.js +163 -11
- package/src/MediaManager.js +12 -2
- package/src/PeerConnection.js +343 -311
- package/src/PeerPigeonMesh.js +576 -135
- package/src/PigeonRTC-browser.js +247 -0
- package/src/SignalingClient.js +14 -243
- package/src/SignalingHandler.js +31 -10
- package/src/StorageManager.js +0 -39
- package/src/WebDHT-Simple.js +389 -0
- package/src/WebDHT.js +363 -1165
- package/src/browser-entry.js +58 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/crypto-test.html +0 -427
- package/examples/browser/ui-old.js +0 -1926
- package/examples/browser/ui.js +0 -3391
- package/websocket-server/README.md +0 -247
- package/websocket-server/server.js +0 -391
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-specific PigeonRTC implementation
|
|
3
|
+
* This is a simplified version that only includes browser-compatible code
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Simple RTCAdapter base class
|
|
7
|
+
export class RTCAdapter {
|
|
8
|
+
getRTCPeerConnection() {
|
|
9
|
+
throw new Error('getRTCPeerConnection must be implemented by adapter');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
getRTCSessionDescription() {
|
|
13
|
+
throw new Error('getRTCSessionDescription must be implemented by adapter');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
getRTCIceCandidate() {
|
|
17
|
+
throw new Error('getRTCIceCandidate must be implemented by adapter');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
getMediaStream() {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
isSupported() {
|
|
25
|
+
throw new Error('isSupported must be implemented by adapter');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
getName() {
|
|
29
|
+
throw new Error('getName must be implemented by adapter');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async initialize() {
|
|
33
|
+
// Default implementation does nothing
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async getUserMedia(_constraints) {
|
|
37
|
+
throw new Error('getUserMedia not supported by this adapter');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async getDisplayMedia(_constraints) {
|
|
41
|
+
throw new Error('getDisplayMedia not supported by this adapter');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Browser RTCAdapter
|
|
46
|
+
export class BrowserRTCAdapter extends RTCAdapter {
|
|
47
|
+
constructor() {
|
|
48
|
+
super();
|
|
49
|
+
this._checkSupport();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
_checkSupport() {
|
|
53
|
+
if (typeof window === 'undefined' || typeof navigator === 'undefined') {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
this.hasRTCPeerConnection = !!(
|
|
58
|
+
window.RTCPeerConnection ||
|
|
59
|
+
window.webkitRTCPeerConnection ||
|
|
60
|
+
window.mozRTCPeerConnection
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
this.hasGetUserMedia = !!(
|
|
64
|
+
navigator.mediaDevices?.getUserMedia ||
|
|
65
|
+
navigator.getUserMedia ||
|
|
66
|
+
navigator.webkitGetUserMedia ||
|
|
67
|
+
navigator.mozGetUserMedia
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
this.hasGetDisplayMedia = !!(
|
|
71
|
+
navigator.mediaDevices?.getDisplayMedia
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
getRTCPeerConnection() {
|
|
76
|
+
if (typeof window === 'undefined') {
|
|
77
|
+
throw new Error('BrowserRTCAdapter requires a browser environment');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return window.RTCPeerConnection ||
|
|
81
|
+
window.webkitRTCPeerConnection ||
|
|
82
|
+
window.mozRTCPeerConnection;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
getRTCSessionDescription() {
|
|
86
|
+
if (typeof window === 'undefined') {
|
|
87
|
+
throw new Error('BrowserRTCAdapter requires a browser environment');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return window.RTCSessionDescription ||
|
|
91
|
+
window.mozRTCSessionDescription;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
getRTCIceCandidate() {
|
|
95
|
+
if (typeof window === 'undefined') {
|
|
96
|
+
throw new Error('BrowserRTCAdapter requires a browser environment');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return window.RTCIceCandidate ||
|
|
100
|
+
window.mozRTCIceCandidate;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
getMediaStream() {
|
|
104
|
+
if (typeof window === 'undefined') {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return window.MediaStream || window.webkitMediaStream;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
isSupported() {
|
|
112
|
+
return typeof window !== 'undefined' && this.hasRTCPeerConnection;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
getName() {
|
|
116
|
+
return 'BrowserRTCAdapter';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async getUserMedia(constraints) {
|
|
120
|
+
if (typeof navigator === 'undefined') {
|
|
121
|
+
throw new Error('getUserMedia requires a browser environment');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (navigator.mediaDevices?.getUserMedia) {
|
|
125
|
+
return await navigator.mediaDevices.getUserMedia(constraints);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const getUserMedia = navigator.getUserMedia ||
|
|
129
|
+
navigator.webkitGetUserMedia ||
|
|
130
|
+
navigator.mozGetUserMedia;
|
|
131
|
+
|
|
132
|
+
if (!getUserMedia) {
|
|
133
|
+
throw new Error('getUserMedia is not supported in this browser');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
getUserMedia.call(navigator, constraints, resolve, reject);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async getDisplayMedia(constraints) {
|
|
142
|
+
if (typeof navigator === 'undefined') {
|
|
143
|
+
throw new Error('getDisplayMedia requires a browser environment');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (!navigator.mediaDevices?.getDisplayMedia) {
|
|
147
|
+
throw new Error('getDisplayMedia is not supported in this browser');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return await navigator.mediaDevices.getDisplayMedia(constraints);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Simplified PigeonRTC class for browser
|
|
155
|
+
export class PigeonRTC {
|
|
156
|
+
constructor(options = {}) {
|
|
157
|
+
this.adapter = options.adapter || null;
|
|
158
|
+
this.initialized = false;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async initialize(options = {}) {
|
|
162
|
+
if (this.initialized) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (options.adapter) {
|
|
167
|
+
this.adapter = options.adapter;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!this.adapter) {
|
|
171
|
+
this.adapter = new BrowserRTCAdapter();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
await this.adapter.initialize();
|
|
175
|
+
this.initialized = true;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
_ensureInitialized() {
|
|
179
|
+
if (!this.initialized || !this.adapter) {
|
|
180
|
+
throw new Error('PigeonRTC not initialized. Call initialize() first.');
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
getRTCPeerConnection() {
|
|
185
|
+
this._ensureInitialized();
|
|
186
|
+
return this.adapter.getRTCPeerConnection();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
getRTCSessionDescription() {
|
|
190
|
+
this._ensureInitialized();
|
|
191
|
+
return this.adapter.getRTCSessionDescription();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
getRTCIceCandidate() {
|
|
195
|
+
this._ensureInitialized();
|
|
196
|
+
return this.adapter.getRTCIceCandidate();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
getMediaStream() {
|
|
200
|
+
this._ensureInitialized();
|
|
201
|
+
return this.adapter.getMediaStream();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
createPeerConnection(config) {
|
|
205
|
+
this._ensureInitialized();
|
|
206
|
+
const RTCPeerConnection = this.adapter.getRTCPeerConnection();
|
|
207
|
+
return new RTCPeerConnection(config);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
createSessionDescription(init) {
|
|
211
|
+
this._ensureInitialized();
|
|
212
|
+
const RTCSessionDescription = this.adapter.getRTCSessionDescription();
|
|
213
|
+
return new RTCSessionDescription(init);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
createIceCandidate(init) {
|
|
217
|
+
this._ensureInitialized();
|
|
218
|
+
const RTCIceCandidate = this.adapter.getRTCIceCandidate();
|
|
219
|
+
return new RTCIceCandidate(init);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async getUserMedia(constraints) {
|
|
223
|
+
this._ensureInitialized();
|
|
224
|
+
return await this.adapter.getUserMedia(constraints);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async getDisplayMedia(constraints) {
|
|
228
|
+
this._ensureInitialized();
|
|
229
|
+
return await this.adapter.getDisplayMedia(constraints);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
isSupported() {
|
|
233
|
+
return this.adapter ? this.adapter.isSupported() : false;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
getAdapterName() {
|
|
237
|
+
return this.adapter ? this.adapter.getName() : 'None';
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export async function createPigeonRTC(options = {}) {
|
|
242
|
+
const rtc = new PigeonRTC(options);
|
|
243
|
+
await rtc.initialize(options);
|
|
244
|
+
return rtc;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export default createPigeonRTC;
|
package/src/SignalingClient.js
CHANGED
|
@@ -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
|
|
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(
|
|
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(
|
|
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
|
-
//
|
|
198
|
-
this.
|
|
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
|
}
|
package/src/SignalingHandler.js
CHANGED
|
@@ -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
|
-
//
|
|
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)}... (
|
|
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
|
|
package/src/StorageManager.js
CHANGED
|
@@ -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
|
}
|