@ryuhan/baileys 1.0.10 → 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 (410) hide show
  1. package/README.md +15 -2
  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 +78 -64
  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 -39
  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 +477 -316
  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 +1092 -515
  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 +1148 -387
  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 -219
  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 +49 -0
  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 -35
  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 +146 -49
  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 +319 -195
  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 +24 -28
  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 -61
  405. package/lib/index.js.map +1 -0
  406. package/package.json +52 -81
  407. package/WAProto/p.html +0 -1
  408. package/lib/Defaults/rimuru-version.json +0 -3
  409. package/lib/Signal/Group/queue-job.js +0 -57
  410. package/lib/Utils/rimuru-event-stream.js +0 -63
@@ -1,85 +1,221 @@
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) => {
19
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
20
- const sock = (0, messages_send_1.makeMessagesSocket)(config);
21
- const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, groupMetadata, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, createParticipantNodes, getUSyncDevices, sendPeerDataOperationMessage, } = sock;
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
7
+ import { WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { makeMutex } from '../Utils/make-mutex.js';
10
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { extractGroupMetadata } from './groups.js';
12
+ import { makeMessagesSocket } from './messages-send.js';
13
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
14
+ export const makeMessagesRecvSocket = (config) => {
15
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
16
+ const sock = makeMessagesSocket(config);
17
+ const { ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager } = sock;
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
- });
36
- const groupParticipantJidCache = new node_cache_1.default({
37
- stdTTL: 10 * 60, // 10 mins
38
- useClones: false
39
- });
40
- const groupMetadataWarmupCache = new node_cache_1.default({
41
- stdTTL: 60, // avoid repeated warmup calls per group
42
- useClones: false
43
- });
19
+ const retryMutex = makeMutex();
20
+ const msgRetryCache = config.msgRetryCounterCache ||
21
+ new NodeCache({
22
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
23
+ useClones: false
24
+ });
25
+ const callOfferCache = config.callOfferCache ||
26
+ new NodeCache({
27
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
28
+ useClones: false
29
+ });
30
+ const placeholderResendCache = config.placeholderResendCache ||
31
+ new NodeCache({
32
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
33
+ useClones: false
34
+ });
35
+ // Debounce identity-change session refreshes per JID to avoid bursts
36
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
44
37
  let sendActiveReceipts = false;
45
- const cacheGroupParticipants = (metadata) => {
46
- for (const participant of metadata.participants || []) {
47
- if (!participant.id || !participant.jid) {
48
- continue;
49
- }
50
- groupParticipantJidCache.set(`${metadata.id}:${participant.id}`, participant.jid);
51
- if (participant.lid) {
52
- groupParticipantJidCache.set(`${metadata.id}:${participant.lid}`, participant.jid);
53
- }
38
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
39
+ if (!authState.creds.me?.id) {
40
+ throw new Boom('Not authenticated');
54
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);
55
53
  };
56
- const warmupGroupParticipants = async (groupJid) => {
57
- if (groupMetadataWarmupCache.get(groupJid)) {
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');
58
60
  return;
59
61
  }
60
- groupMetadataWarmupCache.set(groupJid, true);
61
- try {
62
- const metadata = await groupMetadata(groupJid);
63
- cacheGroupParticipants(metadata);
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);
64
66
  }
65
- catch (error) {
66
- logger.debug({ error, groupJid }, 'failed to warm up group participant cache');
67
+ await delay(2000);
68
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
69
+ logger.debug({ messageKey }, 'message received while resend requested');
70
+ return 'RESOLVED';
67
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);
68
87
  };
69
- const resolveGroupParticipantJid = async (groupJid, participantLid) => {
70
- const cacheKey = `${groupJid}:${participantLid}`;
71
- const cachedParticipant = groupParticipantJidCache.get(cacheKey);
72
- if (cachedParticipant) {
73
- return cachedParticipant;
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;
74
94
  }
95
+ let data;
75
96
  try {
76
- const metadata = await groupMetadata(groupJid);
77
- cacheGroupParticipants(metadata);
78
- return groupParticipantJidCache.get(cacheKey);
97
+ data = JSON.parse(mexNode.content.toString());
79
98
  }
80
99
  catch (error) {
81
- logger.debug({ error, groupJid, participantLid }, 'failed to resolve group participant jid');
82
- return undefined;
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;
83
219
  }
84
220
  };
85
221
  const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
@@ -100,112 +236,113 @@ const makeMessagesRecvSocket = (config) => {
100
236
  if (!!attrs.recipient) {
101
237
  stanza.attrs.recipient = attrs.recipient;
102
238
  }
103
- 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)) {
104
241
  stanza.attrs.type = attrs.type;
105
242
  }
106
- if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
243
+ if (tag === 'message' && getBinaryNodeChild({ tag, attrs, content }, 'unavailable')) {
107
244
  stanza.attrs.from = authState.creds.me.id;
108
245
  }
109
246
  logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, 'sent ack');
110
247
  await sendNode(stanza);
111
248
  };
112
- const offerCall = async (toJid, isVideo = false) => {
113
- const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
114
- const offerContent = [];
115
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '16000' }, content: undefined });
116
- offerContent.push({ tag: 'audio', attrs: { enc: 'opus', rate: '8000' }, content: undefined });
117
- if (isVideo) {
118
- offerContent.push({
119
- tag: 'video',
120
- attrs: {
121
- orientation: '0',
122
- 'screen_width': '1920',
123
- 'screen_height': '1080',
124
- 'device_orientation': '0',
125
- enc: 'vp8',
126
- dec: 'vp8',
127
- }
128
- });
129
- }
130
- offerContent.push({ tag: 'net', attrs: { medium: '3' }, content: undefined });
131
- offerContent.push({ tag: 'capability', attrs: { ver: '1' }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
132
- offerContent.push({ tag: 'encopt', attrs: { keygen: '2' }, content: undefined });
133
- const encKey = (0, crypto_1.randomBytes)(32);
134
- const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
135
- await assertSessions(devices, true);
136
- const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
137
- call: {
138
- callKey: encKey
139
- }
140
- });
141
- offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
142
- if (shouldIncludeDeviceIdentity) {
143
- offerContent.push({
144
- tag: 'device-identity',
145
- attrs: {},
146
- content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
147
- });
148
- }
149
- const stanza = ({
150
- tag: 'call',
151
- attrs: {
152
- to: toJid,
153
- },
154
- content: [{
155
- tag: 'offer',
156
- attrs: {
157
- 'call-id': callId,
158
- 'call-creator': authState.creds.me.id,
159
- },
160
- content: offerContent,
161
- }],
162
- });
163
- await query(stanza);
164
- return {
165
- callId,
166
- toJid,
167
- isVideo,
168
- };
169
- };
170
249
  const rejectCall = async (callId, callFrom) => {
171
- const stanza = ({
250
+ const stanza = {
172
251
  tag: 'call',
173
252
  attrs: {
174
253
  from: authState.creds.me.id,
175
- to: callFrom,
254
+ to: callFrom
176
255
  },
177
- content: [{
256
+ content: [
257
+ {
178
258
  tag: 'reject',
179
259
  attrs: {
180
260
  'call-id': callId,
181
261
  'call-creator': callFrom,
182
- count: '0',
262
+ count: '0'
183
263
  },
184
- content: undefined,
185
- }],
186
- });
264
+ content: undefined
265
+ }
266
+ ]
267
+ };
187
268
  await query(stanza);
188
269
  };
189
270
  const sendRetryRequest = async (node, forceIncludeKeys = false) => {
190
- 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 || '');
191
272
  const { key: msgKey } = fullMessage;
192
273
  const msgId = msgKey.id;
193
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
194
- let retryCount = msgRetryCache.get(key) || 0;
195
- if (retryCount >= maxMsgRetryCount) {
196
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
197
- msgRetryCache.del(key);
198
- return;
274
+ if (messageRetryManager) {
275
+ // Check if we've exceeded max retries using the new system
276
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
277
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
278
+ messageRetryManager.markRetryFailed(msgId);
279
+ return;
280
+ }
281
+ // Increment retry count using new system
282
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
283
+ // Use the new retry count for the rest of the logic
284
+ const key = `${msgId}:${msgKey?.participant}`;
285
+ await msgRetryCache.set(key, retryCount);
286
+ }
287
+ else {
288
+ // Fallback to old system
289
+ const key = `${msgId}:${msgKey?.participant}`;
290
+ let retryCount = (await msgRetryCache.get(key)) || 0;
291
+ if (retryCount >= maxMsgRetryCount) {
292
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
293
+ await msgRetryCache.del(key);
294
+ return;
295
+ }
296
+ retryCount += 1;
297
+ await msgRetryCache.set(key, retryCount);
199
298
  }
200
- retryCount += 1;
201
- msgRetryCache.set(key, retryCount);
299
+ const key = `${msgId}:${msgKey?.participant}`;
300
+ const retryCount = (await msgRetryCache.get(key)) || 1;
202
301
  const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
203
- if (retryCount === 1) {
204
- //request a resend via phone
205
- const msgId = await requestPlaceholderResend(msgKey);
206
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
302
+ const fromJid = node.attrs.from;
303
+ // Check if we should recreate the session
304
+ let shouldRecreateSession = false;
305
+ let recreateReason = '';
306
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
307
+ try {
308
+ // Check if we have a session with this JID
309
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
310
+ const hasSession = await signalRepository.validateSession(fromJid);
311
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
312
+ shouldRecreateSession = result.recreate;
313
+ recreateReason = result.reason;
314
+ if (shouldRecreateSession) {
315
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
316
+ // Delete existing session to force recreation
317
+ await authState.keys.set({ session: { [sessionId]: null } });
318
+ forceIncludeKeys = true;
319
+ }
320
+ }
321
+ catch (error) {
322
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
323
+ }
324
+ }
325
+ if (retryCount <= 2) {
326
+ // Use new retry manager for phone requests if available
327
+ if (messageRetryManager) {
328
+ // Schedule phone request with delay (like whatsmeow)
329
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
330
+ try {
331
+ const requestId = await requestPlaceholderResend(msgKey);
332
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
333
+ }
334
+ catch (error) {
335
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
336
+ }
337
+ });
338
+ }
339
+ else {
340
+ // Fallback to immediate request
341
+ const msgId = await requestPlaceholderResend(msgKey);
342
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
343
+ }
207
344
  }
208
- const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
345
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
209
346
  await authState.keys.transaction(async () => {
210
347
  const receipt = {
211
348
  tag: 'receipt',
@@ -221,13 +358,15 @@ const makeMessagesRecvSocket = (config) => {
221
358
  count: retryCount.toString(),
222
359
  id: node.attrs.id,
223
360
  t: node.attrs.t,
224
- v: '1'
361
+ v: '1',
362
+ // ADD ERROR FIELD
363
+ error: '0'
225
364
  }
226
365
  },
227
366
  {
228
367
  tag: 'registration',
229
368
  attrs: {},
230
- content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
369
+ content: encodeBigEndian(authState.creds.registrationId)
231
370
  }
232
371
  ]
233
372
  };
@@ -237,8 +376,8 @@ const makeMessagesRecvSocket = (config) => {
237
376
  if (node.attrs.participant) {
238
377
  receipt.attrs.participant = node.attrs.participant;
239
378
  }
240
- if (retryCount > 1 || forceIncludeKeys) {
241
- const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
379
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
380
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
242
381
  const [keyId] = Object.keys(preKeys);
243
382
  const key = preKeys[+keyId];
244
383
  const content = receipt.content;
@@ -246,10 +385,10 @@ const makeMessagesRecvSocket = (config) => {
246
385
  tag: 'keys',
247
386
  attrs: {},
248
387
  content: [
249
- { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
388
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
250
389
  { tag: 'identity', attrs: {}, content: identityKey.public },
251
- (0, Utils_1.xmppPreKey)(key, +keyId),
252
- (0, Utils_1.xmppSignedPreKey)(signedPreKey),
390
+ xmppPreKey(key, +keyId),
391
+ xmppSignedPreKey(signedPreKey),
253
392
  { tag: 'device-identity', attrs: {}, content: deviceIdentity }
254
393
  ]
255
394
  });
@@ -257,63 +396,73 @@ const makeMessagesRecvSocket = (config) => {
257
396
  }
258
397
  await sendNode(receipt);
259
398
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
260
- });
399
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
261
400
  };
262
401
  const handleEncryptNotification = async (node) => {
263
402
  const from = node.attrs.from;
264
- if (from === WABinary_1.S_WHATSAPP_NET) {
265
- const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
403
+ if (from === S_WHATSAPP_NET) {
404
+ const countChild = getBinaryNodeChild(node, 'count');
266
405
  const count = +countChild.attrs.value;
267
- const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
406
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
268
407
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
269
408
  if (shouldUploadMorePreKeys) {
270
409
  await uploadPreKeys();
271
410
  }
272
411
  }
273
412
  else {
274
- const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
275
- if (identityNode) {
276
- logger.info({ jid: from }, 'identity changed');
277
- // not handling right now
278
- // signal will override new identity anyway
279
- }
280
- else {
413
+ const result = await handleIdentityChange(node, {
414
+ meId: authState.creds.me?.id,
415
+ meLid: authState.creds.me?.lid,
416
+ validateSession: signalRepository.validateSession,
417
+ assertSessions,
418
+ debounceCache: identityAssertDebounce,
419
+ logger
420
+ });
421
+ if (result.action === 'no_identity_node') {
281
422
  logger.info({ node }, 'unknown encrypt notification');
282
423
  }
283
424
  }
284
425
  };
285
- const handleGroupNotification = (participant, child, msg) => {
286
- var _a, _b, _c, _d;
287
- const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
288
- switch (child === null || child === void 0 ? void 0 : child.tag) {
426
+ const handleGroupNotification = (fullNode, child, msg) => {
427
+ // TODO: Support PN/LID (Here is only LID now)
428
+ const actingParticipantLid = fullNode.attrs.participant;
429
+ const actingParticipantPn = fullNode.attrs.participant_pn;
430
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
431
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
432
+ switch (child?.tag) {
289
433
  case 'create':
290
- const metadata = (0, groups_1.extractGroupMetadata)(child);
291
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
434
+ const metadata = extractGroupMetadata(child);
435
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
292
436
  msg.messageStubParameters = [metadata.subject];
293
- msg.key = { participant: metadata.owner };
294
- ev.emit('chats.upsert', [{
437
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
438
+ ev.emit('chats.upsert', [
439
+ {
295
440
  id: metadata.id,
296
441
  name: metadata.subject,
297
- conversationTimestamp: metadata.creation,
298
- }]);
299
- ev.emit('groups.upsert', [{
442
+ conversationTimestamp: metadata.creation
443
+ }
444
+ ]);
445
+ ev.emit('groups.upsert', [
446
+ {
300
447
  ...metadata,
301
- author: participant
302
- }]);
448
+ author: actingParticipantLid,
449
+ authorPn: actingParticipantPn
450
+ }
451
+ ]);
303
452
  break;
304
453
  case 'ephemeral':
305
454
  case 'not_ephemeral':
306
455
  msg.message = {
307
456
  protocolMessage: {
308
- type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
457
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
309
458
  ephemeralExpiration: +(child.attrs.expiration || 0)
310
459
  }
311
460
  };
312
461
  break;
313
462
  case 'modify':
314
- const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
463
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
315
464
  msg.messageStubParameters = oldNumber || [];
316
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
465
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
317
466
  break;
318
467
  case 'promote':
319
468
  case 'demote':
@@ -321,179 +470,141 @@ const makeMessagesRecvSocket = (config) => {
321
470
  case 'add':
322
471
  case 'leave':
323
472
  const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
324
- msg.messageStubType = Types_1.WAMessageStubType[stubType];
325
- const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
473
+ msg.messageStubType = WAMessageStubType[stubType];
474
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
475
+ // TODO: Store LID MAPPINGS
476
+ return {
477
+ id: attrs.jid,
478
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
479
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
480
+ admin: (attrs.type || null)
481
+ };
482
+ });
326
483
  if (participants.length === 1 &&
327
484
  // if recv. "remove" message and sender removed themselves
328
485
  // mark as left
329
- (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
486
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
487
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
330
488
  child.tag === 'remove') {
331
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
489
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
332
490
  }
333
- msg.messageStubParameters = participants;
491
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
334
492
  break;
335
493
  case 'subject':
336
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
494
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
337
495
  msg.messageStubParameters = [child.attrs.subject];
338
496
  break;
339
497
  case 'description':
340
- const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
341
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
498
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
499
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
342
500
  msg.messageStubParameters = description ? [description] : undefined;
343
501
  break;
344
502
  case 'announcement':
345
503
  case 'not_announcement':
346
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
347
- msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
504
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
505
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
348
506
  break;
349
507
  case 'locked':
350
508
  case 'unlocked':
351
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
352
- msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
509
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
510
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
353
511
  break;
354
512
  case 'invite':
355
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
513
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
356
514
  msg.messageStubParameters = [child.attrs.code];
357
515
  break;
358
516
  case 'member_add_mode':
359
517
  const addMode = child.content;
360
518
  if (addMode) {
361
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
519
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
362
520
  msg.messageStubParameters = [addMode.toString()];
363
521
  }
364
522
  break;
365
523
  case 'membership_approval_mode':
366
- const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
524
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
367
525
  if (approvalMode) {
368
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
526
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
369
527
  msg.messageStubParameters = [approvalMode.attrs.state];
370
528
  }
371
529
  break;
372
530
  case 'created_membership_requests':
373
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
374
- msg.messageStubParameters = [participantJid, '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
+ ];
375
537
  break;
376
538
  case 'revoked_membership_requests':
377
- const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
378
- msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
379
- msg.messageStubParameters = [participantJid, 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
+ ];
380
546
  break;
381
- break;
382
- default:
383
- // console.log("WILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
384
- }
385
- };
386
- const handleNewsletterNotification = (id, node) => {
387
- const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
388
- const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
389
- const serverId = message.attrs.server_id;
390
- const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
391
- const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
392
- if (reactionsList) {
393
- const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
394
- if (reactions.length === 0) {
395
- ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
396
- }
397
- reactions.forEach(item => {
398
- var _a, _b;
399
- 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) } });
400
- });
401
- }
402
- if (viewsList.length) {
403
- viewsList.forEach(item => {
404
- ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
405
- });
406
- }
407
- };
408
- const handleMexNewsletterNotification = (id, node) => {
409
- var _a;
410
- const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
411
- const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
412
- let contentPath;
413
- if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
414
- let action;
415
- if (operation === Types_1.MexOperations.PROMOTE) {
416
- action = 'promote';
417
- contentPath = content.data[Types_1.XWAPaths.PROMOTE];
418
- }
419
- if (operation === Types_1.MexOperations.DEMOTE) {
420
- action = 'demote';
421
- contentPath = content.data[Types_1.XWAPaths.DEMOTE];
422
- }
423
- ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
424
- }
425
- if (operation === Types_1.MexOperations.UPDATE) {
426
- contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
427
- ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
428
547
  }
429
548
  };
430
549
  const processNotification = async (node) => {
431
- var _a, _b;
432
550
  const result = {};
433
- const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
551
+ const [child] = getAllBinaryNodeChildren(node);
434
552
  const nodeType = node.attrs.type;
435
- const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
553
+ const from = jidNormalizedUser(node.attrs.from);
436
554
  switch (nodeType) {
437
- case 'privacy_token':
438
- const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
439
- for (const { attrs, content } of tokenList) {
440
- const jid = attrs.jid;
441
- ev.emit('chats.update', [
442
- {
443
- id: jid,
444
- tcToken: content
445
- }
446
- ]);
447
- logger.debug({ jid }, 'got privacy token update');
448
- }
449
- break;
450
555
  case 'newsletter':
451
- handleNewsletterNotification(node.attrs.from, child);
556
+ await handleNewsletterNotification(node);
452
557
  break;
453
558
  case 'mex':
454
- handleMexNewsletterNotification(node.attrs.from, child);
559
+ await handleMexNewsletterNotification(node);
455
560
  break;
456
561
  case 'w:gp2':
457
- handleGroupNotification(node.attrs.participant, child, result);
562
+ // TODO: HANDLE PARTICIPANT_PN
563
+ handleGroupNotification(node, child, result);
458
564
  break;
459
565
  case 'mediaretry':
460
- const event = (0, Utils_1.decodeMediaRetryNode)(node);
566
+ const event = decodeMediaRetryNode(node);
461
567
  ev.emit('messages.media-update', [event]);
462
568
  break;
463
569
  case 'encrypt':
464
570
  await handleEncryptNotification(node);
465
571
  break;
466
572
  case 'devices':
467
- const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
468
- if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
469
- const deviceJids = devices.map(d => d.attrs.jid);
470
- 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');
471
578
  }
579
+ //TODO: drop a new event, add hashes
472
580
  break;
473
581
  case 'server_sync':
474
- const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
582
+ const update = getBinaryNodeChild(node, 'collection');
475
583
  if (update) {
476
584
  const name = update.attrs.name;
477
585
  await resyncAppState([name], false);
478
586
  }
479
587
  break;
480
588
  case 'picture':
481
- const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
482
- const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
483
- ev.emit('contacts.update', [{
484
- 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 || '',
485
595
  imgUrl: setPicture ? 'changed' : 'removed'
486
- }]);
487
- if ((0, WABinary_1.isJidGroup)(from)) {
596
+ }
597
+ ]);
598
+ if (isJidGroup(from)) {
488
599
  const node = setPicture || delPicture;
489
- result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
600
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
490
601
  if (setPicture) {
491
602
  result.messageStubParameters = [setPicture.attrs.id];
492
603
  }
493
- result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
604
+ result.participant = node?.attrs.author;
494
605
  result.key = {
495
- ...result.key || {},
496
- participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
606
+ ...(result.key || {}),
607
+ participant: setPicture?.attrs.author
497
608
  };
498
609
  }
499
610
  break;
@@ -507,44 +618,48 @@ const makeMessagesRecvSocket = (config) => {
507
618
  ...authState.creds.accountSettings,
508
619
  defaultDisappearingMode: {
509
620
  ephemeralExpiration: newDuration,
510
- ephemeralSettingTimestamp: timestamp,
511
- },
621
+ ephemeralSettingTimestamp: timestamp
622
+ }
512
623
  }
513
624
  });
514
625
  }
515
626
  else if (child.tag === 'blocklist') {
516
- const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
627
+ const blocklists = getBinaryNodeChildren(child, 'item');
517
628
  for (const { attrs } of blocklists) {
518
629
  const blocklist = [attrs.jid];
519
- const type = (attrs.action === 'block') ? 'add' : 'remove';
630
+ const type = attrs.action === 'block' ? 'add' : 'remove';
520
631
  ev.emit('blocklist.update', { blocklist, type });
521
632
  }
522
633
  }
523
634
  break;
524
635
  case 'link_code_companion_reg':
525
- const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
526
- const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
527
- const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
528
- 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'));
529
640
  const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
530
- const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
531
- const random = (0, crypto_1.randomBytes)(32);
532
- const linkCodeSalt = (0, crypto_1.randomBytes)(32);
533
- 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, {
534
645
  salt: linkCodeSalt,
535
646
  info: 'link_code_pairing_key_bundle_encryption_key'
536
647
  });
537
- const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
538
- const encryptIv = (0, crypto_1.randomBytes)(12);
539
- 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));
540
655
  const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
541
- const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
656
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
542
657
  const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
543
- 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');
544
659
  await query({
545
660
  tag: 'iq',
546
661
  attrs: {
547
- to: WABinary_1.S_WHATSAPP_NET,
662
+ to: S_WHATSAPP_NET,
548
663
  type: 'set',
549
664
  id: sock.generateMessageTag(),
550
665
  xmlns: 'md'
@@ -554,7 +669,7 @@ const makeMessagesRecvSocket = (config) => {
554
669
  tag: 'link_code_companion_reg',
555
670
  attrs: {
556
671
  jid: authState.creds.me.id,
557
- stage: 'companion_finish',
672
+ stage: 'companion_finish'
558
673
  },
559
674
  content: [
560
675
  {
@@ -578,53 +693,125 @@ const makeMessagesRecvSocket = (config) => {
578
693
  });
579
694
  authState.creds.registered = true;
580
695
  ev.emit('creds.update', authState.creds);
696
+ break;
697
+ case 'privacy_token':
698
+ await handlePrivacyTokenNotification(node);
699
+ break;
581
700
  }
582
701
  if (Object.keys(result).length) {
583
702
  return result;
584
703
  }
585
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
+ };
586
727
  async function decipherLinkPublicKey(data) {
587
728
  const buffer = toRequiredBuffer(data);
588
729
  const salt = buffer.slice(0, 32);
589
- const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
730
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
590
731
  const iv = buffer.slice(32, 48);
591
732
  const payload = buffer.slice(48, 80);
592
- return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
733
+ return aesDecryptCTR(payload, secretKey, iv);
593
734
  }
594
735
  function toRequiredBuffer(data) {
595
736
  if (data === undefined) {
596
- throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
737
+ throw new Boom('Invalid buffer', { statusCode: 400 });
597
738
  }
598
739
  return data instanceof Buffer ? data : Buffer.from(data);
599
740
  }
600
- const willSendMessageAgain = (id, participant) => {
741
+ const willSendMessageAgain = async (id, participant) => {
601
742
  const key = `${id}:${participant}`;
602
- const retryCount = msgRetryCache.get(key) || 0;
743
+ const retryCount = (await msgRetryCache.get(key)) || 0;
603
744
  return retryCount < maxMsgRetryCount;
604
745
  };
605
- const updateSendMessageAgainCount = (id, participant) => {
746
+ const updateSendMessageAgainCount = async (id, participant) => {
606
747
  const key = `${id}:${participant}`;
607
- const newValue = (msgRetryCache.get(key) || 0) + 1;
608
- msgRetryCache.set(key, newValue);
748
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
749
+ await msgRetryCache.set(key, newValue);
609
750
  };
610
751
  const sendMessagesAgain = async (key, ids, retryNode) => {
611
- var _a;
612
- // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
613
- const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
614
752
  const remoteJid = key.remoteJid;
615
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
+ }
616
782
  // if it's the primary jid sending the request
617
783
  // just re-send the message to everyone
618
784
  // prevents the first message decryption failure
619
- 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
+ }
620
805
  await assertSessions([participant], true);
621
- if ((0, WABinary_1.isJidGroup)(remoteJid)) {
806
+ if (isJidGroup(remoteJid)) {
622
807
  await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
623
808
  }
624
- logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
809
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason }, 'forced new session for retry recp');
625
810
  for (const [i, msg] of msgs.entries()) {
626
- if (msg) {
627
- updateSendMessageAgainCount(ids[i], participant);
811
+ if (!ids[i])
812
+ continue;
813
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
814
+ await updateSendMessageAgainCount(ids[i], participant);
628
815
  const msgRelayOpts = { messageId: ids[i] };
629
816
  if (sendToAll) {
630
817
  msgRelayOpts.useUserDevicesCache = false;
@@ -643,11 +830,10 @@ const makeMessagesRecvSocket = (config) => {
643
830
  }
644
831
  };
645
832
  const handleReceipt = async (node) => {
646
- var _a, _b;
647
833
  const { attrs, content } = node;
648
834
  const isLid = attrs.from.includes('lid');
649
- 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);
650
- 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;
651
837
  const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
652
838
  const key = {
653
839
  remoteJid,
@@ -655,33 +841,31 @@ const makeMessagesRecvSocket = (config) => {
655
841
  fromMe,
656
842
  participant: attrs.participant
657
843
  };
658
- if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
844
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
659
845
  logger.debug({ remoteJid }, 'ignoring receipt from jid');
660
846
  await sendMessageAck(node);
661
847
  return;
662
848
  }
663
849
  const ids = [attrs.id];
664
850
  if (Array.isArray(content)) {
665
- const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
851
+ const items = getBinaryNodeChildren(content[0], 'item');
666
852
  ids.push(...items.map(i => i.attrs.id));
667
853
  }
668
854
  try {
669
855
  await Promise.all([
670
- processingMutex.mutex(async () => {
671
- const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
856
+ receiptMutex.mutex(async () => {
857
+ const status = getStatusFromReceiptType(attrs.type);
672
858
  if (typeof status !== 'undefined' &&
673
- (
674
859
  // basically, we only want to know when a message from us has been delivered to/read by the other person
675
860
  // or another device of ours has read some messages
676
- status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
677
- !isNodeFromMe)) {
678
- 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)) {
679
863
  if (attrs.participant) {
680
- const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
864
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
681
865
  ev.emit('message-receipt.update', ids.map(id => ({
682
866
  key: { ...key, id },
683
867
  receipt: {
684
- userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
868
+ userJid: jidNormalizedUser(attrs.participant),
685
869
  [updateKey]: +attrs.t
686
870
  }
687
871
  })));
@@ -690,22 +874,23 @@ const makeMessagesRecvSocket = (config) => {
690
874
  else {
691
875
  ev.emit('messages.update', ids.map(id => ({
692
876
  key: { ...key, id },
693
- update: { status }
877
+ update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
694
878
  })));
695
879
  }
696
880
  }
697
881
  if (attrs.type === 'retry') {
698
882
  // correctly set who is asking for the retry
699
883
  key.participant = key.participant || attrs.from;
700
- const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
701
- if (willSendMessageAgain(ids[0], key.participant)) {
884
+ const retryNode = getBinaryNodeChild(node, 'retry');
885
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
702
886
  if (key.fromMe) {
703
887
  try {
888
+ await updateSendMessageAgainCount(ids[0], key.participant);
704
889
  logger.debug({ attrs, key }, 'recv retry request');
705
890
  await sendMessagesAgain(key, ids, retryNode);
706
891
  }
707
892
  catch (error) {
708
- 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');
709
894
  }
710
895
  }
711
896
  else {
@@ -725,28 +910,30 @@ const makeMessagesRecvSocket = (config) => {
725
910
  };
726
911
  const handleNotification = async (node) => {
727
912
  const remoteJid = node.attrs.from;
728
- if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
913
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== S_WHATSAPP_NET) {
729
914
  logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
730
915
  await sendMessageAck(node);
731
916
  return;
732
917
  }
733
918
  try {
734
919
  await Promise.all([
735
- processingMutex.mutex(async () => {
736
- var _a;
920
+ notificationMutex.mutex(async () => {
737
921
  const msg = await processNotification(node);
738
922
  if (msg) {
739
- 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);
740
925
  msg.key = {
741
926
  remoteJid,
742
927
  fromMe,
743
928
  participant: node.attrs.participant,
929
+ participantAlt,
930
+ addressingMode,
744
931
  id: node.attrs.id,
745
932
  ...(msg.key || {})
746
933
  };
747
- (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
934
+ msg.participant ?? (msg.participant = node.attrs.participant);
748
935
  msg.messageTimestamp = +node.attrs.t;
749
- const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
936
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
750
937
  await upsertMessage(fullMsg, 'append');
751
938
  }
752
939
  })
@@ -756,96 +943,414 @@ const makeMessagesRecvSocket = (config) => {
756
943
  await sendMessageAck(node);
757
944
  }
758
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
+ };
759
1184
  const handleMessage = async (node) => {
760
- var _a, _b, _c;
761
- if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
1185
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== S_WHATSAPP_NET) {
762
1186
  logger.debug({ key: node.attrs.key }, 'ignored message');
763
- await sendMessageAck(node);
1187
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
764
1188
  return;
765
1189
  }
766
- const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
1190
+ const encNode = getBinaryNodeChild(node, 'enc');
767
1191
  // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
768
- if (encNode && encNode.attrs.type === 'msmsg') {
1192
+ if (encNode?.attrs.type === 'msmsg') {
769
1193
  logger.debug({ key: node.attrs.key }, 'ignored msmsg');
770
- await sendMessageAck(node);
1194
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
771
1195
  return;
772
1196
  }
773
- let response;
774
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
775
- await sendMessageAck(node);
776
- const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
777
- response = await requestPlaceholderResend(key);
778
- if (response === 'RESOLVED') {
779
- 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
+ }
780
1208
  }
781
- logger.debug('received unavailable message, acked and requested resend from phone');
782
- }
783
- else {
784
- if (placeholderResendCache.get(node.attrs.id)) {
785
- placeholderResendCache.del(node.attrs.id);
1209
+ else {
1210
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1211
+ await signalRepository.migrateSession(alt, primaryJid);
786
1212
  }
787
1213
  }
788
- const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
789
- 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) {
790
- msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
791
- }
792
- 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) {
793
- 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');
794
1220
  }
795
1221
  try {
796
- await Promise.all([
797
- processingMutex.mutex(async () => {
798
- var _a, _b, _c, _d, _e, _f;
799
- await decrypt();
800
- // message failed to decrypt
801
- if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
802
- 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) {
803
- 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);
1244
+ }
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
+ }
804
1290
  }
805
- retryMutex.mutex(async () => {
806
- if (ws.isOpen) {
807
- if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
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');
808
1299
  return;
809
1300
  }
810
- 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');
811
1315
  await sendRetryRequest(node, !encNode);
812
1316
  if (retryRequestDelayMs) {
813
- await (0, Utils_1.delay)(retryRequestDelayMs);
1317
+ await delay(retryRequestDelayMs);
814
1318
  }
815
1319
  }
816
- else {
817
- 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
+ }
818
1330
  }
1331
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
819
1332
  });
820
1333
  }
821
- 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) {
822
1341
  // no type in the receipt => message delivered
823
1342
  let type = undefined;
824
- if ((_b = msg.key.participant) === null || _b === void 0 ? void 0 : _b.endsWith('@lid')) {
825
- msg.key.participant = node.attrs.participant_pn || authState.creds.me.id;
826
- }
827
- 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'))) {
828
- if (msg.message.extendedTextMessage.contextInfo) {
829
- const sender = msg.message.extendedTextMessage.contextInfo.participant;
830
- const resolvedSender = await resolveGroupParticipantJid(msg.key.remoteJid, sender);
831
- msg.message.extendedTextMessage.contextInfo.participant = resolvedSender || sender;
832
- }
833
- }
834
- else if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid)) {
835
- void warmupGroupParticipants(msg.key.remoteJid);
836
- }
837
- if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
838
- msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
839
- }
840
1343
  let participant = msg.key.participant;
841
- if (category === 'peer') { // special peer message
1344
+ if (category === 'peer') {
1345
+ // special peer message
842
1346
  type = 'peer_msg';
843
1347
  }
844
- 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
845
1350
  type = 'sender';
846
1351
  // need to specially handle this case
847
- if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
848
- participant = author;
1352
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1353
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
849
1354
  }
850
1355
  }
851
1356
  else if (!sendActiveReceipts) {
@@ -853,126 +1358,170 @@ const makeMessagesRecvSocket = (config) => {
853
1358
  }
854
1359
  await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
855
1360
  // send ack for history message
856
- const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
1361
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
857
1362
  if (isAnyHistoryMsg) {
858
- const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
859
- 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
860
1365
  }
861
1366
  }
862
- (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
863
- await sendMessageAck(node);
864
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
865
- })
866
- ]);
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
+ });
867
1467
  }
868
1468
  catch (error) {
869
- logger.error({ error, node }, 'error in handling message');
1469
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
870
1470
  }
871
1471
  };
872
- const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
873
- var _a;
874
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
875
- throw new boom_1.Boom('Not authenticated');
876
- }
877
- const pdoMessage = {
878
- historySyncOnDemandRequest: {
879
- chatJid: oldestMsgKey.remoteJid,
880
- oldestMsgFromMe: oldestMsgKey.fromMe,
881
- oldestMsgId: oldestMsgKey.id,
882
- oldestMsgTimestampMs: oldestMsgTimestamp,
883
- onDemandMsgCount: count
884
- },
885
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
886
- };
887
- return sendPeerDataOperationMessage(pdoMessage);
888
- };
889
- const requestPlaceholderResend = async (messageKey) => {
890
- var _a;
891
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
892
- throw new boom_1.Boom('Not authenticated');
893
- }
894
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
895
- logger.debug({ messageKey }, 'already requested resend');
896
- return;
897
- }
898
- else {
899
- placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
900
- }
901
- await (0, Utils_1.delay)(5000);
902
- if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
903
- logger.debug({ messageKey }, 'message received while resend requested');
904
- return 'RESOLVED';
905
- }
906
- const pdoMessage = {
907
- placeholderMessageResendRequest: [{
908
- messageKey
909
- }],
910
- peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
911
- };
912
- setTimeout(() => {
913
- if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
914
- logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
915
- placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
916
- }
917
- }, 15000);
918
- return sendPeerDataOperationMessage(pdoMessage);
919
- };
920
1472
  const handleCall = async (node) => {
921
1473
  const { attrs } = node;
922
- 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
+ }
923
1479
  const callId = infoChild.attrs['call-id'];
924
1480
  const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
925
- const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
926
1481
  const call = {
927
1482
  chatId: attrs.from,
928
1483
  from,
1484
+ callerPn: infoChild.attrs['caller_pn'],
929
1485
  id: callId,
930
1486
  date: new Date(+attrs.t * 1000),
931
1487
  offline: !!attrs.offline,
932
- status,
1488
+ status
933
1489
  };
934
1490
  if (status === 'offer') {
935
- call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
1491
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
936
1492
  call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
937
1493
  call.groupJid = infoChild.attrs['group-jid'];
938
- callOfferCache.set(call.id, call);
1494
+ await callOfferCache.set(call.id, call);
939
1495
  }
940
- const existingCall = callOfferCache.get(call.id);
1496
+ const existingCall = await callOfferCache.get(call.id);
941
1497
  // use existing call info to populate this event
942
1498
  if (existingCall) {
943
1499
  call.isVideo = existingCall.isVideo;
944
1500
  call.isGroup = existingCall.isGroup;
1501
+ call.callerPn = call.callerPn || existingCall.callerPn;
945
1502
  }
946
1503
  // delete data once call has ended
947
1504
  if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
948
- callOfferCache.del(call.id);
1505
+ await callOfferCache.del(call.id);
949
1506
  }
950
1507
  ev.emit('call', [call]);
951
1508
  await sendMessageAck(node);
952
1509
  };
953
1510
  const handleBadAck = async ({ attrs }) => {
954
- const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
955
- // current hypothesis is that if pash is sent in the ack
956
- // it means -- the message hasn't reached all devices yet
957
- // we'll retry sending the message here
958
- if (attrs.phash) {
959
- logger.info({ attrs }, 'received phash in ack, resending message...');
960
- const cacheKey = `${key.remoteJid}:${key.id}`;
961
- if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
962
- logger.warn({ attrs }, 'reached max retry count, not sending message again');
963
- msgRetryCache.del(cacheKey);
964
- return;
965
- }
966
- const retryCount = msgRetryCache.get(cacheKey) || 0;
967
- const msg = await getMessage(key);
968
- if (msg) {
969
- await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
970
- msgRetryCache.set(cacheKey, retryCount + 1);
971
- }
972
- else {
973
- logger.warn({ attrs }, 'could not send message again, as it was not found');
974
- }
975
- }
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
+ // }
976
1525
  // error in acknowledgement,
977
1526
  // device could not display the message
978
1527
  if (attrs.error) {
@@ -981,13 +1530,24 @@ const makeMessagesRecvSocket = (config) => {
981
1530
  {
982
1531
  key,
983
1532
  update: {
984
- status: Types_1.WAMessageStatus.ERROR,
985
- messageStubParameters: [
986
- attrs.error
987
- ]
1533
+ status: WAMessageStatus.ERROR,
1534
+ messageStubParameters: [attrs.error]
988
1535
  }
989
1536
  }
990
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
+ // }
991
1551
  }
992
1552
  };
993
1553
  /// processes a node with the given function
@@ -997,10 +1557,13 @@ const makeMessagesRecvSocket = (config) => {
997
1557
  await execTask();
998
1558
  ev.flush();
999
1559
  function execTask() {
1000
- return exec(node, false)
1001
- .catch(err => onUnexpectedError(err, identifier));
1560
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1002
1561
  }
1003
1562
  };
1563
+ /** Yields control to the event loop to prevent blocking */
1564
+ const yieldToEventLoop = () => {
1565
+ return new Promise(resolve => setImmediate(resolve));
1566
+ };
1004
1567
  const makeOfflineNodeProcessor = () => {
1005
1568
  const nodeProcessorMap = new Map([
1006
1569
  ['message', handleMessage],
@@ -1010,6 +1573,8 @@ const makeMessagesRecvSocket = (config) => {
1010
1573
  ]);
1011
1574
  const nodes = [];
1012
1575
  let isProcessing = false;
1576
+ // Number of nodes to process before yielding to event loop
1577
+ const BATCH_SIZE = 10;
1013
1578
  const enqueue = (type, node) => {
1014
1579
  nodes.push({ type, node });
1015
1580
  if (isProcessing) {
@@ -1017,6 +1582,7 @@ const makeMessagesRecvSocket = (config) => {
1017
1582
  }
1018
1583
  isProcessing = true;
1019
1584
  const promise = async () => {
1585
+ let processedInBatch = 0;
1020
1586
  while (nodes.length && ws.isOpen) {
1021
1587
  const { type, node } = nodes.shift();
1022
1588
  const nodeProcessor = nodeProcessorMap.get(type);
@@ -1025,6 +1591,13 @@ const makeMessagesRecvSocket = (config) => {
1025
1591
  continue;
1026
1592
  }
1027
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
+ }
1028
1601
  }
1029
1602
  isProcessing = false;
1030
1603
  };
@@ -1033,33 +1606,35 @@ const makeMessagesRecvSocket = (config) => {
1033
1606
  return { enqueue };
1034
1607
  };
1035
1608
  const offlineNodeProcessor = makeOfflineNodeProcessor();
1036
- const processNode = (type, node, identifier, exec) => {
1609
+ const processNode = async (type, node, identifier, exec) => {
1037
1610
  const isOffline = !!node.attrs.offline;
1038
1611
  if (isOffline) {
1039
1612
  offlineNodeProcessor.enqueue(type, node);
1040
1613
  }
1041
1614
  else {
1042
- processNodeWithBuffer(node, identifier, exec);
1615
+ await processNodeWithBuffer(node, identifier, exec);
1043
1616
  }
1044
1617
  };
1045
1618
  // recv a message
1046
- ws.on('CB:message', (node) => {
1047
- processNode('message', node, 'processing message', handleMessage);
1619
+ ws.on('CB:message', async (node) => {
1620
+ await processNode('message', node, 'processing message', handleMessage);
1048
1621
  });
1049
1622
  ws.on('CB:call', async (node) => {
1050
- processNode('call', node, 'handling call', handleCall);
1623
+ await processNode('call', node, 'handling call', handleCall);
1051
1624
  });
1052
- ws.on('CB:receipt', node => {
1053
- processNode('receipt', node, 'handling receipt', handleReceipt);
1625
+ ws.on('CB:receipt', async (node) => {
1626
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
1054
1627
  });
1055
1628
  ws.on('CB:notification', async (node) => {
1056
- processNode('notification', node, 'handling notification', handleNotification);
1629
+ await processNode('notification', node, 'handling notification', handleNotification);
1057
1630
  });
1058
1631
  ws.on('CB:ack,class:message', (node) => {
1059
- handleBadAck(node)
1060
- .catch(error => onUnexpectedError(error, 'handling bad ack'));
1632
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1061
1633
  });
1062
- ev.on('call', ([call]) => {
1634
+ ev.on('call', async ([call]) => {
1635
+ if (!call) {
1636
+ return;
1637
+ }
1063
1638
  // missed call + group call notification message generation
1064
1639
  if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1065
1640
  const msg = {
@@ -1068,21 +1643,23 @@ const makeMessagesRecvSocket = (config) => {
1068
1643
  id: call.id,
1069
1644
  fromMe: false
1070
1645
  },
1071
- messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
1646
+ messageTimestamp: unixTimestampSeconds(call.date)
1072
1647
  };
1073
1648
  if (call.status === 'timeout') {
1074
1649
  if (call.isGroup) {
1075
- 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;
1076
1653
  }
1077
1654
  else {
1078
- 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;
1079
1656
  }
1080
1657
  }
1081
1658
  else {
1082
1659
  msg.message = { call: { callKey: Buffer.from(call.id) } };
1083
1660
  }
1084
- const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1085
- upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1661
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
1662
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1086
1663
  }
1087
1664
  });
1088
1665
  ev.on('connection.update', ({ isOnline }) => {
@@ -1096,9 +1673,9 @@ const makeMessagesRecvSocket = (config) => {
1096
1673
  sendMessageAck,
1097
1674
  sendRetryRequest,
1098
1675
  rejectCall,
1099
- offerCall,
1100
1676
  fetchMessageHistory,
1101
1677
  requestPlaceholderResend,
1678
+ messageRetryManager
1102
1679
  };
1103
1680
  };
1104
- exports.makeMessagesRecvSocket = makeMessagesRecvSocket;
1681
+ //# sourceMappingURL=messages-recv.js.map