@twsxtd/baileys 7.0.0-rc.9.commit.02a305a1ee38

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