@xbibzlibrary/whatsbibz 1.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 (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,1307 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { makeMutex } from '../Utils/make-mutex.js';
10
+ import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
+ import { buildAckStanza } from '../Utils/stanza-ack.js';
12
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
13
+ import { extractGroupMetadata } from './groups.js';
14
+ import { makeMessagesSocket } from './messages-send.js';
15
+ export const makeMessagesRecvSocket = (config) => {
16
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
17
+ const sock = makeMessagesSocket(config);
18
+ const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
19
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
20
+ const retryMutex = makeMutex();
21
+ const msgRetryCache = config.msgRetryCounterCache ||
22
+ new NodeCache({
23
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
24
+ useClones: false
25
+ });
26
+ const callOfferCache = config.callOfferCache ||
27
+ new NodeCache({
28
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
29
+ useClones: false
30
+ });
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
36
+ // Debounce identity-change session refreshes per JID to avoid bursts
37
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
38
+ let sendActiveReceipts = false;
39
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
40
+ if (!authState.creds.me?.id) {
41
+ throw new Boom('Not authenticated');
42
+ }
43
+ const pdoMessage = {
44
+ historySyncOnDemandRequest: {
45
+ chatJid: oldestMsgKey.remoteJid,
46
+ oldestMsgFromMe: oldestMsgKey.fromMe,
47
+ oldestMsgId: oldestMsgKey.id,
48
+ oldestMsgTimestampMs: oldestMsgTimestamp,
49
+ onDemandMsgCount: count
50
+ },
51
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
52
+ };
53
+ return sendPeerDataOperationMessage(pdoMessage);
54
+ };
55
+ const requestPlaceholderResend = async (messageKey, msgData) => {
56
+ if (!authState.creds.me?.id) {
57
+ throw new Boom('Not authenticated');
58
+ }
59
+ if (await placeholderResendCache.get(messageKey?.id)) {
60
+ logger.debug({ messageKey }, 'already requested resend');
61
+ return;
62
+ }
63
+ else {
64
+ // Store original message data so PDO response handler can preserve
65
+ // metadata (LID details, timestamps, etc.) that the phone may omit
66
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
67
+ }
68
+ await delay(2000);
69
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
70
+ logger.debug({ messageKey }, 'message received while resend requested');
71
+ return 'RESOLVED';
72
+ }
73
+ const pdoMessage = {
74
+ placeholderMessageResendRequest: [
75
+ {
76
+ messageKey
77
+ }
78
+ ],
79
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
80
+ };
81
+ setTimeout(async () => {
82
+ if (await placeholderResendCache.get(messageKey?.id)) {
83
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
84
+ await placeholderResendCache.del(messageKey?.id);
85
+ }
86
+ }, 8000);
87
+ return sendPeerDataOperationMessage(pdoMessage);
88
+ };
89
+ // Handles mex newsletter notifications
90
+ const handleMexNewsletterNotification = async (node) => {
91
+ const mexNode = getBinaryNodeChild(node, 'mex');
92
+ if (!mexNode?.content) {
93
+ logger.warn({ node }, 'Invalid mex newsletter notification');
94
+ return;
95
+ }
96
+ let data;
97
+ try {
98
+ data = JSON.parse(mexNode.content.toString());
99
+ }
100
+ catch (error) {
101
+ logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
102
+ return;
103
+ }
104
+ const operation = data?.operation;
105
+ const updates = data?.updates;
106
+ if (!updates || !operation) {
107
+ logger.warn({ data }, 'Invalid mex newsletter notification content');
108
+ return;
109
+ }
110
+ logger.info({ operation, updates }, 'got mex newsletter notification');
111
+ switch (operation) {
112
+ case 'NotificationNewsletterUpdate':
113
+ for (const update of updates) {
114
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
115
+ ev.emit('newsletter-settings.update', {
116
+ id: update.jid,
117
+ update: update.settings
118
+ });
119
+ }
120
+ }
121
+ break;
122
+ case 'NotificationNewsletterAdminPromote':
123
+ for (const update of updates) {
124
+ if (update.jid && update.user) {
125
+ ev.emit('newsletter-participants.update', {
126
+ id: update.jid,
127
+ author: node.attrs.from,
128
+ user: update.user,
129
+ new_role: 'ADMIN',
130
+ action: 'promote'
131
+ });
132
+ }
133
+ }
134
+ break;
135
+ default:
136
+ logger.info({ operation, data }, 'Unhandled mex newsletter notification');
137
+ break;
138
+ }
139
+ };
140
+ // Handles newsletter notifications
141
+ const handleNewsletterNotification = async (node) => {
142
+ const from = node.attrs.from;
143
+ const child = getAllBinaryNodeChildren(node)[0];
144
+ const author = node.attrs.participant;
145
+ logger.info({ from, child }, 'got newsletter notification');
146
+ switch (child.tag) {
147
+ case 'reaction':
148
+ const reactionUpdate = {
149
+ id: from,
150
+ server_id: child.attrs.message_id,
151
+ reaction: {
152
+ code: getBinaryNodeChildString(child, 'reaction'),
153
+ count: 1
154
+ }
155
+ };
156
+ ev.emit('newsletter.reaction', reactionUpdate);
157
+ break;
158
+ case 'view':
159
+ const viewUpdate = {
160
+ id: from,
161
+ server_id: child.attrs.message_id,
162
+ count: parseInt(child.content?.toString() || '0', 10)
163
+ };
164
+ ev.emit('newsletter.view', viewUpdate);
165
+ break;
166
+ case 'participant':
167
+ const participantUpdate = {
168
+ id: from,
169
+ author,
170
+ user: child.attrs.jid,
171
+ action: child.attrs.action,
172
+ new_role: child.attrs.role
173
+ };
174
+ ev.emit('newsletter-participants.update', participantUpdate);
175
+ break;
176
+ case 'update':
177
+ const settingsNode = getBinaryNodeChild(child, 'settings');
178
+ if (settingsNode) {
179
+ const update = {};
180
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
181
+ if (nameNode?.content)
182
+ update.name = nameNode.content.toString();
183
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
184
+ if (descriptionNode?.content)
185
+ update.description = descriptionNode.content.toString();
186
+ ev.emit('newsletter-settings.update', {
187
+ id: from,
188
+ update
189
+ });
190
+ }
191
+ break;
192
+ case 'message':
193
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
194
+ if (plaintextNode?.content) {
195
+ try {
196
+ const contentBuf = typeof plaintextNode.content === 'string'
197
+ ? Buffer.from(plaintextNode.content, 'binary')
198
+ : Buffer.from(plaintextNode.content);
199
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
200
+ const fullMessage = proto.WebMessageInfo.fromObject({
201
+ key: {
202
+ remoteJid: from,
203
+ id: child.attrs.message_id || child.attrs.server_id,
204
+ fromMe: false // TODO: is this really true though
205
+ },
206
+ message: messageProto,
207
+ messageTimestamp: +child.attrs.t
208
+ }).toJSON();
209
+ await upsertMessage(fullMessage, 'append');
210
+ logger.info('Processed plaintext newsletter message');
211
+ }
212
+ catch (error) {
213
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
214
+ }
215
+ }
216
+ break;
217
+ default:
218
+ logger.warn({ node }, 'Unknown newsletter notification');
219
+ break;
220
+ }
221
+ };
222
+ const sendMessageAck = async (node, errorCode) => {
223
+ const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
224
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
225
+ await sendNode(stanza);
226
+ };
227
+ const rejectCall = async (callId, callFrom) => {
228
+ const stanza = {
229
+ tag: 'call',
230
+ attrs: {
231
+ from: authState.creds.me.id,
232
+ to: callFrom
233
+ },
234
+ content: [
235
+ {
236
+ tag: 'reject',
237
+ attrs: {
238
+ 'call-id': callId,
239
+ 'call-creator': callFrom,
240
+ count: '0'
241
+ },
242
+ content: undefined
243
+ }
244
+ ]
245
+ };
246
+ await query(stanza);
247
+ };
248
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
249
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
250
+ const { key: msgKey } = fullMessage;
251
+ const msgId = msgKey.id;
252
+ if (messageRetryManager) {
253
+ // Check if we've exceeded max retries using the new system
254
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
255
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
256
+ messageRetryManager.markRetryFailed(msgId);
257
+ return;
258
+ }
259
+ // Increment retry count using new system
260
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
261
+ // Use the new retry count for the rest of the logic
262
+ const key = `${msgId}:${msgKey?.participant}`;
263
+ await msgRetryCache.set(key, retryCount);
264
+ }
265
+ else {
266
+ // Fallback to old system
267
+ const key = `${msgId}:${msgKey?.participant}`;
268
+ let retryCount = (await msgRetryCache.get(key)) || 0;
269
+ if (retryCount >= maxMsgRetryCount) {
270
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
271
+ await msgRetryCache.del(key);
272
+ return;
273
+ }
274
+ retryCount += 1;
275
+ await msgRetryCache.set(key, retryCount);
276
+ }
277
+ const key = `${msgId}:${msgKey?.participant}`;
278
+ const retryCount = (await msgRetryCache.get(key)) || 1;
279
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
280
+ const fromJid = node.attrs.from;
281
+ // Check if we should recreate the session
282
+ let shouldRecreateSession = false;
283
+ let recreateReason = '';
284
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
285
+ try {
286
+ // Check if we have a session with this JID
287
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
288
+ const hasSession = await signalRepository.validateSession(fromJid);
289
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
290
+ shouldRecreateSession = result.recreate;
291
+ recreateReason = result.reason;
292
+ if (shouldRecreateSession) {
293
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
294
+ // Delete existing session to force recreation
295
+ await authState.keys.set({ session: { [sessionId]: null } });
296
+ forceIncludeKeys = true;
297
+ }
298
+ }
299
+ catch (error) {
300
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
301
+ }
302
+ }
303
+ if (retryCount <= 2) {
304
+ // Use new retry manager for phone requests if available
305
+ if (messageRetryManager) {
306
+ // Schedule phone request with delay (like whatsmeow)
307
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
308
+ try {
309
+ const requestId = await requestPlaceholderResend(msgKey);
310
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
311
+ }
312
+ catch (error) {
313
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
314
+ }
315
+ });
316
+ }
317
+ else {
318
+ // Fallback to immediate request
319
+ const msgId = await requestPlaceholderResend(msgKey);
320
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
321
+ }
322
+ }
323
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
324
+ await authState.keys.transaction(async () => {
325
+ const receipt = {
326
+ tag: 'receipt',
327
+ attrs: {
328
+ id: msgId,
329
+ type: 'retry',
330
+ to: node.attrs.from
331
+ },
332
+ content: [
333
+ {
334
+ tag: 'retry',
335
+ attrs: {
336
+ count: retryCount.toString(),
337
+ id: node.attrs.id,
338
+ t: node.attrs.t,
339
+ v: '1',
340
+ // ADD ERROR FIELD
341
+ error: '0'
342
+ }
343
+ },
344
+ {
345
+ tag: 'registration',
346
+ attrs: {},
347
+ content: encodeBigEndian(authState.creds.registrationId)
348
+ }
349
+ ]
350
+ };
351
+ if (node.attrs.recipient) {
352
+ receipt.attrs.recipient = node.attrs.recipient;
353
+ }
354
+ if (node.attrs.participant) {
355
+ receipt.attrs.participant = node.attrs.participant;
356
+ }
357
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
358
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
359
+ const [keyId] = Object.keys(preKeys);
360
+ const key = preKeys[+keyId];
361
+ const content = receipt.content;
362
+ content.push({
363
+ tag: 'keys',
364
+ attrs: {},
365
+ content: [
366
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
367
+ { tag: 'identity', attrs: {}, content: identityKey.public },
368
+ xmppPreKey(key, +keyId),
369
+ xmppSignedPreKey(signedPreKey),
370
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
371
+ ]
372
+ });
373
+ ev.emit('creds.update', update);
374
+ }
375
+ await sendNode(receipt);
376
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
377
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
378
+ };
379
+ const handleEncryptNotification = async (node) => {
380
+ const from = node.attrs.from;
381
+ if (from === S_WHATSAPP_NET) {
382
+ const countChild = getBinaryNodeChild(node, 'count');
383
+ const count = +countChild.attrs.value;
384
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
385
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
386
+ if (shouldUploadMorePreKeys) {
387
+ await uploadPreKeys();
388
+ }
389
+ }
390
+ else {
391
+ const result = await handleIdentityChange(node, {
392
+ meId: authState.creds.me?.id,
393
+ meLid: authState.creds.me?.lid,
394
+ validateSession: signalRepository.validateSession,
395
+ assertSessions,
396
+ debounceCache: identityAssertDebounce,
397
+ logger
398
+ });
399
+ if (result.action === 'no_identity_node') {
400
+ logger.info({ node }, 'unknown encrypt notification');
401
+ }
402
+ }
403
+ };
404
+ const handleGroupNotification = (fullNode, child, msg) => {
405
+ // TODO: Support PN/LID (Here is only LID now)
406
+ const actingParticipantLid = fullNode.attrs.participant;
407
+ const actingParticipantPn = fullNode.attrs.participant_pn;
408
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
409
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
410
+ switch (child?.tag) {
411
+ case 'create':
412
+ const metadata = extractGroupMetadata(child);
413
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
414
+ msg.messageStubParameters = [metadata.subject];
415
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
416
+ ev.emit('chats.upsert', [
417
+ {
418
+ id: metadata.id,
419
+ name: metadata.subject,
420
+ conversationTimestamp: metadata.creation
421
+ }
422
+ ]);
423
+ ev.emit('groups.upsert', [
424
+ {
425
+ ...metadata,
426
+ author: actingParticipantLid,
427
+ authorPn: actingParticipantPn
428
+ }
429
+ ]);
430
+ break;
431
+ case 'ephemeral':
432
+ case 'not_ephemeral':
433
+ msg.message = {
434
+ protocolMessage: {
435
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
436
+ ephemeralExpiration: +(child.attrs.expiration || 0)
437
+ }
438
+ };
439
+ break;
440
+ case 'modify':
441
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
442
+ msg.messageStubParameters = oldNumber || [];
443
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
444
+ break;
445
+ case 'promote':
446
+ case 'demote':
447
+ case 'remove':
448
+ case 'add':
449
+ case 'leave':
450
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
451
+ msg.messageStubType = WAMessageStubType[stubType];
452
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
453
+ // TODO: Store LID MAPPINGS
454
+ return {
455
+ id: attrs.jid,
456
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
457
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
458
+ admin: (attrs.type || null)
459
+ };
460
+ });
461
+ if (participants.length === 1 &&
462
+ // if recv. "remove" message and sender removed themselves
463
+ // mark as left
464
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
465
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
466
+ child.tag === 'remove') {
467
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
468
+ }
469
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
470
+ break;
471
+ case 'subject':
472
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
473
+ msg.messageStubParameters = [child.attrs.subject];
474
+ break;
475
+ case 'description':
476
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
477
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
478
+ msg.messageStubParameters = description ? [description] : undefined;
479
+ break;
480
+ case 'announcement':
481
+ case 'not_announcement':
482
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
483
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
484
+ break;
485
+ case 'locked':
486
+ case 'unlocked':
487
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
488
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
489
+ break;
490
+ case 'invite':
491
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
492
+ msg.messageStubParameters = [child.attrs.code];
493
+ break;
494
+ case 'member_add_mode':
495
+ const addMode = child.content;
496
+ if (addMode) {
497
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
498
+ msg.messageStubParameters = [addMode.toString()];
499
+ }
500
+ break;
501
+ case 'membership_approval_mode':
502
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
503
+ if (approvalMode) {
504
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
505
+ msg.messageStubParameters = [approvalMode.attrs.state];
506
+ }
507
+ break;
508
+ case 'created_membership_requests':
509
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
510
+ msg.messageStubParameters = [
511
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
512
+ 'created',
513
+ child.attrs.request_method
514
+ ];
515
+ break;
516
+ case 'revoked_membership_requests':
517
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
518
+ // TODO: LIDMAPPING SUPPORT
519
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
520
+ msg.messageStubParameters = [
521
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
522
+ isDenied ? 'revoked' : 'rejected'
523
+ ];
524
+ break;
525
+ }
526
+ };
527
+ const processNotification = async (node) => {
528
+ const result = {};
529
+ const [child] = getAllBinaryNodeChildren(node);
530
+ const nodeType = node.attrs.type;
531
+ const from = jidNormalizedUser(node.attrs.from);
532
+ switch (nodeType) {
533
+ case 'newsletter':
534
+ await handleNewsletterNotification(node);
535
+ break;
536
+ case 'mex':
537
+ await handleMexNewsletterNotification(node);
538
+ break;
539
+ case 'w:gp2':
540
+ // TODO: HANDLE PARTICIPANT_PN
541
+ handleGroupNotification(node, child, result);
542
+ break;
543
+ case 'mediaretry':
544
+ const event = decodeMediaRetryNode(node);
545
+ ev.emit('messages.media-update', [event]);
546
+ break;
547
+ case 'encrypt':
548
+ await handleEncryptNotification(node);
549
+ break;
550
+ case 'devices':
551
+ const devices = getBinaryNodeChildren(child, 'device');
552
+ if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
553
+ areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
554
+ const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
555
+ logger.info({ deviceData }, 'my own devices changed');
556
+ }
557
+ //TODO: drop a new event, add hashes
558
+ break;
559
+ case 'server_sync':
560
+ const update = getBinaryNodeChild(node, 'collection');
561
+ if (update) {
562
+ const name = update.attrs.name;
563
+ await resyncAppState([name], false);
564
+ }
565
+ break;
566
+ case 'picture':
567
+ const setPicture = getBinaryNodeChild(node, 'set');
568
+ const delPicture = getBinaryNodeChild(node, 'delete');
569
+ // TODO: WAJIDHASH stuff proper support inhouse
570
+ ev.emit('contacts.update', [
571
+ {
572
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
573
+ imgUrl: setPicture ? 'changed' : 'removed'
574
+ }
575
+ ]);
576
+ if (isJidGroup(from)) {
577
+ const node = setPicture || delPicture;
578
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
579
+ if (setPicture) {
580
+ result.messageStubParameters = [setPicture.attrs.id];
581
+ }
582
+ result.participant = node?.attrs.author;
583
+ result.key = {
584
+ ...(result.key || {}),
585
+ participant: setPicture?.attrs.author
586
+ };
587
+ }
588
+ break;
589
+ case 'account_sync':
590
+ if (child.tag === 'disappearing_mode') {
591
+ const newDuration = +child.attrs.duration;
592
+ const timestamp = +child.attrs.t;
593
+ logger.info({ newDuration }, 'updated account disappearing mode');
594
+ ev.emit('creds.update', {
595
+ accountSettings: {
596
+ ...authState.creds.accountSettings,
597
+ defaultDisappearingMode: {
598
+ ephemeralExpiration: newDuration,
599
+ ephemeralSettingTimestamp: timestamp
600
+ }
601
+ }
602
+ });
603
+ }
604
+ else if (child.tag === 'blocklist') {
605
+ const blocklists = getBinaryNodeChildren(child, 'item');
606
+ for (const { attrs } of blocklists) {
607
+ const blocklist = [attrs.jid];
608
+ const type = attrs.action === 'block' ? 'add' : 'remove';
609
+ ev.emit('blocklist.update', { blocklist, type });
610
+ }
611
+ }
612
+ break;
613
+ case 'link_code_companion_reg':
614
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
615
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
616
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
617
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
618
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
619
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
620
+ const random = randomBytes(32);
621
+ const linkCodeSalt = randomBytes(32);
622
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
623
+ salt: linkCodeSalt,
624
+ info: 'link_code_pairing_key_bundle_encryption_key'
625
+ });
626
+ const encryptPayload = Buffer.concat([
627
+ Buffer.from(authState.creds.signedIdentityKey.public),
628
+ primaryIdentityPublicKey,
629
+ random
630
+ ]);
631
+ const encryptIv = randomBytes(12);
632
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
633
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
634
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
635
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
636
+ authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
637
+ await query({
638
+ tag: 'iq',
639
+ attrs: {
640
+ to: S_WHATSAPP_NET,
641
+ type: 'set',
642
+ id: sock.generateMessageTag(),
643
+ xmlns: 'md'
644
+ },
645
+ content: [
646
+ {
647
+ tag: 'link_code_companion_reg',
648
+ attrs: {
649
+ jid: authState.creds.me.id,
650
+ stage: 'companion_finish'
651
+ },
652
+ content: [
653
+ {
654
+ tag: 'link_code_pairing_wrapped_key_bundle',
655
+ attrs: {},
656
+ content: encryptedPayload
657
+ },
658
+ {
659
+ tag: 'companion_identity_public',
660
+ attrs: {},
661
+ content: authState.creds.signedIdentityKey.public
662
+ },
663
+ {
664
+ tag: 'link_code_pairing_ref',
665
+ attrs: {},
666
+ content: ref
667
+ }
668
+ ]
669
+ }
670
+ ]
671
+ });
672
+ authState.creds.registered = true;
673
+ ev.emit('creds.update', authState.creds);
674
+ break;
675
+ case 'privacy_token':
676
+ await handlePrivacyTokenNotification(node);
677
+ break;
678
+ }
679
+ if (Object.keys(result).length) {
680
+ return result;
681
+ }
682
+ };
683
+ const handlePrivacyTokenNotification = async (node) => {
684
+ const tokensNode = getBinaryNodeChild(node, 'tokens');
685
+ const from = jidNormalizedUser(node.attrs.from);
686
+ if (!tokensNode)
687
+ return;
688
+ const tokenNodes = getBinaryNodeChildren(tokensNode, 'token');
689
+ for (const tokenNode of tokenNodes) {
690
+ const { attrs, content } = tokenNode;
691
+ const type = attrs.type;
692
+ const timestamp = attrs.t;
693
+ if (type === 'trusted_contact' && content instanceof Buffer) {
694
+ logger.debug({
695
+ from,
696
+ timestamp,
697
+ tcToken: content
698
+ }, 'received trusted contact token');
699
+ await authState.keys.set({
700
+ tctoken: { [from]: { token: content, timestamp } }
701
+ });
702
+ }
703
+ }
704
+ };
705
+ async function decipherLinkPublicKey(data) {
706
+ const buffer = toRequiredBuffer(data);
707
+ const salt = buffer.slice(0, 32);
708
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
709
+ const iv = buffer.slice(32, 48);
710
+ const payload = buffer.slice(48, 80);
711
+ return aesDecryptCTR(payload, secretKey, iv);
712
+ }
713
+ function toRequiredBuffer(data) {
714
+ if (data === undefined) {
715
+ throw new Boom('Invalid buffer', { statusCode: 400 });
716
+ }
717
+ return data instanceof Buffer ? data : Buffer.from(data);
718
+ }
719
+ const willSendMessageAgain = async (id, participant) => {
720
+ const key = `${id}:${participant}`;
721
+ const retryCount = (await msgRetryCache.get(key)) || 0;
722
+ return retryCount < maxMsgRetryCount;
723
+ };
724
+ const updateSendMessageAgainCount = async (id, participant) => {
725
+ const key = `${id}:${participant}`;
726
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
727
+ await msgRetryCache.set(key, newValue);
728
+ };
729
+ const sendMessagesAgain = async (key, ids, retryNode) => {
730
+ const remoteJid = key.remoteJid;
731
+ const participant = key.participant || remoteJid;
732
+ const retryCount = +retryNode.attrs.count || 1;
733
+ // Try to get messages from cache first, then fallback to getMessage
734
+ const msgs = [];
735
+ for (const id of ids) {
736
+ let msg;
737
+ // Try to get from retry cache first if enabled
738
+ if (messageRetryManager) {
739
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
740
+ if (cachedMsg) {
741
+ msg = cachedMsg.message;
742
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
743
+ // Mark retry as successful since we found the message
744
+ messageRetryManager.markRetrySuccess(id);
745
+ }
746
+ }
747
+ // Fallback to getMessage if not found in cache
748
+ if (!msg) {
749
+ msg = await getMessage({ ...key, id });
750
+ if (msg) {
751
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
752
+ // Also mark as successful if found via getMessage
753
+ if (messageRetryManager) {
754
+ messageRetryManager.markRetrySuccess(id);
755
+ }
756
+ }
757
+ }
758
+ msgs.push(msg);
759
+ }
760
+ // if it's the primary jid sending the request
761
+ // just re-send the message to everyone
762
+ // prevents the first message decryption failure
763
+ const sendToAll = !jidDecode(participant)?.device;
764
+ // Check if we should recreate session for this retry
765
+ let shouldRecreateSession = false;
766
+ let recreateReason = '';
767
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
768
+ try {
769
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
770
+ const hasSession = await signalRepository.validateSession(participant);
771
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
772
+ shouldRecreateSession = result.recreate;
773
+ recreateReason = result.reason;
774
+ if (shouldRecreateSession) {
775
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
776
+ await authState.keys.set({ session: { [sessionId]: null } });
777
+ }
778
+ }
779
+ catch (error) {
780
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
781
+ }
782
+ }
783
+ await assertSessions([participant], true);
784
+ if (isJidGroup(remoteJid)) {
785
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
786
+ }
787
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
788
+ for (const [i, msg] of msgs.entries()) {
789
+ if (!ids[i])
790
+ continue;
791
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
792
+ await updateSendMessageAgainCount(ids[i], participant);
793
+ const msgRelayOpts = { messageId: ids[i] };
794
+ if (sendToAll) {
795
+ msgRelayOpts.useUserDevicesCache = false;
796
+ }
797
+ else {
798
+ msgRelayOpts.participant = {
799
+ jid: participant,
800
+ count: +retryNode.attrs.count
801
+ };
802
+ }
803
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
804
+ }
805
+ else {
806
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
807
+ }
808
+ }
809
+ };
810
+ const handleReceipt = async (node) => {
811
+ const { attrs, content } = node;
812
+ const isLid = attrs.from.includes('lid');
813
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
814
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
815
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
816
+ const key = {
817
+ remoteJid,
818
+ id: '',
819
+ fromMe,
820
+ participant: attrs.participant
821
+ };
822
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
823
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
824
+ await sendMessageAck(node);
825
+ return;
826
+ }
827
+ const ids = [attrs.id];
828
+ if (Array.isArray(content)) {
829
+ const items = getBinaryNodeChildren(content[0], 'item');
830
+ ids.push(...items.map(i => i.attrs.id));
831
+ }
832
+ try {
833
+ await Promise.all([
834
+ receiptMutex.mutex(async () => {
835
+ const status = getStatusFromReceiptType(attrs.type);
836
+ if (typeof status !== 'undefined' &&
837
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
838
+ // or another device of ours has read some messages
839
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
840
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
841
+ if (attrs.participant) {
842
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
843
+ ev.emit('message-receipt.update', ids.map(id => ({
844
+ key: { ...key, id },
845
+ receipt: {
846
+ userJid: jidNormalizedUser(attrs.participant),
847
+ [updateKey]: +attrs.t
848
+ }
849
+ })));
850
+ }
851
+ }
852
+ else {
853
+ ev.emit('messages.update', ids.map(id => ({
854
+ key: { ...key, id },
855
+ update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
856
+ })));
857
+ }
858
+ }
859
+ if (attrs.type === 'retry') {
860
+ // correctly set who is asking for the retry
861
+ key.participant = key.participant || attrs.from;
862
+ const retryNode = getBinaryNodeChild(node, 'retry');
863
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
864
+ if (key.fromMe) {
865
+ try {
866
+ await updateSendMessageAgainCount(ids[0], key.participant);
867
+ logger.debug({ attrs, key }, 'recv retry request');
868
+ await sendMessagesAgain(key, ids, retryNode);
869
+ }
870
+ catch (error) {
871
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
872
+ }
873
+ }
874
+ else {
875
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
876
+ }
877
+ }
878
+ else {
879
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
880
+ }
881
+ }
882
+ })
883
+ ]);
884
+ }
885
+ finally {
886
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
887
+ }
888
+ };
889
+ const handleNotification = async (node) => {
890
+ const remoteJid = node.attrs.from;
891
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
892
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
893
+ await sendMessageAck(node);
894
+ return;
895
+ }
896
+ try {
897
+ await Promise.all([
898
+ notificationMutex.mutex(async () => {
899
+ const msg = await processNotification(node);
900
+ if (msg) {
901
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
902
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
903
+ msg.key = {
904
+ remoteJid,
905
+ fromMe,
906
+ participant: node.attrs.participant,
907
+ participantAlt,
908
+ addressingMode,
909
+ id: node.attrs.id,
910
+ ...(msg.key || {})
911
+ };
912
+ msg.participant ?? (msg.participant = node.attrs.participant);
913
+ msg.messageTimestamp = +node.attrs.t;
914
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
915
+ await upsertMessage(fullMsg, 'append');
916
+ }
917
+ })
918
+ ]);
919
+ }
920
+ finally {
921
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
922
+ }
923
+ };
924
+ const handleMessage = async (node) => {
925
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
926
+ logger.debug({ key: node.attrs.key }, 'ignored message');
927
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
928
+ return;
929
+ }
930
+ const encNode = getBinaryNodeChild(node, 'enc');
931
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
932
+ if (encNode?.attrs.type === 'msmsg') {
933
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
934
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
935
+ return;
936
+ }
937
+ let acked = false;
938
+ try {
939
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
940
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
941
+ // store new mappings we didn't have before
942
+ if (!!alt) {
943
+ const altServer = jidDecode(alt)?.server;
944
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
945
+ if (altServer === 'lid') {
946
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
947
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
948
+ await signalRepository.migrateSession(primaryJid, alt);
949
+ }
950
+ }
951
+ else {
952
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
953
+ await signalRepository.migrateSession(alt, primaryJid);
954
+ }
955
+ }
956
+ await messageMutex.mutex(async () => {
957
+ await decrypt();
958
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
959
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
960
+ }
961
+ // message failed to decrypt
962
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
963
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
964
+ acked = true;
965
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
966
+ }
967
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
968
+ // Message arrived without encryption (e.g. CTWA ads messages).
969
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
970
+ const unavailableNode = getBinaryNodeChild(node, 'unavailable');
971
+ const unavailableType = unavailableNode?.attrs?.type;
972
+ if (unavailableType === 'bot_unavailable_fanout' ||
973
+ unavailableType === 'hosted_unavailable_fanout' ||
974
+ unavailableType === 'view_once_unavailable_fanout') {
975
+ logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
976
+ acked = true;
977
+ return sendMessageAck(node);
978
+ }
979
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
980
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
981
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
982
+ acked = true;
983
+ return sendMessageAck(node);
984
+ }
985
+ // Request the real content from the phone via placeholder resend PDO.
986
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
987
+ // and store the requestId in stubParameters[1] so users can correlate
988
+ // with the incoming PDO response event.
989
+ const cleanKey = {
990
+ remoteJid: msg.key.remoteJid,
991
+ fromMe: msg.key.fromMe,
992
+ id: msg.key.id,
993
+ participant: msg.key.participant
994
+ };
995
+ // Cache the original message metadata so the PDO response handler
996
+ // can preserve key fields (LID details etc.) that the phone may omit
997
+ const msgData = {
998
+ key: msg.key,
999
+ messageTimestamp: msg.messageTimestamp,
1000
+ pushName: msg.pushName,
1001
+ participant: msg.participant,
1002
+ verifiedBizName: msg.verifiedBizName
1003
+ };
1004
+ requestPlaceholderResend(cleanKey, msgData)
1005
+ .then(requestId => {
1006
+ if (requestId && requestId !== 'RESOLVED') {
1007
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
1008
+ ev.emit('messages.update', [
1009
+ {
1010
+ key: msg.key,
1011
+ update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
1012
+ }
1013
+ ]);
1014
+ }
1015
+ })
1016
+ .catch(err => {
1017
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1018
+ });
1019
+ acked = true;
1020
+ await sendMessageAck(node);
1021
+ // Don't return — fall through to upsertMessage so the stub is emitted
1022
+ }
1023
+ else {
1024
+ // Skip retry for expired status messages (>24h old)
1025
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
1026
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1027
+ if (messageAge > STATUS_EXPIRY_SECONDS) {
1028
+ logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1029
+ acked = true;
1030
+ return sendMessageAck(node);
1031
+ }
1032
+ }
1033
+ const errorMessage = msg?.messageStubParameters?.[0] || '';
1034
+ const isPreKeyError = errorMessage.includes('PreKey');
1035
+ logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
1036
+ // Handle both pre-key and normal retries in single mutex
1037
+ await retryMutex.mutex(async () => {
1038
+ try {
1039
+ if (!ws.isOpen) {
1040
+ logger.debug({ node }, 'Connection closed, skipping retry');
1041
+ return;
1042
+ }
1043
+ // Handle pre-key errors with upload and delay
1044
+ if (isPreKeyError) {
1045
+ logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
1046
+ try {
1047
+ logger.debug('Uploading pre-keys for error recovery');
1048
+ await uploadPreKeys(5);
1049
+ logger.debug('Waiting for server to process new pre-keys');
1050
+ await delay(1000);
1051
+ }
1052
+ catch (uploadErr) {
1053
+ logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1054
+ }
1055
+ }
1056
+ const encNode = getBinaryNodeChild(node, 'enc');
1057
+ await sendRetryRequest(node, !encNode);
1058
+ if (retryRequestDelayMs) {
1059
+ await delay(retryRequestDelayMs);
1060
+ }
1061
+ }
1062
+ catch (err) {
1063
+ logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1064
+ // Still attempt retry even if pre-key upload failed
1065
+ try {
1066
+ const encNode = getBinaryNodeChild(node, 'enc');
1067
+ await sendRetryRequest(node, !encNode);
1068
+ }
1069
+ catch (retryErr) {
1070
+ logger.error({ retryErr }, 'Failed to send retry after error handling');
1071
+ }
1072
+ }
1073
+ acked = true;
1074
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1075
+ });
1076
+ }
1077
+ }
1078
+ else {
1079
+ if (messageRetryManager && msg.key.id) {
1080
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1081
+ }
1082
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1083
+ if (!isNewsletter) {
1084
+ // no type in the receipt => message delivered
1085
+ let type = undefined;
1086
+ let participant = msg.key.participant;
1087
+ if (category === 'peer') {
1088
+ // special peer message
1089
+ type = 'peer_msg';
1090
+ }
1091
+ else if (msg.key.fromMe) {
1092
+ // message was sent by us from a different device
1093
+ type = 'sender';
1094
+ // need to specially handle this case
1095
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1096
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1097
+ }
1098
+ }
1099
+ else if (!sendActiveReceipts) {
1100
+ type = 'inactive';
1101
+ }
1102
+ acked = true;
1103
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1104
+ // send ack for history message
1105
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1106
+ if (isAnyHistoryMsg) {
1107
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1108
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
1109
+ }
1110
+ }
1111
+ else {
1112
+ acked = true;
1113
+ await sendMessageAck(node);
1114
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1115
+ }
1116
+ }
1117
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1118
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1119
+ });
1120
+ }
1121
+ catch (error) {
1122
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1123
+ if (!acked) {
1124
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
1125
+ }
1126
+ }
1127
+ };
1128
+ const handleCall = async (node) => {
1129
+ try {
1130
+ const { attrs } = node;
1131
+ const [infoChild] = getAllBinaryNodeChildren(node);
1132
+ if (!infoChild) {
1133
+ throw new Boom('Missing call info in call node');
1134
+ }
1135
+ const status = getCallStatusFromNode(infoChild);
1136
+ const callId = infoChild.attrs['call-id'];
1137
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1138
+ const call = {
1139
+ chatId: attrs.from,
1140
+ from,
1141
+ callerPn: infoChild.attrs['caller_pn'],
1142
+ id: callId,
1143
+ date: new Date(+attrs.t * 1000),
1144
+ offline: !!attrs.offline,
1145
+ status
1146
+ };
1147
+ if (status === 'offer') {
1148
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1149
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1150
+ call.groupJid = infoChild.attrs['group-jid'];
1151
+ await callOfferCache.set(call.id, call);
1152
+ }
1153
+ const existingCall = await callOfferCache.get(call.id);
1154
+ // use existing call info to populate this event
1155
+ if (existingCall) {
1156
+ call.isVideo = existingCall.isVideo;
1157
+ call.isGroup = existingCall.isGroup;
1158
+ call.callerPn = call.callerPn || existingCall.callerPn;
1159
+ }
1160
+ // delete data once call has ended
1161
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1162
+ await callOfferCache.del(call.id);
1163
+ }
1164
+ ev.emit('call', [call]);
1165
+ }
1166
+ catch (error) {
1167
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1168
+ }
1169
+ finally {
1170
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1171
+ }
1172
+ };
1173
+ const handleBadAck = async ({ attrs }) => {
1174
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1175
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1176
+ // // current hypothesis is that if pash is sent in the ack
1177
+ // // it means -- the message hasn't reached all devices yet
1178
+ // // we'll retry sending the message here
1179
+ // if(attrs.phash) {
1180
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1181
+ // const msg = await getMessage(key)
1182
+ // if(msg) {
1183
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1184
+ // } else {
1185
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1186
+ // }
1187
+ // }
1188
+ // error in acknowledgement,
1189
+ // device could not display the message
1190
+ if (attrs.error) {
1191
+ logger.warn({ attrs }, 'received error in ack');
1192
+ ev.emit('messages.update', [
1193
+ {
1194
+ key,
1195
+ update: {
1196
+ status: WAMessageStatus.ERROR,
1197
+ messageStubParameters: [attrs.error]
1198
+ }
1199
+ }
1200
+ ]);
1201
+ // resend the message with device_fanout=false, use at your own risk
1202
+ // if (attrs.error === '475') {
1203
+ // const msg = await getMessage(key)
1204
+ // if (msg) {
1205
+ // await relayMessage(key.remoteJid!, msg, {
1206
+ // messageId: key.id!,
1207
+ // useUserDevicesCache: false,
1208
+ // additionalAttributes: {
1209
+ // device_fanout: 'false'
1210
+ // }
1211
+ // })
1212
+ // }
1213
+ // }
1214
+ }
1215
+ };
1216
+ /// processes a node with the given function
1217
+ /// and adds the task to the existing buffer if we're buffering events
1218
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1219
+ ev.buffer();
1220
+ await execTask();
1221
+ ev.flush();
1222
+ function execTask() {
1223
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1224
+ }
1225
+ };
1226
+ const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1227
+ ['message', handleMessage],
1228
+ ['call', handleCall],
1229
+ ['receipt', handleReceipt],
1230
+ ['notification', handleNotification]
1231
+ ]), {
1232
+ isWsOpen: () => ws.isOpen,
1233
+ onUnexpectedError,
1234
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1235
+ });
1236
+ const processNode = async (type, node, identifier, exec) => {
1237
+ const isOffline = !!node.attrs.offline;
1238
+ if (isOffline) {
1239
+ offlineNodeProcessor.enqueue(type, node);
1240
+ }
1241
+ else {
1242
+ await processNodeWithBuffer(node, identifier, exec);
1243
+ }
1244
+ };
1245
+ // recv a message
1246
+ ws.on('CB:message', async (node) => {
1247
+ await processNode('message', node, 'processing message', handleMessage);
1248
+ });
1249
+ ws.on('CB:call', async (node) => {
1250
+ await processNode('call', node, 'handling call', handleCall);
1251
+ });
1252
+ ws.on('CB:receipt', async (node) => {
1253
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
1254
+ });
1255
+ ws.on('CB:notification', async (node) => {
1256
+ await processNode('notification', node, 'handling notification', handleNotification);
1257
+ });
1258
+ ws.on('CB:ack,class:message', (node) => {
1259
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1260
+ });
1261
+ ev.on('call', async ([call]) => {
1262
+ if (!call) {
1263
+ return;
1264
+ }
1265
+ // missed call + group call notification message generation
1266
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1267
+ const msg = {
1268
+ key: {
1269
+ remoteJid: call.chatId,
1270
+ id: call.id,
1271
+ fromMe: false
1272
+ },
1273
+ messageTimestamp: unixTimestampSeconds(call.date)
1274
+ };
1275
+ if (call.status === 'timeout') {
1276
+ if (call.isGroup) {
1277
+ msg.messageStubType = call.isVideo
1278
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1279
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1280
+ }
1281
+ else {
1282
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1283
+ }
1284
+ }
1285
+ else {
1286
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1287
+ }
1288
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
1289
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1290
+ }
1291
+ });
1292
+ ev.on('connection.update', ({ isOnline }) => {
1293
+ if (typeof isOnline !== 'undefined') {
1294
+ sendActiveReceipts = isOnline;
1295
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1296
+ }
1297
+ });
1298
+ return {
1299
+ ...sock,
1300
+ sendMessageAck,
1301
+ sendRetryRequest,
1302
+ rejectCall,
1303
+ fetchMessageHistory,
1304
+ requestPlaceholderResend,
1305
+ messageRetryManager
1306
+ };
1307
+ };