anya-bail 1.0.1

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