xero-wa 1.0.10

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