@hiroosy/baileys-lite 0.3.8 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hiroosy/baileys-lite",
3
- "version": "0.3.8",
4
- "description": "A Lightweight Baileys built with NodeJs 18+",
3
+ "version": "0.3.9",
4
+ "description": "A Lightweight Baileys built with Pure NodeJs 18+",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/HirooSy/baileys-lite.git"
@@ -5,7 +5,7 @@ import { concatBytes, EMPTY_BYTES, readUInt32BE, toArrayBuffer } from '../bytes.
5
5
  import { derivePerJidSrtpKey } from '../crypto/encryption.js';
6
6
  import { SrtpSession } from '../crypto/srtp.js';
7
7
  import { SrtcpSendContext } from '../crypto/rtcp.js';
8
- import { generateSecureSsrc } from '../crypto/ssrc.js';
8
+ import { deriveWasmRelayStreamSsrcs, generateSecureSsrc } from '../crypto/ssrc.js';
9
9
  import { WaAppDataStream } from '../app-data/WaAppDataStream.js';
10
10
  import { buildScreenShareStanza, parseScreenShareNode, WA_SCREEN_SHARE_STATE } from '../signaling/screen-share.js';
11
11
  import { MLowCodec } from '../media/mlow-codec.js';
@@ -32,6 +32,9 @@ export class WaCallMediaSession {
32
32
  audioEngine;
33
33
  initialTransportSent = false;
34
34
  outgoingPreacceptSent = false;
35
+ answeredRelays = new Map();
36
+ announcedRelayNames = new Set();
37
+ relayLatencyOpened = false;
35
38
  selfSsrc = 0;
36
39
  selfSsrcJid = '';
37
40
  peerSsrcs = [];
@@ -110,6 +113,9 @@ export class WaCallMediaSession {
110
113
  this.sctpRelay.on('relay_connected', () => {
111
114
  this.onRelayConnected();
112
115
  });
116
+ this.sctpRelay.on('relay_answered', (detail) => {
117
+ this.onRelayAnswered(detail);
118
+ });
113
119
  this.sctpRelay.on('relay_receive', (relayInfo) => {
114
120
  this.onRelayData(relayInfo.data);
115
121
  });
@@ -279,24 +285,31 @@ export class WaCallMediaSession {
279
285
  });
280
286
  }
281
287
  }
282
- async sendIncomingRelayLatency() {
288
+ onRelayAnswered(detail) {
289
+ if (!detail?.name || this.answeredRelays.has(detail.name))
290
+ return;
291
+ this.answeredRelays.set(detail.name, detail.rttMs);
292
+ if (this.relayLatencyOpened) {
293
+ void this.announceRelayLatency();
294
+ }
295
+ }
296
+ async announceRelayLatency(isEligible = (ep) => this.answeredRelays.has(ep.relayName)) {
283
297
  if (!this.info.relayData)
284
298
  return;
285
299
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
286
300
  const callId = this.info.callId;
287
301
  const callCreator = this.info.callCreator;
288
302
  const destinationJids = this.info.relayData.participantJids || [];
289
- const seenRelayNames = new Set();
290
303
  for (const ep of this.info.relayData.endpoints) {
291
304
  const name = ep.relayName || '';
292
- if (!name || seenRelayNames.has(name))
305
+ if (!name || ep.ip.includes(':') || this.announcedRelayNames.has(name) || !isEligible(ep))
293
306
  continue;
294
- seenRelayNames.add(name);
307
+ this.announcedRelayNames.add(name);
295
308
  try {
296
309
  const relayData = [
297
310
  {
298
311
  relayName: name,
299
- latency: ep.c2rRtt || 0,
312
+ latency: ep.c2rRtt ?? this.answeredRelays.get(name) ?? 0,
300
313
  addressBytes: ep.addressBytes
301
314
  }
302
315
  ];
@@ -304,13 +317,23 @@ export class WaCallMediaSession {
304
317
  await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
305
318
  }
306
319
  catch (err) {
307
- this.logger.error('error sending incoming relaylatency', {
320
+ this.announcedRelayNames.delete(name);
321
+ this.logger.error('error sending relaylatency', {
308
322
  relayName: name,
309
323
  message: toError(err).message
310
324
  });
311
325
  }
312
326
  }
313
327
  }
328
+ async sendIncomingRelayLatency() {
329
+ if (!this.info.relayData)
330
+ return;
331
+ this.relayLatencyOpened = true;
332
+ const dialed = new Set(this.selectRelayEndpoints(this.info.relayData.endpoints)
333
+ .slice(0, this.sctpRelay.maxActiveRelays)
334
+ .map((ep) => ep.relayName));
335
+ await this.announceRelayLatency((ep) => dialed.size === 0 || dialed.has(ep.relayName) || this.answeredRelays.has(ep.relayName));
336
+ }
314
337
  async handleCallAccept(node, peerJid) {
315
338
  const nodeInfo = extractNodeInfo(node);
316
339
  if (!nodeInfo)
@@ -459,31 +482,8 @@ export class WaCallMediaSession {
459
482
  const meId = this.deps.authClient.getCurrentCredentials()?.meJid ?? '';
460
483
  const callId = this.info.callId;
461
484
  const callCreator = this.info.callCreator;
462
- const destinationJids = this.info.relayData.participantJids || [];
463
- const seenRelayNames = new Set();
464
- for (const ep of this.info.relayData.endpoints) {
465
- const name = ep.relayName || '';
466
- if (!name || seenRelayNames.has(name))
467
- continue;
468
- seenRelayNames.add(name);
469
- try {
470
- const relayData = [
471
- {
472
- relayName: name,
473
- latency: ep.c2rRtt || 0,
474
- addressBytes: ep.addressBytes
475
- }
476
- ];
477
- const relayLatencyNode = buildRelayLatencyStanza(this.info.peerJid, callId, callCreator, relayData, destinationJids, meId);
478
- await this.deps.lowLevelCoordinator.sendNode(relayLatencyNode);
479
- }
480
- catch (err) {
481
- this.logger.error('error sending relaylatency', {
482
- relayName: name,
483
- message: toError(err).message
484
- });
485
- }
486
- }
485
+ this.relayLatencyOpened = true;
486
+ await this.announceRelayLatency();
487
487
  if (!this.initialTransportSent) {
488
488
  try {
489
489
  const basePeerJid = toUserJid(peerJid);
@@ -1065,6 +1065,9 @@ export class WaCallMediaSession {
1065
1065
  this.audioEngine.stop();
1066
1066
  this.videoEngine.stop();
1067
1067
  this.sctpRelay.cleanup();
1068
+ this.answeredRelays.clear();
1069
+ this.announcedRelayNames.clear();
1070
+ this.relayLatencyOpened = false;
1068
1071
  if (this.rtcpTimer) {
1069
1072
  clearInterval(this.rtcpTimer);
1070
1073
  this.rtcpTimer = null;
@@ -1355,11 +1358,11 @@ export class WaCallMediaSession {
1355
1358
  this.srtpErrorCount++;
1356
1359
  }
1357
1360
  }
1358
- async connectRelays(endpoints) {
1361
+ selectRelayEndpoints(endpoints) {
1359
1362
  const seen = new Set();
1360
1363
  const uniqueEndpoints = [];
1361
1364
  for (const ep of endpoints) {
1362
- if ((ep.protocol ?? 0) !== 0)
1365
+ if ((ep.protocol ?? 0) !== 0 || ep.ip.includes(':'))
1363
1366
  continue;
1364
1367
  const key = `${ep.ip}:${ep.port}`;
1365
1368
  if (!seen.has(key)) {
@@ -1381,30 +1384,40 @@ export class WaCallMediaSession {
1381
1384
  usable[0] ??
1382
1385
  null;
1383
1386
  }
1384
- const WA_RELAY_PORT = 3478;
1385
- const relays = chosen
1386
- ? [
1387
- {
1388
- ip: chosen.ip,
1389
- port: WA_RELAY_PORT,
1390
- token: chosen.token,
1391
- authToken: chosen.authToken,
1392
- rawAuthToken: chosen.rawAuthToken,
1393
- rawToken: chosen.rawToken,
1394
- key: chosen.key,
1395
- relayId: chosen.relayId,
1396
- name: chosen.relayName || `${chosen.ip}:${WA_RELAY_PORT}`,
1397
- authTokenId: chosen.authTokenId,
1398
- isFna: chosen.isFna
1399
- }
1400
- ]
1401
- : [];
1387
+ const ordered = chosen ? [chosen] : [];
1388
+ const orderedAddresses = new Set(chosen ? [chosen.ip] : []);
1389
+ for (const ep of usable) {
1390
+ if (ordered.length >= 4)
1391
+ break;
1392
+ if (orderedAddresses.has(ep.ip))
1393
+ continue;
1394
+ orderedAddresses.add(ep.ip);
1395
+ ordered.push(ep);
1396
+ }
1397
+ return ordered;
1398
+ }
1399
+ async connectRelays(endpoints) {
1400
+ const ordered = this.selectRelayEndpoints(endpoints);
1401
+ const relays = ordered.map((ep) => ({
1402
+ ip: ep.ip,
1403
+ port: ep.port || 3478,
1404
+ token: ep.token,
1405
+ authToken: ep.authToken,
1406
+ rawAuthToken: ep.rawAuthToken,
1407
+ rawToken: ep.rawToken,
1408
+ key: ep.key,
1409
+ relayId: ep.relayId,
1410
+ name: ep.relayName || `${ep.ip}:${ep.port || 3478}`,
1411
+ authTokenId: ep.authTokenId,
1412
+ isFna: ep.isFna
1413
+ }));
1402
1414
  if (relays.length === 0) {
1403
1415
  this.logger.error('no relay configs', { callId: this.info.callId });
1404
1416
  return;
1405
1417
  }
1406
1418
  this.sctpRelay.setParticipantIds(this.info.relayData?.selfPid, this.info.relayData?.peerPid);
1407
1419
  this.sctpRelay.setSsrc(this.selfSsrc);
1420
+ this.sctpRelay.setStreamSsrcs(this.selfSsrcJid ? deriveWasmRelayStreamSsrcs(this.info.callId, this.selfSsrcJid) : null);
1408
1421
  if (this.info.mediaType === CallMediaType.Video) {
1409
1422
  this.sctpRelay.setVideoSsrc(this.videoSsrc);
1410
1423
  }
@@ -101,6 +101,7 @@ export class WaAudioEngine {
101
101
  this.extMaxBuffer = Math.floor(this.sampleRate);
102
102
  this.streamPreBufferSize = Math.floor(this.sampleRate * 0.3);
103
103
  this.streamHighWater = Math.floor(this.sampleRate * 0.6);
104
+ this.streamMaxBacklog = Math.floor(this.sampleRate * 1);
104
105
  }
105
106
  setAudioSender(sender) {
106
107
  this.audioSender = sender;
@@ -267,6 +268,8 @@ export class WaAudioEngine {
267
268
  if (WaAudioEngine.isRemoteSource(source)) {
268
269
  args.push('-user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5');
269
270
  }
271
+ if (/\.m3u8/i.test(source))
272
+ args.push('-live_start_index', '-1');
270
273
  args.push('-i', source, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', String(this.sampleRate), '-acodec', 'pcm_s16le', '-f', 's16le', 'pipe:1');
271
274
  const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'ignore'] });
272
275
  this.streamProc = proc;
@@ -327,15 +330,14 @@ export class WaAudioEngine {
327
330
  this.streamQueue.shift();
328
331
  }
329
332
  }
330
- if (this.streamQueue.length > 0) {
331
- if (!this.streamPaused) {
332
- this.streamPaused = true;
333
- proc.stdout.pause();
334
- }
333
+ let queued = 0;
334
+ for (const chunk of this.streamQueue)
335
+ queued += chunk.length;
336
+ if (queued > this.streamMaxBacklog) {
337
+ proc.stdout?.pause();
335
338
  }
336
- else if (this.streamPaused) {
337
- this.streamPaused = false;
338
- proc.stdout.resume();
339
+ else {
340
+ proc.stdout?.resume();
339
341
  }
340
342
  }
341
343
  isStreamFinished() {
@@ -5,7 +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, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, parseStunResponse } from './stun.js';
8
+ import { buildAllocateForRelay, buildBindingRequest, buildBindingRequestWithSubs, buildRelayBindingSuccess, buildSenderSubscriptions, buildSSRCSubscriptionList, buildWhatsAppPing, createWasmStreamDescriptors, parseRelayedAddressMismatch, parseStunResponse } from './stun.js';
9
+ import { randomBytes } from '../crypto/primitives.js';
9
10
  import { PayloadType } from '../types.js';
10
11
 
11
12
  const CONFIG = {
@@ -40,12 +41,18 @@ function randomUfrag() {
40
41
  }
41
42
 
42
43
  export class WaManualRelay extends EventEmitter {
44
+ rejectedModes = new Set();
45
+ answeredRelayNames = new Set();
46
+ maxActiveRelays = 3;
43
47
  logger;
44
48
  connections = new Map();
45
49
  relayMap = new Map();
50
+ standbyRelays = [];
51
+ failedRelays = new Set();
46
52
  audioSsrc = 0;
47
53
  videoSsrc = 0;
48
54
  subscriptionSsrc = 0;
55
+ streamSsrcs = null;
49
56
  selfPid = 0;
50
57
  peerPid = 0;
51
58
  rxStun = { bindReq: 0, bindAnswered: 0, allocOk: 0, allocErr: 0, pong: 0, other: 0 };
@@ -54,10 +61,13 @@ export class WaManualRelay extends EventEmitter {
54
61
  globalBufferedBytes = 0;
55
62
  stats = { sent: 0, received: 0, connected: 0 };
56
63
  retrySchedule = [1000, 2000, 4000];
64
+ transports = ['dtls', 'raw'];
57
65
 
58
66
  constructor(options = {}) {
59
67
  super();
60
68
  this.logger = options.logger ?? createNoopLogger();
69
+ this.transports = options.transports ?? this.transports;
70
+ this.maxActiveRelays = options.maxActiveRelays ?? this.maxActiveRelays;
61
71
  }
62
72
 
63
73
  setSsrc(ssrc) {
@@ -77,6 +87,10 @@ export class WaManualRelay extends EventEmitter {
77
87
  this.videoSsrc = ssrc;
78
88
  }
79
89
 
90
+ setStreamSsrcs(ssrcs) {
91
+ this.streamSsrcs = ssrcs;
92
+ }
93
+
80
94
  setSubscriptionSsrc(ssrc) {
81
95
  this.subscriptionSsrc = ssrc;
82
96
  }
@@ -86,33 +100,54 @@ export class WaManualRelay extends EventEmitter {
86
100
  return authTokenId ? `${base}#${authTokenId}` : base;
87
101
  }
88
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
+
89
122
  async configureRelays(relays) {
90
123
  this.configuring = true;
91
- for (const relay of relays) {
92
- const port = relay.port || CONFIG.TRUE_WEB_CLIENT_RELAY_PORT;
93
- const connectionId = this.makeConnectionId(relay.ip, port, relay.authTokenId);
94
- this.relayMap.set(connectionId, {
95
- id: connectionId,
96
- ip: relay.ip,
97
- port,
98
- token: relay.token,
99
- authToken: relay.authToken,
100
- rawAuthToken: relay.rawAuthToken,
101
- rawToken: relay.rawToken,
102
- key: relay.key,
103
- relayId: relay.relayId,
104
- name: relay.name || 'unknown',
105
- authTokenId: relay.authTokenId,
106
- isFna: relay.isFna
107
- });
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
+ }
108
132
  }
133
+ this.standbyRelays = infos.filter((info) => !this.relayMap.has(info.id));
109
134
  const connectionPromises = [];
110
135
  for (const [, relayInfo] of this.relayMap) {
111
136
  if (!this.connections.has(relayInfo.id)) {
112
137
  connectionPromises.push(this.ensureConnection(relayInfo));
113
138
  }
114
139
  }
115
- await Promise.all(connectionPromises);
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
+ }
116
151
  this.configuring = false;
117
152
  if (this.globalBuffer.length > 0) {
118
153
  for (const item of this.globalBuffer) this.sendToRelay(item.ip, item.port, item.data);
@@ -121,9 +156,64 @@ export class WaManualRelay extends EventEmitter {
121
156
  }
122
157
  }
123
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
+
124
213
  getOrCreateConnection(relayInfo) {
125
214
  let conn = this.connections.get(relayInfo.id);
126
215
  if (!conn) {
216
+ const routes = this.buildRoutes(relayInfo);
127
217
  conn = {
128
218
  state: ConnectionState.None,
129
219
  relayInfo,
@@ -141,6 +231,25 @@ export class WaManualRelay extends EventEmitter {
141
231
  recovering: false,
142
232
  lastInboundAt: 0,
143
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(),
144
253
  stats: { sentPackets: 0, receivedPackets: 0, sentBytes: 0, receivedBytes: 0 }
145
254
  };
146
255
  this.connections.set(relayInfo.id, conn);
@@ -155,11 +264,17 @@ export class WaManualRelay extends EventEmitter {
155
264
  }
156
265
  const promise = this.connect(conn);
157
266
  conn.connectPromise = promise;
267
+ let failed = false;
158
268
  try {
159
269
  await promise;
160
- } catch { } finally {
270
+ } catch {
271
+ failed = true;
272
+ } finally {
161
273
  conn.connectPromise = null;
162
274
  }
275
+ if (failed && this.advanceRoute(conn, 'connect_failed')) {
276
+ await this.ensureConnection(relayInfo);
277
+ }
163
278
  };
164
279
 
165
280
  performIceBinding(socket, relayInfo, conn) {
@@ -195,9 +310,9 @@ export class WaManualRelay extends EventEmitter {
195
310
  resolve(false);
196
311
  return;
197
312
  }
198
- const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
313
+ const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling', transactionId: conn.stunTransactionId });
199
314
  try {
200
- socket.send(packet, relayInfo.port, relayInfo.ip);
315
+ socket.send(packet, conn.dialPort, relayInfo.ip);
201
316
  } catch { }
202
317
  const wait = CONFIG.ICE_BINDING_TIMEOUTS_MS[attempt];
203
318
  attempt += 1;
@@ -222,7 +337,7 @@ export class WaManualRelay extends EventEmitter {
222
337
  }
223
338
  try {
224
339
  const packet = buildBindingRequest(username, hmacKey, undefined, { iceRole: 'controlling' });
225
- socket.send(packet, relayInfo.port, relayInfo.ip);
340
+ socket.send(packet, conn.dialPort, relayInfo.ip);
226
341
  } catch { }
227
342
  }, CONFIG.ICE_CONSENT_REFRESH_MS);
228
343
  }
@@ -230,12 +345,15 @@ export class WaManualRelay extends EventEmitter {
230
345
  connect = async (conn) => {
231
346
  this.closePeerObjects(conn);
232
347
  conn.state = ConnectionState.Connecting;
348
+ conn.answered = false;
233
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;
234
354
  return new Promise((resolve, reject) => {
235
355
  const socket = dgram.createSocket('udp4');
236
356
  conn.socket = socket;
237
- const targetIp = relayInfo.ip;
238
- const targetPort = relayInfo.port;
239
357
 
240
358
  let settledConn = false;
241
359
  const settle = (err) => {
@@ -254,6 +372,54 @@ export class WaManualRelay extends EventEmitter {
254
372
  }
255
373
  };
256
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
+
257
423
  const connLogger = this.logger.child?.({ connectionId: relayInfo.id }) ?? this.logger;
258
424
 
259
425
  const dtls = new DtlsClient({
@@ -279,7 +445,6 @@ export class WaManualRelay extends EventEmitter {
279
445
  if (!iceBindingDone) {
280
446
  return;
281
447
  }
282
-
283
448
  const isDtlsRecord = datagram.length >= 1 && datagram[0] >= 20 && datagram[0] <= 63;
284
449
  if (!isDtlsRecord) {
285
450
  return;
@@ -293,51 +458,21 @@ export class WaManualRelay extends EventEmitter {
293
458
  } catch { }
294
459
  }
295
460
  });
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
- });
300
461
 
301
462
  dtls.on('connected', () => {
463
+ this.logger.info('[RELAY] dtls connected', { connectionId: relayInfo.id, port: targetPort });
302
464
  dc.start();
303
465
  });
304
466
  dtls.on('error', (err) => {
305
467
  settle(err);
306
468
  });
307
469
  dc.on('open', () => {
308
- conn.state = ConnectionState.Open;
309
- this.flushBufferedPackets(conn);
310
- conn.lastInboundAt = Date.now();
311
- this.startKeepalive(conn);
312
- if (CONFIG.ICE_CONSENT_REFRESH_ENABLED) this.startIceConsentRefresh(socket, relayInfo, conn);
313
- this.sendStunAllocateOnOpen(conn, relayInfo);
314
- for (const delayMs of [50, 150, 500, 3000]) setTimeout(() => this.sendStunAllocateOnOpen(conn, conn.relayInfo), delayMs);
315
- this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
316
- this.stats.connected++;
317
- const wasRecovering = conn.recovering;
318
- if (wasRecovering) {
319
- conn.recovering = false;
320
- conn.retryCount = 0;
321
- }
322
- this.emit('relay_connected', { ip: relayInfo.ip, port: relayInfo.port });
323
- if (wasRecovering) this.emit('relay_recovered', { connectionId: relayInfo.id });
324
- settle(null);
470
+ this.handleChannelOpen(conn, relayInfo, socket, settle);
325
471
  });
326
472
  dc.on('error', (err) => {
327
473
  settle(err);
328
474
  });
329
- dc.on('message', (payload) => {
330
- conn.lastInboundAt = Date.now();
331
- this.handleRelayStun(conn, relayInfo, payload);
332
- conn.stats.receivedPackets++;
333
- conn.stats.receivedBytes += byteLengthOf(payload);
334
- this.stats.received++;
335
- this.emit('relay_receive', { ip: relayInfo.ip, port: relayInfo.port, data: payload });
336
- });
337
-
338
- conn.connectionTimeout = setTimeout(() => {
339
- settle(new Error(`relay connect timed out after ${CONFIG.CONNECTION_TIMEOUT_MS}ms`));
340
- }, CONFIG.CONNECTION_TIMEOUT_MS);
475
+ dc.on('message', receive);
341
476
 
342
477
  socket.bind(0, async () => {
343
478
  if (CONFIG.ICE_BINDING_ENABLED) {
@@ -348,16 +483,65 @@ export class WaManualRelay extends EventEmitter {
348
483
  return;
349
484
  }
350
485
  }
351
-
352
486
  iceBindingDone = true;
353
487
  dtls.start();
354
488
  });
355
489
  });
356
490
  };
357
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
+
358
541
  resendSubscriptions() {
359
542
  for (const [, conn] of this.connections) {
360
543
  if (conn.state === ConnectionState.Open && conn.dataChannel) {
544
+ if (conn.allocateExhausted) this.restartAllocateLadder(conn);
361
545
  this.sendStunAllocateOnOpen(conn, conn.relayInfo);
362
546
  }
363
547
  }
@@ -383,9 +567,19 @@ export class WaManualRelay extends EventEmitter {
383
567
  }
384
568
  else if (type === 0x0103) {
385
569
  this.rxStun.allocOk++;
570
+ conn.allocateResponses++;
571
+ this.lockAllocateForm(conn, data);
386
572
  }
387
573
  else if (type === 0x0113 || type === 0x0111) {
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 });
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
+ }
389
583
  }
390
584
  else if (type === 0x0802) {
391
585
  this.rxStun.pong++;
@@ -396,33 +590,185 @@ export class WaManualRelay extends EventEmitter {
396
590
  }
397
591
 
398
592
  sendStunAllocateOnOpen(conn, relayInfo) {
399
- if (!relayInfo.rawToken || relayInfo.rawToken.length === 0) {
400
- return;
401
- }
402
593
  if (!relayInfo.key) {
403
594
  return;
404
595
  }
405
- if (!this.audioSsrc) {
596
+ const ssrc = this.subscriptionSsrc || this.audioSsrc;
597
+ if (!ssrc) {
406
598
  return;
407
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) {
408
607
  const hmacKey = TEXT_ENCODER.encode(relayInfo.key);
409
- const subs = buildSenderSubscriptions(this.subscriptionSsrc || this.audioSsrc);
608
+ const subs = buildSenderSubscriptions(ssrc);
410
609
  const remoteUfrag = relayInfo.authToken || relayInfo.token;
411
610
  if (remoteUfrag) {
412
611
  const username = TEXT_ENCODER.encode(`${remoteUfrag}:${conn.localUfrag}`);
413
- this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
612
+ this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true, conn.stunTransactionId)));
414
613
  }
415
614
  if (relayInfo.token && relayInfo.token !== remoteUfrag) {
416
615
  const username = TEXT_ENCODER.encode(`${relayInfo.token}:${conn.localUfrag}`);
417
- this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(username, hmacKey, subs, true, true)));
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
+ }
706
+
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;
418
740
  }
419
- this.sendToChannel(conn, toArrayBuffer(buildBindingRequestWithSubs(undefined, undefined, subs, false, false)));
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
+ }
420
756
 
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);
425
- conn.allocatePacket = toArrayBuffer(packet);
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
+ }
426
772
  this.sendToChannel(conn, conn.allocatePacket);
427
773
  }
428
774
 
@@ -437,6 +783,10 @@ export class WaManualRelay extends EventEmitter {
437
783
  }
438
784
 
439
785
  closePeerObjects(conn) {
786
+ if (conn.fallbackTimer) {
787
+ clearTimeout(conn.fallbackTimer);
788
+ conn.fallbackTimer = null;
789
+ }
440
790
  if (conn.keepaliveTimer) {
441
791
  clearInterval(conn.keepaliveTimer);
442
792
  conn.keepaliveTimer = null;
@@ -462,8 +812,15 @@ export class WaManualRelay extends EventEmitter {
462
812
  return;
463
813
  }
464
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
+ }
465
822
  if (conn.allocatePacket) this.sendToChannel(conn, conn.allocatePacket);
466
- this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing()));
823
+ this.sendToChannel(conn, toArrayBuffer(buildWhatsAppPing(conn.stunTransactionId)));
467
824
  }, CONFIG.KEEPALIVE_INTERVAL_MS);
468
825
  }
469
826
 
@@ -515,26 +872,45 @@ export class WaManualRelay extends EventEmitter {
515
872
  }
516
873
  }
517
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
+
518
886
  broadcast(data) {
519
887
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
520
888
  const isAudio = bytes.length < 2 || (bytes[1] & 0x7f) !== PayloadType.H264;
521
889
  let sentAny = false;
522
- for (const [, conn] of this.connections) {
523
- if (conn.state === ConnectionState.Open && conn.dataChannel) {
524
- try {
525
- conn.dataChannel.send(data, isAudio);
526
- conn.stats.sentPackets++;
527
- conn.stats.sentBytes += byteLengthOf(data);
528
- this.stats.sent++;
529
- sentAny = true;
530
- } catch { }
531
- }
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 { }
532
898
  }
533
899
  return sentAny;
534
900
  }
535
901
 
536
902
  handleRelayLoss(conn) {
537
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 });
538
914
  this.closePeerObjects(conn);
539
915
  conn.state = ConnectionState.Closed;
540
916
  if (!conn.recovering) conn.retryCount = 0;
@@ -600,6 +976,10 @@ export class WaManualRelay extends EventEmitter {
600
976
  }
601
977
  this.connections.clear();
602
978
  this.relayMap.clear();
979
+ this.standbyRelays = [];
980
+ this.failedRelays.clear();
981
+ this.answeredRelayNames.clear();
982
+ this.rejectedModes.clear();
603
983
  this.globalBuffer = [];
604
984
  this.globalBufferedBytes = 0;
605
985
  }
@@ -1,6 +1,35 @@
1
1
  import { getNodeChildren, getNodeChildrenByTag, getNodeTextContent } from '../shim/transport.js';
2
2
  import { base64ToBytes, bytesToBase64 } from '../shim/util.js';
3
3
  import { TEXT_DECODER } from '../bytes.js';
4
+ function formatIpv6(bytes) {
5
+ const groups = new Array(8);
6
+ let bestStart = -1;
7
+ let bestLen = 0;
8
+ let runStart = -1;
9
+ let runLen = 0;
10
+ for (let i = 0; i < 8; i++) {
11
+ const value = (bytes[i * 2] << 8) | bytes[i * 2 + 1];
12
+ groups[i] = value.toString(16);
13
+ if (value === 0) {
14
+ if (runStart < 0) {
15
+ runStart = i;
16
+ }
17
+ runLen++;
18
+ if (runLen > bestLen) {
19
+ bestStart = runStart;
20
+ bestLen = runLen;
21
+ }
22
+ }
23
+ else {
24
+ runStart = -1;
25
+ runLen = 0;
26
+ }
27
+ }
28
+ if (bestLen < 2) {
29
+ return groups.join(':');
30
+ }
31
+ return `${groups.slice(0, bestStart).join(':')}::${groups.slice(bestStart + bestLen).join(':')}`;
32
+ }
4
33
  export function parseRelayFromAck(ackNode) {
5
34
  const relays = [];
6
35
  const participantJids = [];
@@ -98,37 +127,49 @@ export function parseRelayFromAck(ackNode) {
98
127
  }
99
128
  }
100
129
  }
101
- for (const rcNode of getNodeChildrenByTag(relayNode, 'te2')) {
102
- const tokenId = rcNode.attrs?.token_id || '0';
103
- const authTokenId = rcNode.attrs?.auth_token_id || '';
104
- const token = tokens.get(tokenId) || '';
105
- const authToken = authTokenId ? authTokens.get(authTokenId) : undefined;
106
- const relayName = rcNode.attrs?.relay_name || '';
107
- const protocol = rcNode.attrs?.protocol ? parseInt(rcNode.attrs.protocol, 10) : 0;
108
- const isFna = rcNode.attrs?.is_fna === '1';
109
- if (!(rcNode.content instanceof Uint8Array) || rcNode.content.length < 6)
110
- continue;
111
- const addrBytes = rcNode.content;
112
- const addressBytes = new Uint8Array(addrBytes);
113
- if (addrBytes.length === 6) {
114
- const ip = `${addrBytes[0]}.${addrBytes[1]}.${addrBytes[2]}.${addrBytes[3]}`;
115
- const port = (addrBytes[4] << 8) | addrBytes[5];
116
- relays.push({
117
- ip,
118
- port,
119
- token,
120
- authToken,
130
+ for (const endpointTag of ['te2', 'te']) {
131
+ for (const rcNode of getNodeChildrenByTag(relayNode, endpointTag)) {
132
+ const addrBytes = rcNode.content;
133
+ if (!(addrBytes instanceof Uint8Array)) {
134
+ continue;
135
+ }
136
+ const addrLength = addrBytes.length;
137
+ if (addrLength !== 6 && addrLength !== 18 && addrLength !== 24) {
138
+ continue;
139
+ }
140
+ const tokenId = rcNode.attrs?.token_id || '0';
141
+ const authTokenId = rcNode.attrs?.auth_token_id || '';
142
+ const shared = {
143
+ token: tokens.get(tokenId) || '',
144
+ authToken: authTokenId ? authTokens.get(authTokenId) : undefined,
121
145
  rawAuthToken: authTokenId ? rawAuthTokens.get(authTokenId) : undefined,
122
146
  rawToken: rawTokens.get(tokenId),
123
147
  key: relayKey,
124
148
  relayId: parseInt(rcNode.attrs?.relay_id || '0', 10),
125
- protocol,
149
+ protocol: rcNode.attrs?.protocol ? parseInt(rcNode.attrs.protocol, 10) : 0,
126
150
  c2rRtt: rcNode.attrs?.c2r_rtt ? parseInt(rcNode.attrs.c2r_rtt, 10) : undefined,
127
- relayName,
128
- addressBytes,
151
+ relayName: rcNode.attrs?.relay_name || '',
129
152
  authTokenId: authTokenId || tokenId,
130
- isFna
131
- });
153
+ isFna: rcNode.attrs?.is_fna === '1'
154
+ };
155
+ if (addrLength !== 18) {
156
+ const v4 = addrBytes.subarray(0, 6);
157
+ relays.push({
158
+ ...shared,
159
+ ip: `${v4[0]}.${v4[1]}.${v4[2]}.${v4[3]}`,
160
+ port: (v4[4] << 8) | v4[5],
161
+ addressBytes: new Uint8Array(v4)
162
+ });
163
+ }
164
+ if (addrLength !== 6) {
165
+ const v6 = addrLength === 18 ? addrBytes : addrBytes.subarray(6);
166
+ relays.push({
167
+ ...shared,
168
+ ip: formatIpv6(v6),
169
+ port: (v6[16] << 8) | v6[17],
170
+ addressBytes: new Uint8Array(v6)
171
+ });
172
+ }
132
173
  }
133
174
  }
134
175
  }
@@ -164,25 +164,141 @@ export function createWasmStreamDescriptors(streamSsrcs) {
164
164
  }
165
165
  return concatBytes(entries);
166
166
  }
167
- function encodeXorRelayedAddress(ip, port) {
168
- const data = new Uint8Array(8);
169
- data[0] = 0x00;
170
- data[1] = 0x01;
171
- writeUInt16BE(data, port ^ (STUN_MAGIC_COOKIE >>> 16), 2);
172
- const parts = ip.split('.').map(Number);
173
- const ipNum = ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
174
- writeUInt32BE(data, (ipNum ^ STUN_MAGIC_COOKIE) >>> 0, 4);
167
+ function parseIpv4Bytes(ip) {
168
+ const octets = ip.split('.');
169
+ if (octets.length !== 4) {
170
+ return null;
171
+ }
172
+ const out = new Uint8Array(4);
173
+ for (let i = 0; i < 4; i++) {
174
+ if (!/^\d{1,3}$/.test(octets[i]) || Number(octets[i]) > 255) {
175
+ return null;
176
+ }
177
+ out[i] = Number(octets[i]);
178
+ }
179
+ return out;
180
+ }
181
+ function parseIpv6Bytes(text) {
182
+ let ip = text;
183
+ const zone = ip.indexOf('%');
184
+ if (zone >= 0) {
185
+ ip = ip.slice(0, zone);
186
+ }
187
+ if (ip.includes('.')) {
188
+ const split = ip.lastIndexOf(':');
189
+ const tail = split >= 0 ? parseIpv4Bytes(ip.slice(split + 1)) : null;
190
+ if (!tail) {
191
+ return null;
192
+ }
193
+ ip = `${ip.slice(0, split + 1)}${((tail[0] << 8) | tail[1]).toString(16)}:${((tail[2] << 8) | tail[3]).toString(16)}`;
194
+ }
195
+ const halves = ip.split('::');
196
+ if (halves.length > 2) {
197
+ return null;
198
+ }
199
+ const head = halves[0] ? halves[0].split(':') : [];
200
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
201
+ const gap = 8 - head.length - tail.length;
202
+ if (halves.length === 2 ? gap < 1 : gap !== 0) {
203
+ return null;
204
+ }
205
+ const groups = [...head, ...new Array(halves.length === 2 ? gap : 0).fill('0'), ...tail];
206
+ const out = new Uint8Array(16);
207
+ for (let i = 0; i < 8; i++) {
208
+ if (!/^[0-9a-fA-F]{1,4}$/.test(groups[i])) {
209
+ return null;
210
+ }
211
+ const value = parseInt(groups[i], 16);
212
+ out[i * 2] = value >> 8;
213
+ out[i * 2 + 1] = value & 0xff;
214
+ }
215
+ return out;
216
+ }
217
+ function relayXorKey(transactionId) {
218
+ const key = new Uint8Array(16);
219
+ writeUInt32BE(key, STUN_MAGIC_COOKIE, 0);
220
+ for (let i = 0; i < 12; i++) {
221
+ key[4 + i] = transactionId[(i & ~3) + 3 - (i & 3)];
222
+ }
223
+ return key;
224
+ }
225
+ function stripAddressBrackets(text) {
226
+ if (typeof text !== 'string') {
227
+ return '';
228
+ }
229
+ const trimmed = text.trim();
230
+ return trimmed.startsWith('[') && trimmed.endsWith(']') ? trimmed.slice(1, -1) : trimmed;
231
+ }
232
+ function resolveRelayedAddressBytes(ip, form) {
233
+ const bare = stripAddressBrackets(ip);
234
+ if (!bare) {
235
+ return null;
236
+ }
237
+ const ipv4 = bare.includes(':') ? null : parseIpv4Bytes(bare);
238
+ const ipv6 = ipv4 ? null : parseIpv6Bytes(bare);
239
+ if (!ipv4 && !ipv6) {
240
+ return null;
241
+ }
242
+ if (form !== 'mapped') {
243
+ return ipv4 ?? ipv6;
244
+ }
245
+ if (ipv6) {
246
+ return ipv6;
247
+ }
248
+ const mapped = new Uint8Array(16);
249
+ mapped.set([0xff, 0xff], 10);
250
+ mapped.set(ipv4, 12);
251
+ return mapped;
252
+ }
253
+ function encodeXorRelayedAddress(ip, port, transactionId, form = 'exact') {
254
+ const portNumber = Number(port);
255
+ if (!Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
256
+ return undefined;
257
+ }
258
+ if (!transactionId || transactionId.length !== 12) {
259
+ return undefined;
260
+ }
261
+ const address = resolveRelayedAddressBytes(ip, form);
262
+ if (!address) {
263
+ return undefined;
264
+ }
265
+ const data = new Uint8Array(4 + address.length);
266
+ data[1] = address.length === 16 ? 0x02 : 0x01;
267
+ writeUInt16BE(data, portNumber ^ (STUN_MAGIC_COOKIE >>> 16), 2);
268
+ const key = relayXorKey(transactionId);
269
+ for (let i = 0; i < address.length; i++) {
270
+ data[4 + i] = address[i] ^ key[i];
271
+ }
175
272
  return data;
176
273
  }
177
-
178
- export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort, username, transactionId = generateTransactionId()) {
274
+ export function parseRelayedAddressMismatch(reason) {
275
+ if (typeof reason !== 'string') {
276
+ return null;
277
+ }
278
+ const match = /destination address:\s*(.+?)\s+relay address:\s*(.+?)[\s\0]*$/i.exec(reason);
279
+ if (!match) {
280
+ return null;
281
+ }
282
+ const readEndpoint = (text) => {
283
+ const hit = /^\[(.+)\]:(\d{1,5})$/.exec(text) ?? /^([^:\s]+):(\d{1,5})$/.exec(text);
284
+ if (!hit) {
285
+ return null;
286
+ }
287
+ const port = Number(hit[2]);
288
+ return port >= 1 && port <= 65535 ? { ip: hit[1], port } : null;
289
+ };
290
+ return { destination: readEndpoint(match[1]), relay: readEndpoint(match[2]) };
291
+ }
292
+ export function buildAllocateForRelay(relayToken, streamDescriptors, hmacKey, relayIp, relayPort, transactionId = generateTransactionId(), options = {}) {
179
293
  const parts = [];
180
294
  parts.push(encodeAttribute(ATTR_SENDER_SUBSCRIPTIONS, relayToken));
181
295
  parts.push(encodeAttribute(ATTR_SSRC_LIST, streamDescriptors));
182
- parts.push(encodeAttribute(ATTR_REQUESTED_TRANSPORT, new Uint8Array([17, 0, 0, 0])));
183
- if (username && username.length > 0)
184
- parts.push(encodeAttribute(ATTR_USERNAME, username));
185
- parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, encodeXorRelayedAddress(relayIp, relayPort)));
296
+ if (relayIp && relayPort && options.relayedAddress !== 'none') {
297
+ const xorRelayedAddress = encodeXorRelayedAddress(relayIp, relayPort, transactionId, options.relayedAddress);
298
+ if (xorRelayedAddress) {
299
+ parts.push(encodeAttribute(ATTR_XOR_RELAYED_ADDRESS, xorRelayedAddress));
300
+ }
301
+ }
186
302
  const attrs = concatBytes(parts);
187
303
  return buildStunMessage(STUN_ALLOCATE_REQUEST, attrs, transactionId, hmacKey, false);
188
304
  }
@@ -193,7 +309,7 @@ export function buildBindingRequest(username, hmacKey, senderSubscriptions, incl
193
309
  const iceRole = options.iceRole ?? 'controlling';
194
310
  const includePriority = options.includePriority ?? true;
195
311
  const includeUsername = options.includeUsername ?? true;
196
- const transactionId = generateTransactionId();
312
+ const transactionId = options.transactionId ?? generateTransactionId();
197
313
  const usernameAttr = includeUsername ? encodeAttribute(ATTR_USERNAME, username) : undefined;
198
314
  const priorityAttr = includePriority
199
315
  ? (() => {