@nuiisweety/baileys 0.1.0

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