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