@twsxtd/baileys 7.0.0-rc.9.commit.02a305a1ee38

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