felixid 1.1.1

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.
Files changed (109) hide show
  1. package/WAProto/GenerateStatics.sh +4 -0
  2. package/WAProto/WAProto.proto +4775 -0
  3. package/WAProto/index.js +169661 -0
  4. package/WAProto/p.html +1 -0
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/index.js +120 -0
  7. package/lib/Defaults/wileys-version.json +3 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.js +96 -0
  11. package/lib/Signal/Group/index.js +57 -0
  12. package/lib/Signal/Group/keyhelper.js +55 -0
  13. package/lib/Signal/Group/queue-job.js +57 -0
  14. package/lib/Signal/Group/sender-chain-key.js +34 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-message.js +69 -0
  17. package/lib/Signal/Group/sender-key-name.js +51 -0
  18. package/lib/Signal/Group/sender-key-record.js +53 -0
  19. package/lib/Signal/Group/sender-key-state.js +99 -0
  20. package/lib/Signal/Group/sender-message-key.js +29 -0
  21. package/lib/Signal/libsignal.js +174 -0
  22. package/lib/Socket/Client/index.js +18 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +72 -0
  25. package/lib/Socket/business.js +260 -0
  26. package/lib/Socket/chats.js +997 -0
  27. package/lib/Socket/groups.js +332 -0
  28. package/lib/Socket/index.js +10 -0
  29. package/lib/Socket/messages-recv.js +1106 -0
  30. package/lib/Socket/messages-send.js +874 -0
  31. package/lib/Socket/newsletter.js +286 -0
  32. package/lib/Socket/socket.js +648 -0
  33. package/lib/Socket/usync.js +70 -0
  34. package/lib/Store/index.js +8 -0
  35. package/lib/Store/make-in-memory-store.js +439 -0
  36. package/lib/Store/make-ordered-dictionary.js +81 -0
  37. package/lib/Store/object-repository.js +27 -0
  38. package/lib/Types/Auth.js +2 -0
  39. package/lib/Types/Call.js +2 -0
  40. package/lib/Types/Chat.js +4 -0
  41. package/lib/Types/Contact.js +2 -0
  42. package/lib/Types/Events.js +2 -0
  43. package/lib/Types/GroupMetadata.js +2 -0
  44. package/lib/Types/Label.js +27 -0
  45. package/lib/Types/LabelAssociation.js +9 -0
  46. package/lib/Types/Message.js +7 -0
  47. package/lib/Types/Newsletter.js +18 -0
  48. package/lib/Types/Product.js +2 -0
  49. package/lib/Types/Signal.js +2 -0
  50. package/lib/Types/Socket.js +2 -0
  51. package/lib/Types/State.js +2 -0
  52. package/lib/Types/USync.js +2 -0
  53. package/lib/Types/index.js +42 -0
  54. package/lib/Utils/auth-utils.js +199 -0
  55. package/lib/Utils/browser-utils.js +35 -0
  56. package/lib/Utils/business.js +234 -0
  57. package/lib/Utils/chat-utils.js +730 -0
  58. package/lib/Utils/crypto.js +193 -0
  59. package/lib/Utils/decode-wa-message.js +217 -0
  60. package/lib/Utils/event-buffer.js +518 -0
  61. package/lib/Utils/generics.js +467 -0
  62. package/lib/Utils/history.js +94 -0
  63. package/lib/Utils/index.js +35 -0
  64. package/lib/Utils/link-preview.js +126 -0
  65. package/lib/Utils/logger.js +7 -0
  66. package/lib/Utils/lt-hash.js +51 -0
  67. package/lib/Utils/make-mutex.js +43 -0
  68. package/lib/Utils/message-retry-manager.js +128 -0
  69. package/lib/Utils/messages-media.js +879 -0
  70. package/lib/Utils/messages.js +1049 -0
  71. package/lib/Utils/noise-handler.js +150 -0
  72. package/lib/Utils/process-message.js +404 -0
  73. package/lib/Utils/signal.js +153 -0
  74. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  75. package/lib/Utils/validate-connection.js +229 -0
  76. package/lib/Utils/wileys-event-stream.js +63 -0
  77. package/lib/Voip/audio-feeder.js +166 -0
  78. package/lib/Voip/index.js +562 -0
  79. package/lib/Voip/relay-transport.js +829 -0
  80. package/lib/Voip/signaling.js +1092 -0
  81. package/lib/Voip/types.js +23 -0
  82. package/lib/Voip/wasm-engine.js +1255 -0
  83. package/lib/Voip/worker-bootstrap.js +1078 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +265 -0
  86. package/lib/WABinary/encode.js +250 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +85 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15350 -0
  93. package/lib/WAM/encode.js +155 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  101. package/lib/WAUSync/Protocols/index.js +20 -0
  102. package/lib/WAUSync/USyncQuery.js +89 -0
  103. package/lib/WAUSync/USyncUser.js +26 -0
  104. package/lib/WAUSync/index.js +19 -0
  105. package/lib/assets/wasm/loader.js +5 -0
  106. package/lib/assets/wasm/whatsapp.wasm +0 -0
  107. package/lib/assets/wasm/worker-modules.js +273 -0
  108. package/lib/index.js +41 -0
  109. package/package.json +119 -0
@@ -0,0 +1,829 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayRtcTransport = void 0;
4
+
5
+ const fs_1 = require("node:fs");
6
+
7
+ const RELAY_PROTO_UDP = 0;
8
+ const FAUX_WEB_CLIENT_RELAY_PORT = 3478;
9
+ const TRUE_WEB_CLIENT_RELAY_PORT = 3480;
10
+ const CONNECTION_TIMEOUT_MS = 20000;
11
+ const ICE_RESTART_IDLE_THRESHOLD_MS = 10000;
12
+ const ICE_RTT_POLL_MS = 1000;
13
+ const MAX_BUFFER_SIZE = 256 * 1024;
14
+
15
+ const RELAY_PACKET_LOG_PATH = process.env.CALL_DUMP_RELAY_PACKETS_PATH ?? "";
16
+ const DISABLE_IPV6 = process.env.CALL_DISABLE_IPV6 !== "0";
17
+ const RELAY_PORT_MODE = process.env.CALL_RELAY_PORT_MODE === "web" ? "web" : "original";
18
+ const USE_ORIGINAL_RELAY_PORTS = RELAY_PORT_MODE === "original";
19
+
20
+ const RELAY_DTLS_FINGERPRINT = "F9:CA:0C:98:A3:CC:71:D6:42:CE:5A:E2:53:D2:15:20:D3:1B:BA:D8:57:A4:F0:AF:BE:0B:FB:F3:6B:0C:A0:68";
21
+
22
+ const getConnectionIdentifier = (ip, port) => ip.includes(":") ? `[${ip}]:${port}` : `${ip}:${port}`;
23
+
24
+ const createEmptyStats = () => ({
25
+ sentPackets: 0,
26
+ receivedPackets: 0,
27
+ sentBytes: 0,
28
+ receivedBytes: 0,
29
+ droppedPackets: 0,
30
+ openConnections: 0
31
+ });
32
+
33
+ const getRelayLookupId = (ip, port) => getConnectionIdentifier(
34
+ ip,
35
+ port === TRUE_WEB_CLIENT_RELAY_PORT ? TRUE_WEB_CLIENT_RELAY_PORT : port
36
+ );
37
+
38
+ const getRtcConnectPort = info => info.ip === "157.240.24.133" ? FAUX_WEB_CLIENT_RELAY_PORT : info.port;
39
+
40
+ const getVoipStackPort = info => {
41
+ if (USE_ORIGINAL_RELAY_PORTS) {
42
+ return info.originalPort || info.port;
43
+ }
44
+
45
+ const sourcePort = info.originalPort || info.port;
46
+
47
+ return sourcePort === TRUE_WEB_CLIENT_RELAY_PORT
48
+ ? TRUE_WEB_CLIENT_RELAY_PORT
49
+ : FAUX_WEB_CLIENT_RELAY_PORT;
50
+ };
51
+
52
+ const bufferPacket = (connection, packet) => {
53
+ if (packet.byteLength > MAX_BUFFER_SIZE) {
54
+ connection.stats.droppedPackets += 1;
55
+ return false;
56
+ }
57
+
58
+ while (
59
+ connection.packetBuffer.length > 0 &&
60
+ connection.bufferedBytes + packet.byteLength > MAX_BUFFER_SIZE
61
+ ) {
62
+ const dropped = connection.packetBuffer.shift();
63
+
64
+ if (dropped) {
65
+ connection.bufferedBytes -= dropped.byteLength;
66
+ connection.stats.droppedPackets += 1;
67
+ }
68
+ }
69
+
70
+ connection.packetBuffer.push(packet);
71
+ connection.bufferedBytes += packet.byteLength;
72
+
73
+ return true;
74
+ };
75
+
76
+ const shiftPacket = connection => {
77
+ const packet = connection.packetBuffer.shift() ?? null;
78
+
79
+ if (packet) {
80
+ connection.bufferedBytes -= packet.byteLength;
81
+ }
82
+
83
+ return packet;
84
+ };
85
+
86
+ const replaceIceCredentials = (sdp, ufrag, pwd) => sdp
87
+ .replace(/a=ice-ufrag:[^\r\n]+/g, `a=ice-ufrag:${ufrag}`)
88
+ .replace(/a=ice-pwd:[^\r\n]+/g, `a=ice-pwd:${pwd}`);
89
+
90
+ const replaceDtlsFingerprint = (sdp, algorithm, fingerprint) => sdp
91
+ .replace(/a=fingerprint:[^\r\n]+/g, `a=fingerprint:${algorithm} ${fingerprint}`);
92
+
93
+ const removeIceCandidates = sdp => sdp
94
+ .replace(/a=candidate:[^\r\n]+\r?\n/g, "")
95
+ .replace(/a=end-of-candidates\r?\n?/g, "");
96
+
97
+ const appendRelayCandidate = (sdp, ip, port) => {
98
+ const candidate = `a=candidate:2 1 udp 2122262783 ${ip} ${port} typ host generation 0 network-cost 5`;
99
+
100
+ return `${removeIceCandidates(sdp)}${candidate}\r\na=end-of-candidates\r\n`;
101
+ };
102
+
103
+ const buildRemoteRelayAnswer = (offerSdp, info) => {
104
+ const setupLine = info.enableEdgerayDtlsActiveMode ? "a=setup:active" : "a=setup:passive";
105
+
106
+ let answerSdp = offerSdp.replace(/a=setup:actpass/g, setupLine);
107
+
108
+ answerSdp = replaceIceCredentials(answerSdp, info.authToken ?? info.token, info.key);
109
+ answerSdp = replaceDtlsFingerprint(answerSdp, "sha-256", RELAY_DTLS_FINGERPRINT);
110
+ answerSdp = answerSdp.replace(/a=ice-options:[^\r\n]+\r\n/g, "");
111
+ answerSdp = answerSdp.replace(/a=max-message-size:[^\r\n]+/g, "a=max-message-size:1200");
112
+
113
+ return appendRelayCandidate(answerSdp, info.ip, info.port);
114
+ };
115
+
116
+ const toArrayBuffer = data => {
117
+ const copy = new Uint8Array(data.byteLength);
118
+ copy.set(data);
119
+
120
+ return copy.buffer;
121
+ };
122
+
123
+ const toUint8Array = data => {
124
+ if (data instanceof Uint8Array) {
125
+ return new Uint8Array(data);
126
+ }
127
+
128
+ if (Buffer.isBuffer(data)) {
129
+ return new Uint8Array(data);
130
+ }
131
+
132
+ if (data instanceof ArrayBuffer) {
133
+ return new Uint8Array(data);
134
+ }
135
+
136
+ if (data && typeof data === "object" && "byteLength" in data && "buffer" in data) {
137
+ const view = data;
138
+
139
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
140
+ }
141
+
142
+ return null;
143
+ };
144
+
145
+ const classifyRelayPacket = packet => {
146
+ if (packet.byteLength < 2) {
147
+ return "non_stun";
148
+ }
149
+
150
+ const bytes = new Uint8Array(packet);
151
+ const first = bytes[0];
152
+ const second = bytes[1];
153
+
154
+ if ((first & 0xc0) !== 0) {
155
+ return "non_stun";
156
+ }
157
+
158
+ const stunType = ((first & 0x3f) << 8) | second;
159
+
160
+ if (stunType === 0x0001) {
161
+ return "stun_bind";
162
+ }
163
+
164
+ if (stunType === 0x0003) {
165
+ return "stun_alloc";
166
+ }
167
+
168
+ return "stun_unknown";
169
+ };
170
+
171
+ const appendRelayPacketLog = (direction, connection, packet) => {
172
+ if (!RELAY_PACKET_LOG_PATH) {
173
+ return;
174
+ }
175
+
176
+ const buffer = packet instanceof ArrayBuffer
177
+ ? Buffer.from(new Uint8Array(packet))
178
+ : Buffer.from(packet.buffer, packet.byteOffset, packet.byteLength);
179
+
180
+ (0, fs_1.appendFileSync)(
181
+ RELAY_PACKET_LOG_PATH,
182
+ JSON.stringify({
183
+ ts: new Date().toISOString(),
184
+ direction,
185
+ id: connection.info.id,
186
+ relayId: connection.info.relayId,
187
+ relayName: connection.info.name,
188
+ ip: connection.info.ip,
189
+ rtcPort: connection.info.port,
190
+ voipPort: getVoipStackPort(connection.info),
191
+ size: buffer.byteLength,
192
+ hex: buffer.toString("hex")
193
+ }) + "\n"
194
+ );
195
+ };
196
+
197
+ class RelayRtcTransport {
198
+ constructor(config) {
199
+ this.config = config;
200
+ this._relayInfoById = new Map();
201
+ this._connections = new Map();
202
+ this._totals = createEmptyStats();
203
+ this._wrtcPromise = null;
204
+
205
+ this.updateRelayList = update => {
206
+ const nextInfoById = new Map();
207
+
208
+ for (const relay of update.relays ?? []) {
209
+ if (
210
+ relay.token_id == null ||
211
+ relay.token_id < 0 ||
212
+ relay.token_id >= (update.relay_tokens ?? []).length
213
+ ) {
214
+ continue;
215
+ }
216
+
217
+ const authToken = update.auth_tokens && relay.auth_token_id != null && relay.auth_token_id >= 0
218
+ ? update.auth_tokens[relay.auth_token_id]
219
+ : undefined;
220
+
221
+ for (const address of relay.addresses ?? []) {
222
+ if (address.protocol !== RELAY_PROTO_UDP) {
223
+ continue;
224
+ }
225
+
226
+ if (address.ipv4 && address.port != null) {
227
+ const clientPort = USE_ORIGINAL_RELAY_PORTS ? address.port : TRUE_WEB_CLIENT_RELAY_PORT;
228
+ const id = getConnectionIdentifier(address.ipv4, clientPort);
229
+
230
+ nextInfoById.set(id, {
231
+ id,
232
+ relayId: relay.relay_id,
233
+ ip: address.ipv4,
234
+ port: clientPort,
235
+ originalPort: address.port,
236
+ isIPv6: false,
237
+ token: update.relay_tokens[relay.token_id],
238
+ authToken,
239
+ key: update.relay_key,
240
+ name: relay.relay_name,
241
+ enableEdgerayDtlsActiveMode: update.enable_edgeray_dtls_active_mode === true
242
+ });
243
+ }
244
+
245
+ if (!DISABLE_IPV6 && address.ipv6 && address.port_v6 != null) {
246
+ const clientPort = USE_ORIGINAL_RELAY_PORTS ? address.port_v6 : TRUE_WEB_CLIENT_RELAY_PORT;
247
+ const id = getConnectionIdentifier(address.ipv6, clientPort);
248
+
249
+ nextInfoById.set(id, {
250
+ id,
251
+ relayId: relay.relay_id,
252
+ ip: address.ipv6,
253
+ port: clientPort,
254
+ originalPort: address.port_v6,
255
+ isIPv6: true,
256
+ token: update.relay_tokens[relay.token_id],
257
+ authToken,
258
+ key: update.relay_key,
259
+ name: relay.relay_name,
260
+ enableEdgerayDtlsActiveMode: update.enable_edgeray_dtls_active_mode === true
261
+ });
262
+ }
263
+ }
264
+ }
265
+
266
+ for (const id of this._relayInfoById.keys()) {
267
+ if (!nextInfoById.has(id)) {
268
+ this._closeConnection(id);
269
+ }
270
+ }
271
+
272
+ this._relayInfoById.clear();
273
+
274
+ for (const [id, info] of nextInfoById) {
275
+ this._relayInfoById.set(id, info);
276
+ void this._ensureConnection(info);
277
+ }
278
+ };
279
+
280
+ this.send = (packet, ip, port) => {
281
+ const requestedId = getConnectionIdentifier(ip, port);
282
+ const preferredPort = USE_ORIGINAL_RELAY_PORTS ? port : TRUE_WEB_CLIENT_RELAY_PORT;
283
+
284
+ const candidateIds = [
285
+ requestedId,
286
+ getConnectionIdentifier(ip, preferredPort),
287
+ getRelayLookupId(ip, TRUE_WEB_CLIENT_RELAY_PORT),
288
+ getRelayLookupId(ip, FAUX_WEB_CLIENT_RELAY_PORT)
289
+ ];
290
+
291
+ let info;
292
+
293
+ for (const candidateId of candidateIds) {
294
+ info = this._relayInfoById.get(candidateId);
295
+
296
+ if (info) {
297
+ break;
298
+ }
299
+ }
300
+
301
+ if (!info) {
302
+ if (DISABLE_IPV6 && ip.includes(":")) {
303
+ return 0;
304
+ }
305
+
306
+ const earlyConnection = this._getOrCreateEarlyConnection(ip, port);
307
+ bufferPacket(earlyConnection, toArrayBuffer(packet));
308
+
309
+ return packet.byteLength;
310
+ }
311
+
312
+ const connection = this._getOrCreateConnection(info);
313
+ const arrayBuffer = toArrayBuffer(packet);
314
+
315
+ if (
316
+ classifyRelayPacket(arrayBuffer) === "stun_alloc" &&
317
+ connection.state === "open" &&
318
+ connection.sentMedia &&
319
+ Date.now() - connection.lastRxPacketTime > ICE_RESTART_IDLE_THRESHOLD_MS
320
+ ) {
321
+ connection.packetBuffer = [];
322
+ connection.bufferedBytes = 0;
323
+ bufferPacket(connection, arrayBuffer);
324
+ void this._restartIce(connection);
325
+
326
+ return packet.byteLength;
327
+ }
328
+
329
+ if (connection.state === "open" && connection.dataChannel?.readyState === "open") {
330
+ if (!this._sendBufferedPacket(connection, arrayBuffer)) {
331
+ connection.stats.droppedPackets += 1;
332
+ }
333
+
334
+ return packet.byteLength;
335
+ }
336
+
337
+ bufferPacket(connection, arrayBuffer);
338
+ void this._ensureConnection(info);
339
+
340
+ return packet.byteLength;
341
+ };
342
+
343
+ this.getStats = () => {
344
+ let openConnections = 0;
345
+
346
+ for (const connection of this._connections.values()) {
347
+ if (connection.state === "open") {
348
+ openConnections += 1;
349
+ }
350
+ }
351
+
352
+ return {
353
+ ...this._totals,
354
+ openConnections
355
+ };
356
+ };
357
+
358
+ this.closeAll = async () => {
359
+ for (const id of [...this._connections.keys()]) {
360
+ this._closeConnection(id);
361
+ }
362
+ };
363
+
364
+ this._getOrCreateConnection = info => {
365
+ const existing = this._connections.get(info.id);
366
+
367
+ if (existing) {
368
+ existing.info = info;
369
+ return existing;
370
+ }
371
+
372
+ const created = {
373
+ info,
374
+ state: "none",
375
+ peerConnection: null,
376
+ dataChannel: null,
377
+ iceCandidate: null,
378
+ packetBuffer: [],
379
+ bufferedBytes: 0,
380
+ connectPromise: null,
381
+ connectionTimeout: null,
382
+ iceStatsInterval: null,
383
+ lastIceRttMs: null,
384
+ hasReceivedFirstPacket: false,
385
+ hasNonStunPacketSent: false,
386
+ sentMedia: false,
387
+ lastRxPacketTime: 0,
388
+ isReconnecting: false,
389
+ stats: createEmptyStats()
390
+ };
391
+
392
+ this._connections.set(info.id, created);
393
+
394
+ return created;
395
+ };
396
+
397
+ this._getOrCreateEarlyConnection = (ip, port) => {
398
+ const id = getConnectionIdentifier(ip, port);
399
+ const existing = this._connections.get(id);
400
+
401
+ if (existing) {
402
+ return existing;
403
+ }
404
+
405
+ const placeholderInfo = {
406
+ id,
407
+ relayId: 0,
408
+ ip,
409
+ port,
410
+ originalPort: port,
411
+ isIPv6: ip.includes(":"),
412
+ token: "",
413
+ key: "",
414
+ name: "early-packet",
415
+ enableEdgerayDtlsActiveMode: false
416
+ };
417
+
418
+ const created = {
419
+ info: placeholderInfo,
420
+ state: "none",
421
+ peerConnection: null,
422
+ dataChannel: null,
423
+ iceCandidate: null,
424
+ packetBuffer: [],
425
+ bufferedBytes: 0,
426
+ connectPromise: null,
427
+ connectionTimeout: null,
428
+ iceStatsInterval: null,
429
+ lastIceRttMs: null,
430
+ hasReceivedFirstPacket: false,
431
+ hasNonStunPacketSent: false,
432
+ sentMedia: false,
433
+ lastRxPacketTime: 0,
434
+ isReconnecting: false,
435
+ stats: createEmptyStats()
436
+ };
437
+
438
+ this._connections.set(id, created);
439
+
440
+ return created;
441
+ };
442
+
443
+ this._ensureConnection = async info => {
444
+ const connection = this._getOrCreateConnection(info);
445
+
446
+ if (connection.state === "open" || connection.state === "connecting") {
447
+ return connection.connectPromise ?? Promise.resolve();
448
+ }
449
+
450
+ const promise = this._connect(connection);
451
+ connection.connectPromise = promise;
452
+
453
+ try {
454
+ await promise;
455
+ } finally {
456
+ connection.connectPromise = null;
457
+ }
458
+ };
459
+
460
+ this._connect = async connection => {
461
+ const wrtcModule = await this._loadWrtc();
462
+ const { RTCPeerConnection } = wrtcModule;
463
+
464
+ if (typeof RTCPeerConnection !== "function") {
465
+ throw new Error("RTCPeerConnection unavailable from @roamhq/wrtc");
466
+ }
467
+
468
+ this._closePeerObjects(connection);
469
+
470
+ connection.state = "connecting";
471
+
472
+ const pc = new RTCPeerConnection();
473
+ const dc = pc.createDataChannel("pre-negotiated", {
474
+ negotiated: true,
475
+ id: 0,
476
+ ordered: false,
477
+ maxRetransmits: 0,
478
+ priority: "high"
479
+ });
480
+
481
+ connection.peerConnection = pc;
482
+ connection.dataChannel = dc;
483
+
484
+ dc.binaryType = "arraybuffer";
485
+
486
+ dc.onopen = () => {
487
+ connection.state = "open";
488
+ connection.isReconnecting = false;
489
+
490
+ if (connection.connectionTimeout) {
491
+ clearTimeout(connection.connectionTimeout);
492
+ connection.connectionTimeout = null;
493
+ }
494
+
495
+ this._flushBufferedPackets(connection);
496
+ this._startIceRttPolling(connection);
497
+ };
498
+
499
+ dc.onclose = () => {
500
+ if (connection.state !== "failed") {
501
+ connection.state = "closed";
502
+ }
503
+ };
504
+
505
+ dc.onerror = () => {
506
+ connection.state = "failed";
507
+ };
508
+
509
+ dc.onmessage = event => {
510
+ this._handleIncomingPacket(connection, event.data);
511
+ };
512
+
513
+ pc.onicecandidate = event => {
514
+ if (event.candidate?.candidate && !connection.iceCandidate) {
515
+ connection.iceCandidate = event.candidate.candidate;
516
+ }
517
+ };
518
+
519
+ pc.oniceconnectionstatechange = () => {
520
+ if (pc.iceConnectionState === "failed" || pc.iceConnectionState === "closed") {
521
+ connection.state = "failed";
522
+ }
523
+ };
524
+
525
+ connection.connectionTimeout = setTimeout(() => {
526
+ if (connection.state === "connecting") {
527
+ connection.state = "failed";
528
+ this._closePeerObjects(connection);
529
+ }
530
+ }, CONNECTION_TIMEOUT_MS);
531
+
532
+ const offer = await pc.createOffer();
533
+
534
+ await pc.setLocalDescription(offer);
535
+
536
+ const remoteSdp = buildRemoteRelayAnswer(offer.sdp ?? "", {
537
+ ...connection.info,
538
+ port: getRtcConnectPort(connection.info)
539
+ });
540
+
541
+ await pc.setRemoteDescription({
542
+ type: "answer",
543
+ sdp: remoteSdp
544
+ });
545
+ };
546
+
547
+ this._restartIce = async connection => {
548
+ if (connection.isReconnecting || !connection.hasNonStunPacketSent) {
549
+ return;
550
+ }
551
+
552
+ const { RTCPeerConnection } = await this._loadWrtc();
553
+
554
+ if (typeof RTCPeerConnection !== "function") {
555
+ return;
556
+ }
557
+
558
+ connection.isReconnecting = true;
559
+
560
+ try {
561
+ this._closePeerObjects(connection);
562
+ connection.state = "connecting";
563
+
564
+ const pc = new RTCPeerConnection();
565
+ const dc = pc.createDataChannel("pre-negotiated", {
566
+ negotiated: true,
567
+ id: 0,
568
+ ordered: false,
569
+ maxRetransmits: 0,
570
+ priority: "high"
571
+ });
572
+
573
+ connection.peerConnection = pc;
574
+ connection.dataChannel = dc;
575
+
576
+ dc.binaryType = "arraybuffer";
577
+
578
+ dc.onopen = () => {
579
+ connection.state = "open";
580
+ connection.isReconnecting = false;
581
+ this._flushBufferedPackets(connection);
582
+ this._startIceRttPolling(connection);
583
+ };
584
+
585
+ dc.onclose = () => {
586
+ if (connection.state !== "failed") {
587
+ connection.state = "closed";
588
+ }
589
+ };
590
+
591
+ dc.onerror = () => {
592
+ connection.state = "failed";
593
+ };
594
+
595
+ dc.onmessage = event => {
596
+ this._handleIncomingPacket(connection, event.data);
597
+ };
598
+
599
+ pc.onicecandidate = event => {
600
+ if (event.candidate?.candidate && !connection.iceCandidate) {
601
+ connection.iceCandidate = event.candidate.candidate;
602
+ }
603
+ };
604
+
605
+ const offer = await pc.createOffer({
606
+ iceRestart: false
607
+ });
608
+
609
+ let localSdp = offer.sdp ?? "";
610
+
611
+ if (connection.iceCandidate) {
612
+ localSdp = `${removeIceCandidates(localSdp)}a=${connection.iceCandidate}\r\na=end-of-candidates\r\n`;
613
+ }
614
+
615
+ await pc.setLocalDescription({
616
+ type: "offer",
617
+ sdp: localSdp
618
+ });
619
+
620
+ const remoteSdp = buildRemoteRelayAnswer(localSdp, {
621
+ ...connection.info,
622
+ port: getRtcConnectPort(connection.info)
623
+ });
624
+
625
+ await pc.setRemoteDescription({
626
+ type: "answer",
627
+ sdp: remoteSdp
628
+ });
629
+ } catch {
630
+ connection.state = "failed";
631
+ } finally {
632
+ connection.isReconnecting = false;
633
+ }
634
+ };
635
+
636
+ this._handleIncomingPacket = (connection, raw) => {
637
+ const packet = toUint8Array(raw);
638
+
639
+ if (!packet) {
640
+ return;
641
+ }
642
+
643
+ connection.stats.receivedPackets += 1;
644
+ connection.stats.receivedBytes += packet.byteLength;
645
+ connection.hasReceivedFirstPacket = true;
646
+ connection.lastRxPacketTime = Date.now();
647
+
648
+ this._totals.receivedPackets += 1;
649
+ this._totals.receivedBytes += packet.byteLength;
650
+
651
+ appendRelayPacketLog("recv", connection, packet);
652
+
653
+ this.config.onTransportMessage(packet, connection.info.ip, getVoipStackPort(connection.info));
654
+ };
655
+
656
+ this._flushBufferedPackets = connection => {
657
+ while (
658
+ connection.state === "open" &&
659
+ connection.dataChannel?.readyState === "open" &&
660
+ connection.packetBuffer.length > 0
661
+ ) {
662
+ const packet = shiftPacket(connection);
663
+
664
+ if (!packet) {
665
+ break;
666
+ }
667
+
668
+ if (!this._sendBufferedPacket(connection, packet)) {
669
+ connection.stats.droppedPackets += 1;
670
+ break;
671
+ }
672
+ }
673
+ };
674
+
675
+ this._sendBufferedPacket = (connection, packet) => {
676
+ try {
677
+ connection.dataChannel?.send(packet);
678
+
679
+ if (classifyRelayPacket(packet) === "non_stun") {
680
+ connection.hasNonStunPacketSent = true;
681
+ connection.sentMedia = true;
682
+ }
683
+
684
+ connection.stats.sentPackets += 1;
685
+ connection.stats.sentBytes += packet.byteLength;
686
+
687
+ this._totals.sentPackets += 1;
688
+ this._totals.sentBytes += packet.byteLength;
689
+
690
+ appendRelayPacketLog("send", connection, packet);
691
+
692
+ return true;
693
+ } catch {
694
+ return false;
695
+ }
696
+ };
697
+
698
+ this._startIceRttPolling = connection => {
699
+ this._stopIceRttPolling(connection);
700
+
701
+ const pc = connection.peerConnection;
702
+
703
+ if (!pc || typeof pc.getStats !== "function" || !this.config.onIceRtt) {
704
+ return;
705
+ }
706
+
707
+ const poll = async () => {
708
+ const rttMs = await this._readCurrentRoundTripTimeMs(pc);
709
+
710
+ if (rttMs == null || connection.lastIceRttMs === rttMs) {
711
+ return;
712
+ }
713
+
714
+ connection.lastIceRttMs = rttMs;
715
+ this.config.onIceRtt?.(rttMs, connection.info.ip, connection.info.port);
716
+ };
717
+
718
+ void poll();
719
+
720
+ connection.iceStatsInterval = setInterval(() => {
721
+ void poll();
722
+ }, ICE_RTT_POLL_MS);
723
+
724
+ connection.iceStatsInterval.unref?.();
725
+ };
726
+
727
+ this._stopIceRttPolling = connection => {
728
+ if (connection.iceStatsInterval) {
729
+ clearInterval(connection.iceStatsInterval);
730
+ connection.iceStatsInterval = null;
731
+ }
732
+
733
+ connection.lastIceRttMs = null;
734
+ };
735
+
736
+ this._readCurrentRoundTripTimeMs = async pc => {
737
+ try {
738
+ const stats = await pc.getStats();
739
+
740
+ const reports = stats && typeof stats.values === "function"
741
+ ? Array.from(stats.values())
742
+ : Array.isArray(stats)
743
+ ? stats
744
+ : Object.values(stats ?? {});
745
+
746
+ if (!reports.length) {
747
+ return null;
748
+ }
749
+
750
+ let selectedCandidatePairId = "";
751
+
752
+ for (const report of reports) {
753
+ if (report?.type === "transport" && typeof report.selectedCandidatePairId === "string") {
754
+ selectedCandidatePairId = report.selectedCandidatePairId;
755
+ break;
756
+ }
757
+ }
758
+
759
+ const candidatePairs = reports.filter(report => report?.type === "candidate-pair");
760
+
761
+ const selectedPair =
762
+ selectedCandidatePairId && candidatePairs.find(report => report?.id === selectedCandidatePairId) ||
763
+ candidatePairs.find(report => report?.selected || report?.nominated) ||
764
+ candidatePairs[0];
765
+
766
+ const rttSeconds = typeof selectedPair?.currentRoundTripTime === "number"
767
+ ? selectedPair.currentRoundTripTime
768
+ : typeof selectedPair?.totalRoundTripTime === "number" &&
769
+ typeof selectedPair?.responsesReceived === "number" &&
770
+ selectedPair.responsesReceived > 0
771
+ ? selectedPair.totalRoundTripTime / selectedPair.responsesReceived
772
+ : null;
773
+
774
+ if (rttSeconds == null || !Number.isFinite(rttSeconds) || rttSeconds <= 0) {
775
+ return null;
776
+ }
777
+
778
+ return Math.max(1, Math.round(rttSeconds * 1000));
779
+ } catch {
780
+ return null;
781
+ }
782
+ };
783
+
784
+ this._closeConnection = id => {
785
+ const connection = this._connections.get(id);
786
+
787
+ if (!connection) {
788
+ return;
789
+ }
790
+
791
+ if (connection.connectionTimeout) {
792
+ clearTimeout(connection.connectionTimeout);
793
+ connection.connectionTimeout = null;
794
+ }
795
+
796
+ this._closePeerObjects(connection);
797
+
798
+ connection.state = "closed";
799
+ connection.packetBuffer = [];
800
+ connection.bufferedBytes = 0;
801
+
802
+ this._connections.delete(id);
803
+ };
804
+
805
+ this._closePeerObjects = connection => {
806
+ this._stopIceRttPolling(connection);
807
+
808
+ try {
809
+ connection.dataChannel?.close?.();
810
+ } catch { }
811
+
812
+ try {
813
+ connection.peerConnection?.close?.();
814
+ } catch { }
815
+
816
+ connection.dataChannel = null;
817
+ connection.peerConnection = null;
818
+ };
819
+
820
+ this._loadWrtc = () => {
821
+ this._wrtcPromise ??= import("@roamhq/wrtc").then(module => module.default ?? module);
822
+
823
+ return this._wrtcPromise;
824
+ };
825
+ }
826
+ }
827
+
828
+ exports.RelayRtcTransport = RelayRtcTransport;
829
+ exports.default = RelayRtcTransport;