@hiroosy/baileys-lite 0.3.7 → 0.3.9

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.
@@ -5,8 +5,8 @@ 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, buildWhatsAppPing, createWasmStreamDescriptors, parseStunResponse } from './stun.js';
9
- import { randomBytes } from 'node:crypto';
8
+ import { buildAllocateForRelay, buildBindingRequest, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, createWasmStreamDescriptors, parseRelayedAddressMismatch, parseStunResponse } from './stun.js';
9
+ import { randomBytes } from '../crypto/primitives.js';
10
10
  import { PayloadType } from '../types.js';
11
11
 
12
12
  const CONFIG = {
@@ -41,42 +41,42 @@ function randomUfrag() {
41
41
  }
42
42
 
43
43
  export class WaManualRelay extends EventEmitter {
44
+ rejectedModes = new Set();
45
+ answeredRelayNames = new Set();
46
+ maxActiveRelays = 3;
44
47
  logger;
45
48
  connections = new Map();
46
49
  relayMap = new Map();
50
+ standbyRelays = [];
51
+ failedRelays = new Set();
47
52
  audioSsrc = 0;
48
53
  videoSsrc = 0;
49
54
  subscriptionSsrc = 0;
50
55
  streamSsrcs = null;
56
+ selfPid = 0;
57
+ peerPid = 0;
51
58
  rxStun = { bindReq: 0, bindAnswered: 0, allocOk: 0, allocErr: 0, pong: 0, other: 0 };
52
59
  configuring = false;
53
60
  globalBuffer = [];
54
61
  globalBufferedBytes = 0;
55
62
  stats = { sent: 0, received: 0, connected: 0 };
63
+ retrySchedule = [1000, 2000, 4000];
64
+ transports = ['dtls', 'raw'];
56
65
 
57
66
  constructor(options = {}) {
58
67
  super();
59
68
  this.logger = options.logger ?? createNoopLogger();
69
+ this.transports = options.transports ?? this.transports;
70
+ this.maxActiveRelays = options.maxActiveRelays ?? this.maxActiveRelays;
60
71
  }
61
72
 
62
73
  setSsrc(ssrc) {
63
74
  this.audioSsrc = ssrc;
64
- this.logger.debug('manual relay ssrc set', { ssrc: `0x${ssrc.toString(16).padStart(8, '0')}` });
65
- }
66
-
67
- setStreamSsrcs(streamSsrcs) {
68
- const out = Array.from(streamSsrcs, (v) => v >>> 0);
69
- const used = new Set(out.slice(0, 6).filter((v) => v !== 0));
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;
75
+ }
76
+
77
+ setParticipantIds(selfPid, peerPid) {
78
+ this.selfPid = selfPid ?? 0;
79
+ this.peerPid = peerPid ?? 0;
80
80
  }
81
81
 
82
82
  getRxStunStats() {
@@ -85,14 +85,14 @@ export class WaManualRelay extends EventEmitter {
85
85
 
86
86
  setVideoSsrc(ssrc) {
87
87
  this.videoSsrc = ssrc;
88
- this.logger.debug('manual relay video ssrc set', { ssrc: `0x${ssrc.toString(16).padStart(8, '0')}` });
88
+ }
89
+
90
+ setStreamSsrcs(ssrcs) {
91
+ this.streamSsrcs = ssrcs;
89
92
  }
90
93
 
91
94
  setSubscriptionSsrc(ssrc) {
92
95
  this.subscriptionSsrc = ssrc;
93
- this.logger.debug('manual relay subscription ssrc set', {
94
- ssrc: `0x${ssrc.toString(16).padStart(8, '0')}`
95
- });
96
96
  }
97
97
 
98
98
  makeConnectionId(ip, port, authTokenId) {
@@ -100,35 +100,54 @@ export class WaManualRelay extends EventEmitter {
100
100
  return authTokenId ? `${base}#${authTokenId}` : base;
101
101
  }
102
102
 
103
+ toRelayInfo(relay) {
104
+ const port = relay.port || CONFIG.TRUE_WEB_CLIENT_RELAY_PORT;
105
+ return {
106
+ id: this.makeConnectionId(relay.ip, port, relay.authTokenId),
107
+ ip: relay.ip,
108
+ port,
109
+ token: relay.token,
110
+ authToken: relay.authToken,
111
+ rawAuthToken: relay.rawAuthToken,
112
+ rawToken: relay.rawToken,
113
+ key: relay.key,
114
+ relayId: relay.relayId,
115
+ name: relay.name || 'unknown',
116
+ authTokenId: relay.authTokenId,
117
+ isFna: relay.isFna,
118
+ fallbackPort: port === CONFIG.TRUE_WEB_CLIENT_RELAY_PORT ? 3478 : CONFIG.TRUE_WEB_CLIENT_RELAY_PORT
119
+ };
120
+ }
121
+
103
122
  async configureRelays(relays) {
104
- this.logger.debug('manual relay configuring relays', { count: relays.length });
105
123
  this.configuring = true;
106
- for (const relay of relays) {
107
- const port = relay.port || CONFIG.TRUE_WEB_CLIENT_RELAY_PORT;
108
- const connectionId = this.makeConnectionId(relay.ip, port, relay.authTokenId);
109
- this.relayMap.set(connectionId, {
110
- id: connectionId,
111
- ip: relay.ip,
112
- port,
113
- token: relay.token,
114
- authToken: relay.authToken,
115
- rawAuthToken: relay.rawAuthToken,
116
- rawToken: relay.rawToken,
117
- key: relay.key,
118
- relayId: relay.relayId,
119
- name: relay.name || 'unknown',
120
- authTokenId: relay.authTokenId,
121
- isFna: relay.isFna
122
- });
124
+ const infos = relays.map((relay) => this.toRelayInfo(relay)).filter((info) => !this.failedRelays.has(info.id));
125
+ for (const info of infos) {
126
+ if (this.relayMap.has(info.id)) {
127
+ this.relayMap.set(info.id, info);
128
+ }
129
+ else if (this.relayMap.size < this.maxActiveRelays) {
130
+ this.relayMap.set(info.id, info);
131
+ }
123
132
  }
133
+ this.standbyRelays = infos.filter((info) => !this.relayMap.has(info.id));
124
134
  const connectionPromises = [];
125
135
  for (const [, relayInfo] of this.relayMap) {
126
136
  if (!this.connections.has(relayInfo.id)) {
127
137
  connectionPromises.push(this.ensureConnection(relayInfo));
128
138
  }
129
139
  }
130
- await Promise.all(connectionPromises);
131
- this.logger.debug('manual relay configuration done', { connected: this.stats.connected });
140
+ if (connectionPromises.length > 0) {
141
+ const settled = connectionPromises.map((promise) => promise.catch(() => {}));
142
+ const firstOpen = new Promise((resolve) => {
143
+ for (const promise of settled) {
144
+ promise.then(() => {
145
+ if (this.hasConnection()) resolve();
146
+ });
147
+ }
148
+ });
149
+ await Promise.race([Promise.all(settled), firstOpen]);
150
+ }
132
151
  this.configuring = false;
133
152
  if (this.globalBuffer.length > 0) {
134
153
  for (const item of this.globalBuffer) this.sendToRelay(item.ip, item.port, item.data);
@@ -137,9 +156,64 @@ export class WaManualRelay extends EventEmitter {
137
156
  }
138
157
  }
139
158
 
159
+ buildRoutes(relayInfo) {
160
+ const ports = [relayInfo.port];
161
+ if (relayInfo.fallbackPort !== undefined && relayInfo.fallbackPort !== relayInfo.port) {
162
+ ports.push(relayInfo.fallbackPort);
163
+ }
164
+ const routes = [];
165
+ const preferRaw = !relayInfo.authToken && this.transports.includes('raw');
166
+ const rank = (mode) => (this.rejectedModes.has(`${relayInfo.ip}|${mode}`) ? 2 : 0) + (preferRaw && mode !== 'raw' ? 1 : 0);
167
+ const modes = [...this.transports].sort((a, b) => rank(a) - rank(b));
168
+ for (const mode of modes) {
169
+ for (const port of ports) {
170
+ routes.push({ mode, port });
171
+ }
172
+ }
173
+ if (routes.length === 0) {
174
+ routes.push({ mode: 'dtls', port: relayInfo.port });
175
+ }
176
+ return routes;
177
+ }
178
+
179
+ applyRoute(conn, index) {
180
+ const route = conn.routes[index];
181
+ conn.routeIndex = index;
182
+ conn.mode = route.mode;
183
+ conn.dialPort = route.port;
184
+ conn.returnPathSeen = false;
185
+ this.restartAllocateLadder(conn);
186
+ }
187
+
188
+ restartAllocateLadder(conn) {
189
+ conn.allocateStage = 0;
190
+ conn.allocateLocked = false;
191
+ conn.allocateExhausted = false;
192
+ conn.allocateCandidates = null;
193
+ conn.allocateAttempts.clear();
194
+ conn.allocatePacket = null;
195
+ conn.proven = false;
196
+ conn.refused = false;
197
+ conn.allocateResponses = 0;
198
+ conn.stunTransactionId = randomBytes(12);
199
+ }
200
+
201
+ advanceRoute(conn, reason, targetIndex = conn.routeIndex + 1) {
202
+ if (targetIndex >= conn.routes.length) {
203
+ return false;
204
+ }
205
+ const from = conn.routes[conn.routeIndex];
206
+ this.applyRoute(conn, targetIndex);
207
+ this.logger.warn('[RELAY] switching relay route', { connectionId: conn.relayInfo.id, reason, from, to: conn.routes[conn.routeIndex] });
208
+ this.closePeerObjects(conn);
209
+ conn.state = ConnectionState.Closed;
210
+ return true;
211
+ }
212
+
140
213
  getOrCreateConnection(relayInfo) {
141
214
  let conn = this.connections.get(relayInfo.id);
142
215
  if (!conn) {
216
+ const routes = this.buildRoutes(relayInfo);
143
217
  conn = {
144
218
  state: ConnectionState.None,
145
219
  relayInfo,
@@ -152,7 +226,30 @@ export class WaManualRelay extends EventEmitter {
152
226
  connectionTimeout: null,
153
227
  keepaliveTimer: null,
154
228
  iceConsentTimer: null,
229
+ retryTimer: null,
230
+ retryCount: 0,
231
+ recovering: false,
232
+ lastInboundAt: 0,
155
233
  localUfrag: randomUfrag(),
234
+ stunTransactionId: randomBytes(12),
235
+ routes,
236
+ routeIndex: 0,
237
+ mode: routes[0].mode,
238
+ dialPort: routes[0].port,
239
+ fallbackTimer: null,
240
+ answered: false,
241
+ keepaliveTicks: 0,
242
+ allocateStage: 0,
243
+ allocateLocked: false,
244
+ allocateExhausted: false,
245
+ allocateCandidates: null,
246
+ allocateRounds: 0,
247
+ returnPathSeen: false,
248
+ proven: false,
249
+ refused: false,
250
+ allocateResponses: 0,
251
+ openedAt: 0,
252
+ allocateAttempts: new Map(),
156
253
  stats: { sentPackets: 0, receivedPackets: 0, sentBytes: 0, receivedBytes: 0 }
157
254
  };
158
255
  this.connections.set(relayInfo.id, conn);
@@ -167,16 +264,17 @@ export class WaManualRelay extends EventEmitter {
167
264
  }
168
265
  const promise = this.connect(conn);
169
266
  conn.connectPromise = promise;
267
+ let failed = false;
170
268
  try {
171
269
  await promise;
172
- } catch (err) {
173
- this.logger.debug('manual relay connection attempt failed', {
174
- connectionId: relayInfo.id,
175
- message: toError(err).message
176
- });
270
+ } catch {
271
+ failed = true;
177
272
  } finally {
178
273
  conn.connectPromise = null;
179
274
  }
275
+ if (failed && this.advanceRoute(conn, 'connect_failed')) {
276
+ await this.ensureConnection(relayInfo);
277
+ }
180
278
  };
181
279
 
182
280
  performIceBinding(socket, relayInfo, conn) {
@@ -199,11 +297,6 @@ export class WaManualRelay extends EventEmitter {
199
297
  settled = true;
200
298
  clearTimeout(timer);
201
299
  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
300
  resolve(info.isSuccess);
208
301
  }
209
302
  };
@@ -214,18 +307,13 @@ export class WaManualRelay extends EventEmitter {
214
307
  if (attempt >= CONFIG.ICE_BINDING_TIMEOUTS_MS.length) {
215
308
  settled = true;
216
309
  socket.removeListener('message', onMessage);
217
- this.logger.debug('ice binding got no response, proceeding to dtls anyway', {
218
- connectionId: relayInfo.id
219
- });
220
310
  resolve(false);
221
311
  return;
222
312
  }
223
- const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
313
+ const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling', transactionId: conn.stunTransactionId });
224
314
  try {
225
- socket.send(packet, relayInfo.port, relayInfo.ip);
226
- } catch (err) {
227
- this.logger.trace('ice binding send failed', { connectionId: relayInfo.id, message: toError(err).message });
228
- }
315
+ socket.send(packet, conn.dialPort, relayInfo.ip);
316
+ } catch { }
229
317
  const wait = CONFIG.ICE_BINDING_TIMEOUTS_MS[attempt];
230
318
  attempt += 1;
231
319
  timer = setTimeout(sendAttempt, wait);
@@ -249,22 +337,23 @@ export class WaManualRelay extends EventEmitter {
249
337
  }
250
338
  try {
251
339
  const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
252
- socket.send(packet, relayInfo.port, relayInfo.ip);
253
- } catch (err) {
254
- this.logger.trace('ice consent refresh send failed', { connectionId: relayInfo.id, message: toError(err).message });
255
- }
340
+ socket.send(packet, conn.dialPort, relayInfo.ip);
341
+ } catch { }
256
342
  }, CONFIG.ICE_CONSENT_REFRESH_MS);
257
343
  }
258
344
 
259
345
  connect = async (conn) => {
260
346
  this.closePeerObjects(conn);
261
347
  conn.state = ConnectionState.Connecting;
348
+ conn.answered = false;
262
349
  const relayInfo = conn.relayInfo;
350
+ const targetIp = relayInfo.ip;
351
+ const targetPort = conn.dialPort;
352
+ const dtlsRoute = conn.mode === 'dtls';
353
+ const timeoutMs = dtlsRoute ? 6000 : CONFIG.CONNECTION_TIMEOUT_MS;
263
354
  return new Promise((resolve, reject) => {
264
355
  const socket = dgram.createSocket('udp4');
265
356
  conn.socket = socket;
266
- const targetIp = relayInfo.ip;
267
- const targetPort = relayInfo.port;
268
357
 
269
358
  let settledConn = false;
270
359
  const settle = (err) => {
@@ -283,11 +372,59 @@ export class WaManualRelay extends EventEmitter {
283
372
  }
284
373
  };
285
374
 
375
+ const receive = (payload) => {
376
+ if (conn.socket !== socket) return;
377
+ conn.lastInboundAt = Date.now();
378
+ conn.answered = true;
379
+ const view = payload instanceof Uint8Array ? payload : new Uint8Array(payload);
380
+ if (!conn.returnPathSeen && view.length > 0 && (view[0] & 0xc0) !== 0) {
381
+ conn.returnPathSeen = true;
382
+ this.logger.info('[RELAY] return media confirmed', { connectionId: relayInfo.id, mode: conn.mode, port: conn.dialPort, bytes: view.length });
383
+ this.markRelayProven(conn, 'media');
384
+ }
385
+ this.handleRelayStun(conn, relayInfo, payload);
386
+ conn.stats.receivedPackets++;
387
+ conn.stats.receivedBytes += byteLengthOf(payload);
388
+ this.stats.received++;
389
+ this.emit('relay_receive', { ip: relayInfo.ip, port: relayInfo.port, data: payload });
390
+ };
391
+
392
+ socket.on('error', (err) => {
393
+ if (conn.state === ConnectionState.Open) this.handleRelayLoss(conn);
394
+ settle(err instanceof Error ? err : new Error(String(err)));
395
+ });
396
+
397
+ conn.connectionTimeout = setTimeout(() => {
398
+ settle(new Error(`relay connect timed out after ${timeoutMs}ms (${conn.mode} ${targetIp}:${targetPort})`));
399
+ }, timeoutMs);
400
+
401
+ if (!dtlsRoute) {
402
+ socket.on('message', (datagram) => {
403
+ receive(new Uint8Array(datagram.buffer, datagram.byteOffset, datagram.byteLength));
404
+ });
405
+ socket.connect(targetPort, targetIp, (err) => {
406
+ if (settledConn) return;
407
+ if (err) {
408
+ settle(err);
409
+ return;
410
+ }
411
+ conn.dataChannel = {
412
+ send: (data) => {
413
+ socket.send(Buffer.from(data));
414
+ },
415
+ getSendBacklog: () => 0,
416
+ close: () => {}
417
+ };
418
+ this.handleChannelOpen(conn, relayInfo, socket, settle);
419
+ });
420
+ return;
421
+ }
422
+
286
423
  const connLogger = this.logger.child?.({ connectionId: relayInfo.id }) ?? this.logger;
287
424
 
288
425
  const dtls = new DtlsClient({
289
426
  sendDatagram: (datagram) => {
290
- try { socket.send(datagram, targetPort, targetIp); } catch { }
427
+ try { socket.send(datagram, targetPort, targetIp); } catch { }
291
428
  },
292
429
  logger: connLogger
293
430
  });
@@ -297,7 +434,7 @@ export class WaManualRelay extends EventEmitter {
297
434
  sendDtlsPayload: (plaintext) => {
298
435
  if (!dtls.isConnected) return;
299
436
  const record = dtls.encryptApplicationData(plaintext);
300
- try { socket.send(record, targetPort, targetIp); } catch { }
437
+ try { socket.send(record, targetPort, targetIp); } catch { }
301
438
  },
302
439
  logger: connLogger
303
440
  });
@@ -308,7 +445,6 @@ export class WaManualRelay extends EventEmitter {
308
445
  if (!iceBindingDone) {
309
446
  return;
310
447
  }
311
-
312
448
  const isDtlsRecord = datagram.length >= 1 && datagram[0] >= 20 && datagram[0] <= 63;
313
449
  if (!isDtlsRecord) {
314
450
  return;
@@ -317,82 +453,96 @@ export class WaManualRelay extends EventEmitter {
317
453
  const payloads = dtls.decryptApplicationData(datagram);
318
454
  for (const payload of payloads) dc.handleDtlsPayload(payload);
319
455
  } else {
320
-
321
456
  try {
322
457
  dtls.handleDatagram(datagram);
323
- } catch (err) {
324
- this.logger.trace('handleDatagram threw', {
325
- connectionId: relayInfo.id, message: toError(err).message
326
- });
327
- }
458
+ } catch { }
328
459
  }
329
460
  });
330
- socket.on('error', (err) => settle(err instanceof Error ? err : new Error(String(err))));
331
461
 
332
462
  dtls.on('connected', () => {
333
- this.logger.debug('dtls handshake complete', { connectionId: relayInfo.id });
463
+ this.logger.info('[RELAY] dtls connected', { connectionId: relayInfo.id, port: targetPort });
334
464
  dc.start();
335
465
  });
336
466
  dtls.on('error', (err) => {
337
- this.logger.debug('dtls error', { connectionId: relayInfo.id, message: toError(err).message });
338
467
  settle(err);
339
468
  });
340
469
  dc.on('open', () => {
341
- this.logger.debug('datachannel open', { connectionId: relayInfo.id });
342
- conn.state = ConnectionState.Open;
343
- this.flushBufferedPackets(conn);
344
- this.logger.warn('[RELAY] mode=meowcaller v3 ice_binding=off consent_refresh=off allocate_streams=' + (this.streamSsrcs ? 9 : 2), { connectionId: relayInfo.id });
345
- this.startKeepalive(conn);
346
- if (CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
347
- this.sendStunAllocateOnOpen(conn, relayInfo);
348
- this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
349
- this.stats.connected++;
350
- this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
351
- settle(null);
470
+ this.handleChannelOpen(conn, relayInfo, socket, settle);
352
471
  });
353
472
  dc.on('error', (err) => {
354
- this.logger.debug('datachannel error', { connectionId: relayInfo.id, message: toError(err).message });
355
473
  settle(err);
356
474
  });
357
- dc.on('message', (payload) => {
358
- this.handleRelayStun(conn, relayInfo, payload);
359
- conn.stats.receivedPackets++;
360
- conn.stats.receivedBytes += byteLengthOf(payload);
361
- this.stats.received++;
362
- this.emit('relay_receive', { ip: relayInfo.ip, port: relayInfo.port, data: payload });
363
- });
364
-
365
- conn.connectionTimeout = setTimeout(() => {
366
- settle(new Error(`relay connect timed out after ${CONFIG.CONNECTION_TIMEOUT_MS}ms`));
367
- }, CONFIG.CONNECTION_TIMEOUT_MS);
475
+ dc.on('message', receive);
368
476
 
369
477
  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
478
  if (CONFIG.ICE_BINDING_ENABLED) {
375
479
  const bindingOk = await this.performIceBinding(socket, relayInfo, conn);
376
480
  if (settledConn) return;
377
481
  if (!bindingOk) {
378
- this.logger.debug('ice binding failed, aborting before dtls', { connectionId: relayInfo.id });
379
482
  settle(new Error('ICE binding to relay failed or timed out'));
380
483
  return;
381
484
  }
382
485
  }
383
-
384
486
  iceBindingDone = true;
385
- this.logger.debug('ice binding ok, starting dtls (client role)', { connectionId: relayInfo.id });
386
487
  dtls.start();
387
488
  });
388
489
  });
389
490
  };
390
491
 
492
+ handleChannelOpen(conn, relayInfo, socket, settle) {
493
+ if (conn.socket !== socket) return;
494
+ if (conn.allocateLocked || conn.allocateExhausted || conn.proven || conn.refused) {
495
+ this.restartAllocateLadder(conn);
496
+ }
497
+ conn.state = ConnectionState.Open;
498
+ conn.answered = false;
499
+ conn.openedAt = Date.now();
500
+ this.flushBufferedPackets(conn);
501
+ conn.lastInboundAt = Date.now();
502
+ this.logger.info('[RELAY] channel open', { connectionId: relayInfo.id, mode: conn.mode, port: conn.dialPort, hasAuthToken: Boolean(relayInfo.authToken) });
503
+ this.startKeepalive(conn);
504
+ this.armRouteFallback(conn);
505
+ if (conn.mode === 'dtls' && CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
506
+ this.sendStunAllocateOnOpen(conn, relayInfo);
507
+ for (const delayMs of [50, 150, 500, 3000]) setTimeout(() => this.sendStunAllocateOnOpen(conn, conn.relayInfo), delayMs);
508
+ this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing(conn.stunTransactionId)));
509
+ this.stats.connected++;
510
+ const wasRecovering = conn.recovering;
511
+ if (wasRecovering) {
512
+ conn.recovering = false;
513
+ conn.retryCount = 0;
514
+ }
515
+ this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
516
+ if (wasRecovering) this.emit('relay_recovered', { connectionId: relayInfo.id });
517
+ settle(null);
518
+ }
519
+
520
+ armRouteFallback(conn) {
521
+ if (conn.fallbackTimer) {
522
+ clearTimeout(conn.fallbackTimer);
523
+ conn.fallbackTimer = null;
524
+ }
525
+ if (conn.routeIndex + 1 >= conn.routes.length) {
526
+ return;
527
+ }
528
+ const socket = conn.socket;
529
+ conn.fallbackTimer = setTimeout(() => {
530
+ conn.fallbackTimer = null;
531
+ if (conn.socket !== socket || conn.state !== ConnectionState.Open || conn.answered) {
532
+ return;
533
+ }
534
+ if (this.advanceRoute(conn, 'relay_unanswered')) {
535
+ void this.ensureConnection(conn.relayInfo);
536
+ }
537
+ }, 4000);
538
+ conn.fallbackTimer.unref?.();
539
+ }
540
+
391
541
  resendSubscriptions() {
392
542
  for (const [, conn] of this.connections) {
393
543
  if (conn.state === ConnectionState.Open && conn.dataChannel) {
544
+ if (conn.allocateExhausted) this.restartAllocateLadder(conn);
394
545
  this.sendStunAllocateOnOpen(conn, conn.relayInfo);
395
- this.logger.debug('manual relay subscriptions resent', { connectionId: conn.relayInfo.id });
396
546
  }
397
547
  }
398
548
  }
@@ -416,10 +566,20 @@ export class WaManualRelay extends EventEmitter {
416
566
  }
417
567
  }
418
568
  else if (type === 0x0103) {
419
- if (this.rxStun.allocOk++ === 0) this.logger.warn('[RELAY] allocate success from relay', { connectionId: relayInfo.id });
569
+ this.rxStun.allocOk++;
570
+ conn.allocateResponses++;
571
+ this.lockAllocateForm(conn, data);
420
572
  }
421
573
  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 });
574
+ const errorInfo = parseStunResponse(data);
575
+ conn.allocateResponses++;
576
+ if (this.rxStun.allocErr++ === 0) {
577
+ this.logger.warn('[RELAY] allocate/binding ERROR from relay', { connectionId: relayInfo.id, type: '0x' + type.toString(16), bytes: data.length, errorCode: errorInfo?.errorCode, errorReason: errorInfo?.errorReason, hex: Buffer.from(data).toString('hex') });
578
+ }
579
+ if (type === 0x0113 && errorInfo?.errorCode === 452) {
580
+ if (!conn.allocateLocked) conn.refused = true;
581
+ this.advanceAllocateForm(conn, relayInfo, data, errorInfo);
582
+ }
423
583
  }
424
584
  else if (type === 0x0802) {
425
585
  this.rxStun.pong++;
@@ -430,30 +590,186 @@ export class WaManualRelay extends EventEmitter {
430
590
  }
431
591
 
432
592
  sendStunAllocateOnOpen(conn, relayInfo) {
433
- const connectionId = relayInfo.id;
434
- if (!relayInfo.rawToken || relayInfo.rawToken.length === 0) {
435
- this.logger.debug('allocate skipped, no relay token', { connectionId });
436
- return;
437
- }
438
593
  if (!relayInfo.key) {
439
- this.logger.debug('allocate skipped, no relay key', { connectionId });
440
594
  return;
441
595
  }
442
- if (!this.audioSsrc) {
443
- this.logger.debug('allocate skipped, no ssrc yet', { connectionId });
596
+ const ssrc = this.subscriptionSsrc || this.audioSsrc;
597
+ if (!ssrc) {
444
598
  return;
445
599
  }
600
+ if (conn.mode === 'dtls') {
601
+ this.sendBindingRegistrations(conn, relayInfo, ssrc);
602
+ }
603
+ this.sendAllocate(conn, relayInfo);
604
+ }
605
+
606
+ sendBindingRegistrations(conn, relayInfo, ssrc) {
446
607
  const hmacKey = TEXT_ENCODER.encode(relayInfo.key);
608
+ const subs = buildSenderSubscriptions(ssrc);
609
+ const remoteUfrag = relayInfo.authToken || relayInfo.token;
610
+ if (remoteUfrag) {
611
+ const username = TEXT_ENCODER.encode(`${remoteUfrag}:${conn.localUfrag}`);
612
+ this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true, conn.stunTransactionId)));
613
+ }
614
+ if (relayInfo.token && relayInfo.token !== remoteUfrag) {
615
+ const username = TEXT_ENCODER.encode(`${relayInfo.token}:${conn.localUfrag}`);
616
+ this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true, conn.stunTransactionId)));
617
+ }
618
+ this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(undefined, undefined, subs, false, false, conn.stunTransactionId)));
619
+ }
620
+
621
+ resolveRelayTarget(conn, relayInfo) {
622
+ const dialed = { ip: relayInfo.ip, port: conn.dialPort ?? relayInfo.port };
623
+ if (conn.mode === 'dtls') {
624
+ return dialed;
625
+ }
626
+ try {
627
+ const remote = conn.socket?.remoteAddress();
628
+ if (remote?.address && remote.port) {
629
+ return { ip: remote.address, port: remote.port };
630
+ }
631
+ }
632
+ catch (err) {
633
+ this.logger.debug('[RELAY] remote address unavailable', { message: toError(err).message });
634
+ }
635
+ return dialed;
636
+ }
637
+
638
+ getAllocateCandidates(conn, relayInfo) {
639
+ if (conn.allocateCandidates) {
640
+ return conn.allocateCandidates;
641
+ }
642
+ const target = this.resolveRelayTarget(conn, relayInfo);
643
+ const ports = [target.port, relayInfo.port, conn.dialPort, relayInfo.fallbackPort].filter((port, index, all) => Number.isInteger(port) && port > 0 && all.indexOf(port) === index);
644
+ const candidates = ports.map((port) => ({ form: 'exact', ip: target.ip, port }));
645
+ candidates.push({ form: 'mapped', ip: target.ip, port: ports[0] });
646
+ candidates.push({ form: 'none', ip: target.ip, port: ports[0] });
647
+ conn.allocateCandidates = candidates;
648
+ return candidates;
649
+ }
650
+
651
+ lockAllocateForm(conn, data) {
652
+ if (conn.allocateLocked) {
653
+ return;
654
+ }
655
+ const attempt = conn.allocateAttempts.get(Buffer.from(data.subarray(8, 20)).toString('hex'));
656
+ if (attempt) {
657
+ conn.allocateStage = attempt.stage;
658
+ conn.stunTransactionId = attempt.transactionId;
659
+ }
660
+ conn.allocateLocked = true;
661
+ conn.allocateExhausted = false;
662
+ conn.refused = false;
663
+ this.rejectedModes.delete(`${conn.relayInfo.ip}|${conn.mode}`);
664
+ this.logger.info('[RELAY] allocate accepted', { connectionId: conn.relayInfo.id, route: { mode: conn.mode, port: conn.dialPort }, relayedAddress: attempt?.candidate ?? null });
665
+ this.markRelayProven(conn, 'allocate');
666
+ }
667
+
668
+ markRelayProven(conn, via) {
669
+ if (conn.proven) {
670
+ return;
671
+ }
672
+ conn.proven = true;
673
+ const relayInfo = conn.relayInfo;
674
+ this.logger.info('[RELAY] relay proven', { connectionId: relayInfo.id, via });
675
+ if (this.answeredRelayNames.has(relayInfo.name)) {
676
+ return;
677
+ }
678
+ this.answeredRelayNames.add(relayInfo.name);
679
+ this.emit('relay_answered', { name: relayInfo.name, ip: relayInfo.ip, port: relayInfo.port, rttMs: conn.openedAt ? Date.now() - conn.openedAt : undefined });
680
+ }
681
+
682
+ advanceAllocateForm(conn, relayInfo, data, errorInfo) {
683
+ if (conn.allocateLocked || conn.allocateExhausted) {
684
+ return;
685
+ }
686
+ const attempt = conn.allocateAttempts.get(Buffer.from(data.subarray(8, 20)).toString('hex'));
687
+ if (!attempt || attempt.stage !== conn.allocateStage) {
688
+ return;
689
+ }
690
+ const candidates = this.getAllocateCandidates(conn, relayInfo);
691
+ const mismatch = parseRelayedAddressMismatch(errorInfo?.errorReason);
692
+ const learned = mismatch?.relay;
693
+ if (learned && !candidates.some((entry) => entry.form === 'exact' && entry.ip === learned.ip && entry.port === learned.port)) {
694
+ candidates.splice(conn.allocateStage + 1, 0, { form: 'exact', ip: learned.ip, port: learned.port });
695
+ }
696
+ const echoedSame = Boolean(mismatch?.destination && mismatch?.relay && mismatch.destination.ip === mismatch.relay.ip && mismatch.destination.port === mismatch.relay.port);
697
+ if (echoedSame || conn.allocateStage >= candidates.length - 1) {
698
+ this.handleAllocateExhausted(conn, relayInfo, errorInfo);
699
+ return;
700
+ }
701
+ this.logger.warn('[RELAY] relayed address rejected, trying next candidate', { connectionId: relayInfo.id, rejected: attempt.candidate, next: candidates[conn.allocateStage + 1], serverRead: mismatch?.destination ?? null, serverRelay: mismatch?.relay ?? null });
702
+ conn.allocateStage++;
703
+ conn.stunTransactionId = randomBytes(12);
704
+ this.sendAllocate(conn, relayInfo);
705
+ }
447
706
 
448
- const streamSsrcs = this.streamSsrcs
449
- ? [...this.streamSsrcs]
450
- : [this.audioSsrc, 0, 0, this.videoSsrc || 0, 0, 0, 0, 0, 0];
451
- streamSsrcs[0] = this.audioSsrc;
452
- const descriptors = createWasmStreamDescriptors(streamSsrcs);
453
- const packet = buildAllocateForRelay(relayInfo.rawToken, descriptors, hmacKey, relayInfo.ip, relayInfo.port);
454
- conn.allocatePacket = toArrayBuffer(packet);
707
+ handleAllocateExhausted(conn, relayInfo, errorInfo) {
708
+ conn.allocateExhausted = true;
709
+ conn.refused = true;
710
+ conn.allocatePacket = null;
711
+ this.logger.warn('[RELAY] every relayed address candidate was rejected', { connectionId: relayInfo.id, route: { mode: conn.mode, port: conn.dialPort }, errorReason: errorInfo?.errorReason });
712
+ this.rejectedModes.add(`${relayInfo.ip}|${conn.mode}`);
713
+ if (this.advanceRoute(conn, 'allocate_rejected')) {
714
+ void this.ensureConnection(relayInfo);
715
+ return;
716
+ }
717
+ if (this.activateStandbyRelay(conn)) {
718
+ return;
719
+ }
720
+ if (conn.allocateRounds < 2) {
721
+ conn.allocateRounds += 1;
722
+ this.applyRoute(conn, 0);
723
+ this.closePeerObjects(conn);
724
+ conn.state = ConnectionState.Closed;
725
+ conn.retryTimer = setTimeout(() => {
726
+ conn.retryTimer = null;
727
+ if (this.connections.get(relayInfo.id) !== conn) return;
728
+ void this.ensureConnection(relayInfo);
729
+ }, 3000 * conn.allocateRounds);
730
+ conn.retryTimer.unref?.();
731
+ return;
732
+ }
733
+ this.logger.error('[RELAY] allocate failed on every route and relay', { connectionId: relayInfo.id, rounds: conn.allocateRounds });
734
+ }
735
+
736
+ activateStandbyRelay(conn) {
737
+ const next = this.standbyRelays.shift();
738
+ if (!next) {
739
+ return false;
740
+ }
741
+ const failedId = conn.relayInfo.id;
742
+ this.failedRelays.add(failedId);
743
+ this.relayMap.delete(failedId);
744
+ this.connections.delete(failedId);
745
+ if (conn.retryTimer) {
746
+ clearTimeout(conn.retryTimer);
747
+ conn.retryTimer = null;
748
+ }
749
+ this.closePeerObjects(conn);
750
+ conn.state = ConnectionState.Failed;
751
+ this.relayMap.set(next.id, next);
752
+ this.logger.warn('[RELAY] switching to standby relay', { from: failedId, to: next.id });
753
+ void this.ensureConnection(next);
754
+ return true;
755
+ }
756
+
757
+ sendAllocate(conn, relayInfo) {
758
+ if (conn.allocateExhausted) {
759
+ return;
760
+ }
761
+ if (!relayInfo.rawToken || relayInfo.rawToken.length === 0 || !relayInfo.key || !this.audioSsrc) {
762
+ return;
763
+ }
764
+ const candidates = this.getAllocateCandidates(conn, relayInfo);
765
+ const candidate = candidates[Math.min(conn.allocateStage, candidates.length - 1)];
766
+ const descriptors = this.streamSsrcs ? createWasmStreamDescriptors(this.streamSsrcs) : buildSSRCSubscriptionList([this.audioSsrc], [this.subscriptionSsrc], this.selfPid, this.peerPid);
767
+ conn.allocatePacket = toArrayBuffer(buildAllocateForRelay(relayInfo.rawToken, descriptors, TEXT_ENCODER.encode(relayInfo.key), candidate.ip, candidate.port, conn.stunTransactionId, { relayedAddress: candidate.form }));
768
+ const attemptKey = Buffer.from(conn.stunTransactionId).toString('hex');
769
+ if (!conn.allocateAttempts.has(attemptKey)) {
770
+ conn.allocateAttempts.set(attemptKey, { stage: conn.allocateStage, transactionId: conn.stunTransactionId, candidate });
771
+ }
455
772
  this.sendToChannel(conn, conn.allocatePacket);
456
- this.logger.trace('allocate sent', { connectionId, size: packet.length });
457
773
  }
458
774
 
459
775
  sendToChannel(conn, data) {
@@ -463,12 +779,14 @@ export class WaManualRelay extends EventEmitter {
463
779
  conn.stats.sentPackets++;
464
780
  conn.stats.sentBytes += byteLengthOf(data);
465
781
  this.stats.sent++;
466
- } catch (err) {
467
- this.logger.trace('sendToChannel failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
468
- }
782
+ } catch { }
469
783
  }
470
784
 
471
785
  closePeerObjects(conn) {
786
+ if (conn.fallbackTimer) {
787
+ clearTimeout(conn.fallbackTimer);
788
+ conn.fallbackTimer = null;
789
+ }
472
790
  if (conn.keepaliveTimer) {
473
791
  clearInterval(conn.keepaliveTimer);
474
792
  conn.keepaliveTimer = null;
@@ -477,9 +795,9 @@ export class WaManualRelay extends EventEmitter {
477
795
  clearInterval(conn.iceConsentTimer);
478
796
  conn.iceConsentTimer = null;
479
797
  }
480
- try { conn.dataChannel?.close?.(); } catch (err) { this.logger.trace('datachannel close failed', { message: toError(err).message }); }
481
- try { conn.dtlsClient?.close?.(); } catch (err) { this.logger.trace('dtls close failed', { message: toError(err).message }); }
482
- try { conn.socket?.close?.(); } catch (err) { this.logger.trace('socket close failed', { message: toError(err).message }); }
798
+ try { conn.dataChannel?.close?.(); } catch { }
799
+ try { conn.dtlsClient?.close?.(); } catch { }
800
+ try { conn.socket?.close?.(); } catch { }
483
801
  conn.socket = null;
484
802
  conn.dtlsClient = null;
485
803
  conn.dataChannel = null;
@@ -489,9 +807,20 @@ export class WaManualRelay extends EventEmitter {
489
807
  if (conn.keepaliveTimer) clearInterval(conn.keepaliveTimer);
490
808
  conn.keepaliveTimer = setInterval(() => {
491
809
  if (conn.state !== ConnectionState.Open || !conn.dataChannel) return;
810
+ if (Date.now() - conn.lastInboundAt > 15_000) {
811
+ this.handleRelayLoss(conn);
812
+ return;
813
+ }
492
814
 
815
+ if (!conn.proven && conn.answered && !conn.refused && conn.allocateResponses === 0 && Date.now() - conn.openedAt >= 3000) {
816
+ this.markRelayProven(conn, 'answered');
817
+ }
818
+ conn.keepaliveTicks++;
819
+ if (conn.keepaliveTicks % 5 === 0) {
820
+ this.logger.info('[RELAY] status', { connectionId: conn.relayInfo.id, mode: conn.mode, port: conn.dialPort, answered: conn.answered, locked: conn.allocateLocked, sentPackets: conn.stats.sentPackets, receivedPackets: conn.stats.receivedPackets, rx: this.rxStun });
821
+ }
493
822
  if (conn.allocatePacket) this.sendToChannel(conn, conn.allocatePacket);
494
- this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
823
+ this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing(conn.stunTransactionId)));
495
824
  }, CONFIG.KEEPALIVE_INTERVAL_MS);
496
825
  }
497
826
 
@@ -505,9 +834,7 @@ export class WaManualRelay extends EventEmitter {
505
834
  conn.stats.sentPackets++;
506
835
  conn.stats.sentBytes += byteLengthOf(packet);
507
836
  this.stats.sent++;
508
- } catch (err) {
509
- this.logger.trace('flush send failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
510
- }
837
+ } catch { }
511
838
  }
512
839
  }
513
840
 
@@ -537,36 +864,78 @@ export class WaManualRelay extends EventEmitter {
537
864
  conn.stats.sentPackets++;
538
865
  conn.stats.sentBytes += byteLengthOf(data);
539
866
  this.stats.sent++;
540
- } catch (err) {
541
- this.logger.trace('sendToRelay failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
542
- }
867
+ } catch { }
543
868
  } else {
544
869
  this.bufferPacket(conn, data);
545
- void this.ensureConnection(conn.relayInfo);
870
+ if (!conn.recovering) void this.ensureConnection(conn.relayInfo);
546
871
  }
547
872
  }
548
873
  }
549
874
 
875
+ pickMediaConnections() {
876
+ const open = [];
877
+ for (const [, conn] of this.connections) {
878
+ if (conn.state === ConnectionState.Open && conn.dataChannel) open.push(conn);
879
+ }
880
+ const proven = open.filter((conn) => conn.proven);
881
+ if (proven.length > 0) return proven;
882
+ const viable = open.filter((conn) => !conn.refused);
883
+ return viable.length > 0 ? viable : open;
884
+ }
885
+
550
886
  broadcast(data) {
551
887
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
552
888
  const isAudio = bytes.length < 2 || (bytes[1] & 0x7f) !== PayloadType.H264;
553
889
  let sentAny = false;
554
- for (const [, conn] of this.connections) {
555
- if (conn.state === ConnectionState.Open && conn.dataChannel) {
556
- try {
557
- conn.dataChannel.send(data, isAudio);
558
- conn.stats.sentPackets++;
559
- conn.stats.sentBytes += byteLengthOf(data);
560
- this.stats.sent++;
561
- sentAny = true;
562
- } catch (err) {
563
- this.logger.trace('broadcast send failed', { connectionId: conn.relayInfo.id, message: toError(err).message });
564
- }
565
- }
890
+ for (const conn of this.pickMediaConnections()) {
891
+ try {
892
+ conn.dataChannel.send(data, isAudio);
893
+ conn.stats.sentPackets++;
894
+ conn.stats.sentBytes += byteLengthOf(data);
895
+ this.stats.sent++;
896
+ sentAny = true;
897
+ } catch { }
566
898
  }
567
899
  return sentAny;
568
900
  }
569
901
 
902
+ handleRelayLoss(conn) {
903
+ if (conn.state !== ConnectionState.Open) return;
904
+ if (!conn.answered) {
905
+ if (this.advanceRoute(conn, 'relay_lost_unanswered')) {
906
+ void this.ensureConnection(conn.relayInfo);
907
+ return;
908
+ }
909
+ if (conn.routes.length > 1) {
910
+ this.applyRoute(conn, 0);
911
+ }
912
+ }
913
+ this.logger.warn('[RELAY] relay lost', { connectionId: conn.relayInfo.id, port: conn.dialPort, silentMs: Date.now() - conn.lastInboundAt, answered: conn.answered, rx: this.rxStun });
914
+ this.closePeerObjects(conn);
915
+ conn.state = ConnectionState.Closed;
916
+ if (!conn.recovering) conn.retryCount = 0;
917
+ conn.recovering = true;
918
+ this.emit('relay_lost', { connectionId: conn.relayInfo.id, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
919
+ this.scheduleRelayRetry(conn);
920
+ }
921
+
922
+ scheduleRelayRetry(conn) {
923
+ if (conn.retryCount >= this.retrySchedule.length) {
924
+ this.emit('relay_failed', { connectionId: conn.relayInfo.id, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
925
+ return;
926
+ }
927
+ const delay = this.retrySchedule[conn.retryCount];
928
+ conn.retryCount += 1;
929
+ conn.retryTimer = setTimeout(async () => {
930
+ conn.retryTimer = null;
931
+ if (this.connections.get(conn.relayInfo.id) !== conn) return;
932
+ this.emit('relay_retrying', { connectionId: conn.relayInfo.id, attempt: conn.retryCount, anyOpen: this.hasConnection(), max: this.retrySchedule.length });
933
+ await this.ensureConnection(conn.relayInfo);
934
+ if (conn.state !== ConnectionState.Open) this.scheduleRelayRetry(conn);
935
+ }, delay);
936
+ conn.retryTimer.unref?.();
937
+ }
938
+
570
939
  hasConnection() {
571
940
  for (const [, conn] of this.connections) {
572
941
  if (conn.state === ConnectionState.Open) return true;
@@ -600,9 +969,17 @@ export class WaManualRelay extends EventEmitter {
600
969
  }
601
970
 
602
971
  cleanup() {
603
- for (const [, conn] of this.connections) this.closePeerObjects(conn);
972
+ for (const [, conn] of this.connections) {
973
+ if (conn.retryTimer) clearTimeout(conn.retryTimer);
974
+ conn.retryTimer = null;
975
+ this.closePeerObjects(conn);
976
+ }
604
977
  this.connections.clear();
605
978
  this.relayMap.clear();
979
+ this.standbyRelays = [];
980
+ this.failedRelays.clear();
981
+ this.answeredRelayNames.clear();
982
+ this.rejectedModes.clear();
606
983
  this.globalBuffer = [];
607
984
  this.globalBufferedBytes = 0;
608
985
  }