@hiroosy/baileys-lite 0.0.3 → 0.3.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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,8 +1,3 @@
1
- /**
2
- * Message-receive socket layer (wraps makeMessagesSocket from messages-send.js).
3
- * Was Socket/messages-recv.js. Handles inbound messages, receipts, notifications,
4
- * calls, retry requests, bad acks, offline node processing and tctoken pruning.
5
- */
6
1
  import { randomBytes } from 'node:crypto'
7
2
  import { proto } from '../../WAProto/index.js'
8
3
  import { Boom } from '../foundation/boom.js'
@@ -79,19 +74,22 @@ export const makeMessagesRecvSocket = (config) => {
79
74
  const sock = makeMessagesSocket(config);
80
75
  const { userDevicesCache, devicesMutex, ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache } = sock;
81
76
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
82
- /** this mutex ensures that each retryRequest will wait for the previous one to finish */
77
+
83
78
  const retryMutex = makeMutex();
79
+
84
80
  const msgRetryCache = config.msgRetryCounterCache ||
85
81
  new Cache({
86
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
82
+ max: 8192,
83
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
87
84
  useClones: false
88
85
  });
89
86
  const callOfferCache = config.callOfferCache ||
90
87
  new Cache({
91
- stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
88
+ max: 2048,
89
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
92
90
  useClones: false
93
91
  });
94
- // Debounce identity-change session refreshes per JID to avoid bursts
92
+
95
93
  const identityAssertDebounce = new Cache({ stdTTL: 5, useClones: false });
96
94
  let sendActiveReceipts = false;
97
95
  const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
@@ -119,8 +117,7 @@ export const makeMessagesRecvSocket = (config) => {
119
117
  return;
120
118
  }
121
119
  else {
122
- // Store original message data so PDO response handler can preserve
123
- // metadata (LID details, timestamps, etc.) that the phone may omit
120
+
124
121
  await placeholderResendCache.set(messageKey?.id, msgData || true);
125
122
  }
126
123
  await delay(2000);
@@ -178,7 +175,7 @@ export const makeMessagesRecvSocket = (config) => {
178
175
  case 'MessageCappingInfoNotification':
179
176
  handleMessageCappingNotification(data);
180
177
  break;
181
- // newsletter ops still use the legacy <mex> child structure
178
+
182
179
  case 'NotificationNewsletterUpdate':
183
180
  case 'NotificationLinkedProfilesUpdates':
184
181
  case 'NotificationNewsletterAdminPromote':
@@ -221,7 +218,7 @@ export const makeMessagesRecvSocket = (config) => {
221
218
  });
222
219
  return;
223
220
  }
224
- // WA Web defaults to now+60s when the server omits the expiry
221
+
225
222
  const timeEnforcementEnds = payload.time_enforcement_ends
226
223
  ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
227
224
  : new Date(Date.now() + 60000);
@@ -326,7 +323,7 @@ export const makeMessagesRecvSocket = (config) => {
326
323
  break;
327
324
  }
328
325
  };
329
- // Handles newsletter notifications
326
+
330
327
  const handleNewsletterNotification = async (node) => {
331
328
  const from = node.attrs.from;
332
329
  const children = getAllBinaryNodeChildren(node);
@@ -395,7 +392,7 @@ export const makeMessagesRecvSocket = (config) => {
395
392
  key: {
396
393
  remoteJid: from,
397
394
  id: child.attrs.message_id || child.attrs.server_id,
398
- fromMe: false // TODO: is this really true though
395
+ fromMe: false
399
396
  },
400
397
  message: messageProto,
401
398
  messageTimestamp: +child.attrs.t
@@ -416,9 +413,7 @@ export const makeMessagesRecvSocket = (config) => {
416
413
  }
417
414
  };
418
415
  const sendMessageAck = async (node, errorCode) => {
419
- // Notifications (e.g. companion_reg_refresh) can arrive and need acking before
420
- // pairing/login completes, while authState.creds.me is still undefined. Falling
421
- // back to buildAckStanza's existing no-`from` path instead of crashing here.
416
+
422
417
  const stanza = buildAckStanza(node, errorCode, authState.creds.me?.id);
423
418
  logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
424
419
  await sendNode(stanza);
@@ -449,20 +444,20 @@ export const makeMessagesRecvSocket = (config) => {
449
444
  const { key: msgKey } = fullMessage;
450
445
  const msgId = msgKey.id;
451
446
  if (messageRetryManager) {
452
- // Check if we've exceeded max retries using the new system
447
+
453
448
  if (messageRetryManager.hasExceededMaxRetries(msgId)) {
454
449
  logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
455
450
  messageRetryManager.markRetryFailed(msgId);
456
451
  return;
457
452
  }
458
- // Increment retry count using new system
453
+
459
454
  const retryCount = messageRetryManager.incrementRetryCount(msgId);
460
- // Use the new retry count for the rest of the logic
455
+
461
456
  const key = `${msgId}:${msgKey?.participant}`;
462
457
  await msgRetryCache.set(key, retryCount);
463
458
  }
464
459
  else {
465
- // Fallback to old system
460
+
466
461
  const key = `${msgId}:${msgKey?.participant}`;
467
462
  let retryCount = (await msgRetryCache.get(key)) || 0;
468
463
  if (retryCount >= maxMsgRetryCount) {
@@ -477,12 +472,12 @@ export const makeMessagesRecvSocket = (config) => {
477
472
  const retryCount = (await msgRetryCache.get(key)) || 1;
478
473
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
479
474
  const fromJid = node.attrs.from;
480
- // Check if we should recreate the session
475
+
481
476
  let shouldRecreateSession = false;
482
477
  let recreateReason = '';
483
478
  if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
484
479
  try {
485
- // Check if we have a session with this JID
480
+
486
481
  const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
487
482
  const hasSession = await signalRepository.validateSession(fromJid);
488
483
  const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
@@ -490,7 +485,7 @@ export const makeMessagesRecvSocket = (config) => {
490
485
  recreateReason = result.reason;
491
486
  if (shouldRecreateSession) {
492
487
  logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
493
- // Delete existing session to force recreation
488
+
494
489
  await authState.keys.set({ session: { [sessionId]: null } });
495
490
  forceIncludeKeys = true;
496
491
  }
@@ -500,9 +495,9 @@ export const makeMessagesRecvSocket = (config) => {
500
495
  }
501
496
  }
502
497
  if (retryCount <= 2) {
503
- // Use new retry manager for phone requests if available
498
+
504
499
  if (messageRetryManager) {
505
- // Schedule phone request with delay (like whatsmeow)
500
+
506
501
  messageRetryManager.schedulePhoneRequest(msgId, async () => {
507
502
  try {
508
503
  const requestId = await requestPlaceholderResend(msgKey);
@@ -514,7 +509,7 @@ export const makeMessagesRecvSocket = (config) => {
514
509
  });
515
510
  }
516
511
  else {
517
- // Fallback to immediate request
512
+
518
513
  const msgId = await requestPlaceholderResend(msgKey);
519
514
  logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
520
515
  }
@@ -536,7 +531,7 @@ export const makeMessagesRecvSocket = (config) => {
536
531
  id: node.attrs.id,
537
532
  t: node.attrs.t,
538
533
  v: '1',
539
- // ADD ERROR FIELD
534
+
540
535
  error: '0'
541
536
  }
542
537
  },
@@ -575,13 +570,9 @@ export const makeMessagesRecvSocket = (config) => {
575
570
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
576
571
  }, authState?.creds?.me?.id || 'sendRetryRequest');
577
572
  };
578
- // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
573
+
579
574
  const inFlightPreKeyLow = new Set();
580
- /**
581
- * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
582
- * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
583
- * the session refresh (not after it).
584
- */
575
+
585
576
  const reissueTcTokenAfterIdentityChange = (from) => {
586
577
  void (async () => {
587
578
  const normalizedJid = jidNormalizedUser(from);
@@ -645,7 +636,7 @@ export const makeMessagesRecvSocket = (config) => {
645
636
  }
646
637
  };
647
638
  const handleGroupNotification = (fullNode, child, msg) => {
648
- // TODO: Support PN/LID (Here is only LID now)
639
+
649
640
  const actingParticipantLid = fullNode.attrs.participant;
650
641
  const actingParticipantPn = fullNode.attrs.participant_pn;
651
642
  const actingParticipantUsername = fullNode.attrs.participant_username;
@@ -695,7 +686,7 @@ export const makeMessagesRecvSocket = (config) => {
695
686
  const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
696
687
  msg.messageStubType = WAMessageStubType[stubType];
697
688
  const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
698
- // TODO: Store LID MAPPINGS
689
+
699
690
  return {
700
691
  id: attrs.jid,
701
692
  phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
@@ -705,8 +696,7 @@ export const makeMessagesRecvSocket = (config) => {
705
696
  };
706
697
  });
707
698
  if (participants.length === 1 &&
708
- // if recv. "remove" message and sender removed themselves
709
- // mark as left
699
+
710
700
  (areJidsSameUser(participants[0].id, actingParticipantLid) ||
711
701
  areJidsSameUser(participants[0].id, actingParticipantPn)) &&
712
702
  child.tag === 'remove') {
@@ -761,7 +751,7 @@ export const makeMessagesRecvSocket = (config) => {
761
751
  break;
762
752
  case 'revoked_membership_requests':
763
753
  const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
764
- // TODO: LIDMAPPING SUPPORT
754
+
765
755
  msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
766
756
  msg.messageStubParameters = [
767
757
  JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
@@ -820,9 +810,7 @@ export const makeMessagesRecvSocket = (config) => {
820
810
  }
821
811
  const existingCache = (await userDevicesCache?.get(user)) || [];
822
812
  if (!existingCache.length) {
823
- // No baseline yet; skip applying the delta so getUSyncDevices can
824
- // later fetch the full device list. Caching just the notification
825
- // entries would make a partial list look authoritative.
813
+
826
814
  logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
827
815
  continue;
828
816
  }
@@ -866,7 +854,7 @@ export const makeMessagesRecvSocket = (config) => {
866
854
  await handleMexNotification(node);
867
855
  break;
868
856
  case 'w:gp2':
869
- // TODO: HANDLE PARTICIPANT_PN
857
+
870
858
  handleGroupNotification(node, child, result);
871
859
  break;
872
860
  case 'mediaretry':
@@ -894,7 +882,7 @@ export const makeMessagesRecvSocket = (config) => {
894
882
  case 'picture':
895
883
  const setPicture = getBinaryNodeChild(node, 'set');
896
884
  const delPicture = getBinaryNodeChild(node, 'delete');
897
- // TODO: WAJIDHASH stuff proper support inhouse
885
+
898
886
  ev.emit('contacts.update', [
899
887
  {
900
888
  id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
@@ -1008,11 +996,7 @@ export const makeMessagesRecvSocket = (config) => {
1008
996
  return result;
1009
997
  }
1010
998
  };
1011
- /**
1012
- * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
1013
- * Used to coalesce writes during a session; pruning always re-reads the persisted index
1014
- * to cover writes made by other layers (e.g. history sync).
1015
- */
999
+
1016
1000
  const tcTokenKnownJids = new Set();
1017
1001
  const tcTokenIndexLoaded = (async () => {
1018
1002
  try {
@@ -1031,8 +1015,7 @@ export const makeMessagesRecvSocket = (config) => {
1031
1015
  clearTimeout(tcTokenIndexTimer);
1032
1016
  tcTokenIndexTimer = undefined;
1033
1017
  }
1034
- // Merge with whatever is already persisted so we don't clobber writes from other
1035
- // paths (history sync, concurrent sessions on the same store).
1018
+
1036
1019
  const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
1037
1020
  return authState.keys.set({ tctoken: write });
1038
1021
  }
@@ -1058,8 +1041,7 @@ export const makeMessagesRecvSocket = (config) => {
1058
1041
  if (!tokensNode)
1059
1042
  return;
1060
1043
  const from = jidNormalizedUser(node.attrs.from);
1061
- // WA Web uses: senderLid ?? toLid(from) for the storage key
1062
- // The sender_lid attribute provides the LID directly when available
1044
+
1063
1045
  const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
1064
1046
  ? jidNormalizedUser(node.attrs.sender_lid)
1065
1047
  : undefined;
@@ -1102,26 +1084,26 @@ export const makeMessagesRecvSocket = (config) => {
1102
1084
  const participant = key.participant || remoteJid;
1103
1085
  const retryCount = +retryNode.attrs.count || 1;
1104
1086
  const msgId = ids[0];
1105
- // Try to get messages from cache first, then fallback to getMessage
1087
+
1106
1088
  const msgs = [];
1107
1089
  for (const id of ids) {
1108
1090
  let msg;
1109
- // Try to get from retry cache first if enabled
1091
+
1110
1092
  if (messageRetryManager) {
1111
1093
  const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1112
1094
  if (cachedMsg) {
1113
1095
  msg = cachedMsg.message;
1114
1096
  logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
1115
- // Mark retry as successful since we found the message
1097
+
1116
1098
  messageRetryManager.markRetrySuccess(id);
1117
1099
  }
1118
1100
  }
1119
- // Fallback to getMessage if not found in cache
1101
+
1120
1102
  if (!msg) {
1121
1103
  msg = await getMessage({ ...key, id });
1122
1104
  if (msg) {
1123
1105
  logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
1124
- // Also mark as successful if found via getMessage
1106
+
1125
1107
  if (messageRetryManager) {
1126
1108
  messageRetryManager.markRetrySuccess(id);
1127
1109
  }
@@ -1129,9 +1111,7 @@ export const makeMessagesRecvSocket = (config) => {
1129
1111
  }
1130
1112
  msgs.push(msg);
1131
1113
  }
1132
- // if it's the primary jid sending the request
1133
- // just re-send the message to everyone
1134
- // prevents the first message decryption failure
1114
+
1135
1115
  const sendToAll = !jidDecode(participant)?.device;
1136
1116
  const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1137
1117
  let injectedFromBundle = false;
@@ -1244,8 +1224,7 @@ export const makeMessagesRecvSocket = (config) => {
1244
1224
  receiptMutex.mutex(async () => {
1245
1225
  const status = getStatusFromReceiptType(attrs.type);
1246
1226
  if (typeof status !== 'undefined' &&
1247
- // basically, we only want to know when a message from us has been delivered to/read by the other person
1248
- // or another device of ours has read some messages
1227
+
1249
1228
  (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
1250
1229
  if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
1251
1230
  if (attrs.participant) {
@@ -1267,7 +1246,7 @@ export const makeMessagesRecvSocket = (config) => {
1267
1246
  }
1268
1247
  }
1269
1248
  if (attrs.type === 'retry') {
1270
- // correctly set who is asking for the retry
1249
+
1271
1250
  key.participant = key.participant || attrs.from;
1272
1251
  const retryNode = getBinaryNodeChild(node, 'retry');
1273
1252
  if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
@@ -1293,7 +1272,8 @@ export const makeMessagesRecvSocket = (config) => {
1293
1272
  ]);
1294
1273
  }
1295
1274
  finally {
1296
- await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
1275
+ if (!node[Symbol.for('baileys.ackedByVoip')])
1276
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
1297
1277
  }
1298
1278
  };
1299
1279
  const handleNotification = async (node) => {
@@ -1329,7 +1309,7 @@ export const makeMessagesRecvSocket = (config) => {
1329
1309
  };
1330
1310
  const handleMessage = async (node) => {
1331
1311
  const encNode = getBinaryNodeChild(node, 'enc');
1332
- // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1312
+
1333
1313
  if (encNode?.attrs.type === 'msmsg') {
1334
1314
  logger.debug({ key: node.attrs.key }, 'ignored msmsg');
1335
1315
  await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
@@ -1339,7 +1319,7 @@ export const makeMessagesRecvSocket = (config) => {
1339
1319
  try {
1340
1320
  const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1341
1321
  const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1342
- // store new mappings we didn't have before
1322
+
1343
1323
  if (!!alt) {
1344
1324
  const altServer = jidDecode(alt)?.server;
1345
1325
  const primaryJid = msg.key.participant || msg.key.remoteJid;
@@ -1359,15 +1339,14 @@ export const makeMessagesRecvSocket = (config) => {
1359
1339
  if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1360
1340
  messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1361
1341
  }
1362
- // message failed to decrypt
1342
+
1363
1343
  if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1364
1344
  if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1365
1345
  acked = true;
1366
1346
  return sendMessageAck(node, NACK_REASONS.ParsingError);
1367
1347
  }
1368
1348
  if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1369
- // Message arrived without encryption (e.g. CTWA ads messages).
1370
- // Check if this is eligible for placeholder resend (matching WA Web filters).
1349
+
1371
1350
  const unavailableNode = getBinaryNodeChild(node, 'unavailable');
1372
1351
  const unavailableType = unavailableNode?.attrs?.type;
1373
1352
  if (unavailableType === 'bot_unavailable_fanout' ||
@@ -1383,18 +1362,14 @@ export const makeMessagesRecvSocket = (config) => {
1383
1362
  acked = true;
1384
1363
  return sendMessageAck(node);
1385
1364
  }
1386
- // Request the real content from the phone via placeholder resend PDO.
1387
- // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
1388
- // and store the requestId in stubParameters[1] so users can correlate
1389
- // with the incoming PDO response event.
1365
+
1390
1366
  const cleanKey = {
1391
1367
  remoteJid: msg.key.remoteJid,
1392
1368
  fromMe: msg.key.fromMe,
1393
1369
  id: msg.key.id,
1394
1370
  participant: msg.key.participant
1395
1371
  };
1396
- // Cache the original message metadata so the PDO response handler
1397
- // can preserve key fields (LID details etc.) that the phone may omit
1372
+
1398
1373
  const msgData = {
1399
1374
  key: msg.key,
1400
1375
  messageTimestamp: msg.messageTimestamp,
@@ -1419,10 +1394,10 @@ export const makeMessagesRecvSocket = (config) => {
1419
1394
  });
1420
1395
  acked = true;
1421
1396
  await sendMessageAck(node);
1422
- // Don't return — fall through to upsertMessage so the stub is emitted
1397
+
1423
1398
  }
1424
1399
  else {
1425
- // Skip retry for expired status messages (>24h old)
1400
+
1426
1401
  if (isJidStatusBroadcast(msg.key.remoteJid)) {
1427
1402
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1428
1403
  if (messageAge > STATUS_EXPIRY_SECONDS) {
@@ -1432,7 +1407,7 @@ export const makeMessagesRecvSocket = (config) => {
1432
1407
  }
1433
1408
  }
1434
1409
  logger.debug('[handleMessage] Attempting retry request for failed decryption');
1435
- // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1410
+
1436
1411
  await retryMutex.mutex(async () => {
1437
1412
  try {
1438
1413
  if (!ws.isOpen) {
@@ -1459,19 +1434,19 @@ export const makeMessagesRecvSocket = (config) => {
1459
1434
  }
1460
1435
  const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1461
1436
  if (!isNewsletter) {
1462
- // no type in the receipt => message delivered
1437
+
1463
1438
  let type = undefined;
1464
1439
  let participant = msg.key.participant;
1465
1440
  if (category === 'peer') {
1466
- // special peer message
1441
+
1467
1442
  type = 'peer_msg';
1468
1443
  }
1469
1444
  else if (msg.key.fromMe) {
1470
- // message was sent by us from a different device
1445
+
1471
1446
  type = 'sender';
1472
- // need to specially handle this case
1447
+
1473
1448
  if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1474
- participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1449
+ participant = author;
1475
1450
  }
1476
1451
  }
1477
1452
  else if (!sendActiveReceipts) {
@@ -1479,11 +1454,11 @@ export const makeMessagesRecvSocket = (config) => {
1479
1454
  }
1480
1455
  acked = true;
1481
1456
  await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1482
- // send ack for history message
1457
+
1483
1458
  const isAnyHistoryMsg = getHistoryMsg(msg.message);
1484
1459
  if (isAnyHistoryMsg) {
1485
1460
  const jid = jidNormalizedUser(msg.key.remoteJid);
1486
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
1461
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1487
1462
  }
1488
1463
  }
1489
1464
  else {
@@ -1536,13 +1511,13 @@ export const makeMessagesRecvSocket = (config) => {
1536
1511
  await callOfferCache.set(call.id, call);
1537
1512
  }
1538
1513
  const existingCall = await callOfferCache.get(call.id);
1539
- // use existing call info to populate this event
1514
+
1540
1515
  if (existingCall) {
1541
1516
  call.isVideo = existingCall.isVideo;
1542
1517
  call.isGroup = existingCall.isGroup;
1543
1518
  call.callerPn = call.callerPn || existingCall.callerPn;
1544
1519
  }
1545
- // delete data once call has ended
1520
+
1546
1521
  if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1547
1522
  await callOfferCache.del(call.id);
1548
1523
  }
@@ -1552,34 +1527,17 @@ export const makeMessagesRecvSocket = (config) => {
1552
1527
  logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1553
1528
  }
1554
1529
  finally {
1555
- await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1530
+ if (!node[Symbol.for('baileys.ackedByVoip')])
1531
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1556
1532
  }
1557
1533
  };
1558
1534
  const handleBadAck = async ({ attrs }) => {
1559
1535
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1560
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1561
- // // current hypothesis is that if pash is sent in the ack
1562
- // // it means -- the message hasn't reached all devices yet
1563
- // // we'll retry sending the message here
1564
- // if(attrs.phash) {
1565
- // logger.info({ attrs }, 'received phash in ack, resending message...')
1566
- // const msg = await getMessage(key)
1567
- // if(msg) {
1568
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1569
- // } else {
1570
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
1571
- // }
1572
- // }
1573
- // error in acknowledgement,
1574
- // device could not display the message
1536
+
1575
1537
  if (attrs.error) {
1576
1538
  const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
1577
1539
  if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
1578
- // 463 = 1:1 message missing privacy token (tctoken). Usually means the
1579
- // account is restricted: WhatsApp blocks starting new chats but preserves
1580
- // existing ones, since established chats already carry a tctoken.
1581
- // WA Web prevents this client-side (disables the compose bar).
1582
- // No retry — retrying counts as another "reach out" and worsens the restriction.
1540
+
1583
1541
  logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
1584
1542
  const ackFrom = attrs.from;
1585
1543
  if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
@@ -1612,7 +1570,7 @@ export const makeMessagesRecvSocket = (config) => {
1612
1570
  logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1613
1571
  }
1614
1572
  else if (isReachoutTimelocked) {
1615
- // user is temporarily restricted, fetch current restriction details
1573
+
1616
1574
  await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
1617
1575
  logger.warn({ attrs }, 'received error in ack');
1618
1576
  }
@@ -1630,8 +1588,7 @@ export const makeMessagesRecvSocket = (config) => {
1630
1588
  ]);
1631
1589
  }
1632
1590
  };
1633
- /// processes a node with the given function
1634
- /// and adds the task to the existing buffer if we're buffering events
1591
+
1635
1592
  const processNodeWithBuffer = async (node, identifier, exec) => {
1636
1593
  ev.buffer();
1637
1594
  await execTask();
@@ -1651,7 +1608,7 @@ export const makeMessagesRecvSocket = (config) => {
1651
1608
  yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1652
1609
  });
1653
1610
  const processNode = async (type, node, identifier, exec) => {
1654
- // Fast path: ack and drop ignored JIDs before entering the buffer/queue
1611
+
1655
1612
  const from = node.attrs.from;
1656
1613
  let ignoreJid = from;
1657
1614
  if (type === 'receipt' && from) {
@@ -1672,7 +1629,7 @@ export const makeMessagesRecvSocket = (config) => {
1672
1629
  await processNodeWithBuffer(node, identifier, exec);
1673
1630
  }
1674
1631
  };
1675
- // recv a message
1632
+
1676
1633
  ws.on('CB:message', async (node) => {
1677
1634
  await processNode('message', node, 'processing message', handleMessage);
1678
1635
  });
@@ -1692,7 +1649,7 @@ export const makeMessagesRecvSocket = (config) => {
1692
1649
  if (!call) {
1693
1650
  return;
1694
1651
  }
1695
- // missed call + group call notification message generation
1652
+
1696
1653
  if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1697
1654
  const msg = {
1698
1655
  key: {
@@ -1719,30 +1676,28 @@ export const makeMessagesRecvSocket = (config) => {
1719
1676
  await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1720
1677
  }
1721
1678
  });
1722
- /** timestamp of last tctoken prune run — throttles to once per 24h */
1679
+
1723
1680
  let lastTcTokenPruneTs = 0;
1724
- /** dedupe in-flight 463 recovery token issuance by target JID */
1681
+
1725
1682
  const inFlight463Recoveries = new Set();
1726
1683
  ev.on('connection.update', ({ isOnline, connection }) => {
1727
1684
  if (typeof isOnline !== 'undefined') {
1728
1685
  sendActiveReceipts = isOnline;
1729
1686
  logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1730
1687
  }
1731
- // Flush pending tctoken index save on disconnect to avoid writing after close
1688
+
1732
1689
  if (connection === 'close' && tcTokenIndexTimer) {
1733
1690
  clearTimeout(tcTokenIndexTimer);
1734
1691
  tcTokenIndexTimer = undefined;
1735
- // Best-effort flush — may fail if store is already closed
1692
+
1736
1693
  try {
1737
1694
  void Promise.resolve(flushTcTokenIndex()).catch(() => { });
1738
1695
  }
1739
1696
  catch {
1740
- /* ignore sync errors */
1697
+
1741
1698
  }
1742
1699
  }
1743
- // Prune expired tctokens when coming online, at most once per 24 hours
1744
- // Matches WA Web's CLEAN_TC_TOKENS task
1745
- // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
1700
+
1746
1701
  if (isOnline) {
1747
1702
  const now = Date.now();
1748
1703
  const DAY_MS = 24 * 60 * 60 * 1000;
@@ -1765,8 +1720,7 @@ export const makeMessagesRecvSocket = (config) => {
1765
1720
  async function pruneExpiredTcTokens() {
1766
1721
  try {
1767
1722
  await tcTokenIndexLoaded;
1768
- // Union with the persisted index picks up JIDs added by other layers
1769
- // (history sync) without needing inter-module wiring.
1723
+
1770
1724
  const persisted = await readTcTokenIndex(authState.keys);
1771
1725
  const allJids = new Set(tcTokenKnownJids);
1772
1726
  for (const jid of persisted)
@@ -1781,7 +1735,7 @@ export const makeMessagesRecvSocket = (config) => {
1781
1735
  for (const jid of jids) {
1782
1736
  const entry = allTokens[jid];
1783
1737
  if (!entry) {
1784
- // Tracked but nothing in store — drop from index.
1738
+
1785
1739
  mutated++;
1786
1740
  continue;
1787
1741
  }