@zelynskybail/baileys 2.6.31 → 2.6.35

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.
@@ -0,0 +1,662 @@
1
+ import { decodeBinaryNode } from '../WABinary/decode.js';
2
+ import { encodeBinaryNode } from '../WABinary/encode.js';
3
+ import { getBinaryNodeChild, getAllBinaryNodeChildren } from '../WABinary/generic-utils.js';
4
+ import { jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/jid-utils.js';
5
+ import { encodeWAMessage, unpadRandomMax16 } from '../Utils/generics.js';
6
+ import { parseAndInjectE2ESessions } from '../Utils/signal.js';
7
+ import { encodeSignedDeviceIdentity } from '../Utils/validate-connection.js';
8
+ import { proto } from '../../WAProto/index.js';
9
+
10
+ const S_WHATSAPP_NET = "@s.whatsapp.net";
11
+ const TC_TOKEN_REQUEST_TIMEOUT_MS = 3500;
12
+ const SESSION_CACHE_TTL_MS = 5 * 60_000;
13
+ const ACK_TIMEOUT_MS = 15_000;
14
+
15
+ const getNodeChildren = (node) =>
16
+ Array.isArray(node.content) ? node.content : [];
17
+
18
+ const setNodeChildren = (node, children) => {
19
+ node.content = children.length ? children : undefined;
20
+ };
21
+
22
+ const replaceNodeChild = (node, tag, nextChild) => {
23
+ const children = getNodeChildren(node);
24
+ const index = children.findIndex((c) => c.tag === tag);
25
+ if (index >= 0) children[index] = nextChild;
26
+ else children.push(nextChild);
27
+ setNodeChildren(node, children);
28
+ };
29
+
30
+ const removeNodeChildrenByTag = (node, tag) => {
31
+ setNodeChildren(node, getNodeChildren(node).filter((c) => c.tag !== tag));
32
+ };
33
+
34
+ const parseCountAttr = (value, fallback = 0) => {
35
+ const parsed = Number(value);
36
+ return Number.isFinite(parsed) ? parsed : fallback;
37
+ };
38
+
39
+ export class SignalingBridge {
40
+ #sock;
41
+ #onIncomingCall = null; // JAP@Add --- inbound-offer observer (VoipClient 'incoming-call' event)
42
+ #voip = null;
43
+ #observedTcTokens = new Map();
44
+ #pendingTcTokenWaiters = new Map();
45
+ #ensuredSignalSessions = new Map();
46
+ #remoteDevicePeerByCallId = new Map();
47
+ #remoteObfuscatedPeerByCallId = new Map();
48
+ #remoteXmppRoutePeerByCallId = new Map();
49
+ #incomingCallPeerById = new Map();
50
+ #pendingOffers = new Map(); // JAP@Add --- inbound offers awaiting answer/reject (callId -> info)
51
+ #outgoingSignalingQueue = Promise.resolve(undefined);
52
+ #incomingSignalingQueue = Promise.resolve(undefined);
53
+
54
+ constructor(config) {
55
+ this.#sock = config.sock;
56
+ // JAP@Add --- optional inbound-call observer
57
+ this.#onIncomingCall = typeof config?.onIncomingCall === 'function' ? config.onIncomingCall : null;
58
+ }
59
+
60
+ attachEngine = (voip) => {
61
+ this.#voip = voip;
62
+ };
63
+
64
+ // JAP@Add --- self-contained `trusted_contact` token fetcher (the base socket
65
+ // only has `issuePrivacyTokens`, which *issues* tokens rather than *requesting*
66
+ // someone else's). Kept here so this module doesn't require patching Socket/messages-send.js.
67
+ #getPrivacyTokens = async (jids) => {
68
+ const t = Math.floor(Date.now() / 1000).toString();
69
+ return this.#sock.query({
70
+ tag: "iq",
71
+ attrs: {
72
+ to: S_WHATSAPP_NET,
73
+ type: "set",
74
+ xmlns: "privacy",
75
+ },
76
+ content: [
77
+ {
78
+ tag: "tokens",
79
+ attrs: {},
80
+ content: jids.map((jid) => ({
81
+ tag: "token",
82
+ attrs: {
83
+ jid: jidNormalizedUser(jid),
84
+ t,
85
+ type: "trusted_contact",
86
+ },
87
+ })),
88
+ },
89
+ ],
90
+ });
91
+ };
92
+
93
+ init = async () => {
94
+ const originalKeysSet = this.#sock.authState.keys.set.bind(this.#sock.authState.keys);
95
+ this.#sock.authState.keys.set = async (data) => {
96
+ const result = await originalKeysSet(data);
97
+ for (const [jid, entry] of Object.entries(data?.tctoken ?? {})) {
98
+ if (entry?.token instanceof Uint8Array && entry.token.length > 0) {
99
+ this.#rememberTcToken(jid, entry.token, entry.timestamp);
100
+ }
101
+ }
102
+ return result;
103
+ };
104
+ };
105
+
106
+ sendSignaling = (peerJid, callId, xmlPayload) => {
107
+ this.#outgoingSignalingQueue = this.#outgoingSignalingQueue
108
+ .then(() => this.#doSendSignaling(peerJid, callId, xmlPayload))
109
+ .catch(() => {});
110
+ };
111
+
112
+ processIncomingCall = (node, voip, activeCallId) => {
113
+ this.#incomingSignalingQueue = this.#incomingSignalingQueue
114
+ .then(() => this.#doProcessIncomingCall(node, voip, activeCallId))
115
+ .catch(() => {});
116
+ };
117
+
118
+ processIncomingReceipt = (node, voip, activeCallId) => {
119
+ this.#incomingSignalingQueue = this.#incomingSignalingQueue
120
+ .then(() => this.#doProcessIncomingReceipt(node, voip, activeCallId))
121
+ .catch(() => {});
122
+ };
123
+
124
+ requestTcToken = async (jid) => {
125
+ const userJid = this.#toBareJid(jid);
126
+ const cached = await this.#getTcToken(userJid);
127
+ if (cached?.length) return cached;
128
+
129
+ try {
130
+ const response = await this.#getPrivacyTokens([userJid]);
131
+ const tokensNode =
132
+ getBinaryNodeChild(response, "tokens") ??
133
+ getBinaryNodeChild(getBinaryNodeChild(response, "iq"), "tokens");
134
+ const tokenNodes = tokensNode
135
+ ? getAllBinaryNodeChildren(tokensNode).filter((c) => c.tag === "token")
136
+ : [];
137
+
138
+ for (const tokenNode of tokenNodes) {
139
+ const tokenJid = String(tokenNode.attrs.jid ?? "");
140
+ if (jidNormalizedUser(tokenJid) !== jidNormalizedUser(userJid)) continue;
141
+ const content = tokenNode.content;
142
+ if (content instanceof Uint8Array && content.length > 0) {
143
+ const token = Buffer.from(content);
144
+ await this.#sock.authState.keys.set({
145
+ tctoken: { [userJid]: { token, timestamp: String(tokenNode.attrs.t ?? "") } },
146
+ });
147
+ return token;
148
+ }
149
+ }
150
+ } catch {}
151
+
152
+ return this.#getTcToken(userJid);
153
+ };
154
+
155
+ ensureTcToken = async (...jids) => {
156
+ const uniqueJids = [
157
+ ...new Set(jids.map((j) => this.#toBareJid(String(j ?? "").trim())).filter(Boolean)),
158
+ ];
159
+ for (const jid of uniqueJids) {
160
+ const cached = await this.#getTcToken(jid);
161
+ if (cached?.length) return cached;
162
+ }
163
+ for (const jid of uniqueJids) {
164
+ const fetched = await Promise.race([
165
+ this.requestTcToken(jid),
166
+ new Promise((r) => setTimeout(() => r(undefined), TC_TOKEN_REQUEST_TIMEOUT_MS)),
167
+ ]);
168
+ if (fetched?.length) return fetched;
169
+ }
170
+ return undefined;
171
+ };
172
+
173
+ discoverPeerDevices = async (peerLidJid) => {
174
+ const devices = await this.#sock.getUSyncDevices([peerLidJid], true, false);
175
+ return this.#normalizeStartCallPeerList(devices.map((d) => d.jid).filter(Boolean));
176
+ };
177
+
178
+ ensureSessionsForPeers = async (jids) => {
179
+ const targets = this.#expandSignalSessionTargets(jids);
180
+ if (targets.length) await this.#ensureSignalSessions(targets, true);
181
+ };
182
+
183
+ resolveLid = async (pnJid) =>
184
+ this.#sock.signalRepository.lidMapping?.getLIDForPN(pnJid);
185
+
186
+ issueTcToken = async (jid) => {
187
+ const userJid = this.#toBareJid(jid);
188
+ const issuedAt = Math.floor(Date.now() / 1000);
189
+ try {
190
+ await this.#sock.query({
191
+ tag: "iq",
192
+ attrs: {
193
+ to: S_WHATSAPP_NET, type: "set", xmlns: "privacy",
194
+ id: this.#sock.generateMessageTag(),
195
+ },
196
+ content: [{
197
+ tag: "tokens", attrs: {},
198
+ content: [{
199
+ tag: "token",
200
+ attrs: { jid: userJid, t: String(issuedAt), type: "trusted_contact" },
201
+ }],
202
+ }],
203
+ });
204
+ return true;
205
+ } catch {
206
+ return false;
207
+ }
208
+ };
209
+
210
+ getRemoteDeviceJid = (callId) =>
211
+ this.#remoteDevicePeerByCallId.get(callId);
212
+
213
+ /** JAP@Add --- inspect/take a pending inbound offer (used by `answerCall`). */
214
+ getPendingOffer = (callId) => this.#pendingOffers.get(callId);
215
+ hasPendingOffer = (callId) => this.#pendingOffers.has(callId);
216
+ listPendingOffers = () => [...this.#pendingOffers.values()];
217
+ takePendingOffer = (callId) => {
218
+ const info = this.#pendingOffers.get(callId);
219
+ if (info) this.#pendingOffers.delete(callId);
220
+ return info;
221
+ };
222
+
223
+ #doSendSignaling = async (peerJid, callId, xmlPayload) => {
224
+ const rawPayload = Buffer.from(xmlPayload);
225
+ let voipNode;
226
+ try {
227
+ voipNode = await decodeBinaryNode(Buffer.concat([Buffer.from([0]), rawPayload]));
228
+ } catch {
229
+ voipNode = await decodeBinaryNode(rawPayload);
230
+ }
231
+
232
+ const signalingTag = String(voipNode.tag);
233
+ const effectivePeerJid = this.#resolveOutboundPeerJid(callId, peerJid);
234
+
235
+ if (signalingTag === "offer" && !voipNode.attrs["call-creator"]) {
236
+ const selfLid = this.#sock.authState.creds.me?.lid;
237
+ if (selfLid) voipNode.attrs["call-creator"] = selfLid;
238
+ }
239
+
240
+ const destination = getBinaryNodeChild(voipNode, "destination");
241
+ if (destination) {
242
+ const destinations = getNodeChildren(destination);
243
+ const destinationJids = destinations
244
+ .map((n) => String(n.attrs.jid ?? "").trim())
245
+ .filter(Boolean);
246
+ const sessionTargets = this.#expandSignalSessionTargets(destinationJids);
247
+ if (sessionTargets.length) await this.#ensureSignalSessions(sessionTargets, signalingTag === "offer");
248
+
249
+ const rootEnc = getBinaryNodeChild(voipNode, "enc");
250
+ const encCount = parseCountAttr(rootEnc?.attrs.count);
251
+ let includeDeviceIdentity = false;
252
+
253
+ for (const destNode of destinations) {
254
+ const targetJid = String(destNode.attrs.jid ?? "").trim();
255
+ const destEnc = getBinaryNodeChild(destNode, "enc");
256
+ if (!targetJid || !destEnc || !(destEnc.content instanceof Uint8Array)) continue;
257
+ try {
258
+ const encrypted = await this.#encryptCallKey(targetJid, destEnc.content, encCount);
259
+ includeDeviceIdentity = includeDeviceIdentity || encrypted.shouldIncludeDeviceIdentity;
260
+ setNodeChildren(destNode, [encrypted.encNode]);
261
+ } catch {
262
+ for (const d of destinations) removeNodeChildrenByTag(d, "enc");
263
+ break;
264
+ }
265
+ }
266
+ if (includeDeviceIdentity) this.#appendDeviceIdentity(voipNode);
267
+
268
+ await this.#sendCallStanza(this.#toBareJid(peerJid), voipNode, signalingTag, effectivePeerJid, peerJid);
269
+ return;
270
+ }
271
+
272
+ if (signalingTag === "offer" || signalingTag === "enc_rekey") {
273
+ const enc = getBinaryNodeChild(voipNode, "enc");
274
+ if (enc && enc.content instanceof Uint8Array) {
275
+ const targetJid = this.#toCallDeviceJid(effectivePeerJid);
276
+ const encrypted = await this.#encryptCallKey(targetJid, enc.content, parseCountAttr(enc.attrs.count));
277
+ replaceNodeChild(voipNode, "enc", encrypted.encNode);
278
+ if (encrypted.shouldIncludeDeviceIdentity) this.#appendDeviceIdentity(voipNode);
279
+
280
+ await this.#sendCallStanza(targetJid, voipNode, signalingTag, effectivePeerJid, peerJid);
281
+ return;
282
+ }
283
+ }
284
+
285
+ const routeTo = signalingTag !== "offer" && signalingTag !== "enc_rekey"
286
+ ? this.#toBareJid(effectivePeerJid)
287
+ : this.#toCallDeviceJid(effectivePeerJid);
288
+ await this.#sendCallStanza(routeTo, voipNode, signalingTag, effectivePeerJid, peerJid);
289
+ };
290
+
291
+ #sendCallStanza = async (routeTo, voipNode, signalingTag, effectivePeerJid, callbackPeerJid) => {
292
+ const stanzaId = this.#sock.generateMessageTag();
293
+ await this.#sock.sendNode({
294
+ tag: "call",
295
+ attrs: { to: routeTo, id: stanzaId },
296
+ content: [voipNode],
297
+ });
298
+
299
+ void (async () => {
300
+ try {
301
+ const ackNode = await this.#sock.waitForMessage(stanzaId, ACK_TIMEOUT_MS);
302
+ if (!ackNode || !this.#voip) return;
303
+ const ackPayload = Buffer.from(encodeBinaryNode(ackNode)).toString("base64");
304
+ const tcToken = await this.ensureTcToken(effectivePeerJid, callbackPeerJid);
305
+ try {
306
+ this.#voip.handleSignalingAck({
307
+ payload: ackPayload,
308
+ ackError: ackNode.attrs?.error ?? "0",
309
+ msgType: ackNode.attrs?.type ?? signalingTag,
310
+ peerJid: effectivePeerJid,
311
+ extraData: tcToken,
312
+ });
313
+ } catch {}
314
+ } catch {}
315
+ })();
316
+ };
317
+
318
+ #doProcessIncomingCall = async (node, voip, activeCallId) => {
319
+ const voipChild = getAllBinaryNodeChildren(node)[0];
320
+ if (!voipChild) return;
321
+
322
+ const incomingCallId = String(voipChild.attrs["call-id"] ?? voipChild.attrs.call_id ?? "");
323
+ const callIdForRouting = incomingCallId || activeCallId;
324
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId) {
325
+ // JAP@Add --- multi-call awareness: surface as busy instead of silently dropping
326
+ try { this.#onIncomingCall?.({ callId: incomingCallId, from: String(node.attrs.from ?? ''), busy: true, ignored: true }); } catch {}
327
+ return;
328
+ }
329
+
330
+ const senderDeviceJid =
331
+ String(voipChild.attrs.participant ?? "") ||
332
+ String(node.attrs.participant ?? "") ||
333
+ String(node.attrs.from ?? "") ||
334
+ String(voipChild.attrs["call-creator"] ?? "");
335
+ const callbackPeerJid = String(node.attrs.from ?? "") || senderDeviceJid;
336
+ const platform = voipChild.attrs.platform ?? node.attrs.platform ?? "";
337
+ const appVersion = voipChild.attrs.version ?? node.attrs.version ?? "";
338
+ const epochId = voipChild.attrs.e ?? node.attrs.e ?? "0";
339
+ const timestamp = voipChild.attrs.t ?? node.attrs.t ?? "0";
340
+ const offline = !!(voipChild.attrs.offline ?? node.attrs.offline);
341
+
342
+ let usableNode = voipChild;
343
+ if (getBinaryNodeChild(voipChild, "enc")) {
344
+ usableNode = await this.#maybeDecryptEnc(voipChild, senderDeviceJid);
345
+ }
346
+
347
+ const b64 = Buffer.from(encodeBinaryNode(usableNode)).toString("base64");
348
+
349
+ const storedPeerJid = callIdForRouting ? this.#incomingCallPeerById.get(callIdForRouting) : undefined;
350
+ let mappedRemoteDeviceJid = callIdForRouting ? this.#remoteDevicePeerByCallId.get(callIdForRouting) : undefined;
351
+
352
+ if (callIdForRouting && (callbackPeerJid || senderDeviceJid)) {
353
+ this.#remoteXmppRoutePeerByCallId.set(callIdForRouting, callbackPeerJid || senderDeviceJid);
354
+ const hinted = this.#pickConcreteRouteHint(senderDeviceJid, callbackPeerJid);
355
+ if (hinted && hinted !== mappedRemoteDeviceJid) {
356
+ mappedRemoteDeviceJid = hinted;
357
+ this.#remoteDevicePeerByCallId.set(callIdForRouting, hinted);
358
+ }
359
+ }
360
+
361
+ const routedPeerJid = usableNode.tag === "offer"
362
+ ? this.#preferDeviceRouteJid(senderDeviceJid, callbackPeerJid, storedPeerJid)
363
+ : this.#preferOrderedRouteJid(mappedRemoteDeviceJid, storedPeerJid, senderDeviceJid, callbackPeerJid);
364
+
365
+ if (callIdForRouting && routedPeerJid) {
366
+ this.#incomingCallPeerById.set(callIdForRouting, routedPeerJid);
367
+ }
368
+
369
+ const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
370
+
371
+ switch (usableNode.tag) {
372
+ case "offer":
373
+ voip.handleSignalingOffer({
374
+ payload: b64,
375
+ peerPlatform: Number(platform || 0),
376
+ peerAppVersion: appVersion,
377
+ epochId, timestamp,
378
+ isOffline: offline,
379
+ isOfferNotContact: false,
380
+ peerJid: routedPeerJid,
381
+ tcToken,
382
+ });
383
+ // JAP@Add --- track the offer so `answerCall()`/`joinGroupCall()` can pick it up,
384
+ // then surface it so bots can react (log / auto-reply / auto-answer).
385
+ try {
386
+ const fromAttr = String(node.attrs.from ?? '');
387
+ const info = {
388
+ callId: callIdForRouting,
389
+ from: routedPeerJid,
390
+ senderDeviceJid,
391
+ callCreator: String(voipChild.attrs['call-creator'] ?? ''),
392
+ groupJid: fromAttr.endsWith('@g.us') ? fromAttr : '',
393
+ isGroupCall: fromAttr.endsWith('@g.us'),
394
+ platform,
395
+ appVersion,
396
+ timestamp: Number(timestamp || 0),
397
+ isOffline: offline,
398
+ receivedAt: Date.now(),
399
+ };
400
+ if (callIdForRouting) this.#pendingOffers.set(callIdForRouting, info);
401
+ this.#onIncomingCall?.({ ...info });
402
+ } catch {}
403
+ break;
404
+ case "ack":
405
+ voip.handleSignalingAck({
406
+ payload: b64,
407
+ ackError: usableNode.attrs.error ?? "0",
408
+ msgType: usableNode.attrs.type ?? "",
409
+ peerJid: routedPeerJid,
410
+ extraData: tcToken,
411
+ });
412
+ break;
413
+ default:
414
+ voip.handleSignalingMessage({
415
+ payload: b64,
416
+ peerPlatform: platform,
417
+ peerAppVersion: appVersion,
418
+ epochId, timestamp,
419
+ isOffline: offline,
420
+ peerJid: routedPeerJid,
421
+ tcToken,
422
+ });
423
+ if (callIdForRouting && (usableNode.tag === "terminate" || usableNode.tag === "reject")) {
424
+ this.#pendingOffers.delete(callIdForRouting);
425
+ this.#incomingCallPeerById.delete(callIdForRouting);
426
+ this.#remoteDevicePeerByCallId.delete(callIdForRouting);
427
+ this.#remoteObfuscatedPeerByCallId.delete(callIdForRouting);
428
+ this.#remoteXmppRoutePeerByCallId.delete(callIdForRouting);
429
+ }
430
+ break;
431
+ }
432
+ };
433
+
434
+ #doProcessIncomingReceipt = async (node, voip, activeCallId) => {
435
+ const receiptChild = getAllBinaryNodeChildren(node)[0];
436
+ if (!receiptChild) return;
437
+
438
+ const incomingCallId = String(receiptChild.attrs["call-id"] ?? receiptChild.attrs.call_id ?? "");
439
+ const callIdForRouting = incomingCallId || activeCallId;
440
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId) return;
441
+
442
+ const callbackPeerJid = String(node.attrs.from ?? receiptChild.attrs["call-creator"] ?? "");
443
+ const storedPeerJid = callIdForRouting ? this.#incomingCallPeerById.get(callIdForRouting) : undefined;
444
+ const routedPeerJid = this.#preferOrderedRouteJid(storedPeerJid, callbackPeerJid);
445
+ if (callIdForRouting && routedPeerJid) this.#incomingCallPeerById.set(callIdForRouting, routedPeerJid);
446
+
447
+ const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
448
+ voip.handleSignalingReceipt({
449
+ payload: Buffer.from(encodeBinaryNode(node)).toString("base64"),
450
+ peerJid: routedPeerJid,
451
+ tcToken,
452
+ });
453
+ };
454
+
455
+ #maybeDecryptEnc = async (voipNode, peerJid) => {
456
+ const enc = getBinaryNodeChild(voipNode, "enc");
457
+ if (!enc || !(enc.content instanceof Uint8Array)) return voipNode;
458
+ const type = enc.attrs.type;
459
+ if (type !== "pkmsg" && type !== "msg") return voipNode;
460
+
461
+ const candidates = [...new Set([peerJid, this.#toCallDeviceJid(peerJid)])].filter(Boolean);
462
+ let lastErr;
463
+ for (const jid of candidates) {
464
+ try {
465
+ const decrypted = await this.#sock.signalRepository.decryptMessage({
466
+ jid, type, ciphertext: enc.content,
467
+ });
468
+ const parsed = proto.Message.decode(unpadRandomMax16(decrypted));
469
+ const callKey = parsed.call?.callKey;
470
+ if (!callKey || callKey.length === 0) {
471
+ throw new Error("decrypted signaling has no call.callKey");
472
+ }
473
+ enc.content = callKey;
474
+ return voipNode;
475
+ } catch (err) {
476
+ lastErr = err;
477
+ }
478
+ }
479
+ throw lastErr;
480
+ };
481
+
482
+ #encryptCallKey = async (targetJid, rawCallKey, count) => {
483
+ const primaryDeviceJid = this.#toPrimaryDeviceJid(targetJid);
484
+ const sessionTargets = primaryDeviceJid && primaryDeviceJid !== targetJid
485
+ ? [primaryDeviceJid, targetJid]
486
+ : [targetJid];
487
+ await this.#ensureSignalSessions(sessionTargets, false);
488
+
489
+ const { type, ciphertext } = await this.#sock.signalRepository.encryptMessage({
490
+ jid: targetJid,
491
+ data: encodeWAMessage({ call: { callKey: Buffer.from(rawCallKey) } }),
492
+ });
493
+
494
+ return {
495
+ encNode: {
496
+ tag: "enc",
497
+ attrs: { v: "2", type, count: String(count) },
498
+ content: Buffer.from(ciphertext),
499
+ },
500
+ shouldIncludeDeviceIdentity: type === "pkmsg",
501
+ };
502
+ };
503
+
504
+ #ensureSignalSessions = async (jids, refresh) => {
505
+ const missing = [];
506
+ for (const jid of [...new Set(jids.filter(Boolean))]) {
507
+ const signalId = this.#sock.signalRepository.jidToSignalProtocolAddress(jid);
508
+ const cachedAt = this.#ensuredSignalSessions.get(signalId);
509
+ if (!refresh && cachedAt && Date.now() - cachedAt < SESSION_CACHE_TTL_MS) continue;
510
+ if (!refresh) {
511
+ const validation = await this.#sock.signalRepository.validateSession(jid);
512
+ if (validation.exists) {
513
+ this.#ensuredSignalSessions.set(signalId, Date.now());
514
+ continue;
515
+ }
516
+ }
517
+ missing.push(jid);
518
+ }
519
+ if (!missing.length) return;
520
+
521
+ const sessionNode = await this.#sock.query({
522
+ tag: "iq",
523
+ attrs: { xmlns: "encrypt", type: "get", to: S_WHATSAPP_NET },
524
+ content: [{
525
+ tag: "key", attrs: {},
526
+ content: missing.map((jid) => ({ tag: "user", attrs: { jid } })),
527
+ }],
528
+ });
529
+ await parseAndInjectE2ESessions(sessionNode, this.#sock.signalRepository);
530
+ for (const jid of missing) {
531
+ this.#ensuredSignalSessions.set(
532
+ this.#sock.signalRepository.jidToSignalProtocolAddress(jid),
533
+ Date.now(),
534
+ );
535
+ }
536
+ };
537
+
538
+ #appendDeviceIdentity = (voipNode) => {
539
+ if (getBinaryNodeChild(voipNode, "device-identity")) return;
540
+ const account = this.#sock.authState.creds.account;
541
+ if (!account) return;
542
+ const children = getNodeChildren(voipNode);
543
+ children.push({
544
+ tag: "device-identity",
545
+ attrs: {},
546
+ content: encodeSignedDeviceIdentity(account, true),
547
+ });
548
+ setNodeChildren(voipNode, children);
549
+ };
550
+
551
+ #toBareJid = (jid) => {
552
+ const decoded = jidDecode(jid);
553
+ if (!decoded?.user) return jid;
554
+ const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
555
+ return jidEncode(decoded.user, server);
556
+ };
557
+
558
+ #toCallDeviceJid = (jid) => {
559
+ const decoded = jidDecode(jid);
560
+ if (!decoded?.user) return jid;
561
+ const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
562
+ if (decoded.device == null) return jidEncode(decoded.user, server);
563
+ return `${decoded.user}:${decoded.device}@${server}`;
564
+ };
565
+
566
+ #toPrimaryDeviceJid = (jid) => {
567
+ const decoded = jidDecode(jid);
568
+ if (!decoded?.user) return undefined;
569
+ const device = decoded.device;
570
+ if (device == null || device === 0) return undefined;
571
+ const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
572
+ return jidEncode(decoded.user, server);
573
+ };
574
+
575
+ #hasConcreteDevice = (jid) => {
576
+ const decoded = jidDecode(jid);
577
+ return !!decoded?.user && decoded.device != null;
578
+ };
579
+
580
+ #preferDeviceRouteJid = (...candidates) => {
581
+ for (const c of candidates) {
582
+ const jid = String(c ?? "").trim();
583
+ if (jid && this.#hasConcreteDevice(jid)) return jid;
584
+ }
585
+ for (const c of candidates) {
586
+ const jid = String(c ?? "").trim();
587
+ if (jid) return this.#toCallDeviceJid(jid);
588
+ }
589
+ return "";
590
+ };
591
+
592
+ #preferOrderedRouteJid = (...candidates) => {
593
+ for (const c of candidates) {
594
+ const jid = String(c ?? "").trim();
595
+ if (jid) return this.#toCallDeviceJid(jid);
596
+ }
597
+ return "";
598
+ };
599
+
600
+ #pickConcreteRouteHint = (...candidates) => {
601
+ for (const c of candidates) {
602
+ const jid = String(c ?? "").trim();
603
+ if (jid && this.#hasConcreteDevice(jid)) return jid;
604
+ }
605
+ return "";
606
+ };
607
+
608
+ #resolveOutboundPeerJid = (callId, wasmPeerJid) => {
609
+ const peerJid = String(wasmPeerJid ?? "").trim();
610
+ if (!peerJid || !callId) return peerJid;
611
+ return this.#remoteDevicePeerByCallId.get(callId) ?? peerJid;
612
+ };
613
+
614
+ #expandSignalSessionTargets = (jids) =>
615
+ [...new Set(jids.flatMap((jid) => {
616
+ const primary = this.#toPrimaryDeviceJid(jid);
617
+ return primary && primary !== jid ? [primary, jid] : [jid];
618
+ }))];
619
+
620
+ #normalizeStartCallPeerList = (jids) => {
621
+ const result = new Set();
622
+ for (const jid of jids) {
623
+ const decoded = jidDecode(jid);
624
+ if (!decoded?.user) {
625
+ result.add(jid);
626
+ continue;
627
+ }
628
+ const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
629
+ result.add(jidEncode(decoded.user, server));
630
+ if (decoded.device != null) {
631
+ result.add(`${decoded.user}:${decoded.device}@${server}`);
632
+ }
633
+ }
634
+ return [...result].slice(0, 5);
635
+ };
636
+
637
+ #rememberTcToken = (jid, token, timestamp = "") => {
638
+ const bareJid = this.#toBareJid(jid);
639
+ if (!token.length) return;
640
+ this.#observedTcTokens.set(bareJid, { token: Buffer.from(token), timestamp });
641
+ const waiters = this.#pendingTcTokenWaiters.get(bareJid);
642
+ if (waiters?.length) {
643
+ this.#pendingTcTokenWaiters.delete(bareJid);
644
+ for (const w of waiters) w(Buffer.from(token));
645
+ }
646
+ };
647
+
648
+ #getTcToken = async (jid) => {
649
+ const userJid = this.#toBareJid(jid);
650
+ const observed = this.#observedTcTokens.get(userJid)?.token;
651
+ if (observed?.length) return Buffer.from(observed);
652
+ try {
653
+ const data = await this.#sock.authState.keys.get("tctoken", [userJid]);
654
+ const token = data[userJid]?.token;
655
+ if (token && token.length > 0) {
656
+ this.#rememberTcToken(userJid, token, data[userJid]?.timestamp);
657
+ return token;
658
+ }
659
+ } catch {}
660
+ return undefined;
661
+ };
662
+ }