xero-wa 1.0.10

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