@vinzsocket/baileys 2.8.35 → 3.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (410) hide show
  1. package/WAProto/GenerateStatics.sh +2 -2
  2. package/WAProto/WAProto.proto +1339 -493
  3. package/WAProto/fix-imports.js +75 -19
  4. package/WAProto/index.d.ts +5274 -1945
  5. package/WAProto/index.js +81079 -20694
  6. package/lib/Defaults/index.d.ts +75 -0
  7. package/lib/Defaults/index.d.ts.map +1 -0
  8. package/lib/Defaults/index.js +122 -110
  9. package/lib/Defaults/index.js.map +1 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +11 -18
  13. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.js +27 -35
  17. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  18. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  19. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  20. package/lib/Signal/Group/group_cipher.js +75 -95
  21. package/lib/Signal/Group/group_cipher.js.map +1 -0
  22. package/lib/Signal/Group/index.d.ts +12 -0
  23. package/lib/Signal/Group/index.d.ts.map +1 -0
  24. package/lib/Signal/Group/index.js +12 -79
  25. package/lib/Signal/Group/index.js.map +1 -0
  26. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  27. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  28. package/lib/Signal/Group/keyhelper.js +14 -25
  29. package/lib/Signal/Group/keyhelper.js.map +1 -0
  30. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.js +24 -37
  33. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  34. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.js +62 -61
  37. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.js +64 -68
  41. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.js +41 -47
  45. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.js +36 -50
  49. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.js +76 -96
  53. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  54. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.js +25 -34
  57. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  58. package/lib/Signal/libsignal.d.ts +5 -0
  59. package/lib/Signal/libsignal.d.ts.map +1 -0
  60. package/lib/Signal/libsignal.js +415 -402
  61. package/lib/Signal/libsignal.js.map +1 -0
  62. package/lib/Signal/lid-mapping.d.ts +23 -0
  63. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  64. package/lib/Signal/lid-mapping.js +273 -111
  65. package/lib/Signal/lid-mapping.js.map +1 -0
  66. package/lib/Socket/Client/index.d.ts +3 -0
  67. package/lib/Socket/Client/index.d.ts.map +1 -0
  68. package/lib/Socket/Client/index.js +3 -27
  69. package/lib/Socket/Client/index.js.map +1 -0
  70. package/lib/Socket/Client/types.d.ts +16 -0
  71. package/lib/Socket/Client/types.d.ts.map +1 -0
  72. package/lib/Socket/Client/types.js +10 -17
  73. package/lib/Socket/Client/types.js.map +1 -0
  74. package/lib/Socket/Client/websocket.d.ts +13 -0
  75. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  76. package/lib/Socket/Client/websocket.js +53 -57
  77. package/lib/Socket/Client/websocket.js.map +1 -0
  78. package/lib/Socket/business.d.ts +217 -0
  79. package/lib/Socket/business.d.ts.map +1 -0
  80. package/lib/Socket/business.js +374 -363
  81. package/lib/Socket/business.js.map +1 -0
  82. package/lib/Socket/chats.d.ts +124 -0
  83. package/lib/Socket/chats.d.ts.map +1 -0
  84. package/lib/Socket/chats.js +1162 -1041
  85. package/lib/Socket/chats.js.map +1 -0
  86. package/lib/Socket/communities.d.ts +273 -0
  87. package/lib/Socket/communities.d.ts.map +1 -0
  88. package/lib/Socket/communities.js +418 -469
  89. package/lib/Socket/communities.js.map +1 -0
  90. package/lib/Socket/groups.d.ts +161 -0
  91. package/lib/Socket/groups.d.ts.map +1 -0
  92. package/lib/Socket/groups.js +337 -393
  93. package/lib/Socket/groups.js.map +1 -0
  94. package/lib/Socket/index.d.ts +260 -0
  95. package/lib/Socket/index.d.ts.map +1 -0
  96. package/lib/Socket/index.js +10 -20
  97. package/lib/Socket/index.js.map +1 -0
  98. package/lib/Socket/messages-recv.d.ts +203 -0
  99. package/lib/Socket/messages-recv.d.ts.map +1 -0
  100. package/lib/Socket/messages-recv.js +1738 -1394
  101. package/lib/Socket/messages-recv.js.map +1 -0
  102. package/lib/Socket/messages-send.d.ts +199 -0
  103. package/lib/Socket/messages-send.d.ts.map +1 -0
  104. package/lib/Socket/messages-send.js +1101 -1245
  105. package/lib/Socket/messages-send.js.map +1 -0
  106. package/lib/Socket/mex.d.ts +3 -0
  107. package/lib/Socket/mex.d.ts.map +1 -0
  108. package/lib/Socket/mex.js +38 -51
  109. package/lib/Socket/mex.js.map +1 -0
  110. package/lib/Socket/newsletter.d.ts +170 -0
  111. package/lib/Socket/newsletter.d.ts.map +1 -0
  112. package/lib/Socket/newsletter.js +175 -225
  113. package/lib/Socket/newsletter.js.map +1 -0
  114. package/lib/Socket/socket.d.ts +59 -0
  115. package/lib/Socket/socket.d.ts.map +1 -0
  116. package/lib/Socket/socket.js +930 -914
  117. package/lib/Socket/socket.js.map +1 -0
  118. package/lib/Types/Auth.d.ts +117 -0
  119. package/lib/Types/Auth.d.ts.map +1 -0
  120. package/lib/Types/Auth.js +2 -5
  121. package/lib/Types/Auth.js.map +1 -0
  122. package/lib/Types/Bussines.d.ts +25 -0
  123. package/lib/Types/Bussines.d.ts.map +1 -0
  124. package/lib/Types/Bussines.js +2 -5
  125. package/lib/Types/Bussines.js.map +1 -0
  126. package/lib/Types/Call.d.ts +15 -0
  127. package/lib/Types/Call.d.ts.map +1 -0
  128. package/lib/Types/Call.js +2 -5
  129. package/lib/Types/Call.js.map +1 -0
  130. package/lib/Types/Chat.d.ts +124 -0
  131. package/lib/Types/Chat.d.ts.map +1 -0
  132. package/lib/Types/Chat.js +7 -7
  133. package/lib/Types/Chat.js.map +1 -0
  134. package/lib/Types/Contact.d.ts +26 -0
  135. package/lib/Types/Contact.d.ts.map +1 -0
  136. package/lib/Types/Contact.js +2 -5
  137. package/lib/Types/Contact.js.map +1 -0
  138. package/lib/Types/Events.d.ts +256 -0
  139. package/lib/Types/Events.d.ts.map +1 -0
  140. package/lib/Types/Events.js +2 -3
  141. package/lib/Types/Events.js.map +1 -0
  142. package/lib/Types/GroupMetadata.d.ts +71 -0
  143. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  144. package/lib/Types/GroupMetadata.js +2 -5
  145. package/lib/Types/GroupMetadata.js.map +1 -0
  146. package/lib/Types/Label.d.ts +47 -0
  147. package/lib/Types/Label.d.ts.map +1 -0
  148. package/lib/Types/Label.js +22 -28
  149. package/lib/Types/Label.js.map +1 -0
  150. package/lib/Types/LabelAssociation.d.ts +30 -0
  151. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  152. package/lib/Types/LabelAssociation.js +4 -10
  153. package/lib/Types/LabelAssociation.js.map +1 -0
  154. package/lib/Types/Message.d.ts +320 -0
  155. package/lib/Types/Message.d.ts.map +1 -0
  156. package/lib/Types/Message.js +8 -20
  157. package/lib/Types/Message.js.map +1 -0
  158. package/lib/Types/Mex.d.ts +141 -0
  159. package/lib/Types/Mex.d.ts.map +1 -0
  160. package/lib/Types/Mex.js +37 -0
  161. package/lib/Types/Mex.js.map +1 -0
  162. package/lib/Types/Product.d.ts +79 -0
  163. package/lib/Types/Product.d.ts.map +1 -0
  164. package/lib/Types/Product.js +2 -5
  165. package/lib/Types/Product.js.map +1 -0
  166. package/lib/Types/Signal.d.ts +87 -0
  167. package/lib/Types/Signal.d.ts.map +1 -0
  168. package/lib/Types/Signal.js +2 -3
  169. package/lib/Types/Signal.js.map +1 -0
  170. package/lib/Types/Socket.d.ts +136 -0
  171. package/lib/Types/Socket.d.ts.map +1 -0
  172. package/lib/Types/Socket.js +3 -4
  173. package/lib/Types/Socket.js.map +1 -0
  174. package/lib/Types/State.d.ts +97 -0
  175. package/lib/Types/State.d.ts.map +1 -0
  176. package/lib/Types/State.js +54 -17
  177. package/lib/Types/State.js.map +1 -0
  178. package/lib/Types/USync.d.ts +26 -0
  179. package/lib/Types/USync.d.ts.map +1 -0
  180. package/lib/Types/USync.js +2 -3
  181. package/lib/Types/USync.js.map +1 -0
  182. package/lib/Types/index.d.ts +65 -0
  183. package/lib/Types/index.d.ts.map +1 -0
  184. package/lib/Types/index.js +24 -165
  185. package/lib/Types/index.js.map +1 -0
  186. package/lib/Utils/auth-utils.d.ts +24 -0
  187. package/lib/Utils/auth-utils.d.ts.map +1 -0
  188. package/lib/Utils/auth-utils.js +272 -461
  189. package/lib/Utils/auth-utils.js.map +1 -0
  190. package/lib/Utils/browser-utils.d.ts +4 -0
  191. package/lib/Utils/browser-utils.d.ts.map +1 -0
  192. package/lib/Utils/browser-utils.js +28 -0
  193. package/lib/Utils/browser-utils.js.map +1 -0
  194. package/lib/Utils/business.d.ts +23 -0
  195. package/lib/Utils/business.d.ts.map +1 -0
  196. package/lib/Utils/business.js +207 -223
  197. package/lib/Utils/business.js.map +1 -0
  198. package/lib/Utils/chat-utils.d.ts +100 -0
  199. package/lib/Utils/chat-utils.d.ts.map +1 -0
  200. package/lib/Utils/chat-utils.js +828 -803
  201. package/lib/Utils/chat-utils.js.map +1 -0
  202. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  203. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  204. package/lib/Utils/companion-reg-client-utils.js +35 -0
  205. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  206. package/lib/Utils/crypto.d.ts +37 -0
  207. package/lib/Utils/crypto.d.ts.map +1 -0
  208. package/lib/Utils/crypto.js +87 -144
  209. package/lib/Utils/crypto.js.map +1 -0
  210. package/lib/Utils/decode-wa-message.d.ts +66 -0
  211. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  212. package/lib/Utils/decode-wa-message.js +291 -262
  213. package/lib/Utils/decode-wa-message.js.map +1 -0
  214. package/lib/Utils/event-buffer.d.ts +36 -0
  215. package/lib/Utils/event-buffer.d.ts.map +1 -0
  216. package/lib/Utils/event-buffer.js +598 -560
  217. package/lib/Utils/event-buffer.js.map +1 -0
  218. package/lib/Utils/generics.d.ts +91 -0
  219. package/lib/Utils/generics.d.ts.map +1 -0
  220. package/lib/Utils/generics.js +329 -363
  221. package/lib/Utils/generics.js.map +1 -0
  222. package/lib/Utils/history.d.ts +24 -0
  223. package/lib/Utils/history.d.ts.map +1 -0
  224. package/lib/Utils/history.js +129 -96
  225. package/lib/Utils/history.js.map +1 -0
  226. package/lib/Utils/identity-change-handler.d.ts +44 -0
  227. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  228. package/lib/Utils/identity-change-handler.js +50 -0
  229. package/lib/Utils/identity-change-handler.js.map +1 -0
  230. package/lib/Utils/index.d.ts +22 -0
  231. package/lib/Utils/index.d.ts.map +1 -0
  232. package/lib/Utils/index.js +22 -236
  233. package/lib/Utils/index.js.map +1 -0
  234. package/lib/Utils/link-preview.d.ts +21 -0
  235. package/lib/Utils/link-preview.d.ts.map +1 -0
  236. package/lib/Utils/link-preview.js +69 -86
  237. package/lib/Utils/link-preview.js.map +1 -0
  238. package/lib/Utils/logger.d.ts +12 -0
  239. package/lib/Utils/logger.d.ts.map +1 -0
  240. package/lib/Utils/logger.js +3 -11
  241. package/lib/Utils/logger.js.map +1 -0
  242. package/lib/Utils/lt-hash.d.ts +8 -0
  243. package/lib/Utils/lt-hash.d.ts.map +1 -0
  244. package/lib/Utils/lt-hash.js +2 -52
  245. package/lib/Utils/lt-hash.js.map +1 -0
  246. package/lib/Utils/make-mutex.d.ts +9 -0
  247. package/lib/Utils/make-mutex.d.ts.map +1 -0
  248. package/lib/Utils/make-mutex.js +30 -43
  249. package/lib/Utils/make-mutex.js.map +1 -0
  250. package/lib/Utils/message-retry-manager.d.ts +115 -0
  251. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  252. package/lib/Utils/message-retry-manager.js +259 -162
  253. package/lib/Utils/message-retry-manager.js.map +1 -0
  254. package/lib/Utils/messages-media.d.ts +133 -0
  255. package/lib/Utils/messages-media.d.ts.map +1 -0
  256. package/lib/Utils/messages-media.js +732 -711
  257. package/lib/Utils/messages-media.js.map +1 -0
  258. package/lib/Utils/messages.d.ts +91 -0
  259. package/lib/Utils/messages.d.ts.map +1 -0
  260. package/lib/Utils/messages.js +817 -803
  261. package/lib/Utils/messages.js.map +1 -0
  262. package/lib/Utils/noise-handler.d.ts +20 -0
  263. package/lib/Utils/noise-handler.d.ts.map +1 -0
  264. package/lib/Utils/noise-handler.js +195 -168
  265. package/lib/Utils/noise-handler.js.map +1 -0
  266. package/lib/Utils/offline-node-processor.d.ts +17 -0
  267. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  268. package/lib/Utils/offline-node-processor.js +40 -0
  269. package/lib/Utils/offline-node-processor.js.map +1 -0
  270. package/lib/Utils/pre-key-manager.d.ts +28 -0
  271. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  272. package/lib/Utils/pre-key-manager.js +106 -0
  273. package/lib/Utils/pre-key-manager.js.map +1 -0
  274. package/lib/Utils/process-message.d.ts +60 -0
  275. package/lib/Utils/process-message.d.ts.map +1 -0
  276. package/lib/Utils/process-message.js +601 -424
  277. package/lib/Utils/process-message.js.map +1 -0
  278. package/lib/Utils/reporting-utils.d.ts +11 -0
  279. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  280. package/lib/Utils/reporting-utils.js +258 -0
  281. package/lib/Utils/reporting-utils.js.map +1 -0
  282. package/lib/Utils/signal.d.ts +47 -0
  283. package/lib/Utils/signal.d.ts.map +1 -0
  284. package/lib/Utils/signal.js +180 -206
  285. package/lib/Utils/signal.js.map +1 -0
  286. package/lib/Utils/stanza-ack.d.ts +11 -0
  287. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  288. package/lib/Utils/stanza-ack.js +38 -0
  289. package/lib/Utils/stanza-ack.js.map +1 -0
  290. package/lib/Utils/sync-action-utils.d.ts +19 -0
  291. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  292. package/lib/Utils/sync-action-utils.js +49 -0
  293. package/lib/Utils/sync-action-utils.js.map +1 -0
  294. package/lib/Utils/tc-token-utils.d.ts +37 -0
  295. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  296. package/lib/Utils/tc-token-utils.js +163 -0
  297. package/lib/Utils/tc-token-utils.js.map +1 -0
  298. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  299. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  300. package/lib/Utils/use-multi-file-auth-state.js +98 -101
  301. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  302. package/lib/Utils/validate-connection.d.ts +11 -0
  303. package/lib/Utils/validate-connection.d.ts.map +1 -0
  304. package/lib/Utils/validate-connection.js +191 -188
  305. package/lib/Utils/validate-connection.js.map +1 -0
  306. package/lib/WABinary/constants.d.ts +28 -0
  307. package/lib/WABinary/constants.d.ts.map +1 -0
  308. package/lib/WABinary/constants.js +1295 -36
  309. package/lib/WABinary/constants.js.map +1 -0
  310. package/lib/WABinary/decode.d.ts +7 -0
  311. package/lib/WABinary/decode.d.ts.map +1 -0
  312. package/lib/WABinary/decode.js +254 -232
  313. package/lib/WABinary/decode.js.map +1 -0
  314. package/lib/WABinary/encode.d.ts +3 -0
  315. package/lib/WABinary/encode.d.ts.map +1 -0
  316. package/lib/WABinary/encode.js +208 -210
  317. package/lib/WABinary/encode.js.map +1 -0
  318. package/lib/WABinary/generic-utils.d.ts +15 -0
  319. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  320. package/lib/WABinary/generic-utils.js +97 -106
  321. package/lib/WABinary/generic-utils.js.map +1 -0
  322. package/lib/WABinary/index.d.ts +6 -0
  323. package/lib/WABinary/index.d.ts.map +1 -0
  324. package/lib/WABinary/index.js +6 -60
  325. package/lib/WABinary/index.js.map +1 -0
  326. package/lib/WABinary/jid-utils.d.ts +48 -0
  327. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  328. package/lib/WABinary/jid-utils.js +83 -70
  329. package/lib/WABinary/jid-utils.js.map +1 -0
  330. package/lib/WABinary/types.d.ts +19 -0
  331. package/lib/WABinary/types.d.ts.map +1 -0
  332. package/lib/WABinary/types.js +2 -4
  333. package/lib/WABinary/types.js.map +1 -0
  334. package/lib/WAM/BinaryInfo.d.ts +9 -0
  335. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  336. package/lib/WAM/BinaryInfo.js +9 -16
  337. package/lib/WAM/BinaryInfo.js.map +1 -0
  338. package/lib/WAM/constants.d.ts +40 -0
  339. package/lib/WAM/constants.d.ts.map +1 -0
  340. package/lib/WAM/constants.js +22853 -13001
  341. package/lib/WAM/constants.js.map +1 -0
  342. package/lib/WAM/encode.d.ts +3 -0
  343. package/lib/WAM/encode.d.ts.map +1 -0
  344. package/lib/WAM/encode.js +133 -133
  345. package/lib/WAM/encode.js.map +1 -0
  346. package/lib/WAM/index.d.ts +4 -0
  347. package/lib/WAM/index.d.ts.map +1 -0
  348. package/lib/WAM/index.js +4 -38
  349. package/lib/WAM/index.js.map +1 -0
  350. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  351. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  352. package/lib/WAUSync/Protocols/USyncContactProtocol.js +50 -34
  353. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  354. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  355. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  356. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -61
  357. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  358. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  359. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  360. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -32
  361. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  362. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  363. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  364. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +35 -40
  365. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  366. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  367. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  368. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +23 -29
  369. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  370. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  371. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  372. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +47 -64
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  374. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  375. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  376. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +27 -26
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  378. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  379. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  380. package/lib/WAUSync/Protocols/index.js +6 -60
  381. package/lib/WAUSync/Protocols/index.js.map +1 -0
  382. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  383. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  384. package/lib/WAUSync/USyncQuery.js +94 -97
  385. package/lib/WAUSync/USyncQuery.js.map +1 -0
  386. package/lib/WAUSync/USyncUser.d.ts +17 -0
  387. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  388. package/lib/WAUSync/USyncUser.js +30 -29
  389. package/lib/WAUSync/USyncUser.js.map +1 -0
  390. package/lib/WAUSync/index.d.ts +4 -0
  391. package/lib/WAUSync/index.d.ts.map +1 -0
  392. package/lib/WAUSync/index.js +4 -38
  393. package/lib/WAUSync/index.js.map +1 -0
  394. package/lib/index.d.ts +12 -0
  395. package/lib/index.d.ts.map +1 -0
  396. package/lib/index.js +11 -114
  397. package/lib/index.js.map +1 -0
  398. package/package.json +47 -20
  399. package/README.md +0 -1315
  400. package/lib/Signal/Group/queue-job.js +0 -61
  401. package/lib/Store/index.js +0 -49
  402. package/lib/Store/make-cache-manager-store.js +0 -106
  403. package/lib/Store/make-in-memory-store.js +0 -497
  404. package/lib/Store/make-ordered-dictionary.js +0 -83
  405. package/lib/Store/object-repository.js +0 -32
  406. package/lib/Types/Newsletter.js +0 -37
  407. package/lib/Utils/baileys-event-stream.js +0 -74
  408. package/lib/Utils/extended-messages.js +0 -285
  409. package/lib/Utils/lid-resolver.js +0 -81
  410. package/lib/Utils/mention.js +0 -137
@@ -1,1289 +1,1145 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.makeMessagesSocket = void 0;
7
- var _nodeCache = _interopRequireDefault(require("@cacheable/node-cache"));
8
- var _boom = require("@hapi/boom");
9
- var _index = require("../../WAProto/index.js");
10
- var _index2 = require("../Defaults/index.js");
11
- var _index3 = require("../Types/index.js");
12
- var _index4 = require("../Utils/index.js");
13
- var _extendedMessages = require("../Utils/extended-messages.js");
14
- var _linkPreview = require("../Utils/link-preview.js");
15
- var _makeMutex = require("../Utils/make-mutex.js");
16
- var _index5 = require("../WABinary/index.js");
17
- var _index6 = require("../WAUSync/index.js");
18
- var _newsletter = require("./newsletter.js");
19
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
20
- const makeMessagesSocket = config => {
21
- const {
22
- logger,
23
- linkPreviewImageThumbnailWidth,
24
- generateHighQualityLinkPreview,
25
- options: axiosOptions,
26
- patchMessageBeforeSending,
27
- cachedGroupMetadata,
28
- enableRecentMessageCache,
29
- maxMsgRetryCount
30
- } = config;
31
- const sock = (0, _newsletter.makeNewsletterSocket)(config);
32
- const {
33
- ev,
34
- authState,
35
- processingMutex,
36
- signalRepository,
37
- upsertMessage,
38
- query,
39
- fetchPrivacySettings,
40
- sendNode,
41
- groupMetadata,
42
- groupToggleEphemeral
43
- } = sock;
44
- const userDevicesCache = config.userDevicesCache || new _nodeCache.default({
45
- stdTTL: _index2.DEFAULT_CACHE_TTLS.USER_DEVICES,
46
- // 5 minutes
47
- useClones: false
48
- });
49
- // Initialize message retry manager if enabled
50
- const messageRetryManager = enableRecentMessageCache ? new _index4.MessageRetryManager(logger, maxMsgRetryCount) : null;
51
- // Prevent race conditions in Signal session encryption by user
52
- const encryptionMutex = (0, _makeMutex.makeKeyedMutex)();
53
- let mediaConn;
54
- const refreshMediaConn = async (forceGet = false) => {
55
- const media = await mediaConn;
56
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
57
- mediaConn = (async () => {
58
- const result = await query({
59
- tag: 'iq',
60
- attrs: {
61
- type: 'set',
62
- xmlns: 'w:m',
63
- to: _index5.S_WHATSAPP_NET
64
- },
65
- content: [{
66
- tag: 'media_conn',
67
- attrs: {}
68
- }]
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeNewsletterSocket } from './newsletter.js';
13
+ export const makeMessagesSocket = (config) => {
14
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
15
+ const sock = makeNewsletterSocket(config);
16
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ /**
19
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
+ */
23
+ const inFlightTcTokenIssuance = new Set();
24
+ const userDevicesCache = config.userDevicesCache ||
25
+ new NodeCache({
26
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
27
+ useClones: false
69
28
  });
70
- const mediaConnNode = (0, _index5.getBinaryNodeChild)(result, 'media_conn');
29
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
+ const devicesMutex = makeMutex();
31
+ // Initialize message retry manager if enabled
32
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
+ // Prevent race conditions in Signal session encryption by user
34
+ const encryptionMutex = makeKeyedMutex();
35
+ let mediaConn;
36
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
+ let mediaHost = DEF_MEDIA_HOST;
38
+ const refreshMediaConn = async (forceGet = false) => {
39
+ const media = await mediaConn;
40
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
41
+ mediaConn = (async () => {
42
+ const result = await query({
43
+ tag: 'iq',
44
+ attrs: {
45
+ type: 'set',
46
+ xmlns: 'w:m',
47
+ to: S_WHATSAPP_NET
48
+ },
49
+ content: [{ tag: 'media_conn', attrs: {} }]
50
+ });
51
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
52
+ // TODO: explore full length of data that whatsapp provides
53
+ const node = {
54
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
+ hostname: attrs.hostname,
56
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
57
+ })),
58
+ auth: mediaConnNode.attrs.auth,
59
+ ttl: +mediaConnNode.attrs.ttl,
60
+ fetchDate: new Date()
61
+ };
62
+ logger.debug('fetched media conn');
63
+ if (node.hosts[0]) {
64
+ mediaHost = node.hosts[0].hostname;
65
+ }
66
+ return node;
67
+ })();
68
+ }
69
+ return mediaConn;
70
+ };
71
+ /**
72
+ * generic send receipt function
73
+ * used for receipts of phone call, read, delivery etc.
74
+ * */
75
+ const sendReceipt = async (jid, participant, messageIds, type) => {
76
+ if (!messageIds || messageIds.length === 0) {
77
+ throw new Boom('missing ids in receipt');
78
+ }
71
79
  const node = {
72
- hosts: (0, _index5.getBinaryNodeChildren)(mediaConnNode, 'host').map(({
73
- attrs
74
- }) => ({
75
- hostname: attrs.hostname,
76
- maxContentLengthBytes: +attrs.maxContentLengthBytes
77
- })),
78
- auth: mediaConnNode.attrs.auth,
79
- ttl: +mediaConnNode.attrs.ttl,
80
- fetchDate: new Date()
80
+ tag: 'receipt',
81
+ attrs: {
82
+ id: messageIds[0]
83
+ }
81
84
  };
82
- logger.debug('fetched media conn');
83
- return node;
84
- })();
85
- }
86
- return mediaConn;
87
- };
88
- /**
89
- * generic send receipt function
90
- * used for receipts of phone call, read, delivery etc.
91
- * */
92
- const sendReceipt = async (jid, participant, messageIds, type) => {
93
- if (!messageIds || messageIds.length === 0) {
94
- throw new _boom.Boom('missing ids in receipt');
95
- }
96
- const node = {
97
- tag: 'receipt',
98
- attrs: {
99
- id: messageIds[0]
100
- }
101
- };
102
- const isReadReceipt = type === 'read' || type === 'read-self';
103
- if (isReadReceipt) {
104
- node.attrs.t = (0, _index4.unixTimestampSeconds)().toString();
105
- }
106
- if (type === 'sender' && (0, _index5.isPnUser)(jid)) {
107
- node.attrs.recipient = jid;
108
- node.attrs.to = participant;
109
- } else {
110
- node.attrs.to = jid;
111
- if (participant) {
112
- node.attrs.participant = participant;
113
- }
114
- }
115
- if (type) {
116
- node.attrs.type = type;
117
- }
118
- const remainingMessageIds = messageIds.slice(1);
119
- if (remainingMessageIds.length) {
120
- node.content = [{
121
- tag: 'list',
122
- attrs: {},
123
- content: remainingMessageIds.map(id => ({
124
- tag: 'item',
125
- attrs: {
126
- id
127
- }
128
- }))
129
- }];
130
- }
131
- logger.debug({
132
- attrs: node.attrs,
133
- messageIds
134
- }, 'sending receipt for messages');
135
- await sendNode(node);
136
- };
137
- /** Correctly bulk send receipts to multiple chats, participants */
138
- const sendReceipts = async (keys, type) => {
139
- const recps = (0, _index4.aggregateMessageKeysNotFromMe)(keys);
140
- for (const {
141
- jid,
142
- participant,
143
- messageIds
144
- } of recps) {
145
- await sendReceipt(jid, participant, messageIds, type);
146
- }
147
- };
148
- /** Bulk read messages. Keys can be from different chats & participants */
149
- const readMessages = async keys => {
150
- const privacySettings = await fetchPrivacySettings();
151
- // based on privacy settings, we have to change the read type
152
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
153
- await sendReceipts(keys, readType);
154
- };
155
- /**
156
- * Deduplicate JIDs when both LID and PN versions exist for same user
157
- * Prefers LID over PN to maintain single encryption layer
158
- */
159
- const deduplicateLidPnJids = jids => {
160
- const lidUsers = new Set();
161
- const filteredJids = [];
162
- // Collect all LID users
163
- for (const jid of jids) {
164
- if (jid.includes('@lid')) {
165
- const user = (0, _index5.jidDecode)(jid)?.user;
166
- if (user) lidUsers.add(user);
167
- }
168
- }
169
- // Filter out PN versions when LID exists
170
- for (const jid of jids) {
171
- if (jid.includes('@s.whatsapp.net')) {
172
- const user = (0, _index5.jidDecode)(jid)?.user;
173
- if (user && lidUsers.has(user)) {
174
- logger.debug({
175
- jid
176
- }, 'Skipping PN - LID version exists');
177
- continue;
85
+ const isReadReceipt = type === 'read' || type === 'read-self';
86
+ if (isReadReceipt) {
87
+ node.attrs.t = unixTimestampSeconds().toString();
178
88
  }
179
- }
180
- filteredJids.push(jid);
181
- }
182
- return filteredJids;
183
- };
184
- /** Fetch all the devices we've to send a message to */
185
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
186
- const deviceResults = [];
187
- if (!useCache) {
188
- logger.debug('not using cache for devices');
189
- }
190
- const toFetch = [];
191
- // Deduplicate and normalize JIDs
192
- jids = deduplicateLidPnJids(Array.from(new Set(jids)));
193
- for (let jid of jids) {
194
- const decoded = (0, _index5.jidDecode)(jid);
195
- const user = decoded?.user;
196
- const device = decoded?.device;
197
- const isExplicitDevice = typeof device === 'number' && device >= 0;
198
- // Handle explicit device JIDs directly
199
- if (isExplicitDevice && user) {
200
- deviceResults.push({
201
- user,
202
- device,
203
- wireJid: jid // Preserve exact JID format for wire protocol
204
- });
205
- continue;
206
- }
207
- // For user JIDs, normalize and prepare for device enumeration
208
- jid = (0, _index5.jidNormalizedUser)(jid);
209
- if (useCache) {
210
- const devices = userDevicesCache.get(user);
211
- if (devices) {
212
- const isLidJid = jid.includes('@lid');
213
- const devicesWithWire = devices.map(d => ({
214
- ...d,
215
- wireJid: isLidJid ? (0, _index5.jidEncode)(d.user, 'lid', d.device) : (0, _index5.jidEncode)(d.user, 's.whatsapp.net', d.device)
216
- }));
217
- deviceResults.push(...devicesWithWire);
218
- logger.trace({
219
- user
220
- }, 'using cache for devices');
221
- } else {
222
- toFetch.push(jid);
89
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
90
+ node.attrs.recipient = jid;
91
+ node.attrs.to = participant;
223
92
  }
224
- } else {
225
- toFetch.push(jid);
226
- }
227
- }
228
- if (!toFetch.length) {
229
- return deviceResults;
230
- }
231
- const requestedLidUsers = new Set();
232
- for (const jid of toFetch) {
233
- if (jid.includes('@lid')) {
234
- const user = (0, _index5.jidDecode)(jid)?.user;
235
- if (user) requestedLidUsers.add(user);
236
- }
237
- }
238
- const query = new _index6.USyncQuery().withContext('message').withDeviceProtocol();
239
- for (const jid of toFetch) {
240
- query.withUser(new _index6.USyncUser().withId(jid));
241
- }
242
- const result = await sock.executeUSyncQuery(query);
243
- if (result) {
244
- const extracted = (0, _index4.extractDeviceJids)(result?.list, authState.creds.me.id, ignoreZeroDevices);
245
- const deviceMap = {};
246
- for (const item of extracted) {
247
- deviceMap[item.user] = deviceMap[item.user] || [];
248
- deviceMap[item.user]?.push(item);
249
- }
250
- // Process each user's devices as a group for bulk LID migration
251
- for (const [user, userDevices] of Object.entries(deviceMap)) {
252
- const isLidUser = requestedLidUsers.has(user);
253
- // Process all devices for this user
254
- for (const item of userDevices) {
255
- const finalWireJid = isLidUser ? (0, _index5.jidEncode)(user, 'lid', item.device) : (0, _index5.jidEncode)(item.user, 's.whatsapp.net', item.device);
256
- deviceResults.push({
257
- ...item,
258
- wireJid: finalWireJid
259
- });
260
- logger.debug({
261
- user: item.user,
262
- device: item.device,
263
- finalWireJid,
264
- usedLid: isLidUser
265
- }, 'Processed device with LID priority');
93
+ else {
94
+ node.attrs.to = jid;
95
+ if (participant) {
96
+ node.attrs.participant = participant;
97
+ }
266
98
  }
267
- }
268
- for (const key in deviceMap) {
269
- userDevicesCache.set(key, deviceMap[key]);
270
- }
271
- }
272
- return deviceResults;
273
- };
274
- // Helper to check if JID has migrated LID session
275
- const checkForMigratedLidSession = async jid => {
276
- if (!jid.includes('@s.whatsapp.net')) return false;
277
- const lidMapping = signalRepository.getLIDMappingStore();
278
- const lidForPN = await lidMapping.getLIDForPN(jid);
279
- if (!lidForPN?.includes('@lid')) return false;
280
- const lidSignalId = signalRepository.jidToSignalProtocolAddress(lidForPN);
281
- const lidSessions = await authState.keys.get('session', [lidSignalId]);
282
- return !!lidSessions[lidSignalId];
283
- };
284
- const assertSessions = async (jids, force) => {
285
- let didFetchNewSession = false;
286
- const jidsRequiringFetch = [];
287
- // Apply same deduplication as in getUSyncDevices
288
- jids = deduplicateLidPnJids(jids);
289
- if (force) {
290
- // Check which sessions are missing (with LID migration check)
291
- const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid));
292
- const sessions = await authState.keys.get('session', addrs);
293
- // Helper to check session for a JID
294
- const checkJidSession = async jid => {
295
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
296
- let hasSession = !!sessions[signalId];
297
- // Check for migrated LID session if PN session missing
298
- if (!hasSession) {
299
- hasSession = await checkForMigratedLidSession(jid);
300
- if (hasSession) {
301
- logger.debug({
302
- jid
303
- }, 'Found migrated LID session during force assert, skipping PN fetch');
304
- }
99
+ if (type) {
100
+ node.attrs.type = type;
305
101
  }
306
- // Add to fetch list if no session exists
307
- if (!hasSession) {
308
- if (jid.includes('@lid')) {
309
- logger.debug({
310
- jid
311
- }, 'No LID session found, will create new LID session');
312
- }
313
- jidsRequiringFetch.push(jid);
102
+ const remainingMessageIds = messageIds.slice(1);
103
+ if (remainingMessageIds.length) {
104
+ node.content = [
105
+ {
106
+ tag: 'list',
107
+ attrs: {},
108
+ content: remainingMessageIds.map(id => ({
109
+ tag: 'item',
110
+ attrs: { id }
111
+ }))
112
+ }
113
+ ];
314
114
  }
315
- };
316
- // Process all JIDs
317
- for (const jid of jids) {
318
- await checkJidSession(jid);
319
- }
320
- } else {
321
- const lidMapping = signalRepository.getLIDMappingStore();
322
- const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid));
323
- const sessions = await authState.keys.get('session', addrs);
324
- // Group JIDs by user for bulk migration
325
- const userGroups = new Map();
326
- for (const jid of jids) {
327
- const user = (0, _index5.jidNormalizedUser)(jid);
328
- if (!userGroups.has(user)) {
329
- userGroups.set(user, []);
115
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
116
+ await sendNode(node);
117
+ };
118
+ /** Correctly bulk send receipts to multiple chats, participants */
119
+ const sendReceipts = async (keys, type) => {
120
+ const recps = aggregateMessageKeysNotFromMe(keys);
121
+ for (const { jid, participant, messageIds } of recps) {
122
+ await sendReceipt(jid, participant, messageIds, type);
330
123
  }
331
- userGroups.get(user).push(jid);
332
- }
333
- // Helper to check LID mapping for a user
334
- const checkUserLidMapping = async (user, userJids) => {
335
- if (!userJids.some(jid => jid.includes('@s.whatsapp.net'))) {
336
- return {
337
- shouldMigrate: false,
338
- lidForPN: undefined
339
- };
124
+ };
125
+ /** Bulk read messages. Keys can be from different chats & participants */
126
+ const readMessages = async (keys) => {
127
+ const privacySettings = await fetchPrivacySettings();
128
+ // based on privacy settings, we have to change the read type
129
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
130
+ await sendReceipts(keys, readType);
131
+ };
132
+ /** Fetch all the devices we've to send a message to */
133
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
134
+ const deviceResults = [];
135
+ if (!useCache) {
136
+ logger.debug('not using cache for devices');
340
137
  }
341
- try {
342
- const mapping = await lidMapping.getLIDForPN(user);
343
- if (mapping?.includes('@lid')) {
344
- logger.debug({
345
- user,
346
- lidForPN: mapping,
347
- deviceCount: userJids.length
348
- }, 'User has LID mapping - preparing bulk migration');
349
- return {
350
- shouldMigrate: true,
351
- lidForPN: mapping
352
- };
353
- }
354
- } catch (error) {
355
- logger.debug({
356
- user,
357
- error
358
- }, 'Failed to check LID mapping for user');
138
+ const toFetch = [];
139
+ const jidsWithUser = jids
140
+ .map(jid => {
141
+ const decoded = jidDecode(jid);
142
+ const user = decoded?.user;
143
+ const device = decoded?.device;
144
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
145
+ if (isExplicitDevice && user) {
146
+ deviceResults.push({
147
+ user,
148
+ device,
149
+ jid
150
+ });
151
+ return null;
152
+ }
153
+ jid = jidNormalizedUser(jid);
154
+ return { jid, user };
155
+ })
156
+ .filter(jid => jid !== null);
157
+ let mgetDevices;
158
+ if (useCache && userDevicesCache.mget) {
159
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
160
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
359
161
  }
360
- return {
361
- shouldMigrate: false,
362
- lidForPN: undefined
363
- };
364
- };
365
- // Helper to migrate a single device
366
- const migrateDeviceToLid = async (jid, lidForPN) => {
367
- if (!jid.includes('@s.whatsapp.net')) return;
368
- try {
369
- const lidWithDevice = (0, _index5.transferDevice)(jid, lidForPN);
370
- await signalRepository.migrateSession(jid, lidWithDevice);
371
- logger.debug({
372
- fromJid: jid,
373
- toJid: lidWithDevice
374
- }, 'Migrated device session to LID');
375
- // Delete PN session after successful migration
376
- try {
377
- await signalRepository.deleteSession(jid);
378
- logger.debug({
379
- deletedPNSession: jid
380
- }, 'Deleted PN session after migration');
381
- } catch (deleteError) {
382
- logger.warn({
383
- jid,
384
- error: deleteError
385
- }, 'Failed to delete PN session');
386
- }
387
- } catch (migrationError) {
388
- logger.warn({
389
- jid,
390
- error: migrationError
391
- }, 'Failed to migrate device session');
162
+ for (const { jid, user } of jidsWithUser) {
163
+ if (useCache) {
164
+ const devices = mgetDevices?.[user] ||
165
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
166
+ if (devices) {
167
+ const devicesWithJid = devices.map(d => ({
168
+ ...d,
169
+ jid: jidEncode(d.user, d.server, d.device)
170
+ }));
171
+ deviceResults.push(...devicesWithJid);
172
+ logger.trace({ user }, 'using cache for devices');
173
+ }
174
+ else {
175
+ toFetch.push(jid);
176
+ }
177
+ }
178
+ else {
179
+ toFetch.push(jid);
180
+ }
392
181
  }
393
- };
394
- // Process each user group for potential bulk LID migration
395
- for (const [user, userJids] of userGroups) {
396
- const mappingResult = await checkUserLidMapping(user, userJids);
397
- const shouldMigrateUser = mappingResult.shouldMigrate;
398
- const lidForPN = mappingResult.lidForPN;
399
- // Migrate all devices for this user if LID mapping exists
400
- if (shouldMigrateUser && lidForPN) {
401
- // Migrate each device individually
402
- for (const jid of userJids) {
403
- await migrateDeviceToLid(jid, lidForPN);
404
- }
405
- logger.info({
406
- user,
407
- lidMapping: lidForPN,
408
- deviceCount: userJids.length
409
- }, 'Completed migration attempt for user devices');
182
+ if (!toFetch.length) {
183
+ return deviceResults;
410
184
  }
411
- // Helper to check session for migrated user
412
- const checkMigratedSession = async jid => {
413
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
414
- let hasSession = !!sessions[signalId];
415
- let jidToFetch = jid;
416
- // Check if we should use migrated LID session instead
417
- if (shouldMigrateUser && lidForPN && jid.includes('@s.whatsapp.net')) {
418
- const originalDecoded = (0, _index5.jidDecode)(jid);
419
- const deviceId = originalDecoded?.device || 0;
420
- const lidDecoded = (0, _index5.jidDecode)(lidForPN);
421
- const lidWithDevice = (0, _index5.jidEncode)(lidDecoded?.user, 'lid', deviceId);
422
- // Check if LID session exists
423
- const lidSignalId = signalRepository.jidToSignalProtocolAddress(lidWithDevice);
424
- const lidSessions = await authState.keys.get('session', [lidSignalId]);
425
- hasSession = !!lidSessions[lidSignalId];
426
- jidToFetch = lidWithDevice;
427
- if (hasSession) {
428
- logger.debug({
429
- originalJid: jid,
430
- lidJid: lidWithDevice
431
- }, '✅ Found bulk-migrated LID session');
185
+ const requestedLidUsers = new Set();
186
+ for (const jid of toFetch) {
187
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
188
+ const user = jidDecode(jid)?.user;
189
+ if (user)
190
+ requestedLidUsers.add(user);
432
191
  }
433
- }
434
- // Add to fetch list if no session exists
435
- if (!hasSession) {
436
- jidsRequiringFetch.push(jidToFetch);
437
- logger.debug({
438
- jid: jidToFetch,
439
- originalJid: jid !== jidToFetch ? jid : undefined
440
- }, 'Adding to session fetch list');
441
- }
442
- };
443
- // Now check which sessions need to be fetched for this user
444
- for (const jid of userJids) {
445
- await checkMigratedSession(jid);
446
192
  }
447
- }
448
- }
449
- if (jidsRequiringFetch.length) {
450
- logger.debug({
451
- jidsRequiringFetch
452
- }, 'fetching sessions');
453
- // DEBUG: Check if there are PN versions of LID users being fetched
454
- const lidUsersBeingFetched = new Set();
455
- const pnUsersBeingFetched = new Set();
456
- for (const jid of jidsRequiringFetch) {
457
- const user = (0, _index5.jidDecode)(jid)?.user;
458
- if (user) {
459
- if (jid.includes('@lid')) {
460
- lidUsersBeingFetched.add(user);
461
- } else if (jid.includes('@s.whatsapp.net')) {
462
- pnUsersBeingFetched.add(user);
463
- }
193
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
194
+ for (const jid of toFetch) {
195
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
464
196
  }
465
- }
466
- // Find overlaps
467
- const overlapping = Array.from(pnUsersBeingFetched).filter(user => lidUsersBeingFetched.has(user));
468
- if (overlapping.length > 0) {
469
- logger.warn({
470
- overlapping,
471
- lidUsersBeingFetched: Array.from(lidUsersBeingFetched),
472
- pnUsersBeingFetched: Array.from(pnUsersBeingFetched)
473
- }, 'Fetching both LID and PN sessions for same users');
474
- }
475
- const result = await query({
476
- tag: 'iq',
477
- attrs: {
478
- xmlns: 'encrypt',
479
- type: 'get',
480
- to: _index5.S_WHATSAPP_NET
481
- },
482
- content: [{
483
- tag: 'key',
484
- attrs: {},
485
- content: jidsRequiringFetch.map(jid => ({
486
- tag: 'user',
487
- attrs: {
488
- jid
197
+ const result = await sock.executeUSyncQuery(query);
198
+ if (result) {
199
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
200
+ const lidResults = result.list.filter(a => !!a.lid);
201
+ if (lidResults.length > 0) {
202
+ logger.trace('Storing LID maps from device call');
203
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
204
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
205
+ try {
206
+ const lids = lidResults.map(a => a.lid);
207
+ if (lids.length) {
208
+ await assertSessions(lids, true);
209
+ }
210
+ }
211
+ catch (e) {
212
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
213
+ }
214
+ }
215
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
216
+ const deviceMap = {};
217
+ for (const item of extracted) {
218
+ deviceMap[item.user] = deviceMap[item.user] || [];
219
+ deviceMap[item.user]?.push(item);
220
+ }
221
+ // Process each user's devices as a group for bulk LID migration
222
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
223
+ const isLidUser = requestedLidUsers.has(user);
224
+ // Process all devices for this user
225
+ for (const item of userDevices) {
226
+ const finalJid = isLidUser
227
+ ? jidEncode(user, item.server, item.device)
228
+ : jidEncode(item.user, item.server, item.device);
229
+ deviceResults.push({
230
+ ...item,
231
+ jid: finalJid
232
+ });
233
+ logger.debug({
234
+ user: item.user,
235
+ device: item.device,
236
+ finalJid,
237
+ usedLid: isLidUser
238
+ }, 'Processed device with LID priority');
239
+ }
489
240
  }
490
- }))
491
- }]
492
- });
493
- await (0, _index4.parseAndInjectE2ESessions)(result, signalRepository);
494
- didFetchNewSession = true;
495
- }
496
- return didFetchNewSession;
497
- };
498
- const sendPeerDataOperationMessage = async pdoMessage => {
499
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
500
- if (!authState.creds.me?.id) {
501
- throw new _boom.Boom('Not authenticated');
502
- }
503
- const protocolMessage = {
504
- protocolMessage: {
505
- peerDataOperationRequestMessage: pdoMessage,
506
- type: _index.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
507
- }
241
+ await devicesMutex.mutex(async () => {
242
+ if (userDevicesCache.mset) {
243
+ // if the cache supports mset, we can set all devices in one go
244
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
245
+ }
246
+ else {
247
+ for (const key in deviceMap) {
248
+ if (deviceMap[key])
249
+ await userDevicesCache.set(key, deviceMap[key]);
250
+ }
251
+ }
252
+ });
253
+ const userDeviceUpdates = {};
254
+ for (const [userId, devices] of Object.entries(deviceMap)) {
255
+ if (devices && devices.length > 0) {
256
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
257
+ }
258
+ }
259
+ if (Object.keys(userDeviceUpdates).length > 0) {
260
+ try {
261
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
262
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
263
+ }
264
+ catch (error) {
265
+ logger.warn({ error }, 'failed to store user device lists');
266
+ }
267
+ }
268
+ }
269
+ return deviceResults;
508
270
  };
509
- const meJid = (0, _index5.jidNormalizedUser)(authState.creds.me.id);
510
- const msgId = await relayMessage(meJid, protocolMessage, {
511
- additionalAttributes: {
512
- category: 'peer',
513
- push_priority: 'high_force'
514
- }
515
- });
516
- return msgId;
517
- };
518
- const createParticipantNodes = async (jids, message, extraAttrs, dsmMessage) => {
519
- let patched = await patchMessageBeforeSending(message, jids);
520
- if (!Array.isArray(patched)) {
521
- patched = jids ? jids.map(jid => ({
522
- recipientJid: jid,
523
- ...patched
524
- })) : [patched];
525
- }
526
- let shouldIncludeDeviceIdentity = false;
527
- const meId = authState.creds.me.id;
528
- const meLid = authState.creds.me?.lid;
529
- const meLidUser = meLid ? (0, _index5.jidDecode)(meLid)?.user : null;
530
- const devicesByUser = new Map();
531
- for (const patchedMessageWithJid of patched) {
532
- const {
533
- recipientJid: wireJid,
534
- ...patchedMessage
535
- } = patchedMessageWithJid;
536
- if (!wireJid) continue;
537
- // Extract user from JID for grouping
538
- const decoded = (0, _index5.jidDecode)(wireJid);
539
- const user = decoded?.user;
540
- if (!user) continue;
541
- if (!devicesByUser.has(user)) {
542
- devicesByUser.set(user, []);
543
- }
544
- devicesByUser.get(user).push({
545
- recipientJid: wireJid,
546
- patchedMessage
547
- });
548
- }
549
- // Process each user's devices sequentially, but different users in parallel
550
- const userEncryptionPromises = Array.from(devicesByUser.entries()).map(([user, userDevices]) => encryptionMutex.mutex(user, async () => {
551
- logger.debug({
552
- user,
553
- deviceCount: userDevices.length
554
- }, 'Acquiring encryption lock for user devices');
555
- const userNodes = [];
556
- // Helper to get encryption JID with LID migration
557
- const getEncryptionJid = async wireJid => {
558
- if (!wireJid.includes('@s.whatsapp.net')) return wireJid;
559
- try {
560
- const lidMapping = signalRepository.getLIDMappingStore();
561
- const lidForPN = await lidMapping.getLIDForPN(wireJid);
562
- if (!lidForPN?.includes('@lid')) return wireJid;
563
- // Preserve device ID from original wire JID
564
- const wireDecoded = (0, _index5.jidDecode)(wireJid);
565
- const deviceId = wireDecoded?.device || 0;
566
- const lidDecoded = (0, _index5.jidDecode)(lidForPN);
567
- const lidWithDevice = (0, _index5.jidEncode)(lidDecoded?.user, 'lid', deviceId);
568
- // Migrate session to LID for unified encryption layer
569
- try {
570
- await signalRepository.migrateSession(wireJid, lidWithDevice);
571
- const recipientUser = (0, _index5.jidNormalizedUser)(wireJid);
572
- const ownPnUser = (0, _index5.jidNormalizedUser)(meId);
573
- const isOwnDevice = recipientUser === ownPnUser;
574
- logger.info({
575
- wireJid,
576
- lidWithDevice,
577
- isOwnDevice
578
- }, 'Migrated to LID encryption');
579
- // Delete PN session after successful migration
580
- try {
581
- await signalRepository.deleteSession(wireJid);
582
- logger.debug({
583
- deletedPNSession: wireJid
584
- }, 'Deleted PN session');
585
- } catch (deleteError) {
586
- logger.warn({
587
- wireJid,
588
- error: deleteError
589
- }, 'Failed to delete PN session');
271
+ /**
272
+ * Update Member Label
273
+ */
274
+ const updateMemberLabel = (jid, memberLabel) => {
275
+ return relayMessage(jid, {
276
+ protocolMessage: {
277
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
278
+ memberLabel: {
279
+ label: memberLabel?.slice(0, 30),
280
+ labelTimestamp: unixTimestampSeconds()
281
+ }
282
+ }
283
+ }, {
284
+ additionalNodes: [
285
+ {
286
+ tag: 'meta',
287
+ attrs: {
288
+ tag_reason: 'user_update',
289
+ appdata: 'member_tag'
290
+ },
291
+ content: undefined
292
+ }
293
+ ]
294
+ });
295
+ };
296
+ const assertSessions = async (jids, force) => {
297
+ let didFetchNewSession = false;
298
+ const uniqueJids = [...new Set(jids)];
299
+ const jidsRequiringFetch = [];
300
+ logger.debug({ jids }, 'assertSessions call with jids');
301
+ for (const jid of uniqueJids) {
302
+ if (!force) {
303
+ const sessionValidation = await signalRepository.validateSession(jid);
304
+ if (sessionValidation.exists) {
305
+ continue;
306
+ }
590
307
  }
591
- return lidWithDevice;
592
- } catch (migrationError) {
593
- logger.warn({
594
- wireJid,
595
- error: migrationError
596
- }, 'Failed to migrate session');
597
- return wireJid;
598
- }
599
- } catch (error) {
600
- logger.debug({
601
- wireJid,
602
- error
603
- }, 'Failed to check LID mapping');
604
- return wireJid;
308
+ jidsRequiringFetch.push(jid);
605
309
  }
606
- };
607
- // Encrypt to this user's devices sequentially to prevent session corruption
608
- for (const {
609
- recipientJid: wireJid,
610
- patchedMessage
611
- } of userDevices) {
612
- // DSM logic: Use DSM for own other devices (following whatsmeow implementation)
613
- let messageToEncrypt = patchedMessage;
614
- if (dsmMessage) {
615
- const {
616
- user: targetUser
617
- } = (0, _index5.jidDecode)(wireJid);
618
- const {
619
- user: ownPnUser
620
- } = (0, _index5.jidDecode)(meId);
621
- const ownLidUser = meLidUser;
622
- // Check if this is our device (same user, different device)
623
- const isOwnUser = targetUser === ownPnUser || ownLidUser && targetUser === ownLidUser;
624
- // Exclude exact sender device (whatsmeow: if jid == ownJID || jid == ownLID { continue })
625
- const isExactSenderDevice = wireJid === meId || authState.creds.me?.lid && wireJid === authState.creds.me.lid;
626
- if (isOwnUser && !isExactSenderDevice) {
627
- messageToEncrypt = dsmMessage;
628
- logger.debug({
629
- wireJid,
630
- targetUser
631
- }, 'Using DSM for own device');
632
- }
310
+ if (jidsRequiringFetch.length) {
311
+ // LID if mapped, otherwise original
312
+ const wireJids = [
313
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
315
+ ];
316
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
317
+ const result = await query({
318
+ tag: 'iq',
319
+ attrs: {
320
+ xmlns: 'encrypt',
321
+ type: 'get',
322
+ to: S_WHATSAPP_NET
323
+ },
324
+ content: [
325
+ {
326
+ tag: 'key',
327
+ attrs: {},
328
+ content: wireJids.map(jid => {
329
+ const attrs = { jid };
330
+ if (force)
331
+ attrs.reason = 'identity';
332
+ return { tag: 'user', attrs };
333
+ })
334
+ }
335
+ ]
336
+ });
337
+ await parseAndInjectE2ESessions(result, signalRepository);
338
+ didFetchNewSession = true;
633
339
  }
634
- const bytes = (0, _index4.encodeWAMessage)(messageToEncrypt);
635
- // Get encryption JID with LID migration
636
- const encryptionJid = await getEncryptionJid(wireJid);
637
- // ENCRYPT: Use the determined encryption identity (prefers migrated LID)
638
- const {
639
- type,
640
- ciphertext
641
- } = await signalRepository.encryptMessage({
642
- jid: encryptionJid,
643
- // Unified encryption layer (LID when available)
644
- data: bytes
645
- });
646
- if (type === 'pkmsg') {
647
- shouldIncludeDeviceIdentity = true;
340
+ return didFetchNewSession;
341
+ };
342
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
343
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
344
+ if (!authState.creds.me?.id) {
345
+ throw new Boom('Not authenticated');
648
346
  }
649
- const node = {
650
- tag: 'to',
651
- attrs: {
652
- jid: wireJid
653
- },
654
- // Always use original wire identity in envelope
655
- content: [{
656
- tag: 'enc',
657
- attrs: {
658
- v: '2',
659
- type,
660
- ...(extraAttrs || {})
661
- },
662
- content: ciphertext
663
- }]
347
+ const protocolMessage = {
348
+ protocolMessage: {
349
+ peerDataOperationRequestMessage: pdoMessage,
350
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
351
+ }
664
352
  };
665
- userNodes.push(node);
666
- }
667
- logger.debug({
668
- user,
669
- nodesCreated: userNodes.length
670
- }, 'Releasing encryption lock for user devices');
671
- return userNodes;
672
- }));
673
- // Wait for all users to complete (users are processed in parallel)
674
- const userNodesArrays = await Promise.all(userEncryptionPromises);
675
- const nodes = userNodesArrays.flat();
676
- return {
677
- nodes,
678
- shouldIncludeDeviceIdentity
679
- };
680
- };
681
- const relayMessage = async (jid, message, {
682
- messageId: msgId,
683
- participant,
684
- additionalAttributes,
685
- additionalNodes,
686
- useUserDevicesCache,
687
- useCachedGroupMetadata,
688
- statusJidList
689
- }) => {
690
- const meId = authState.creds.me.id;
691
- const meLid = authState.creds.me?.lid;
692
- // ADDRESSING CONSISTENCY: Keep envelope addressing as user provided, handle LID migration in encryption
693
- let shouldIncludeDeviceIdentity = false;
694
- const {
695
- user,
696
- server
697
- } = (0, _index5.jidDecode)(jid);
698
- const statusJid = 'status@broadcast';
699
- const isGroup = server === 'g.us';
700
- const isStatus = jid === statusJid;
701
- const isLid = server === 'lid';
702
- const isNewsletter = server === 'newsletter';
703
- // Keep user's original JID choice for envelope addressing
704
- const finalJid = jid;
705
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
706
- let ownId = meId;
707
- if (isLid && meLid) {
708
- ownId = meLid;
709
- logger.debug({
710
- to: jid,
711
- ownId
712
- }, 'Using LID identity for @lid conversation');
713
- } else {
714
- logger.debug({
715
- to: jid,
716
- ownId
717
- }, 'Using PN identity for @s.whatsapp.net conversation');
718
- }
719
- msgId = msgId || (0, _index4.generateMessageIDV2)(sock.user?.id);
720
- useUserDevicesCache = useUserDevicesCache !== false;
721
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
722
- const participants = [];
723
- const destinationJid = !isStatus ? finalJid : statusJid;
724
- const binaryNodeContent = [];
725
- const devices = [];
726
- const meMsg = {
727
- deviceSentMessage: {
728
- destinationJid,
729
- message
730
- },
731
- messageContextInfo: message.messageContextInfo
353
+ const meJid = jidNormalizedUser(authState.creds.me.id);
354
+ const msgId = await relayMessage(meJid, protocolMessage, {
355
+ additionalAttributes: {
356
+ category: 'peer',
357
+ push_priority: 'high_force'
358
+ },
359
+ additionalNodes: [
360
+ {
361
+ tag: 'meta',
362
+ attrs: { appdata: 'default' }
363
+ }
364
+ ]
365
+ });
366
+ return msgId;
732
367
  };
733
- const extraAttrs = {};
734
- if (participant) {
735
- // when the retry request is not for a group
736
- // only send to the specific device that asked for a retry
737
- // otherwise the message is sent out to every device that should be a recipient
738
- if (!isGroup && !isStatus) {
739
- additionalAttributes = {
740
- ...additionalAttributes,
741
- device_fanout: 'false'
742
- };
743
- }
744
- const {
745
- user,
746
- device
747
- } = (0, _index5.jidDecode)(participant.jid);
748
- devices.push({
749
- user,
750
- device,
751
- wireJid: participant.jid // Use the participant JID as wire JID
752
- });
753
- }
754
- await authState.keys.transaction(async () => {
755
- const mediaType = getMediaType(message);
756
- if (mediaType) {
757
- extraAttrs['mediatype'] = mediaType;
758
- }
759
- if (isNewsletter) {
760
- // Patch message if needed, then encode as plaintext
761
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
762
- const bytes = (0, _index4.encodeNewsletterMessage)(patched);
763
- binaryNodeContent.push({
764
- tag: 'plaintext',
765
- attrs: {},
766
- content: bytes
368
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
369
+ if (!recipientJids.length) {
370
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
371
+ }
372
+ const patched = await patchMessageBeforeSending(message, recipientJids);
373
+ const patchedMessages = Array.isArray(patched)
374
+ ? patched
375
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
376
+ let shouldIncludeDeviceIdentity = false;
377
+ const meId = authState.creds.me.id;
378
+ const meLid = authState.creds.me?.lid;
379
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
380
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
381
+ try {
382
+ if (!jid)
383
+ return null;
384
+ let msgToEncrypt = patchedMessage;
385
+ if (dsmMessage) {
386
+ const { user: targetUser } = jidDecode(jid);
387
+ const { user: ownPnUser } = jidDecode(meId);
388
+ const ownLidUser = meLidUser;
389
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
390
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
391
+ if (isOwnUser && !isExactSenderDevice) {
392
+ msgToEncrypt = dsmMessage;
393
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
394
+ }
395
+ }
396
+ const bytes = encodeWAMessage(msgToEncrypt);
397
+ const mutexKey = jid;
398
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
399
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
400
+ if (type === 'pkmsg') {
401
+ shouldIncludeDeviceIdentity = true;
402
+ }
403
+ return {
404
+ tag: 'to',
405
+ attrs: { jid },
406
+ content: [
407
+ {
408
+ tag: 'enc',
409
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
410
+ content: ciphertext
411
+ }
412
+ ]
413
+ };
414
+ });
415
+ return node;
416
+ }
417
+ catch (err) {
418
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
419
+ return null;
420
+ }
767
421
  });
768
- const stanza = {
769
- tag: 'message',
770
- attrs: {
771
- to: jid,
772
- id: msgId,
773
- type: getMessageType(message),
774
- ...(additionalAttributes || {})
775
- },
776
- content: binaryNodeContent
422
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
423
+ if (recipientJids.length > 0 && nodes.length === 0) {
424
+ throw new Boom('All encryptions failed', { statusCode: 500 });
425
+ }
426
+ return { nodes, shouldIncludeDeviceIdentity };
427
+ };
428
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
429
+ const meId = assertMeId(authState.creds);
430
+ const meLid = authState.creds.me?.lid;
431
+ const isRetryResend = Boolean(participant?.jid);
432
+ let shouldIncludeDeviceIdentity = isRetryResend;
433
+ const statusJid = 'status@broadcast';
434
+ const { user, server } = jidDecode(jid);
435
+ const isGroup = server === 'g.us';
436
+ const isStatus = jid === statusJid;
437
+ const isLid = server === 'lid';
438
+ const isNewsletter = server === 'newsletter';
439
+ const isGroupOrStatus = isGroup || isStatus;
440
+ const finalJid = jid;
441
+ msgId = msgId || generateMessageIDV2(meId);
442
+ useUserDevicesCache = useUserDevicesCache !== false;
443
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
444
+ const participants = [];
445
+ const destinationJid = !isStatus ? finalJid : statusJid;
446
+ const binaryNodeContent = [];
447
+ const devices = [];
448
+ let reportingMessage;
449
+ const meMsg = {
450
+ deviceSentMessage: {
451
+ destinationJid,
452
+ message
453
+ },
454
+ messageContextInfo: message.messageContextInfo
777
455
  };
778
- logger.debug({
779
- msgId
780
- }, `sending newsletter message to ${jid}`);
781
- await sendNode(stanza);
782
- return;
783
- }
784
- if ((0, _index4.normalizeMessageContent)(message)?.pinInChatMessage) {
785
- extraAttrs['decrypt-fail'] = 'hide';
786
- }
787
- if (isGroup || isStatus) {
788
- const [groupData, senderKeyMap] = await Promise.all([(async () => {
789
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
790
- if (groupData && Array.isArray(groupData?.participants)) {
791
- logger.trace({
792
- jid,
793
- participants: groupData.participants.length
794
- }, 'using cached group metadata');
795
- } else if (!isStatus) {
796
- groupData = await groupMetadata(jid);
797
- }
798
- return groupData;
799
- })(), (async () => {
800
- if (!participant && !isStatus) {
801
- const result = await authState.keys.get('sender-key-memory', [jid]);
802
- return result[jid] || {};
803
- }
804
- return {};
805
- })()]);
806
- if (!participant) {
807
- const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
808
- if (isStatus && statusJidList) {
809
- participantsList.push(...statusJidList);
810
- }
811
- if (!isStatus) {
812
- const groupAddressingMode = groupData?.addressingMode || (isLid ? _index3.WAMessageAddressingMode.LID : _index3.WAMessageAddressingMode.PN);
813
- additionalAttributes = {
814
- ...additionalAttributes,
815
- addressing_mode: groupAddressingMode
456
+ const extraAttrs = {};
457
+ if (participant) {
458
+ if (!isGroup && !isStatus) {
459
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
460
+ }
461
+ const { user, device } = jidDecode(participant.jid);
462
+ devices.push({
463
+ user,
464
+ device,
465
+ jid: participant.jid
466
+ });
467
+ }
468
+ await authState.keys.transaction(async () => {
469
+ const mediaType = getMediaType(message);
470
+ if (mediaType) {
471
+ extraAttrs['mediatype'] = mediaType;
472
+ }
473
+ if (isNewsletter) {
474
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
475
+ const bytes = encodeNewsletterMessage(patched);
476
+ binaryNodeContent.push({
477
+ tag: 'plaintext',
478
+ attrs: {},
479
+ content: bytes
480
+ });
481
+ const stanza = {
482
+ tag: 'message',
483
+ attrs: {
484
+ to: jid,
485
+ id: msgId,
486
+ type: getMessageType(message),
487
+ ...(additionalAttributes || {})
488
+ },
489
+ content: binaryNodeContent
490
+ };
491
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
492
+ await sendNode(stanza);
493
+ return;
494
+ }
495
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
496
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
497
+ }
498
+ if (isGroupOrStatus && !isRetryResend) {
499
+ const [groupData, senderKeyMap] = await Promise.all([
500
+ (async () => {
501
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
502
+ if (groupData && Array.isArray(groupData?.participants)) {
503
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
504
+ }
505
+ else if (!isStatus) {
506
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
507
+ }
508
+ return groupData;
509
+ })(),
510
+ (async () => {
511
+ if (!participant && !isStatus) {
512
+ // what if sender memory is less accurate than the cached metadata
513
+ // on participant change in group, we should do sender memory manipulation
514
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
515
+ return result[jid] || {};
516
+ }
517
+ return {};
518
+ })()
519
+ ]);
520
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
521
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
522
+ additionalAttributes = {
523
+ ...additionalAttributes,
524
+ expiration: groupData.ephemeralDuration.toString()
525
+ };
526
+ }
527
+ if (isStatus && statusJidList) {
528
+ participantsList.push(...statusJidList);
529
+ }
530
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
531
+ devices.push(...additionalDevices);
532
+ if (isGroup) {
533
+ additionalAttributes = {
534
+ ...additionalAttributes,
535
+ addressing_mode: groupData?.addressingMode || 'lid'
536
+ };
537
+ }
538
+ const patched = await patchMessageBeforeSending(message);
539
+ if (Array.isArray(patched)) {
540
+ throw new Boom('Per-jid patching is not supported in groups');
541
+ }
542
+ const bytes = encodeWAMessage(patched);
543
+ reportingMessage = patched;
544
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
545
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
546
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
547
+ group: destinationJid,
548
+ data: bytes,
549
+ meId: groupSenderIdentity
550
+ });
551
+ const senderKeyRecipients = [];
552
+ for (const device of devices) {
553
+ const deviceJid = device.jid;
554
+ const hasKey = !!senderKeyMap[deviceJid];
555
+ if ((!hasKey || !!participant) &&
556
+ !isHostedLidUser(deviceJid) &&
557
+ !isHostedPnUser(deviceJid) &&
558
+ device.device !== 99) {
559
+ //todo: revamp all this logic
560
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
561
+ senderKeyRecipients.push(deviceJid);
562
+ senderKeyMap[deviceJid] = true;
563
+ }
564
+ }
565
+ if (senderKeyRecipients.length) {
566
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
567
+ const senderKeyMsg = {
568
+ senderKeyDistributionMessage: {
569
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
570
+ groupId: destinationJid
571
+ }
572
+ };
573
+ const senderKeySessionTargets = senderKeyRecipients;
574
+ await assertSessions(senderKeySessionTargets);
575
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
576
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
577
+ participants.push(...result.nodes);
578
+ }
579
+ binaryNodeContent.push({
580
+ tag: 'enc',
581
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
582
+ content: ciphertext
583
+ });
584
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
585
+ }
586
+ else {
587
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
588
+ // TODO: investigate if this is true
589
+ let ownId = meId;
590
+ if (isLid && meLid) {
591
+ ownId = meLid;
592
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
593
+ }
594
+ else {
595
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
596
+ }
597
+ const { user: ownUser } = jidDecode(ownId);
598
+ if (!participant) {
599
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
600
+ reportingMessage = Array.isArray(patchedForReporting)
601
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
602
+ : patchedForReporting;
603
+ }
604
+ if (!isRetryResend) {
605
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
606
+ devices.push({
607
+ user,
608
+ device: 0,
609
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
610
+ });
611
+ if (user !== ownUser) {
612
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
613
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
614
+ devices.push({
615
+ user: ownUserForAddressing,
616
+ device: 0,
617
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
618
+ });
619
+ }
620
+ if (additionalAttributes?.['category'] !== 'peer') {
621
+ // Clear placeholders and enumerate actual devices
622
+ devices.length = 0;
623
+ // Use conversation-appropriate sender identity
624
+ const senderIdentity = isLid && meLid
625
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
626
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
627
+ // Enumerate devices for sender and target with consistent addressing
628
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
629
+ devices.push(...sessionDevices);
630
+ logger.debug({
631
+ deviceCount: devices.length,
632
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
633
+ }, 'Device enumeration complete with unified addressing');
634
+ }
635
+ }
636
+ const allRecipients = [];
637
+ const meRecipients = [];
638
+ const otherRecipients = [];
639
+ const { user: mePnUser } = jidDecode(meId);
640
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
641
+ for (const { user, jid } of devices) {
642
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
643
+ if (isExactSenderDevice) {
644
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
645
+ continue;
646
+ }
647
+ // Check if this is our device (could match either PN or LID user)
648
+ const isMe = user === mePnUser || user === meLidUser;
649
+ if (isMe) {
650
+ meRecipients.push(jid);
651
+ }
652
+ else {
653
+ otherRecipients.push(jid);
654
+ }
655
+ allRecipients.push(jid);
656
+ }
657
+ await assertSessions(allRecipients);
658
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
659
+ // For own devices: use DSM if available (1:1 chats only)
660
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
661
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
662
+ ]);
663
+ participants.push(...meNodes);
664
+ participants.push(...otherNodes);
665
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
666
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
667
+ }
668
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
669
+ }
670
+ if (isRetryResend) {
671
+ const isParticipantLid = isLidUser(participant.jid);
672
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
673
+ let messageToSend = message;
674
+ if (isGroupOrStatus) {
675
+ let groupSenderIdentity;
676
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
677
+ groupSenderIdentity = meLid;
678
+ }
679
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
680
+ groupSenderIdentity = meId;
681
+ }
682
+ if (groupSenderIdentity) {
683
+ try {
684
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
685
+ group: destinationJid,
686
+ meId: groupSenderIdentity
687
+ });
688
+ messageToSend = {
689
+ ...message,
690
+ senderKeyDistributionMessage: {
691
+ groupId: destinationJid,
692
+ axolotlSenderKeyDistributionMessage: skdm
693
+ }
694
+ };
695
+ }
696
+ catch (err) {
697
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
698
+ }
699
+ }
700
+ }
701
+ const encodedMessageToSend = isMe
702
+ ? encodeWAMessage({
703
+ deviceSentMessage: {
704
+ destinationJid,
705
+ message: messageToSend
706
+ }
707
+ })
708
+ : encodeWAMessage(messageToSend);
709
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
710
+ data: encodedMessageToSend,
711
+ jid: participant.jid
712
+ });
713
+ binaryNodeContent.push({
714
+ tag: 'enc',
715
+ attrs: {
716
+ v: '2',
717
+ type,
718
+ count: participant.count.toString()
719
+ },
720
+ content: encryptedContent
721
+ });
722
+ }
723
+ if (participants.length) {
724
+ if (additionalAttributes?.['category'] === 'peer') {
725
+ const peerNode = participants[0]?.content?.[0];
726
+ if (peerNode) {
727
+ binaryNodeContent.push(peerNode); // push only enc
728
+ }
729
+ }
730
+ else {
731
+ binaryNodeContent.push({
732
+ tag: 'participants',
733
+ attrs: {},
734
+ content: participants
735
+ });
736
+ }
737
+ }
738
+ const stanza = {
739
+ tag: 'message',
740
+ attrs: {
741
+ id: msgId,
742
+ to: destinationJid,
743
+ type: getMessageType(message),
744
+ ...(additionalAttributes || {})
745
+ },
746
+ content: binaryNodeContent
816
747
  };
817
- }
818
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
819
- devices.push(...additionalDevices);
748
+ // if the participant to send to is explicitly specified (generally retry recp)
749
+ // ensure the message is only sent to that person
750
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
751
+ if (participant) {
752
+ if (isJidGroup(destinationJid)) {
753
+ stanza.attrs.to = destinationJid;
754
+ stanza.attrs.participant = participant.jid;
755
+ }
756
+ else if (areJidsSameUser(participant.jid, meId)) {
757
+ stanza.attrs.to = participant.jid;
758
+ stanza.attrs.recipient = destinationJid;
759
+ }
760
+ else {
761
+ stanza.attrs.to = participant.jid;
762
+ }
763
+ }
764
+ else {
765
+ stanza.attrs.to = destinationJid;
766
+ }
767
+ if (shouldIncludeDeviceIdentity) {
768
+ ;
769
+ stanza.content.push({
770
+ tag: 'device-identity',
771
+ attrs: {},
772
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
773
+ });
774
+ logger.debug({ jid }, 'adding device identity');
775
+ }
776
+ if (!isNewsletter &&
777
+ !isRetryResend &&
778
+ reportingMessage?.messageContextInfo?.messageSecret &&
779
+ shouldIncludeReportingToken(reportingMessage)) {
780
+ try {
781
+ const encoded = encodeWAMessage(reportingMessage);
782
+ const reportingKey = {
783
+ id: msgId,
784
+ fromMe: true,
785
+ remoteJid: destinationJid,
786
+ participant: participant?.jid
787
+ };
788
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
789
+ if (reportingNode) {
790
+ ;
791
+ stanza.content.push(reportingNode);
792
+ logger.trace({ jid }, 'added reporting token to message');
793
+ }
794
+ }
795
+ catch (error) {
796
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
797
+ }
798
+ }
799
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
800
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
801
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
802
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
803
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
804
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
805
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
806
+ let tcTokenBuffer = existingTokenEntry?.token;
807
+ // Treat expired tokens the same as missing — clear from cache
808
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
809
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
810
+ tcTokenBuffer = undefined;
811
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
812
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
813
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
814
+ : null;
815
+ try {
816
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
817
+ }
818
+ catch (err) {
819
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
820
+ }
821
+ }
822
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
823
+ ;
824
+ stanza.content.push({
825
+ tag: 'tctoken',
826
+ attrs: {},
827
+ content: tcTokenBuffer
828
+ });
829
+ }
830
+ if (additionalNodes && additionalNodes.length > 0) {
831
+ ;
832
+ stanza.content.push(...additionalNodes);
833
+ }
834
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
835
+ await sendNode(stanza);
836
+ // Fire-and-forget: issue our token to the contact AFTER message send.
837
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
838
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
839
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
840
+ if (is1on1Send &&
841
+ !isProtocolMsg &&
842
+ !isBotOrPSA &&
843
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
844
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
845
+ inFlightTcTokenIssuance.add(tcTokenJid);
846
+ const issueTimestamp = unixTimestampSeconds();
847
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
848
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
849
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
850
+ .then(async (result) => {
851
+ await storeTcTokensFromIqResult({
852
+ result,
853
+ fallbackJid: tcTokenJid,
854
+ keys: authState.keys,
855
+ getLIDForPN
856
+ });
857
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
858
+ const currentEntry = currentData[tcTokenJid];
859
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
860
+ await authState.keys.set({
861
+ tctoken: {
862
+ [tcTokenJid]: {
863
+ token: Buffer.alloc(0),
864
+ ...currentEntry,
865
+ senderTimestamp: issueTimestamp
866
+ },
867
+ ...indexWrite
868
+ }
869
+ });
870
+ })
871
+ .catch(err => {
872
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
873
+ })
874
+ .finally(() => {
875
+ inFlightTcTokenIssuance.delete(tcTokenJid);
876
+ });
877
+ }
878
+ // Add message to retry cache if enabled
879
+ if (messageRetryManager && !participant) {
880
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
881
+ }
882
+ }, meId);
883
+ return msgId;
884
+ };
885
+ const getMessageType = (message) => {
886
+ const normalizedMessage = normalizeMessageContent(message);
887
+ if (!normalizedMessage)
888
+ return 'text';
889
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
890
+ return 'reaction';
820
891
  }
821
- const patched = await patchMessageBeforeSending(message);
822
- if (Array.isArray(patched)) {
823
- throw new _boom.Boom('Per-jid patching is not supported in groups');
892
+ if (normalizedMessage.pollCreationMessage ||
893
+ normalizedMessage.pollCreationMessageV2 ||
894
+ normalizedMessage.pollCreationMessageV3 ||
895
+ normalizedMessage.pollUpdateMessage) {
896
+ return 'poll';
824
897
  }
825
- const bytes = (0, _index4.encodeWAMessage)(patched);
826
- // This should match the group's addressing mode and conversation context
827
- const groupAddressingMode = groupData?.addressingMode || (isLid ? 'lid' : 'pn');
828
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
829
- const {
830
- ciphertext,
831
- senderKeyDistributionMessage
832
- } = await signalRepository.encryptGroupMessage({
833
- group: destinationJid,
834
- data: bytes,
835
- meId: groupSenderIdentity
836
- });
837
- const senderKeyJids = [];
838
- // ensure a connection is established with every device
839
- for (const device of devices) {
840
- // This preserves the LID migration results from getUSyncDevices
841
- const deviceJid = device.wireJid;
842
- const hasKey = !!senderKeyMap[deviceJid];
843
- if (!hasKey || !!participant) {
844
- senderKeyJids.push(deviceJid);
845
- // store that this person has had the sender keys sent to them
846
- senderKeyMap[deviceJid] = true;
847
- }
898
+ if (normalizedMessage.eventMessage) {
899
+ return 'event';
848
900
  }
849
- // if there are some participants with whom the session has not been established
850
- // if there are, we re-send the senderkey
851
- if (senderKeyJids.length) {
852
- logger.debug({
853
- senderKeyJids
854
- }, 'sending new sender key');
855
- const senderKeyMsg = {
856
- senderKeyDistributionMessage: {
857
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
858
- groupId: destinationJid
859
- }
860
- };
861
- await assertSessions(senderKeyJids, false);
862
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
863
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
864
- participants.push(...result.nodes);
901
+ if (getMediaType(normalizedMessage) !== '') {
902
+ return 'media';
865
903
  }
866
- binaryNodeContent.push({
867
- tag: 'enc',
868
- attrs: {
869
- v: '2',
870
- type: 'skmsg'
871
- },
872
- content: ciphertext
873
- });
874
- await authState.keys.set({
875
- 'sender-key-memory': {
876
- [jid]: senderKeyMap
877
- }
878
- });
879
- } else {
880
- const {
881
- user: ownUser
882
- } = (0, _index5.jidDecode)(ownId);
883
- if (!participant) {
884
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
885
- devices.push({
886
- user,
887
- device: 0,
888
- wireJid: (0, _index5.jidEncode)(user, targetUserServer, 0)
889
- });
890
- // Own user matches conversation addressing mode
891
- if (user !== ownUser) {
892
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
893
- const ownUserForAddressing = isLid && meLid ? (0, _index5.jidDecode)(meLid).user : (0, _index5.jidDecode)(meId).user;
894
- devices.push({
895
- user: ownUserForAddressing,
896
- device: 0,
897
- wireJid: (0, _index5.jidEncode)(ownUserForAddressing, ownUserServer, 0)
898
- });
899
- }
900
- if (additionalAttributes?.['category'] !== 'peer') {
901
- // Clear placeholders and enumerate actual devices
902
- devices.length = 0;
903
- // Use conversation-appropriate sender identity
904
- const senderIdentity = isLid && meLid ? (0, _index5.jidEncode)((0, _index5.jidDecode)(meLid)?.user, 'lid', undefined) : (0, _index5.jidEncode)((0, _index5.jidDecode)(meId)?.user, 's.whatsapp.net', undefined);
905
- // Enumerate devices for sender and target with consistent addressing
906
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], false, false);
907
- devices.push(...sessionDevices);
908
- logger.debug({
909
- deviceCount: devices.length,
910
- devices: devices.map(d => `${d.user}:${d.device}@${(0, _index5.jidDecode)(d.wireJid)?.server}`)
911
- }, 'Device enumeration complete with unified addressing');
912
- }
904
+ return 'text';
905
+ };
906
+ const getMediaType = (message) => {
907
+ if (message.imageMessage) {
908
+ return 'image';
913
909
  }
914
- const allJids = [];
915
- const meJids = [];
916
- const otherJids = [];
917
- const {
918
- user: mePnUser
919
- } = (0, _index5.jidDecode)(meId);
920
- const {
921
- user: meLidUser
922
- } = meLid ? (0, _index5.jidDecode)(meLid) : {
923
- user: null
924
- };
925
- for (const {
926
- user,
927
- wireJid
928
- } of devices) {
929
- const isExactSenderDevice = wireJid === meId || meLid && wireJid === meLid;
930
- if (isExactSenderDevice) {
931
- logger.debug({
932
- wireJid,
933
- meId,
934
- meLid
935
- }, 'Skipping exact sender device (whatsmeow pattern)');
936
- continue;
937
- }
938
- // Check if this is our device (could match either PN or LID user)
939
- const isMe = user === mePnUser || meLidUser && user === meLidUser;
940
- const jid = wireJid;
941
- if (isMe) {
942
- meJids.push(jid);
943
- } else {
944
- otherJids.push(jid);
945
- }
946
- allJids.push(jid);
910
+ else if (message.videoMessage) {
911
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
947
912
  }
948
- await assertSessions([...otherJids, ...meJids], false);
949
- const [{
950
- nodes: meNodes,
951
- shouldIncludeDeviceIdentity: s1
952
- }, {
953
- nodes: otherNodes,
954
- shouldIncludeDeviceIdentity: s2
955
- }] = await Promise.all([
956
- // For own devices: use DSM if available (1:1 chats only)
957
- createParticipantNodes(meJids, meMsg || message, extraAttrs), createParticipantNodes(otherJids, message, extraAttrs, meMsg)]);
958
- participants.push(...meNodes);
959
- participants.push(...otherNodes);
960
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
961
- }
962
- if (participants.length) {
963
- if (additionalAttributes?.['category'] === 'peer') {
964
- const peerNode = participants[0]?.content?.[0];
965
- if (peerNode) {
966
- binaryNodeContent.push(peerNode); // push only enc
967
- }
968
- } else {
969
- binaryNodeContent.push({
970
- tag: 'participants',
971
- attrs: {},
972
- content: participants
973
- });
913
+ else if (message.audioMessage) {
914
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
974
915
  }
975
- }
976
- const stanza = {
977
- tag: 'message',
978
- attrs: {
979
- id: msgId,
980
- to: destinationJid,
981
- type: getMessageType(message),
982
- ...(additionalAttributes || {})
983
- },
984
- content: binaryNodeContent
985
- };
986
- // if the participant to send to is explicitly specified (generally retry recp)
987
- // ensure the message is only sent to that person
988
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
989
- if (participant) {
990
- if ((0, _index5.isJidGroup)(destinationJid)) {
991
- stanza.attrs.to = destinationJid;
992
- stanza.attrs.participant = participant.jid;
993
- } else if ((0, _index5.areJidsSameUser)(participant.jid, meId)) {
994
- stanza.attrs.to = participant.jid;
995
- stanza.attrs.recipient = destinationJid;
996
- } else {
997
- stanza.attrs.to = participant.jid;
916
+ else if (message.contactMessage) {
917
+ return 'vcard';
998
918
  }
999
- } else {
1000
- stanza.attrs.to = destinationJid;
1001
- }
1002
- if (shouldIncludeDeviceIdentity) {
1003
- ;
1004
- stanza.content.push({
1005
- tag: 'device-identity',
1006
- attrs: {},
1007
- content: (0, _index4.encodeSignedDeviceIdentity)(authState.creds.account, true)
1008
- });
1009
- logger.debug({
1010
- jid
1011
- }, 'adding device identity');
1012
- }
1013
- if (additionalNodes && additionalNodes.length > 0) {
1014
- ;
1015
- stanza.content.push(...additionalNodes);
1016
- }
1017
- logger.debug({
1018
- msgId
1019
- }, `sending message to ${participants.length} devices`);
1020
- await sendNode(stanza);
1021
- // Add message to retry cache if enabled
1022
- if (messageRetryManager && !participant) {
1023
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1024
- }
1025
- }, meId);
1026
- return msgId;
1027
- };
1028
- const getMessageType = message => {
1029
- if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
1030
- return 'poll';
1031
- }
1032
- if (message.eventMessage) {
1033
- return 'event';
1034
- }
1035
- return 'text';
1036
- };
1037
- const getMediaType = message => {
1038
- if (message.imageMessage) {
1039
- return 'image';
1040
- } else if (message.videoMessage) {
1041
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
1042
- } else if (message.audioMessage) {
1043
- return message.audioMessage.ptt ? 'ptt' : 'audio';
1044
- } else if (message.contactMessage) {
1045
- return 'vcard';
1046
- } else if (message.documentMessage) {
1047
- return 'document';
1048
- } else if (message.contactsArrayMessage) {
1049
- return 'contact_array';
1050
- } else if (message.liveLocationMessage) {
1051
- return 'livelocation';
1052
- } else if (message.stickerMessage) {
1053
- return 'sticker';
1054
- } else if (message.listMessage) {
1055
- return 'list';
1056
- } else if (message.listResponseMessage) {
1057
- return 'list_response';
1058
- } else if (message.buttonsResponseMessage) {
1059
- return 'buttons_response';
1060
- } else if (message.orderMessage) {
1061
- return 'order';
1062
- } else if (message.productMessage) {
1063
- return 'product';
1064
- } else if (message.interactiveResponseMessage) {
1065
- return 'native_flow_response';
1066
- } else if (message.groupInviteMessage) {
1067
- return 'url';
1068
- }
1069
- };
1070
- const getPrivacyTokens = async jids => {
1071
- const t = (0, _index4.unixTimestampSeconds)().toString();
1072
- const result = await query({
1073
- tag: 'iq',
1074
- attrs: {
1075
- to: _index5.S_WHATSAPP_NET,
1076
- type: 'set',
1077
- xmlns: 'privacy'
1078
- },
1079
- content: [{
1080
- tag: 'tokens',
1081
- attrs: {},
1082
- content: jids.map(jid => ({
1083
- tag: 'token',
1084
- attrs: {
1085
- jid: (0, _index5.jidNormalizedUser)(jid),
1086
- t,
1087
- type: 'trusted_contact'
1088
- }
1089
- }))
1090
- }]
1091
- });
1092
- return result;
1093
- };
1094
- const waUploadToServer = (0, _index4.getWAUploadToServer)(config, refreshMediaConn);
1095
- const extendedMessages = (0, _extendedMessages.makeExtendedMessageHandlers)({
1096
- generateWAMessage: _index4.generateWAMessage,
1097
- generateWAMessageContent: _index4.generateWAMessageContent,
1098
- generateWAMessageFromContent: _index4.generateWAMessageFromContent,
1099
- generateMessageID: _index4.generateMessageID,
1100
- prepareWAMessageMedia: _index4.prepareWAMessageMedia,
1101
- waUploadToServer,
1102
- relayMessage
1103
- });
1104
- const waitForMsgMediaUpdate = (0, _index4.bindWaitForEvent)(ev, 'messages.media-update');
1105
- return {
1106
- ...sock,
1107
- getPrivacyTokens,
1108
- assertSessions,
1109
- relayMessage,
1110
- sendReceipt,
1111
- sendReceipts,
1112
- readMessages,
1113
- refreshMediaConn,
1114
- waUploadToServer,
1115
- fetchPrivacySettings,
1116
- sendPeerDataOperationMessage,
1117
- createParticipantNodes,
1118
- getUSyncDevices,
1119
- messageRetryManager,
1120
- updateMediaMessage: async message => {
1121
- const content = (0, _index4.assertMediaContent)(message.message);
1122
- const mediaKey = content.mediaKey;
1123
- const meId = authState.creds.me.id;
1124
- const node = await (0, _index4.encryptMediaRetryRequest)(message.key, mediaKey, meId);
1125
- let error = undefined;
1126
- await Promise.all([sendNode(node), waitForMsgMediaUpdate(async update => {
1127
- const result = update.find(c => c.key.id === message.key.id);
1128
- if (result) {
1129
- if (result.error) {
1130
- error = result.error;
1131
- } else {
1132
- try {
1133
- const media = await (0, _index4.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
1134
- if (media.result !== _index.proto.MediaRetryNotification.ResultType.SUCCESS) {
1135
- const resultStr = _index.proto.MediaRetryNotification.ResultType[media.result];
1136
- throw new _boom.Boom(`Media re-upload failed by device (${resultStr})`, {
1137
- data: media,
1138
- statusCode: (0, _index4.getStatusCodeForMediaRetry)(media.result) || 404
1139
- });
1140
- }
1141
- content.directPath = media.directPath;
1142
- content.url = (0, _index4.getUrlFromDirectPath)(content.directPath);
1143
- logger.debug({
1144
- directPath: media.directPath,
1145
- key: result.key
1146
- }, 'media update successful');
1147
- } catch (err) {
1148
- error = err;
1149
- }
1150
- }
1151
- return true;
919
+ else if (message.documentMessage) {
920
+ return 'document';
1152
921
  }
1153
- })]);
1154
- if (error) {
1155
- throw error;
1156
- }
1157
- ev.emit('messages.update', [{
1158
- key: message.key,
1159
- update: {
1160
- message: message.message
922
+ else if (message.contactsArrayMessage) {
923
+ return 'contact_array';
1161
924
  }
1162
- }]);
1163
- return message;
1164
- },
1165
- sendMessage: async (jid, content, options = {}) => {
1166
- const userJid = authState.creds.me.id;
1167
- const extendedType = (0, _extendedMessages.detectExtendedMessageType)(content);
1168
- if (extendedType) {
1169
- const msgId = options.messageId || (0, _index4.generateMessageIDV2)(sock.user?.id);
1170
- switch (extendedType) {
1171
- case 'PAYMENT':
1172
- {
1173
- const paymentContent = await extendedMessages.handlePayment(content, options.quoted);
1174
- await relayMessage(jid, paymentContent, {
1175
- messageId: msgId
1176
- });
1177
- return {
1178
- key: {
1179
- id: msgId,
1180
- remoteJid: jid,
1181
- fromMe: true
1182
- },
1183
- message: paymentContent
1184
- };
1185
- }
1186
- case 'INTERACTIVE':
1187
- {
1188
- const interactiveContent = await extendedMessages.buildInteractiveContent(content, options);
1189
- const interactiveMsg = (0, _index4.generateWAMessageFromContent)(jid, interactiveContent, {
1190
- quoted: options.quoted,
1191
- userJid
1192
- });
1193
- await relayMessage(jid, interactiveMsg.message, {
1194
- messageId: interactiveMsg.key.id
1195
- });
1196
- return interactiveMsg;
1197
- }
1198
- case 'ALBUM':
1199
- return await extendedMessages.sendAlbumMessage(jid, content, options.quoted);
1200
- case 'POLL_RESULT':
1201
- return await extendedMessages.sendPollResultMessage(jid, content, options.quoted);
1202
- case 'GROUP_STORY':
1203
- return await extendedMessages.sendGroupStoryMessage(jid, content, options.quoted);
925
+ else if (message.liveLocationMessage) {
926
+ return 'livelocation';
927
+ }
928
+ else if (message.stickerMessage) {
929
+ return 'sticker';
930
+ }
931
+ else if (message.listMessage) {
932
+ return 'list';
1204
933
  }
1205
- }
1206
- if (typeof content === 'object' && 'disappearingMessagesInChat' in content && typeof content['disappearingMessagesInChat'] !== 'undefined' && (0, _index5.isJidGroup)(jid)) {
1207
- const {
1208
- disappearingMessagesInChat
1209
- } = content;
1210
- const value = typeof disappearingMessagesInChat === 'boolean' ? disappearingMessagesInChat ? _index2.WA_DEFAULT_EPHEMERAL : 0 : disappearingMessagesInChat;
1211
- await groupToggleEphemeral(jid, value);
1212
- } else {
1213
- const fullMsg = await (0, _index4.generateWAMessage)(jid, content, {
1214
- logger,
1215
- userJid,
1216
- getUrlInfo: text => (0, _linkPreview.getUrlInfo)(text, {
1217
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1218
- fetchOpts: {
1219
- timeout: 3000,
1220
- ...(axiosOptions || {})
934
+ else if (message.listResponseMessage) {
935
+ return 'list_response';
936
+ }
937
+ else if (message.buttonsResponseMessage) {
938
+ return 'buttons_response';
939
+ }
940
+ else if (message.orderMessage) {
941
+ return 'order';
942
+ }
943
+ else if (message.productMessage) {
944
+ return 'product';
945
+ }
946
+ else if (message.interactiveResponseMessage) {
947
+ return 'native_flow_response';
948
+ }
949
+ else if (message.groupInviteMessage) {
950
+ return 'url';
951
+ }
952
+ return '';
953
+ };
954
+ const issuePrivacyTokens = async (jids, timestamp) => {
955
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
956
+ const result = await query({
957
+ tag: 'iq',
958
+ attrs: {
959
+ to: S_WHATSAPP_NET,
960
+ type: 'set',
961
+ xmlns: 'privacy'
1221
962
  },
1222
- logger,
1223
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1224
- }),
1225
- //TODO: CACHE
1226
- getProfilePicUrl: sock.profilePictureUrl,
1227
- getCallLink: sock.createCallLink,
1228
- upload: waUploadToServer,
1229
- mediaCache: config.mediaCache,
1230
- options: config.options,
1231
- messageId: (0, _index4.generateMessageIDV2)(sock.user?.id),
1232
- ...options
963
+ content: [
964
+ {
965
+ tag: 'tokens',
966
+ attrs: {},
967
+ content: jids.map(jid => ({
968
+ tag: 'token',
969
+ attrs: {
970
+ jid: jidNormalizedUser(jid),
971
+ t,
972
+ type: 'trusted_contact'
973
+ }
974
+ }))
975
+ }
976
+ ]
1233
977
  });
1234
- const isEventMsg = 'event' in content && !!content.event;
1235
- const isDeleteMsg = 'delete' in content && !!content.delete;
1236
- const isEditMsg = 'edit' in content && !!content.edit;
1237
- const isPinMsg = 'pin' in content && !!content.pin;
1238
- const isPollMessage = 'poll' in content && !!content.poll;
1239
- const additionalAttributes = {};
1240
- const additionalNodes = [];
1241
- // required for delete
1242
- if (isDeleteMsg) {
1243
- // if the chat is a group, and I am not the author, then delete the message as an admin
1244
- if ((0, _index5.isJidGroup)(content.delete?.remoteJid) && !content.delete?.fromMe) {
1245
- additionalAttributes.edit = '8';
1246
- } else {
1247
- additionalAttributes.edit = '7';
1248
- }
1249
- } else if (isEditMsg) {
1250
- additionalAttributes.edit = '1';
1251
- } else if (isPinMsg) {
1252
- additionalAttributes.edit = '2';
1253
- } else if (isPollMessage) {
1254
- additionalNodes.push({
1255
- tag: 'meta',
1256
- attrs: {
1257
- polltype: 'creation'
1258
- }
1259
- });
1260
- } else if (isEventMsg) {
1261
- additionalNodes.push({
1262
- tag: 'meta',
1263
- attrs: {
1264
- event_type: 'creation'
1265
- }
1266
- });
978
+ return result;
979
+ };
980
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
981
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
982
+ registerSocketEndHandler(() => {
983
+ if (!config.userDevicesCache && userDevicesCache.close) {
984
+ userDevicesCache.close();
1267
985
  }
1268
- if ('cachedGroupMetadata' in options) {
1269
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
986
+ mediaConn = undefined;
987
+ if (messageRetryManager) {
988
+ messageRetryManager.clear();
1270
989
  }
1271
- await relayMessage(jid, fullMsg.message, {
1272
- messageId: fullMsg.key.id,
1273
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1274
- additionalAttributes,
1275
- statusJidList: options.statusJidList,
1276
- additionalNodes
1277
- });
1278
- if (config.emitOwnEvents) {
1279
- process.nextTick(() => {
1280
- processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1281
- });
990
+ });
991
+ return {
992
+ ...sock,
993
+ userDevicesCache,
994
+ devicesMutex,
995
+ issuePrivacyTokens,
996
+ assertSessions,
997
+ relayMessage,
998
+ sendReceipt,
999
+ sendReceipts,
1000
+ readMessages,
1001
+ refreshMediaConn,
1002
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1003
+ getMediaHost: () => mediaHost,
1004
+ waUploadToServer,
1005
+ fetchPrivacySettings,
1006
+ sendPeerDataOperationMessage,
1007
+ createParticipantNodes,
1008
+ getUSyncDevices,
1009
+ messageRetryManager,
1010
+ updateMemberLabel,
1011
+ updateMediaMessage: async (message) => {
1012
+ const content = assertMediaContent(message.message);
1013
+ const mediaKey = content.mediaKey;
1014
+ const meId = authState.creds.me.id;
1015
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1016
+ let error = undefined;
1017
+ await Promise.all([
1018
+ sendNode(node),
1019
+ waitForMsgMediaUpdate(async (update) => {
1020
+ const result = update.find(c => c.key.id === message.key.id);
1021
+ if (result) {
1022
+ if (result.error) {
1023
+ error = result.error;
1024
+ }
1025
+ else {
1026
+ try {
1027
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1028
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1029
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1030
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1031
+ data: media,
1032
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1033
+ });
1034
+ }
1035
+ content.directPath = media.directPath;
1036
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1037
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1038
+ }
1039
+ catch (err) {
1040
+ error = err;
1041
+ }
1042
+ }
1043
+ return true;
1044
+ }
1045
+ })
1046
+ ]);
1047
+ if (error) {
1048
+ throw error;
1049
+ }
1050
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1051
+ return message;
1052
+ },
1053
+ sendMessage: async (jid, content, options = {}) => {
1054
+ const userJid = authState.creds.me.id;
1055
+ if (typeof content === 'object' &&
1056
+ 'disappearingMessagesInChat' in content &&
1057
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1058
+ isJidGroup(jid)) {
1059
+ const { disappearingMessagesInChat } = content;
1060
+ const value = typeof disappearingMessagesInChat === 'boolean'
1061
+ ? disappearingMessagesInChat
1062
+ ? WA_DEFAULT_EPHEMERAL
1063
+ : 0
1064
+ : disappearingMessagesInChat;
1065
+ await groupToggleEphemeral(jid, value);
1066
+ }
1067
+ else {
1068
+ const fullMsg = await generateWAMessage(jid, content, {
1069
+ logger,
1070
+ userJid,
1071
+ getUrlInfo: text => getUrlInfo(text, {
1072
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1073
+ fetchOpts: {
1074
+ timeout: 3000,
1075
+ ...(httpRequestOptions || {})
1076
+ },
1077
+ logger,
1078
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1079
+ }),
1080
+ //TODO: CACHE
1081
+ getProfilePicUrl: sock.profilePictureUrl,
1082
+ getCallLink: sock.createCallLink,
1083
+ upload: waUploadToServer,
1084
+ mediaCache: config.mediaCache,
1085
+ options: config.options,
1086
+ messageId: generateMessageIDV2(sock.user?.id),
1087
+ ...options
1088
+ });
1089
+ const isEventMsg = 'event' in content && !!content.event;
1090
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1091
+ const isEditMsg = 'edit' in content && !!content.edit;
1092
+ const isPinMsg = 'pin' in content && !!content.pin;
1093
+ const isPollMessage = 'poll' in content && !!content.poll;
1094
+ const additionalAttributes = {};
1095
+ const additionalNodes = [];
1096
+ // required for delete
1097
+ if (isDeleteMsg) {
1098
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1099
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1100
+ additionalAttributes.edit = '8';
1101
+ }
1102
+ else {
1103
+ additionalAttributes.edit = '7';
1104
+ }
1105
+ }
1106
+ else if (isEditMsg) {
1107
+ additionalAttributes.edit = '1';
1108
+ }
1109
+ else if (isPinMsg) {
1110
+ additionalAttributes.edit = '2';
1111
+ }
1112
+ else if (isPollMessage) {
1113
+ additionalNodes.push({
1114
+ tag: 'meta',
1115
+ attrs: {
1116
+ polltype: 'creation'
1117
+ }
1118
+ });
1119
+ }
1120
+ else if (isEventMsg) {
1121
+ additionalNodes.push({
1122
+ tag: 'meta',
1123
+ attrs: {
1124
+ event_type: 'creation'
1125
+ }
1126
+ });
1127
+ }
1128
+ await relayMessage(jid, fullMsg.message, {
1129
+ messageId: fullMsg.key.id,
1130
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1131
+ additionalAttributes,
1132
+ statusJidList: options.statusJidList,
1133
+ additionalNodes
1134
+ });
1135
+ if (config.emitOwnEvents) {
1136
+ process.nextTick(async () => {
1137
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1138
+ });
1139
+ }
1140
+ return fullMsg;
1141
+ }
1282
1142
  }
1283
- return fullMsg;
1284
- }
1285
- }
1286
- };
1143
+ };
1287
1144
  };
1288
- //# sourceMappingURL=messages-send.js.map
1289
- exports.makeMessagesSocket = makeMessagesSocket;
1145
+ //# sourceMappingURL=messages-send.js.map