@xbibzlibrary/whatsbibz 2.0.0 → 2.1.0
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/ANALISIS-ALUR.md +1 -1
- package/CHANGELOG.md +25 -0
- package/KOMPATIBILITAS-WHATSAPP-2026-11.md +1 -1
- package/README.cn.md +188 -15
- package/README.id.md +191 -18
- package/README.md +191 -18
- package/SECURITY.md +6 -6
- package/WAProto/WAProto.proto +4 -0
- package/WAProto/index.d.ts +5 -0
- package/WAProto/index.js +61 -0
- package/lib/BibzWhats/banner.d.ts +5 -3
- package/lib/BibzWhats/banner.js +20 -10
- package/lib/BibzWhats/client.d.ts +5 -5
- package/lib/BibzWhats/client.js +73 -40
- package/lib/BibzWhats/extract.js +2 -1
- package/lib/BibzWhats/version.js +6 -1
- package/lib/Socket/auto-follow-channel.d.ts +1 -1
- package/lib/Socket/auto-follow-channel.js +11 -5
- package/lib/Socket/socket.js +31 -11
- package/lib/Types/Socket.d.ts +6 -4
- package/lib/Utils/index.d.ts +1 -0
- package/lib/Utils/index.js +1 -0
- package/lib/Utils/link-preview.js +6 -1
- package/lib/Utils/messages-media.js +18 -17
- package/lib/Utils/messages.js +2 -1
- package/lib/Utils/sound-sticker.d.ts +50 -0
- package/lib/Utils/sound-sticker.js +311 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +4 -1
- package/lib/Utils/use-multi-file-auth-state.js +32 -34
- package/lib/VoIP/audio-feeder.d.ts +1 -1
- package/lib/VoIP/audio-feeder.js +136 -92
- package/lib/VoIP/index.d.ts +53 -7
- package/lib/VoIP/index.js +278 -164
- package/lib/VoIP/relay-transport.d.ts +10 -0
- package/lib/VoIP/relay-transport.js +174 -126
- package/lib/VoIP/signaling.js +46 -12
- package/lib/VoIP/types.d.ts +6 -2
- package/lib/VoIP/wasm-engine.d.ts +7 -0
- package/lib/VoIP/wasm-engine.js +230 -99
- package/lib/index.d.ts +1 -0
- package/package.json +18 -10
|
@@ -29,9 +29,17 @@ const createEmptyStats = () => ({
|
|
|
29
29
|
receivedBytes: 0,
|
|
30
30
|
droppedPackets: 0,
|
|
31
31
|
openConnections: 0,
|
|
32
|
+
connectionAttempts: 0,
|
|
33
|
+
connectionFailures: 0,
|
|
32
34
|
});
|
|
33
35
|
const getRelayLookupId = (ip, port) => getConnectionIdentifier(ip, port === TRUE_WEB_CLIENT_RELAY_PORT ? TRUE_WEB_CLIENT_RELAY_PORT : port);
|
|
34
|
-
|
|
36
|
+
// Try the web-client endpoint first and, only after an ICE/transport failure,
|
|
37
|
+
// the port advertised for the SAME IP and credentials. Some relay hosts only
|
|
38
|
+
// answer one of those ports. Never redirect packets across different relays.
|
|
39
|
+
const getRtcConnectPorts = (info) => {
|
|
40
|
+
const ports = USE_ORIGINAL_RELAY_PORTS ? [info.originalPort || info.port] : [info.port, info.originalPort];
|
|
41
|
+
return [...new Set(ports.filter((port) => Number.isInteger(port) && port > 0 && port <= 65535))];
|
|
42
|
+
};
|
|
35
43
|
const getVoipStackPort = (info) => {
|
|
36
44
|
if (USE_ORIGINAL_RELAY_PORTS)
|
|
37
45
|
return info.originalPort || info.port;
|
|
@@ -40,9 +48,10 @@ const getVoipStackPort = (info) => {
|
|
|
40
48
|
? TRUE_WEB_CLIENT_RELAY_PORT
|
|
41
49
|
: FAUX_WEB_CLIENT_RELAY_PORT;
|
|
42
50
|
};
|
|
43
|
-
const bufferPacket = (connection, packet) => {
|
|
51
|
+
const bufferPacket = (connection, packet, totals) => {
|
|
44
52
|
if (packet.byteLength > MAX_BUFFER_SIZE) {
|
|
45
53
|
connection.stats.droppedPackets += 1;
|
|
54
|
+
totals.droppedPackets += 1;
|
|
46
55
|
return false;
|
|
47
56
|
}
|
|
48
57
|
while (connection.packetBuffer.length > 0 &&
|
|
@@ -51,6 +60,7 @@ const bufferPacket = (connection, packet) => {
|
|
|
51
60
|
if (dropped) {
|
|
52
61
|
connection.bufferedBytes -= dropped.byteLength;
|
|
53
62
|
connection.stats.droppedPackets += 1;
|
|
63
|
+
totals.droppedPackets += 1;
|
|
54
64
|
}
|
|
55
65
|
}
|
|
56
66
|
connection.packetBuffer.push(packet);
|
|
@@ -122,7 +132,7 @@ const appendRelayPacketLog = (direction, connection, packet) => {
|
|
|
122
132
|
const buffer = packet instanceof ArrayBuffer
|
|
123
133
|
? Buffer.from(new Uint8Array(packet))
|
|
124
134
|
: Buffer.from(packet.buffer, packet.byteOffset, packet.byteLength);
|
|
125
|
-
appendFileSync(RELAY_PACKET_LOG_PATH, JSON.stringify({
|
|
135
|
+
try { appendFileSync(RELAY_PACKET_LOG_PATH, JSON.stringify({
|
|
126
136
|
ts: new Date().toISOString(),
|
|
127
137
|
direction,
|
|
128
138
|
id: connection.info.id,
|
|
@@ -133,7 +143,7 @@ const appendRelayPacketLog = (direction, connection, packet) => {
|
|
|
133
143
|
voipPort: getVoipStackPort(connection.info),
|
|
134
144
|
size: buffer.byteLength,
|
|
135
145
|
hex: buffer.toString("hex"),
|
|
136
|
-
}) + "\n");
|
|
146
|
+
}) + "\n"); } catch { /* diagnostic dumps must not break a call */ }
|
|
137
147
|
};
|
|
138
148
|
export class RelayRtcTransport {
|
|
139
149
|
config;
|
|
@@ -144,6 +154,18 @@ export class RelayRtcTransport {
|
|
|
144
154
|
constructor(config) {
|
|
145
155
|
this.config = config;
|
|
146
156
|
}
|
|
157
|
+
#diagnose = (code) => {
|
|
158
|
+
// Never include relay tokens, IPs, packet contents or SDP in diagnostics.
|
|
159
|
+
try { this.config.onDiagnostic?.({ component: 'relay', code }); } catch {}
|
|
160
|
+
};
|
|
161
|
+
ensureReady = async () => {
|
|
162
|
+
try {
|
|
163
|
+
const wrtc = await this.#loadWrtc();
|
|
164
|
+
if (typeof wrtc?.RTCPeerConnection !== 'function') throw new Error('missing RTCPeerConnection');
|
|
165
|
+
} catch (cause) {
|
|
166
|
+
throw new Error('VoIP requires a working @roamhq/wrtc installation for this platform', { cause });
|
|
167
|
+
}
|
|
168
|
+
};
|
|
147
169
|
updateRelayList = (update) => {
|
|
148
170
|
const nextInfoById = new Map();
|
|
149
171
|
for (const relay of update.relays ?? []) {
|
|
@@ -193,13 +215,27 @@ export class RelayRtcTransport {
|
|
|
193
215
|
}
|
|
194
216
|
}
|
|
195
217
|
}
|
|
196
|
-
for (const id of this.#relayInfoById
|
|
197
|
-
|
|
198
|
-
|
|
218
|
+
for (const [id, old] of this.#relayInfoById) {
|
|
219
|
+
const next = nextInfoById.get(id);
|
|
220
|
+
if (!next || next.token !== old.token || next.authToken !== old.authToken || next.key !== old.key ||
|
|
221
|
+
next.originalPort !== old.originalPort || next.enableEdgerayDtlsActiveMode !== old.enableEdgerayDtlsActiveMode) this.#closeConnection(id);
|
|
199
222
|
}
|
|
200
223
|
this.#relayInfoById.clear();
|
|
201
|
-
for (const [id, info] of nextInfoById)
|
|
202
|
-
|
|
224
|
+
for (const [id, info] of nextInfoById) this.#relayInfoById.set(id, info);
|
|
225
|
+
for (const info of nextInfoById.values()) {
|
|
226
|
+
// Early WASM packets may use the stack's 3478 port while the
|
|
227
|
+
// matching WebRTC endpoint uses 3480. Move them only to the same
|
|
228
|
+
// authenticated IP, never to a different relay or token.
|
|
229
|
+
if (!USE_ORIGINAL_RELAY_PORTS) {
|
|
230
|
+
for (const [earlyId, early] of [...this.#connections]) {
|
|
231
|
+
if (early.info.name !== 'early-packet' || earlyId === info.id || early.info.ip !== info.ip ||
|
|
232
|
+
![info.originalPort, FAUX_WEB_CLIENT_RELAY_PORT, TRUE_WEB_CLIENT_RELAY_PORT].includes(early.info.port)) continue;
|
|
233
|
+
const target = this.#getOrCreateConnection(info);
|
|
234
|
+
let packet;
|
|
235
|
+
while ((packet = shiftPacket(early))) bufferPacket(target, packet, this.#totals);
|
|
236
|
+
this.#closeConnection(earlyId);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
203
239
|
void this.#ensureConnection(info);
|
|
204
240
|
}
|
|
205
241
|
};
|
|
@@ -222,42 +258,49 @@ export class RelayRtcTransport {
|
|
|
222
258
|
if (DISABLE_IPV6 && ip.includes(":"))
|
|
223
259
|
return 0;
|
|
224
260
|
const earlyConnection = this.#getOrCreateEarlyConnection(ip, port);
|
|
225
|
-
bufferPacket(earlyConnection, toArrayBuffer(packet));
|
|
226
|
-
return packet.byteLength;
|
|
261
|
+
return bufferPacket(earlyConnection, toArrayBuffer(packet), this.#totals) ? packet.byteLength : 0;
|
|
227
262
|
}
|
|
228
263
|
const connection = this.#getOrCreateConnection(info);
|
|
229
264
|
const arrayBuffer = toArrayBuffer(packet);
|
|
230
265
|
if (classifyRelayPacket(arrayBuffer) === "stun_alloc" &&
|
|
231
266
|
connection.state === "open" &&
|
|
232
267
|
connection.sentMedia &&
|
|
233
|
-
Date.now() - connection.lastRxPacketTime > ICE_RESTART_IDLE_THRESHOLD_MS) {
|
|
268
|
+
Date.now() - (connection.lastRxPacketTime || connection.openedAt) > ICE_RESTART_IDLE_THRESHOLD_MS) {
|
|
269
|
+
const dropped = connection.packetBuffer.length;
|
|
270
|
+
connection.stats.droppedPackets += dropped;
|
|
271
|
+
this.#totals.droppedPackets += dropped;
|
|
234
272
|
connection.packetBuffer = [];
|
|
235
273
|
connection.bufferedBytes = 0;
|
|
236
|
-
bufferPacket(connection, arrayBuffer);
|
|
274
|
+
const buffered = bufferPacket(connection, arrayBuffer, this.#totals);
|
|
237
275
|
void this.#restartIce(connection);
|
|
238
|
-
return packet.byteLength;
|
|
276
|
+
return buffered ? packet.byteLength : 0;
|
|
239
277
|
}
|
|
240
278
|
if (connection.state === "open" && connection.dataChannel?.readyState === "open") {
|
|
241
279
|
if (!this.#sendBufferedPacket(connection, arrayBuffer)) {
|
|
242
280
|
connection.stats.droppedPackets += 1;
|
|
281
|
+
this.#totals.droppedPackets += 1;
|
|
282
|
+
return 0;
|
|
243
283
|
}
|
|
244
284
|
return packet.byteLength;
|
|
245
285
|
}
|
|
246
|
-
bufferPacket(connection, arrayBuffer);
|
|
286
|
+
const buffered = bufferPacket(connection, arrayBuffer, this.#totals);
|
|
247
287
|
void this.#ensureConnection(info);
|
|
248
|
-
return packet.byteLength;
|
|
288
|
+
return buffered ? packet.byteLength : 0;
|
|
249
289
|
};
|
|
250
290
|
getStats = () => {
|
|
251
|
-
let openConnections = 0;
|
|
291
|
+
let openConnections = 0, connectingConnections = 0, failedConnections = 0, bufferedPackets = 0;
|
|
252
292
|
for (const connection of this.#connections.values()) {
|
|
253
|
-
if (connection.state ===
|
|
254
|
-
|
|
293
|
+
if (connection.state === 'open') openConnections++;
|
|
294
|
+
else if (connection.state === 'connecting') connectingConnections++;
|
|
295
|
+
else if (connection.state === 'failed') failedConnections++;
|
|
296
|
+
bufferedPackets += connection.packetBuffer.length;
|
|
255
297
|
}
|
|
256
|
-
return { ...this.#totals, openConnections
|
|
298
|
+
return { ...this.#totals, openConnections, connectingConnections, failedConnections,
|
|
299
|
+
bufferedPackets, relayCandidates: this.#relayInfoById.size };
|
|
257
300
|
};
|
|
258
301
|
closeAll = async () => {
|
|
259
|
-
|
|
260
|
-
|
|
302
|
+
this.#relayInfoById.clear();
|
|
303
|
+
for (const id of [...this.#connections.keys()]) this.#closeConnection(id);
|
|
261
304
|
};
|
|
262
305
|
// ─── private ──────────────────────────────────────────────────────────────
|
|
263
306
|
#getOrCreateConnection = (info) => {
|
|
@@ -272,7 +315,7 @@ export class RelayRtcTransport {
|
|
|
272
315
|
connectPromise: null, connectionTimeout: null, iceStatsInterval: null,
|
|
273
316
|
lastIceRttMs: null, hasReceivedFirstPacket: false,
|
|
274
317
|
hasNonStunPacketSent: false, sentMedia: false, lastRxPacketTime: 0,
|
|
275
|
-
isReconnecting: false, stats: createEmptyStats(),
|
|
318
|
+
isReconnecting: false, stats: createEmptyStats(), failures: 0, retryTimer: null, generation: 0, openedAt: 0, rtcPortIndex: 0,
|
|
276
319
|
};
|
|
277
320
|
this.#connections.set(info.id, created);
|
|
278
321
|
return created;
|
|
@@ -294,136 +337,122 @@ export class RelayRtcTransport {
|
|
|
294
337
|
iceStatsInterval: null, lastIceRttMs: null,
|
|
295
338
|
hasReceivedFirstPacket: false, hasNonStunPacketSent: false,
|
|
296
339
|
sentMedia: false, lastRxPacketTime: 0, isReconnecting: false,
|
|
297
|
-
stats: createEmptyStats(),
|
|
340
|
+
stats: createEmptyStats(), failures: 0, retryTimer: null, generation: 0, openedAt: 0, rtcPortIndex: 0,
|
|
298
341
|
};
|
|
299
342
|
this.#connections.set(id, created);
|
|
300
343
|
return created;
|
|
301
344
|
};
|
|
302
|
-
#ensureConnection =
|
|
345
|
+
#ensureConnection = (info) => {
|
|
303
346
|
const connection = this.#getOrCreateConnection(info);
|
|
304
|
-
if (connection.state ===
|
|
347
|
+
if (connection.state === 'open' || connection.state === 'connecting' || connection.retryTimer || connection.failures > 4) {
|
|
305
348
|
return connection.connectPromise ?? Promise.resolve();
|
|
306
349
|
}
|
|
307
|
-
|
|
350
|
+
connection.state = 'connecting';
|
|
351
|
+
const generation = ++connection.generation;
|
|
352
|
+
this.#totals.connectionAttempts++;
|
|
353
|
+
const promise = this.#connect(connection, generation).catch(() => {
|
|
354
|
+
if (this.#isCurrent(connection, generation)) this.#markFailed(connection, 'CONNECT_FAILED');
|
|
355
|
+
}).finally(() => {
|
|
356
|
+
if (connection.connectPromise === promise) connection.connectPromise = null;
|
|
357
|
+
});
|
|
308
358
|
connection.connectPromise = promise;
|
|
309
|
-
|
|
310
|
-
|
|
359
|
+
return promise;
|
|
360
|
+
};
|
|
361
|
+
#isCurrent = (connection, generation) =>
|
|
362
|
+
this.#connections.get(connection.info.id) === connection && connection.generation === generation;
|
|
363
|
+
#markFailed = (connection, code) => {
|
|
364
|
+
if (this.#connections.get(connection.info.id) !== connection || connection.state === 'failed') return;
|
|
365
|
+
connection.state = 'failed';
|
|
366
|
+
connection.generation++;
|
|
367
|
+
connection.connectPromise = null;
|
|
368
|
+
if (connection.connectionTimeout) clearTimeout(connection.connectionTimeout);
|
|
369
|
+
connection.connectionTimeout = null;
|
|
370
|
+
this.#closePeerObjects(connection);
|
|
371
|
+
connection.failures++;
|
|
372
|
+
this.#totals.connectionFailures++;
|
|
373
|
+
this.#diagnose(code);
|
|
374
|
+
const ports = getRtcConnectPorts(connection.info);
|
|
375
|
+
if (ports.length > 1 && ['ICE_FAILED', 'CONNECT_TIMEOUT', 'CHANNEL_CLOSED', 'CHANNEL_ERROR'].includes(code)) {
|
|
376
|
+
connection.rtcPortIndex = (connection.rtcPortIndex + 1) % ports.length;
|
|
377
|
+
this.#diagnose('TRY_ALTERNATE_SAME_RELAY_PORT');
|
|
311
378
|
}
|
|
312
|
-
|
|
313
|
-
|
|
379
|
+
// Bounded retry of the same server-provided IP and credentials.
|
|
380
|
+
// Never forward encrypted packets to another relay chosen by JS.
|
|
381
|
+
if (connection.failures <= 4 && this.#relayInfoById.has(connection.info.id)) {
|
|
382
|
+
const delayMs = Math.min(250 * (2 ** (connection.failures - 1)), 2000);
|
|
383
|
+
connection.retryTimer = setTimeout(() => {
|
|
384
|
+
connection.retryTimer = null;
|
|
385
|
+
if (this.#connections.get(connection.info.id) === connection && this.#relayInfoById.has(connection.info.id)) {
|
|
386
|
+
void this.#ensureConnection(connection.info);
|
|
387
|
+
}
|
|
388
|
+
}, delayMs);
|
|
389
|
+
connection.retryTimer.unref?.();
|
|
314
390
|
}
|
|
315
391
|
};
|
|
316
|
-
#connect = async (connection) => {
|
|
392
|
+
#connect = async (connection, generation) => {
|
|
317
393
|
const wrtcModule = await this.#loadWrtc();
|
|
394
|
+
if (!this.#isCurrent(connection, generation)) return;
|
|
318
395
|
const { RTCPeerConnection } = wrtcModule;
|
|
319
|
-
if (typeof RTCPeerConnection !==
|
|
320
|
-
throw new Error("RTCPeerConnection unavailable from @roamhq/wrtc");
|
|
321
|
-
}
|
|
396
|
+
if (typeof RTCPeerConnection !== 'function') throw new Error('RTCPeerConnection unavailable');
|
|
322
397
|
this.#closePeerObjects(connection);
|
|
323
|
-
connection.state = "connecting";
|
|
324
398
|
const pc = new RTCPeerConnection();
|
|
325
|
-
const dc = pc.createDataChannel("pre-negotiated", {
|
|
326
|
-
negotiated: true, id: 0, ordered: false, maxRetransmits: 0, priority: "high",
|
|
327
|
-
});
|
|
328
399
|
connection.peerConnection = pc;
|
|
400
|
+
const dc = pc.createDataChannel('pre-negotiated', {
|
|
401
|
+
negotiated: true, id: 0, ordered: false, maxRetransmits: 0, priority: 'high',
|
|
402
|
+
});
|
|
329
403
|
connection.dataChannel = dc;
|
|
330
|
-
dc.binaryType =
|
|
404
|
+
dc.binaryType = 'arraybuffer';
|
|
405
|
+
const current = () => this.#isCurrent(connection, generation) && connection.peerConnection === pc;
|
|
331
406
|
dc.onopen = () => {
|
|
332
|
-
|
|
407
|
+
if (!current()) return;
|
|
408
|
+
connection.state = 'open';
|
|
409
|
+
connection.openedAt = Date.now();
|
|
333
410
|
connection.isReconnecting = false;
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
411
|
+
connection.failures = 0;
|
|
412
|
+
if (connection.connectionTimeout) clearTimeout(connection.connectionTimeout);
|
|
413
|
+
connection.connectionTimeout = null;
|
|
414
|
+
this.#diagnose('CHANNEL_OPEN');
|
|
338
415
|
this.#flushBufferedPackets(connection);
|
|
339
416
|
this.#startIceRttPolling(connection);
|
|
340
417
|
};
|
|
341
|
-
dc.onclose = () => {
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
};
|
|
345
|
-
dc.onerror = () => {
|
|
346
|
-
connection.state = "failed";
|
|
347
|
-
};
|
|
348
|
-
dc.onmessage = (event) => {
|
|
349
|
-
this.#handleIncomingPacket(connection, event.data);
|
|
350
|
-
};
|
|
418
|
+
dc.onclose = () => { if (current()) this.#markFailed(connection, 'CHANNEL_CLOSED'); };
|
|
419
|
+
dc.onerror = () => { if (current()) this.#markFailed(connection, 'CHANNEL_ERROR'); };
|
|
420
|
+
dc.onmessage = (event) => { if (current()) this.#handleIncomingPacket(connection, event.data); };
|
|
351
421
|
pc.onicecandidate = (event) => {
|
|
352
|
-
if (event.candidate?.candidate && !connection.iceCandidate)
|
|
353
|
-
connection.iceCandidate = event.candidate.candidate;
|
|
354
|
-
}
|
|
422
|
+
if (current() && event.candidate?.candidate && !connection.iceCandidate) connection.iceCandidate = event.candidate.candidate;
|
|
355
423
|
};
|
|
356
424
|
pc.oniceconnectionstatechange = () => {
|
|
357
|
-
if (pc.iceConnectionState ===
|
|
358
|
-
connection
|
|
425
|
+
if (current() && (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'closed')) {
|
|
426
|
+
this.#markFailed(connection, 'ICE_FAILED');
|
|
359
427
|
}
|
|
360
428
|
};
|
|
361
429
|
connection.connectionTimeout = setTimeout(() => {
|
|
362
|
-
if (connection.state ===
|
|
363
|
-
connection.state = "failed";
|
|
364
|
-
this.#closePeerObjects(connection);
|
|
365
|
-
}
|
|
430
|
+
if (current() && connection.state === 'connecting') this.#markFailed(connection, 'CONNECT_TIMEOUT');
|
|
366
431
|
}, CONNECTION_TIMEOUT_MS);
|
|
432
|
+
connection.connectionTimeout.unref?.();
|
|
367
433
|
const offer = await pc.createOffer();
|
|
434
|
+
if (!current()) return;
|
|
368
435
|
await pc.setLocalDescription(offer);
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
436
|
+
if (!current()) return;
|
|
437
|
+
const ports = getRtcConnectPorts(connection.info);
|
|
438
|
+
if (!ports.length) throw new Error('Relay has no valid RTC port');
|
|
439
|
+
const remoteSdp = buildRemoteRelayAnswer(offer.sdp ?? '', {
|
|
440
|
+
...connection.info, port: ports[connection.rtcPortIndex % ports.length],
|
|
372
441
|
});
|
|
373
|
-
await pc.setRemoteDescription({ type:
|
|
442
|
+
await pc.setRemoteDescription({ type: 'answer', sdp: remoteSdp });
|
|
374
443
|
};
|
|
375
|
-
#restartIce =
|
|
376
|
-
if (connection.isReconnecting || !connection.hasNonStunPacketSent
|
|
377
|
-
return;
|
|
378
|
-
|
|
379
|
-
if (typeof RTCPeerConnection !== "function")
|
|
380
|
-
return;
|
|
444
|
+
#restartIce = (connection) => {
|
|
445
|
+
if (connection.isReconnecting || !connection.hasNonStunPacketSent ||
|
|
446
|
+
this.#connections.get(connection.info.id) !== connection) return;
|
|
447
|
+
this.#diagnose('ICE_RESTART');
|
|
381
448
|
connection.isReconnecting = true;
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
connection.peerConnection = pc;
|
|
390
|
-
connection.dataChannel = dc;
|
|
391
|
-
dc.binaryType = "arraybuffer";
|
|
392
|
-
dc.onopen = () => {
|
|
393
|
-
connection.state = "open";
|
|
394
|
-
connection.isReconnecting = false;
|
|
395
|
-
this.#flushBufferedPackets(connection);
|
|
396
|
-
this.#startIceRttPolling(connection);
|
|
397
|
-
};
|
|
398
|
-
dc.onclose = () => { if (connection.state !== "failed")
|
|
399
|
-
connection.state = "closed"; };
|
|
400
|
-
dc.onerror = () => { connection.state = "failed"; };
|
|
401
|
-
dc.onmessage = (event) => {
|
|
402
|
-
this.#handleIncomingPacket(connection, event.data);
|
|
403
|
-
};
|
|
404
|
-
pc.onicecandidate = (event) => {
|
|
405
|
-
if (event.candidate?.candidate && !connection.iceCandidate) {
|
|
406
|
-
connection.iceCandidate = event.candidate.candidate;
|
|
407
|
-
}
|
|
408
|
-
};
|
|
409
|
-
const offer = await pc.createOffer({ iceRestart: false });
|
|
410
|
-
let localSdp = offer.sdp ?? "";
|
|
411
|
-
if (connection.iceCandidate) {
|
|
412
|
-
localSdp = `${removeIceCandidates(localSdp)}a=${connection.iceCandidate}\r\na=end-of-candidates\r\n`;
|
|
413
|
-
}
|
|
414
|
-
await pc.setLocalDescription({ type: "offer", sdp: localSdp });
|
|
415
|
-
const remoteSdp = buildRemoteRelayAnswer(localSdp, {
|
|
416
|
-
...connection.info,
|
|
417
|
-
port: getRtcConnectPort(connection.info),
|
|
418
|
-
});
|
|
419
|
-
await pc.setRemoteDescription({ type: "answer", sdp: remoteSdp });
|
|
420
|
-
}
|
|
421
|
-
catch {
|
|
422
|
-
connection.state = "failed";
|
|
423
|
-
}
|
|
424
|
-
finally {
|
|
425
|
-
connection.isReconnecting = false;
|
|
426
|
-
}
|
|
449
|
+
connection.generation++;
|
|
450
|
+
connection.connectPromise = null;
|
|
451
|
+
if (connection.connectionTimeout) clearTimeout(connection.connectionTimeout);
|
|
452
|
+
connection.connectionTimeout = null;
|
|
453
|
+
this.#closePeerObjects(connection);
|
|
454
|
+
connection.state = 'none';
|
|
455
|
+
void this.#ensureConnection(connection.info);
|
|
427
456
|
};
|
|
428
457
|
#handleIncomingPacket = (connection, raw) => {
|
|
429
458
|
const packet = toUint8Array(raw);
|
|
@@ -447,6 +476,7 @@ export class RelayRtcTransport {
|
|
|
447
476
|
break;
|
|
448
477
|
if (!this.#sendBufferedPacket(connection, packet)) {
|
|
449
478
|
connection.stats.droppedPackets += 1;
|
|
479
|
+
this.#totals.droppedPackets += 1;
|
|
450
480
|
break;
|
|
451
481
|
}
|
|
452
482
|
}
|
|
@@ -476,10 +506,12 @@ export class RelayRtcTransport {
|
|
|
476
506
|
return;
|
|
477
507
|
const poll = async () => {
|
|
478
508
|
const rttMs = await this.#readCurrentRoundTripTimeMs(pc);
|
|
479
|
-
if (rttMs == null || connection.lastIceRttMs === rttMs)
|
|
509
|
+
if (connection.peerConnection !== pc || connection.state !== 'open' || rttMs == null || connection.lastIceRttMs === rttMs)
|
|
480
510
|
return;
|
|
481
511
|
connection.lastIceRttMs = rttMs;
|
|
482
|
-
|
|
512
|
+
// Report the port as seen by the WASM stack, not the translated
|
|
513
|
+
// WebRTC port, so its own path selection sees the correct relay.
|
|
514
|
+
this.config.onIceRtt?.(rttMs, connection.info.ip, getVoipStackPort(connection.info));
|
|
483
515
|
};
|
|
484
516
|
void poll();
|
|
485
517
|
connection.iceStatsInterval = setInterval(() => { void poll(); }, ICE_RTT_POLL_MS);
|
|
@@ -530,18 +562,31 @@ export class RelayRtcTransport {
|
|
|
530
562
|
const connection = this.#connections.get(id);
|
|
531
563
|
if (!connection)
|
|
532
564
|
return;
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
565
|
+
connection.generation++;
|
|
566
|
+
if (connection.connectionTimeout) clearTimeout(connection.connectionTimeout);
|
|
567
|
+
if (connection.retryTimer) clearTimeout(connection.retryTimer);
|
|
568
|
+
connection.connectionTimeout = null;
|
|
569
|
+
connection.retryTimer = null;
|
|
570
|
+
connection.connectPromise = null;
|
|
537
571
|
this.#closePeerObjects(connection);
|
|
538
572
|
connection.state = "closed";
|
|
573
|
+
this.#totals.droppedPackets += connection.packetBuffer.length;
|
|
539
574
|
connection.packetBuffer = [];
|
|
540
575
|
connection.bufferedBytes = 0;
|
|
541
576
|
this.#connections.delete(id);
|
|
542
577
|
};
|
|
543
578
|
#closePeerObjects = (connection) => {
|
|
544
579
|
this.#stopIceRttPolling(connection);
|
|
580
|
+
if (connection.dataChannel) {
|
|
581
|
+
connection.dataChannel.onopen = null;
|
|
582
|
+
connection.dataChannel.onclose = null;
|
|
583
|
+
connection.dataChannel.onerror = null;
|
|
584
|
+
connection.dataChannel.onmessage = null;
|
|
585
|
+
}
|
|
586
|
+
if (connection.peerConnection) {
|
|
587
|
+
connection.peerConnection.onicecandidate = null;
|
|
588
|
+
connection.peerConnection.oniceconnectionstatechange = null;
|
|
589
|
+
}
|
|
545
590
|
try {
|
|
546
591
|
connection.dataChannel?.close?.();
|
|
547
592
|
}
|
|
@@ -554,7 +599,10 @@ export class RelayRtcTransport {
|
|
|
554
599
|
connection.peerConnection = null;
|
|
555
600
|
};
|
|
556
601
|
#loadWrtc = () => {
|
|
557
|
-
this.#wrtcPromise ??=
|
|
602
|
+
this.#wrtcPromise ??= Promise.resolve()
|
|
603
|
+
.then(() => this.config.loadWrtc ? this.config.loadWrtc() : import('@roamhq/wrtc'))
|
|
604
|
+
.then((module) => module.default ?? module)
|
|
605
|
+
.catch((error) => { this.#wrtcPromise = null; throw error; });
|
|
558
606
|
return this.#wrtcPromise;
|
|
559
607
|
};
|
|
560
608
|
}
|
package/lib/VoIP/signaling.js
CHANGED
|
@@ -49,44 +49,74 @@ export class SignalingBridge {
|
|
|
49
49
|
#incomingCallPeerById = new Map();
|
|
50
50
|
#outgoingSignalingQueue = Promise.resolve(undefined);
|
|
51
51
|
#incomingSignalingQueue = Promise.resolve(undefined);
|
|
52
|
+
#originalKeysSet = null;
|
|
53
|
+
#wrappedKeysSet = null;
|
|
54
|
+
#destroyed = false;
|
|
55
|
+
#onDiagnostic;
|
|
52
56
|
|
|
53
57
|
constructor(config) {
|
|
54
58
|
this.#sock = config.sock;
|
|
59
|
+
this.#onDiagnostic = config.onDiagnostic;
|
|
55
60
|
}
|
|
56
61
|
|
|
62
|
+
#diagnose = (code) => {
|
|
63
|
+
try { this.#onDiagnostic?.({ component: 'signaling', code }); } catch {}
|
|
64
|
+
};
|
|
65
|
+
|
|
57
66
|
attachEngine = (voip) => {
|
|
58
67
|
this.#voip = voip;
|
|
59
68
|
};
|
|
60
69
|
|
|
61
70
|
init = async () => {
|
|
62
|
-
|
|
63
|
-
this.#sock.authState.keys
|
|
64
|
-
|
|
65
|
-
|
|
71
|
+
if (this.#wrappedKeysSet) throw new Error('Signaling bridge already initialized');
|
|
72
|
+
const keys = this.#sock.authState.keys;
|
|
73
|
+
this.#originalKeysSet = keys.set;
|
|
74
|
+
const original = this.#originalKeysSet;
|
|
75
|
+
this.#destroyed = false;
|
|
76
|
+
this.#wrappedKeysSet = async (data) => {
|
|
77
|
+
const result = await original.call(keys, data);
|
|
78
|
+
if (!this.#destroyed) for (const [jid, entry] of Object.entries(data?.tctoken ?? {})) {
|
|
66
79
|
if (entry?.token instanceof Uint8Array && entry.token.length > 0) {
|
|
67
80
|
this.#rememberTcToken(jid, entry.token, entry.timestamp);
|
|
68
81
|
}
|
|
69
82
|
}
|
|
70
83
|
return result;
|
|
71
84
|
};
|
|
85
|
+
keys.set = this.#wrappedKeysSet;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
destroy = () => {
|
|
89
|
+
this.#destroyed = true;
|
|
90
|
+
const keys = this.#sock.authState.keys;
|
|
91
|
+
if (keys.set === this.#wrappedKeysSet) keys.set = this.#originalKeysSet;
|
|
92
|
+
this.#wrappedKeysSet = null;
|
|
93
|
+
this.#originalKeysSet = null;
|
|
94
|
+
this.#voip = null;
|
|
95
|
+
this.#observedTcTokens.clear();
|
|
96
|
+
this.#pendingTcTokenWaiters.clear();
|
|
97
|
+
this.#ensuredSignalSessions.clear();
|
|
98
|
+
this.#remoteDevicePeerByCallId.clear();
|
|
99
|
+
this.#remoteObfuscatedPeerByCallId.clear();
|
|
100
|
+
this.#remoteXmppRoutePeerByCallId.clear();
|
|
101
|
+
this.#incomingCallPeerById.clear();
|
|
72
102
|
};
|
|
73
103
|
|
|
74
104
|
sendSignaling = (peerJid, callId, xmlPayload) => {
|
|
75
105
|
this.#outgoingSignalingQueue = this.#outgoingSignalingQueue
|
|
76
|
-
.then(() => this.#doSendSignaling(peerJid, callId, xmlPayload))
|
|
77
|
-
.catch(() => {});
|
|
106
|
+
.then(() => { if (!this.#destroyed) return this.#doSendSignaling(peerJid, callId, xmlPayload); })
|
|
107
|
+
.catch(() => { if (!this.#destroyed) this.#diagnose('OUTGOING_SIGNALING_FAILED'); });
|
|
78
108
|
};
|
|
79
109
|
|
|
80
110
|
processIncomingCall = (node, voip, activeCallId) => {
|
|
81
111
|
this.#incomingSignalingQueue = this.#incomingSignalingQueue
|
|
82
|
-
.then(() => this.#doProcessIncomingCall(node, voip, activeCallId))
|
|
83
|
-
.catch(() => {});
|
|
112
|
+
.then(() => { if (!this.#destroyed) return this.#doProcessIncomingCall(node, voip, activeCallId); })
|
|
113
|
+
.catch(() => { if (!this.#destroyed) this.#diagnose('INCOMING_SIGNALING_FAILED'); });
|
|
84
114
|
};
|
|
85
115
|
|
|
86
116
|
processIncomingReceipt = (node, voip, activeCallId) => {
|
|
87
117
|
this.#incomingSignalingQueue = this.#incomingSignalingQueue
|
|
88
|
-
.then(() => this.#doProcessIncomingReceipt(node, voip, activeCallId))
|
|
89
|
-
.catch(() => {});
|
|
118
|
+
.then(() => { if (!this.#destroyed) return this.#doProcessIncomingReceipt(node, voip, activeCallId); })
|
|
119
|
+
.catch(() => { if (!this.#destroyed) this.#diagnose('SIGNALING_RECEIPT_FAILED'); });
|
|
90
120
|
};
|
|
91
121
|
|
|
92
122
|
requestTcToken = async (jid) => {
|
|
@@ -129,10 +159,11 @@ export class SignalingBridge {
|
|
|
129
159
|
if (cached?.length) return cached;
|
|
130
160
|
}
|
|
131
161
|
for (const jid of uniqueJids) {
|
|
162
|
+
let timer;
|
|
132
163
|
const fetched = await Promise.race([
|
|
133
164
|
this.requestTcToken(jid),
|
|
134
|
-
new Promise((r) => setTimeout(() => r(undefined), TC_TOKEN_REQUEST_TIMEOUT_MS)),
|
|
135
|
-
]);
|
|
165
|
+
new Promise((r) => { timer = setTimeout(() => r(undefined), TC_TOKEN_REQUEST_TIMEOUT_MS); }),
|
|
166
|
+
]).finally(() => clearTimeout(timer));
|
|
136
167
|
if (fetched?.length) return fetched;
|
|
137
168
|
}
|
|
138
169
|
return undefined;
|
|
@@ -247,6 +278,7 @@ export class SignalingBridge {
|
|
|
247
278
|
};
|
|
248
279
|
|
|
249
280
|
#sendCallStanza = async (routeTo, voipNode, signalingTag, effectivePeerJid, callbackPeerJid) => {
|
|
281
|
+
if (this.#destroyed) return;
|
|
250
282
|
const stanzaId = this.#sock.generateMessageTag();
|
|
251
283
|
await this.#sock.sendNode({
|
|
252
284
|
tag: "call",
|
|
@@ -323,6 +355,7 @@ export class SignalingBridge {
|
|
|
323
355
|
}
|
|
324
356
|
|
|
325
357
|
const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
|
|
358
|
+
if (this.#destroyed) return;
|
|
326
359
|
|
|
327
360
|
switch (usableNode.tag) {
|
|
328
361
|
case "offer":
|
|
@@ -382,6 +415,7 @@ export class SignalingBridge {
|
|
|
382
415
|
if (callIdForRouting && routedPeerJid) this.#incomingCallPeerById.set(callIdForRouting, routedPeerJid);
|
|
383
416
|
|
|
384
417
|
const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
|
|
418
|
+
if (this.#destroyed) return;
|
|
385
419
|
voip.handleSignalingReceipt({
|
|
386
420
|
payload: Buffer.from(encodeBinaryNode(node)).toString("base64"),
|
|
387
421
|
peerJid: routedPeerJid,
|
package/lib/VoIP/types.d.ts
CHANGED
|
@@ -15,10 +15,14 @@ export type AudioConfig = {
|
|
|
15
15
|
export type CallOptions = {
|
|
16
16
|
/** Phone number, digits only (e.g. `"12345678901"`). */
|
|
17
17
|
to: string;
|
|
18
|
-
/**
|
|
18
|
+
/** Trusted operator-supplied source path; never unchecked chat input. */
|
|
19
19
|
audioSource?: string;
|
|
20
|
-
/** Auto-hangup after N ms (default: 120000). */
|
|
20
|
+
/** Auto-hangup after N ms (default: 120000, 0 disables). */
|
|
21
21
|
durationMs?: number;
|
|
22
|
+
/** End a call that has not connected (default: 45000, 0 disables). */
|
|
23
|
+
connectTimeoutMs?: number;
|
|
24
|
+
/** Hang up after the source drains (default false). */
|
|
25
|
+
endOnAudioEnd?: boolean;
|
|
22
26
|
};
|
|
23
27
|
/** Events emitted by an `ActiveCall`. */
|
|
24
28
|
export type CallEvents = {
|
|
@@ -9,6 +9,7 @@ export type WasmEngineCallbacks = {
|
|
|
9
9
|
onSignalingXmpp?: (peerJid: string, callId: string, xmlPayload: Uint8Array) => void;
|
|
10
10
|
onCallEvent?: (eventType: number, eventData?: string) => void;
|
|
11
11
|
onVoipReady?: () => void;
|
|
12
|
+
onDiagnostic?: (event: { component: string; code: string }) => void;
|
|
12
13
|
sendDataToRelay?: (data: Uint8Array, ip: string, port: number) => number;
|
|
13
14
|
onLog?: (level: string, message: string) => void;
|
|
14
15
|
onAudioCaptureInit?: (config: WasmAudioConfig) => void;
|
|
@@ -29,6 +30,8 @@ export type WasmEngineConfig = {
|
|
|
29
30
|
workerModulesCode?: string;
|
|
30
31
|
loaderModuleName?: string;
|
|
31
32
|
callbacks?: WasmEngineCallbacks;
|
|
33
|
+
/** Integer 4–20; defaults to 20 workers per pool. Smaller pools are experimental and may deadlock. */
|
|
34
|
+
workerPoolSize?: number;
|
|
32
35
|
enableLogs?: boolean;
|
|
33
36
|
options?: {
|
|
34
37
|
heartbeatInterval?: number;
|
|
@@ -38,6 +41,10 @@ export type WasmEngineConfig = {
|
|
|
38
41
|
logLevel?: number;
|
|
39
42
|
};
|
|
40
43
|
};
|
|
44
|
+
/** @internal Worker callbacks are routed to their owning engine. */
|
|
45
|
+
export declare class NodeWorkerMessagePort {
|
|
46
|
+
constructor(worker: any, name?: string, onCallback?: (name: string, data: any) => void);
|
|
47
|
+
}
|
|
41
48
|
export declare class WasmEngine {
|
|
42
49
|
#private;
|
|
43
50
|
static registerGlobalCallbackListener: (callbackName: string, handler: (data: any) => void) => void;
|