@xsat10/baileys-xsat 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (424) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +38 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +2213 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +139 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +19 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +38 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +87 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +79 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +27 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +33 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +68 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +54 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +48 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +88 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +33 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +575 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +309 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +27 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +18 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +62 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +217 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +375 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +124 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1328 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +522 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/fake-chat.js +96 -0
  94. package/lib/Socket/graphql.js +724 -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 +430 -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 +21 -0
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/interop.js +466 -0
  104. package/lib/Socket/luxu.js +422 -0
  105. package/lib/Socket/messages-recv.d.ts +203 -0
  106. package/lib/Socket/messages-recv.d.ts.map +1 -0
  107. package/lib/Socket/messages-recv.js +2408 -0
  108. package/lib/Socket/messages-recv.js.map +1 -0
  109. package/lib/Socket/messages-send.d.ts +199 -0
  110. package/lib/Socket/messages-send.d.ts.map +1 -0
  111. package/lib/Socket/messages-send.js +1681 -0
  112. package/lib/Socket/messages-send.js.map +1 -0
  113. package/lib/Socket/mex.d.ts +3 -0
  114. package/lib/Socket/mex.d.ts.map +1 -0
  115. package/lib/Socket/mex.js +55 -0
  116. package/lib/Socket/mex.js.map +1 -0
  117. package/lib/Socket/newsletter.d.ts +170 -0
  118. package/lib/Socket/newsletter.d.ts.map +1 -0
  119. package/lib/Socket/newsletter.js +231 -0
  120. package/lib/Socket/newsletter.js.map +1 -0
  121. package/lib/Socket/privacy.js +321 -0
  122. package/lib/Socket/socket.d.ts +59 -0
  123. package/lib/Socket/socket.d.ts.map +1 -0
  124. package/lib/Socket/socket.js +1039 -0
  125. package/lib/Socket/socket.js.map +1 -0
  126. package/lib/Socket/spam-report.js +94 -0
  127. package/lib/Socket/username.js +239 -0
  128. package/lib/Store/index.d.ts +3 -0
  129. package/lib/Store/index.js +10 -0
  130. package/lib/Store/keyed-db.js +112 -0
  131. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  132. package/lib/Store/make-cache-manager-store.js +82 -0
  133. package/lib/Store/make-in-memory-store.d.ts +118 -0
  134. package/lib/Store/make-in-memory-store.js +429 -0
  135. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  136. package/lib/Store/make-ordered-dictionary.js +81 -0
  137. package/lib/Store/object-repository.d.ts +10 -0
  138. package/lib/Store/object-repository.js +27 -0
  139. package/lib/Store/reporting-info-store.js +73 -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 +5 -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 +5 -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 +5 -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 +5 -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 +3 -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 +5 -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 +31 -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 +13 -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 +23 -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 +43 -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 +5 -0
  187. package/lib/Types/Product.js.map +1 -0
  188. package/lib/Types/Signal.d.ts +87 -0
  189. package/lib/Types/Signal.d.ts.map +1 -0
  190. package/lib/Types/Signal.js +3 -0
  191. package/lib/Types/Signal.js.map +1 -0
  192. package/lib/Types/Socket.d.ts +136 -0
  193. package/lib/Types/Socket.d.ts.map +1 -0
  194. package/lib/Types/Socket.js +4 -0
  195. package/lib/Types/Socket.js.map +1 -0
  196. package/lib/Types/State.d.ts +97 -0
  197. package/lib/Types/State.d.ts.map +1 -0
  198. package/lib/Types/State.js +62 -0
  199. package/lib/Types/State.js.map +1 -0
  200. package/lib/Types/USync.d.ts +26 -0
  201. package/lib/Types/USync.d.ts.map +1 -0
  202. package/lib/Types/USync.js +3 -0
  203. package/lib/Types/USync.js.map +1 -0
  204. package/lib/Types/index.d.ts +65 -0
  205. package/lib/Types/index.d.ts.map +1 -0
  206. package/lib/Types/index.js +167 -0
  207. package/lib/Types/index.js.map +1 -0
  208. package/lib/Utils/auth-utils.d.ts +24 -0
  209. package/lib/Utils/auth-utils.d.ts.map +1 -0
  210. package/lib/Utils/auth-utils.js +332 -0
  211. package/lib/Utils/auth-utils.js.map +1 -0
  212. package/lib/Utils/browser-utils.d.ts +4 -0
  213. package/lib/Utils/browser-utils.d.ts.map +1 -0
  214. package/lib/Utils/browser-utils.js +39 -0
  215. package/lib/Utils/browser-utils.js.map +1 -0
  216. package/lib/Utils/business.d.ts +23 -0
  217. package/lib/Utils/business.d.ts.map +1 -0
  218. package/lib/Utils/business.js +247 -0
  219. package/lib/Utils/business.js.map +1 -0
  220. package/lib/Utils/chat-utils.d.ts +100 -0
  221. package/lib/Utils/chat-utils.d.ts.map +1 -0
  222. package/lib/Utils/chat-utils.js +971 -0
  223. package/lib/Utils/chat-utils.js.map +1 -0
  224. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  225. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  226. package/lib/Utils/companion-reg-client-utils.js +43 -0
  227. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  228. package/lib/Utils/crypto.d.ts +37 -0
  229. package/lib/Utils/crypto.d.ts.map +1 -0
  230. package/lib/Utils/crypto.js +160 -0
  231. package/lib/Utils/crypto.js.map +1 -0
  232. package/lib/Utils/decode-wa-message.d.ts +66 -0
  233. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  234. package/lib/Utils/decode-wa-message.js +380 -0
  235. package/lib/Utils/decode-wa-message.js.map +1 -0
  236. package/lib/Utils/event-buffer.d.ts +36 -0
  237. package/lib/Utils/event-buffer.d.ts.map +1 -0
  238. package/lib/Utils/event-buffer.js +666 -0
  239. package/lib/Utils/event-buffer.js.map +1 -0
  240. package/lib/Utils/fake-chat-utils.js +57 -0
  241. package/lib/Utils/generics.d.ts +91 -0
  242. package/lib/Utils/generics.d.ts.map +1 -0
  243. package/lib/Utils/generics.js +458 -0
  244. package/lib/Utils/generics.js.map +1 -0
  245. package/lib/Utils/history.d.ts +24 -0
  246. package/lib/Utils/history.d.ts.map +1 -0
  247. package/lib/Utils/history.js +160 -0
  248. package/lib/Utils/history.js.map +1 -0
  249. package/lib/Utils/identity-change-handler.d.ts +44 -0
  250. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  251. package/lib/Utils/identity-change-handler.js +94 -0
  252. package/lib/Utils/identity-change-handler.js.map +1 -0
  253. package/lib/Utils/index.d.ts +22 -0
  254. package/lib/Utils/index.d.ts.map +1 -0
  255. package/lib/Utils/index.js +258 -0
  256. package/lib/Utils/index.js.map +1 -0
  257. package/lib/Utils/link-preview.d.ts +21 -0
  258. package/lib/Utils/link-preview.d.ts.map +1 -0
  259. package/lib/Utils/link-preview.js +102 -0
  260. package/lib/Utils/link-preview.js.map +1 -0
  261. package/lib/Utils/logger.d.ts +12 -0
  262. package/lib/Utils/logger.d.ts.map +1 -0
  263. package/lib/Utils/logger.js +11 -0
  264. package/lib/Utils/logger.js.map +1 -0
  265. package/lib/Utils/lt-hash.d.ts +8 -0
  266. package/lib/Utils/lt-hash.d.ts.map +1 -0
  267. package/lib/Utils/lt-hash.js +14 -0
  268. package/lib/Utils/lt-hash.js.map +1 -0
  269. package/lib/Utils/make-mutex.d.ts +9 -0
  270. package/lib/Utils/make-mutex.d.ts.map +1 -0
  271. package/lib/Utils/make-mutex.js +43 -0
  272. package/lib/Utils/make-mutex.js.map +1 -0
  273. package/lib/Utils/message-composer.js +288 -0
  274. package/lib/Utils/message-retry-manager.d.ts +115 -0
  275. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  276. package/lib/Utils/message-retry-manager.js +283 -0
  277. package/lib/Utils/message-retry-manager.js.map +1 -0
  278. package/lib/Utils/messages-media.d.ts +133 -0
  279. package/lib/Utils/messages-media.d.ts.map +1 -0
  280. package/lib/Utils/messages-media.js +914 -0
  281. package/lib/Utils/messages-media.js.map +1 -0
  282. package/lib/Utils/messages.d.ts +91 -0
  283. package/lib/Utils/messages.d.ts.map +1 -0
  284. package/lib/Utils/messages.js +963 -0
  285. package/lib/Utils/messages.js.map +1 -0
  286. package/lib/Utils/noise-handler.d.ts +20 -0
  287. package/lib/Utils/noise-handler.d.ts.map +1 -0
  288. package/lib/Utils/noise-handler.js +238 -0
  289. package/lib/Utils/noise-handler.js.map +1 -0
  290. package/lib/Utils/offline-node-processor.d.ts +17 -0
  291. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  292. package/lib/Utils/offline-node-processor.js +54 -0
  293. package/lib/Utils/offline-node-processor.js.map +1 -0
  294. package/lib/Utils/pre-key-manager.d.ts +28 -0
  295. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  296. package/lib/Utils/pre-key-manager.js +109 -0
  297. package/lib/Utils/pre-key-manager.js.map +1 -0
  298. package/lib/Utils/process-message.d.ts +60 -0
  299. package/lib/Utils/process-message.d.ts.map +1 -0
  300. package/lib/Utils/process-message.js +710 -0
  301. package/lib/Utils/process-message.js.map +1 -0
  302. package/lib/Utils/reporting-utils.d.ts +11 -0
  303. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  304. package/lib/Utils/reporting-utils.js +586 -0
  305. package/lib/Utils/reporting-utils.js.map +1 -0
  306. package/lib/Utils/signal.d.ts +47 -0
  307. package/lib/Utils/signal.d.ts.map +1 -0
  308. package/lib/Utils/signal.js +279 -0
  309. package/lib/Utils/signal.js.map +1 -0
  310. package/lib/Utils/spam-report-utils.js +209 -0
  311. package/lib/Utils/stanza-ack.d.ts +11 -0
  312. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  313. package/lib/Utils/stanza-ack.js +47 -0
  314. package/lib/Utils/stanza-ack.js.map +1 -0
  315. package/lib/Utils/sync-action-utils.d.ts +19 -0
  316. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  317. package/lib/Utils/sync-action-utils.js +61 -0
  318. package/lib/Utils/sync-action-utils.js.map +1 -0
  319. package/lib/Utils/tc-token-utils.d.ts +37 -0
  320. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  321. package/lib/Utils/tc-token-utils.js +176 -0
  322. package/lib/Utils/tc-token-utils.js.map +1 -0
  323. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  324. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  325. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  326. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  327. package/lib/Utils/validate-connection.d.ts +11 -0
  328. package/lib/Utils/validate-connection.d.ts.map +1 -0
  329. package/lib/Utils/validate-connection.js +229 -0
  330. package/lib/Utils/validate-connection.js.map +1 -0
  331. package/lib/WABinary/constants.d.ts +28 -0
  332. package/lib/WABinary/constants.d.ts.map +1 -0
  333. package/lib/WABinary/constants.js +42 -0
  334. package/lib/WABinary/constants.js.map +1 -0
  335. package/lib/WABinary/decode.d.ts +7 -0
  336. package/lib/WABinary/decode.d.ts.map +1 -0
  337. package/lib/WABinary/decode.js +271 -0
  338. package/lib/WABinary/decode.js.map +1 -0
  339. package/lib/WABinary/encode.d.ts +3 -0
  340. package/lib/WABinary/encode.d.ts.map +1 -0
  341. package/lib/WABinary/encode.js +226 -0
  342. package/lib/WABinary/encode.js.map +1 -0
  343. package/lib/WABinary/generic-utils.d.ts +15 -0
  344. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  345. package/lib/WABinary/generic-utils.js +219 -0
  346. package/lib/WABinary/generic-utils.js.map +1 -0
  347. package/lib/WABinary/index.d.ts +6 -0
  348. package/lib/WABinary/index.d.ts.map +1 -0
  349. package/lib/WABinary/index.js +60 -0
  350. package/lib/WABinary/index.js.map +1 -0
  351. package/lib/WABinary/jid-utils.d.ts +48 -0
  352. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  353. package/lib/WABinary/jid-utils.js +123 -0
  354. package/lib/WABinary/jid-utils.js.map +1 -0
  355. package/lib/WABinary/types.d.ts +19 -0
  356. package/lib/WABinary/types.d.ts.map +1 -0
  357. package/lib/WABinary/types.js +4 -0
  358. package/lib/WABinary/types.js.map +1 -0
  359. package/lib/WAM/BinaryInfo.d.ts +9 -0
  360. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  361. package/lib/WAM/BinaryInfo.js +17 -0
  362. package/lib/WAM/BinaryInfo.js.map +1 -0
  363. package/lib/WAM/constants.d.ts +40 -0
  364. package/lib/WAM/constants.d.ts.map +1 -0
  365. package/lib/WAM/constants.js +1 -0
  366. package/lib/WAM/constants.js.map +1 -0
  367. package/lib/WAM/encode.d.ts +3 -0
  368. package/lib/WAM/encode.d.ts.map +1 -0
  369. package/lib/WAM/encode.js +150 -0
  370. package/lib/WAM/encode.js.map +1 -0
  371. package/lib/WAM/index.d.ts +4 -0
  372. package/lib/WAM/index.d.ts.map +1 -0
  373. package/lib/WAM/index.js +38 -0
  374. package/lib/WAM/index.js.map +1 -0
  375. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  376. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  377. package/lib/WAUSync/Protocols/USyncContactProtocol.js +63 -0
  378. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  379. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  380. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  381. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  382. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  383. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  384. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  385. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +34 -0
  386. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  387. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  388. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  389. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +43 -0
  390. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  391. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  392. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  393. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  395. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  396. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  397. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +68 -0
  398. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  399. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  400. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  401. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +37 -0
  402. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  403. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  404. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  405. package/lib/WAUSync/Protocols/index.js +60 -0
  406. package/lib/WAUSync/Protocols/index.js.map +1 -0
  407. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  408. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  409. package/lib/WAUSync/USyncQuery.js +103 -0
  410. package/lib/WAUSync/USyncQuery.js.map +1 -0
  411. package/lib/WAUSync/USyncUser.d.ts +17 -0
  412. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  413. package/lib/WAUSync/USyncUser.js +54 -0
  414. package/lib/WAUSync/USyncUser.js.map +1 -0
  415. package/lib/WAUSync/index.d.ts +4 -0
  416. package/lib/WAUSync/index.d.ts.map +1 -0
  417. package/lib/WAUSync/index.js +38 -0
  418. package/lib/WAUSync/index.js.map +1 -0
  419. package/lib/index.d.ts +13 -0
  420. package/lib/index.d.ts.map +1 -0
  421. package/lib/index.js +129 -0
  422. package/lib/index.js.map +1 -0
  423. package/package.json +77 -0
  424. package/scripts/patch-deps.js +35 -0
@@ -0,0 +1,2408 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.makeMessagesRecvSocket = void 0;
7
+ var _nodeCache = _interopRequireDefault(require("@cacheable/node-cache"));
8
+ var _boom = require("@hapi/boom");
9
+ var _crypto = require("crypto");
10
+ var _long = _interopRequireDefault(require("long"));
11
+ var _index = require("../../WAProto/index.js");
12
+ var _index2 = require("../Defaults/index.js");
13
+ var _index3 = require("../Types/index.js");
14
+ var _index4 = require("../Utils/index.js");
15
+ var _makeMutex = require("../Utils/make-mutex.js");
16
+ var _offlineNodeProcessor = require("../Utils/offline-node-processor.js");
17
+ var _stanzaAck = require("../Utils/stanza-ack.js");
18
+ var _tcTokenUtils = require("../Utils/tc-token-utils.js");
19
+ var _index5 = require("../WABinary/index.js");
20
+ var _groups = require("./groups.js");
21
+ var _messagesSend = require("./messages-send.js");
22
+ var _reportingInfoStore = require("../Store/reporting-info-store.js");
23
+ var _spamReportUtils = require("../Utils/spam-report-utils.js");
24
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
25
+ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(_index3.ReachoutTimelockEnforcementType));
26
+ function isValidEnforcementType(value) {
27
+ return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
28
+ }
29
+ const makeMessagesRecvSocket = config => {
30
+ if (!config.reportingInfoStore) {
31
+ config.reportingInfoStore = (0, _reportingInfoStore.createReportingInfoStore)();
32
+ }
33
+ const reportingInfoStore = config.reportingInfoStore;
34
+ const {
35
+ logger,
36
+ retryRequestDelayMs,
37
+ maxMsgRetryCount,
38
+ getMessage,
39
+ shouldIgnoreJid,
40
+ enableAutoSessionRecreation
41
+ } = config;
42
+ const sock = (0, _messagesSend.makeMessagesSocket)(config);
43
+ const {
44
+ userDevicesCache,
45
+ devicesMutex,
46
+ ev,
47
+ authState,
48
+ ws,
49
+ messageMutex,
50
+ notificationMutex,
51
+ receiptMutex,
52
+ signalRepository,
53
+ query,
54
+ upsertMessage,
55
+ resyncAppState,
56
+ onUnexpectedError,
57
+ assertSessions,
58
+ sendNode,
59
+ sendMessage,
60
+ relayMessage,
61
+ sendReceipt,
62
+ uploadPreKeys,
63
+ sendPeerDataOperationMessage,
64
+ messageRetryManager,
65
+ registerSocketEndHandler,
66
+ issuePrivacyTokens,
67
+ fetchAccountReachoutTimelock,
68
+ placeholderResendCache
69
+ } = sock;
70
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
71
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
72
+ const retryMutex = (0, _makeMutex.makeMutex)();
73
+ const msgRetryCache = config.msgRetryCounterCache || new _nodeCache.default({
74
+ stdTTL: _index2.DEFAULT_CACHE_TTLS.MSG_RETRY,
75
+ // 1 hour
76
+ useClones: false
77
+ });
78
+ const callOfferCache = config.callOfferCache || new _nodeCache.default({
79
+ stdTTL: _index2.DEFAULT_CACHE_TTLS.CALL_OFFER,
80
+ // 5 mins
81
+ useClones: false
82
+ });
83
+ // Debounce identity-change session refreshes per JID to avoid bursts
84
+ const identityAssertDebounce = new _nodeCache.default({
85
+ stdTTL: 5,
86
+ useClones: false
87
+ });
88
+ let sendActiveReceipts = false;
89
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
90
+ if (!authState.creds.me?.id) {
91
+ throw new _boom.Boom('Not authenticated');
92
+ }
93
+ const pdoMessage = {
94
+ historySyncOnDemandRequest: {
95
+ chatJid: oldestMsgKey.remoteJid,
96
+ oldestMsgFromMe: oldestMsgKey.fromMe,
97
+ oldestMsgId: oldestMsgKey.id,
98
+ oldestMsgTimestampMs: oldestMsgTimestamp,
99
+ onDemandMsgCount: count
100
+ },
101
+ peerDataOperationRequestType: _index.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
102
+ };
103
+ return sendPeerDataOperationMessage(pdoMessage);
104
+ };
105
+ const requestPlaceholderResend = async (messageKey, msgData) => {
106
+ if (!authState.creds.me?.id) {
107
+ throw new _boom.Boom('Not authenticated');
108
+ }
109
+ if (await placeholderResendCache.get(messageKey?.id)) {
110
+ logger.debug({
111
+ messageKey
112
+ }, 'already requested resend');
113
+ return;
114
+ } else {
115
+ // Store original message data so PDO response handler can preserve
116
+ // metadata (LID details, timestamps, etc.) that the phone may omit
117
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
118
+ }
119
+ await (0, _index4.delay)(2000);
120
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
121
+ logger.debug({
122
+ messageKey
123
+ }, 'message received while resend requested');
124
+ return 'RESOLVED';
125
+ }
126
+ const pdoMessage = {
127
+ placeholderMessageResendRequest: [{
128
+ messageKey
129
+ }],
130
+ peerDataOperationRequestType: _index.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
131
+ };
132
+ setTimeout(async () => {
133
+ if (await placeholderResendCache.get(messageKey?.id)) {
134
+ logger.debug({
135
+ messageKey
136
+ }, 'PDO message without response after 8 seconds. Phone possibly offline');
137
+ await placeholderResendCache.del(messageKey?.id);
138
+ }
139
+ }, 8000);
140
+ return sendPeerDataOperationMessage(pdoMessage);
141
+ };
142
+ const handleMexNotification = async node => {
143
+ const updateNode = (0, _index5.getBinaryNodeChild)(node, 'update');
144
+ if (updateNode) {
145
+ const opName = updateNode.attrs?.op_name;
146
+ if (!opName) {
147
+ logger.warn({
148
+ node: (0, _index5.binaryNodeToString)(node)
149
+ }, 'mex notification missing op_name, fallback to legacy');
150
+ await handleLegacyMexNewsletterNotification(node);
151
+ return;
152
+ }
153
+ let mexResponse;
154
+ try {
155
+ mexResponse = JSON.parse(updateNode.content.toString());
156
+ } catch (error) {
157
+ logger.error({
158
+ err: error,
159
+ opName
160
+ }, 'failed to parse mex notification JSON');
161
+ return;
162
+ }
163
+ if (mexResponse.errors?.length) {
164
+ logger.warn({
165
+ errors: mexResponse.errors,
166
+ opName
167
+ }, 'mex notification has GQL errors');
168
+ return;
169
+ }
170
+ const data = mexResponse.data;
171
+ if (!data) {
172
+ logger.warn({
173
+ opName
174
+ }, 'mex notification has null data');
175
+ return;
176
+ }
177
+ logger.debug({
178
+ opName
179
+ }, 'processing mex notification');
180
+ switch (opName) {
181
+ case 'NotificationUserReachoutTimelockUpdate':
182
+ handleReachoutTimelockNotification(data);
183
+ break;
184
+ case 'MessageCappingInfoNotification':
185
+ handleMessageCappingNotification(data);
186
+ break;
187
+ // newsletter ops still use the legacy <mex> child structure
188
+ case 'NotificationNewsletterUpdate':
189
+ case 'NotificationLinkedProfilesUpdates':
190
+ case 'NotificationNewsletterAdminPromote':
191
+ case 'NotificationNewsletterAdminDemote':
192
+ case 'NotificationNewsletterUserSettingChange':
193
+ case 'NotificationNewsletterJoin':
194
+ case 'NotificationNewsletterLeave':
195
+ case 'NotificationNewsletterStateChange':
196
+ case 'NotificationNewsletterAdminMetadataUpdate':
197
+ case 'NotificationNewsletterOwnerUpdate':
198
+ case 'NotificationNewsletterAdminInviteRevoke':
199
+ case 'NotificationNewsletterWamoSubStatusChange':
200
+ case 'NotificationNewsletterBlockUser':
201
+ case 'NotificationNewsletterPaidPartnership':
202
+ case 'NotificationNewsletterMilestone':
203
+ case 'NewsletterResponseStateUpdate':
204
+ await handleLegacyMexNewsletterNotification(node);
205
+ break;
206
+ default:
207
+ logger.debug({
208
+ opName
209
+ }, 'unhandled mex notification');
210
+ break;
211
+ }
212
+ return;
213
+ }
214
+ await handleLegacyMexNewsletterNotification(node);
215
+ };
216
+ const handleReachoutTimelockNotification = data => {
217
+ const payload = data.xwa2_notify_account_reachout_timelock;
218
+ if (!payload) {
219
+ logger.warn('reachout timelock notification missing payload');
220
+ return;
221
+ }
222
+ if (!payload.is_active) {
223
+ logger.info('reachout timelock restriction lifted');
224
+ ev.emit('connection.update', {
225
+ reachoutTimeLock: {
226
+ isActive: false,
227
+ enforcementType: _index3.ReachoutTimelockEnforcementType.DEFAULT
228
+ }
229
+ });
230
+ return;
231
+ }
232
+ // WA Web defaults to now+60s when the server omits the expiry
233
+ const timeEnforcementEnds = payload.time_enforcement_ends ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000) : new Date(Date.now() + 60000);
234
+ const enforcementType = isValidEnforcementType(payload.enforcement_type) ? payload.enforcement_type : _index3.ReachoutTimelockEnforcementType.DEFAULT;
235
+ logger.info({
236
+ enforcementType,
237
+ timeEnforcementEnds
238
+ }, 'reachout timelock restriction set');
239
+ ev.emit('connection.update', {
240
+ reachoutTimeLock: {
241
+ isActive: true,
242
+ timeEnforcementEnds,
243
+ enforcementType
244
+ }
245
+ });
246
+ };
247
+ const handleMessageCappingNotification = data => {
248
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
249
+ if (!payload) {
250
+ logger.warn('message capping notification missing payload');
251
+ return;
252
+ }
253
+ logger.info({
254
+ payload
255
+ }, 'received message capping update');
256
+ ev.emit('message-capping.update', payload);
257
+ };
258
+ const handleLegacyMexNewsletterNotification = async node => {
259
+ const mexNode = (0, _index5.getBinaryNodeChild)(node, 'mex');
260
+ const updateNode = mexNode?.content ? null : (0, _index5.getBinaryNodeChild)(node, 'update') || (0, _index5.getAllBinaryNodeChildren)(node)[0];
261
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
262
+ if (!payloadNode?.content) {
263
+ logger.warn({
264
+ node: (0, _index5.binaryNodeToString)(node)
265
+ }, 'invalid mex newsletter notification');
266
+ return;
267
+ }
268
+ let data;
269
+ try {
270
+ const payloadContent = payloadNode.content;
271
+ if (Array.isArray(payloadContent)) {
272
+ logger.warn({
273
+ payloadNode
274
+ }, 'invalid mex newsletter notification payload format');
275
+ return;
276
+ }
277
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
278
+ data = JSON.parse(contentBuf.toString());
279
+ } catch (error) {
280
+ logger.error({
281
+ err: error,
282
+ node: (0, _index5.binaryNodeToString)(node)
283
+ }, 'failed to parse mex newsletter notification');
284
+ return;
285
+ }
286
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
287
+ let updates = data?.updates;
288
+ if (!updates) {
289
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
290
+ if (linkedProfiles) {
291
+ updates = [linkedProfiles];
292
+ }
293
+ }
294
+ if (!updates || !operation) {
295
+ logger.warn({
296
+ data
297
+ }, 'invalid mex newsletter notification content');
298
+ return;
299
+ }
300
+ logger.info({
301
+ operation,
302
+ updates
303
+ }, 'got mex newsletter notification');
304
+ switch (operation) {
305
+ case 'NotificationNewsletterUpdate':
306
+ for (const update of updates) {
307
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
308
+ ev.emit('newsletter-settings.update', {
309
+ id: update.jid,
310
+ update: update.settings
311
+ });
312
+ }
313
+ }
314
+ break;
315
+ case 'NotificationNewsletterAdminPromote':
316
+ for (const update of updates) {
317
+ if (update.jid && update.user) {
318
+ ev.emit('newsletter-participants.update', {
319
+ id: update.jid,
320
+ author: node.attrs.from,
321
+ user: update.user,
322
+ new_role: 'ADMIN',
323
+ action: 'promote'
324
+ });
325
+ }
326
+ }
327
+ break;
328
+ case 'NotificationLinkedProfilesUpdates':
329
+ for (const update of updates) {
330
+ const lid = update?.jid;
331
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
332
+ const mappings = [];
333
+ for (const profile of addedProfiles) {
334
+ const pn = typeof profile === 'string' ? profile : profile?.pn ?? profile?.jid ?? null;
335
+ if (lid && pn) {
336
+ const mapping = {
337
+ lid,
338
+ pn
339
+ };
340
+ ev.emit('lid-mapping.update', mapping);
341
+ mappings.push(mapping);
342
+ }
343
+ }
344
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
345
+ }
346
+ break;
347
+ default:
348
+ logger.info({
349
+ operation,
350
+ data
351
+ }, 'unhandled mex newsletter notification');
352
+ break;
353
+ }
354
+ };
355
+ // Handles newsletter notifications
356
+ const handleNewsletterNotification = async node => {
357
+ const from = node.attrs.from;
358
+ const children = (0, _index5.getAllBinaryNodeChildren)(node);
359
+ const author = node.attrs.participant;
360
+ for (const child of children) {
361
+ logger.debug({
362
+ from,
363
+ child
364
+ }, 'got newsletter notification');
365
+ switch (child.tag) {
366
+ case 'reaction':
367
+ {
368
+ const reactionUpdate = {
369
+ id: from,
370
+ server_id: child.attrs.message_id,
371
+ reaction: {
372
+ code: (0, _index5.getBinaryNodeChildString)(child, 'reaction'),
373
+ count: 1
374
+ }
375
+ };
376
+ ev.emit('newsletter.reaction', reactionUpdate);
377
+ break;
378
+ }
379
+ case 'view':
380
+ {
381
+ const viewUpdate = {
382
+ id: from,
383
+ server_id: child.attrs.message_id,
384
+ count: parseInt(child.content?.toString() || '0', 10)
385
+ };
386
+ ev.emit('newsletter.view', viewUpdate);
387
+ break;
388
+ }
389
+ case 'participant':
390
+ {
391
+ const participantUpdate = {
392
+ id: from,
393
+ author,
394
+ user: child.attrs.jid,
395
+ action: child.attrs.action,
396
+ new_role: child.attrs.role
397
+ };
398
+ ev.emit('newsletter-participants.update', participantUpdate);
399
+ break;
400
+ }
401
+ case 'update':
402
+ {
403
+ const settingsNode = (0, _index5.getBinaryNodeChild)(child, 'settings');
404
+ if (settingsNode) {
405
+ const update = {};
406
+ const nameNode = (0, _index5.getBinaryNodeChild)(settingsNode, 'name');
407
+ if (nameNode?.content) update.name = nameNode.content.toString();
408
+ const descriptionNode = (0, _index5.getBinaryNodeChild)(settingsNode, 'description');
409
+ if (descriptionNode?.content) update.description = descriptionNode.content.toString();
410
+ ev.emit('newsletter-settings.update', {
411
+ id: from,
412
+ update
413
+ });
414
+ }
415
+ break;
416
+ }
417
+ case 'message':
418
+ {
419
+ const plaintextNode = (0, _index5.getBinaryNodeChild)(child, 'plaintext');
420
+ if (plaintextNode?.content) {
421
+ try {
422
+ const contentBuf = typeof plaintextNode.content === 'string' ? Buffer.from(plaintextNode.content, 'binary') : Buffer.from(plaintextNode.content);
423
+ const messageProto = _index.proto.Message.decode(contentBuf).toJSON();
424
+ const fullMessage = _index.proto.WebMessageInfo.fromObject({
425
+ key: {
426
+ remoteJid: from,
427
+ id: child.attrs.message_id || child.attrs.server_id,
428
+ fromMe: false // TODO: is this really true though
429
+ },
430
+ message: messageProto,
431
+ messageTimestamp: +child.attrs.t
432
+ }).toJSON();
433
+ await upsertMessage(fullMessage, 'append');
434
+ logger.debug('Processed plaintext newsletter message');
435
+ } catch (error) {
436
+ logger.error({
437
+ error
438
+ }, 'Failed to decode plaintext newsletter message');
439
+ }
440
+ }
441
+ break;
442
+ }
443
+ default:
444
+ logger.warn({
445
+ node,
446
+ child
447
+ }, 'Unknown newsletter notification child');
448
+ break;
449
+ }
450
+ }
451
+ };
452
+ const sendMessageAck = async (node, errorCode) => {
453
+ const stanza = (0, _stanzaAck.buildAckStanza)(node, errorCode, authState.creds.me.id);
454
+ logger.debug({
455
+ recv: {
456
+ tag: node.tag,
457
+ attrs: node.attrs
458
+ },
459
+ sent: stanza.attrs
460
+ }, 'sent ack');
461
+ await sendNode(stanza);
462
+ };
463
+ const rejectCall = async (callId, callFrom) => {
464
+ const stanza = {
465
+ tag: 'call',
466
+ attrs: {
467
+ from: authState.creds.me.id,
468
+ to: callFrom
469
+ },
470
+ content: [{
471
+ tag: 'reject',
472
+ attrs: {
473
+ 'call-id': callId,
474
+ 'call-creator': callFrom,
475
+ count: '0'
476
+ },
477
+ content: undefined
478
+ }]
479
+ };
480
+ await query(stanza);
481
+ };
482
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
483
+ const {
484
+ fullMessage
485
+ } = (0, _index4.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
486
+ const {
487
+ key: msgKey
488
+ } = fullMessage;
489
+ const msgId = msgKey.id;
490
+ if (messageRetryManager) {
491
+ // Check if we've exceeded max retries using the new system
492
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
493
+ logger.debug({
494
+ msgId
495
+ }, 'reached retry limit with new retry manager, clearing');
496
+ messageRetryManager.markRetryFailed(msgId);
497
+ return;
498
+ }
499
+ // Increment retry count using new system
500
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
501
+ // Use the new retry count for the rest of the logic
502
+ const key = `${msgId}:${msgKey?.participant}`;
503
+ await msgRetryCache.set(key, retryCount);
504
+ } else {
505
+ // Fallback to old system
506
+ const key = `${msgId}:${msgKey?.participant}`;
507
+ let retryCount = (await msgRetryCache.get(key)) || 0;
508
+ if (retryCount >= maxMsgRetryCount) {
509
+ logger.debug({
510
+ retryCount,
511
+ msgId
512
+ }, 'reached retry limit, clearing');
513
+ await msgRetryCache.del(key);
514
+ return;
515
+ }
516
+ retryCount += 1;
517
+ await msgRetryCache.set(key, retryCount);
518
+ }
519
+ const key = `${msgId}:${msgKey?.participant}`;
520
+ const retryCount = (await msgRetryCache.get(key)) || 1;
521
+ const {
522
+ account,
523
+ signedPreKey,
524
+ signedIdentityKey: identityKey
525
+ } = authState.creds;
526
+ const fromJid = node.attrs.from;
527
+ // Check if we should recreate the session
528
+ let shouldRecreateSession = false;
529
+ let recreateReason = '';
530
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
531
+ try {
532
+ // Check if we have a session with this JID
533
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
534
+ const hasSession = await signalRepository.validateSession(fromJid);
535
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
536
+ shouldRecreateSession = result.recreate;
537
+ recreateReason = result.reason;
538
+ if (shouldRecreateSession) {
539
+ logger.debug({
540
+ fromJid,
541
+ retryCount,
542
+ reason: recreateReason
543
+ }, 'recreating session for retry');
544
+ // Delete existing session to force recreation
545
+ await authState.keys.set({
546
+ session: {
547
+ [sessionId]: null
548
+ }
549
+ });
550
+ forceIncludeKeys = true;
551
+ }
552
+ } catch (error) {
553
+ logger.warn({
554
+ error,
555
+ fromJid
556
+ }, 'failed to check session recreation');
557
+ }
558
+ }
559
+ if (retryCount <= 2) {
560
+ // Use new retry manager for phone requests if available
561
+ if (messageRetryManager) {
562
+ // Schedule phone request with delay (like whatsmeow)
563
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
564
+ try {
565
+ const requestId = await requestPlaceholderResend(msgKey);
566
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
567
+ } catch (error) {
568
+ logger.warn({
569
+ error,
570
+ msgId
571
+ }, 'failed to send scheduled phone request');
572
+ }
573
+ });
574
+ } else {
575
+ // Fallback to immediate request
576
+ const msgId = await requestPlaceholderResend(msgKey);
577
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
578
+ }
579
+ }
580
+ const deviceIdentity = (0, _index4.encodeSignedDeviceIdentity)(account, true);
581
+ await authState.keys.transaction(async () => {
582
+ const receipt = {
583
+ tag: 'receipt',
584
+ attrs: {
585
+ id: msgId,
586
+ type: 'retry',
587
+ to: node.attrs.from
588
+ },
589
+ content: [{
590
+ tag: 'retry',
591
+ attrs: {
592
+ count: retryCount.toString(),
593
+ id: node.attrs.id,
594
+ t: node.attrs.t,
595
+ v: '1',
596
+ // ADD ERROR FIELD
597
+ error: '0'
598
+ }
599
+ }, {
600
+ tag: 'registration',
601
+ attrs: {},
602
+ content: (0, _index4.encodeBigEndian)(authState.creds.registrationId)
603
+ }]
604
+ };
605
+ if (node.attrs.recipient) {
606
+ receipt.attrs.recipient = node.attrs.recipient;
607
+ }
608
+ if (node.attrs.participant) {
609
+ receipt.attrs.participant = node.attrs.participant;
610
+ }
611
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
612
+ const {
613
+ update,
614
+ preKeys
615
+ } = await (0, _index4.getNextPreKeys)(authState, 1);
616
+ const [keyId] = Object.keys(preKeys);
617
+ const key = preKeys[+keyId];
618
+ const content = receipt.content;
619
+ content.push({
620
+ tag: 'keys',
621
+ attrs: {},
622
+ content: [{
623
+ tag: 'type',
624
+ attrs: {},
625
+ content: Buffer.from(_index2.KEY_BUNDLE_TYPE)
626
+ }, {
627
+ tag: 'identity',
628
+ attrs: {},
629
+ content: identityKey.public
630
+ }, (0, _index4.xmppPreKey)(key, +keyId), (0, _index4.xmppSignedPreKey)(signedPreKey), {
631
+ tag: 'device-identity',
632
+ attrs: {},
633
+ content: deviceIdentity
634
+ }]
635
+ });
636
+ ev.emit('creds.update', update);
637
+ }
638
+ await sendNode(receipt);
639
+ logger.info({
640
+ msgAttrs: node.attrs,
641
+ retryCount
642
+ }, 'sent retry receipt');
643
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
644
+ };
645
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
646
+ const inFlightPreKeyLow = new Set();
647
+ /**
648
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
649
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
650
+ * the session refresh (not after it).
651
+ */
652
+ const reissueTcTokenAfterIdentityChange = from => {
653
+ void (async () => {
654
+ const normalizedJid = (0, _index5.jidNormalizedUser)(from);
655
+ const tcJid = await (0, _tcTokenUtils.resolveTcTokenJid)(normalizedJid, getLIDForPN);
656
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
657
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
658
+ if (senderTs === null || senderTs === undefined || (0, _tcTokenUtils.isTcTokenExpired)(senderTs)) {
659
+ return;
660
+ }
661
+ logger.debug({
662
+ jid: normalizedJid,
663
+ senderTimestamp: senderTs
664
+ }, 'identity changed, re-issuing tctoken');
665
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
666
+ const issueJid = await (0, _tcTokenUtils.resolveIssuanceJid)(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
667
+ const result = await issuePrivacyTokens([issueJid], senderTs);
668
+ await (0, _tcTokenUtils.storeTcTokensFromIqResult)({
669
+ result,
670
+ fallbackJid: tcJid,
671
+ keys: authState.keys,
672
+ getLIDForPN,
673
+ onNewJidStored: trackTcTokenJid
674
+ });
675
+ })().catch(err => {
676
+ logger.debug({
677
+ jid: from,
678
+ err: err?.message
679
+ }, 'failed to re-issue tctoken after identity change');
680
+ });
681
+ };
682
+ const handleEncryptNotification = async node => {
683
+ const from = node.attrs.from;
684
+ if (from === _index5.S_WHATSAPP_NET) {
685
+ const stanzaId = node.attrs.id;
686
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
687
+ return;
688
+ }
689
+ const countChild = (0, _index5.getBinaryNodeChild)(node, 'count');
690
+ const count = +countChild.attrs.value;
691
+ const shouldUploadMorePreKeys = count < _index2.MIN_PREKEY_COUNT;
692
+ logger.debug({
693
+ count,
694
+ shouldUploadMorePreKeys
695
+ }, 'recv pre-key count');
696
+ if (shouldUploadMorePreKeys) {
697
+ if (stanzaId) inFlightPreKeyLow.add(stanzaId);
698
+ try {
699
+ await uploadPreKeys();
700
+ } finally {
701
+ if (stanzaId) inFlightPreKeyLow.delete(stanzaId);
702
+ }
703
+ }
704
+ } else {
705
+ const result = await (0, _index4.handleIdentityChange)(node, {
706
+ meId: authState.creds.me?.id,
707
+ meLid: authState.creds.me?.lid,
708
+ validateSession: signalRepository.validateSession,
709
+ assertSessions,
710
+ debounceCache: identityAssertDebounce,
711
+ logger,
712
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
713
+ });
714
+ if (result.action === 'no_identity_node') {
715
+ logger.info({
716
+ node
717
+ }, 'unknown encrypt notification');
718
+ }
719
+ }
720
+ };
721
+ const handleGroupNotification = (fullNode, child, msg) => {
722
+ // TODO: Support PN/LID (Here is only LID now)
723
+ const actingParticipantLid = fullNode.attrs.participant;
724
+ const actingParticipantPn = fullNode.attrs.participant_pn;
725
+ const actingParticipantUsername = fullNode.attrs.participant_username;
726
+ const affectedParticipantLid = (0, _index5.getBinaryNodeChild)(child, 'participant')?.attrs?.jid || actingParticipantLid;
727
+ const affectedParticipantPn = (0, _index5.getBinaryNodeChild)(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
728
+ switch (child?.tag) {
729
+ case 'create':
730
+ const metadata = (0, _groups.extractGroupMetadata)(child);
731
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CREATE;
732
+ msg.messageStubParameters = [metadata.subject];
733
+ msg.key = {
734
+ participant: metadata.owner,
735
+ participantAlt: metadata.ownerPn
736
+ };
737
+ ev.emit('chats.upsert', [{
738
+ id: metadata.id,
739
+ name: metadata.subject,
740
+ conversationTimestamp: metadata.creation
741
+ }]);
742
+ ev.emit('groups.upsert', [{
743
+ ...metadata,
744
+ author: actingParticipantLid,
745
+ authorPn: actingParticipantPn,
746
+ authorUsername: actingParticipantUsername
747
+ }]);
748
+ break;
749
+ case 'ephemeral':
750
+ case 'not_ephemeral':
751
+ msg.message = {
752
+ protocolMessage: {
753
+ type: _index.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
754
+ ephemeralExpiration: +(child.attrs.expiration || 0)
755
+ }
756
+ };
757
+ break;
758
+ case 'modify':
759
+ const oldNumber = (0, _index5.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
760
+ msg.messageStubParameters = oldNumber || [];
761
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
762
+ break;
763
+ case 'promote':
764
+ case 'demote':
765
+ case 'remove':
766
+ case 'add':
767
+ case 'leave':
768
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
769
+ msg.messageStubType = _index3.WAMessageStubType[stubType];
770
+ const participants = (0, _index5.getBinaryNodeChildren)(child, 'participant').map(({
771
+ attrs
772
+ }) => {
773
+ // TODO: Store LID MAPPINGS
774
+ return {
775
+ id: attrs.jid,
776
+ phoneNumber: (0, _index5.isLidUser)(attrs.jid) && (0, _index5.isPnUser)(attrs.phone_number) ? attrs.phone_number : undefined,
777
+ lid: (0, _index5.isPnUser)(attrs.jid) && (0, _index5.isLidUser)(attrs.lid) ? attrs.lid : undefined,
778
+ username: attrs.participant_username || attrs.username || undefined,
779
+ admin: attrs.type || null
780
+ };
781
+ });
782
+ if (participants.length === 1 && (
783
+ // if recv. "remove" message and sender removed themselves
784
+ // mark as left
785
+ (0, _index5.areJidsSameUser)(participants[0].id, actingParticipantLid) || (0, _index5.areJidsSameUser)(participants[0].id, actingParticipantPn)) && child.tag === 'remove') {
786
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
787
+ }
788
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
789
+ break;
790
+ case 'subject':
791
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_SUBJECT;
792
+ msg.messageStubParameters = [child.attrs.subject];
793
+ break;
794
+ case 'description':
795
+ const description = (0, _index5.getBinaryNodeChild)(child, 'body')?.content?.toString();
796
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
797
+ msg.messageStubParameters = description ? [description] : undefined;
798
+ break;
799
+ case 'announcement':
800
+ case 'not_announcement':
801
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
802
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
803
+ break;
804
+ case 'locked':
805
+ case 'unlocked':
806
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_RESTRICT;
807
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
808
+ break;
809
+ case 'invite':
810
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
811
+ msg.messageStubParameters = [child.attrs.code];
812
+ break;
813
+ case 'member_add_mode':
814
+ const addMode = child.content;
815
+ if (addMode) {
816
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
817
+ msg.messageStubParameters = [addMode.toString()];
818
+ }
819
+ break;
820
+ case 'membership_approval_mode':
821
+ const approvalMode = (0, _index5.getBinaryNodeChild)(child, 'group_join');
822
+ if (approvalMode) {
823
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
824
+ msg.messageStubParameters = [approvalMode.attrs.state];
825
+ }
826
+ break;
827
+ case 'created_membership_requests':
828
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
829
+ msg.messageStubParameters = [JSON.stringify({
830
+ lid: affectedParticipantLid,
831
+ pn: affectedParticipantPn
832
+ }), 'created', child.attrs.request_method];
833
+ break;
834
+ case 'revoked_membership_requests':
835
+ const isDenied = (0, _index5.areJidsSameUser)(affectedParticipantLid, actingParticipantLid);
836
+ // TODO: LIDMAPPING SUPPORT
837
+ msg.messageStubType = _index3.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
838
+ msg.messageStubParameters = [JSON.stringify({
839
+ lid: affectedParticipantLid,
840
+ pn: affectedParticipantPn
841
+ }), isDenied ? 'revoked' : 'rejected'];
842
+ break;
843
+ }
844
+ };
845
+ const handleDevicesNotification = async node => {
846
+ const [child] = (0, _index5.getAllBinaryNodeChildren)(node);
847
+ const from = (0, _index5.jidNormalizedUser)(node.attrs.from);
848
+ if (!child) {
849
+ logger.debug({
850
+ from
851
+ }, 'devices notification missing child, skipping');
852
+ return;
853
+ }
854
+ const tag = child.tag;
855
+ const deviceHash = child.attrs.device_hash;
856
+ const devices = (0, _index5.getBinaryNodeChildren)(child, 'device');
857
+ if ((0, _index5.areJidsSameUser)(from, authState.creds.me.id) || (0, _index5.areJidsSameUser)(from, authState.creds.me.lid)) {
858
+ const deviceJids = devices.map(d => d.attrs.jid);
859
+ logger.info({
860
+ deviceJids
861
+ }, 'got my own devices');
862
+ }
863
+ if (!devices.length) {
864
+ logger.debug({
865
+ from,
866
+ tag
867
+ }, 'no devices in notification, skipping');
868
+ return;
869
+ }
870
+ const decoded = [];
871
+ for (const d of devices) {
872
+ const jid = d.attrs.jid;
873
+ if (!jid) continue;
874
+ const parts = (0, _index5.jidDecode)(jid);
875
+ if (!parts) {
876
+ logger.debug({
877
+ jid
878
+ }, 'failed to decode device jid, skipping');
879
+ continue;
880
+ }
881
+ decoded.push({
882
+ jid,
883
+ user: parts.user,
884
+ server: parts.server,
885
+ device: parts.device
886
+ });
887
+ }
888
+ if (!decoded.length) return;
889
+ await devicesMutex.mutex(async () => {
890
+ const byUser = new Map();
891
+ for (const d of decoded) {
892
+ const list = byUser.get(d.user) || [];
893
+ list.push(d);
894
+ byUser.set(d.user, list);
895
+ }
896
+ for (const [user, entries] of byUser) {
897
+ if (tag === 'update') {
898
+ logger.debug({
899
+ user
900
+ }, `${user}'s device list updated, dropping cached devices`);
901
+ await userDevicesCache?.del(user);
902
+ continue;
903
+ }
904
+ if (tag === 'remove') {
905
+ await signalRepository.deleteSession(entries.map(e => e.jid));
906
+ }
907
+ const existingCache = (await userDevicesCache?.get(user)) || [];
908
+ if (!existingCache.length) {
909
+ // No baseline yet; skip applying the delta so getUSyncDevices can
910
+ // later fetch the full device list. Caching just the notification
911
+ // entries would make a partial list look authoritative.
912
+ logger.debug({
913
+ user,
914
+ tag
915
+ }, 'device list not cached, deferring to USync refresh');
916
+ continue;
917
+ }
918
+ const affected = new Set(entries.map(e => e.device));
919
+ let updatedDevices;
920
+ switch (tag) {
921
+ case 'add':
922
+ logger.info({
923
+ deviceHash,
924
+ count: entries.length
925
+ }, 'devices added');
926
+ updatedDevices = [...existingCache.filter(d => !affected.has(d.device)), ...entries.map(e => ({
927
+ user: e.user,
928
+ server: e.server,
929
+ device: e.device
930
+ }))];
931
+ break;
932
+ case 'remove':
933
+ logger.info({
934
+ deviceHash,
935
+ count: entries.length
936
+ }, 'devices removed');
937
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
938
+ break;
939
+ default:
940
+ logger.debug({
941
+ tag
942
+ }, 'Unknown device list change tag');
943
+ continue;
944
+ }
945
+ if (updatedDevices.length === 0) {
946
+ await userDevicesCache?.del(user);
947
+ } else {
948
+ await userDevicesCache?.set(user, updatedDevices);
949
+ }
950
+ }
951
+ });
952
+ };
953
+ const processNotification = async node => {
954
+ const result = {};
955
+ const [child] = (0, _index5.getAllBinaryNodeChildren)(node);
956
+ const nodeType = node.attrs.type;
957
+ const from = (0, _index5.jidNormalizedUser)(node.attrs.from);
958
+ switch (nodeType) {
959
+ case 'newsletter':
960
+ await handleNewsletterNotification(node);
961
+ break;
962
+ case 'mex':
963
+ await handleMexNotification(node);
964
+ break;
965
+ case 'w:gp2':
966
+ // TODO: HANDLE PARTICIPANT_PN
967
+ handleGroupNotification(node, child, result);
968
+ break;
969
+ case 'mediaretry':
970
+ const event = (0, _index4.decodeMediaRetryNode)(node);
971
+ ev.emit('messages.media-update', [event]);
972
+ break;
973
+ case 'encrypt':
974
+ await handleEncryptNotification(node);
975
+ break;
976
+ case 'devices':
977
+ try {
978
+ await handleDevicesNotification(node);
979
+ } catch (error) {
980
+ logger.error({
981
+ error,
982
+ node
983
+ }, 'failed to handle devices notification');
984
+ }
985
+ break;
986
+ case 'server_sync':
987
+ const update = (0, _index5.getBinaryNodeChild)(node, 'collection');
988
+ if (update) {
989
+ const name = update.attrs.name;
990
+ await resyncAppState([name], false);
991
+ }
992
+ break;
993
+ case 'picture':
994
+ const setPicture = (0, _index5.getBinaryNodeChild)(node, 'set');
995
+ const delPicture = (0, _index5.getBinaryNodeChild)(node, 'delete');
996
+ // TODO: WAJIDHASH stuff proper support inhouse
997
+ ev.emit('contacts.update', [{
998
+ id: (0, _index5.jidNormalizedUser)(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
999
+ imgUrl: setPicture ? 'changed' : 'removed'
1000
+ }]);
1001
+ if ((0, _index5.isJidGroup)(from)) {
1002
+ const node = setPicture || delPicture;
1003
+ result.messageStubType = _index3.WAMessageStubType.GROUP_CHANGE_ICON;
1004
+ if (setPicture) {
1005
+ result.messageStubParameters = [setPicture.attrs.id];
1006
+ }
1007
+ result.participant = node?.attrs.author;
1008
+ result.key = {
1009
+ ...(result.key || {}),
1010
+ participant: setPicture?.attrs.author
1011
+ };
1012
+ }
1013
+ break;
1014
+ case 'account_sync':
1015
+ if (child.tag === 'disappearing_mode') {
1016
+ const newDuration = +child.attrs.duration;
1017
+ const timestamp = +child.attrs.t;
1018
+ logger.info({
1019
+ newDuration
1020
+ }, 'updated account disappearing mode');
1021
+ ev.emit('creds.update', {
1022
+ accountSettings: {
1023
+ ...authState.creds.accountSettings,
1024
+ defaultDisappearingMode: {
1025
+ ephemeralExpiration: newDuration,
1026
+ ephemeralSettingTimestamp: timestamp
1027
+ }
1028
+ }
1029
+ });
1030
+ } else if (child.tag === 'blocklist') {
1031
+ const blocklists = (0, _index5.getBinaryNodeChildren)(child, 'item');
1032
+ for (const {
1033
+ attrs
1034
+ } of blocklists) {
1035
+ const blocklist = [attrs.jid];
1036
+ const type = attrs.action === 'block' ? 'add' : 'remove';
1037
+ ev.emit('blocklist.update', {
1038
+ blocklist,
1039
+ type
1040
+ });
1041
+ }
1042
+ }
1043
+ break;
1044
+ case 'link_code_companion_reg':
1045
+ const linkCodeCompanionReg = (0, _index5.getBinaryNodeChild)(node, 'link_code_companion_reg');
1046
+ const ref = toRequiredBuffer((0, _index5.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
1047
+ const primaryIdentityPublicKey = toRequiredBuffer((0, _index5.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
1048
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, _index5.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
1049
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
1050
+ const companionSharedKey = _index4.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
1051
+ const random = (0, _crypto.randomBytes)(32);
1052
+ const linkCodeSalt = (0, _crypto.randomBytes)(32);
1053
+ const linkCodePairingExpanded = (0, _index4.hkdf)(companionSharedKey, 32, {
1054
+ salt: linkCodeSalt,
1055
+ info: 'link_code_pairing_key_bundle_encryption_key'
1056
+ });
1057
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
1058
+ const encryptIv = (0, _crypto.randomBytes)(12);
1059
+ const encrypted = (0, _index4.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
1060
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
1061
+ const identitySharedKey = _index4.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
1062
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
1063
+ authState.creds.advSecretKey = Buffer.from((0, _index4.hkdf)(identityPayload, 32, {
1064
+ info: 'adv_secret'
1065
+ })).toString('base64');
1066
+ await query({
1067
+ tag: 'iq',
1068
+ attrs: {
1069
+ to: _index5.S_WHATSAPP_NET,
1070
+ type: 'set',
1071
+ id: sock.generateMessageTag(),
1072
+ xmlns: 'md'
1073
+ },
1074
+ content: [{
1075
+ tag: 'link_code_companion_reg',
1076
+ attrs: {
1077
+ jid: authState.creds.me.id,
1078
+ stage: 'companion_finish'
1079
+ },
1080
+ content: [{
1081
+ tag: 'link_code_pairing_wrapped_key_bundle',
1082
+ attrs: {},
1083
+ content: encryptedPayload
1084
+ }, {
1085
+ tag: 'companion_identity_public',
1086
+ attrs: {},
1087
+ content: authState.creds.signedIdentityKey.public
1088
+ }, {
1089
+ tag: 'link_code_pairing_ref',
1090
+ attrs: {},
1091
+ content: ref
1092
+ }]
1093
+ }]
1094
+ });
1095
+ authState.creds.registered = true;
1096
+ ev.emit('creds.update', authState.creds);
1097
+ break;
1098
+ case 'privacy_token':
1099
+ await handlePrivacyTokenNotification(node);
1100
+ break;
1101
+ }
1102
+ if (Object.keys(result).length) {
1103
+ return result;
1104
+ }
1105
+ };
1106
+ /**
1107
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
1108
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
1109
+ * to cover writes made by other layers (e.g. history sync).
1110
+ */
1111
+ const tcTokenKnownJids = new Set();
1112
+ const tcTokenIndexLoaded = (async () => {
1113
+ try {
1114
+ const jids = await (0, _tcTokenUtils.readTcTokenIndex)(authState.keys);
1115
+ for (const jid of jids) tcTokenKnownJids.add(jid);
1116
+ logger.debug({
1117
+ count: tcTokenKnownJids.size
1118
+ }, 'loaded tctoken index');
1119
+ } catch (err) {
1120
+ logger.warn({
1121
+ err: err?.message
1122
+ }, 'failed to load tctoken index');
1123
+ }
1124
+ })();
1125
+ let tcTokenIndexTimer;
1126
+ async function flushTcTokenIndex() {
1127
+ if (tcTokenIndexTimer) {
1128
+ clearTimeout(tcTokenIndexTimer);
1129
+ tcTokenIndexTimer = undefined;
1130
+ }
1131
+ // Merge with whatever is already persisted so we don't clobber writes from other
1132
+ // paths (history sync, concurrent sessions on the same store).
1133
+ const write = await (0, _tcTokenUtils.buildMergedTcTokenIndexWrite)(authState.keys, tcTokenKnownJids);
1134
+ return authState.keys.set({
1135
+ tctoken: write
1136
+ });
1137
+ }
1138
+ function scheduleTcTokenIndexSave() {
1139
+ if (tcTokenIndexTimer) {
1140
+ clearTimeout(tcTokenIndexTimer);
1141
+ }
1142
+ tcTokenIndexTimer = setTimeout(() => {
1143
+ tcTokenIndexTimer = undefined;
1144
+ flushTcTokenIndex().catch(err => {
1145
+ logger.warn({
1146
+ err: err?.message
1147
+ }, 'failed to save tctoken index');
1148
+ });
1149
+ }, 5000);
1150
+ }
1151
+ function trackTcTokenJid(jid) {
1152
+ if (jid && jid !== _tcTokenUtils.TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
1153
+ tcTokenKnownJids.add(jid);
1154
+ scheduleTcTokenIndexSave();
1155
+ }
1156
+ }
1157
+ const handlePrivacyTokenNotification = async node => {
1158
+ const tokensNode = (0, _index5.getBinaryNodeChild)(node, 'tokens');
1159
+ if (!tokensNode) return;
1160
+ const from = (0, _index5.jidNormalizedUser)(node.attrs.from);
1161
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1162
+ // The sender_lid attribute provides the LID directly when available
1163
+ const senderLid = node.attrs.sender_lid && (0, _index5.isLidUser)((0, _index5.jidNormalizedUser)(node.attrs.sender_lid)) ? (0, _index5.jidNormalizedUser)(node.attrs.sender_lid) : undefined;
1164
+ const fallbackJid = senderLid ?? (await (0, _tcTokenUtils.resolveTcTokenJid)(from, getLIDForPN));
1165
+ logger.debug({
1166
+ from,
1167
+ storageJid: fallbackJid
1168
+ }, 'processing privacy token notification');
1169
+ await (0, _tcTokenUtils.storeTcTokensFromIqResult)({
1170
+ result: node,
1171
+ fallbackJid,
1172
+ keys: authState.keys,
1173
+ getLIDForPN,
1174
+ onNewJidStored: trackTcTokenJid
1175
+ });
1176
+ };
1177
+ async function decipherLinkPublicKey(data) {
1178
+ const buffer = toRequiredBuffer(data);
1179
+ const salt = buffer.slice(0, 32);
1180
+ const secretKey = await (0, _index4.derivePairingCodeKey)(authState.creds.pairingCode, salt);
1181
+ const iv = buffer.slice(32, 48);
1182
+ const payload = buffer.slice(48, 80);
1183
+ return (0, _index4.aesDecryptCTR)(payload, secretKey, iv);
1184
+ }
1185
+ function toRequiredBuffer(data) {
1186
+ if (data === undefined) {
1187
+ throw new _boom.Boom('Invalid buffer', {
1188
+ statusCode: 400
1189
+ });
1190
+ }
1191
+ return data instanceof Buffer ? data : Buffer.from(data);
1192
+ }
1193
+ const willSendMessageAgain = async (id, participant) => {
1194
+ const key = `${id}:${participant}`;
1195
+ const retryCount = (await msgRetryCache.get(key)) || 0;
1196
+ return retryCount < maxMsgRetryCount;
1197
+ };
1198
+ const updateSendMessageAgainCount = async (id, participant) => {
1199
+ const key = `${id}:${participant}`;
1200
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1201
+ await msgRetryCache.set(key, newValue);
1202
+ };
1203
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1204
+ const remoteJid = key.remoteJid;
1205
+ const participant = key.participant || remoteJid;
1206
+ const retryCount = +retryNode.attrs.count || 1;
1207
+ const msgId = ids[0];
1208
+ // Try to get messages from cache first, then fallback to getMessage
1209
+ const msgs = [];
1210
+ for (const id of ids) {
1211
+ let msg;
1212
+ // Try to get from retry cache first if enabled
1213
+ if (messageRetryManager) {
1214
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1215
+ if (cachedMsg) {
1216
+ msg = cachedMsg.message;
1217
+ logger.debug({
1218
+ jid: remoteJid,
1219
+ id
1220
+ }, 'found message in retry cache');
1221
+ // Mark retry as successful since we found the message
1222
+ messageRetryManager.markRetrySuccess(id);
1223
+ }
1224
+ }
1225
+ // Fallback to getMessage if not found in cache
1226
+ if (!msg) {
1227
+ msg = await getMessage({
1228
+ ...key,
1229
+ id
1230
+ });
1231
+ if (msg) {
1232
+ logger.debug({
1233
+ jid: remoteJid,
1234
+ id
1235
+ }, 'found message via getMessage');
1236
+ // Also mark as successful if found via getMessage
1237
+ if (messageRetryManager) {
1238
+ messageRetryManager.markRetrySuccess(id);
1239
+ }
1240
+ }
1241
+ }
1242
+ msgs.push(msg);
1243
+ }
1244
+ // if it's the primary jid sending the request
1245
+ // just re-send the message to everyone
1246
+ // prevents the first message decryption failure
1247
+ const sendToAll = !(0, _index5.jidDecode)(participant)?.device;
1248
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1249
+ let injectedFromBundle = false;
1250
+ const bundle = (0, _index4.extractE2ESessionFromRetryReceipt)(receiptNode);
1251
+ if (bundle) {
1252
+ try {
1253
+ await signalRepository.injectE2ESession({
1254
+ jid: participant,
1255
+ session: bundle
1256
+ });
1257
+ injectedFromBundle = true;
1258
+ logger.debug({
1259
+ participant,
1260
+ retryCount
1261
+ }, 'injected session from retry receipt key bundle');
1262
+ } catch (error) {
1263
+ logger.warn({
1264
+ error,
1265
+ participant
1266
+ }, 'failed to inject session from retry receipt');
1267
+ }
1268
+ }
1269
+ if (!injectedFromBundle) {
1270
+ const receivedRegId = (0, _index5.getBinaryNodeChildUInt)(receiptNode, 'registration', 4);
1271
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
1272
+ const info = await signalRepository.getSessionInfo(participant);
1273
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
1274
+ logger.info({
1275
+ participant,
1276
+ stored: info.registrationId,
1277
+ received: receivedRegId
1278
+ }, 'reg id mismatch on retry without bundle, deleting session');
1279
+ await authState.keys.set({
1280
+ session: {
1281
+ [sessionId]: null
1282
+ }
1283
+ });
1284
+ }
1285
+ }
1286
+ }
1287
+ const BASE_KEY_CHECK_RETRY = 2;
1288
+ if (msgId && messageRetryManager) {
1289
+ const info = await signalRepository.getSessionInfo(participant);
1290
+ if (info) {
1291
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1292
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1293
+ } else if (retryCount > BASE_KEY_CHECK_RETRY) {
1294
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
1295
+ logger.warn({
1296
+ participant,
1297
+ retryCount
1298
+ }, 'base key collision on retry, forcing fresh session');
1299
+ await authState.keys.set({
1300
+ session: {
1301
+ [sessionId]: null
1302
+ }
1303
+ });
1304
+ }
1305
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1306
+ }
1307
+ }
1308
+ }
1309
+ let shouldRecreateSession = false;
1310
+ let recreateReason = '';
1311
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
1312
+ try {
1313
+ const hasSession = await signalRepository.validateSession(participant);
1314
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
1315
+ shouldRecreateSession = result.recreate;
1316
+ recreateReason = result.reason;
1317
+ if (shouldRecreateSession) {
1318
+ logger.debug({
1319
+ participant,
1320
+ retryCount,
1321
+ reason: recreateReason
1322
+ }, 'recreating session for outgoing retry');
1323
+ await authState.keys.set({
1324
+ session: {
1325
+ [sessionId]: null
1326
+ }
1327
+ });
1328
+ }
1329
+ } catch (error) {
1330
+ logger.warn({
1331
+ error,
1332
+ participant
1333
+ }, 'failed to check session recreation for outgoing retry');
1334
+ }
1335
+ }
1336
+ if (!injectedFromBundle) {
1337
+ await assertSessions([participant], true);
1338
+ }
1339
+ if ((0, _index5.isJidGroup)(remoteJid)) {
1340
+ await authState.keys.set({
1341
+ 'sender-key-memory': {
1342
+ [remoteJid]: null
1343
+ }
1344
+ });
1345
+ }
1346
+ logger.debug({
1347
+ participant,
1348
+ sendToAll,
1349
+ shouldRecreateSession,
1350
+ recreateReason,
1351
+ injectedFromBundle
1352
+ }, 'prepared session for retry resend');
1353
+ for (const [i, msg] of msgs.entries()) {
1354
+ if (!ids[i]) continue;
1355
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
1356
+ await updateSendMessageAgainCount(ids[i], participant);
1357
+ const msgRelayOpts = {
1358
+ messageId: ids[i]
1359
+ };
1360
+ if (sendToAll) {
1361
+ msgRelayOpts.useUserDevicesCache = false;
1362
+ } else {
1363
+ msgRelayOpts.participant = {
1364
+ jid: participant,
1365
+ count: +retryNode.attrs.count
1366
+ };
1367
+ }
1368
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1369
+ } else {
1370
+ logger.debug({
1371
+ jid: key.remoteJid,
1372
+ id: ids[i]
1373
+ }, 'recv retry request, but message not available');
1374
+ }
1375
+ }
1376
+ };
1377
+ const handleReceipt = async node => {
1378
+ const {
1379
+ attrs,
1380
+ content
1381
+ } = node;
1382
+ const isLid = attrs.from.includes('lid');
1383
+ const isNodeFromMe = (0, _index5.areJidsSameUser)(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1384
+ const remoteJid = !isNodeFromMe || (0, _index5.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
1385
+ const fromMe = !attrs.recipient || (attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe;
1386
+ const key = {
1387
+ remoteJid,
1388
+ id: '',
1389
+ fromMe,
1390
+ participant: attrs.participant
1391
+ };
1392
+ const ids = [attrs.id];
1393
+ if (Array.isArray(content)) {
1394
+ const items = (0, _index5.getBinaryNodeChildren)(content[0], 'item');
1395
+ ids.push(...items.map(i => i.attrs.id));
1396
+ }
1397
+ try {
1398
+ await Promise.all([receiptMutex.mutex(async () => {
1399
+ const status = (0, _index4.getStatusFromReceiptType)(attrs.type);
1400
+ if (typeof status !== 'undefined' && (
1401
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1402
+ // or another device of ours has read some messages
1403
+ status >= _index.proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
1404
+ if ((0, _index5.isJidGroup)(remoteJid) || (0, _index5.isJidStatusBroadcast)(remoteJid)) {
1405
+ if (attrs.participant) {
1406
+ const updateKey = status === _index.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
1407
+ ev.emit('message-receipt.update', ids.map(id => ({
1408
+ key: {
1409
+ ...key,
1410
+ id
1411
+ },
1412
+ receipt: {
1413
+ userJid: (0, _index5.jidNormalizedUser)(attrs.participant),
1414
+ [updateKey]: +attrs.t
1415
+ }
1416
+ })));
1417
+ }
1418
+ } else {
1419
+ ev.emit('messages.update', ids.map(id => ({
1420
+ key: {
1421
+ ...key,
1422
+ id
1423
+ },
1424
+ update: {
1425
+ status,
1426
+ messageTimestamp: (0, _index4.toNumber)(+(attrs.t ?? 0))
1427
+ }
1428
+ })));
1429
+ }
1430
+ }
1431
+ if (attrs.type === 'retry') {
1432
+ // correctly set who is asking for the retry
1433
+ key.participant = key.participant || attrs.from;
1434
+ const retryNode = (0, _index5.getBinaryNodeChild)(node, 'retry');
1435
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
1436
+ if (key.fromMe) {
1437
+ try {
1438
+ await updateSendMessageAgainCount(ids[0], key.participant);
1439
+ logger.debug({
1440
+ attrs,
1441
+ key
1442
+ }, 'recv retry request');
1443
+ await sendMessagesAgain(key, ids, retryNode, node);
1444
+ } catch (error) {
1445
+ logger.error({
1446
+ key,
1447
+ ids,
1448
+ trace: error instanceof Error ? error.stack : 'Unknown error'
1449
+ }, 'error in sending message again');
1450
+ }
1451
+ } else {
1452
+ logger.info({
1453
+ attrs,
1454
+ key
1455
+ }, 'recv retry for not fromMe message');
1456
+ }
1457
+ } else {
1458
+ logger.info({
1459
+ attrs,
1460
+ key
1461
+ }, 'will not send message again, as sent too many times');
1462
+ }
1463
+ }
1464
+ })]);
1465
+ } finally {
1466
+ await sendMessageAck(node).catch(ackErr => logger.error({
1467
+ ackErr
1468
+ }, 'failed to ack receipt'));
1469
+ }
1470
+ };
1471
+ const handleNotification = async node => {
1472
+ const remoteJid = node.attrs.from;
1473
+ try {
1474
+ await Promise.all([notificationMutex.mutex(async () => {
1475
+ const msg = await processNotification(node);
1476
+ if (msg) {
1477
+ const fromMe = (0, _index5.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
1478
+ const {
1479
+ senderAlt: participantAlt,
1480
+ addressingMode
1481
+ } = (0, _index4.extractAddressingContext)(node);
1482
+ msg.key = {
1483
+ remoteJid,
1484
+ fromMe,
1485
+ participant: node.attrs.participant,
1486
+ participantAlt,
1487
+ participantUsername: node.attrs.participant_username,
1488
+ addressingMode,
1489
+ id: node.attrs.id,
1490
+ ...(msg.key || {})
1491
+ };
1492
+ msg.participant ?? (msg.participant = node.attrs.participant);
1493
+ msg.messageTimestamp = +node.attrs.t;
1494
+ const fullMsg = _index.proto.WebMessageInfo.fromObject(msg);
1495
+ await upsertMessage(fullMsg, 'append');
1496
+ }
1497
+ })]);
1498
+ } finally {
1499
+ await sendMessageAck(node).catch(ackErr => logger.error({
1500
+ ackErr
1501
+ }, 'failed to ack notification'));
1502
+ }
1503
+ };
1504
+ const handleMessage = async node => {
1505
+ const encNode = (0, _index5.getBinaryNodeChild)(node, 'enc');
1506
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1507
+ if (encNode?.attrs.type === 'msmsg') {
1508
+ logger.debug({
1509
+ key: node.attrs.key
1510
+ }, 'ignored msmsg');
1511
+ await sendMessageAck(node, _index4.NACK_REASONS.MissingMessageSecret);
1512
+ return;
1513
+ }
1514
+ let acked = false;
1515
+ try {
1516
+ const {
1517
+ fullMessage: msg,
1518
+ category,
1519
+ author,
1520
+ decrypt
1521
+ } = (0, _index4.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1522
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1523
+ // store new mappings we didn't have before
1524
+ if (!!alt) {
1525
+ const altServer = (0, _index5.jidDecode)(alt)?.server;
1526
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1527
+ if (altServer === 'lid') {
1528
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1529
+ await signalRepository.lidMapping.storeLIDPNMappings([{
1530
+ lid: alt,
1531
+ pn: primaryJid
1532
+ }]);
1533
+ await signalRepository.migrateSession(primaryJid, alt);
1534
+ }
1535
+ } else {
1536
+ await signalRepository.lidMapping.storeLIDPNMappings([{
1537
+ lid: primaryJid,
1538
+ pn: alt
1539
+ }]);
1540
+ await signalRepository.migrateSession(alt, primaryJid);
1541
+ }
1542
+ }
1543
+ await messageMutex.mutex(async () => {
1544
+ await decrypt();
1545
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1546
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1547
+ }
1548
+ // message failed to decrypt
1549
+ if (msg.messageStubType === _index.proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1550
+ if (msg?.messageStubParameters?.[0] === _index4.MISSING_KEYS_ERROR_TEXT) {
1551
+ acked = true;
1552
+ return sendMessageAck(node, _index4.NACK_REASONS.ParsingError);
1553
+ }
1554
+ if (msg.messageStubParameters?.[0] === _index4.NO_MESSAGE_FOUND_ERROR_TEXT) {
1555
+ // Message arrived without encryption (e.g. CTWA ads messages).
1556
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
1557
+ const unavailableNode = (0, _index5.getBinaryNodeChild)(node, 'unavailable');
1558
+ const unavailableType = unavailableNode?.attrs?.type;
1559
+ if (unavailableType === 'bot_unavailable_fanout' || unavailableType === 'hosted_unavailable_fanout' || unavailableType === 'view_once_unavailable_fanout') {
1560
+ logger.debug({
1561
+ msgId: msg.key.id,
1562
+ unavailableType
1563
+ }, 'skipping placeholder resend for excluded unavailable type');
1564
+ acked = true;
1565
+ return sendMessageAck(node);
1566
+ }
1567
+ const messageAge = (0, _index4.unixTimestampSeconds)() - (0, _index4.toNumber)(msg.messageTimestamp);
1568
+ if (messageAge > _index2.PLACEHOLDER_MAX_AGE_SECONDS) {
1569
+ logger.debug({
1570
+ msgId: msg.key.id,
1571
+ messageAge
1572
+ }, 'skipping placeholder resend for old message');
1573
+ acked = true;
1574
+ return sendMessageAck(node);
1575
+ }
1576
+ // Request the real content from the phone via placeholder resend PDO.
1577
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
1578
+ // and store the requestId in stubParameters[1] so users can correlate
1579
+ // with the incoming PDO response event.
1580
+ const cleanKey = {
1581
+ remoteJid: msg.key.remoteJid,
1582
+ fromMe: msg.key.fromMe,
1583
+ id: msg.key.id,
1584
+ participant: msg.key.participant
1585
+ };
1586
+ // Cache the original message metadata so the PDO response handler
1587
+ // can preserve key fields (LID details etc.) that the phone may omit
1588
+ const msgData = {
1589
+ key: msg.key,
1590
+ messageTimestamp: msg.messageTimestamp,
1591
+ pushName: msg.pushName,
1592
+ participant: msg.participant,
1593
+ verifiedBizName: msg.verifiedBizName
1594
+ };
1595
+ requestPlaceholderResend(cleanKey, msgData).then(requestId => {
1596
+ if (requestId && requestId !== 'RESOLVED') {
1597
+ logger.debug({
1598
+ msgId: msg.key.id,
1599
+ requestId
1600
+ }, 'requested placeholder resend for unavailable message');
1601
+ ev.emit('messages.update', [{
1602
+ key: msg.key,
1603
+ update: {
1604
+ messageStubParameters: [_index4.NO_MESSAGE_FOUND_ERROR_TEXT, requestId]
1605
+ }
1606
+ }]);
1607
+ }
1608
+ }).catch(err => {
1609
+ logger.warn({
1610
+ err,
1611
+ msgId: msg.key.id
1612
+ }, 'failed to request placeholder resend for unavailable message');
1613
+ });
1614
+ acked = true;
1615
+ await sendMessageAck(node);
1616
+ // Don't return — fall through to upsertMessage so the stub is emitted
1617
+ } else {
1618
+ // Skip retry for expired status messages (>24h old)
1619
+ if ((0, _index5.isJidStatusBroadcast)(msg.key.remoteJid)) {
1620
+ const messageAge = (0, _index4.unixTimestampSeconds)() - (0, _index4.toNumber)(msg.messageTimestamp);
1621
+ if (messageAge > _index2.STATUS_EXPIRY_SECONDS) {
1622
+ logger.debug({
1623
+ msgId: msg.key.id,
1624
+ messageAge,
1625
+ remoteJid: msg.key.remoteJid
1626
+ }, 'skipping retry for expired status message');
1627
+ acked = true;
1628
+ return sendMessageAck(node);
1629
+ }
1630
+ }
1631
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1632
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1633
+ await retryMutex.mutex(async () => {
1634
+ try {
1635
+ if (!ws.isOpen) {
1636
+ logger.debug({
1637
+ node
1638
+ }, 'Connection closed, skipping retry');
1639
+ return;
1640
+ }
1641
+ const encNode = (0, _index5.getBinaryNodeChild)(node, 'enc');
1642
+ await sendRetryRequest(node, !encNode);
1643
+ if (retryRequestDelayMs) {
1644
+ await (0, _index4.delay)(retryRequestDelayMs);
1645
+ }
1646
+ } catch (err) {
1647
+ logger.error({
1648
+ err
1649
+ }, 'Failed to send retry');
1650
+ }
1651
+ acked = true;
1652
+ await sendMessageAck(node, _index4.NACK_REASONS.UnhandledError);
1653
+ });
1654
+ }
1655
+ } else {
1656
+ if (messageRetryManager && msg.key.id) {
1657
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1658
+ }
1659
+ const isNewsletter = (0, _index5.isJidNewsletter)(msg.key.remoteJid);
1660
+ if (!isNewsletter) {
1661
+ // no type in the receipt => message delivered
1662
+ let type = undefined;
1663
+ let participant = msg.key.participant;
1664
+ if (category === 'peer') {
1665
+ // special peer message
1666
+ type = 'peer_msg';
1667
+ } else if (msg.key.fromMe) {
1668
+ // message was sent by us from a different device
1669
+ type = 'sender';
1670
+ // need to specially handle this case
1671
+ if ((0, _index5.isLidUser)(msg.key.remoteJid) || (0, _index5.isLidUser)(msg.key.remoteJidAlt)) {
1672
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1673
+ }
1674
+ } else if (!sendActiveReceipts) {
1675
+ type = 'inactive';
1676
+ }
1677
+ acked = true;
1678
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1679
+ // send ack for history message
1680
+ const isAnyHistoryMsg = (0, _index4.getHistoryMsg)(msg.message);
1681
+ if (isAnyHistoryMsg) {
1682
+ const jid = (0, _index5.jidNormalizedUser)(msg.key.remoteJid);
1683
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
1684
+ }
1685
+ } else {
1686
+ acked = true;
1687
+ await sendMessageAck(node);
1688
+ logger.debug({
1689
+ key: msg.key
1690
+ }, 'processed newsletter message without receipts');
1691
+ }
1692
+ }
1693
+ (0, _index4.cleanMessage)(msg, authState.creds.me.id, authState.creds.me.lid);
1694
+ if (!msg.key.fromMe) {
1695
+ try {
1696
+ const info = (0, _spamReportUtils.extractReportingInfoFromStanza)(node);
1697
+ if (info) {
1698
+ const senderJid = msg.key.participant || author || msg.key.remoteJid;
1699
+ const contentType = msg.message ? (0, _index4.getContentType)(msg.message) : undefined;
1700
+ reportingInfoStore.add(senderJid, {
1701
+ stanzaId: info.stanzaId,
1702
+ timestamp: info.timestamp || Number(msg.messageTimestamp) || 0,
1703
+ reportingTag: info.reportingTag,
1704
+ text: (0, _spamReportUtils.extractMessageText)(msg),
1705
+ pushName: msg.pushName || node.attrs?.notify || '',
1706
+ messageType: contentType === 'conversation' || contentType === 'extendedTextMessage' ? 'text' : contentType || 'text',
1707
+ fromJid: senderJid
1708
+ });
1709
+ logger.debug({
1710
+ jid: senderJid,
1711
+ stanzaId: info.stanzaId,
1712
+ tagLen: info.reportingTag.length
1713
+ }, 'stored reporting_tag for spam report');
1714
+ }
1715
+ } catch (storeErr) {
1716
+ logger.warn({
1717
+ err: storeErr,
1718
+ key: msg.key
1719
+ }, 'failed to store reporting_tag');
1720
+ }
1721
+ }
1722
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1723
+ });
1724
+ } catch (error) {
1725
+ logger.error({
1726
+ error,
1727
+ node: (0, _index5.binaryNodeToString)(node)
1728
+ }, 'error in handling message');
1729
+ if (!acked) {
1730
+ await sendMessageAck(node, _index4.NACK_REASONS.UnhandledError).catch(ackErr => logger.error({
1731
+ ackErr
1732
+ }, 'failed to ack message after error'));
1733
+ }
1734
+ }
1735
+ };
1736
+ const handleCall = async node => {
1737
+ try {
1738
+ const {
1739
+ attrs
1740
+ } = node;
1741
+ const [infoChild] = (0, _index5.getAllBinaryNodeChildren)(node);
1742
+ if (!infoChild) {
1743
+ throw new _boom.Boom('Missing call info in call node');
1744
+ }
1745
+ const status = (0, _index4.getCallStatusFromNode)(infoChild);
1746
+ const callId = infoChild.attrs['call-id'];
1747
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1748
+ const call = {
1749
+ chatId: attrs.from,
1750
+ from,
1751
+ callerPn: infoChild.attrs['caller_pn'],
1752
+ id: callId,
1753
+ date: new Date(+attrs.t * 1000),
1754
+ offline: !!attrs.offline,
1755
+ status
1756
+ };
1757
+ if (status === 'relaylatency') {
1758
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
1759
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1760
+ if (Number.isFinite(latencyMs)) {
1761
+ call.latencyMs = latencyMs;
1762
+ }
1763
+ }
1764
+ if (status === 'offer') {
1765
+ call.isVideo = !!(0, _index5.getBinaryNodeChild)(infoChild, 'video');
1766
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1767
+ call.groupJid = infoChild.attrs['group-jid'];
1768
+ await callOfferCache.set(call.id, call);
1769
+ }
1770
+ const existingCall = await callOfferCache.get(call.id);
1771
+ // use existing call info to populate this event
1772
+ if (existingCall) {
1773
+ call.isVideo = existingCall.isVideo;
1774
+ call.isGroup = existingCall.isGroup;
1775
+ call.callerPn = call.callerPn || existingCall.callerPn;
1776
+ }
1777
+ // delete data once call has ended
1778
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1779
+ await callOfferCache.del(call.id);
1780
+ }
1781
+ ev.emit('call', [call]);
1782
+ } catch (error) {
1783
+ logger.error({
1784
+ error,
1785
+ node: (0, _index5.binaryNodeToString)(node)
1786
+ }, 'error in handling call');
1787
+ } finally {
1788
+ await sendMessageAck(node).catch(ackErr => logger.error({
1789
+ ackErr
1790
+ }, 'failed to ack call'));
1791
+ }
1792
+ };
1793
+ const handleBadAck = async ({
1794
+ attrs
1795
+ }) => {
1796
+ const key = {
1797
+ remoteJid: attrs.from,
1798
+ fromMe: true,
1799
+ id: attrs.id
1800
+ };
1801
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1802
+ // // current hypothesis is that if pash is sent in the ack
1803
+ // // it means -- the message hasn't reached all devices yet
1804
+ // // we'll retry sending the message here
1805
+ // if(attrs.phash) {
1806
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1807
+ // const msg = await getMessage(key)
1808
+ // if(msg) {
1809
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1810
+ // } else {
1811
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1812
+ // }
1813
+ // }
1814
+ // error in acknowledgement,
1815
+ // device could not display the message
1816
+ if (attrs.error) {
1817
+ const isReachoutTimelocked = attrs.error === String(_index4.NACK_REASONS.SenderReachoutTimelocked);
1818
+ if (attrs.error === _index4.SERVER_ERROR_CODES.MessageAccountRestriction) {
1819
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
1820
+ // account is restricted: WhatsApp blocks starting new chats but preserves
1821
+ // existing ones, since established chats already carry a tctoken.
1822
+ // WA Web prevents this client-side (disables the compose bar).
1823
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
1824
+ logger.warn({
1825
+ msgId: attrs.id,
1826
+ from: attrs.from
1827
+ }, 'error 463: account restricted or missing tctoken for contact');
1828
+ const ackFrom = attrs.from;
1829
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
1830
+ inFlight463Recoveries.add(ackFrom);
1831
+ void (async () => {
1832
+ try {
1833
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1834
+ const tcStorageJid = await (0, _tcTokenUtils.resolveTcTokenJid)(ackFrom, getLIDForPN);
1835
+ const issueJid = await (0, _tcTokenUtils.resolveIssuanceJid)(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
1836
+ const result = await issuePrivacyTokens([issueJid], (0, _index4.unixTimestampSeconds)());
1837
+ await (0, _tcTokenUtils.storeTcTokensFromIqResult)({
1838
+ result,
1839
+ fallbackJid: tcStorageJid,
1840
+ keys: authState.keys,
1841
+ getLIDForPN,
1842
+ onNewJidStored: trackTcTokenJid
1843
+ });
1844
+ logger.debug({
1845
+ from: ackFrom
1846
+ }, 'completed 463 token recovery issuance');
1847
+ } catch (err) {
1848
+ logger.debug({
1849
+ from: ackFrom,
1850
+ err: err?.message
1851
+ }, 'failed 463 token recovery issuance');
1852
+ } finally {
1853
+ inFlight463Recoveries.delete(ackFrom);
1854
+ }
1855
+ })();
1856
+ }
1857
+ } else if (attrs.error === _index4.SERVER_ERROR_CODES.SmaxInvalid) {
1858
+ logger.warn({
1859
+ msgId: attrs.id,
1860
+ from: attrs.from
1861
+ }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1862
+ } else if (isReachoutTimelocked) {
1863
+ // user is temporarily restricted, fetch current restriction details
1864
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({
1865
+ err
1866
+ }, 'failed to fetch reachout timelock'));
1867
+ logger.warn({
1868
+ attrs
1869
+ }, 'received error in ack');
1870
+ } else {
1871
+ logger.warn({
1872
+ attrs
1873
+ }, 'received error in ack');
1874
+ }
1875
+ ev.emit('messages.update', [{
1876
+ key,
1877
+ update: {
1878
+ status: _index3.WAMessageStatus.ERROR,
1879
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, _index4.ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1880
+ }
1881
+ }]);
1882
+ }
1883
+ };
1884
+ /// processes a node with the given function
1885
+ /// and adds the task to the existing buffer if we're buffering events
1886
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1887
+ ev.buffer();
1888
+ await execTask();
1889
+ ev.flush();
1890
+ function execTask() {
1891
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1892
+ }
1893
+ };
1894
+ const offlineNodeProcessor = (0, _offlineNodeProcessor.makeOfflineNodeProcessor)(new Map([['message', handleMessage], ['call', handleCall], ['receipt', handleReceipt], ['notification', handleNotification]]), {
1895
+ isWsOpen: () => ws.isOpen,
1896
+ onUnexpectedError,
1897
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1898
+ });
1899
+ const processNode = async (type, node, identifier, exec) => {
1900
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
1901
+ const from = node.attrs.from;
1902
+ let ignoreJid = from;
1903
+ if (type === 'receipt' && from) {
1904
+ const attrs = node.attrs;
1905
+ const isLid = attrs.from.includes('lid');
1906
+ const isNodeFromMe = (0, _index5.areJidsSameUser)(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1907
+ ignoreJid = !isNodeFromMe || (0, _index5.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
1908
+ }
1909
+ if (ignoreJid && ignoreJid !== _index5.S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
1910
+ await sendMessageAck(node, type === 'message' ? _index4.NACK_REASONS.UnhandledError : undefined);
1911
+ return;
1912
+ }
1913
+ const isOffline = !!node.attrs.offline;
1914
+ if (isOffline) {
1915
+ offlineNodeProcessor.enqueue(type, node);
1916
+ } else {
1917
+ await processNodeWithBuffer(node, identifier, exec);
1918
+ }
1919
+ };
1920
+ // recv a message
1921
+ ws.on('CB:message', async node => {
1922
+ await processNode('message', node, 'processing message', handleMessage);
1923
+ });
1924
+ ws.on('CB:call', async node => {
1925
+ await processNode('call', node, 'handling call', handleCall);
1926
+ });
1927
+ ws.on('CB:receipt', async node => {
1928
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
1929
+ });
1930
+ ws.on('CB:notification', async node => {
1931
+ await processNode('notification', node, 'handling notification', handleNotification);
1932
+ });
1933
+ ws.on('CB:ack,class:message', node => {
1934
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1935
+ });
1936
+ ev.on('call', async ([call]) => {
1937
+ if (!call) {
1938
+ return;
1939
+ }
1940
+ // missed call + group call notification message generation
1941
+ if (call.status === 'timeout' || call.status === 'offer' && call.isGroup) {
1942
+ const msg = {
1943
+ key: {
1944
+ remoteJid: call.chatId,
1945
+ id: call.id,
1946
+ fromMe: false
1947
+ },
1948
+ messageTimestamp: (0, _index4.unixTimestampSeconds)(call.date)
1949
+ };
1950
+ if (call.status === 'timeout') {
1951
+ if (call.isGroup) {
1952
+ msg.messageStubType = call.isVideo ? _index3.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : _index3.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1953
+ } else {
1954
+ msg.messageStubType = call.isVideo ? _index3.WAMessageStubType.CALL_MISSED_VIDEO : _index3.WAMessageStubType.CALL_MISSED_VOICE;
1955
+ }
1956
+ } else {
1957
+ msg.message = {
1958
+ call: {
1959
+ callKey: Buffer.from(call.id)
1960
+ }
1961
+ };
1962
+ }
1963
+ const protoMsg = _index.proto.WebMessageInfo.fromObject(msg);
1964
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1965
+ }
1966
+ });
1967
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
1968
+ let lastTcTokenPruneTs = 0;
1969
+ /** dedupe in-flight 463 recovery token issuance by target JID */
1970
+ const inFlight463Recoveries = new Set();
1971
+ ev.on('connection.update', ({
1972
+ isOnline,
1973
+ connection
1974
+ }) => {
1975
+ if (typeof isOnline !== 'undefined') {
1976
+ sendActiveReceipts = isOnline;
1977
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1978
+ }
1979
+ // Flush pending tctoken index save on disconnect to avoid writing after close
1980
+ if (connection === 'close' && tcTokenIndexTimer) {
1981
+ clearTimeout(tcTokenIndexTimer);
1982
+ tcTokenIndexTimer = undefined;
1983
+ // Best-effort flush — may fail if store is already closed
1984
+ try {
1985
+ void Promise.resolve(flushTcTokenIndex()).catch(() => {});
1986
+ } catch {
1987
+ /* ignore sync errors */
1988
+ }
1989
+ }
1990
+ // Prune expired tctokens when coming online, at most once per 24 hours
1991
+ // Matches WA Web's CLEAN_TC_TOKENS task
1992
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
1993
+ if (isOnline) {
1994
+ const now = Date.now();
1995
+ const DAY_MS = 24 * 60 * 60 * 1000;
1996
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
1997
+ lastTcTokenPruneTs = now;
1998
+ void pruneExpiredTcTokens();
1999
+ }
2000
+ }
2001
+ });
2002
+ registerSocketEndHandler(() => {
2003
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
2004
+ msgRetryCache.close();
2005
+ }
2006
+ if (!config.callOfferCache && callOfferCache.close) {
2007
+ callOfferCache.close();
2008
+ }
2009
+ identityAssertDebounce.close();
2010
+ sendActiveReceipts = false;
2011
+ });
2012
+ async function pruneExpiredTcTokens() {
2013
+ try {
2014
+ await tcTokenIndexLoaded;
2015
+ // Union with the persisted index picks up JIDs added by other layers
2016
+ // (history sync) without needing inter-module wiring.
2017
+ const persisted = await (0, _tcTokenUtils.readTcTokenIndex)(authState.keys);
2018
+ const allJids = new Set(tcTokenKnownJids);
2019
+ for (const jid of persisted) allJids.add(jid);
2020
+ if (!allJids.size) return;
2021
+ const jids = [...allJids];
2022
+ const allTokens = await authState.keys.get('tctoken', jids);
2023
+ const writes = {};
2024
+ const survivors = new Set();
2025
+ let mutated = 0;
2026
+ for (const jid of jids) {
2027
+ const entry = allTokens[jid];
2028
+ if (!entry) {
2029
+ // Tracked but nothing in store — drop from index.
2030
+ mutated++;
2031
+ continue;
2032
+ }
2033
+ const hasPeerToken = !!entry.token?.length;
2034
+ const peerTokenExpired = hasPeerToken && (0, _tcTokenUtils.isTcTokenExpired)(entry.timestamp);
2035
+ const hasSenderTs = entry.senderTimestamp !== undefined;
2036
+ const senderTsExpired = hasSenderTs && (0, _tcTokenUtils.isTcTokenExpired)(entry.senderTimestamp);
2037
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
2038
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
2039
+ if (!keepPeerToken && !keepSenderTs) {
2040
+ writes[jid] = null;
2041
+ mutated++;
2042
+ } else if (peerTokenExpired && keepSenderTs) {
2043
+ writes[jid] = {
2044
+ token: Buffer.alloc(0),
2045
+ senderTimestamp: entry.senderTimestamp
2046
+ };
2047
+ survivors.add(jid);
2048
+ mutated++;
2049
+ } else {
2050
+ survivors.add(jid);
2051
+ }
2052
+ }
2053
+ if (mutated === 0) return;
2054
+ await authState.keys.set({
2055
+ tctoken: {
2056
+ ...writes,
2057
+ [_tcTokenUtils.TC_TOKEN_INDEX_KEY]: {
2058
+ token: Buffer.from(JSON.stringify([...survivors]))
2059
+ }
2060
+ }
2061
+ });
2062
+ tcTokenKnownJids.clear();
2063
+ for (const jid of survivors) tcTokenKnownJids.add(jid);
2064
+ logger.debug({
2065
+ mutated,
2066
+ remaining: survivors.size
2067
+ }, 'pruned expired tctokens');
2068
+ } catch (err) {
2069
+ logger.warn({
2070
+ err: err?.message
2071
+ }, 'failed to prune expired tctokens');
2072
+ }
2073
+ }
2074
+ const sendText = async (jid, text, options = {}, quoted = null) => sendMessage(jid, {
2075
+ text,
2076
+ ...options
2077
+ }, {
2078
+ quoted
2079
+ });
2080
+ const sendImage = async (jid, image, caption, options = {}, quoted = null) => sendMessage(jid, {
2081
+ image,
2082
+ caption,
2083
+ ...options
2084
+ }, {
2085
+ quoted
2086
+ });
2087
+ const sendVideo = async (jid, video, caption, options = {}, quoted = null) => sendMessage(jid, {
2088
+ video,
2089
+ caption,
2090
+ ...options
2091
+ }, {
2092
+ quoted
2093
+ });
2094
+ const sendDocument = async (jid, document, fileName, caption, options = {}, quoted = null) => sendMessage(jid, {
2095
+ document,
2096
+ fileName,
2097
+ caption,
2098
+ ...options
2099
+ }, {
2100
+ quoted
2101
+ });
2102
+ const sendAudio = async (jid, audio, options = {}, quoted = null) => sendMessage(jid, {
2103
+ audio,
2104
+ ...options
2105
+ }, {
2106
+ quoted
2107
+ });
2108
+ const sendLocation = async (jid, name, degreesLongitude, degreesLatitude, url, address, options = {}, quoted = null) => sendMessage(jid, {
2109
+ location: {
2110
+ degreesLongitude,
2111
+ degreesLatitude,
2112
+ name,
2113
+ url,
2114
+ address
2115
+ },
2116
+ ...options
2117
+ }, {
2118
+ quoted
2119
+ });
2120
+ const sendPoll = async (jid, name, pollVote = [], multiSelect = false, options = {}, quoted = null) => {
2121
+ const selectableCount = multiSelect ? pollVote.length : 1;
2122
+ return sendMessage(jid, {
2123
+ poll: {
2124
+ name,
2125
+ values: pollVote,
2126
+ selectableCount
2127
+ },
2128
+ ...options
2129
+ }, {
2130
+ quoted
2131
+ });
2132
+ };
2133
+ const sendQuiz = async (jid, name, pollVote = [], answer, options = {}, quoted = null) => sendMessage(jid, {
2134
+ poll: {
2135
+ name,
2136
+ values: pollVote,
2137
+ selectableCount: 1,
2138
+ type: "QUIZ",
2139
+ answer: {
2140
+ optionName: answer
2141
+ }
2142
+ },
2143
+ ...options
2144
+ }, {
2145
+ quoted
2146
+ });
2147
+ const sendPtv = (jid, ptv, options = {}, quoted = null) => sendMessage(jid, {
2148
+ ptv,
2149
+ ...options
2150
+ }, {
2151
+ quoted
2152
+ });
2153
+ const normalizeMenuButtons = buttons => {
2154
+ if (!Array.isArray(buttons)) return [];
2155
+ return buttons.map((btn, index) => {
2156
+ if (typeof btn === 'string') {
2157
+ return {
2158
+ id: btn,
2159
+ text: btn
2160
+ };
2161
+ }
2162
+ const id = btn.id || btn.buttonId || btn.cmd || `btn_${index}`;
2163
+ const text = btn.text || btn.label || btn.buttonText?.displayText || btn.displayText || String(id);
2164
+ return {
2165
+ id: String(id),
2166
+ text: String(text)
2167
+ };
2168
+ }).filter(b => b.id);
2169
+ };
2170
+ const buildMenuTextFallback = (text, buttons, footer) => {
2171
+ const hint = buttons.map(b => `▸ ${b.text} (${b.id})`).join('\n');
2172
+ return `${String(text || '').trim()}${hint ? `\n\n${hint}` : ''}${footer ? `\n\n_${footer}_` : ''}`.trim();
2173
+ };
2174
+ const MAX_NATIVE_FLOW_BUTTONS = 3;
2175
+ const buildNativeFlowButtons = (normalized, options = {}) => {
2176
+ const telegram = options.telegram || options.url;
2177
+ const flowButtons = [];
2178
+ const slots = MAX_NATIVE_FLOW_BUTTONS;
2179
+ const menuButtons = normalized.slice(0, slots);
2180
+ const reserveUrl = options.includeUrlButton !== false && telegram && menuButtons.length < slots;
2181
+ if (reserveUrl) {
2182
+ flowButtons.push({
2183
+ name: 'cta_url',
2184
+ buttonParamsJson: JSON.stringify({
2185
+ display_text: options.urlLabel || 'Telegram',
2186
+ url: telegram,
2187
+ merchant_url: telegram
2188
+ })
2189
+ });
2190
+ }
2191
+ const quickLimit = slots - flowButtons.length;
2192
+ for (const btn of menuButtons.slice(0, quickLimit)) {
2193
+ flowButtons.push({
2194
+ name: 'quick_reply',
2195
+ buttonParamsJson: JSON.stringify({
2196
+ display_text: btn.text.slice(0, 25),
2197
+ id: btn.id
2198
+ })
2199
+ });
2200
+ }
2201
+ return flowButtons;
2202
+ };
2203
+ const buildInteractiveHeader = async (thumb, headerTitle) => {
2204
+ if (thumb && sock.waUploadToServer) {
2205
+ try {
2206
+ const mediaContent = await (0, _index4.generateWAMessageContent)({
2207
+ image: thumb
2208
+ }, {
2209
+ upload: sock.waUploadToServer
2210
+ });
2211
+ return {
2212
+ title: headerTitle,
2213
+ hasMediaAttachment: true,
2214
+ ...mediaContent
2215
+ };
2216
+ } catch {}
2217
+ }
2218
+ if (thumb) {
2219
+ return {
2220
+ title: headerTitle,
2221
+ hasMediaAttachment: true,
2222
+ imageMessage: {
2223
+ jpegThumbnail: thumb,
2224
+ mimetype: 'image/jpeg'
2225
+ }
2226
+ };
2227
+ }
2228
+ return {
2229
+ title: headerTitle,
2230
+ hasMediaAttachment: false
2231
+ };
2232
+ };
2233
+ const sendButtonMenu = async (jid, text, buttons = [], options = {}) => {
2234
+ const normalized = normalizeMenuButtons(buttons);
2235
+ const footerText = [options.footer || '', options.telegram || options.url ? `${options.urlLabel || 'Telegram'}: ${options.telegram || options.url}` : ''].filter(Boolean).join('\n');
2236
+ const thumb = options.jpegThumbnail || options.thumbnail || options.image || null;
2237
+ const headerTitle = options.headerTitle || options.title || "Manta'X";
2238
+ const mentionJid = options.mentionJid || options.mentionedJid;
2239
+ const quoted = options.quoted || null;
2240
+ const modes = options.tryModes || ['interactive', 'buttons', 'text'];
2241
+ const errors = [];
2242
+ if (modes.includes('interactive')) {
2243
+ try {
2244
+ const flowButtons = buildNativeFlowButtons(normalized, options);
2245
+ const interactive = {
2246
+ body: {
2247
+ text: String(text || '').trim()
2248
+ },
2249
+ footer: footerText ? {
2250
+ text: footerText
2251
+ } : undefined,
2252
+ nativeFlowMessage: {
2253
+ buttons: flowButtons,
2254
+ messageParamsJson: '',
2255
+ messageVersion: 1
2256
+ },
2257
+ header: await buildInteractiveHeader(thumb, headerTitle)
2258
+ };
2259
+ if (mentionJid) {
2260
+ interactive.contextInfo = {
2261
+ mentionedJid: Array.isArray(mentionJid) ? mentionJid : [mentionJid]
2262
+ };
2263
+ }
2264
+ const content = {
2265
+ messageContextInfo: {
2266
+ messageSecret: (0, _crypto.randomBytes)(32)
2267
+ },
2268
+ interactiveMessage: interactive
2269
+ };
2270
+ const msg = await (0, _index4.generateWAMessageFromContent)(jid, content, {
2271
+ userJid: authState.creds.me?.id,
2272
+ quoted
2273
+ });
2274
+ await relayMessage(jid, msg.message, {
2275
+ messageId: msg.key.id
2276
+ });
2277
+ return {
2278
+ mode: 'interactive',
2279
+ message: msg,
2280
+ buttonCount: flowButtons.length
2281
+ };
2282
+ } catch (err) {
2283
+ errors.push(`interactive: ${err?.message || err}`);
2284
+ }
2285
+ }
2286
+ if (modes.includes('buttons')) {
2287
+ try {
2288
+ const legacyButtons = normalized.map(btn => ({
2289
+ buttonId: btn.id,
2290
+ buttonText: {
2291
+ displayText: btn.text.slice(0, 25)
2292
+ },
2293
+ type: 1
2294
+ }));
2295
+ const buttonsMessage = {
2296
+ contentText: String(text || '').trim(),
2297
+ footerText: footerText || undefined,
2298
+ buttons: legacyButtons,
2299
+ contextInfo: mentionJid ? {
2300
+ mentionedJid: Array.isArray(mentionJid) ? mentionJid : [mentionJid]
2301
+ } : undefined
2302
+ };
2303
+ if (thumb) {
2304
+ buttonsMessage.headerType = 6;
2305
+ buttonsMessage.locationMessage = {
2306
+ degreesLatitude: options.degreesLatitude ?? 0,
2307
+ degreesLongitude: options.degreesLongitude ?? 0,
2308
+ jpegThumbnail: thumb,
2309
+ name: headerTitle
2310
+ };
2311
+ } else {
2312
+ buttonsMessage.headerType = 1;
2313
+ }
2314
+ const content = {
2315
+ buttonsMessage
2316
+ };
2317
+ const msg = await (0, _index4.generateWAMessageFromContent)(jid, content, {
2318
+ userJid: authState.creds.me?.id,
2319
+ quoted
2320
+ });
2321
+ await relayMessage(jid, msg.message, {
2322
+ messageId: msg.key.id
2323
+ });
2324
+ return {
2325
+ mode: 'buttons',
2326
+ message: msg
2327
+ };
2328
+ } catch (err) {
2329
+ errors.push(`buttons: ${err?.message || err}`);
2330
+ }
2331
+ }
2332
+ const fallbackText = buildMenuTextFallback(text, normalized, footerText);
2333
+ const msg = await sendText(jid, fallbackText, mentionJid ? {
2334
+ mentionedJid: Array.isArray(mentionJid) ? mentionJid : [mentionJid]
2335
+ } : {}, quoted);
2336
+ return {
2337
+ mode: 'text',
2338
+ message: msg,
2339
+ errors
2340
+ };
2341
+ };
2342
+ const statusMention = async (jid, content) => {
2343
+ const msg = await (0, _index4.generateWAMessageFromContent)(jid, content, {
2344
+ userJid: authState.creds.me.id
2345
+ });
2346
+ await relayMessage("status@broadcast", msg.message, {
2347
+ statusJidList: [jid, authState.creds.me.id],
2348
+ additionalNodes: [{
2349
+ tag: "meta",
2350
+ attrs: {},
2351
+ content: [{
2352
+ tag: "mentioned_users",
2353
+ attrs: {},
2354
+ content: [{
2355
+ tag: "to",
2356
+ attrs: {
2357
+ jid
2358
+ },
2359
+ content: undefined
2360
+ }]
2361
+ }]
2362
+ }]
2363
+ });
2364
+ const mentionMsg = {
2365
+ statusMentionMessage: {
2366
+ message: {
2367
+ protocolMessage: {
2368
+ key: msg.key,
2369
+ type: 25,
2370
+ timestamp: Math.floor(Date.now() / 1000)
2371
+ }
2372
+ }
2373
+ }
2374
+ };
2375
+ const x = (0, _index4.generateWAMessageFromContent)(jid, mentionMsg, {});
2376
+ return relayMessage(jid, x.message, {
2377
+ messageId: x.key.id,
2378
+ additionalNodes: [{
2379
+ tag: "meta",
2380
+ attrs: {
2381
+ is_status_mention: "true"
2382
+ }
2383
+ }]
2384
+ });
2385
+ };
2386
+ return {
2387
+ ...sock,
2388
+ sendMessageAck,
2389
+ sendRetryRequest,
2390
+ rejectCall,
2391
+ fetchMessageHistory,
2392
+ requestPlaceholderResend,
2393
+ messageRetryManager,
2394
+ sendText,
2395
+ sendImage,
2396
+ sendVideo,
2397
+ sendAudio,
2398
+ sendDocument,
2399
+ sendLocation,
2400
+ sendPoll,
2401
+ sendQuiz,
2402
+ sendPtv,
2403
+ sendButtonMenu,
2404
+ statusMention
2405
+ };
2406
+ };
2407
+ //# sourceMappingURL=messages-recv.js.map
2408
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;