@onedevil405/baileys 1.0.0

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 (372) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +4633 -0
  4. package/WAProto/fix-imports.js +29 -0
  5. package/WAProto/index.d.ts +10688 -0
  6. package/WAProto/index.js +37306 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.d.ts +58 -0
  9. package/lib/Defaults/index.d.ts.map +1 -0
  10. package/lib/Defaults/index.js +108 -0
  11. package/lib/Defaults/index.js.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  14. package/lib/Signal/Group/ciphertext-message.js +12 -0
  15. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  20. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  21. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  22. package/lib/Signal/Group/group_cipher.js +82 -0
  23. package/lib/Signal/Group/group_cipher.js.map +1 -0
  24. package/lib/Signal/Group/index.d.ts +12 -0
  25. package/lib/Signal/Group/index.d.ts.map +1 -0
  26. package/lib/Signal/Group/index.js +12 -0
  27. package/lib/Signal/Group/index.js.map +1 -0
  28. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  29. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  30. package/lib/Signal/Group/keyhelper.js +18 -0
  31. package/lib/Signal/Group/keyhelper.js.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.js +26 -0
  35. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.js +58 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.js +64 -0
  43. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.js +48 -0
  47. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.js +41 -0
  51. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.js +84 -0
  55. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  58. package/lib/Signal/Group/sender-message-key.js +26 -0
  59. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  60. package/lib/Signal/libsignal.d.ts +5 -0
  61. package/lib/Signal/libsignal.d.ts.map +1 -0
  62. package/lib/Signal/libsignal.js +345 -0
  63. package/lib/Signal/libsignal.js.map +1 -0
  64. package/lib/Signal/lid-mapping.d.ts +24 -0
  65. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  66. package/lib/Signal/lid-mapping.js +126 -0
  67. package/lib/Signal/lid-mapping.js.map +1 -0
  68. package/lib/Socket/Client/index.d.ts +3 -0
  69. package/lib/Socket/Client/index.d.ts.map +1 -0
  70. package/lib/Socket/Client/index.js +3 -0
  71. package/lib/Socket/Client/index.js.map +1 -0
  72. package/lib/Socket/Client/types.d.ts +16 -0
  73. package/lib/Socket/Client/types.d.ts.map +1 -0
  74. package/lib/Socket/Client/types.js +11 -0
  75. package/lib/Socket/Client/types.js.map +1 -0
  76. package/lib/Socket/Client/websocket.d.ts +13 -0
  77. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  78. package/lib/Socket/Client/websocket.js +50 -0
  79. package/lib/Socket/Client/websocket.js.map +1 -0
  80. package/lib/Socket/business.d.ts +188 -0
  81. package/lib/Socket/business.d.ts.map +1 -0
  82. package/lib/Socket/business.js +376 -0
  83. package/lib/Socket/business.js.map +1 -0
  84. package/lib/Socket/chats.d.ts +98 -0
  85. package/lib/Socket/chats.d.ts.map +1 -0
  86. package/lib/Socket/chats.js +959 -0
  87. package/lib/Socket/chats.js.map +1 -0
  88. package/lib/Socket/communities.d.ts +233 -0
  89. package/lib/Socket/communities.d.ts.map +1 -0
  90. package/lib/Socket/communities.js +395 -0
  91. package/lib/Socket/communities.js.map +1 -0
  92. package/lib/Socket/groups.d.ts +137 -0
  93. package/lib/Socket/groups.d.ts.map +1 -0
  94. package/lib/Socket/groups.js +325 -0
  95. package/lib/Socket/groups.js.map +1 -0
  96. package/lib/Socket/index.d.ts +220 -0
  97. package/lib/Socket/index.d.ts.map +1 -0
  98. package/lib/Socket/index.js +17 -0
  99. package/lib/Socket/index.js.map +1 -0
  100. package/lib/Socket/messages-recv.d.ts +173 -0
  101. package/lib/Socket/messages-recv.d.ts.map +1 -0
  102. package/lib/Socket/messages-recv.js +1229 -0
  103. package/lib/Socket/messages-recv.js.map +1 -0
  104. package/lib/Socket/messages-send.d.ts +169 -0
  105. package/lib/Socket/messages-send.d.ts.map +1 -0
  106. package/lib/Socket/messages-send.js +930 -0
  107. package/lib/Socket/messages-send.js.map +1 -0
  108. package/lib/Socket/mex.d.ts +3 -0
  109. package/lib/Socket/mex.d.ts.map +1 -0
  110. package/lib/Socket/mex.js +42 -0
  111. package/lib/Socket/mex.js.map +1 -0
  112. package/lib/Socket/newsletter.d.ts +147 -0
  113. package/lib/Socket/newsletter.d.ts.map +1 -0
  114. package/lib/Socket/newsletter.js +181 -0
  115. package/lib/Socket/newsletter.js.map +1 -0
  116. package/lib/Socket/socket.d.ts +50 -0
  117. package/lib/Socket/socket.d.ts.map +1 -0
  118. package/lib/Socket/socket.js +824 -0
  119. package/lib/Socket/socket.js.map +1 -0
  120. package/lib/Types/Auth.d.ts +106 -0
  121. package/lib/Types/Auth.d.ts.map +1 -0
  122. package/lib/Types/Auth.js +2 -0
  123. package/lib/Types/Auth.js.map +1 -0
  124. package/lib/Types/Bussines.d.ts +25 -0
  125. package/lib/Types/Bussines.d.ts.map +1 -0
  126. package/lib/Types/Bussines.js +2 -0
  127. package/lib/Types/Bussines.js.map +1 -0
  128. package/lib/Types/Call.d.ts +14 -0
  129. package/lib/Types/Call.d.ts.map +1 -0
  130. package/lib/Types/Call.js +2 -0
  131. package/lib/Types/Call.js.map +1 -0
  132. package/lib/Types/Chat.d.ts +123 -0
  133. package/lib/Types/Chat.d.ts.map +1 -0
  134. package/lib/Types/Chat.js +8 -0
  135. package/lib/Types/Chat.js.map +1 -0
  136. package/lib/Types/Contact.d.ts +24 -0
  137. package/lib/Types/Contact.d.ts.map +1 -0
  138. package/lib/Types/Contact.js +2 -0
  139. package/lib/Types/Contact.js.map +1 -0
  140. package/lib/Types/Events.d.ts +199 -0
  141. package/lib/Types/Events.d.ts.map +1 -0
  142. package/lib/Types/Events.js +2 -0
  143. package/lib/Types/Events.js.map +1 -0
  144. package/lib/Types/GroupMetadata.d.ts +66 -0
  145. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  146. package/lib/Types/GroupMetadata.js +2 -0
  147. package/lib/Types/GroupMetadata.js.map +1 -0
  148. package/lib/Types/Label.d.ts +47 -0
  149. package/lib/Types/Label.d.ts.map +1 -0
  150. package/lib/Types/Label.js +25 -0
  151. package/lib/Types/Label.js.map +1 -0
  152. package/lib/Types/LabelAssociation.d.ts +30 -0
  153. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  154. package/lib/Types/LabelAssociation.js +7 -0
  155. package/lib/Types/LabelAssociation.js.map +1 -0
  156. package/lib/Types/Message.d.ts +301 -0
  157. package/lib/Types/Message.d.ts.map +1 -0
  158. package/lib/Types/Message.js +11 -0
  159. package/lib/Types/Message.js.map +1 -0
  160. package/lib/Types/Newsletter.d.ts +135 -0
  161. package/lib/Types/Newsletter.d.ts.map +1 -0
  162. package/lib/Types/Newsletter.js +31 -0
  163. package/lib/Types/Newsletter.js.map +1 -0
  164. package/lib/Types/Product.d.ts +79 -0
  165. package/lib/Types/Product.d.ts.map +1 -0
  166. package/lib/Types/Product.js +2 -0
  167. package/lib/Types/Product.js.map +1 -0
  168. package/lib/Types/Signal.d.ts +76 -0
  169. package/lib/Types/Signal.d.ts.map +1 -0
  170. package/lib/Types/Signal.js +2 -0
  171. package/lib/Types/Signal.js.map +1 -0
  172. package/lib/Types/Socket.d.ts +138 -0
  173. package/lib/Types/Socket.d.ts.map +1 -0
  174. package/lib/Types/Socket.js +3 -0
  175. package/lib/Types/Socket.js.map +1 -0
  176. package/lib/Types/State.d.ts +39 -0
  177. package/lib/Types/State.d.ts.map +1 -0
  178. package/lib/Types/State.js +13 -0
  179. package/lib/Types/State.js.map +1 -0
  180. package/lib/Types/USync.d.ts +26 -0
  181. package/lib/Types/USync.d.ts.map +1 -0
  182. package/lib/Types/USync.js +2 -0
  183. package/lib/Types/USync.js.map +1 -0
  184. package/lib/Types/index.d.ts +65 -0
  185. package/lib/Types/index.d.ts.map +1 -0
  186. package/lib/Types/index.js +26 -0
  187. package/lib/Types/index.js.map +1 -0
  188. package/lib/Utils/auth-utils.d.ts +19 -0
  189. package/lib/Utils/auth-utils.d.ts.map +1 -0
  190. package/lib/Utils/auth-utils.js +474 -0
  191. package/lib/Utils/auth-utils.js.map +1 -0
  192. package/lib/Utils/baileys-event-stream.d.ts +17 -0
  193. package/lib/Utils/baileys-event-stream.d.ts.map +1 -0
  194. package/lib/Utils/baileys-event-stream.js +56 -0
  195. package/lib/Utils/baileys-event-stream.js.map +1 -0
  196. package/lib/Utils/browser-utils.d.ts +4 -0
  197. package/lib/Utils/browser-utils.d.ts.map +1 -0
  198. package/lib/Utils/browser-utils.js +28 -0
  199. package/lib/Utils/browser-utils.js.map +1 -0
  200. package/lib/Utils/business.d.ts +23 -0
  201. package/lib/Utils/business.d.ts.map +1 -0
  202. package/lib/Utils/business.js +231 -0
  203. package/lib/Utils/business.js.map +1 -0
  204. package/lib/Utils/chat-utils.d.ts +71 -0
  205. package/lib/Utils/chat-utils.d.ts.map +1 -0
  206. package/lib/Utils/chat-utils.js +764 -0
  207. package/lib/Utils/chat-utils.js.map +1 -0
  208. package/lib/Utils/crypto.d.ts +41 -0
  209. package/lib/Utils/crypto.d.ts.map +1 -0
  210. package/lib/Utils/crypto.js +142 -0
  211. package/lib/Utils/crypto.js.map +1 -0
  212. package/lib/Utils/decode-wa-message.d.ts +47 -0
  213. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  214. package/lib/Utils/decode-wa-message.js +269 -0
  215. package/lib/Utils/decode-wa-message.js.map +1 -0
  216. package/lib/Utils/event-buffer.d.ts +34 -0
  217. package/lib/Utils/event-buffer.d.ts.map +1 -0
  218. package/lib/Utils/event-buffer.js +547 -0
  219. package/lib/Utils/event-buffer.js.map +1 -0
  220. package/lib/Utils/generics.d.ts +91 -0
  221. package/lib/Utils/generics.d.ts.map +1 -0
  222. package/lib/Utils/generics.js +366 -0
  223. package/lib/Utils/generics.js.map +1 -0
  224. package/lib/Utils/history.d.ts +20 -0
  225. package/lib/Utils/history.d.ts.map +1 -0
  226. package/lib/Utils/history.js +85 -0
  227. package/lib/Utils/history.js.map +1 -0
  228. package/lib/Utils/index.d.ts +21 -0
  229. package/lib/Utils/index.d.ts.map +1 -0
  230. package/lib/Utils/index.js +21 -0
  231. package/lib/Utils/index.js.map +1 -0
  232. package/lib/Utils/link-preview.d.ts +22 -0
  233. package/lib/Utils/link-preview.d.ts.map +1 -0
  234. package/lib/Utils/link-preview.js +85 -0
  235. package/lib/Utils/link-preview.js.map +1 -0
  236. package/lib/Utils/logger.d.ts +12 -0
  237. package/lib/Utils/logger.d.ts.map +1 -0
  238. package/lib/Utils/logger.js +3 -0
  239. package/lib/Utils/logger.js.map +1 -0
  240. package/lib/Utils/lt-hash.d.ts +13 -0
  241. package/lib/Utils/lt-hash.d.ts.map +1 -0
  242. package/lib/Utils/lt-hash.js +48 -0
  243. package/lib/Utils/lt-hash.js.map +1 -0
  244. package/lib/Utils/make-mutex.d.ts +8 -0
  245. package/lib/Utils/make-mutex.d.ts.map +1 -0
  246. package/lib/Utils/make-mutex.js +40 -0
  247. package/lib/Utils/make-mutex.js.map +1 -0
  248. package/lib/Utils/message-retry-manager.d.ts +82 -0
  249. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  250. package/lib/Utils/message-retry-manager.js +149 -0
  251. package/lib/Utils/message-retry-manager.js.map +1 -0
  252. package/lib/Utils/messages-media.d.ts +113 -0
  253. package/lib/Utils/messages-media.d.ts.map +1 -0
  254. package/lib/Utils/messages-media.js +643 -0
  255. package/lib/Utils/messages-media.js.map +1 -0
  256. package/lib/Utils/messages.d.ts +76 -0
  257. package/lib/Utils/messages.d.ts.map +1 -0
  258. package/lib/Utils/messages.js +810 -0
  259. package/lib/Utils/messages.js.map +1 -0
  260. package/lib/Utils/noise-handler.d.ts +20 -0
  261. package/lib/Utils/noise-handler.d.ts.map +1 -0
  262. package/lib/Utils/noise-handler.js +147 -0
  263. package/lib/Utils/noise-handler.js.map +1 -0
  264. package/lib/Utils/process-message.d.ts +43 -0
  265. package/lib/Utils/process-message.d.ts.map +1 -0
  266. package/lib/Utils/process-message.js +384 -0
  267. package/lib/Utils/process-message.js.map +1 -0
  268. package/lib/Utils/proto-utils.d.ts +7 -0
  269. package/lib/Utils/proto-utils.d.ts.map +1 -0
  270. package/lib/Utils/proto-utils.js +7 -0
  271. package/lib/Utils/proto-utils.js.map +1 -0
  272. package/lib/Utils/signal.d.ts +34 -0
  273. package/lib/Utils/signal.d.ts.map +1 -0
  274. package/lib/Utils/signal.js +150 -0
  275. package/lib/Utils/signal.js.map +1 -0
  276. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  277. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  278. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  279. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  280. package/lib/Utils/validate-connection.d.ts +11 -0
  281. package/lib/Utils/validate-connection.d.ts.map +1 -0
  282. package/lib/Utils/validate-connection.js +166 -0
  283. package/lib/Utils/validate-connection.js.map +1 -0
  284. package/lib/WABinary/constants.d.ts +28 -0
  285. package/lib/WABinary/constants.d.ts.map +1 -0
  286. package/lib/WABinary/constants.js +1301 -0
  287. package/lib/WABinary/constants.js.map +1 -0
  288. package/lib/WABinary/decode.d.ts +7 -0
  289. package/lib/WABinary/decode.d.ts.map +1 -0
  290. package/lib/WABinary/decode.js +228 -0
  291. package/lib/WABinary/decode.js.map +1 -0
  292. package/lib/WABinary/encode.d.ts +3 -0
  293. package/lib/WABinary/encode.d.ts.map +1 -0
  294. package/lib/WABinary/encode.js +216 -0
  295. package/lib/WABinary/encode.js.map +1 -0
  296. package/lib/WABinary/generic-utils.d.ts +15 -0
  297. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  298. package/lib/WABinary/generic-utils.js +103 -0
  299. package/lib/WABinary/generic-utils.js.map +1 -0
  300. package/lib/WABinary/index.d.ts +6 -0
  301. package/lib/WABinary/index.d.ts.map +1 -0
  302. package/lib/WABinary/index.js +6 -0
  303. package/lib/WABinary/index.js.map +1 -0
  304. package/lib/WABinary/jid-utils.d.ts +37 -0
  305. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  306. package/lib/WABinary/jid-utils.js +58 -0
  307. package/lib/WABinary/jid-utils.js.map +1 -0
  308. package/lib/WABinary/types.d.ts +19 -0
  309. package/lib/WABinary/types.d.ts.map +1 -0
  310. package/lib/WABinary/types.js +2 -0
  311. package/lib/WABinary/types.js.map +1 -0
  312. package/lib/WAM/BinaryInfo.d.ts +9 -0
  313. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  314. package/lib/WAM/BinaryInfo.js +10 -0
  315. package/lib/WAM/BinaryInfo.js.map +1 -0
  316. package/lib/WAM/constants.d.ts +40 -0
  317. package/lib/WAM/constants.d.ts.map +1 -0
  318. package/lib/WAM/constants.js +15241 -0
  319. package/lib/WAM/constants.js.map +1 -0
  320. package/lib/WAM/encode.d.ts +3 -0
  321. package/lib/WAM/encode.d.ts.map +1 -0
  322. package/lib/WAM/encode.js +150 -0
  323. package/lib/WAM/encode.js.map +1 -0
  324. package/lib/WAM/index.d.ts +4 -0
  325. package/lib/WAM/index.d.ts.map +1 -0
  326. package/lib/WAM/index.js +4 -0
  327. package/lib/WAM/index.js.map +1 -0
  328. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  329. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  330. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  331. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  332. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  333. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  334. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  335. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  336. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  337. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  338. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  339. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  340. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  341. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  342. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  343. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  344. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  345. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  346. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  347. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  348. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  349. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  350. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  351. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  352. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  353. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  354. package/lib/WAUSync/Protocols/index.js +5 -0
  355. package/lib/WAUSync/Protocols/index.js.map +1 -0
  356. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  357. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  358. package/lib/WAUSync/USyncQuery.js +91 -0
  359. package/lib/WAUSync/USyncQuery.js.map +1 -0
  360. package/lib/WAUSync/USyncUser.d.ts +13 -0
  361. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  362. package/lib/WAUSync/USyncUser.js +23 -0
  363. package/lib/WAUSync/USyncUser.js.map +1 -0
  364. package/lib/WAUSync/index.d.ts +4 -0
  365. package/lib/WAUSync/index.d.ts.map +1 -0
  366. package/lib/WAUSync/index.js +4 -0
  367. package/lib/WAUSync/index.js.map +1 -0
  368. package/lib/index.d.ts +12 -0
  369. package/lib/index.d.ts.map +1 -0
  370. package/lib/index.js +11 -0
  371. package/lib/index.js.map +1 -0
  372. package/package.json +37 -0
@@ -0,0 +1,930 @@
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 { WAMessageAddressingMode } from '../Types/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
9
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
10
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
11
+ import { makeNewsletterSocket } from './newsletter.js';
12
+ export const makeMessagesSocket = (config) => {
13
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
14
+ const sock = makeNewsletterSocket(config);
15
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
16
+ const userDevicesCache = config.userDevicesCache ||
17
+ new NodeCache({
18
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
19
+ useClones: false
20
+ });
21
+ const peerSessionsCache = new NodeCache({
22
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
23
+ useClones: false
24
+ });
25
+ // Initialize message retry manager if enabled
26
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
27
+ // Prevent race conditions in Signal session encryption by user
28
+ const encryptionMutex = makeKeyedMutex();
29
+ let mediaConn;
30
+ const refreshMediaConn = async (forceGet = false) => {
31
+ const media = await mediaConn;
32
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
33
+ mediaConn = (async () => {
34
+ const result = await query({
35
+ tag: 'iq',
36
+ attrs: {
37
+ type: 'set',
38
+ xmlns: 'w:m',
39
+ to: S_WHATSAPP_NET
40
+ },
41
+ content: [{ tag: 'media_conn', attrs: {} }]
42
+ });
43
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
44
+ const node = {
45
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
46
+ hostname: attrs.hostname,
47
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
48
+ })),
49
+ auth: mediaConnNode.attrs.auth,
50
+ ttl: +mediaConnNode.attrs.ttl,
51
+ fetchDate: new Date()
52
+ };
53
+ logger.debug('fetched media conn');
54
+ return node;
55
+ })();
56
+ }
57
+ return mediaConn;
58
+ };
59
+ /**
60
+ * generic send receipt function
61
+ * used for receipts of phone call, read, delivery etc.
62
+ * */
63
+ const sendReceipt = async (jid, participant, messageIds, type) => {
64
+ if (!messageIds || messageIds.length === 0) {
65
+ throw new Boom('missing ids in receipt');
66
+ }
67
+ const node = {
68
+ tag: 'receipt',
69
+ attrs: {
70
+ id: messageIds[0]
71
+ }
72
+ };
73
+ const isReadReceipt = type === 'read' || type === 'read-self';
74
+ if (isReadReceipt) {
75
+ node.attrs.t = unixTimestampSeconds().toString();
76
+ }
77
+ if (type === 'sender' && isPnUser(jid)) {
78
+ node.attrs.recipient = jid;
79
+ node.attrs.to = participant;
80
+ }
81
+ else {
82
+ node.attrs.to = jid;
83
+ if (participant) {
84
+ node.attrs.participant = participant;
85
+ }
86
+ }
87
+ if (type) {
88
+ node.attrs.type = type;
89
+ }
90
+ const remainingMessageIds = messageIds.slice(1);
91
+ if (remainingMessageIds.length) {
92
+ node.content = [
93
+ {
94
+ tag: 'list',
95
+ attrs: {},
96
+ content: remainingMessageIds.map(id => ({
97
+ tag: 'item',
98
+ attrs: { id }
99
+ }))
100
+ }
101
+ ];
102
+ }
103
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
104
+ await sendNode(node);
105
+ };
106
+ /** Correctly bulk send receipts to multiple chats, participants */
107
+ const sendReceipts = async (keys, type) => {
108
+ const recps = aggregateMessageKeysNotFromMe(keys);
109
+ for (const { jid, participant, messageIds } of recps) {
110
+ await sendReceipt(jid, participant, messageIds, type);
111
+ }
112
+ };
113
+ /** Bulk read messages. Keys can be from different chats & participants */
114
+ const readMessages = async (keys) => {
115
+ const privacySettings = await fetchPrivacySettings();
116
+ // based on privacy settings, we have to change the read type
117
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
118
+ await sendReceipts(keys, readType);
119
+ };
120
+ const resolveSessionJids = async (jids) => {
121
+ const uniquePnJids = Array.from(new Set(jids.filter(isPnUser)));
122
+ if (!uniquePnJids.length) {
123
+ return new Map();
124
+ }
125
+ const lookups = await Promise.all(uniquePnJids.map(async (pnJid) => {
126
+ try {
127
+ const resolved = await signalRepository.lidMapping.getLIDForPN(pnJid);
128
+ return resolved ? [pnJid, resolved] : [pnJid, pnJid];
129
+ }
130
+ catch (error) {
131
+ logger.warn({ pnJid, error }, 'Failed to resolve LID mapping for PN JID');
132
+ return [pnJid, pnJid];
133
+ }
134
+ }));
135
+ const sessionMap = new Map();
136
+ for (const entry of lookups) {
137
+ if (entry) {
138
+ sessionMap.set(entry[0], entry[1]);
139
+ }
140
+ }
141
+ return sessionMap;
142
+ };
143
+ /** Fetch all the devices we've to send a message to */
144
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
145
+ const deviceResults = [];
146
+ if (!useCache) {
147
+ logger.debug('not using cache for devices');
148
+ }
149
+ const toFetch = [];
150
+ const jidsWithUser = jids
151
+ .map(jid => {
152
+ const decoded = jidDecode(jid);
153
+ const user = decoded?.user;
154
+ const device = decoded?.device;
155
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
156
+ if (isExplicitDevice && user) {
157
+ deviceResults.push({
158
+ user,
159
+ device,
160
+ wireJid: jid // again this makes no sense
161
+ });
162
+ return null;
163
+ }
164
+ jid = jidNormalizedUser(jid);
165
+ return { jid, user };
166
+ })
167
+ .filter(jid => jid !== null);
168
+ let mgetDevices;
169
+ if (useCache && userDevicesCache.mget) {
170
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
171
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
172
+ }
173
+ for (const { jid, user } of jidsWithUser) {
174
+ if (useCache) {
175
+ const devices = mgetDevices?.[user] ||
176
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
177
+ if (devices) {
178
+ const isLidJid = jid.includes('@lid');
179
+ const devicesWithWire = devices.map(d => ({
180
+ ...d,
181
+ wireJid: isLidJid ? jidEncode(d.user, 'lid', d.device) : jidEncode(d.user, 's.whatsapp.net', d.device)
182
+ }));
183
+ deviceResults.push(...devicesWithWire);
184
+ logger.trace({ user }, 'using cache for devices');
185
+ }
186
+ else {
187
+ toFetch.push(jid);
188
+ }
189
+ }
190
+ else {
191
+ toFetch.push(jid);
192
+ }
193
+ }
194
+ if (!toFetch.length) {
195
+ return deviceResults;
196
+ }
197
+ const requestedLidUsers = new Set();
198
+ for (const jid of toFetch) {
199
+ if (jid.includes('@lid')) {
200
+ const user = jidDecode(jid)?.user;
201
+ if (user)
202
+ requestedLidUsers.add(user);
203
+ }
204
+ }
205
+ const query = new USyncQuery().withContext('message').withDeviceProtocol();
206
+ for (const jid of toFetch) {
207
+ 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
208
+ }
209
+ const result = await sock.executeUSyncQuery(query);
210
+ if (result) {
211
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices);
212
+ const deviceMap = {};
213
+ for (const item of extracted) {
214
+ deviceMap[item.user] = deviceMap[item.user] || [];
215
+ deviceMap[item.user]?.push(item);
216
+ }
217
+ // Process each user's devices as a group for bulk LID migration
218
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
219
+ const isLidUser = requestedLidUsers.has(user);
220
+ // Process all devices for this user
221
+ for (const item of userDevices) {
222
+ const finalWireJid = isLidUser
223
+ ? jidEncode(user, 'lid', item.device)
224
+ : jidEncode(item.user, 's.whatsapp.net', item.device);
225
+ deviceResults.push({
226
+ ...item,
227
+ wireJid: finalWireJid
228
+ });
229
+ logger.debug({
230
+ user: item.user,
231
+ device: item.device,
232
+ finalWireJid,
233
+ usedLid: isLidUser
234
+ }, 'Processed device with LID priority');
235
+ }
236
+ }
237
+ if (userDevicesCache.mset) {
238
+ // if the cache supports mset, we can set all devices in one go
239
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
240
+ }
241
+ else {
242
+ for (const key in deviceMap) {
243
+ if (deviceMap[key])
244
+ await userDevicesCache.set(key, deviceMap[key]);
245
+ }
246
+ }
247
+ const userDeviceUpdates = {};
248
+ for (const [userId, devices] of Object.entries(deviceMap)) {
249
+ if (devices && devices.length > 0) {
250
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
251
+ }
252
+ }
253
+ if (Object.keys(userDeviceUpdates).length > 0) {
254
+ try {
255
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
256
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
257
+ }
258
+ catch (error) {
259
+ logger.warn({ error }, 'failed to store user device lists');
260
+ }
261
+ }
262
+ }
263
+ return deviceResults;
264
+ };
265
+ const assertSessions = async (jids) => {
266
+ let didFetchNewSession = false;
267
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
268
+ const jidsRequiringFetch = [];
269
+ // Check peerSessionsCache and authState.keys
270
+ for (const jid of uniqueJids) {
271
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
272
+ const cachedSession = peerSessionsCache.get(signalId);
273
+ if (cachedSession !== undefined) {
274
+ if (cachedSession) {
275
+ continue; // Session exists in cache
276
+ }
277
+ }
278
+ else {
279
+ const sessions = await authState.keys.get('session', [signalId]);
280
+ const hasSession = !!sessions[signalId];
281
+ peerSessionsCache.set(signalId, hasSession);
282
+ if (hasSession) {
283
+ continue;
284
+ }
285
+ }
286
+ jidsRequiringFetch.push(jid);
287
+ }
288
+ if (jidsRequiringFetch.length) {
289
+ logger.debug({ jidsRequiringFetch }, 'fetching sessions');
290
+ const result = await query({
291
+ tag: 'iq',
292
+ attrs: {
293
+ xmlns: 'encrypt',
294
+ type: 'get',
295
+ to: S_WHATSAPP_NET
296
+ },
297
+ content: [
298
+ {
299
+ tag: 'key',
300
+ attrs: {},
301
+ content: jidsRequiringFetch.map(jid => ({
302
+ tag: 'user',
303
+ attrs: { jid }
304
+ }))
305
+ }
306
+ ]
307
+ });
308
+ await parseAndInjectE2ESessions(result, signalRepository);
309
+ didFetchNewSession = true;
310
+ // Cache fetched sessions
311
+ for (const jid of jidsRequiringFetch) {
312
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
313
+ peerSessionsCache.set(signalId, true);
314
+ }
315
+ }
316
+ return didFetchNewSession;
317
+ };
318
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
319
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
320
+ if (!authState.creds.me?.id) {
321
+ throw new Boom('Not authenticated');
322
+ }
323
+ const protocolMessage = {
324
+ protocolMessage: {
325
+ peerDataOperationRequestMessage: pdoMessage,
326
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
327
+ }
328
+ };
329
+ const meJid = jidNormalizedUser(authState.creds.me.id);
330
+ const msgId = await relayMessage(meJid, protocolMessage, {
331
+ additionalAttributes: {
332
+ category: 'peer',
333
+ push_priority: 'high_force'
334
+ }
335
+ });
336
+ return msgId;
337
+ };
338
+ const createParticipantNodesWithSessionMap = async (recipientWireJids, sessionMap, message, extraAttrs, dsmMessage) => {
339
+ if (!recipientWireJids.length) {
340
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
341
+ }
342
+ const patched = await patchMessageBeforeSending(message, recipientWireJids);
343
+ const patchedMessages = Array.isArray(patched)
344
+ ? patched
345
+ : recipientWireJids.map(jid => ({ recipientJid: jid, message: patched }));
346
+ let shouldIncludeDeviceIdentity = false;
347
+ const meId = authState.creds.me.id;
348
+ const meLid = authState.creds.me?.lid;
349
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
350
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: wireJid, message: patchedMessage }) => {
351
+ if (!wireJid)
352
+ return null;
353
+ wireJid = sessionMap.get(wireJid) ?? wireJid;
354
+ let msgToEncrypt = patchedMessage;
355
+ if (dsmMessage) {
356
+ const { user: targetUser } = jidDecode(wireJid);
357
+ const { user: ownPnUser } = jidDecode(meId);
358
+ const ownLidUser = meLidUser;
359
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
360
+ const isExactSenderDevice = wireJid === meId || (meLid && wireJid === meLid);
361
+ if (isOwnUser && !isExactSenderDevice) {
362
+ msgToEncrypt = dsmMessage;
363
+ logger.debug({ wireJid, targetUser }, 'Using DSM for own device');
364
+ }
365
+ }
366
+ const bytes = encodeWAMessage(msgToEncrypt);
367
+ const mutexKey = wireJid;
368
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
369
+ const { type, ciphertext } = await signalRepository.encryptMessage({
370
+ jid: wireJid,
371
+ data: bytes
372
+ });
373
+ if (type === 'pkmsg') {
374
+ shouldIncludeDeviceIdentity = true;
375
+ }
376
+ return {
377
+ tag: 'to',
378
+ attrs: { jid: wireJid },
379
+ content: [
380
+ {
381
+ tag: 'enc',
382
+ attrs: {
383
+ v: '2',
384
+ type,
385
+ ...(extraAttrs || {})
386
+ },
387
+ content: ciphertext
388
+ }
389
+ ]
390
+ };
391
+ });
392
+ return node;
393
+ });
394
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
395
+ return { nodes, shouldIncludeDeviceIdentity };
396
+ };
397
+ const createParticipantNodes = async (recipientWireJids, message, extraAttrs, dsmMessage) => {
398
+ const sessionMap = await resolveSessionJids(recipientWireJids);
399
+ return createParticipantNodesWithSessionMap(recipientWireJids, sessionMap, message, extraAttrs, dsmMessage);
400
+ };
401
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
402
+ const meId = authState.creds.me.id;
403
+ const meLid = authState.creds.me?.lid;
404
+ let shouldIncludeDeviceIdentity = false;
405
+ const statusJid = 'status@broadcast';
406
+ const { user, server } = jidDecode(jid);
407
+ const isGroup = server === 'g.us';
408
+ const isStatus = jid === statusJid;
409
+ const isLid = server === 'lid';
410
+ const isNewsletter = server === 'newsletter';
411
+ const finalJid = jid;
412
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
413
+ // TODO: investigate if this is true
414
+ let ownId = meId;
415
+ if (isLid && meLid) {
416
+ ownId = meLid;
417
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
418
+ }
419
+ else {
420
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
421
+ }
422
+ msgId = msgId || generateMessageIDV2(sock.user?.id);
423
+ useUserDevicesCache = useUserDevicesCache !== false;
424
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
425
+ const participants = [];
426
+ const destinationJid = !isStatus ? finalJid : statusJid;
427
+ const binaryNodeContent = [];
428
+ const devices = [];
429
+ const meMsg = {
430
+ deviceSentMessage: {
431
+ destinationJid,
432
+ message
433
+ },
434
+ messageContextInfo: message.messageContextInfo
435
+ };
436
+ const extraAttrs = {};
437
+ if (participant) {
438
+ if (!isGroup && !isStatus) {
439
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
440
+ }
441
+ const { user, device } = jidDecode(participant.jid);
442
+ devices.push({
443
+ user,
444
+ device,
445
+ wireJid: participant.jid
446
+ });
447
+ }
448
+ await authState.keys.transaction(async () => {
449
+ const mediaType = getMediaType(message);
450
+ if (mediaType) {
451
+ extraAttrs['mediatype'] = mediaType;
452
+ }
453
+ if (isNewsletter) {
454
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
455
+ const bytes = encodeNewsletterMessage(patched);
456
+ binaryNodeContent.push({
457
+ tag: 'plaintext',
458
+ attrs: {},
459
+ content: bytes
460
+ });
461
+ const stanza = {
462
+ tag: 'message',
463
+ attrs: {
464
+ to: jid,
465
+ id: msgId,
466
+ type: getMessageType(message),
467
+ ...(additionalAttributes || {})
468
+ },
469
+ content: binaryNodeContent
470
+ };
471
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
472
+ await sendNode(stanza);
473
+ return;
474
+ }
475
+ if (normalizeMessageContent(message)?.pinInChatMessage) {
476
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
477
+ }
478
+ if (isGroup || isStatus) {
479
+ const [groupData, senderKeyMap] = await Promise.all([
480
+ (async () => {
481
+ 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?
482
+ if (groupData && Array.isArray(groupData?.participants)) {
483
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
484
+ }
485
+ else if (!isStatus) {
486
+ groupData = await groupMetadata(jid);
487
+ }
488
+ return groupData;
489
+ })(),
490
+ (async () => {
491
+ if (!participant && !isStatus) {
492
+ 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?
493
+ return result[jid] || {};
494
+ }
495
+ return {};
496
+ })()
497
+ ]);
498
+ if (!participant) {
499
+ const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
500
+ if (isStatus && statusJidList) {
501
+ participantsList.push(...statusJidList);
502
+ }
503
+ if (!isStatus) {
504
+ const groupAddressingMode = groupData?.addressingMode || (isLid ? WAMessageAddressingMode.LID : WAMessageAddressingMode.PN);
505
+ additionalAttributes = {
506
+ ...additionalAttributes,
507
+ addressing_mode: groupAddressingMode
508
+ };
509
+ }
510
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
511
+ devices.push(...additionalDevices);
512
+ }
513
+ const patched = await patchMessageBeforeSending(message);
514
+ if (Array.isArray(patched)) {
515
+ throw new Boom('Per-jid patching is not supported in groups');
516
+ }
517
+ const bytes = encodeWAMessage(patched);
518
+ const groupAddressingMode = groupData?.addressingMode || (isLid ? 'lid' : 'pn');
519
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
520
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
521
+ group: destinationJid,
522
+ data: bytes,
523
+ meId: groupSenderIdentity
524
+ });
525
+ const deviceSessionMap = await resolveSessionJids(devices.map(d => d.wireJid));
526
+ const senderKeyRecipients = [];
527
+ for (const device of devices) {
528
+ const deviceJid = device.wireJid;
529
+ const hasKey = !!senderKeyMap[deviceJid];
530
+ if (!hasKey || !!participant) {
531
+ senderKeyRecipients.push(deviceJid);
532
+ senderKeyMap[deviceJid] = true;
533
+ }
534
+ }
535
+ if (senderKeyRecipients.length) {
536
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
537
+ const senderKeyMsg = {
538
+ senderKeyDistributionMessage: {
539
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
540
+ groupId: destinationJid
541
+ }
542
+ };
543
+ const senderKeySessionTargets = senderKeyRecipients.map(jid => deviceSessionMap.get(jid) ?? jid);
544
+ await assertSessions(senderKeySessionTargets);
545
+ const result = await createParticipantNodesWithSessionMap(senderKeyRecipients, deviceSessionMap, senderKeyMsg, extraAttrs);
546
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
547
+ participants.push(...result.nodes);
548
+ }
549
+ binaryNodeContent.push({
550
+ tag: 'enc',
551
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
552
+ content: ciphertext
553
+ });
554
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
555
+ }
556
+ else {
557
+ const { user: ownUser } = jidDecode(ownId);
558
+ if (!participant) {
559
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
560
+ devices.push({
561
+ user,
562
+ device: 0,
563
+ wireJid: jidEncode(user, targetUserServer, 0)
564
+ });
565
+ // Own user matches conversation addressing mode
566
+ if (user !== ownUser) {
567
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
568
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
569
+ devices.push({
570
+ user: ownUserForAddressing,
571
+ device: 0,
572
+ wireJid: jidEncode(ownUserForAddressing, ownUserServer, 0)
573
+ });
574
+ }
575
+ if (additionalAttributes?.['category'] !== 'peer') {
576
+ // Clear placeholders and enumerate actual devices
577
+ devices.length = 0;
578
+ // Use conversation-appropriate sender identity
579
+ const senderIdentity = isLid && meLid
580
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
581
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
582
+ // Enumerate devices for sender and target with consistent addressing
583
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
584
+ devices.push(...sessionDevices);
585
+ logger.debug({
586
+ deviceCount: devices.length,
587
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.wireJid)?.server}`)
588
+ }, 'Device enumeration complete with unified addressing');
589
+ }
590
+ }
591
+ const allRecipients = [];
592
+ const meRecipients = [];
593
+ const otherRecipients = [];
594
+ const { user: mePnUser } = jidDecode(meId);
595
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
596
+ for (const { user, wireJid } of devices) {
597
+ const isExactSenderDevice = wireJid === meId || (meLid && wireJid === meLid);
598
+ if (isExactSenderDevice) {
599
+ logger.debug({ wireJid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
600
+ continue;
601
+ }
602
+ // Check if this is our device (could match either PN or LID user)
603
+ const isMe = user === mePnUser || (meLidUser && user === meLidUser);
604
+ if (isMe) {
605
+ meRecipients.push(wireJid);
606
+ }
607
+ else {
608
+ otherRecipients.push(wireJid);
609
+ }
610
+ allRecipients.push(wireJid);
611
+ }
612
+ const deviceSessionMap = await resolveSessionJids(devices.map(d => d.wireJid));
613
+ const sessionTargets = allRecipients.map(jid => deviceSessionMap.get(jid) ?? jid);
614
+ await assertSessions(sessionTargets);
615
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
616
+ // For own devices: use DSM if available (1:1 chats only)
617
+ createParticipantNodesWithSessionMap(meRecipients, deviceSessionMap, meMsg || message, extraAttrs),
618
+ createParticipantNodesWithSessionMap(otherRecipients, deviceSessionMap, message, extraAttrs, meMsg)
619
+ ]);
620
+ participants.push(...meNodes);
621
+ participants.push(...otherNodes);
622
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
623
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
624
+ }
625
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
626
+ }
627
+ if (participants.length) {
628
+ if (additionalAttributes?.['category'] === 'peer') {
629
+ const peerNode = participants[0]?.content?.[0];
630
+ if (peerNode) {
631
+ binaryNodeContent.push(peerNode); // push only enc
632
+ }
633
+ }
634
+ else {
635
+ binaryNodeContent.push({
636
+ tag: 'participants',
637
+ attrs: {},
638
+ content: participants
639
+ });
640
+ }
641
+ }
642
+ const stanza = {
643
+ tag: 'message',
644
+ attrs: {
645
+ id: msgId,
646
+ to: destinationJid,
647
+ type: getMessageType(message),
648
+ ...(additionalAttributes || {})
649
+ },
650
+ content: binaryNodeContent
651
+ };
652
+ // if the participant to send to is explicitly specified (generally retry recp)
653
+ // ensure the message is only sent to that person
654
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
655
+ if (participant) {
656
+ if (isJidGroup(destinationJid)) {
657
+ stanza.attrs.to = destinationJid;
658
+ stanza.attrs.participant = participant.jid;
659
+ }
660
+ else if (areJidsSameUser(participant.jid, meId)) {
661
+ stanza.attrs.to = participant.jid;
662
+ stanza.attrs.recipient = destinationJid;
663
+ }
664
+ else {
665
+ stanza.attrs.to = participant.jid;
666
+ }
667
+ }
668
+ else {
669
+ stanza.attrs.to = destinationJid;
670
+ }
671
+ if (shouldIncludeDeviceIdentity) {
672
+ ;
673
+ stanza.content.push({
674
+ tag: 'device-identity',
675
+ attrs: {},
676
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
677
+ });
678
+ logger.debug({ jid }, 'adding device identity');
679
+ }
680
+ if (additionalNodes && additionalNodes.length > 0) {
681
+ ;
682
+ stanza.content.push(...additionalNodes);
683
+ }
684
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
685
+ await sendNode(stanza);
686
+ // Add message to retry cache if enabled
687
+ if (messageRetryManager && !participant) {
688
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
689
+ }
690
+ }, meId);
691
+ return msgId;
692
+ };
693
+ const getMessageType = (message) => {
694
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
695
+ return 'poll';
696
+ }
697
+ if (message.eventMessage) {
698
+ return 'event';
699
+ }
700
+ if (getMediaType(message) !== '') {
701
+ return 'media';
702
+ }
703
+ return 'text';
704
+ };
705
+ const getMediaType = (message) => {
706
+ if (message.imageMessage) {
707
+ return 'image';
708
+ }
709
+ else if (message.videoMessage) {
710
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
711
+ }
712
+ else if (message.audioMessage) {
713
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
714
+ }
715
+ else if (message.contactMessage) {
716
+ return 'vcard';
717
+ }
718
+ else if (message.documentMessage) {
719
+ return 'document';
720
+ }
721
+ else if (message.contactsArrayMessage) {
722
+ return 'contact_array';
723
+ }
724
+ else if (message.liveLocationMessage) {
725
+ return 'livelocation';
726
+ }
727
+ else if (message.stickerMessage) {
728
+ return 'sticker';
729
+ }
730
+ else if (message.listMessage) {
731
+ return 'list';
732
+ }
733
+ else if (message.listResponseMessage) {
734
+ return 'list_response';
735
+ }
736
+ else if (message.buttonsResponseMessage) {
737
+ return 'buttons_response';
738
+ }
739
+ else if (message.orderMessage) {
740
+ return 'order';
741
+ }
742
+ else if (message.productMessage) {
743
+ return 'product';
744
+ }
745
+ else if (message.interactiveResponseMessage) {
746
+ return 'native_flow_response';
747
+ }
748
+ else if (message.groupInviteMessage) {
749
+ return 'url';
750
+ }
751
+ return '';
752
+ };
753
+ const getPrivacyTokens = async (jids) => {
754
+ const t = unixTimestampSeconds().toString();
755
+ const result = await query({
756
+ tag: 'iq',
757
+ attrs: {
758
+ to: S_WHATSAPP_NET,
759
+ type: 'set',
760
+ xmlns: 'privacy'
761
+ },
762
+ content: [
763
+ {
764
+ tag: 'tokens',
765
+ attrs: {},
766
+ content: jids.map(jid => ({
767
+ tag: 'token',
768
+ attrs: {
769
+ jid: jidNormalizedUser(jid),
770
+ t,
771
+ type: 'trusted_contact'
772
+ }
773
+ }))
774
+ }
775
+ ]
776
+ });
777
+ return result;
778
+ };
779
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
780
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
781
+ return {
782
+ ...sock,
783
+ getPrivacyTokens,
784
+ assertSessions,
785
+ relayMessage,
786
+ sendReceipt,
787
+ sendReceipts,
788
+ readMessages,
789
+ refreshMediaConn,
790
+ waUploadToServer,
791
+ fetchPrivacySettings,
792
+ sendPeerDataOperationMessage,
793
+ createParticipantNodes,
794
+ getUSyncDevices,
795
+ messageRetryManager,
796
+ updateMediaMessage: async (message) => {
797
+ const content = assertMediaContent(message.message);
798
+ const mediaKey = content.mediaKey;
799
+ const meId = authState.creds.me.id;
800
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
801
+ let error = undefined;
802
+ await Promise.all([
803
+ sendNode(node),
804
+ waitForMsgMediaUpdate(async (update) => {
805
+ const result = update.find(c => c.key.id === message.key.id);
806
+ if (result) {
807
+ if (result.error) {
808
+ error = result.error;
809
+ }
810
+ else {
811
+ try {
812
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
813
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
814
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
815
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
816
+ data: media,
817
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
818
+ });
819
+ }
820
+ content.directPath = media.directPath;
821
+ content.url = getUrlFromDirectPath(content.directPath);
822
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
823
+ }
824
+ catch (err) {
825
+ error = err;
826
+ }
827
+ }
828
+ return true;
829
+ }
830
+ })
831
+ ]);
832
+ if (error) {
833
+ throw error;
834
+ }
835
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
836
+ return message;
837
+ },
838
+ sendMessage: async (jid, content, options = {}) => {
839
+ const userJid = authState.creds.me.id;
840
+ if (typeof content === 'object' &&
841
+ 'disappearingMessagesInChat' in content &&
842
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
843
+ isJidGroup(jid)) {
844
+ const { disappearingMessagesInChat } = content;
845
+ const value = typeof disappearingMessagesInChat === 'boolean'
846
+ ? disappearingMessagesInChat
847
+ ? WA_DEFAULT_EPHEMERAL
848
+ : 0
849
+ : disappearingMessagesInChat;
850
+ await groupToggleEphemeral(jid, value);
851
+ }
852
+ else {
853
+ const fullMsg = await generateWAMessage(jid, content, {
854
+ logger,
855
+ userJid,
856
+ getUrlInfo: text => getUrlInfo(text, {
857
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
858
+ fetchOpts: {
859
+ timeout: 3000,
860
+ ...(axiosOptions || {})
861
+ },
862
+ logger,
863
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
864
+ }),
865
+ //TODO: CACHE
866
+ getProfilePicUrl: sock.profilePictureUrl,
867
+ getCallLink: sock.createCallLink,
868
+ upload: waUploadToServer,
869
+ mediaCache: config.mediaCache,
870
+ options: config.options,
871
+ messageId: generateMessageIDV2(sock.user?.id),
872
+ ...options
873
+ });
874
+ const isEventMsg = 'event' in content && !!content.event;
875
+ const isDeleteMsg = 'delete' in content && !!content.delete;
876
+ const isEditMsg = 'edit' in content && !!content.edit;
877
+ const isPinMsg = 'pin' in content && !!content.pin;
878
+ const isPollMessage = 'poll' in content && !!content.poll;
879
+ const additionalAttributes = {};
880
+ const additionalNodes = [];
881
+ // required for delete
882
+ if (isDeleteMsg) {
883
+ // if the chat is a group, and I am not the author, then delete the message as an admin
884
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
885
+ additionalAttributes.edit = '8';
886
+ }
887
+ else {
888
+ additionalAttributes.edit = '7';
889
+ }
890
+ }
891
+ else if (isEditMsg) {
892
+ additionalAttributes.edit = '1';
893
+ }
894
+ else if (isPinMsg) {
895
+ additionalAttributes.edit = '2';
896
+ }
897
+ else if (isPollMessage) {
898
+ additionalNodes.push({
899
+ tag: 'meta',
900
+ attrs: {
901
+ polltype: 'creation'
902
+ }
903
+ });
904
+ }
905
+ else if (isEventMsg) {
906
+ additionalNodes.push({
907
+ tag: 'meta',
908
+ attrs: {
909
+ event_type: 'creation'
910
+ }
911
+ });
912
+ }
913
+ await relayMessage(jid, fullMsg.message, {
914
+ messageId: fullMsg.key.id,
915
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
916
+ additionalAttributes,
917
+ statusJidList: options.statusJidList,
918
+ additionalNodes
919
+ });
920
+ if (config.emitOwnEvents) {
921
+ process.nextTick(() => {
922
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
923
+ });
924
+ }
925
+ return fullMsg;
926
+ }
927
+ }
928
+ };
929
+ };
930
+ //# sourceMappingURL=messages-send.js.map