@hiroosy/baileys-lite 0.3.7 → 0.3.8
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/package.json +1 -1
- package/src/voip/app-data/WaAppDataStream.js +0 -39
- package/src/voip/call/WaCallManager.js +4 -32
- package/src/voip/call/WaCallMediaSession.js +35 -309
- package/src/voip/index.js +75 -18
- package/src/voip/media/WaAudioEngine.js +150 -122
- package/src/voip/media/WaVideoEngine.js +7 -22
- package/src/voip/media/mlow-codec.js +7 -141
- package/src/voip/relay/WaManualRelay.js +91 -94
- package/src/voip/relay/dtls/handshake.js +4 -42
- package/src/voip/relay/sctp/association.js +89 -54
- package/src/voip/relay/stun.js +6 -6
- package/src/voip/types.js +1 -1
- package/src/voip/voipClient.js +3 -1
|
@@ -5,8 +5,7 @@ import { PreNegotiatedDataChannel } from './datachannel/pre-negotiated.js';
|
|
|
5
5
|
import { createNoopLogger } from '../shim/core.js';
|
|
6
6
|
import { toError } from '../shim/util.js';
|
|
7
7
|
import { TEXT_ENCODER, toArrayBuffer } from '../bytes.js';
|
|
8
|
-
import { buildAllocateForRelay, buildBindingRequest, buildRelayBindingSuccess,
|
|
9
|
-
import { randomBytes } from 'node:crypto';
|
|
8
|
+
import { buildAllocateForRelay, buildBindingRequest, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, parseStunResponse } from './stun.js';
|
|
10
9
|
import { PayloadType } from '../types.js';
|
|
11
10
|
|
|
12
11
|
const CONFIG = {
|
|
@@ -47,12 +46,14 @@ export class WaManualRelay extends EventEmitter {
|
|
|
47
46
|
audioSsrc = 0;
|
|
48
47
|
videoSsrc = 0;
|
|
49
48
|
subscriptionSsrc = 0;
|
|
50
|
-
|
|
49
|
+
selfPid = 0;
|
|
50
|
+
peerPid = 0;
|
|
51
51
|
rxStun = { bindReq: 0, bindAnswered: 0, allocOk: 0, allocErr: 0, pong: 0, other: 0 };
|
|
52
52
|
configuring = false;
|
|
53
53
|
globalBuffer = [];
|
|
54
54
|
globalBufferedBytes = 0;
|
|
55
55
|
stats = { sent: 0, received: 0, connected: 0 };
|
|
56
|
+
retrySchedule = [1000, 2000, 4000];
|
|
56
57
|
|
|
57
58
|
constructor(options = {}) {
|
|
58
59
|
super();
|
|
@@ -61,22 +62,11 @@ export class WaManualRelay extends EventEmitter {
|
|
|
61
62
|
|
|
62
63
|
setSsrc(ssrc) {
|
|
63
64
|
this.audioSsrc = ssrc;
|
|
64
|
-
this.logger.debug('manual relay ssrc set', { ssrc: `0x${ssrc.toString(16).padStart(8, '0')}` });
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
for (let i = 6; i < 9; i++) {
|
|
71
|
-
for (let attempt = 0; attempt < 64; attempt++) {
|
|
72
|
-
const candidate = randomBytes(4).readUInt32LE(0);
|
|
73
|
-
if (candidate === 0 || used.has(candidate)) continue;
|
|
74
|
-
out[i] = candidate;
|
|
75
|
-
used.add(candidate);
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
this.streamSsrcs = out;
|
|
67
|
+
setParticipantIds(selfPid, peerPid) {
|
|
68
|
+
this.selfPid = selfPid ?? 0;
|
|
69
|
+
this.peerPid = peerPid ?? 0;
|
|
80
70
|
}
|
|
81
71
|
|
|
82
72
|
getRxStunStats() {
|
|
@@ -85,14 +75,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
85
75
|
|
|
86
76
|
setVideoSsrc(ssrc) {
|
|
87
77
|
this.videoSsrc = ssrc;
|
|
88
|
-
this.logger.debug('manual relay video ssrc set', { ssrc: `0x${ssrc.toString(16).padStart(8, '0')}` });
|
|
89
78
|
}
|
|
90
79
|
|
|
91
80
|
setSubscriptionSsrc(ssrc) {
|
|
92
81
|
this.subscriptionSsrc = ssrc;
|
|
93
|
-
this.logger.debug('manual relay subscription ssrc set', {
|
|
94
|
-
ssrc: `0x${ssrc.toString(16).padStart(8, '0')}`
|
|
95
|
-
});
|
|
96
82
|
}
|
|
97
83
|
|
|
98
84
|
makeConnectionId(ip, port, authTokenId) {
|
|
@@ -101,7 +87,6 @@ export class WaManualRelay extends EventEmitter {
|
|
|
101
87
|
}
|
|
102
88
|
|
|
103
89
|
async configureRelays(relays) {
|
|
104
|
-
this.logger.debug('manual relay configuring relays', { count: relays.length });
|
|
105
90
|
this.configuring = true;
|
|
106
91
|
for (const relay of relays) {
|
|
107
92
|
const port = relay.port || CONFIG.TRUE_WEB_CLIENT_RELAY_PORT;
|
|
@@ -128,7 +113,6 @@ export class WaManualRelay extends EventEmitter {
|
|
|
128
113
|
}
|
|
129
114
|
}
|
|
130
115
|
await Promise.all(connectionPromises);
|
|
131
|
-
this.logger.debug('manual relay configuration done', { connected: this.stats.connected });
|
|
132
116
|
this.configuring = false;
|
|
133
117
|
if (this.globalBuffer.length > 0) {
|
|
134
118
|
for (const item of this.globalBuffer) this.sendToRelay(item.ip, item.port, item.data);
|
|
@@ -152,6 +136,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
152
136
|
connectionTimeout: null,
|
|
153
137
|
keepaliveTimer: null,
|
|
154
138
|
iceConsentTimer: null,
|
|
139
|
+
retryTimer: null,
|
|
140
|
+
retryCount: 0,
|
|
141
|
+
recovering: false,
|
|
142
|
+
lastInboundAt: 0,
|
|
155
143
|
localUfrag: randomUfrag(),
|
|
156
144
|
stats: { sentPackets: 0, receivedPackets: 0, sentBytes: 0, receivedBytes: 0 }
|
|
157
145
|
};
|
|
@@ -169,12 +157,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
169
157
|
conn.connectPromise = promise;
|
|
170
158
|
try {
|
|
171
159
|
await promise;
|
|
172
|
-
} catch
|
|
173
|
-
this.logger.debug('manual relay connection attempt failed', {
|
|
174
|
-
connectionId: relayInfo.id,
|
|
175
|
-
message: toError(err).message
|
|
176
|
-
});
|
|
177
|
-
} finally {
|
|
160
|
+
} catch { } finally {
|
|
178
161
|
conn.connectPromise = null;
|
|
179
162
|
}
|
|
180
163
|
};
|
|
@@ -199,11 +182,6 @@ export class WaManualRelay extends EventEmitter {
|
|
|
199
182
|
settled = true;
|
|
200
183
|
clearTimeout(timer);
|
|
201
184
|
socket.removeListener('message', onMessage);
|
|
202
|
-
this.logger.debug('ice binding response', {
|
|
203
|
-
connectionId: relayInfo.id,
|
|
204
|
-
class: info.stunClass,
|
|
205
|
-
errorCode: info.errorCode
|
|
206
|
-
});
|
|
207
185
|
resolve(info.isSuccess);
|
|
208
186
|
}
|
|
209
187
|
};
|
|
@@ -214,18 +192,13 @@ export class WaManualRelay extends EventEmitter {
|
|
|
214
192
|
if (attempt >= CONFIG.ICE_BINDING_TIMEOUTS_MS.length) {
|
|
215
193
|
settled = true;
|
|
216
194
|
socket.removeListener('message', onMessage);
|
|
217
|
-
this.logger.debug('ice binding got no response, proceeding to dtls anyway', {
|
|
218
|
-
connectionId: relayInfo.id
|
|
219
|
-
});
|
|
220
195
|
resolve(false);
|
|
221
196
|
return;
|
|
222
197
|
}
|
|
223
198
|
const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
|
|
224
199
|
try {
|
|
225
200
|
socket.send(packet, relayInfo.port, relayInfo.ip);
|
|
226
|
-
} catch
|
|
227
|
-
this.logger.trace('ice binding send failed', { connectionId: relayInfo.id, message: toError(err).message });
|
|
228
|
-
}
|
|
201
|
+
} catch { }
|
|
229
202
|
const wait = CONFIG.ICE_BINDING_TIMEOUTS_MS[attempt];
|
|
230
203
|
attempt += 1;
|
|
231
204
|
timer = setTimeout(sendAttempt, wait);
|
|
@@ -250,9 +223,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
250
223
|
try {
|
|
251
224
|
const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
|
|
252
225
|
socket.send(packet, relayInfo.port, relayInfo.ip);
|
|
253
|
-
} catch
|
|
254
|
-
this.logger.trace('ice consent refresh send failed', { connectionId: relayInfo.id, message: toError(err).message });
|
|
255
|
-
}
|
|
226
|
+
} catch { }
|
|
256
227
|
}, CONFIG.ICE_CONSENT_REFRESH_MS);
|
|
257
228
|
}
|
|
258
229
|
|
|
@@ -287,7 +258,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
287
258
|
|
|
288
259
|
const dtls = new DtlsClient({
|
|
289
260
|
sendDatagram: (datagram) => {
|
|
290
|
-
try { socket.send(datagram, targetPort, targetIp); } catch {
|
|
261
|
+
try { socket.send(datagram, targetPort, targetIp); } catch { }
|
|
291
262
|
},
|
|
292
263
|
logger: connLogger
|
|
293
264
|
});
|
|
@@ -297,7 +268,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
297
268
|
sendDtlsPayload: (plaintext) => {
|
|
298
269
|
if (!dtls.isConnected) return;
|
|
299
270
|
const record = dtls.encryptApplicationData(plaintext);
|
|
300
|
-
try { socket.send(record, targetPort, targetIp); } catch {
|
|
271
|
+
try { socket.send(record, targetPort, targetIp); } catch { }
|
|
301
272
|
},
|
|
302
273
|
logger: connLogger
|
|
303
274
|
});
|
|
@@ -317,44 +288,46 @@ export class WaManualRelay extends EventEmitter {
|
|
|
317
288
|
const payloads = dtls.decryptApplicationData(datagram);
|
|
318
289
|
for (const payload of payloads) dc.handleDtlsPayload(payload);
|
|
319
290
|
} else {
|
|
320
|
-
|
|
321
291
|
try {
|
|
322
292
|
dtls.handleDatagram(datagram);
|
|
323
|
-
} catch
|
|
324
|
-
this.logger.trace('handleDatagram threw', {
|
|
325
|
-
connectionId: relayInfo.id, message: toError(err).message
|
|
326
|
-
});
|
|
327
|
-
}
|
|
293
|
+
} catch { }
|
|
328
294
|
}
|
|
329
295
|
});
|
|
330
|
-
socket.on('error', (err) =>
|
|
296
|
+
socket.on('error', (err) => {
|
|
297
|
+
if (conn.state === ConnectionState.Open) this.handleRelayLoss(conn);
|
|
298
|
+
settle(err instanceof Error ? err : new Error(String(err)));
|
|
299
|
+
});
|
|
331
300
|
|
|
332
301
|
dtls.on('connected', () => {
|
|
333
|
-
this.logger.debug('dtls handshake complete', { connectionId: relayInfo.id });
|
|
334
302
|
dc.start();
|
|
335
303
|
});
|
|
336
304
|
dtls.on('error', (err) => {
|
|
337
|
-
this.logger.debug('dtls error', { connectionId: relayInfo.id, message: toError(err).message });
|
|
338
305
|
settle(err);
|
|
339
306
|
});
|
|
340
307
|
dc.on('open', () => {
|
|
341
|
-
this.logger.debug('datachannel open', { connectionId: relayInfo.id });
|
|
342
308
|
conn.state = ConnectionState.Open;
|
|
343
309
|
this.flushBufferedPackets(conn);
|
|
344
|
-
|
|
310
|
+
conn.lastInboundAt = Date.now();
|
|
345
311
|
this.startKeepalive(conn);
|
|
346
312
|
if (CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
|
|
347
313
|
this.sendStunAllocateOnOpen(conn, relayInfo);
|
|
314
|
+
for (const delayMs of [50, 150, 500, 3000]) setTimeout(() => this.sendStunAllocateOnOpen(conn, conn.relayInfo), delayMs);
|
|
348
315
|
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
|
|
349
316
|
this.stats.connected++;
|
|
317
|
+
const wasRecovering = conn.recovering;
|
|
318
|
+
if (wasRecovering) {
|
|
319
|
+
conn.recovering = false;
|
|
320
|
+
conn.retryCount = 0;
|
|
321
|
+
}
|
|
350
322
|
this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
|
|
323
|
+
if (wasRecovering) this.emit('relay_recovered', { connectionId: relayInfo.id });
|
|
351
324
|
settle(null);
|
|
352
325
|
});
|
|
353
326
|
dc.on('error', (err) => {
|
|
354
|
-
this.logger.debug('datachannel error', { connectionId: relayInfo.id, message: toError(err).message });
|
|
355
327
|
settle(err);
|
|
356
328
|
});
|
|
357
329
|
dc.on('message', (payload) => {
|
|
330
|
+
conn.lastInboundAt = Date.now();
|
|
358
331
|
this.handleRelayStun(conn, relayInfo, payload);
|
|
359
332
|
conn.stats.receivedPackets++;
|
|
360
333
|
conn.stats.receivedBytes += byteLengthOf(payload);
|
|
@@ -367,22 +340,16 @@ export class WaManualRelay extends EventEmitter {
|
|
|
367
340
|
}, CONFIG.CONNECTION_TIMEOUT_MS);
|
|
368
341
|
|
|
369
342
|
socket.bind(0, async () => {
|
|
370
|
-
this.logger.warn('[DIAG] udp socket bound, starting ice binding check', {
|
|
371
|
-
connectionId: relayInfo.id, localPort: socket.address().port
|
|
372
|
-
});
|
|
373
|
-
|
|
374
343
|
if (CONFIG.ICE_BINDING_ENABLED) {
|
|
375
344
|
const bindingOk = await this.performIceBinding(socket, relayInfo, conn);
|
|
376
345
|
if (settledConn) return;
|
|
377
346
|
if (!bindingOk) {
|
|
378
|
-
this.logger.debug('ice binding failed, aborting before dtls', { connectionId: relayInfo.id });
|
|
379
347
|
settle(new Error('ICE binding to relay failed or timed out'));
|
|
380
348
|
return;
|
|
381
349
|
}
|
|
382
350
|
}
|
|
383
351
|
|
|
384
352
|
iceBindingDone = true;
|
|
385
|
-
this.logger.debug('ice binding ok, starting dtls (client role)', { connectionId: relayInfo.id });
|
|
386
353
|
dtls.start();
|
|
387
354
|
});
|
|
388
355
|
});
|
|
@@ -392,7 +359,6 @@ export class WaManualRelay extends EventEmitter {
|
|
|
392
359
|
for (const [, conn] of this.connections) {
|
|
393
360
|
if (conn.state === ConnectionState.Open && conn.dataChannel) {
|
|
394
361
|
this.sendStunAllocateOnOpen(conn, conn.relayInfo);
|
|
395
|
-
this.logger.debug('manual relay subscriptions resent', { connectionId: conn.relayInfo.id });
|
|
396
362
|
}
|
|
397
363
|
}
|
|
398
364
|
}
|
|
@@ -416,10 +382,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
416
382
|
}
|
|
417
383
|
}
|
|
418
384
|
else if (type === 0x0103) {
|
|
419
|
-
|
|
385
|
+
this.rxStun.allocOk++;
|
|
420
386
|
}
|
|
421
387
|
else if (type === 0x0113 || type === 0x0111) {
|
|
422
|
-
if (this.rxStun.allocErr++ === 0) this.logger.warn('[RELAY] allocate/binding ERROR from relay', { connectionId: relayInfo.id, type: '0x' + type.toString(16), bytes: data.length });
|
|
388
|
+
if (this.rxStun.allocErr++ === 0) this.logger.warn('[RELAY] allocate/binding ERROR from relay', { connectionId: relayInfo.id, type: '0x' + type.toString(16), bytes: data.length, errorCode: parseStunResponse(data)?.errorCode });
|
|
423
389
|
}
|
|
424
390
|
else if (type === 0x0802) {
|
|
425
391
|
this.rxStun.pong++;
|
|
@@ -430,30 +396,34 @@ export class WaManualRelay extends EventEmitter {
|
|
|
430
396
|
}
|
|
431
397
|
|
|
432
398
|
sendStunAllocateOnOpen(conn, relayInfo) {
|
|
433
|
-
const connectionId = relayInfo.id;
|
|
434
399
|
if (!relayInfo.rawToken || relayInfo.rawToken.length === 0) {
|
|
435
|
-
this.logger.debug('allocate skipped, no relay token', { connectionId });
|
|
436
400
|
return;
|
|
437
401
|
}
|
|
438
402
|
if (!relayInfo.key) {
|
|
439
|
-
this.logger.debug('allocate skipped, no relay key', { connectionId });
|
|
440
403
|
return;
|
|
441
404
|
}
|
|
442
405
|
if (!this.audioSsrc) {
|
|
443
|
-
this.logger.debug('allocate skipped, no ssrc yet', { connectionId });
|
|
444
406
|
return;
|
|
445
407
|
}
|
|
446
408
|
const hmacKey = TEXT_ENCODER.encode(relayInfo.key);
|
|
409
|
+
const subs = buildSenderSubscriptions(this.subscriptionSsrc || this.audioSsrc);
|
|
410
|
+
const remoteUfrag = relayInfo.authToken || relayInfo.token;
|
|
411
|
+
if (remoteUfrag) {
|
|
412
|
+
const username = TEXT_ENCODER.encode(`${remoteUfrag}:${conn.localUfrag}`);
|
|
413
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
|
|
414
|
+
}
|
|
415
|
+
if (relayInfo.token && relayInfo.token !== remoteUfrag) {
|
|
416
|
+
const username = TEXT_ENCODER.encode(`${relayInfo.token}:${conn.localUfrag}`);
|
|
417
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
|
|
418
|
+
}
|
|
419
|
+
this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(undefined, undefined, subs, false, false)));
|
|
447
420
|
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
const descriptors = createWasmStreamDescriptors(streamSsrcs);
|
|
453
|
-
const packet = buildAllocateForRelay(relayInfo.rawToken, descriptors, hmacKey, relayInfo.ip, relayInfo.port);
|
|
421
|
+
const peerSsrcs = this.subscriptionSsrc ? [this.subscriptionSsrc] : [];
|
|
422
|
+
const ssrcList = buildSSRCSubscriptionList([this.audioSsrc, this.videoSsrc], peerSsrcs, this.selfPid, this.peerPid);
|
|
423
|
+
const username = remoteUfrag ? TEXT_ENCODER.encode(`${remoteUfrag}:${conn.localUfrag}`) : undefined;
|
|
424
|
+
const packet = buildAllocateForRelay(relayInfo.rawToken, ssrcList, hmacKey, relayInfo.ip, relayInfo.port, username);
|
|
454
425
|
conn.allocatePacket = toArrayBuffer(packet);
|
|
455
426
|
this.sendToChannel(conn, conn.allocatePacket);
|
|
456
|
-
this.logger.trace('allocate sent', { connectionId, size: packet.length });
|
|
457
427
|
}
|
|
458
428
|
|
|
459
429
|
sendToChannel(conn, data) {
|
|
@@ -463,9 +433,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
463
433
|
conn.stats.sentPackets++;
|
|
464
434
|
conn.stats.sentBytes += byteLengthOf(data);
|
|
465
435
|
this.stats.sent++;
|
|
466
|
-
} catch
|
|
467
|
-
this.logger.trace('sendToChannel failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
|
|
468
|
-
}
|
|
436
|
+
} catch { }
|
|
469
437
|
}
|
|
470
438
|
|
|
471
439
|
closePeerObjects(conn) {
|
|
@@ -477,9 +445,9 @@ export class WaManualRelay extends EventEmitter {
|
|
|
477
445
|
clearInterval(conn.iceConsentTimer);
|
|
478
446
|
conn.iceConsentTimer = null;
|
|
479
447
|
}
|
|
480
|
-
try { conn.dataChannel?.close?.(); } catch
|
|
481
|
-
try { conn.dtlsClient?.close?.(); } catch
|
|
482
|
-
try { conn.socket?.close?.(); } catch
|
|
448
|
+
try { conn.dataChannel?.close?.(); } catch { }
|
|
449
|
+
try { conn.dtlsClient?.close?.(); } catch { }
|
|
450
|
+
try { conn.socket?.close?.(); } catch { }
|
|
483
451
|
conn.socket = null;
|
|
484
452
|
conn.dtlsClient = null;
|
|
485
453
|
conn.dataChannel = null;
|
|
@@ -489,6 +457,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
489
457
|
if (conn.keepaliveTimer) clearInterval(conn.keepaliveTimer);
|
|
490
458
|
conn.keepaliveTimer = setInterval(() => {
|
|
491
459
|
if (conn.state !== ConnectionState.Open || !conn.dataChannel) return;
|
|
460
|
+
if (Date.now() - conn.lastInboundAt > 15_000) {
|
|
461
|
+
this.handleRelayLoss(conn);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
492
464
|
|
|
493
465
|
if (conn.allocatePacket) this.sendToChannel(conn, conn.allocatePacket);
|
|
494
466
|
this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
|
|
@@ -505,9 +477,7 @@ export class WaManualRelay extends EventEmitter {
|
|
|
505
477
|
conn.stats.sentPackets++;
|
|
506
478
|
conn.stats.sentBytes += byteLengthOf(packet);
|
|
507
479
|
this.stats.sent++;
|
|
508
|
-
} catch
|
|
509
|
-
this.logger.trace('flush send failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
|
|
510
|
-
}
|
|
480
|
+
} catch { }
|
|
511
481
|
}
|
|
512
482
|
}
|
|
513
483
|
|
|
@@ -537,12 +507,10 @@ export class WaManualRelay extends EventEmitter {
|
|
|
537
507
|
conn.stats.sentPackets++;
|
|
538
508
|
conn.stats.sentBytes += byteLengthOf(data);
|
|
539
509
|
this.stats.sent++;
|
|
540
|
-
} catch
|
|
541
|
-
this.logger.trace('sendToRelay failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
|
|
542
|
-
}
|
|
510
|
+
} catch { }
|
|
543
511
|
} else {
|
|
544
512
|
this.bufferPacket(conn, data);
|
|
545
|
-
void this.ensureConnection(conn.relayInfo);
|
|
513
|
+
if (!conn.recovering) void this.ensureConnection(conn.relayInfo);
|
|
546
514
|
}
|
|
547
515
|
}
|
|
548
516
|
}
|
|
@@ -559,14 +527,39 @@ export class WaManualRelay extends EventEmitter {
|
|
|
559
527
|
conn.stats.sentBytes += byteLengthOf(data);
|
|
560
528
|
this.stats.sent++;
|
|
561
529
|
sentAny = true;
|
|
562
|
-
} catch
|
|
563
|
-
this.logger.trace('broadcast send failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
|
|
564
|
-
}
|
|
530
|
+
} catch { }
|
|
565
531
|
}
|
|
566
532
|
}
|
|
567
533
|
return sentAny;
|
|
568
534
|
}
|
|
569
535
|
|
|
536
|
+
handleRelayLoss(conn) {
|
|
537
|
+
if (conn.state !== ConnectionState.Open) return;
|
|
538
|
+
this.closePeerObjects(conn);
|
|
539
|
+
conn.state = ConnectionState.Closed;
|
|
540
|
+
if (!conn.recovering) conn.retryCount = 0;
|
|
541
|
+
conn.recovering = true;
|
|
542
|
+
this.emit('relay_lost', { connectionId: conn.relayInfo.id, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
|
|
543
|
+
this.scheduleRelayRetry(conn);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
scheduleRelayRetry(conn) {
|
|
547
|
+
if (conn.retryCount >= this.retrySchedule.length) {
|
|
548
|
+
this.emit('relay_failed', { connectionId: conn.relayInfo.id, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const delay = this.retrySchedule[conn.retryCount];
|
|
552
|
+
conn.retryCount += 1;
|
|
553
|
+
conn.retryTimer = setTimeout(async () => {
|
|
554
|
+
conn.retryTimer = null;
|
|
555
|
+
if (this.connections.get(conn.relayInfo.id) !== conn) return;
|
|
556
|
+
this.emit('relay_retrying', { connectionId: conn.relayInfo.id, attempt: conn.retryCount, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
|
|
557
|
+
await this.ensureConnection(conn.relayInfo);
|
|
558
|
+
if (conn.state !== ConnectionState.Open) this.scheduleRelayRetry(conn);
|
|
559
|
+
}, delay);
|
|
560
|
+
conn.retryTimer.unref?.();
|
|
561
|
+
}
|
|
562
|
+
|
|
570
563
|
hasConnection() {
|
|
571
564
|
for (const [, conn] of this.connections) {
|
|
572
565
|
if (conn.state === ConnectionState.Open) return true;
|
|
@@ -600,7 +593,11 @@ export class WaManualRelay extends EventEmitter {
|
|
|
600
593
|
}
|
|
601
594
|
|
|
602
595
|
cleanup() {
|
|
603
|
-
for (const [, conn] of this.connections)
|
|
596
|
+
for (const [, conn] of this.connections) {
|
|
597
|
+
if (conn.retryTimer) clearTimeout(conn.retryTimer);
|
|
598
|
+
conn.retryTimer = null;
|
|
599
|
+
this.closePeerObjects(conn);
|
|
600
|
+
}
|
|
604
601
|
this.connections.clear();
|
|
605
602
|
this.relayMap.clear();
|
|
606
603
|
this.globalBuffer = [];
|
|
@@ -7,14 +7,12 @@ import { generateSelfSignedCert } from './cert-builder.js';
|
|
|
7
7
|
import { generateEcdheKeypair, buildEcdheSignedParams, verifyEcdheParams, signEcdheParams } from './ecdhe.js';
|
|
8
8
|
import { deriveMasterSecret, deriveKeyBlock, deriveVerifyData } from './prf.js';
|
|
9
9
|
import { encryptRecord, decryptRecord, aes128GcmParams } from './aead.js';
|
|
10
|
-
import { createNoopLogger } from '../../shim/core.js';
|
|
11
10
|
|
|
12
11
|
const RETRANSMIT_TIMEOUTS_MS = [1000, 2000, 4000, 8000, 8000];
|
|
13
12
|
const HANDSHAKE_TIMEOUT_MS = 25000;
|
|
14
13
|
|
|
15
14
|
export class DtlsClient extends EventEmitter {
|
|
16
15
|
#sendDatagram;
|
|
17
|
-
#logger;
|
|
18
16
|
#state = 'idle';
|
|
19
17
|
#messageSeq = 0;
|
|
20
18
|
#reassembler = new HandshakeReassembler();
|
|
@@ -37,10 +35,9 @@ export class DtlsClient extends EventEmitter {
|
|
|
37
35
|
#lastFlightDatagrams = [];
|
|
38
36
|
#overallTimeoutTimer = null;
|
|
39
37
|
|
|
40
|
-
constructor({ sendDatagram
|
|
38
|
+
constructor({ sendDatagram }) {
|
|
41
39
|
super();
|
|
42
40
|
this.#sendDatagram = sendDatagram;
|
|
43
|
-
this.#logger = logger ?? createNoopLogger();
|
|
44
41
|
}
|
|
45
42
|
|
|
46
43
|
start() {
|
|
@@ -84,25 +81,15 @@ export class DtlsClient extends EventEmitter {
|
|
|
84
81
|
const out = [];
|
|
85
82
|
let records;
|
|
86
83
|
try { records = decodeRecords(datagram); } catch (e) {
|
|
87
|
-
|
|
88
|
-
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
89
|
-
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
90
|
-
});
|
|
91
84
|
return out;
|
|
92
85
|
}
|
|
93
86
|
for (const record of records) {
|
|
94
87
|
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
95
|
-
this.#logger.trace('post-handshake non-application_data record', {
|
|
96
|
-
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
97
|
-
});
|
|
98
88
|
this.#handleRecord(record);
|
|
99
89
|
continue;
|
|
100
90
|
}
|
|
101
91
|
const readFloor = this.#readSeqByEpoch.get(record.epoch) ?? -1n;
|
|
102
92
|
if (record.sequenceNumber <= readFloor) {
|
|
103
|
-
this.#logger.trace('dropping application_data as replay/duplicate', {
|
|
104
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), readFloor: readFloor.toString()
|
|
105
|
-
});
|
|
106
93
|
continue;
|
|
107
94
|
}
|
|
108
95
|
try {
|
|
@@ -111,16 +98,8 @@ export class DtlsClient extends EventEmitter {
|
|
|
111
98
|
epoch: record.epoch, sequenceNumber: record.sequenceNumber, type: record.type, fragment: record.fragment,
|
|
112
99
|
});
|
|
113
100
|
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
114
|
-
this.#logger.trace('decrypted application_data', {
|
|
115
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), plaintextLen: plaintext.length
|
|
116
|
-
});
|
|
117
101
|
out.push(plaintext);
|
|
118
|
-
} catch
|
|
119
|
-
|
|
120
|
-
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
121
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
122
|
-
});
|
|
123
|
-
}
|
|
102
|
+
} catch { }
|
|
124
103
|
}
|
|
125
104
|
return out;
|
|
126
105
|
}
|
|
@@ -216,7 +195,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
216
195
|
return;
|
|
217
196
|
}
|
|
218
197
|
if (record.type === ContentType.CHANGE_CIPHER_SPEC) {
|
|
219
|
-
|
|
220
198
|
return;
|
|
221
199
|
}
|
|
222
200
|
if (record.type === ContentType.ALERT) {
|
|
@@ -256,7 +234,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
256
234
|
return;
|
|
257
235
|
}
|
|
258
236
|
if (msgType === HandshakeType.CERTIFICATE_REQUEST) {
|
|
259
|
-
|
|
260
237
|
this.#serverRequestedClientCert = true;
|
|
261
238
|
return;
|
|
262
239
|
}
|
|
@@ -323,7 +300,6 @@ export class DtlsClient extends EventEmitter {
|
|
|
323
300
|
|
|
324
301
|
export class DtlsServer extends EventEmitter {
|
|
325
302
|
#sendDatagram;
|
|
326
|
-
#logger;
|
|
327
303
|
#state = 'idle';
|
|
328
304
|
#messageSeq = 0;
|
|
329
305
|
#reassembler = new HandshakeReassembler();
|
|
@@ -342,10 +318,9 @@ export class DtlsServer extends EventEmitter {
|
|
|
342
318
|
#lastFlightDatagrams = [];
|
|
343
319
|
#overallTimeoutTimer = null;
|
|
344
320
|
|
|
345
|
-
constructor({ sendDatagram
|
|
321
|
+
constructor({ sendDatagram }) {
|
|
346
322
|
super();
|
|
347
323
|
this.#sendDatagram = sendDatagram;
|
|
348
|
-
this.#logger = logger ?? createNoopLogger();
|
|
349
324
|
}
|
|
350
325
|
|
|
351
326
|
startPassive() {
|
|
@@ -387,16 +362,10 @@ export class DtlsServer extends EventEmitter {
|
|
|
387
362
|
const out = [];
|
|
388
363
|
let records;
|
|
389
364
|
try { records = decodeRecords(datagram); } catch (e) {
|
|
390
|
-
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
391
|
-
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
392
|
-
});
|
|
393
365
|
return out;
|
|
394
366
|
}
|
|
395
367
|
for (const record of records) {
|
|
396
368
|
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
397
|
-
this.#logger.trace('post-handshake non-application_data record', {
|
|
398
|
-
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
399
|
-
});
|
|
400
369
|
this.#handleRecord(record);
|
|
401
370
|
continue;
|
|
402
371
|
}
|
|
@@ -409,11 +378,7 @@ export class DtlsServer extends EventEmitter {
|
|
|
409
378
|
});
|
|
410
379
|
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
411
380
|
out.push(plaintext);
|
|
412
|
-
} catch
|
|
413
|
-
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
414
|
-
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
415
|
-
});
|
|
416
|
-
}
|
|
381
|
+
} catch { }
|
|
417
382
|
}
|
|
418
383
|
return out;
|
|
419
384
|
}
|
|
@@ -485,15 +450,12 @@ export class DtlsServer extends EventEmitter {
|
|
|
485
450
|
} catch (e) {
|
|
486
451
|
this.#fail(new Error(`DTLS: server-side key derivation failed: ${e.message}`));
|
|
487
452
|
}
|
|
488
|
-
|
|
489
453
|
}
|
|
490
454
|
|
|
491
455
|
#tryDecryptClientFinished(record) {
|
|
492
456
|
const readFloor = this.#readSeqByEpoch.get(1) ?? -1n;
|
|
493
457
|
if (record.sequenceNumber <= readFloor) return;
|
|
494
458
|
if (!this.#keys) {
|
|
495
|
-
|
|
496
|
-
this.#logger.trace('client Finished arrived before key derivation completed', {});
|
|
497
459
|
return;
|
|
498
460
|
}
|
|
499
461
|
let plaintext;
|