@neykoor/baileys 7.0.0-rc13

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