wolfsocket 1.0.5 → 1.0.7

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 (172) hide show
  1. package/WAProto/WAProto.proto +10 -1
  2. package/WAProto/index.d.ts +26 -0
  3. package/WAProto/index.js +18415 -8908
  4. package/lib/Defaults/index.d.ts +6 -0
  5. package/lib/Defaults/index.d.ts.map +1 -1
  6. package/lib/Defaults/index.js +18 -1
  7. package/lib/Defaults/index.js.map +1 -1
  8. package/lib/Signal/lid-mapping.js +1 -1
  9. package/lib/Signal/lid-mapping.js.map +1 -1
  10. package/lib/Socket/business.d.ts +175 -7
  11. package/lib/Socket/business.d.ts.map +1 -1
  12. package/lib/Socket/channelPollVote.d.ts +44 -0
  13. package/lib/Socket/channelPollVote.d.ts.map +1 -0
  14. package/lib/Socket/channelPollVote.js +65 -0
  15. package/lib/Socket/channelPollVote.js.map +1 -0
  16. package/lib/Socket/channelSchedule.d.ts +229 -0
  17. package/lib/Socket/channelSchedule.d.ts.map +1 -0
  18. package/lib/Socket/channelSchedule.js +465 -0
  19. package/lib/Socket/channelSchedule.js.map +1 -0
  20. package/lib/Socket/channelStatus.d.ts +317 -0
  21. package/lib/Socket/channelStatus.d.ts.map +1 -0
  22. package/lib/Socket/channelStatus.js +479 -0
  23. package/lib/Socket/channelStatus.js.map +1 -0
  24. package/lib/Socket/chats.d.ts +30 -5
  25. package/lib/Socket/chats.d.ts.map +1 -1
  26. package/lib/Socket/chats.js +117 -2
  27. package/lib/Socket/chats.js.map +1 -1
  28. package/lib/Socket/communities.d.ts +177 -8
  29. package/lib/Socket/communities.d.ts.map +1 -1
  30. package/lib/Socket/communities.js +22 -6
  31. package/lib/Socket/communities.js.map +1 -1
  32. package/lib/Socket/groupHistory.d.ts +38 -0
  33. package/lib/Socket/groupHistory.d.ts.map +1 -0
  34. package/lib/Socket/groupHistory.js +88 -0
  35. package/lib/Socket/groupHistory.js.map +1 -0
  36. package/lib/Socket/groupStatus.d.ts +10 -2
  37. package/lib/Socket/groupStatus.d.ts.map +1 -1
  38. package/lib/Socket/groupStatus.js +21 -4
  39. package/lib/Socket/groupStatus.js.map +1 -1
  40. package/lib/Socket/groups.d.ts +11 -5
  41. package/lib/Socket/groups.d.ts.map +1 -1
  42. package/lib/Socket/groups.js +9 -2
  43. package/lib/Socket/groups.js.map +1 -1
  44. package/lib/Socket/index.d.ts +175 -7
  45. package/lib/Socket/index.d.ts.map +1 -1
  46. package/lib/Socket/messages-recv.d.ts +175 -7
  47. package/lib/Socket/messages-recv.d.ts.map +1 -1
  48. package/lib/Socket/messages-recv.js +152 -34
  49. package/lib/Socket/messages-recv.js.map +1 -1
  50. package/lib/Socket/messages-send.d.ts +212 -8
  51. package/lib/Socket/messages-send.d.ts.map +1 -1
  52. package/lib/Socket/messages-send.js +512 -135
  53. package/lib/Socket/messages-send.js.map +1 -1
  54. package/lib/Socket/newsletter.d.ts +11 -5
  55. package/lib/Socket/newsletter.d.ts.map +1 -1
  56. package/lib/Socket/newsletterDirectory.d.ts +201 -0
  57. package/lib/Socket/newsletterDirectory.d.ts.map +1 -0
  58. package/lib/Socket/newsletterDirectory.js +291 -0
  59. package/lib/Socket/newsletterDirectory.js.map +1 -0
  60. package/lib/Socket/payment.d.ts +37 -0
  61. package/lib/Socket/payment.d.ts.map +1 -0
  62. package/lib/Socket/payment.js +124 -0
  63. package/lib/Socket/payment.js.map +1 -0
  64. package/lib/Socket/report.d.ts +70 -0
  65. package/lib/Socket/report.d.ts.map +1 -0
  66. package/lib/Socket/report.js +265 -0
  67. package/lib/Socket/report.js.map +1 -0
  68. package/lib/Socket/socket.d.ts.map +1 -1
  69. package/lib/Socket/socket.js +17 -5
  70. package/lib/Socket/socket.js.map +1 -1
  71. package/lib/Socket/stickerPack.d.ts +29 -0
  72. package/lib/Socket/stickerPack.d.ts.map +1 -0
  73. package/lib/Socket/stickerPack.js +130 -0
  74. package/lib/Socket/stickerPack.js.map +1 -0
  75. package/lib/Socket/username.d.ts +55 -0
  76. package/lib/Socket/username.d.ts.map +1 -0
  77. package/lib/Socket/username.js +114 -0
  78. package/lib/Socket/username.js.map +1 -0
  79. package/lib/Types/ChannelStatus.d.ts +34 -0
  80. package/lib/Types/ChannelStatus.d.ts.map +1 -0
  81. package/lib/Types/ChannelStatus.js +2 -0
  82. package/lib/Types/ChannelStatus.js.map +1 -0
  83. package/lib/Types/Chat.d.ts +17 -0
  84. package/lib/Types/Chat.d.ts.map +1 -1
  85. package/lib/Types/Chat.js.map +1 -1
  86. package/lib/Types/Events.d.ts +4 -0
  87. package/lib/Types/Events.d.ts.map +1 -1
  88. package/lib/Types/GroupMetadata.d.ts +2 -0
  89. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  90. package/lib/Types/Message.d.ts +123 -3
  91. package/lib/Types/Message.d.ts.map +1 -1
  92. package/lib/Types/Payment.d.ts +47 -0
  93. package/lib/Types/Payment.d.ts.map +1 -0
  94. package/lib/Types/Payment.js +2 -0
  95. package/lib/Types/Payment.js.map +1 -0
  96. package/lib/Types/Report.d.ts +219 -0
  97. package/lib/Types/Report.d.ts.map +1 -0
  98. package/lib/Types/Report.js +166 -0
  99. package/lib/Types/Report.js.map +1 -0
  100. package/lib/Types/StickerPack.d.ts +52 -0
  101. package/lib/Types/StickerPack.d.ts.map +1 -0
  102. package/lib/Types/StickerPack.js +2 -0
  103. package/lib/Types/StickerPack.js.map +1 -0
  104. package/lib/Types/Username.d.ts +19 -0
  105. package/lib/Types/Username.d.ts.map +1 -0
  106. package/lib/Types/Username.js +2 -0
  107. package/lib/Types/Username.js.map +1 -0
  108. package/lib/Types/index.d.ts +5 -0
  109. package/lib/Types/index.d.ts.map +1 -1
  110. package/lib/Types/index.js +5 -0
  111. package/lib/Types/index.js.map +1 -1
  112. package/lib/Utils/chat-utils.d.ts.map +1 -1
  113. package/lib/Utils/chat-utils.js +19 -1
  114. package/lib/Utils/chat-utils.js.map +1 -1
  115. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  116. package/lib/Utils/decode-wa-message.js +4 -1
  117. package/lib/Utils/decode-wa-message.js.map +1 -1
  118. package/lib/Utils/event-buffer.js +21 -1
  119. package/lib/Utils/event-buffer.js.map +1 -1
  120. package/lib/Utils/generics.js +1 -1
  121. package/lib/Utils/group-history.d.ts +37 -0
  122. package/lib/Utils/group-history.d.ts.map +1 -0
  123. package/lib/Utils/group-history.js +55 -0
  124. package/lib/Utils/group-history.js.map +1 -0
  125. package/lib/Utils/index.d.ts +3 -0
  126. package/lib/Utils/index.d.ts.map +1 -1
  127. package/lib/Utils/index.js +3 -0
  128. package/lib/Utils/index.js.map +1 -1
  129. package/lib/Utils/link-preview.d.ts.map +1 -1
  130. package/lib/Utils/link-preview.js +21 -7
  131. package/lib/Utils/link-preview.js.map +1 -1
  132. package/lib/Utils/message-retry-manager.d.ts +4 -0
  133. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  134. package/lib/Utils/message-retry-manager.js +11 -0
  135. package/lib/Utils/message-retry-manager.js.map +1 -1
  136. package/lib/Utils/messages-media.d.ts +25 -9
  137. package/lib/Utils/messages-media.d.ts.map +1 -1
  138. package/lib/Utils/messages-media.js +114 -27
  139. package/lib/Utils/messages-media.js.map +1 -1
  140. package/lib/Utils/messages.d.ts +89 -2
  141. package/lib/Utils/messages.d.ts.map +1 -1
  142. package/lib/Utils/messages.js +414 -15
  143. package/lib/Utils/messages.js.map +1 -1
  144. package/lib/Utils/offline-node-processor.d.ts +1 -1
  145. package/lib/Utils/offline-node-processor.d.ts.map +1 -1
  146. package/lib/Utils/process-message.d.ts +25 -0
  147. package/lib/Utils/process-message.d.ts.map +1 -1
  148. package/lib/Utils/process-message.js +60 -2
  149. package/lib/Utils/process-message.js.map +1 -1
  150. package/lib/Utils/reporting-utils.d.ts +7 -0
  151. package/lib/Utils/reporting-utils.d.ts.map +1 -1
  152. package/lib/Utils/reporting-utils.js +7 -0
  153. package/lib/Utils/reporting-utils.js.map +1 -1
  154. package/lib/Utils/sync-key-auto-resolve.d.ts +10 -0
  155. package/lib/Utils/sync-key-auto-resolve.d.ts.map +1 -0
  156. package/lib/Utils/sync-key-auto-resolve.js +33 -0
  157. package/lib/Utils/sync-key-auto-resolve.js.map +1 -0
  158. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -1
  159. package/lib/Utils/use-multi-file-auth-state.js +34 -2
  160. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  161. package/lib/Utils/validate-connection.d.ts.map +1 -1
  162. package/lib/Utils/validate-connection.js +3 -2
  163. package/lib/Utils/validate-connection.js.map +1 -1
  164. package/lib/Utils/zip.d.ts +11 -0
  165. package/lib/Utils/zip.d.ts.map +1 -0
  166. package/lib/Utils/zip.js +88 -0
  167. package/lib/Utils/zip.js.map +1 -0
  168. package/lib/WABinary/generic-utils.d.ts +7 -0
  169. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  170. package/lib/WABinary/generic-utils.js +88 -0
  171. package/lib/WABinary/generic-utils.js.map +1 -1
  172. package/package.json +3 -3
@@ -10,7 +10,8 @@ import { makeMutex } from '../Utils/make-mutex.js';
10
10
  import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
11
  import { buildAckStanza } from '../Utils/stanza-ack.js';
12
12
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
13
- import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
13
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidBroadcast, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
14
+ import { decodeChannelStatus } from './channelStatus.js';
14
15
  import { extractGroupMetadata } from './groups.js';
15
16
  import { makeMessagesSocket } from './messages-send.js';
16
17
  const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType));
@@ -29,6 +30,13 @@ export const makeMessagesRecvSocket = (config) => {
29
30
  stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
30
31
  useClones: false
31
32
  });
33
+ const getRetryCount = async (key, defaultValue) => {
34
+ const retryCount = await msgRetryCache.get(key);
35
+ if (retryCount === undefined || retryCount === null) {
36
+ return defaultValue;
37
+ }
38
+ return Number.isFinite(retryCount) ? retryCount : maxMsgRetryCount;
39
+ };
32
40
  const callOfferCache = config.callOfferCache ||
33
41
  new NodeCache({
34
42
  stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
@@ -41,12 +49,22 @@ export const makeMessagesRecvSocket = (config) => {
41
49
  if (!authState.creds.me?.id) {
42
50
  throw new Boom('Not authenticated');
43
51
  }
52
+ let ts = oldestMsgTimestamp;
53
+ if (typeof ts === 'number' && ts > 1e11) {
54
+ ts = Math.floor(ts / 1000);
55
+ }
56
+ else if (ts !== null && typeof ts === 'object' && 'toNumber' in ts) {
57
+ const num = ts.toNumber();
58
+ if (num > 1e11) {
59
+ ts = Math.floor(num / 1000);
60
+ }
61
+ }
44
62
  const pdoMessage = {
45
63
  historySyncOnDemandRequest: {
46
64
  chatJid: oldestMsgKey.remoteJid,
47
65
  oldestMsgFromMe: oldestMsgKey.fromMe,
48
66
  oldestMsgId: oldestMsgKey.id,
49
- oldestMsgTimestampMs: oldestMsgTimestamp,
67
+ oldestMsgTimestampMs: ts,
50
68
  onDemandMsgCount: count
51
69
  },
52
70
  peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
@@ -81,10 +99,10 @@ export const makeMessagesRecvSocket = (config) => {
81
99
  };
82
100
  setTimeout(async () => {
83
101
  if (await placeholderResendCache.get(messageKey?.id)) {
84
- logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
102
+ logger.debug({ messageKey }, 'PDO message without response after 60 seconds. Phone possibly offline');
85
103
  await placeholderResendCache.del(messageKey?.id);
86
104
  }
87
- }, 8000);
105
+ }, 60000);
88
106
  return sendPeerDataOperationMessage(pdoMessage);
89
107
  };
90
108
  const handleMexNotification = async (node) => {
@@ -389,6 +407,9 @@ export const makeMessagesRecvSocket = (config) => {
389
407
  const { key: msgKey } = fullMessage;
390
408
  const msgId = msgKey.id;
391
409
  if (messageRetryManager) {
410
+ const key = `${msgId}:${msgKey?.participant}`;
411
+ const cachedRetryCount = await getRetryCount(key, 0);
412
+ messageRetryManager.restoreRetryCount(msgId, cachedRetryCount);
392
413
  // Check if we've exceeded max retries using the new system
393
414
  if (messageRetryManager.hasExceededMaxRetries(msgId)) {
394
415
  logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
@@ -398,16 +419,14 @@ export const makeMessagesRecvSocket = (config) => {
398
419
  // Increment retry count using new system
399
420
  const retryCount = messageRetryManager.incrementRetryCount(msgId);
400
421
  // Use the new retry count for the rest of the logic
401
- const key = `${msgId}:${msgKey?.participant}`;
402
422
  await msgRetryCache.set(key, retryCount);
403
423
  }
404
424
  else {
405
425
  // Fallback to old system
406
426
  const key = `${msgId}:${msgKey?.participant}`;
407
- let retryCount = (await msgRetryCache.get(key)) || 0;
427
+ let retryCount = await getRetryCount(key, 0);
408
428
  if (retryCount >= maxMsgRetryCount) {
409
429
  logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
410
- await msgRetryCache.del(key);
411
430
  return;
412
431
  }
413
432
  retryCount += 1;
@@ -623,8 +642,24 @@ export const makeMessagesRecvSocket = (config) => {
623
642
  };
624
643
  break;
625
644
  case 'modify':
626
- const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
627
- msg.messageStubParameters = oldNumber || [];
645
+ // 'modify' is not only a number change: the same w:g2
646
+ // notification carries member tag / role changes (the
647
+ // official app's GroupNotificationHandler lists "modify"
648
+ // alongside add/promote/demote/remove). Build the same
649
+ // full participant objects as promote/demote/add so the
650
+ // attributes (incl. the new admin/tag type) survive into
651
+ // messageStubParameters instead of bare JID strings.
652
+ const modifyParticipants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
653
+ return {
654
+ id: attrs.jid,
655
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
656
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
657
+ username: attrs.participant_username || attrs.username || undefined,
658
+ tag: attrs.tag || undefined,
659
+ admin: (attrs.type || null)
660
+ };
661
+ });
662
+ msg.messageStubParameters = modifyParticipants.map(a => JSON.stringify(a));
628
663
  msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
629
664
  break;
630
665
  case 'promote':
@@ -641,6 +676,7 @@ export const makeMessagesRecvSocket = (config) => {
641
676
  phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
642
677
  lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
643
678
  username: attrs.participant_username || attrs.username || undefined,
679
+ tag: attrs.tag || undefined,
644
680
  admin: (attrs.type || null)
645
681
  };
646
682
  });
@@ -878,8 +914,13 @@ export const makeMessagesRecvSocket = (config) => {
878
914
  }
879
915
  }
880
916
  break;
881
- case 'link_code_companion_reg':
917
+ case 'link_code_companion_reg': {
882
918
  const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
919
+ // Server sends two notifications: immediately after companion_hello (stage=undefined,
920
+ // only link_code_pairing_ref) and after phone enters code (stage="primary_hello",
921
+ // all 3 crypto fields). Only process the latter.
922
+ if (linkCodeCompanionReg?.attrs?.stage !== 'primary_hello')
923
+ break;
883
924
  const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
884
925
  const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
885
926
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
@@ -940,6 +981,7 @@ export const makeMessagesRecvSocket = (config) => {
940
981
  authState.creds.registered = true;
941
982
  ev.emit('creds.update', authState.creds);
942
983
  break;
984
+ }
943
985
  case 'privacy_token':
944
986
  await handlePrivacyTokenNotification(node);
945
987
  break;
@@ -1029,14 +1071,24 @@ export const makeMessagesRecvSocket = (config) => {
1029
1071
  }
1030
1072
  const willSendMessageAgain = async (id, participant) => {
1031
1073
  const key = `${id}:${participant}`;
1032
- const retryCount = (await msgRetryCache.get(key)) || 0;
1074
+ const retryCount = await getRetryCount(key, 0);
1033
1075
  return retryCount < maxMsgRetryCount;
1034
1076
  };
1035
1077
  const updateSendMessageAgainCount = async (id, participant) => {
1036
1078
  const key = `${id}:${participant}`;
1037
- const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1079
+ const newValue = (await getRetryCount(key, 0)) + 1;
1038
1080
  await msgRetryCache.set(key, newValue);
1039
1081
  };
1082
+ const acceptRetryIds = async (ids, participant) => {
1083
+ const accepted = [];
1084
+ for (const id of ids) {
1085
+ if (id && (await willSendMessageAgain(id, participant))) {
1086
+ accepted.push(id);
1087
+ await updateSendMessageAgainCount(id, participant);
1088
+ }
1089
+ }
1090
+ return accepted;
1091
+ };
1040
1092
  const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1041
1093
  const remoteJid = key.remoteJid;
1042
1094
  const participant = key.participant || remoteJid;
@@ -1137,11 +1189,11 @@ export const makeMessagesRecvSocket = (config) => {
1137
1189
  }
1138
1190
  logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
1139
1191
  for (const [i, msg] of msgs.entries()) {
1140
- if (!ids[i])
1192
+ const id = ids[i];
1193
+ if (!id)
1141
1194
  continue;
1142
- if (msg && (await willSendMessageAgain(ids[i], participant))) {
1143
- await updateSendMessageAgainCount(ids[i], participant);
1144
- const msgRelayOpts = { messageId: ids[i] };
1195
+ if (msg) {
1196
+ const msgRelayOpts = { messageId: id };
1145
1197
  if (sendToAll) {
1146
1198
  msgRelayOpts.useUserDevicesCache = false;
1147
1199
  }
@@ -1154,7 +1206,7 @@ export const makeMessagesRecvSocket = (config) => {
1154
1206
  await relayMessage(key.remoteJid, msg, msgRelayOpts);
1155
1207
  }
1156
1208
  else {
1157
- logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
1209
+ logger.debug({ jid: key.remoteJid, id }, 'recv retry request, but message not available');
1158
1210
  }
1159
1211
  }
1160
1212
  };
@@ -1198,31 +1250,47 @@ export const makeMessagesRecvSocket = (config) => {
1198
1250
  else {
1199
1251
  ev.emit('messages.update', ids.map(id => ({
1200
1252
  key: { ...key, id },
1201
- update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
1253
+ update: { status }
1202
1254
  })));
1255
+ const timestamp = Number(attrs.t);
1256
+ const timestampField = status === proto.WebMessageInfo.Status.DELIVERY_ACK
1257
+ ? 'receiptTimestamp'
1258
+ : status === proto.WebMessageInfo.Status.READ
1259
+ ? 'readTimestamp'
1260
+ : status === proto.WebMessageInfo.Status.PLAYED
1261
+ ? 'playedTimestamp'
1262
+ : undefined;
1263
+ if (!isJidBroadcast(remoteJid) &&
1264
+ !isJidBroadcast(attrs.from) &&
1265
+ timestampField &&
1266
+ Number.isSafeInteger(timestamp) &&
1267
+ timestamp > 0) {
1268
+ ev.emit('message-receipt.update', ids.map(id => ({
1269
+ key: { ...key, id },
1270
+ receipt: { userJid: jidNormalizedUser(attrs.from), [timestampField]: timestamp }
1271
+ })));
1272
+ }
1203
1273
  }
1204
1274
  }
1205
1275
  if (attrs.type === 'retry') {
1206
1276
  // correctly set who is asking for the retry
1207
1277
  key.participant = key.participant || attrs.from;
1208
1278
  const retryNode = getBinaryNodeChild(node, 'retry');
1209
- if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
1210
- if (key.fromMe) {
1211
- try {
1212
- await updateSendMessageAgainCount(ids[0], key.participant);
1213
- logger.debug({ attrs, key }, 'recv retry request');
1214
- await sendMessagesAgain(key, ids, retryNode, node);
1215
- }
1216
- catch (error) {
1217
- logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
1218
- }
1219
- }
1220
- else {
1221
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
1279
+ if (!key.fromMe) {
1280
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
1281
+ return;
1282
+ }
1283
+ try {
1284
+ const acceptedIds = key.participant ? await acceptRetryIds(ids, key.participant) : [];
1285
+ if (acceptedIds.length === 0) {
1286
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
1287
+ return;
1222
1288
  }
1289
+ logger.debug({ attrs, key }, 'recv retry request');
1290
+ await sendMessagesAgain(key, acceptedIds, retryNode, node);
1223
1291
  }
1224
- else {
1225
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
1292
+ catch (error) {
1293
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
1226
1294
  }
1227
1295
  }
1228
1296
  })
@@ -1353,11 +1421,33 @@ export const makeMessagesRecvSocket = (config) => {
1353
1421
  .catch(err => {
1354
1422
  logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1355
1423
  });
1424
+ // A PDO resend to the own phone does not answer for view-once, so
1425
+ // also ask the sender to re-encrypt and resend via a retry receipt.
1426
+ // Never for fromMe: a self-retry tears the stream down (see below).
1427
+ if (unavailableType === 'view_once' && !msg.key.fromMe) {
1428
+ sendRetryRequest(node, true).catch(err => {
1429
+ logger.warn({ err, msgId: msg.key.id }, 'failed to send view-once retry request to sender');
1430
+ });
1431
+ }
1356
1432
  acked = true;
1357
1433
  await sendMessageAck(node);
1358
1434
  // Don't return — fall through to upsertMessage so the stub is emitted
1359
1435
  }
1360
1436
  else {
1437
+ // A retry receipt only makes sense for a message from SOMEONE ELSE.
1438
+ // An undecryptable `fromMe` message is the echo of our own account
1439
+ // synced from another of our devices (sender fanout / deviceSentMessage),
1440
+ // encrypted under the ORIGINATING device's session — not under a session
1441
+ // this client holds. Asking for a resend is asking ourselves; the server
1442
+ // answers with `<stream:error><ack/>` and tears the stream down (surfaces
1443
+ // as a 500 "bad session" close, which it is not). Ack and move on: a retry
1444
+ // for our own message cannot bring the content back, and keeping the
1445
+ // connection alive is what matters.
1446
+ if (msg.key.fromMe) {
1447
+ logger.debug({ key: msg.key }, 'undecryptable fromMe message: acking without a retry receipt');
1448
+ acked = true;
1449
+ return sendMessageAck(node);
1450
+ }
1361
1451
  // Skip retry for expired status messages (>24h old)
1362
1452
  if (isJidStatusBroadcast(msg.key.remoteJid)) {
1363
1453
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
@@ -1576,11 +1666,27 @@ export const makeMessagesRecvSocket = (config) => {
1576
1666
  return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1577
1667
  }
1578
1668
  };
1669
+ const handleChannelStatus = async (node) => {
1670
+ const status = decodeChannelStatus(node);
1671
+ if (!status) {
1672
+ try {
1673
+ await sendMessageAck(node);
1674
+ }
1675
+ catch (error) {
1676
+ onUnexpectedError(error, 'acking status stanza');
1677
+ }
1678
+ return;
1679
+ }
1680
+ ev.buffer();
1681
+ ev.emit('newsletter.status', status);
1682
+ ev.flush();
1683
+ };
1579
1684
  const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1580
1685
  ['message', handleMessage],
1581
1686
  ['call', handleCall],
1582
1687
  ['receipt', handleReceipt],
1583
- ['notification', handleNotification]
1688
+ ['notification', handleNotification],
1689
+ ['status', handleChannelStatus]
1584
1690
  ]), {
1585
1691
  isWsOpen: () => ws.isOpen,
1586
1692
  onUnexpectedError,
@@ -1608,10 +1714,22 @@ export const makeMessagesRecvSocket = (config) => {
1608
1714
  await processNodeWithBuffer(node, identifier, exec);
1609
1715
  }
1610
1716
  };
1717
+ // channel statuses arrive as top-level <status> stanzas from a channel's
1718
+ // @newsletter JID, not as messages — see Socket/channelStatus.ts. A newsletter
1719
+ // status is not acked: the socket delivers live and offline ones without it,
1720
+ // and acking a newsletter status is not part of the protocol here. But a
1721
+ // CONTACT's status can arrive the same way (top-level <status> instead of
1722
+ // <message from="status@broadcast">) and that one MUST be acked, or the server
1723
+ // ends the stream ~50 minutes later and redelivers it on reconnect
1724
+ // (upstream #2883). decodeChannelStatus returns null for non-@newsletter
1725
+ // senders, so a null here means "contact status: ack it".
1611
1726
  // recv a message
1612
1727
  ws.on('CB:message', async (node) => {
1613
1728
  await processNode('message', node, 'processing message', handleMessage);
1614
1729
  });
1730
+ ws.on('CB:status', async (node) => {
1731
+ await handleChannelStatus(node).catch(error => onUnexpectedError(error, 'handling channel status'));
1732
+ });
1615
1733
  ws.on('CB:call', async (node) => {
1616
1734
  await processNode('call', node, 'handling call', handleCall);
1617
1735
  });