@ryuhan/baileys 1.0.9 → 1.2.9

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