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