@neelegirl/baileys 1.5.6 → 1.5.8

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 (421) hide show
  1. package/README.md +24 -27
  2. package/WAProto/WAProto.proto +665 -291
  3. package/WAProto/index.d.ts +48037 -2294
  4. package/WAProto/index.js +139804 -45203
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.d.ts +64 -58
  7. package/lib/Defaults/index.js +96 -74
  8. package/lib/Defaults/phonenumber-mcc.json +223 -0
  9. package/lib/Signal/WASignalGroup/GroupProtocol.js +1909 -0
  10. package/lib/Signal/WASignalGroup/ciphertext_message.js +16 -0
  11. package/lib/Signal/WASignalGroup/generate-proto.sh +1 -0
  12. package/lib/Signal/WASignalGroup/group.proto +42 -0
  13. package/lib/Signal/WASignalGroup/group_cipher.js +120 -0
  14. package/lib/Signal/WASignalGroup/group_session_builder.js +46 -0
  15. package/lib/Signal/WASignalGroup/index.js +6 -0
  16. package/lib/Signal/WASignalGroup/keyhelper.js +21 -0
  17. package/lib/Signal/WASignalGroup/protobufs.js +3 -0
  18. package/lib/Signal/WASignalGroup/queue_job.js +69 -0
  19. package/lib/Signal/WASignalGroup/readme.md +6 -0
  20. package/lib/Signal/WASignalGroup/sender_chain_key.js +50 -0
  21. package/lib/Signal/WASignalGroup/sender_key_distribution_message.js +78 -0
  22. package/lib/Signal/WASignalGroup/sender_key_message.js +92 -0
  23. package/lib/Signal/WASignalGroup/sender_key_name.js +70 -0
  24. package/lib/Signal/WASignalGroup/sender_key_record.js +56 -0
  25. package/lib/Signal/WASignalGroup/sender_key_state.js +129 -0
  26. package/lib/Signal/{Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -3
  27. package/lib/Signal/libsignal.d.ts +4 -5
  28. package/lib/Signal/libsignal.js +112 -292
  29. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  30. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  31. package/lib/Socket/Client/index.d.ts +2 -3
  32. package/lib/Socket/Client/index.js +22 -3
  33. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  34. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  35. package/lib/Socket/Client/types.d.ts +15 -15
  36. package/lib/Socket/Client/types.js +15 -8
  37. package/lib/Socket/Client/websocket.d.ts +12 -12
  38. package/lib/Socket/Client/websocket.js +36 -24
  39. package/lib/Socket/business.d.ts +177 -178
  40. package/lib/Socket/business.js +71 -179
  41. package/lib/Socket/chats.d.ts +93 -93
  42. package/lib/Socket/chats.js +625 -474
  43. package/lib/Socket/communities.d.ts +62 -83
  44. package/lib/Socket/communities.js +414 -412
  45. package/lib/Socket/groups.d.ts +112 -118
  46. package/lib/Socket/groups.js +171 -146
  47. package/lib/Socket/index.d.ts +182 -222
  48. package/lib/Socket/index.js +17 -12
  49. package/lib/Socket/messages-recv.d.ts +169 -165
  50. package/lib/Socket/messages-recv.js +1721 -1185
  51. package/lib/Socket/messages-send.d.ts +160 -161
  52. package/lib/Socket/messages-send.js +992 -642
  53. package/lib/Socket/mex.d.ts +0 -1
  54. package/lib/Socket/mex.js +9 -4
  55. package/lib/Socket/newsletter.d.ts +139 -139
  56. package/lib/Socket/newsletter.js +258 -153
  57. package/lib/Socket/registration.d.ts +266 -0
  58. package/lib/Socket/registration.js +166 -0
  59. package/lib/Socket/socket.d.ts +36 -42
  60. package/lib/Socket/socket.js +615 -533
  61. package/lib/Socket/usync.d.ts +37 -0
  62. package/lib/Socket/usync.js +83 -0
  63. package/lib/Store/index.d.ts +4 -0
  64. package/lib/Store/index.js +24 -0
  65. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  66. package/lib/Store/make-cache-manager-store.js +90 -0
  67. package/lib/Store/make-in-memory-store.d.ts +123 -0
  68. package/lib/Store/make-in-memory-store.js +429 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  70. package/lib/Store/make-ordered-dictionary.js +86 -0
  71. package/lib/Store/object-repository.d.ts +10 -0
  72. package/lib/Store/object-repository.js +31 -0
  73. package/lib/Types/Auth.d.ts +96 -87
  74. package/lib/Types/Auth.js +3 -2
  75. package/lib/Types/Call.d.ts +13 -13
  76. package/lib/Types/Call.js +3 -2
  77. package/lib/Types/Chat.d.ts +94 -79
  78. package/lib/Types/Chat.js +9 -8
  79. package/lib/Types/Contact.d.ts +9 -13
  80. package/lib/Types/Contact.js +3 -2
  81. package/lib/Types/Events.d.ts +179 -152
  82. package/lib/Types/Events.js +3 -2
  83. package/lib/Types/GroupMetadata.d.ts +48 -49
  84. package/lib/Types/GroupMetadata.js +3 -2
  85. package/lib/Types/Label.d.ts +14 -13
  86. package/lib/Types/Label.js +30 -24
  87. package/lib/Types/LabelAssociation.d.ts +20 -15
  88. package/lib/Types/LabelAssociation.js +12 -6
  89. package/lib/Types/Message.d.ts +404 -234
  90. package/lib/Types/Message.js +13 -11
  91. package/lib/Types/MexUpdates.d.ts +9 -0
  92. package/lib/Types/MexUpdates.js +18 -0
  93. package/lib/Types/Newsletter.d.ts +104 -130
  94. package/lib/Types/Newsletter.js +40 -31
  95. package/lib/Types/Product.d.ts +71 -58
  96. package/lib/Types/Product.js +3 -2
  97. package/lib/Types/Signal.d.ts +55 -63
  98. package/lib/Types/Signal.js +3 -2
  99. package/lib/Types/Socket.d.ts +66 -77
  100. package/lib/Types/Socket.js +3 -3
  101. package/lib/Types/State.d.ts +19 -17
  102. package/lib/Types/State.js +14 -13
  103. package/lib/Types/USync.d.ts +8 -8
  104. package/lib/Types/USync.js +3 -2
  105. package/lib/Types/index.d.ts +61 -47
  106. package/lib/Types/index.js +48 -26
  107. package/lib/Utils/auth-utils.d.ts +10 -8
  108. package/lib/Utils/auth-utils.js +154 -206
  109. package/lib/Utils/baileys-event-stream.d.ts +7 -6
  110. package/lib/Utils/baileys-event-stream.js +43 -29
  111. package/lib/Utils/business.d.ts +20 -14
  112. package/lib/Utils/business.js +134 -110
  113. package/lib/Utils/chat-utils.d.ts +69 -57
  114. package/lib/Utils/chat-utils.js +380 -362
  115. package/lib/Utils/check-npm-version.d.ts +15 -0
  116. package/lib/Utils/check-npm-version.js +52 -0
  117. package/lib/Utils/crypto.d.ts +45 -30
  118. package/lib/Utils/crypto.js +178 -141
  119. package/lib/Utils/decode-wa-message.d.ts +35 -42
  120. package/lib/Utils/decode-wa-message.js +150 -176
  121. package/lib/Utils/event-buffer.d.ts +17 -12
  122. package/lib/Utils/event-buffer.js +286 -269
  123. package/lib/Utils/generics.d.ts +99 -60
  124. package/lib/Utils/generics.js +481 -244
  125. package/lib/Utils/history.d.ts +22 -18
  126. package/lib/Utils/history.js +80 -54
  127. package/lib/Utils/index.d.ts +19 -20
  128. package/lib/Utils/index.js +41 -19
  129. package/lib/Utils/link-preview.d.ts +14 -12
  130. package/lib/Utils/link-preview.js +75 -40
  131. package/lib/Utils/logger.d.ts +11 -10
  132. package/lib/Utils/logger.js +7 -3
  133. package/lib/Utils/lt-hash.d.ts +13 -12
  134. package/lib/Utils/lt-hash.js +37 -27
  135. package/lib/Utils/make-mutex.d.ts +7 -6
  136. package/lib/Utils/make-mutex.js +29 -20
  137. package/lib/Utils/message-retry-manager.d.ts +6 -6
  138. package/lib/Utils/message-retry-manager.js +36 -8
  139. package/lib/Utils/messages-media.d.ts +102 -87
  140. package/lib/Utils/messages-media.js +570 -427
  141. package/lib/Utils/messages.d.ts +64 -37
  142. package/lib/Utils/messages.js +1270 -511
  143. package/lib/Utils/noise-handler.d.ts +18 -18
  144. package/lib/Utils/noise-handler.js +109 -101
  145. package/lib/Utils/process-message.d.ts +32 -25
  146. package/lib/Utils/process-message.js +281 -266
  147. package/lib/Utils/signal.d.ts +32 -24
  148. package/lib/Utils/signal.js +105 -98
  149. package/lib/Utils/use-mongo-file-auth-state.d.ts +6 -0
  150. package/lib/Utils/use-mongo-file-auth-state.js +84 -0
  151. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -5
  152. package/lib/Utils/use-multi-file-auth-state.js +186 -69
  153. package/lib/Utils/use-single-file-auth-state.d.ts +13 -0
  154. package/lib/Utils/use-single-file-auth-state.js +80 -0
  155. package/lib/Utils/validate-connection.d.ts +13 -11
  156. package/lib/Utils/validate-connection.js +116 -124
  157. package/lib/WABinary/constants.d.ts +27 -25
  158. package/lib/WABinary/constants.js +1292 -1277
  159. package/lib/WABinary/decode.d.ts +9 -7
  160. package/lib/WABinary/decode.js +189 -139
  161. package/lib/WABinary/encode.d.ts +3 -3
  162. package/lib/WABinary/encode.js +154 -105
  163. package/lib/WABinary/generic-utils.d.ts +27 -14
  164. package/lib/WABinary/generic-utils.js +102 -62
  165. package/lib/WABinary/index.d.ts +5 -6
  166. package/lib/WABinary/index.js +25 -6
  167. package/lib/WABinary/jid-utils.d.ts +46 -41
  168. package/lib/WABinary/jid-utils.js +80 -84
  169. package/lib/WABinary/types.d.ts +13 -10
  170. package/lib/WABinary/types.js +3 -2
  171. package/lib/WAM/BinaryInfo.d.ts +15 -8
  172. package/lib/WAM/BinaryInfo.js +14 -7
  173. package/lib/WAM/constants.d.ts +37 -30
  174. package/lib/WAM/constants.js +11983 -19465
  175. package/lib/WAM/encode.d.ts +3 -3
  176. package/lib/WAM/encode.js +110 -95
  177. package/lib/WAM/index.d.ts +3 -4
  178. package/lib/WAM/index.js +23 -4
  179. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  180. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  181. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.js +19 -12
  183. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -19
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +26 -18
  185. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -11
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +20 -12
  187. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  188. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  189. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -11
  190. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +24 -16
  191. package/lib/WAUSync/Protocols/index.d.ts +6 -5
  192. package/lib/WAUSync/Protocols/index.js +26 -5
  193. package/lib/WAUSync/USyncQuery.d.ts +28 -26
  194. package/lib/WAUSync/USyncQuery.js +62 -64
  195. package/lib/WAUSync/USyncUser.d.ts +10 -11
  196. package/lib/WAUSync/USyncUser.js +19 -12
  197. package/lib/WAUSync/index.d.ts +3 -4
  198. package/lib/WAUSync/index.js +23 -4
  199. package/lib/index.d.ts +11 -10
  200. package/lib/index.js +33 -11
  201. package/package.json +43 -48
  202. package/WAProto/GenerateStatics.sh +0 -3
  203. package/WAProto/fix-imports.js +0 -29
  204. package/engine-requirements.js +0 -10
  205. package/lib/Defaults/index.d.ts.map +0 -1
  206. package/lib/Defaults/index.js.map +0 -1
  207. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  208. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  209. package/lib/Signal/Group/ciphertext-message.js +0 -12
  210. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  211. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  212. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  213. package/lib/Signal/Group/group-session-builder.js +0 -30
  214. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  215. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  216. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  217. package/lib/Signal/Group/group_cipher.js +0 -82
  218. package/lib/Signal/Group/group_cipher.js.map +0 -1
  219. package/lib/Signal/Group/index.d.ts +0 -12
  220. package/lib/Signal/Group/index.d.ts.map +0 -1
  221. package/lib/Signal/Group/index.js +0 -12
  222. package/lib/Signal/Group/index.js.map +0 -1
  223. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  224. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  225. package/lib/Signal/Group/keyhelper.js +0 -18
  226. package/lib/Signal/Group/keyhelper.js.map +0 -1
  227. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  228. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  229. package/lib/Signal/Group/sender-chain-key.js +0 -26
  230. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  231. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  232. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  233. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  234. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  235. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  236. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  237. package/lib/Signal/Group/sender-key-message.js +0 -66
  238. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  239. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  240. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  241. package/lib/Signal/Group/sender-key-name.js +0 -48
  242. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  243. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  244. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  245. package/lib/Signal/Group/sender-key-record.js +0 -41
  246. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  247. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  248. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  249. package/lib/Signal/Group/sender-key-state.js +0 -84
  250. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  251. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  252. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  253. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  254. package/lib/Signal/libsignal.d.ts.map +0 -1
  255. package/lib/Signal/libsignal.js.map +0 -1
  256. package/lib/Signal/lid-mapping.d.ts +0 -23
  257. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  258. package/lib/Signal/lid-mapping.js +0 -171
  259. package/lib/Signal/lid-mapping.js.map +0 -1
  260. package/lib/Socket/Client/index.d.ts.map +0 -1
  261. package/lib/Socket/Client/index.js.map +0 -1
  262. package/lib/Socket/Client/types.d.ts.map +0 -1
  263. package/lib/Socket/Client/types.js.map +0 -1
  264. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  265. package/lib/Socket/Client/websocket.js.map +0 -1
  266. package/lib/Socket/business.d.ts.map +0 -1
  267. package/lib/Socket/business.js.map +0 -1
  268. package/lib/Socket/chats.d.ts.map +0 -1
  269. package/lib/Socket/chats.js.map +0 -1
  270. package/lib/Socket/communities.d.ts.map +0 -1
  271. package/lib/Socket/communities.js.map +0 -1
  272. package/lib/Socket/groups.d.ts.map +0 -1
  273. package/lib/Socket/groups.js.map +0 -1
  274. package/lib/Socket/index.d.ts.map +0 -1
  275. package/lib/Socket/index.js.map +0 -1
  276. package/lib/Socket/messages-recv.d.ts.map +0 -1
  277. package/lib/Socket/messages-recv.js.map +0 -1
  278. package/lib/Socket/messages-send.d.ts.map +0 -1
  279. package/lib/Socket/messages-send.js.map +0 -1
  280. package/lib/Socket/mex.d.ts.map +0 -1
  281. package/lib/Socket/mex.js.map +0 -1
  282. package/lib/Socket/newsletter.d.ts.map +0 -1
  283. package/lib/Socket/newsletter.js.map +0 -1
  284. package/lib/Socket/socket.d.ts.map +0 -1
  285. package/lib/Socket/socket.js.map +0 -1
  286. package/lib/Types/Auth.d.ts.map +0 -1
  287. package/lib/Types/Auth.js.map +0 -1
  288. package/lib/Types/Bussines.d.ts +0 -25
  289. package/lib/Types/Bussines.d.ts.map +0 -1
  290. package/lib/Types/Bussines.js +0 -2
  291. package/lib/Types/Bussines.js.map +0 -1
  292. package/lib/Types/Call.d.ts.map +0 -1
  293. package/lib/Types/Call.js.map +0 -1
  294. package/lib/Types/Chat.d.ts.map +0 -1
  295. package/lib/Types/Chat.js.map +0 -1
  296. package/lib/Types/Contact.d.ts.map +0 -1
  297. package/lib/Types/Contact.js.map +0 -1
  298. package/lib/Types/Events.d.ts.map +0 -1
  299. package/lib/Types/Events.js.map +0 -1
  300. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  301. package/lib/Types/GroupMetadata.js.map +0 -1
  302. package/lib/Types/Label.d.ts.map +0 -1
  303. package/lib/Types/Label.js.map +0 -1
  304. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  305. package/lib/Types/LabelAssociation.js.map +0 -1
  306. package/lib/Types/Message.d.ts.map +0 -1
  307. package/lib/Types/Message.js.map +0 -1
  308. package/lib/Types/Newsletter.d.ts.map +0 -1
  309. package/lib/Types/Newsletter.js.map +0 -1
  310. package/lib/Types/Product.d.ts.map +0 -1
  311. package/lib/Types/Product.js.map +0 -1
  312. package/lib/Types/Signal.d.ts.map +0 -1
  313. package/lib/Types/Signal.js.map +0 -1
  314. package/lib/Types/Socket.d.ts.map +0 -1
  315. package/lib/Types/Socket.js.map +0 -1
  316. package/lib/Types/State.d.ts.map +0 -1
  317. package/lib/Types/State.js.map +0 -1
  318. package/lib/Types/USync.d.ts.map +0 -1
  319. package/lib/Types/USync.js.map +0 -1
  320. package/lib/Types/index.d.ts.map +0 -1
  321. package/lib/Types/index.js.map +0 -1
  322. package/lib/Utils/auth-utils.d.ts.map +0 -1
  323. package/lib/Utils/auth-utils.js.map +0 -1
  324. package/lib/Utils/baileys-event-stream.d.ts.map +0 -1
  325. package/lib/Utils/baileys-event-stream.js.map +0 -1
  326. package/lib/Utils/browser-utils.d.ts +0 -4
  327. package/lib/Utils/browser-utils.d.ts.map +0 -1
  328. package/lib/Utils/browser-utils.js +0 -28
  329. package/lib/Utils/browser-utils.js.map +0 -1
  330. package/lib/Utils/business.d.ts.map +0 -1
  331. package/lib/Utils/business.js.map +0 -1
  332. package/lib/Utils/chat-utils.d.ts.map +0 -1
  333. package/lib/Utils/chat-utils.js.map +0 -1
  334. package/lib/Utils/crypto.d.ts.map +0 -1
  335. package/lib/Utils/crypto.js.map +0 -1
  336. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  337. package/lib/Utils/decode-wa-message.js.map +0 -1
  338. package/lib/Utils/event-buffer.d.ts.map +0 -1
  339. package/lib/Utils/event-buffer.js.map +0 -1
  340. package/lib/Utils/generics.d.ts.map +0 -1
  341. package/lib/Utils/generics.js.map +0 -1
  342. package/lib/Utils/history.d.ts.map +0 -1
  343. package/lib/Utils/history.js.map +0 -1
  344. package/lib/Utils/index.d.ts.map +0 -1
  345. package/lib/Utils/index.js.map +0 -1
  346. package/lib/Utils/link-preview.d.ts.map +0 -1
  347. package/lib/Utils/link-preview.js.map +0 -1
  348. package/lib/Utils/logger.d.ts.map +0 -1
  349. package/lib/Utils/logger.js.map +0 -1
  350. package/lib/Utils/lt-hash.d.ts.map +0 -1
  351. package/lib/Utils/lt-hash.js.map +0 -1
  352. package/lib/Utils/make-mutex.d.ts.map +0 -1
  353. package/lib/Utils/make-mutex.js.map +0 -1
  354. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  355. package/lib/Utils/message-retry-manager.js.map +0 -1
  356. package/lib/Utils/messages-media.d.ts.map +0 -1
  357. package/lib/Utils/messages-media.js.map +0 -1
  358. package/lib/Utils/messages.d.ts.map +0 -1
  359. package/lib/Utils/messages.js.map +0 -1
  360. package/lib/Utils/noise-handler.d.ts.map +0 -1
  361. package/lib/Utils/noise-handler.js.map +0 -1
  362. package/lib/Utils/pre-key-manager.d.ts +0 -28
  363. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  364. package/lib/Utils/pre-key-manager.js +0 -106
  365. package/lib/Utils/pre-key-manager.js.map +0 -1
  366. package/lib/Utils/process-message.d.ts.map +0 -1
  367. package/lib/Utils/process-message.js.map +0 -1
  368. package/lib/Utils/signal.d.ts.map +0 -1
  369. package/lib/Utils/signal.js.map +0 -1
  370. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  371. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  372. package/lib/Utils/validate-connection.d.ts.map +0 -1
  373. package/lib/Utils/validate-connection.js.map +0 -1
  374. package/lib/WABinary/constants.d.ts.map +0 -1
  375. package/lib/WABinary/constants.js.map +0 -1
  376. package/lib/WABinary/decode.d.ts.map +0 -1
  377. package/lib/WABinary/decode.js.map +0 -1
  378. package/lib/WABinary/encode.d.ts.map +0 -1
  379. package/lib/WABinary/encode.js.map +0 -1
  380. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  381. package/lib/WABinary/generic-utils.js.map +0 -1
  382. package/lib/WABinary/index.d.ts.map +0 -1
  383. package/lib/WABinary/index.js.map +0 -1
  384. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  385. package/lib/WABinary/jid-utils.js.map +0 -1
  386. package/lib/WABinary/types.d.ts.map +0 -1
  387. package/lib/WABinary/types.js.map +0 -1
  388. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  389. package/lib/WAM/BinaryInfo.js.map +0 -1
  390. package/lib/WAM/constants.d.ts.map +0 -1
  391. package/lib/WAM/constants.js.map +0 -1
  392. package/lib/WAM/encode.d.ts.map +0 -1
  393. package/lib/WAM/encode.js.map +0 -1
  394. package/lib/WAM/index.d.ts.map +0 -1
  395. package/lib/WAM/index.js.map +0 -1
  396. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  397. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  398. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  399. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  400. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  401. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  402. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  403. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  404. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
  405. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  406. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  407. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  408. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
  409. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  410. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  411. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  412. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  413. package/lib/WAUSync/Protocols/index.js.map +0 -1
  414. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  415. package/lib/WAUSync/USyncQuery.js.map +0 -1
  416. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  417. package/lib/WAUSync/USyncUser.js.map +0 -1
  418. package/lib/WAUSync/index.d.ts.map +0 -1
  419. package/lib/WAUSync/index.js.map +0 -1
  420. package/lib/index.d.ts.map +0 -1
  421. package/lib/index.js.map +0 -1
@@ -1,1228 +1,1764 @@
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, 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, 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
- let sendActiveReceipts = false;
35
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
36
- if (!authState.creds.me?.id) {
37
- throw new Boom('Not authenticated');
38
- }
39
- const pdoMessage = {
40
- historySyncOnDemandRequest: {
41
- chatJid: oldestMsgKey.remoteJid,
42
- oldestMsgFromMe: oldestMsgKey.fromMe,
43
- oldestMsgId: oldestMsgKey.id,
44
- oldestMsgTimestampMs: oldestMsgTimestamp,
45
- onDemandMsgCount: count
46
- },
47
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
48
- };
49
- return sendPeerDataOperationMessage(pdoMessage);
50
- };
51
- const requestPlaceholderResend = async (messageKey) => {
52
- if (!authState.creds.me?.id) {
53
- throw new Boom('Not authenticated');
54
- }
55
- if (placeholderResendCache.get(messageKey?.id)) {
56
- logger.debug({ messageKey }, 'already requested resend');
57
- return;
58
- }
59
- else {
60
- placeholderResendCache.set(messageKey?.id, true);
61
- }
62
- await delay(5000);
63
- if (!placeholderResendCache.get(messageKey?.id)) {
64
- logger.debug({ messageKey }, 'message received while resend requested');
65
- return 'RESOLVED';
66
- }
67
- const pdoMessage = {
68
- placeholderMessageResendRequest: [
69
- {
70
- messageKey
71
- }
72
- ],
73
- peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
74
- };
75
- setTimeout(() => {
76
- if (placeholderResendCache.get(messageKey?.id)) {
77
- logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
78
- placeholderResendCache.del(messageKey?.id);
79
- }
80
- }, 15000);
81
- return sendPeerDataOperationMessage(pdoMessage);
1
+ "use strict";
2
+
3
+ var __importDefault =
4
+ (this && this.__importDefault) ||
5
+ function (mod) {
6
+ return mod && mod.__esModule ? mod : { default: mod };
7
+ };
8
+
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+
11
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
12
+ const boom_1 = require("@hapi/boom");
13
+ const crypto_1 = require("crypto");
14
+ const WAProto_1 = require("../../WAProto");
15
+ const Defaults_1 = require("../Defaults");
16
+ const Types_1 = require("../Types");
17
+ const Utils_1 = require("../Utils");
18
+ const make_mutex_1 = require("../Utils/make-mutex");
19
+ const WABinary_1 = require("../WABinary");
20
+ const groups_1 = require("./groups");
21
+ const messages_send_1 = require("./messages-send");
22
+
23
+ const makeMessagesRecvSocket = (config) => {
24
+ const {
25
+ logger,
26
+ retryRequestDelayMs,
27
+ maxMsgRetryCount,
28
+ getMessage,
29
+ shouldIgnoreJid,
30
+ } = config;
31
+ const Neele = messages_send_1.makeMessagesSocket(config);
32
+ const {
33
+ ev,
34
+ authState,
35
+ ws,
36
+ processingMutex,
37
+ signalRepository,
38
+ query,
39
+ upsertMessage,
40
+ groupMetadata,
41
+ resyncAppState,
42
+ onUnexpectedError,
43
+ assertSessions,
44
+ sendNode,
45
+ relayMessage,
46
+ sendReceipt,
47
+ uploadPreKeys,
48
+ getUSyncDevices,
49
+ createParticipantNodes,
50
+ sendPeerDataOperationMessage,
51
+ } = Neele;
52
+
53
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
54
+ const retryMutex = make_mutex_1.makeMutex();
55
+
56
+ const msgRetryCache =
57
+ config.msgRetryCounterCache ||
58
+ new node_cache_1.default({
59
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
60
+ useClones: false,
61
+ });
62
+
63
+ const callOfferCache =
64
+ config.callOfferCache ||
65
+ new node_cache_1.default({
66
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER,
67
+ useClones: false,
68
+ });
69
+
70
+ const placeholderResendCache =
71
+ config.placeholderResendCache ||
72
+ new node_cache_1.default({
73
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
74
+ useClones: false,
75
+ });
76
+
77
+ let sendActiveReceipts = false;
78
+
79
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
80
+ const stanza = {
81
+ tag: "ack",
82
+ attrs: {
83
+ id: attrs.id,
84
+ to: attrs.from,
85
+ class: tag,
86
+ },
82
87
  };
83
- // Handles mex newsletter notifications
84
- const handleMexNewsletterNotification = async (node) => {
85
- const mexNode = getBinaryNodeChild(node, 'mex');
86
- if (!mexNode?.content) {
87
- logger.warn({ node }, 'Invalid mex newsletter notification');
88
- return;
89
- }
90
- let data;
91
- try {
92
- data = JSON.parse(mexNode.content.toString());
93
- }
94
- catch (error) {
95
- logger.error({ err: error, node }, 'Failed to parse mex newsletter notification');
96
- return;
97
- }
98
- const operation = data?.operation;
99
- const updates = data?.updates;
100
- if (!updates || !operation) {
101
- logger.warn({ data }, 'Invalid mex newsletter notification content');
102
- return;
103
- }
104
- logger.info({ operation, updates }, 'got mex newsletter notification');
105
- switch (operation) {
106
- case 'NotificationNewsletterUpdate':
107
- for (const update of updates) {
108
- if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
109
- ev.emit('newsletter-settings.update', {
110
- id: update.jid,
111
- update: update.settings
112
- });
113
- }
114
- }
115
- break;
116
- case 'NotificationNewsletterAdminPromote':
117
- for (const update of updates) {
118
- if (update.jid && update.user) {
119
- ev.emit('newsletter-participants.update', {
120
- id: update.jid,
121
- author: node.attrs.from,
122
- user: update.user,
123
- new_role: 'ADMIN',
124
- action: 'promote'
125
- });
126
- }
127
- }
128
- break;
129
- default:
130
- logger.info({ operation, data }, 'Unhandled mex newsletter notification');
131
- break;
132
- }
88
+
89
+ if (!!errorCode) {
90
+ stanza.attrs.error = errorCode.toString();
91
+ }
92
+
93
+ if (!!attrs.participant) {
94
+ stanza.attrs.participant = attrs.participant;
95
+ }
96
+
97
+ if (!!attrs.recipient) {
98
+ stanza.attrs.recipient = attrs.recipient;
99
+ }
100
+
101
+ if (
102
+ !!attrs.type &&
103
+ (tag !== "message" ||
104
+ WABinary_1.getBinaryNodeChild({ tag, attrs, content }, "unavailable") ||
105
+ errorCode !== 0)
106
+ ) {
107
+ stanza.attrs.type = attrs.type;
108
+ }
109
+
110
+ if (
111
+ tag === "message" &&
112
+ WABinary_1.getBinaryNodeChild({ tag, attrs, content }, "unavailable")
113
+ ) {
114
+ stanza.attrs.from = authState.creds.me.id;
115
+ }
116
+
117
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, "sent ack");
118
+ await sendNode(stanza);
119
+ };
120
+
121
+ const offerCall = async (toJid, isVideo = false) => {
122
+ const callId = crypto_1
123
+ .randomBytes(16)
124
+ .toString("hex")
125
+ .toUpperCase()
126
+ .substring(0, 64);
127
+ const offerContent = [];
128
+ offerContent.push({
129
+ tag: "audio",
130
+ attrs: { enc: "opus", rate: "16000" },
131
+ content: undefined,
132
+ });
133
+ offerContent.push({
134
+ tag: "audio",
135
+ attrs: { enc: "opus", rate: "8000" },
136
+ content: undefined,
137
+ });
138
+ if (isVideo) {
139
+ offerContent.push({
140
+ tag: "video",
141
+ attrs: {
142
+ enc: "vp8",
143
+ dec: "vp8",
144
+ orientation: "0",
145
+ screen_width: "1920",
146
+ screen_height: "1080",
147
+ device_orientation: "0",
148
+ },
149
+ content: undefined,
150
+ });
151
+ }
152
+ offerContent.push({
153
+ tag: "net",
154
+ attrs: { medium: "3" },
155
+ content: undefined,
156
+ });
157
+ offerContent.push({
158
+ tag: "capability",
159
+ attrs: { ver: "1" },
160
+ content: new Uint8Array([1, 4, 255, 131, 207, 4]),
161
+ });
162
+ offerContent.push({
163
+ tag: "encopt",
164
+ attrs: { keygen: "2" },
165
+ content: undefined,
166
+ });
167
+ const encKey = crypto_1.randomBytes(32);
168
+ const rawDevices = await getUSyncDevices([toJid], true, false);
169
+ const devices = rawDevices.map(({ user, device }) =>
170
+ WABinary_1.jidEncode(user, "s.whatsapp.net", device)
171
+ );
172
+ await assertSessions(devices, true);
173
+ const { nodes: destinations, shouldIncludeDeviceIdentity } =
174
+ await createParticipantNodes(
175
+ devices,
176
+ { call: { callKey: new Uint8Array(encKey) } },
177
+ { count: "0" }
178
+ );
179
+ offerContent.push({ tag: "destination", attrs: {}, content: destinations });
180
+ if (shouldIncludeDeviceIdentity) {
181
+ offerContent.push({
182
+ tag: "device-identity",
183
+ attrs: {},
184
+ content: Utils_1.encodeSignedDeviceIdentity(
185
+ authState.creds.account,
186
+ true
187
+ ),
188
+ });
189
+ }
190
+ const stanza = {
191
+ tag: "call",
192
+ attrs: {
193
+ id: Utils_1.generateMessageIDV2(),
194
+ to: toJid,
195
+ },
196
+ content: [
197
+ {
198
+ tag: "offer",
199
+ attrs: {
200
+ "call-id": callId,
201
+ "call-creator": authState.creds.me.id,
202
+ },
203
+ content: offerContent,
204
+ },
205
+ ],
133
206
  };
134
- // Handles newsletter notifications
135
- const handleNewsletterNotification = async (node) => {
136
- const from = node.attrs.from;
137
- const child = getAllBinaryNodeChildren(node)[0];
138
- const author = node.attrs.participant;
139
- logger.info({ from, child }, 'got newsletter notification');
140
- switch (child.tag) {
141
- case 'reaction':
142
- const reactionUpdate = {
143
- id: from,
144
- server_id: child.attrs.message_id,
145
- reaction: {
146
- code: getBinaryNodeChildString(child, 'reaction'),
147
- count: 1
148
- }
149
- };
150
- ev.emit('newsletter.reaction', reactionUpdate);
151
- break;
152
- case 'view':
153
- const viewUpdate = {
154
- id: from,
155
- server_id: child.attrs.message_id,
156
- count: parseInt(child.content?.toString() || '0', 10)
157
- };
158
- ev.emit('newsletter.view', viewUpdate);
159
- break;
160
- case 'participant':
161
- const participantUpdate = {
162
- id: from,
163
- author,
164
- user: child.attrs.jid,
165
- action: child.attrs.action,
166
- new_role: child.attrs.role
167
- };
168
- ev.emit('newsletter-participants.update', participantUpdate);
169
- break;
170
- case 'update':
171
- const settingsNode = getBinaryNodeChild(child, 'settings');
172
- if (settingsNode) {
173
- const update = {};
174
- const nameNode = getBinaryNodeChild(settingsNode, 'name');
175
- if (nameNode?.content)
176
- update.name = nameNode.content.toString();
177
- const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
178
- if (descriptionNode?.content)
179
- update.description = descriptionNode.content.toString();
180
- ev.emit('newsletter-settings.update', {
181
- id: from,
182
- update
183
- });
184
- }
185
- break;
186
- case 'message':
187
- const plaintextNode = getBinaryNodeChild(child, 'plaintext');
188
- if (plaintextNode?.content) {
189
- try {
190
- const contentBuf = typeof plaintextNode.content === 'string'
191
- ? Buffer.from(plaintextNode.content, 'binary')
192
- : Buffer.from(plaintextNode.content);
193
- const messageProto = proto.Message.decode(contentBuf).toJSON();
194
- const fullMessage = proto.WebMessageInfo.fromObject({
195
- key: {
196
- remoteJid: from,
197
- id: child.attrs.message_id || child.attrs.server_id,
198
- fromMe: false // TODO: is this really true though
199
- },
200
- message: messageProto,
201
- messageTimestamp: +child.attrs.t
202
- }).toJSON();
203
- await upsertMessage(fullMessage, 'append');
204
- logger.info('Processed plaintext newsletter message');
205
- }
206
- catch (error) {
207
- logger.error({ error }, 'Failed to decode plaintext newsletter message');
208
- }
209
- }
210
- break;
211
- default:
212
- logger.warn({ node }, 'Unknown newsletter notification');
213
- break;
214
- }
207
+ await query(stanza);
208
+ return {
209
+ id: callId,
210
+ to: toJid,
215
211
  };
216
- const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
217
- const stanza = {
218
- tag: 'ack',
219
- attrs: {
220
- id: attrs.id,
221
- to: attrs.from,
222
- class: tag
223
- }
224
- };
225
- if (!!errorCode) {
226
- stanza.attrs.error = errorCode.toString();
227
- }
228
- if (!!attrs.participant) {
229
- stanza.attrs.participant = attrs.participant;
230
- }
231
- if (!!attrs.recipient) {
232
- stanza.attrs.recipient = attrs.recipient;
233
- }
234
- if (!!attrs.type &&
235
- (tag !== 'message' || getBinaryNodeChild({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
236
- stanza.attrs.type = attrs.type;
237
- }
238
- if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
239
- stanza.attrs.from = authState.creds.me.id;
240
- }
241
- logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
242
- await sendNode(stanza);
212
+ };
213
+
214
+ const rejectCall = async (callId, callFrom) => {
215
+ const stanza = {
216
+ tag: "call",
217
+ attrs: {
218
+ from: authState.creds.me.id,
219
+ to: callFrom,
220
+ },
221
+ content: [
222
+ {
223
+ tag: "reject",
224
+ attrs: {
225
+ "call-id": callId,
226
+ "call-creator": callFrom,
227
+ count: "0",
228
+ },
229
+ content: undefined,
230
+ },
231
+ ],
243
232
  };
244
- const rejectCall = async (callId, callFrom) => {
245
- const stanza = {
246
- tag: 'call',
233
+
234
+ await query(stanza);
235
+ };
236
+
237
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
238
+ const { fullMessage } = Utils_1.decodeMessageNode(
239
+ node,
240
+ authState.creds.me.id,
241
+ authState.creds.me.lid || ""
242
+ );
243
+ const { key: msgKey } = fullMessage;
244
+ const msgId = msgKey.id;
245
+ const key = `${msgId}:${msgKey?.participant}`;
246
+ let retryCount = msgRetryCache.get(key) || 0;
247
+
248
+ if (retryCount >= maxMsgRetryCount) {
249
+ logger.debug({ retryCount, msgId }, "reached retry limit, clearing");
250
+ msgRetryCache.del(key);
251
+ return;
252
+ }
253
+ retryCount += 1;
254
+ msgRetryCache.set(key, retryCount);
255
+
256
+ const {
257
+ account,
258
+ signedPreKey,
259
+ signedIdentityKey: identityKey,
260
+ } = authState.creds;
261
+
262
+ if (retryCount === 1) {
263
+ //request a resend via phone
264
+ const msgId = await requestPlaceholderResend(msgKey);
265
+ logger.debug(
266
+ `sendRetryRequest: requested placeholder resend for message ${msgId}`
267
+ );
268
+ }
269
+
270
+ const deviceIdentity = Utils_1.encodeSignedDeviceIdentity(account, true);
271
+
272
+ await authState.keys.transaction(async () => {
273
+ const receipt = {
274
+ tag: "receipt",
275
+ attrs: {
276
+ id: msgId,
277
+ type: "retry",
278
+ to: node.attrs.from,
279
+ },
280
+ content: [
281
+ {
282
+ tag: "retry",
247
283
  attrs: {
248
- from: authState.creds.me.id,
249
- to: callFrom
284
+ count: retryCount.toString(),
285
+ id: node.attrs.id,
286
+ t: node.attrs.t,
287
+ v: "1",
250
288
  },
251
- content: [
252
- {
253
- tag: 'reject',
254
- attrs: {
255
- 'call-id': callId,
256
- 'call-creator': callFrom,
257
- count: '0'
258
- },
259
- content: undefined
260
- }
261
- ]
262
- };
263
- await query(stanza);
264
- };
265
- const sendRetryRequest = async (node, forceIncludeKeys = false) => {
266
- const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
267
- const { key: msgKey } = fullMessage;
268
- const msgId = msgKey.id;
269
- if (messageRetryManager) {
270
- // Check if we've exceeded max retries using the new system
271
- if (messageRetryManager.hasExceededMaxRetries(msgId)) {
272
- logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
273
- messageRetryManager.markRetryFailed(msgId);
274
- return;
275
- }
276
- // Increment retry count using new system
277
- const retryCount = messageRetryManager.incrementRetryCount(msgId);
278
- // Use the new retry count for the rest of the logic
279
- const key = `${msgId}:${msgKey?.participant}`;
280
- msgRetryCache.set(key, retryCount);
281
- }
282
- else {
283
- // Fallback to old system
284
- const key = `${msgId}:${msgKey?.participant}`;
285
- let retryCount = (await msgRetryCache.get(key)) || 0;
286
- if (retryCount >= maxMsgRetryCount) {
287
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
288
- msgRetryCache.del(key);
289
- return;
290
- }
291
- retryCount += 1;
292
- await msgRetryCache.set(key, retryCount);
293
- }
294
- const key = `${msgId}:${msgKey?.participant}`;
295
- const retryCount = (await msgRetryCache.get(key)) || 1;
296
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
297
- const fromJid = node.attrs.from;
298
- // Check if we should recreate the session
299
- let shouldRecreateSession = false;
300
- let recreateReason = '';
301
- if (enableAutoSessionRecreation && messageRetryManager) {
302
- try {
303
- // Check if we have a session with this JID
304
- const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
305
- const hasSession = await signalRepository.validateSession(fromJid);
306
- const result = messageRetryManager.shouldRecreateSession(fromJid, retryCount, hasSession.exists);
307
- shouldRecreateSession = result.recreate;
308
- recreateReason = result.reason;
309
- if (shouldRecreateSession) {
310
- logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
311
- // Delete existing session to force recreation
312
- await authState.keys.set({ session: { [sessionId]: null } });
313
- forceIncludeKeys = true;
314
- }
315
- }
316
- catch (error) {
317
- logger.warn({ error, fromJid }, 'failed to check session recreation');
318
- }
319
- }
320
- if (retryCount <= 2) {
321
- // Use new retry manager for phone requests if available
322
- if (messageRetryManager) {
323
- // Schedule phone request with delay (like whatsmeow)
324
- messageRetryManager.schedulePhoneRequest(msgId, async () => {
325
- try {
326
- const requestId = await requestPlaceholderResend(msgKey);
327
- logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
328
- }
329
- catch (error) {
330
- logger.warn({ error, msgId }, 'failed to send scheduled phone request');
331
- }
332
- });
333
- }
334
- else {
335
- // Fallback to immediate request
336
- const msgId = await requestPlaceholderResend(msgKey);
337
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
338
- }
339
- }
340
- const deviceIdentity = encodeSignedDeviceIdentity(account, true);
341
- await authState.keys.transaction(async () => {
342
- const receipt = {
343
- tag: 'receipt',
344
- attrs: {
345
- id: msgId,
346
- type: 'retry',
347
- to: node.attrs.from
348
- },
349
- content: [
350
- {
351
- tag: 'retry',
352
- attrs: {
353
- count: retryCount.toString(),
354
- id: node.attrs.id,
355
- t: node.attrs.t,
356
- v: '1',
357
- // ADD ERROR FIELD
358
- error: '0'
359
- }
360
- },
361
- {
362
- tag: 'registration',
363
- attrs: {},
364
- content: encodeBigEndian(authState.creds.registrationId)
365
- }
366
- ]
367
- };
368
- if (node.attrs.recipient) {
369
- receipt.attrs.recipient = node.attrs.recipient;
370
- }
371
- if (node.attrs.participant) {
372
- receipt.attrs.participant = node.attrs.participant;
373
- }
374
- if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
375
- const { update, preKeys } = await getNextPreKeys(authState, 1);
376
- const [keyId] = Object.keys(preKeys);
377
- const key = preKeys[+keyId];
378
- const content = receipt.content;
379
- content.push({
380
- tag: 'keys',
381
- attrs: {},
382
- content: [
383
- { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
384
- { tag: 'identity', attrs: {}, content: identityKey.public },
385
- xmppPreKey(key, +keyId),
386
- xmppSignedPreKey(signedPreKey),
387
- { tag: 'device-identity', attrs: {}, content: deviceIdentity }
388
- ]
389
- });
390
- ev.emit('creds.update', update);
289
+ },
290
+ {
291
+ tag: "registration",
292
+ attrs: {},
293
+ content: Utils_1.encodeBigEndian(authState.creds.registrationId),
294
+ },
295
+ ],
296
+ };
297
+
298
+ if (node.attrs.recipient) {
299
+ receipt.attrs.recipient = node.attrs.recipient;
300
+ }
301
+
302
+ if (node.attrs.participant) {
303
+ receipt.attrs.participant = node.attrs.participant;
304
+ }
305
+
306
+ if (retryCount > 1 || forceIncludeKeys) {
307
+ const { update, preKeys } = await Utils_1.getNextPreKeys(authState, 1);
308
+ const [keyId] = Object.keys(preKeys);
309
+ const key = preKeys[+keyId];
310
+ const content = receipt.content;
311
+
312
+ content.push({
313
+ tag: "keys",
314
+ attrs: {},
315
+ content: [
316
+ {
317
+ tag: "type",
318
+ attrs: {},
319
+ content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE),
320
+ },
321
+ { tag: "identity", attrs: {}, content: identityKey.public },
322
+ Utils_1.xmppPreKey(key, +keyId),
323
+ Utils_1.xmppSignedPreKey(signedPreKey),
324
+ { tag: "device-identity", attrs: {}, content: deviceIdentity },
325
+ ],
326
+ });
327
+ ev.emit("creds.update", update);
328
+ }
329
+
330
+ await sendNode(receipt);
331
+
332
+ logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt");
333
+ });
334
+ };
335
+
336
+ const handleEncryptNotification = async (node) => {
337
+ const from = node.attrs.from;
338
+ if (from === WABinary_1.S_WHATSAPP_NET) {
339
+ const countChild = WABinary_1.getBinaryNodeChild(node, "count");
340
+ const count = +countChild.attrs.value;
341
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
342
+ logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count");
343
+
344
+ if (shouldUploadMorePreKeys) {
345
+ await uploadPreKeys();
346
+ }
347
+ } else {
348
+ const identityNode = WABinary_1.getBinaryNodeChild(node, "identity");
349
+ if (identityNode) {
350
+ logger.info({ jid: from }, "identity changed");
351
+ // not handling right now
352
+ // signal will override new identity anyway
353
+ } else {
354
+ logger.info({ node }, "unknown encrypt notification");
355
+ }
356
+ }
357
+ };
358
+
359
+ const handleGroupNotification = (
360
+ participant,
361
+ child,
362
+ msg,
363
+ participantPhoneNumber,
364
+ mode
365
+ ) => {
366
+ if (participant && participant.endsWith("@lid") && participantPhoneNumber) {
367
+ participant = participantPhoneNumber;
368
+ }
369
+
370
+ const participantNode = WABinary_1.getBinaryNodeChild(child, "participant");
371
+
372
+ const participantJid = participantNode
373
+ ? [participantNode]
374
+ .map((p) => {
375
+ const { jid, lid, phone_number } = p.attrs;
376
+
377
+ if (phone_number && phone_number.endsWith("@s.whatsapp.net")) {
378
+ return phone_number;
391
379
  }
392
- await sendNode(receipt);
393
- logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
394
- }, authState?.creds?.me?.id || 'sendRetryRequest');
395
- };
396
- const handleEncryptNotification = async (node) => {
397
- const from = node.attrs.from;
398
- if (from === S_WHATSAPP_NET) {
399
- const countChild = getBinaryNodeChild(node, 'count');
400
- const count = +countChild.attrs.value;
401
- const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
402
- logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
403
- if (shouldUploadMorePreKeys) {
404
- await uploadPreKeys();
380
+
381
+ if (jid && (0, WABinary_1.isJidUser)(jid)) {
382
+ return jid;
405
383
  }
406
- }
407
- else {
408
- const identityNode = getBinaryNodeChild(node, 'identity');
409
- if (identityNode) {
410
- logger.info({ jid: from }, 'identity changed');
411
- // not handling right now
412
- // signal will override new identity anyway
384
+
385
+ if (phone_number) {
386
+ return (0, WABinary_1.jidNormalizedUser)(phone_number);
413
387
  }
414
- else {
415
- logger.info({ node }, 'unknown encrypt notification');
388
+
389
+ if (lid && lid.endsWith("@lid")) {
390
+ return lid;
416
391
  }
417
- }
418
- };
419
- const handleGroupNotification = (fullNode, child, msg) => {
420
- // TODO: Support PN/LID (Here is only LID now)
421
- const actingParticipantLid = fullNode.attrs.participant;
422
- const actingParticipantPn = fullNode.attrs.participant_pn;
423
- const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
424
- const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
425
- switch (child?.tag) {
426
- case 'create':
427
- const metadata = extractGroupMetadata(child);
428
- msg.messageStubType = WAMessageStubType.GROUP_CREATE;
429
- msg.messageStubParameters = [metadata.subject];
430
- msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
431
- ev.emit('chats.upsert', [
432
- {
433
- id: metadata.id,
434
- name: metadata.subject,
435
- conversationTimestamp: metadata.creation
436
- }
437
- ]);
438
- ev.emit('groups.upsert', [
439
- {
440
- ...metadata,
441
- author: actingParticipantLid,
442
- authorPn: actingParticipantPn
443
- }
444
- ]);
445
- break;
446
- case 'ephemeral':
447
- case 'not_ephemeral':
448
- msg.message = {
449
- protocolMessage: {
450
- type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
451
- ephemeralExpiration: +(child.attrs.expiration || 0)
452
- }
453
- };
454
- break;
455
- case 'modify':
456
- const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
457
- msg.messageStubParameters = oldNumber || [];
458
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
459
- break;
460
- case 'promote':
461
- case 'demote':
462
- case 'remove':
463
- case 'add':
464
- case 'leave':
465
- const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
466
- msg.messageStubType = WAMessageStubType[stubType];
467
- const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
468
- // TODO: Store LID MAPPINGS
469
- return {
470
- id: attrs.jid,
471
- phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
472
- lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
473
- admin: (attrs.type || null)
474
- };
475
- });
476
- if (participants.length === 1 &&
477
- // if recv. "remove" message and sender removed themselves
478
- // mark as left
479
- (areJidsSameUser(participants[0].id, actingParticipantLid) ||
480
- areJidsSameUser(participants[0].id, actingParticipantPn)) &&
481
- child.tag === 'remove') {
482
- msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
483
- }
484
- msg.messageStubParameters = participants.map(a => JSON.stringify(a));
485
- break;
486
- case 'subject':
487
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
488
- msg.messageStubParameters = [child.attrs.subject];
489
- break;
490
- case 'description':
491
- const description = getBinaryNodeChild(child, 'body')?.content?.toString();
492
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
493
- msg.messageStubParameters = description ? [description] : undefined;
494
- break;
495
- case 'announcement':
496
- case 'not_announcement':
497
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
498
- msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
499
- break;
500
- case 'locked':
501
- case 'unlocked':
502
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
503
- msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
504
- break;
505
- case 'invite':
506
- msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
507
- msg.messageStubParameters = [child.attrs.code];
508
- break;
509
- case 'member_add_mode':
510
- const addMode = child.content;
511
- if (addMode) {
512
- msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
513
- msg.messageStubParameters = [addMode.toString()];
514
- }
515
- break;
516
- case 'membership_approval_mode':
517
- const approvalMode = getBinaryNodeChild(child, 'group_join');
518
- if (approvalMode) {
519
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
520
- msg.messageStubParameters = [approvalMode.attrs.state];
521
- }
522
- break;
523
- case 'created_membership_requests':
524
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
525
- msg.messageStubParameters = [
526
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
527
- 'created',
528
- child.attrs.request_method
529
- ];
530
- break;
531
- case 'revoked_membership_requests':
532
- const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
533
- // TODO: LIDMAPPING SUPPORT
534
- msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
535
- msg.messageStubParameters = [
536
- JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
537
- isDenied ? 'revoked' : 'rejected'
538
- ];
539
- break;
540
- }
541
- };
542
- const processNotification = async (node) => {
543
- const result = {};
544
- const [child] = getAllBinaryNodeChildren(node);
545
- const nodeType = node.attrs.type;
546
- const from = jidNormalizedUser(node.attrs.from);
547
- switch (nodeType) {
548
- case 'privacy_token':
549
- const tokenList = getBinaryNodeChildren(child, 'token');
550
- for (const { attrs, content } of tokenList) {
551
- const jid = attrs.jid;
552
- ev.emit('chats.update', [
553
- {
554
- id: jid,
555
- tcToken: content
556
- }
557
- ]);
558
- logger.debug({ jid }, 'got privacy token update');
559
- }
560
- break;
561
- case 'newsletter':
562
- await handleNewsletterNotification(node);
563
- break;
564
- case 'mex':
565
- await handleMexNewsletterNotification(node);
566
- break;
567
- case 'w:gp2':
568
- // TODO: HANDLE PARTICIPANT_PN
569
- handleGroupNotification(node, child, result);
570
- break;
571
- case 'mediaretry':
572
- const event = decodeMediaRetryNode(node);
573
- ev.emit('messages.media-update', [event]);
574
- break;
575
- case 'encrypt':
576
- await handleEncryptNotification(node);
577
- break;
578
- case 'devices':
579
- const devices = getBinaryNodeChildren(child, 'device');
580
- if (areJidsSameUser(child.attrs.jid, authState.creds.me.id) ||
581
- areJidsSameUser(child.attrs.lid, authState.creds.me.lid)) {
582
- const deviceData = devices.map(d => ({ id: d.attrs.jid, lid: d.attrs.lid }));
583
- logger.info({ deviceData }, 'my own devices changed');
584
- }
585
- //TODO: drop a new event, add hashes
586
- break;
587
- case 'server_sync':
588
- const update = getBinaryNodeChild(node, 'collection');
589
- if (update) {
590
- const name = update.attrs.name;
591
- await resyncAppState([name], false);
592
- }
593
- break;
594
- case 'picture':
595
- const setPicture = getBinaryNodeChild(node, 'set');
596
- const delPicture = getBinaryNodeChild(node, 'delete');
597
- ev.emit('contacts.update', [
598
- {
599
- id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
600
- imgUrl: setPicture ? 'changed' : 'removed'
601
- }
602
- ]);
603
- if (isJidGroup(from)) {
604
- const node = setPicture || delPicture;
605
- result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
606
- if (setPicture) {
607
- result.messageStubParameters = [setPicture.attrs.id];
608
- }
609
- result.participant = node?.attrs.author;
610
- result.key = {
611
- ...(result.key || {}),
612
- participant: setPicture?.attrs.author
613
- };
614
- }
615
- break;
616
- case 'account_sync':
617
- if (child.tag === 'disappearing_mode') {
618
- const newDuration = +child.attrs.duration;
619
- const timestamp = +child.attrs.t;
620
- logger.info({ newDuration }, 'updated account disappearing mode');
621
- ev.emit('creds.update', {
622
- accountSettings: {
623
- ...authState.creds.accountSettings,
624
- defaultDisappearingMode: {
625
- ephemeralExpiration: newDuration,
626
- ephemeralSettingTimestamp: timestamp
627
- }
628
- }
629
- });
630
- }
631
- else if (child.tag === 'blocklist') {
632
- const blocklists = getBinaryNodeChildren(child, 'item');
633
- for (const { attrs } of blocklists) {
634
- const blocklist = [attrs.jid];
635
- const type = attrs.action === 'block' ? 'add' : 'remove';
636
- ev.emit('blocklist.update', { blocklist, type });
637
- }
638
- }
639
- break;
640
- case 'link_code_companion_reg':
641
- const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
642
- const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
643
- const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
644
- const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
645
- const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
646
- const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
647
- const random = randomBytes(32);
648
- const linkCodeSalt = randomBytes(32);
649
- const linkCodePairingExpanded = await hkdf(companionSharedKey, 32, {
650
- salt: linkCodeSalt,
651
- info: 'link_code_pairing_key_bundle_encryption_key'
652
- });
653
- const encryptPayload = Buffer.concat([
654
- Buffer.from(authState.creds.signedIdentityKey.public),
655
- primaryIdentityPublicKey,
656
- random
657
- ]);
658
- const encryptIv = randomBytes(12);
659
- const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
660
- const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
661
- const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
662
- const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
663
- authState.creds.advSecretKey = (await hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
664
- await query({
665
- tag: 'iq',
666
- attrs: {
667
- to: S_WHATSAPP_NET,
668
- type: 'set',
669
- id: sock.generateMessageTag(),
670
- xmlns: 'md'
671
- },
672
- content: [
673
- {
674
- tag: 'link_code_companion_reg',
675
- attrs: {
676
- jid: authState.creds.me.id,
677
- stage: 'companion_finish'
678
- },
679
- content: [
680
- {
681
- tag: 'link_code_pairing_wrapped_key_bundle',
682
- attrs: {},
683
- content: encryptedPayload
684
- },
685
- {
686
- tag: 'companion_identity_public',
687
- attrs: {},
688
- content: authState.creds.signedIdentityKey.public
689
- },
690
- {
691
- tag: 'link_code_pairing_ref',
692
- attrs: {},
693
- content: ref
694
- }
695
- ]
696
- }
697
- ]
698
- });
699
- authState.creds.registered = true;
700
- ev.emit('creds.update', authState.creds);
701
- }
702
- if (Object.keys(result).length) {
703
- return result;
704
- }
705
- };
706
- async function decipherLinkPublicKey(data) {
707
- const buffer = toRequiredBuffer(data);
708
- const salt = buffer.slice(0, 32);
709
- const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
710
- const iv = buffer.slice(32, 48);
711
- const payload = buffer.slice(48, 80);
712
- return aesDecryptCTR(payload, secretKey, iv);
392
+
393
+ return null;
394
+ })
395
+ .filter(Boolean)[0]
396
+ : null;
397
+
398
+ msg.participant_pn = participantPhoneNumber;
399
+ if (participantPhoneNumber) {
400
+ msg.key = {
401
+ participant: participantPhoneNumber,
402
+ };
713
403
  }
714
- function toRequiredBuffer(data) {
715
- if (data === undefined) {
716
- throw new Boom('Invalid buffer', { statusCode: 400 });
404
+
405
+ switch (child.tag) {
406
+ case "create":
407
+ const metadata = groups_1.extractGroupMetadata(child);
408
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
409
+ msg.messageStubParameters = [metadata.subject];
410
+ msg.key = { participant: metadata.owner };
411
+ ev.emit("chats.upsert", [
412
+ {
413
+ id: metadata.id,
414
+ name: metadata.subject,
415
+ conversationTimestamp: metadata.creation,
416
+ },
417
+ ]);
418
+ ev.emit("groups.upsert", [
419
+ {
420
+ ...metadata,
421
+ author: participant,
422
+ },
423
+ ]);
424
+ break;
425
+ case "delete":
426
+ msg.messageStubType =
427
+ Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_DELETED;
428
+ msg.messageStubParameters = [participantJid, "delete"];
429
+ break;
430
+ case "ephemeral":
431
+ case "not_ephemeral":
432
+ msg.message = {
433
+ protocolMessage: {
434
+ type: WAProto_1.proto.Message.ProtocolMessage.Type
435
+ .EPHEMERAL_SETTING,
436
+ ephemeralExpiration: +(child.attrs.expiration || 0),
437
+ },
438
+ };
439
+ break;
440
+ case "modify":
441
+ const oldNumber = WABinary_1.getBinaryNodeChildren(
442
+ child,
443
+ "participant"
444
+ ).map((p) => p.attrs.jid);
445
+ msg.messageStubParameters = oldNumber || [];
446
+ msg.messageStubType =
447
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
448
+ break;
449
+ case "promote":
450
+ case "demote":
451
+ case "remove":
452
+ case "add":
453
+ case "leave":
454
+ let stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
455
+ if (child.attrs?.reason === "linked_group_join") {
456
+ stubType = GROUP_PARTICIPANT_LINKED_GROUP_JOIN;
717
457
  }
718
- return data instanceof Buffer ? data : Buffer.from(data);
719
- }
720
- const willSendMessageAgain = async (id, participant) => {
721
- const key = `${id}:${participant}`;
722
- const retryCount = (await msgRetryCache.get(key)) || 0;
723
- return retryCount < maxMsgRetryCount;
724
- };
725
- const updateSendMessageAgainCount = async (id, participant) => {
726
- const key = `${id}:${participant}`;
727
- const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
728
- await msgRetryCache.set(key, newValue);
729
- };
730
- const sendMessagesAgain = async (key, ids, retryNode) => {
731
- const remoteJid = key.remoteJid;
732
- const participant = key.participant || remoteJid;
733
- const retryCount = +retryNode.attrs.count || 1;
734
- // Try to get messages from cache first, then fallback to getMessage
735
- const msgs = [];
736
- for (const id of ids) {
737
- let msg;
738
- // Try to get from retry cache first if enabled
739
- if (messageRetryManager) {
740
- const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
741
- if (cachedMsg) {
742
- msg = cachedMsg.message;
743
- logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
744
- // Mark retry as successful since we found the message
745
- messageRetryManager.markRetrySuccess(id);
746
- }
747
- }
748
- // Fallback to getMessage if not found in cache
749
- if (!msg) {
750
- msg = await getMessage({ ...key, id });
751
- if (msg) {
752
- logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
753
- // Also mark as successful if found via getMessage
754
- if (messageRetryManager) {
755
- messageRetryManager.markRetrySuccess(id);
756
- }
757
- }
458
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
459
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(
460
+ child,
461
+ "participant"
462
+ )
463
+ .map((p) => {
464
+ const { jid, lid, phone_number } = p.attrs;
465
+ if (phone_number && phone_number.endsWith("@s.whatsapp.net")) {
466
+ return phone_number;
758
467
  }
759
- msgs.push(msg);
760
- }
761
- // if it's the primary jid sending the request
762
- // just re-send the message to everyone
763
- // prevents the first message decryption failure
764
- const sendToAll = !jidDecode(participant)?.device;
765
- // Check if we should recreate session for this retry
766
- let shouldRecreateSession = false;
767
- let recreateReason = '';
768
- if (enableAutoSessionRecreation && messageRetryManager) {
769
- try {
770
- const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
771
- const hasSession = await signalRepository.validateSession(participant);
772
- const result = messageRetryManager.shouldRecreateSession(participant, retryCount, hasSession.exists);
773
- shouldRecreateSession = result.recreate;
774
- recreateReason = result.reason;
775
- if (shouldRecreateSession) {
776
- logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
777
- await authState.keys.set({ session: { [sessionId]: null } });
778
- }
468
+ if (jid && jid.endsWith("@s.whatsapp.net")) {
469
+ return jid;
779
470
  }
780
- catch (error) {
781
- logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
471
+ if (lid && lid.endsWith("@lid")) {
782
472
  }
473
+ return null;
474
+ })
475
+ .filter(Boolean);
476
+
477
+ if (
478
+ participants.length === 1 &&
479
+ // if recv. "remove" message and sender removed themselves
480
+ // mark as left
481
+ WABinary_1.areJidsSameUser(participants[0], participant) &&
482
+ child.tag === "remove"
483
+ ) {
484
+ msg.messageStubType =
485
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
783
486
  }
784
- await assertSessions([participant]);
785
- if (isJidGroup(remoteJid)) {
786
- await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
487
+ msg.messageStubParameters = participants;
488
+ break;
489
+ case "subject":
490
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
491
+ msg.messageStubType =
492
+ Types_1.WAMessageStubType.COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED;
493
+ msg.messageStubParameters = [participantJid, child.attrs.subject];
494
+ break;
495
+ case "description":
496
+ const description = WABinary_1.getBinaryNodeChild(
497
+ child,
498
+ "body"
499
+ )?.content?.toString();
500
+ msg.messageStubType =
501
+ Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
502
+ msg.messageStubType =
503
+ Types_1.WAMessageStubType.COMMUNITY_CHANGE_DESCRIPTION;
504
+ msg.messageStubParameters = description ? [description] : undefined;
505
+
506
+ break;
507
+ case "announcement":
508
+ case "not_announcement":
509
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
510
+ msg.messageStubParameters = [
511
+ child.tag === "announcement" ? "on" : "off",
512
+ ];
513
+ break;
514
+ case "locked":
515
+ case "unlocked":
516
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
517
+ msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"];
518
+ break;
519
+ case "invite":
520
+ msg.messageStubType =
521
+ Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
522
+ msg.messageStubParameters = [child.attrs.code];
523
+ break;
524
+ case "member_add_mode":
525
+ const addMode = child.content;
526
+ if (addMode) {
527
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
528
+ msg.messageStubParameters = [addMode.toString()];
787
529
  }
788
- logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
789
- for (const [i, msg] of msgs.entries()) {
790
- if (!ids[i])
791
- continue;
792
- if (msg && (await willSendMessageAgain(ids[i], participant))) {
793
- updateSendMessageAgainCount(ids[i], participant);
794
- const msgRelayOpts = { messageId: ids[i] };
795
- if (sendToAll) {
796
- msgRelayOpts.useUserDevicesCache = false;
797
- }
798
- else {
799
- msgRelayOpts.participant = {
800
- jid: participant,
801
- count: +retryNode.attrs.count
802
- };
803
- }
804
- await relayMessage(key.remoteJid, msg, msgRelayOpts);
805
- }
806
- else {
807
- logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
808
- }
530
+ break;
531
+ case "membership_approval_mode":
532
+ const approvalMode = WABinary_1.getBinaryNodeChild(child, "group_join");
533
+ if (approvalMode) {
534
+ msg.messageStubType =
535
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
536
+ msg.messageStubParameters = [approvalMode.attrs.state];
809
537
  }
810
- };
811
- const handleReceipt = async (node) => {
812
- const { attrs, content } = node;
813
- const isLid = attrs.from.includes('lid');
814
- const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
815
- const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
816
- const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
817
- const key = {
818
- remoteJid,
819
- id: '',
820
- fromMe,
821
- participant: attrs.participant
538
+ break;
539
+ case "created_membership_requests":
540
+ msg.messageStubType =
541
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
542
+ msg.messageStubParameters = [
543
+ participantJid,
544
+ "created",
545
+ child.attrs.request_method,
546
+ ];
547
+ break;
548
+ case "revoked_membership_requests":
549
+ const isDenied = WABinary_1.areJidsSameUser(
550
+ participantJid,
551
+ participant
552
+ );
553
+ msg.messageStubType =
554
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
555
+ msg.messageStubParameters = [
556
+ participantJid,
557
+ isDenied ? "revoked" : "rejected",
558
+ ];
559
+ break;
560
+ case "link":
561
+ case "unlink":
562
+ const type = child.attrs?.unlink_type || child.attrs?.link_type;
563
+ const stubMap = {
564
+ parent_group:
565
+ Types_1.WAMessageStubType[
566
+ `COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`
567
+ ],
568
+ sibling_group:
569
+ Types_1.WAMessageStubType[
570
+ `COMMUNITY_${child.tag.toUpperCase()}_SIBLING_GROUP`
571
+ ],
572
+ sub_group:
573
+ Types_1.WAMessageStubType[
574
+ `COMMUNITY_${child.tag.toUpperCase()}_SUB_GROUP`
575
+ ],
822
576
  };
823
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
824
- logger.debug({ remoteJid }, 'ignoring receipt from jid');
825
- await sendMessageAck(node);
826
- return;
827
- }
828
- const ids = [attrs.id];
829
- if (Array.isArray(content)) {
830
- const items = getBinaryNodeChildren(content[0], 'item');
831
- ids.push(...items.map(i => i.attrs.id));
577
+ const groups = WABinary_1.getBinaryNodeChildren(child, "group")
578
+ .map((g) => g.attrs?.jid || g.attrs?.subject || "")
579
+ .filter((x) => x);
580
+ msg.messageStubType =
581
+ stubMap?.[type] ||
582
+ Types_1.WAMessageStubType[
583
+ `COMMUNITY_${child.tag.toUpperCase()}_PARENT_GROUP`
584
+ ];
585
+ msg.messageStubParameters = [participantJid, child.tag, groups];
586
+ break;
587
+ case "linked_group_promote":
588
+ case "linked_group_demote":
589
+ const stubtype = `COMMUNITY_PARTICIPANT_${child.tag
590
+ .split("_")[2]
591
+ .toUpperCase()}`;
592
+ const participantS =
593
+ mode === "lid"
594
+ ? WABinary_1.getBinaryNodeChildren(child, "participant").map(
595
+ (p) => p.attrs.phone_number
596
+ )
597
+ : WABinary_1.getBinaryNodeChildren(child, "participant").map(
598
+ (p) => p.attrs.jid
599
+ );
600
+ msg.messageStubType = Types_1.WAMessageStubType[stubtype];
601
+ msg.messageStubParameters = participantS;
602
+ break;
603
+ case "created_sub_group_suggestion":
604
+ msg.messageStubType =
605
+ Types_1.WAMessageStubType.SUGGESTED_SUBGROUP_ANNOUNCE;
606
+ msg.messageStubParameters = [participantJid, "add"];
607
+ break;
608
+ case "revoked_sub_group_suggestions":
609
+ const res = WABinary_1.getBinaryNodeChildren(
610
+ child,
611
+ "sub_group_suggestions"
612
+ );
613
+ const reason = res.attrs?.reason;
614
+ if (reason === "approved")
615
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
616
+ else
617
+ msg.messageStubType = Types_1.WAMessageStubType.GENERIC_NOTIFICATION;
618
+ msg.messageStubParameters = [participantJid, reason];
619
+ break;
620
+ default:
621
+ logger.warn(child.tag, "Unhandled group node");
622
+ break;
623
+ }
624
+ };
625
+
626
+ const handleNewsletterNotification = (id, node) => {
627
+ const messages = WABinary_1.getBinaryNodeChild(node, "messages");
628
+ const message = WABinary_1.getBinaryNodeChild(node, "message");
629
+ const serverId = node.attrs.server_id;
630
+
631
+ const reactionsList = WABinary_1.getBinaryNodeChild(node, "reactions");
632
+ const viewsList = WABinary_1.getBinaryNodeChild(node, "views_count");
633
+
634
+ if (reactionsList) {
635
+ const reactions = WABinary_1.getBinaryNodeChild(
636
+ reactionsList,
637
+ "reaction"
638
+ );
639
+
640
+ if (reactions.length === 0) {
641
+ ev.emit("newsletter.reaction", {
642
+ id,
643
+ newsletter_server_id: serverId,
644
+ reaction: {
645
+ removed: true,
646
+ },
647
+ });
648
+ }
649
+
650
+ reactions.forEach((item) => {
651
+ ev.emit("newsletter.reaction", {
652
+ id,
653
+ newsletter_server_id: serverId,
654
+ reaction: {
655
+ code: item.attrs?.code,
656
+ count: +item.attrs.count,
657
+ },
658
+ });
659
+ });
660
+ }
661
+
662
+ if (viewsList.length) {
663
+ viewsList.forEach((item) => {
664
+ ev.emit("newsletter.view", {
665
+ id,
666
+ newsletter_server_id: serverId,
667
+ count: +item.attrs.count,
668
+ });
669
+ });
670
+ }
671
+ };
672
+
673
+ const handleMexNotification = (id, node) => {
674
+ const operation = node?.attrs?.op_name;
675
+ const content = JSON.parse(node?.content);
676
+
677
+ let contentPath;
678
+ let action;
679
+
680
+ if (operation === Types_1.MexOperations.UPDATE) {
681
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
682
+
683
+ ev.emit("newsletter-settings.update", {
684
+ id,
685
+ update: contentPath.thread_metadata.settings,
686
+ });
687
+ } else if (operation === Types_1.MexUpdatesOperations.GROUP_LIMIT_SHARING) {
688
+ contentPath =
689
+ content.data[Types_1.XWAPathsMexUpdates.GROUP_SHARING_CHANGE];
690
+
691
+ ev.emit("limit-sharing.update", {
692
+ id,
693
+ author: contentPath.updated_by?.pn
694
+ ? contentPath.updated_by.pn
695
+ : contentPath.updated_by.id,
696
+ action: `${
697
+ contentPath.properties.limit_sharing.limit_sharing_enabled
698
+ ? "on"
699
+ : "off"
700
+ }`,
701
+ trigger: contentPath.properties.limit_sharing.limit_sharing_trigger,
702
+ update_time: contentPath.update_time,
703
+ });
704
+ } else if (operation === Types_1.MexUpdatesOperations.OWNER_COMMUNITY) {
705
+ contentPath =
706
+ content.data[Types_1.XWAPathsMexUpdates.COMMUNITY_OWNER_CHANGE];
707
+
708
+ ev.emit("community-owner.update", {
709
+ id,
710
+ author: contentPath.updated_by?.pn
711
+ ? contentPath.updated_by.pn
712
+ : contentPath.updated_by.id,
713
+ user: contentPath.role_updates[0].user?.pn
714
+ ? contentPath.role_updates[0].user.pn
715
+ : contentPath.role_updates[0].user.jid,
716
+ new_role: contentPath.role_updates[0].new_role,
717
+ update_time: contentPath.update_time,
718
+ });
719
+ } else {
720
+ if (operation === Types_1.MexOperations.PROMOTE) {
721
+ action = "promote";
722
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
723
+ } else {
724
+ action = "demote";
725
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
726
+ }
727
+
728
+ ev.emit("newsletter-participants.update", {
729
+ id,
730
+ author: contentPath.actor.pn,
731
+ user: contentPath.user.pn,
732
+ new_role: contentPath.user_new_role,
733
+ action,
734
+ });
735
+ }
736
+ };
737
+
738
+ const processNotification = async (node) => {
739
+ const result = {};
740
+ const [child] = WABinary_1.getAllBinaryNodeChildren(node);
741
+ const nodeType = node.attrs.type;
742
+ const from = WABinary_1.jidNormalizedUser(node.attrs.from);
743
+
744
+ switch (nodeType) {
745
+ case "privacy_token":
746
+ const tokenList = WABinary_1.getBinaryNodeChildren(child, "token");
747
+ for (const { attrs, content } of tokenList) {
748
+ const jid = attrs.jid;
749
+ ev.emit("chats.update", [
750
+ {
751
+ id: jid,
752
+ tcToken: content,
753
+ },
754
+ ]);
755
+ logger.debug({ jid }, "got privacy token update");
832
756
  }
833
- try {
834
- await Promise.all([
835
- processingMutex.mutex(async () => {
836
- const status = getStatusFromReceiptType(attrs.type);
837
- if (typeof status !== 'undefined' &&
838
- // basically, we only want to know when a message from us has been delivered to/read by the other person
839
- // or another device of ours has read some messages
840
- (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
841
- if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
842
- if (attrs.participant) {
843
- const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
844
- ev.emit('message-receipt.update', ids.map(id => ({
845
- key: { ...key, id },
846
- receipt: {
847
- userJid: jidNormalizedUser(attrs.participant),
848
- [updateKey]: +attrs.t
849
- }
850
- })));
851
- }
852
- }
853
- else {
854
- ev.emit('messages.update', ids.map(id => ({
855
- key: { ...key, id },
856
- update: { status }
857
- })));
858
- }
859
- }
860
- if (attrs.type === 'retry') {
861
- // correctly set who is asking for the retry
862
- key.participant = key.participant || attrs.from;
863
- const retryNode = getBinaryNodeChild(node, 'retry');
864
- if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
865
- if (key.fromMe) {
866
- try {
867
- updateSendMessageAgainCount(ids[0], key.participant);
868
- logger.debug({ attrs, key }, 'recv retry request');
869
- await sendMessagesAgain(key, ids, retryNode);
870
- }
871
- catch (error) {
872
- logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
873
- }
874
- }
875
- else {
876
- logger.info({ attrs, key }, 'recv retry for not fromMe message');
877
- }
878
- }
879
- else {
880
- logger.info({ attrs, key }, 'will not send message again, as sent too many times');
881
- }
882
- }
883
- })
884
- ]);
757
+ break;
758
+ case "w:gp2":
759
+ const mode = node.attrs.addressing_mode;
760
+ handleGroupNotification(
761
+ node.attrs.participant,
762
+ child,
763
+ result,
764
+ node.attrs.participant_pn,
765
+ mode
766
+ );
767
+ break;
768
+ case "newsletter":
769
+ handleNewsletterNotification(node.attrs.from, child);
770
+ break;
771
+ case "mex":
772
+ handleMexNotification(node.attrs.from, child);
773
+ break;
774
+ case "mediaretry":
775
+ const event = Utils_1.decodeMediaRetryNode(node);
776
+ ev.emit("messages.media-update", [event]);
777
+ break;
778
+ case "encrypt":
779
+ await handleEncryptNotification(node);
780
+ break;
781
+ case "devices":
782
+ const devices = WABinary_1.getBinaryNodeChildren(child, "device");
783
+ if (
784
+ WABinary_1.areJidsSameUser(child.attrs.jid, authState.creds.me.id)
785
+ ) {
786
+ const deviceJids = devices.map((d) => d.attrs.jid);
787
+ logger.info({ deviceJids }, "got my own devices");
885
788
  }
886
- finally {
887
- await sendMessageAck(node);
789
+ break;
790
+ case "server_sync":
791
+ const update = WABinary_1.getBinaryNodeChild(node, "collection");
792
+ if (update) {
793
+ const name = update.attrs.name;
794
+ await resyncAppState([name], false);
888
795
  }
889
- };
890
- const handleNotification = async (node) => {
891
- const remoteJid = node.attrs.from;
892
- if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
893
- logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
894
- await sendMessageAck(node);
895
- return;
796
+ break;
797
+ case "picture":
798
+ const setPicture = WABinary_1.getBinaryNodeChild(node, "set");
799
+ const delPicture = WABinary_1.getBinaryNodeChild(node, "delete");
800
+ ev.emit("contacts.update", [
801
+ {
802
+ id:
803
+ WABinary_1.jidNormalizedUser(node?.attrs?.from) ||
804
+ (setPicture || delPicture)?.attrs?.hash ||
805
+ "",
806
+ imgUrl: setPicture ? "changed" : "removed",
807
+ },
808
+ ]);
809
+ if (WABinary_1.isJidGroup(from)) {
810
+ const node = setPicture || delPicture;
811
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
812
+ if (setPicture) {
813
+ result.messageStubParameters = [setPicture.attrs.id];
814
+ }
815
+ result.participant = node?.attrs?.author;
816
+ result.key = {
817
+ ...(result.key || {}),
818
+ participant: setPicture?.attrs?.author,
819
+ };
896
820
  }
897
- try {
898
- await Promise.all([
899
- processingMutex.mutex(async () => {
900
- const msg = await processNotification(node);
901
- if (msg) {
902
- const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
903
- const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
904
- msg.key = {
905
- remoteJid,
906
- fromMe,
907
- participant: node.attrs.participant,
908
- participantAlt,
909
- addressingMode,
910
- id: node.attrs.id,
911
- ...(msg.key || {})
912
- };
913
- msg.participant ?? (msg.participant = node.attrs.participant);
914
- msg.messageTimestamp = +node.attrs.t;
915
- const fullMsg = proto.WebMessageInfo.fromObject(msg);
916
- await upsertMessage(fullMsg, 'append');
917
- }
918
- })
919
- ]);
821
+ break;
822
+ case "account_sync":
823
+ if (child.tag === "disappearing_mode") {
824
+ const newDuration = +child.attrs.duration;
825
+ const timestamp = +child.attrs.t;
826
+ logger.info({ newDuration }, "updated account disappearing mode");
827
+ ev.emit("creds.update", {
828
+ accountSettings: {
829
+ ...authState.creds.accountSettings,
830
+ defaultDisappearingMode: {
831
+ ephemeralExpiration: newDuration,
832
+ ephemeralSettingTimestamp: timestamp,
833
+ },
834
+ },
835
+ });
836
+ } else if (child.tag === "blocklist") {
837
+ const blocklists = WABinary_1.getBinaryNodeChildren(child, "item");
838
+ for (const { attrs } of blocklists) {
839
+ const blocklist = [attrs.jid];
840
+ const type = attrs.action === "block" ? "add" : "remove";
841
+ ev.emit("blocklist.update", { blocklist, type });
842
+ }
920
843
  }
921
- finally {
922
- await sendMessageAck(node);
844
+ break;
845
+ case "link_code_companion_reg":
846
+ const linkCodeCompanionReg = WABinary_1.getBinaryNodeChild(
847
+ node,
848
+ "link_code_companion_reg"
849
+ );
850
+ const ref = toRequiredBuffer(
851
+ WABinary_1.getBinaryNodeChildBuffer(
852
+ linkCodeCompanionReg,
853
+ "link_code_pairing_ref"
854
+ )
855
+ );
856
+ const primaryIdentityPublicKey = toRequiredBuffer(
857
+ WABinary_1.getBinaryNodeChildBuffer(
858
+ linkCodeCompanionReg,
859
+ "primary_identity_pub"
860
+ )
861
+ );
862
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
863
+ WABinary_1.getBinaryNodeChildBuffer(
864
+ linkCodeCompanionReg,
865
+ "link_code_pairing_wrapped_primary_ephemeral_pub"
866
+ )
867
+ );
868
+ const codePairingPublicKey = await decipherLinkPublicKey(
869
+ primaryEphemeralPublicKeyWrapped
870
+ );
871
+ const companionSharedKey = Utils_1.Curve.sharedKey(
872
+ authState.creds.pairingEphemeralKeyPair.private,
873
+ codePairingPublicKey
874
+ );
875
+ const random = crypto_1.randomBytes(32);
876
+ const linkCodeSalt = crypto_1.randomBytes(32);
877
+
878
+ const linkCodePairingExpanded = await Utils_1.hkdf(
879
+ companionSharedKey,
880
+ 32,
881
+ {
882
+ salt: linkCodeSalt,
883
+ info: "link_code_pairing_key_bundle_encryption_key",
884
+ }
885
+ );
886
+
887
+ const encryptPayload = Buffer.concat([
888
+ Buffer.from(authState.creds.signedIdentityKey.public),
889
+ primaryIdentityPublicKey,
890
+ random,
891
+ ]);
892
+ const encryptIv = crypto_1.randomBytes(12);
893
+ const encrypted = Utils_1.aesEncryptGCM(
894
+ encryptPayload,
895
+ linkCodePairingExpanded,
896
+ encryptIv,
897
+ Buffer.alloc(0)
898
+ );
899
+ const encryptedPayload = Buffer.concat([
900
+ linkCodeSalt,
901
+ encryptIv,
902
+ encrypted,
903
+ ]);
904
+ const identitySharedKey = Utils_1.Curve.sharedKey(
905
+ authState.creds.signedIdentityKey.private,
906
+ primaryIdentityPublicKey
907
+ );
908
+ const identityPayload = Buffer.concat([
909
+ companionSharedKey,
910
+ identitySharedKey,
911
+ random,
912
+ ]);
913
+
914
+ authState.creds.advSecretKey = (
915
+ await Utils_1.hkdf(identityPayload, 32, { info: "adv_secret" })
916
+ ).toString("base64");
917
+
918
+ await query({
919
+ tag: "iq",
920
+ attrs: {
921
+ to: WABinary_1.S_WHATSAPP_NET,
922
+ type: "set",
923
+ id: Neele.generateMessageTag(),
924
+ xmlns: "md",
925
+ },
926
+ content: [
927
+ {
928
+ tag: "link_code_companion_reg",
929
+ attrs: {
930
+ jid: authState.creds.me.id,
931
+ stage: "companion_finish",
932
+ },
933
+ content: [
934
+ {
935
+ tag: "link_code_pairing_wrapped_key_bundle",
936
+ attrs: {},
937
+ content: encryptedPayload,
938
+ },
939
+ {
940
+ tag: "companion_identity_public",
941
+ attrs: {},
942
+ content: authState.creds.signedIdentityKey.public,
943
+ },
944
+ {
945
+ tag: "link_code_pairing_ref",
946
+ attrs: {},
947
+ content: ref,
948
+ },
949
+ ],
950
+ },
951
+ ],
952
+ });
953
+
954
+ authState.creds.registered = true;
955
+ ev.emit("creds.update", authState.creds);
956
+ }
957
+
958
+ if (Object.keys(result).length) {
959
+ return result;
960
+ }
961
+ };
962
+
963
+ async function decipherLinkPublicKey(data) {
964
+ const buffer = toRequiredBuffer(data);
965
+ const salt = buffer.slice(0, 32);
966
+ const secretKey = await Utils_1.derivePairingCodeKey(
967
+ authState.creds.pairingCode,
968
+ salt
969
+ );
970
+ const iv = buffer.slice(32, 48);
971
+ const payload = buffer.slice(48, 80);
972
+ return Utils_1.aesDecryptCTR(payload, secretKey, iv);
973
+ }
974
+
975
+ function toRequiredBuffer(data) {
976
+ if (data === undefined) {
977
+ throw new boom_1.Boom("Invalid buffer", { statusCode: 400 });
978
+ }
979
+ return data instanceof Buffer ? data : Buffer.from(data);
980
+ }
981
+
982
+ const willSendMessageAgain = (id, participant) => {
983
+ const key = `${id}:${participant}`;
984
+ const retryCount = msgRetryCache.get(key) || 0;
985
+ return retryCount < maxMsgRetryCount;
986
+ };
987
+
988
+ const updateSendMessageAgainCount = (id, participant) => {
989
+ const key = `${id}:${participant}`;
990
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
991
+ msgRetryCache.set(key, newValue);
992
+ };
993
+
994
+ const sendMessagesAgain = async (key, ids, retryNode) => {
995
+ const msgs = await Promise.all(ids.map((id) => getMessage({ ...key, id })));
996
+ const remoteJid = key.remoteJid;
997
+ const participant = key.participant || remoteJid;
998
+
999
+ // if it's the primary jid sending the request
1000
+ // just re-send the message to everyone
1001
+ // prevents the first message decryption failure
1002
+ const sendToAll = !WABinary_1.jidDecode(participant)?.device;
1003
+ await assertSessions([participant], true);
1004
+
1005
+ if (WABinary_1.isJidGroup(remoteJid)) {
1006
+ await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } });
1007
+ }
1008
+
1009
+ logger.debug(
1010
+ { participant, sendToAll },
1011
+ "forced new session for retry recp"
1012
+ );
1013
+
1014
+ for (const [i, msg] of msgs.entries()) {
1015
+ if (msg) {
1016
+ updateSendMessageAgainCount(ids[i], participant);
1017
+ const msgRelayOpts = { messageId: ids[i] };
1018
+
1019
+ if (sendToAll) {
1020
+ msgRelayOpts.useUserDevicesCache = false;
1021
+ } else {
1022
+ msgRelayOpts.participant = {
1023
+ jid: participant,
1024
+ count: +retryNode.attrs.count,
1025
+ };
923
1026
  }
1027
+
1028
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1029
+ } else {
1030
+ logger.debug(
1031
+ { jid: key.remoteJid, id: ids[i] },
1032
+ "recv retry request, but message not available"
1033
+ );
1034
+ }
1035
+ }
1036
+ };
1037
+
1038
+ const handleReceipt = async (node) => {
1039
+ const { attrs, content } = node;
1040
+ const isLid = attrs.from.includes("lid");
1041
+ const isNodeFromMe = WABinary_1.areJidsSameUser(
1042
+ attrs.participant || attrs.from,
1043
+ isLid ? authState.creds.me?.lid : authState.creds.me?.id
1044
+ );
1045
+ const remoteJid =
1046
+ !isNodeFromMe || WABinary_1.isJidGroup(attrs.from)
1047
+ ? attrs.from
1048
+ : attrs.recipient;
1049
+ const fromMe =
1050
+ !attrs.recipient ||
1051
+ ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe);
1052
+
1053
+ const key = {
1054
+ remoteJid,
1055
+ id: "",
1056
+ fromMe,
1057
+ participant: attrs.participant,
924
1058
  };
925
- const handleMessage = async (node) => {
926
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
927
- logger.debug({ key: node.attrs.key }, 'ignored message');
928
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
929
- return;
930
- }
931
- const encNode = getBinaryNodeChild(node, 'enc');
932
- // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
933
- if (encNode && encNode.attrs.type === 'msmsg') {
934
- logger.debug({ key: node.attrs.key }, 'ignored msmsg');
935
- await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
936
- return;
937
- }
938
- const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
939
- const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
940
- // store new mappings we didn't have before
941
- if (!!alt) {
942
- const altServer = jidDecode(alt)?.server;
943
- const primaryJid = msg.key.participant || msg.key.remoteJid;
944
- if (altServer === 'lid') {
945
- if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
946
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
947
- await signalRepository.migrateSession(primaryJid, alt);
1059
+
1060
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
1061
+ logger.debug({ remoteJid }, "ignoring receipt from jid");
1062
+ await sendMessageAck(node);
1063
+ return;
1064
+ }
1065
+
1066
+ const ids = [attrs.id];
1067
+ if (Array.isArray(content)) {
1068
+ const items = WABinary_1.getBinaryNodeChildren(content[0], "item");
1069
+ ids.push(...items.map((i) => i.attrs.id));
1070
+ }
1071
+
1072
+ try {
1073
+ await Promise.all([
1074
+ processingMutex.mutex(async () => {
1075
+ const status = Utils_1.getStatusFromReceiptType(attrs.type);
1076
+
1077
+ if (
1078
+ typeof status !== "undefined" &&
1079
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1080
+ // or another device of ours has read some messages
1081
+ (status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
1082
+ !isNodeFromMe)
1083
+ ) {
1084
+ if (
1085
+ WABinary_1.isJidGroup(remoteJid) ||
1086
+ WABinary_1.isJidStatusBroadcast(remoteJid)
1087
+ ) {
1088
+ if (attrs.participant) {
1089
+ const updateKey =
1090
+ status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
1091
+ ? "receiptTimestamp"
1092
+ : "readTimestamp";
1093
+ ev.emit(
1094
+ "message-receipt.update",
1095
+ ids.map((id) => ({
1096
+ key: { ...key, id },
1097
+ receipt: {
1098
+ userJid: WABinary_1.jidNormalizedUser(attrs.participant),
1099
+ [updateKey]: +attrs.t,
1100
+ },
1101
+ }))
1102
+ );
1103
+ }
1104
+ } else {
1105
+ ev.emit(
1106
+ "messages.update",
1107
+ ids.map((id) => ({
1108
+ key: { ...key, id },
1109
+ update: { status },
1110
+ }))
1111
+ );
1112
+ }
1113
+ }
1114
+
1115
+ if (attrs.type === "retry") {
1116
+ // correctly set who is asking for the retry
1117
+ key.participant = key.participant || attrs.from;
1118
+ const retryNode = WABinary_1.getBinaryNodeChild(node, "retry");
1119
+
1120
+ if (willSendMessageAgain(ids[0], key.participant)) {
1121
+ if (key.fromMe) {
1122
+ try {
1123
+ logger.debug({ attrs, key }, "recv retry request");
1124
+ await sendMessagesAgain(key, ids, retryNode);
1125
+ } catch (error) {
1126
+ logger.error(
1127
+ { key, ids, trace: error.stack },
1128
+ "error in sending message again"
1129
+ );
948
1130
  }
1131
+ } else {
1132
+ logger.info(
1133
+ { attrs, key },
1134
+ "recv retry for not fromMe message"
1135
+ );
1136
+ }
1137
+ } else {
1138
+ logger.info(
1139
+ { attrs, key },
1140
+ "will not send message again, as sent too many times"
1141
+ );
949
1142
  }
950
- else {
951
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
952
- await signalRepository.migrateSession(alt, primaryJid);
1143
+ }
1144
+ }),
1145
+ ]);
1146
+ } finally {
1147
+ await sendMessageAck(node);
1148
+ }
1149
+ };
1150
+
1151
+ const handleNotification = async (node) => {
1152
+ const remoteJid = node.attrs.from;
1153
+
1154
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
1155
+ logger.debug({ remoteJid, id: node.attrs.id }, "ignored notification");
1156
+ await sendMessageAck(node);
1157
+ return;
1158
+ }
1159
+
1160
+ try {
1161
+ await Promise.all([
1162
+ processingMutex.mutex(async () => {
1163
+ const msg = await processNotification(node);
1164
+
1165
+ if (msg) {
1166
+ const fromMe = WABinary_1.areJidsSameUser(
1167
+ node.attrs.participant || remoteJid,
1168
+ authState.creds.me.id
1169
+ );
1170
+ msg.key = {
1171
+ remoteJid,
1172
+ fromMe,
1173
+ participant: node.attrs.participant,
1174
+ id: node.attrs.id,
1175
+ ...(msg.key || {}),
1176
+ };
1177
+ msg.participant = msg.participant
1178
+ ? msg.participant
1179
+ : node.attrs.participant;
1180
+ msg.messageTimestamp = +node.attrs.t;
1181
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1182
+ await upsertMessage(fullMsg, "append");
1183
+ }
1184
+ }),
1185
+ ]);
1186
+ } finally {
1187
+ await sendMessageAck(node);
1188
+ }
1189
+ };
1190
+
1191
+ const handleMessage = async (node) => {
1192
+ if (
1193
+ shouldIgnoreJid(node.attrs.from) &&
1194
+ node.attrs.from !== "@s.whatsapp.net"
1195
+ ) {
1196
+ logger.debug({ key: node.attrs.key }, "ignored message");
1197
+ await sendMessageAck(node);
1198
+ return;
1199
+ }
1200
+ const groupJid = node.attrs.from;
1201
+ const communityJid = linkedParentMap[groupJid];
1202
+ let response;
1203
+
1204
+ if (
1205
+ WABinary_1.getBinaryNodeChild(node, "unavailable") &&
1206
+ !WABinary_1.getBinaryNodeChild(node, "enc")
1207
+ ) {
1208
+ await sendMessageAck(node);
1209
+ const { key } = Utils_1.decodeMessageNode(
1210
+ node,
1211
+ authState.creds.me.id,
1212
+ authState.creds.me.lid || ""
1213
+ ).fullMessage;
1214
+ response = await requestPlaceholderResend(key);
1215
+
1216
+ if (response === "RESOLVED") {
1217
+ return;
1218
+ }
1219
+
1220
+ logger.debug(
1221
+ "received unavailable message, acked and requested resend from phone"
1222
+ );
1223
+ } else {
1224
+ if (placeholderResendCache.get(node.attrs.id)) {
1225
+ placeholderResendCache.del(node.attrs.id);
1226
+ }
1227
+ }
1228
+
1229
+ const {
1230
+ fullMessage: msg,
1231
+ category,
1232
+ author,
1233
+ decrypt,
1234
+ } = Utils_1.decryptMessageNode(
1235
+ node,
1236
+ authState.creds.me.id,
1237
+ authState.creds.me.lid || "",
1238
+ signalRepository,
1239
+ logger
1240
+ );
1241
+
1242
+ if (
1243
+ response &&
1244
+ msg?.messageStubParameters?.[0] === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT
1245
+ ) {
1246
+ msg.messageStubParameters = [
1247
+ Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT,
1248
+ response,
1249
+ ];
1250
+ }
1251
+
1252
+ if (
1253
+ msg.message?.protocolMessage?.type ===
1254
+ WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER &&
1255
+ node.attrs.sender_pn
1256
+ ) {
1257
+ ev.emit("chats.phoneNumberShare", {
1258
+ lid: node.attrs.from,
1259
+ jid: node.attrs.sender_pn,
1260
+ });
1261
+ }
1262
+
1263
+ try {
1264
+ await Promise.all([
1265
+ processingMutex.mutex(async () => {
1266
+ await decrypt();
1267
+ // message failed to decrypt
1268
+ if (
1269
+ msg.messageStubType ===
1270
+ WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
1271
+ ) {
1272
+ if (
1273
+ msg?.messageStubParameters?.[0] ===
1274
+ Utils_1.MISSING_KEYS_ERROR_TEXT
1275
+ ) {
1276
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
953
1277
  }
954
- }
955
- if (msg.key?.remoteJid && msg.key?.id && messageRetryManager) {
956
- messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
957
- logger.debug({
958
- jid: msg.key.remoteJid,
959
- id: msg.key.id
960
- }, 'Added message to recent cache for retry receipts');
961
- }
962
- try {
963
- await processingMutex.mutex(async () => {
964
- await decrypt();
965
- // message failed to decrypt
966
- if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT) {
967
- if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
968
- return sendMessageAck(node, NACK_REASONS.ParsingError);
969
- }
970
- const errorMessage = msg?.messageStubParameters?.[0] || '';
971
- const isPreKeyError = errorMessage.includes('PreKey');
972
- logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
973
- // Handle both pre-key and normal retries in single mutex
974
- retryMutex.mutex(async () => {
975
- try {
976
- if (!ws.isOpen) {
977
- logger.debug({ node }, 'Connection closed, skipping retry');
978
- return;
979
- }
980
- // Handle pre-key errors with upload and delay
981
- if (isPreKeyError) {
982
- logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
983
- try {
984
- logger.debug('Uploading pre-keys for error recovery');
985
- await uploadPreKeys(5);
986
- logger.debug('Waiting for server to process new pre-keys');
987
- await delay(1000);
988
- }
989
- catch (uploadErr) {
990
- logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
991
- }
992
- }
993
- const encNode = getBinaryNodeChild(node, 'enc');
994
- await sendRetryRequest(node, !encNode);
995
- if (retryRequestDelayMs) {
996
- await delay(retryRequestDelayMs);
997
- }
998
- }
999
- catch (err) {
1000
- logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1001
- // Still attempt retry even if pre-key upload failed
1002
- try {
1003
- const encNode = getBinaryNodeChild(node, 'enc');
1004
- await sendRetryRequest(node, !encNode);
1005
- }
1006
- catch (retryErr) {
1007
- logger.error({ retryErr }, 'Failed to send retry after error handling');
1008
- }
1009
- }
1010
- await sendMessageAck(node, NACK_REASONS.UnhandledError);
1011
- });
1278
+
1279
+ retryMutex.mutex(async () => {
1280
+ if (ws.isOpen) {
1281
+ if (WABinary_1.getBinaryNodeChild(node, "unavailable")) {
1282
+ return;
1012
1283
  }
1013
- else {
1014
- // no type in the receipt => message delivered
1015
- let type = undefined;
1016
- let participant = msg.key.participant;
1017
- if (category === 'peer') {
1018
- // special peer message
1019
- type = 'peer_msg';
1020
- }
1021
- else if (msg.key.fromMe) {
1022
- // message was sent by us from a different device
1023
- type = 'sender';
1024
- // need to specially handle this case
1025
- if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1026
- participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1027
- }
1028
- }
1029
- else if (!sendActiveReceipts) {
1030
- type = 'inactive';
1031
- }
1032
- await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1033
- // send ack for history message
1034
- const isAnyHistoryMsg = getHistoryMsg(msg.message);
1035
- if (isAnyHistoryMsg) {
1036
- const jid = jidNormalizedUser(msg.key.remoteJid);
1037
- await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1038
- }
1284
+
1285
+ const encNode = WABinary_1.getBinaryNodeChild(node, "enc");
1286
+ await sendRetryRequest(node, !encNode);
1287
+
1288
+ if (retryRequestDelayMs) {
1289
+ await Utils_1.delay(retryRequestDelayMs);
1039
1290
  }
1040
- cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1041
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1291
+ } else {
1292
+ logger.debug({ node }, "connection closed, ignoring retry req");
1293
+ }
1042
1294
  });
1043
- }
1044
- catch (error) {
1045
- logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1046
- }
1047
- };
1048
- const handleCall = async (node) => {
1049
- const { attrs } = node;
1050
- const [infoChild] = getAllBinaryNodeChildren(node);
1051
- const status = getCallStatusFromNode(infoChild);
1052
- if (!infoChild) {
1053
- throw new Boom('Missing call info in call node');
1054
- }
1055
- const callId = infoChild.attrs['call-id'];
1056
- const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1057
- const call = {
1058
- chatId: attrs.from,
1059
- from,
1060
- id: callId,
1061
- date: new Date(+attrs.t * 1000),
1062
- offline: !!attrs.offline,
1063
- status
1064
- };
1065
- if (status === 'offer') {
1066
- call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1067
- call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1068
- call.groupJid = infoChild.attrs['group-jid'];
1069
- await callOfferCache.set(call.id, call);
1070
- }
1071
- const existingCall = await callOfferCache.get(call.id);
1072
- // use existing call info to populate this event
1073
- if (existingCall) {
1074
- call.isVideo = existingCall.isVideo;
1075
- call.isGroup = existingCall.isGroup;
1076
- }
1077
- // delete data once call has ended
1078
- if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1079
- await callOfferCache.del(call.id);
1080
- }
1081
- ev.emit('call', [call]);
1082
- await sendMessageAck(node);
1083
- };
1084
- const handleBadAck = async ({ attrs }) => {
1085
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1086
- // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1087
- // // current hypothesis is that if pash is sent in the ack
1088
- // // it means -- the message hasn't reached all devices yet
1089
- // // we'll retry sending the message here
1090
- // if(attrs.phash) {
1091
- // logger.info({ attrs }, 'received phash in ack, resending message...')
1092
- // const msg = await getMessage(key)
1093
- // if(msg) {
1094
- // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1095
- // } else {
1096
- // logger.warn({ attrs }, 'could not send message again, as it was not found')
1097
- // }
1098
- // }
1099
- // error in acknowledgement,
1100
- // device could not display the message
1101
- if (attrs.error) {
1102
- logger.warn({ attrs }, 'received error in ack');
1103
- ev.emit('messages.update', [
1104
- {
1105
- key,
1106
- update: {
1107
- status: WAMessageStatus.ERROR,
1108
- messageStubParameters: [attrs.error]
1109
- }
1295
+ } else {
1296
+ // no type in the receipt => message delivered
1297
+ let type = undefined;
1298
+ if (communityJid) {
1299
+ msg.communityJid = communityJid;
1300
+ }
1301
+ const content = Utils_1.normalizeMessageContent(msg.message);
1302
+ const type_2 = Utils_1.getContentType(content);
1303
+ const message = msg.message[type_2];
1304
+
1305
+ if (node?.attrs?.addressing_mode === "lid") {
1306
+ const metadata = await groupMetadata(node.attrs.from);
1307
+ let found = metadata.participants.find(
1308
+ (p) => p.lid === node.attrs.participant
1309
+ );
1310
+
1311
+ msg.key.participant = found.id;
1312
+
1313
+ if (message?.contextInfo?.participant) {
1314
+ found = metadata.participants.find(
1315
+ (p) => p.lid === msg.message[type_2].contextInfo.participant
1316
+ );
1317
+ msg.message[type_2].contextInfo.participant = found.id;
1318
+ }
1319
+
1320
+ if (message?.contextInfo?.mentionedJid?.length > 0) {
1321
+ let mentions = [];
1322
+ for (const id of message.contextInfo.mentionedJid) {
1323
+ found = metadata.participants.find((p) => p.lid === id);
1324
+ mentions.push(found.id);
1110
1325
  }
1111
- ]);
1112
- }
1326
+ msg.message[type_2].contextInfo.mentionedJid = mentions;
1327
+ }
1328
+ }
1329
+
1330
+ if (
1331
+ !WABinary_1.isJidGroup(node.attrs.from) &&
1332
+ WABinary_1.isLidUser(
1333
+ WABinary_1.jidNormalizedUser(node.attrs.from)
1334
+ )
1335
+ ) {
1336
+ const senderPn = WABinary_1.jidNormalizedUser(
1337
+ node.attrs.peer_recipient_pn || node.attrs.sender_pn
1338
+ );
1339
+ msg.key.remoteJid = senderPn;
1340
+
1341
+ if (message?.contextInfo?.participant) {
1342
+ const isMe =
1343
+ msg.message[type_2].contextInfo.participant ===
1344
+ WABinary_1.jidNormalizedUser(authState.creds.me.lid);
1345
+ msg.message[type_2].contextInfo.participant = isMe
1346
+ ? WABinary_1.jidNormalizedUser(authState.creds.me.id)
1347
+ : senderPn;
1348
+ }
1349
+
1350
+ if (message?.contextInfo?.mentionedJid?.length > 0) {
1351
+ msg.message[type_2].contextInfo.mentionedJid = [senderPn];
1352
+ }
1353
+ }
1354
+
1355
+ let participant = msg.key.participant;
1356
+
1357
+ if (category === "peer") {
1358
+ // special peer message
1359
+ type = "peer_msg";
1360
+ } else if (msg.key.fromMe) {
1361
+ // message was sent by us from a different device
1362
+ type = "sender";
1363
+ // need to specially handle this case
1364
+ if (WABinary_1.isJidUser(msg.key.remoteJid)) {
1365
+ participant = author;
1366
+ }
1367
+ } else if (!sendActiveReceipts) {
1368
+ type = "inactive";
1369
+ }
1370
+
1371
+ await sendReceipt(
1372
+ msg.key.remoteJid,
1373
+ participant,
1374
+ [msg.key.id],
1375
+ type
1376
+ );
1377
+ // send ack for history message
1378
+ const isAnyHistoryMsg = Utils_1.getHistoryMsg(msg.message);
1379
+
1380
+ if (isAnyHistoryMsg) {
1381
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
1382
+ await sendReceipt(jid, undefined, [msg.key.id], "hist_sync");
1383
+ }
1384
+ }
1385
+
1386
+ // if (node?.attrs?.addressing_mode === 'lid' && node?.attrs?.participant_pn) {
1387
+ // msg.key.participant = WABinary_1.jidNormalizedUser(node.attrs.participant_pn)
1388
+ // }
1389
+
1390
+ Utils_1.cleanMessage(msg, authState.creds.me.id);
1391
+ await sendMessageAck(node);
1392
+ await upsertMessage(msg, node.attrs.offline ? "append" : "notify");
1393
+ }),
1394
+ ]);
1395
+ } catch (error) {
1396
+ logger.error({ error, node }, "error in handling message");
1397
+ }
1398
+ };
1399
+
1400
+ const fetchMessageHistory = async (
1401
+ count,
1402
+ oldestMsgKey,
1403
+ oldestMsgTimestamp
1404
+ ) => {
1405
+ if (!authState.creds.me?.id) {
1406
+ throw new boom_1.Boom("Not authenticated");
1407
+ }
1408
+
1409
+ const pdoMessage = {
1410
+ historySyncOnDemandRequest: {
1411
+ chatJid: oldestMsgKey.remoteJid,
1412
+ oldestMsgFromMe: oldestMsgKey.fromMe,
1413
+ oldestMsgId: oldestMsgKey.id,
1414
+ oldestMsgTimestampMs: oldestMsgTimestamp,
1415
+ onDemandMsgCount: count,
1416
+ },
1417
+ peerDataOperationRequestType:
1418
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1419
+ .HISTORY_SYNC_ON_DEMAND,
1113
1420
  };
1114
- /// processes a node with the given function
1115
- /// and adds the task to the existing buffer if we're buffering events
1116
- const processNodeWithBuffer = async (node, identifier, exec) => {
1117
- ev.buffer();
1118
- await execTask();
1119
- ev.flush();
1120
- function execTask() {
1121
- return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1122
- }
1421
+
1422
+ return sendPeerDataOperationMessage(pdoMessage);
1423
+ };
1424
+
1425
+ const requestPlaceholderResend = async (messageKey) => {
1426
+ if (!authState.creds.me?.id) {
1427
+ throw new boom_1.Boom("Not authenticated");
1428
+ }
1429
+
1430
+ if (placeholderResendCache.get(messageKey?.id)) {
1431
+ logger.debug({ messageKey }, "already requested resend");
1432
+ return;
1433
+ } else {
1434
+ placeholderResendCache.set(messageKey?.id, true);
1435
+ }
1436
+
1437
+ await Utils_1.delay(5000);
1438
+
1439
+ if (!placeholderResendCache.get(messageKey?.id)) {
1440
+ logger.debug({ messageKey }, "message received while resend requested");
1441
+ return "RESOLVED";
1442
+ }
1443
+
1444
+ const pdoMessage = {
1445
+ placeholderMessageResendRequest: [
1446
+ {
1447
+ messageKey,
1448
+ },
1449
+ ],
1450
+ peerDataOperationRequestType:
1451
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1452
+ .PLACEHOLDER_MESSAGE_RESEND,
1123
1453
  };
1124
- const makeOfflineNodeProcessor = () => {
1125
- const nodeProcessorMap = new Map([
1126
- ['message', handleMessage],
1127
- ['call', handleCall],
1128
- ['receipt', handleReceipt],
1129
- ['notification', handleNotification]
1130
- ]);
1131
- const nodes = [];
1132
- let isProcessing = false;
1133
- const enqueue = (type, node) => {
1134
- nodes.push({ type, node });
1135
- if (isProcessing) {
1136
- return;
1137
- }
1138
- isProcessing = true;
1139
- const promise = async () => {
1140
- while (nodes.length && ws.isOpen) {
1141
- const { type, node } = nodes.shift();
1142
- const nodeProcessor = nodeProcessorMap.get(type);
1143
- if (!nodeProcessor) {
1144
- onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1145
- continue;
1146
- }
1147
- await nodeProcessor(node);
1148
- }
1149
- isProcessing = false;
1150
- };
1151
- promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1454
+
1455
+ setTimeout(() => {
1456
+ if (placeholderResendCache.get(messageKey?.id)) {
1457
+ logger.debug(
1458
+ { messageKey },
1459
+ "PDO message without response after 15 seconds. Phone possibly offline"
1460
+ );
1461
+ placeholderResendCache.del(messageKey?.id);
1462
+ }
1463
+ }, 15000);
1464
+
1465
+ return sendPeerDataOperationMessage(pdoMessage);
1466
+ };
1467
+
1468
+ const handleCall = async (node) => {
1469
+ let status;
1470
+
1471
+ const { attrs } = node;
1472
+ const [infoChild] = WABinary_1.getAllBinaryNodeChildren(node);
1473
+ const callId = infoChild.attrs["call-id"];
1474
+ const from = infoChild.attrs.from || infoChild.attrs["call-creator"];
1475
+ status = Utils_1.getCallStatusFromNode(infoChild);
1476
+
1477
+ if (WABinary_1.isLidUser(from) && infoChild.tag === "relaylatency") {
1478
+ const verify = callOfferCache.get(callId);
1479
+
1480
+ if (!verify) {
1481
+ status = "offer";
1482
+
1483
+ const callLid = {
1484
+ chatId: attrs.from,
1485
+ from,
1486
+ id: callId,
1487
+ date: new Date(+attrs.t * 1000),
1488
+ offline: !!attrs.offline,
1489
+ status,
1152
1490
  };
1153
- return { enqueue };
1491
+ callOfferCache.set(callId, callLid);
1492
+ }
1493
+ }
1494
+
1495
+ const call = {
1496
+ chatId: attrs.from,
1497
+ from,
1498
+ id: callId,
1499
+ date: new Date(+attrs.t * 1000),
1500
+ offline: !!attrs.offline,
1501
+ status,
1154
1502
  };
1155
- const offlineNodeProcessor = makeOfflineNodeProcessor();
1156
- const processNode = (type, node, identifier, exec) => {
1157
- const isOffline = !!node.attrs.offline;
1158
- if (isOffline) {
1159
- offlineNodeProcessor.enqueue(type, node);
1160
- }
1161
- else {
1162
- processNodeWithBuffer(node, identifier, exec);
1163
- }
1503
+
1504
+ if (status === "offer") {
1505
+ call.isVideo = !!WABinary_1.getBinaryNodeChild(infoChild, "video");
1506
+ call.isGroup =
1507
+ infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"];
1508
+ call.groupJid = infoChild.attrs["group-jid"];
1509
+ callOfferCache.set(call.id, call);
1510
+ }
1511
+
1512
+ const existingCall = callOfferCache.get(call.id);
1513
+
1514
+ // use existing call info to populate this event
1515
+ if (existingCall) {
1516
+ call.isVideo = existingCall.isVideo;
1517
+ call.isGroup = existingCall.isGroup;
1518
+ }
1519
+
1520
+ // delete data once call has ended
1521
+ if (
1522
+ status === "reject" ||
1523
+ status === "accept" ||
1524
+ status === "timeout" ||
1525
+ status === "terminate"
1526
+ ) {
1527
+ callOfferCache.del(call.id);
1528
+ }
1529
+
1530
+ ev.emit("call", [call]);
1531
+
1532
+ await sendMessageAck(node);
1533
+ };
1534
+
1535
+ const handleBadAck = async ({ attrs }) => {
1536
+ const key = {
1537
+ remoteJid: attrs.from,
1538
+ fromMe: true,
1539
+ id: attrs.id,
1540
+ newsletter_server_id: attrs?.server_id,
1164
1541
  };
1165
- // recv a message
1166
- ws.on('CB:message', (node) => {
1167
- processNode('message', node, 'processing message', handleMessage);
1168
- });
1169
- ws.on('CB:call', async (node) => {
1170
- processNode('call', node, 'handling call', handleCall);
1171
- });
1172
- ws.on('CB:receipt', node => {
1173
- processNode('receipt', node, 'handling receipt', handleReceipt);
1174
- });
1175
- ws.on('CB:notification', async (node) => {
1176
- processNode('notification', node, 'handling notification', handleNotification);
1177
- });
1178
- ws.on('CB:ack,class:message', (node) => {
1179
- handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1180
- });
1181
- ev.on('call', ([call]) => {
1182
- if (!call) {
1183
- return;
1542
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1543
+ // // current hypothesis is that if pash is sent in the ack
1544
+ // // it means -- the message hasn't reached all devices yet
1545
+ // // we'll retry sending the message here
1546
+ // if(attrs.phash) {
1547
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1548
+ // const msg = await getMessage(key)
1549
+ // if(msg) {
1550
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1551
+ // } else {
1552
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1553
+ // }
1554
+ // }
1555
+ // error in acknowledgement,
1556
+ // device could not display the message
1557
+ if (attrs.error) {
1558
+ logger.warn({ attrs }, "received error in ack");
1559
+ ev.emit("messages.update", [
1560
+ {
1561
+ key,
1562
+ update: {
1563
+ status: Types_1.WAMessageStatus.ERROR,
1564
+ messageStubParameters: [attrs.error],
1565
+ },
1566
+ },
1567
+ ]);
1568
+ }
1569
+ };
1570
+
1571
+ /// processes a node with the given function
1572
+ /// and adds the task to the existing buffer if we're buffering events
1573
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1574
+ ev.buffer();
1575
+ await execTask();
1576
+ ev.flush();
1577
+ function execTask() {
1578
+ return exec(node, false).catch((err) =>
1579
+ onUnexpectedError(err, identifier)
1580
+ );
1581
+ }
1582
+ };
1583
+
1584
+ let latestNodeInMemory = null;
1585
+ const nodelogger = (node) => {
1586
+ if (!node) return null;
1587
+ latestNodeInMemory = node;
1588
+ return latestNodeInMemory;
1589
+ };
1590
+ const setNodeLoggerListener = () => {
1591
+ return latestNodeInMemory;
1592
+ };
1593
+
1594
+ const makeOfflineNodeProcessor = () => {
1595
+ const nodeProcessorMap = new Map([
1596
+ ["message", handleMessage],
1597
+ ["call", handleCall],
1598
+ ["receipt", handleReceipt],
1599
+ ["notification", handleNotification],
1600
+ ]);
1601
+
1602
+ const nodes = [];
1603
+ let isProcessing = false;
1604
+
1605
+ const enqueue = (type, node) => {
1606
+ nodes.push({ type, node });
1607
+
1608
+ if (isProcessing) {
1609
+ return;
1610
+ }
1611
+
1612
+ isProcessing = true;
1613
+
1614
+ const promise = async () => {
1615
+ while (nodes.length && ws.isOpen) {
1616
+ const { type, node } = nodes.shift();
1617
+ const nodeProcessor = nodeProcessorMap.get(type);
1618
+ if (!nodeProcessor) {
1619
+ onUnexpectedError(
1620
+ new Error(`unknown offline node type: ${type}`),
1621
+ "processing offline node"
1622
+ );
1623
+ continue;
1624
+ }
1625
+ await nodeProcessor(node);
1184
1626
  }
1185
- // missed call + group call notification message generation
1186
- if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1187
- const msg = {
1188
- key: {
1189
- remoteJid: call.chatId,
1190
- id: call.id,
1191
- fromMe: false
1192
- },
1193
- messageTimestamp: unixTimestampSeconds(call.date)
1194
- };
1195
- if (call.status === 'timeout') {
1196
- if (call.isGroup) {
1197
- msg.messageStubType = call.isVideo
1198
- ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1199
- : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1200
- }
1201
- else {
1202
- msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1203
- }
1204
- }
1205
- else {
1206
- msg.message = { call: { callKey: Buffer.from(call.id) } };
1627
+ isProcessing = false;
1628
+ };
1629
+ promise().catch((error) =>
1630
+ onUnexpectedError(error, "processing offline nodes")
1631
+ );
1632
+ };
1633
+
1634
+ return { enqueue };
1635
+ };
1636
+
1637
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1638
+
1639
+ const processNode = (type, node, identifier, exec) => {
1640
+ const isOffline = !!node.attrs.offline;
1641
+
1642
+ if (isOffline) {
1643
+ offlineNodeProcessor.enqueue(type, node);
1644
+ } else {
1645
+ processNodeWithBuffer(node, identifier, exec);
1646
+ }
1647
+ };
1648
+
1649
+ // recv a message
1650
+ ws.on("CB:message", (node) => {
1651
+ processNode("message", node, "processing message", handleMessage);
1652
+ nodelogger(node);
1653
+ const messageJid = node.attrs.from;
1654
+
1655
+ if (linkedParentMap[messageJid]) {
1656
+ // console.log(`Community JID for ${messageJid}: ${linkedParentMap[messageJid]}`);
1657
+ } else {
1658
+ // console.log(`No Community JID found for ${messageJid}`);
1659
+ }
1660
+ });
1661
+ ws.on("CB:call", async (node) => {
1662
+ processNode("call", node, "handling call", handleCall);
1663
+ nodelogger(node);
1664
+ });
1665
+ ws.on("CB:receipt", (node) => {
1666
+ processNode("receipt", node, "handling receipt", handleReceipt);
1667
+ });
1668
+ ws.on("CB:notification", async (node) => {
1669
+ processNode(
1670
+ "notification",
1671
+ node,
1672
+ "handling notification",
1673
+ handleNotification
1674
+ );
1675
+ // nodelogger(node)
1676
+ });
1677
+ ws.on("CB:ack,class:message", (node) => {
1678
+ handleBadAck(node).catch((error) =>
1679
+ onUnexpectedError(error, "handling bad ack")
1680
+ );
1681
+ // nodelogger(node)
1682
+ });
1683
+ const linkedParentMap = {};
1684
+ ws.on("CB:iq", (node) => {
1685
+ if (node && node.tag === "iq" && node.attrs.type === "result") {
1686
+ const groups = node.content;
1687
+
1688
+ if (Array.isArray(groups)) {
1689
+ for (const group of groups) {
1690
+ const groupId = group.attrs.id + "@g.us";
1691
+
1692
+ if (group && Array.isArray(group.content)) {
1693
+ for (const item of group.content) {
1694
+ if (
1695
+ item.tag === "linked_parent" &&
1696
+ item.attrs &&
1697
+ item.attrs.jid
1698
+ ) {
1699
+ linkedParentMap[groupId] = item.attrs.jid;
1700
+ }
1207
1701
  }
1208
- const protoMsg = proto.WebMessageInfo.fromObject(msg);
1209
- upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1702
+ }
1210
1703
  }
1211
- });
1212
- ev.on('connection.update', ({ isOnline }) => {
1213
- if (typeof isOnline !== 'undefined') {
1214
- sendActiveReceipts = isOnline;
1215
- logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1704
+ }
1705
+ }
1706
+ });
1707
+ // codes in telegram channel @wegschleifen
1708
+ ev.on("call", ([call]) => {
1709
+ // missed call + group call notification message generation
1710
+ if (
1711
+ call.status === "timeout" ||
1712
+ (call.status === "offer" && call.isGroup)
1713
+ ) {
1714
+ const msg = {
1715
+ key: {
1716
+ remoteJid: call.chatId,
1717
+ id: call.id,
1718
+ fromMe: false,
1719
+ },
1720
+ messageTimestamp: Utils_1.unixTimestampSeconds(call.date),
1721
+ };
1722
+
1723
+ if (call.status === "timeout") {
1724
+ if (call.isGroup) {
1725
+ msg.messageStubType = call.isVideo
1726
+ ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1727
+ : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1728
+ } else {
1729
+ msg.messageStubType = call.isVideo
1730
+ ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO
1731
+ : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1216
1732
  }
1217
- });
1218
- return {
1219
- ...sock,
1220
- sendMessageAck,
1221
- sendRetryRequest,
1222
- rejectCall,
1223
- fetchMessageHistory,
1224
- requestPlaceholderResend,
1225
- messageRetryManager
1226
- };
1733
+ } else {
1734
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1735
+ }
1736
+
1737
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1738
+ upsertMessage(protoMsg, call.offline ? "append" : "notify");
1739
+ }
1740
+ });
1741
+
1742
+ ev.on("connection.update", ({ isOnline }) => {
1743
+ if (typeof isOnline !== "undefined") {
1744
+ sendActiveReceipts = isOnline;
1745
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1746
+ }
1747
+ });
1748
+
1749
+ return {
1750
+ ...Neele,
1751
+ sendMessageAck,
1752
+ sendRetryRequest,
1753
+ offerCall,
1754
+ rejectCall,
1755
+ nodelogger,
1756
+ setNodeLoggerListener,
1757
+ fetchMessageHistory,
1758
+ requestPlaceholderResend,
1759
+ };
1760
+ };
1761
+
1762
+ module.exports = {
1763
+ makeMessagesRecvSocket,
1227
1764
  };
1228
- //# sourceMappingURL=messages-recv.js.map