xspacesocket 0.0.0-stage → 1.3.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 (477) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +143 -2
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5488 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14043 -0
  7. package/WAProto/index.js +107198 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +81 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +146 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +431 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +387 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/channelPollVote.d.ts +44 -0
  86. package/lib/Socket/channelPollVote.d.ts.map +1 -0
  87. package/lib/Socket/channelPollVote.js +65 -0
  88. package/lib/Socket/channelPollVote.js.map +1 -0
  89. package/lib/Socket/channelSchedule.d.ts +229 -0
  90. package/lib/Socket/channelSchedule.d.ts.map +1 -0
  91. package/lib/Socket/channelSchedule.js +465 -0
  92. package/lib/Socket/channelSchedule.js.map +1 -0
  93. package/lib/Socket/channelStatus.d.ts +317 -0
  94. package/lib/Socket/channelStatus.d.ts.map +1 -0
  95. package/lib/Socket/channelStatus.js +479 -0
  96. package/lib/Socket/channelStatus.js.map +1 -0
  97. package/lib/Socket/chats.d.ts +150 -0
  98. package/lib/Socket/chats.d.ts.map +1 -0
  99. package/lib/Socket/chats.js +1313 -0
  100. package/lib/Socket/chats.js.map +1 -0
  101. package/lib/Socket/communities.d.ts +444 -0
  102. package/lib/Socket/communities.d.ts.map +1 -0
  103. package/lib/Socket/communities.js +447 -0
  104. package/lib/Socket/communities.js.map +1 -0
  105. package/lib/Socket/groupHistory.d.ts +38 -0
  106. package/lib/Socket/groupHistory.d.ts.map +1 -0
  107. package/lib/Socket/groupHistory.js +88 -0
  108. package/lib/Socket/groupHistory.js.map +1 -0
  109. package/lib/Socket/groupStatus.d.ts +28 -0
  110. package/lib/Socket/groupStatus.d.ts.map +1 -0
  111. package/lib/Socket/groupStatus.js +47 -0
  112. package/lib/Socket/groupStatus.js.map +1 -0
  113. package/lib/Socket/groups.d.ts +167 -0
  114. package/lib/Socket/groups.d.ts.map +1 -0
  115. package/lib/Socket/groups.js +354 -0
  116. package/lib/Socket/groups.js.map +1 -0
  117. package/lib/Socket/index.d.ts +430 -0
  118. package/lib/Socket/index.d.ts.map +1 -0
  119. package/lib/Socket/index.js +12 -0
  120. package/lib/Socket/index.js.map +1 -0
  121. package/lib/Socket/messages-recv.d.ts +373 -0
  122. package/lib/Socket/messages-recv.d.ts.map +1 -0
  123. package/lib/Socket/messages-recv.js +1897 -0
  124. package/lib/Socket/messages-recv.js.map +1 -0
  125. package/lib/Socket/messages-send.d.ts +404 -0
  126. package/lib/Socket/messages-send.d.ts.map +1 -0
  127. package/lib/Socket/messages-send.js +1528 -0
  128. package/lib/Socket/messages-send.js.map +1 -0
  129. package/lib/Socket/mex.d.ts +3 -0
  130. package/lib/Socket/mex.d.ts.map +1 -0
  131. package/lib/Socket/mex.js +42 -0
  132. package/lib/Socket/mex.js.map +1 -0
  133. package/lib/Socket/newsletter.d.ts +176 -0
  134. package/lib/Socket/newsletter.d.ts.map +1 -0
  135. package/lib/Socket/newsletter.js +181 -0
  136. package/lib/Socket/newsletter.js.map +1 -0
  137. package/lib/Socket/newsletterDirectory.d.ts +201 -0
  138. package/lib/Socket/newsletterDirectory.d.ts.map +1 -0
  139. package/lib/Socket/newsletterDirectory.js +291 -0
  140. package/lib/Socket/newsletterDirectory.js.map +1 -0
  141. package/lib/Socket/payment.d.ts +37 -0
  142. package/lib/Socket/payment.d.ts.map +1 -0
  143. package/lib/Socket/payment.js +124 -0
  144. package/lib/Socket/payment.js.map +1 -0
  145. package/lib/Socket/report.d.ts +70 -0
  146. package/lib/Socket/report.d.ts.map +1 -0
  147. package/lib/Socket/report.js +265 -0
  148. package/lib/Socket/report.js.map +1 -0
  149. package/lib/Socket/socket.d.ts +59 -0
  150. package/lib/Socket/socket.d.ts.map +1 -0
  151. package/lib/Socket/socket.js +982 -0
  152. package/lib/Socket/socket.js.map +1 -0
  153. package/lib/Socket/stickerPack.d.ts +29 -0
  154. package/lib/Socket/stickerPack.d.ts.map +1 -0
  155. package/lib/Socket/stickerPack.js +130 -0
  156. package/lib/Socket/stickerPack.js.map +1 -0
  157. package/lib/Socket/username.d.ts +55 -0
  158. package/lib/Socket/username.d.ts.map +1 -0
  159. package/lib/Socket/username.js +114 -0
  160. package/lib/Socket/username.js.map +1 -0
  161. package/lib/Types/Auth.d.ts +117 -0
  162. package/lib/Types/Auth.d.ts.map +1 -0
  163. package/lib/Types/Auth.js +2 -0
  164. package/lib/Types/Auth.js.map +1 -0
  165. package/lib/Types/Bussines.d.ts +25 -0
  166. package/lib/Types/Bussines.d.ts.map +1 -0
  167. package/lib/Types/Bussines.js +2 -0
  168. package/lib/Types/Bussines.js.map +1 -0
  169. package/lib/Types/Call.d.ts +15 -0
  170. package/lib/Types/Call.d.ts.map +1 -0
  171. package/lib/Types/Call.js +2 -0
  172. package/lib/Types/Call.js.map +1 -0
  173. package/lib/Types/ChannelStatus.d.ts +34 -0
  174. package/lib/Types/ChannelStatus.d.ts.map +1 -0
  175. package/lib/Types/ChannelStatus.js +2 -0
  176. package/lib/Types/ChannelStatus.js.map +1 -0
  177. package/lib/Types/Chat.d.ts +141 -0
  178. package/lib/Types/Chat.d.ts.map +1 -0
  179. package/lib/Types/Chat.js +8 -0
  180. package/lib/Types/Chat.js.map +1 -0
  181. package/lib/Types/Contact.d.ts +26 -0
  182. package/lib/Types/Contact.d.ts.map +1 -0
  183. package/lib/Types/Contact.js +2 -0
  184. package/lib/Types/Contact.js.map +1 -0
  185. package/lib/Types/Events.d.ts +260 -0
  186. package/lib/Types/Events.d.ts.map +1 -0
  187. package/lib/Types/Events.js +2 -0
  188. package/lib/Types/Events.js.map +1 -0
  189. package/lib/Types/GroupMetadata.d.ts +73 -0
  190. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  191. package/lib/Types/GroupMetadata.js +2 -0
  192. package/lib/Types/GroupMetadata.js.map +1 -0
  193. package/lib/Types/Label.d.ts +47 -0
  194. package/lib/Types/Label.d.ts.map +1 -0
  195. package/lib/Types/Label.js +25 -0
  196. package/lib/Types/Label.js.map +1 -0
  197. package/lib/Types/LabelAssociation.d.ts +30 -0
  198. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  199. package/lib/Types/LabelAssociation.js +7 -0
  200. package/lib/Types/LabelAssociation.js.map +1 -0
  201. package/lib/Types/Message.d.ts +466 -0
  202. package/lib/Types/Message.d.ts.map +1 -0
  203. package/lib/Types/Message.js +11 -0
  204. package/lib/Types/Message.js.map +1 -0
  205. package/lib/Types/Mex.d.ts +141 -0
  206. package/lib/Types/Mex.d.ts.map +1 -0
  207. package/lib/Types/Mex.js +37 -0
  208. package/lib/Types/Mex.js.map +1 -0
  209. package/lib/Types/Payment.d.ts +47 -0
  210. package/lib/Types/Payment.d.ts.map +1 -0
  211. package/lib/Types/Payment.js +2 -0
  212. package/lib/Types/Payment.js.map +1 -0
  213. package/lib/Types/Product.d.ts +79 -0
  214. package/lib/Types/Product.d.ts.map +1 -0
  215. package/lib/Types/Product.js +2 -0
  216. package/lib/Types/Product.js.map +1 -0
  217. package/lib/Types/Report.d.ts +219 -0
  218. package/lib/Types/Report.d.ts.map +1 -0
  219. package/lib/Types/Report.js +166 -0
  220. package/lib/Types/Report.js.map +1 -0
  221. package/lib/Types/Signal.d.ts +87 -0
  222. package/lib/Types/Signal.d.ts.map +1 -0
  223. package/lib/Types/Signal.js +2 -0
  224. package/lib/Types/Signal.js.map +1 -0
  225. package/lib/Types/Socket.d.ts +136 -0
  226. package/lib/Types/Socket.d.ts.map +1 -0
  227. package/lib/Types/Socket.js +3 -0
  228. package/lib/Types/Socket.js.map +1 -0
  229. package/lib/Types/State.d.ts +97 -0
  230. package/lib/Types/State.d.ts.map +1 -0
  231. package/lib/Types/State.js +56 -0
  232. package/lib/Types/State.js.map +1 -0
  233. package/lib/Types/StickerPack.d.ts +52 -0
  234. package/lib/Types/StickerPack.d.ts.map +1 -0
  235. package/lib/Types/StickerPack.js +2 -0
  236. package/lib/Types/StickerPack.js.map +1 -0
  237. package/lib/Types/USync.d.ts +26 -0
  238. package/lib/Types/USync.d.ts.map +1 -0
  239. package/lib/Types/USync.js +2 -0
  240. package/lib/Types/USync.js.map +1 -0
  241. package/lib/Types/Username.d.ts +19 -0
  242. package/lib/Types/Username.d.ts.map +1 -0
  243. package/lib/Types/Username.js +2 -0
  244. package/lib/Types/Username.js.map +1 -0
  245. package/lib/Types/index.d.ts +71 -0
  246. package/lib/Types/index.d.ts.map +1 -0
  247. package/lib/Types/index.js +31 -0
  248. package/lib/Types/index.js.map +1 -0
  249. package/lib/Utils/auth-utils.d.ts +24 -0
  250. package/lib/Utils/auth-utils.d.ts.map +1 -0
  251. package/lib/Utils/auth-utils.js +302 -0
  252. package/lib/Utils/auth-utils.js.map +1 -0
  253. package/lib/Utils/browser-utils.d.ts +4 -0
  254. package/lib/Utils/browser-utils.d.ts.map +1 -0
  255. package/lib/Utils/browser-utils.js +29 -0
  256. package/lib/Utils/browser-utils.js.map +1 -0
  257. package/lib/Utils/business.d.ts +23 -0
  258. package/lib/Utils/business.d.ts.map +1 -0
  259. package/lib/Utils/business.js +231 -0
  260. package/lib/Utils/business.js.map +1 -0
  261. package/lib/Utils/chat-utils.d.ts +100 -0
  262. package/lib/Utils/chat-utils.d.ts.map +1 -0
  263. package/lib/Utils/chat-utils.js +890 -0
  264. package/lib/Utils/chat-utils.js.map +1 -0
  265. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  266. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  267. package/lib/Utils/companion-reg-client-utils.js +35 -0
  268. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  269. package/lib/Utils/crypto.d.ts +37 -0
  270. package/lib/Utils/crypto.d.ts.map +1 -0
  271. package/lib/Utils/crypto.js +118 -0
  272. package/lib/Utils/crypto.js.map +1 -0
  273. package/lib/Utils/decode-wa-message.d.ts +66 -0
  274. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  275. package/lib/Utils/decode-wa-message.js +317 -0
  276. package/lib/Utils/decode-wa-message.js.map +1 -0
  277. package/lib/Utils/event-buffer.d.ts +36 -0
  278. package/lib/Utils/event-buffer.d.ts.map +1 -0
  279. package/lib/Utils/event-buffer.js +642 -0
  280. package/lib/Utils/event-buffer.js.map +1 -0
  281. package/lib/Utils/generics.d.ts +92 -0
  282. package/lib/Utils/generics.d.ts.map +1 -0
  283. package/lib/Utils/generics.js +393 -0
  284. package/lib/Utils/generics.js.map +1 -0
  285. package/lib/Utils/group-history.d.ts +37 -0
  286. package/lib/Utils/group-history.d.ts.map +1 -0
  287. package/lib/Utils/group-history.js +55 -0
  288. package/lib/Utils/group-history.js.map +1 -0
  289. package/lib/Utils/history.d.ts +24 -0
  290. package/lib/Utils/history.d.ts.map +1 -0
  291. package/lib/Utils/history.js +134 -0
  292. package/lib/Utils/history.js.map +1 -0
  293. package/lib/Utils/identity-change-handler.d.ts +44 -0
  294. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  295. package/lib/Utils/identity-change-handler.js +50 -0
  296. package/lib/Utils/identity-change-handler.js.map +1 -0
  297. package/lib/Utils/index.d.ts +26 -0
  298. package/lib/Utils/index.d.ts.map +1 -0
  299. package/lib/Utils/index.js +26 -0
  300. package/lib/Utils/index.js.map +1 -0
  301. package/lib/Utils/link-preview.d.ts +21 -0
  302. package/lib/Utils/link-preview.d.ts.map +1 -0
  303. package/lib/Utils/link-preview.js +99 -0
  304. package/lib/Utils/link-preview.js.map +1 -0
  305. package/lib/Utils/logger.d.ts +13 -0
  306. package/lib/Utils/logger.d.ts.map +1 -0
  307. package/lib/Utils/logger.js +3 -0
  308. package/lib/Utils/logger.js.map +1 -0
  309. package/lib/Utils/lt-hash.d.ts +8 -0
  310. package/lib/Utils/lt-hash.d.ts.map +1 -0
  311. package/lib/Utils/lt-hash.js +8 -0
  312. package/lib/Utils/lt-hash.js.map +1 -0
  313. package/lib/Utils/make-mutex.d.ts +9 -0
  314. package/lib/Utils/make-mutex.d.ts.map +1 -0
  315. package/lib/Utils/make-mutex.js +33 -0
  316. package/lib/Utils/make-mutex.js.map +1 -0
  317. package/lib/Utils/message-retry-manager.d.ts +119 -0
  318. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  319. package/lib/Utils/message-retry-manager.js +276 -0
  320. package/lib/Utils/message-retry-manager.js.map +1 -0
  321. package/lib/Utils/messages-media.d.ts +149 -0
  322. package/lib/Utils/messages-media.d.ts.map +1 -0
  323. package/lib/Utils/messages-media.js +875 -0
  324. package/lib/Utils/messages-media.js.map +1 -0
  325. package/lib/Utils/messages.d.ts +178 -0
  326. package/lib/Utils/messages.d.ts.map +1 -0
  327. package/lib/Utils/messages.js +1325 -0
  328. package/lib/Utils/messages.js.map +1 -0
  329. package/lib/Utils/noise-handler.d.ts +20 -0
  330. package/lib/Utils/noise-handler.d.ts.map +1 -0
  331. package/lib/Utils/noise-handler.js +201 -0
  332. package/lib/Utils/noise-handler.js.map +1 -0
  333. package/lib/Utils/offline-node-processor.d.ts +17 -0
  334. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  335. package/lib/Utils/offline-node-processor.js +40 -0
  336. package/lib/Utils/offline-node-processor.js.map +1 -0
  337. package/lib/Utils/pre-key-manager.d.ts +28 -0
  338. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  339. package/lib/Utils/pre-key-manager.js +106 -0
  340. package/lib/Utils/pre-key-manager.js.map +1 -0
  341. package/lib/Utils/process-message.d.ts +85 -0
  342. package/lib/Utils/process-message.d.ts.map +1 -0
  343. package/lib/Utils/process-message.js +688 -0
  344. package/lib/Utils/process-message.js.map +1 -0
  345. package/lib/Utils/reporting-utils.d.ts +18 -0
  346. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  347. package/lib/Utils/reporting-utils.js +265 -0
  348. package/lib/Utils/reporting-utils.js.map +1 -0
  349. package/lib/Utils/rich-response.d.ts +12 -0
  350. package/lib/Utils/rich-response.d.ts.map +1 -0
  351. package/lib/Utils/rich-response.js +97 -0
  352. package/lib/Utils/rich-response.js.map +1 -0
  353. package/lib/Utils/signal.d.ts +47 -0
  354. package/lib/Utils/signal.d.ts.map +1 -0
  355. package/lib/Utils/signal.js +201 -0
  356. package/lib/Utils/signal.js.map +1 -0
  357. package/lib/Utils/stanza-ack.d.ts +11 -0
  358. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  359. package/lib/Utils/stanza-ack.js +38 -0
  360. package/lib/Utils/stanza-ack.js.map +1 -0
  361. package/lib/Utils/sync-action-utils.d.ts +19 -0
  362. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  363. package/lib/Utils/sync-action-utils.js +49 -0
  364. package/lib/Utils/sync-action-utils.js.map +1 -0
  365. package/lib/Utils/sync-key-auto-resolve.d.ts +10 -0
  366. package/lib/Utils/sync-key-auto-resolve.d.ts.map +1 -0
  367. package/lib/Utils/sync-key-auto-resolve.js +33 -0
  368. package/lib/Utils/sync-key-auto-resolve.js.map +1 -0
  369. package/lib/Utils/tc-token-utils.d.ts +37 -0
  370. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  371. package/lib/Utils/tc-token-utils.js +164 -0
  372. package/lib/Utils/tc-token-utils.js.map +1 -0
  373. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  374. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  375. package/lib/Utils/use-multi-file-auth-state.js +153 -0
  376. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  377. package/lib/Utils/validate-connection.d.ts +11 -0
  378. package/lib/Utils/validate-connection.d.ts.map +1 -0
  379. package/lib/Utils/validate-connection.js +211 -0
  380. package/lib/Utils/validate-connection.js.map +1 -0
  381. package/lib/Utils/zip.d.ts +11 -0
  382. package/lib/Utils/zip.d.ts.map +1 -0
  383. package/lib/Utils/zip.js +88 -0
  384. package/lib/Utils/zip.js.map +1 -0
  385. package/lib/WABinary/constants.d.ts +28 -0
  386. package/lib/WABinary/constants.d.ts.map +1 -0
  387. package/lib/WABinary/constants.js +1301 -0
  388. package/lib/WABinary/constants.js.map +1 -0
  389. package/lib/WABinary/decode.d.ts +7 -0
  390. package/lib/WABinary/decode.d.ts.map +1 -0
  391. package/lib/WABinary/decode.js +262 -0
  392. package/lib/WABinary/decode.js.map +1 -0
  393. package/lib/WABinary/encode.d.ts +3 -0
  394. package/lib/WABinary/encode.d.ts.map +1 -0
  395. package/lib/WABinary/encode.js +220 -0
  396. package/lib/WABinary/encode.js.map +1 -0
  397. package/lib/WABinary/generic-utils.d.ts +22 -0
  398. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  399. package/lib/WABinary/generic-utils.js +201 -0
  400. package/lib/WABinary/generic-utils.js.map +1 -0
  401. package/lib/WABinary/index.d.ts +6 -0
  402. package/lib/WABinary/index.d.ts.map +1 -0
  403. package/lib/WABinary/index.js +6 -0
  404. package/lib/WABinary/index.js.map +1 -0
  405. package/lib/WABinary/jid-utils.d.ts +48 -0
  406. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  407. package/lib/WABinary/jid-utils.js +96 -0
  408. package/lib/WABinary/jid-utils.js.map +1 -0
  409. package/lib/WABinary/types.d.ts +19 -0
  410. package/lib/WABinary/types.d.ts.map +1 -0
  411. package/lib/WABinary/types.js +2 -0
  412. package/lib/WABinary/types.js.map +1 -0
  413. package/lib/WAM/BinaryInfo.d.ts +9 -0
  414. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  415. package/lib/WAM/BinaryInfo.js +10 -0
  416. package/lib/WAM/BinaryInfo.js.map +1 -0
  417. package/lib/WAM/constants.d.ts +40 -0
  418. package/lib/WAM/constants.d.ts.map +1 -0
  419. package/lib/WAM/constants.js +22853 -0
  420. package/lib/WAM/constants.js.map +1 -0
  421. package/lib/WAM/encode.d.ts +3 -0
  422. package/lib/WAM/encode.d.ts.map +1 -0
  423. package/lib/WAM/encode.js +150 -0
  424. package/lib/WAM/encode.js.map +1 -0
  425. package/lib/WAM/index.d.ts +4 -0
  426. package/lib/WAM/index.d.ts.map +1 -0
  427. package/lib/WAM/index.js +4 -0
  428. package/lib/WAM/index.js.map +1 -0
  429. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  430. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  432. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  434. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  436. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  437. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  438. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  439. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  440. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  441. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  442. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  443. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  444. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  445. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  446. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  447. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  448. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  449. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  450. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  451. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  452. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  453. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  454. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  455. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  456. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  457. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  458. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  459. package/lib/WAUSync/Protocols/index.js +6 -0
  460. package/lib/WAUSync/Protocols/index.js.map +1 -0
  461. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  462. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  463. package/lib/WAUSync/USyncQuery.js +98 -0
  464. package/lib/WAUSync/USyncQuery.js.map +1 -0
  465. package/lib/WAUSync/USyncUser.d.ts +17 -0
  466. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  467. package/lib/WAUSync/USyncUser.js +31 -0
  468. package/lib/WAUSync/USyncUser.js.map +1 -0
  469. package/lib/WAUSync/index.d.ts +4 -0
  470. package/lib/WAUSync/index.d.ts.map +1 -0
  471. package/lib/WAUSync/index.js +4 -0
  472. package/lib/WAUSync/index.js.map +1 -0
  473. package/lib/index.d.ts +12 -0
  474. package/lib/index.d.ts.map +1 -0
  475. package/lib/index.js +11 -0
  476. package/lib/index.js.map +1 -0
  477. package/package.json +139 -4
@@ -0,0 +1,1897 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
7
+ import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { ACCOUNT_RESTRICTED_TEXT, aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { makeMutex } from '../Utils/make-mutex.js';
10
+ import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
+ import { buildAckStanza } from '../Utils/stanza-ack.js';
12
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
13
+ import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidBroadcast, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
14
+ import { decodeChannelStatus } from './channelStatus.js';
15
+ import { extractGroupMetadata } from './groups.js';
16
+ import { makeMessagesSocket } from './messages-send.js';
17
+ const ENFORCEMENT_TYPE_VALUES = new Set(Object.values(ReachoutTimelockEnforcementType));
18
+ function isValidEnforcementType(value) {
19
+ return typeof value === 'string' && ENFORCEMENT_TYPE_VALUES.has(value);
20
+ }
21
+ export const makeMessagesRecvSocket = (config) => {
22
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
23
+ const sock = makeMessagesSocket(config);
24
+ const { userDevicesCache, devicesMutex, ev, authState, ws, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, sendPeerDataOperationMessage, messageRetryManager, registerSocketEndHandler, issuePrivacyTokens, fetchAccountReachoutTimelock, placeholderResendCache } = sock;
25
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
26
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
27
+ const retryMutex = makeMutex();
28
+ const msgRetryCache = config.msgRetryCounterCache ||
29
+ new NodeCache({
30
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
31
+ useClones: false
32
+ });
33
+ const getRetryCount = async (key, defaultValue) => {
34
+ const retryCount = await msgRetryCache.get(key);
35
+ if (retryCount === undefined || retryCount === null) {
36
+ return defaultValue;
37
+ }
38
+ return Number.isFinite(retryCount) ? retryCount : maxMsgRetryCount;
39
+ };
40
+ const callOfferCache = config.callOfferCache ||
41
+ new NodeCache({
42
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
43
+ useClones: false
44
+ });
45
+ // Debounce identity-change session refreshes per JID to avoid bursts
46
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
47
+ let sendActiveReceipts = false;
48
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
49
+ if (!authState.creds.me?.id) {
50
+ throw new Boom('Not authenticated');
51
+ }
52
+ let ts = oldestMsgTimestamp;
53
+ if (typeof ts === 'number' && ts > 1e11) {
54
+ ts = Math.floor(ts / 1000);
55
+ }
56
+ else if (ts !== null && typeof ts === 'object' && 'toNumber' in ts) {
57
+ const num = ts.toNumber();
58
+ if (num > 1e11) {
59
+ ts = Math.floor(num / 1000);
60
+ }
61
+ }
62
+ const pdoMessage = {
63
+ historySyncOnDemandRequest: {
64
+ chatJid: oldestMsgKey.remoteJid,
65
+ oldestMsgFromMe: oldestMsgKey.fromMe,
66
+ oldestMsgId: oldestMsgKey.id,
67
+ oldestMsgTimestampMs: ts,
68
+ onDemandMsgCount: count
69
+ },
70
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
71
+ };
72
+ return sendPeerDataOperationMessage(pdoMessage);
73
+ };
74
+ const requestPlaceholderResend = async (messageKey, msgData) => {
75
+ if (!authState.creds.me?.id) {
76
+ throw new Boom('Not authenticated');
77
+ }
78
+ if (await placeholderResendCache.get(messageKey?.id)) {
79
+ logger.debug({ messageKey }, 'already requested resend');
80
+ return;
81
+ }
82
+ else {
83
+ // Store original message data so PDO response handler can preserve
84
+ // metadata (LID details, timestamps, etc.) that the phone may omit
85
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
86
+ }
87
+ await delay(2000);
88
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
89
+ logger.debug({ messageKey }, 'message received while resend requested');
90
+ return 'RESOLVED';
91
+ }
92
+ const pdoMessage = {
93
+ placeholderMessageResendRequest: [
94
+ {
95
+ messageKey
96
+ }
97
+ ],
98
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
99
+ };
100
+ setTimeout(async () => {
101
+ if (await placeholderResendCache.get(messageKey?.id)) {
102
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
103
+ await placeholderResendCache.del(messageKey?.id);
104
+ }
105
+ }, 8000);
106
+ return sendPeerDataOperationMessage(pdoMessage);
107
+ };
108
+ const handleMexNotification = async (node) => {
109
+ const updateNode = getBinaryNodeChild(node, 'update');
110
+ if (updateNode) {
111
+ const opName = updateNode.attrs?.op_name;
112
+ if (!opName) {
113
+ logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy');
114
+ await handleLegacyMexNewsletterNotification(node);
115
+ return;
116
+ }
117
+ let mexResponse;
118
+ try {
119
+ mexResponse = JSON.parse(updateNode.content.toString());
120
+ }
121
+ catch (error) {
122
+ logger.error({ err: error, opName }, 'failed to parse mex notification JSON');
123
+ return;
124
+ }
125
+ if (mexResponse.errors?.length) {
126
+ logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors');
127
+ return;
128
+ }
129
+ const data = mexResponse.data;
130
+ if (!data) {
131
+ logger.warn({ opName }, 'mex notification has null data');
132
+ return;
133
+ }
134
+ logger.debug({ opName }, 'processing mex notification');
135
+ switch (opName) {
136
+ case 'NotificationUserReachoutTimelockUpdate':
137
+ handleReachoutTimelockNotification(data);
138
+ break;
139
+ case 'MessageCappingInfoNotification':
140
+ handleMessageCappingNotification(data);
141
+ break;
142
+ // newsletter ops still use the legacy <mex> child structure
143
+ case 'NotificationNewsletterUpdate':
144
+ case 'NotificationLinkedProfilesUpdates':
145
+ case 'NotificationNewsletterAdminPromote':
146
+ case 'NotificationNewsletterAdminDemote':
147
+ case 'NotificationNewsletterUserSettingChange':
148
+ case 'NotificationNewsletterJoin':
149
+ case 'NotificationNewsletterLeave':
150
+ case 'NotificationNewsletterStateChange':
151
+ case 'NotificationNewsletterAdminMetadataUpdate':
152
+ case 'NotificationNewsletterOwnerUpdate':
153
+ case 'NotificationNewsletterAdminInviteRevoke':
154
+ case 'NotificationNewsletterWamoSubStatusChange':
155
+ case 'NotificationNewsletterBlockUser':
156
+ case 'NotificationNewsletterPaidPartnership':
157
+ case 'NotificationNewsletterMilestone':
158
+ case 'NewsletterResponseStateUpdate':
159
+ await handleLegacyMexNewsletterNotification(node);
160
+ break;
161
+ default:
162
+ logger.debug({ opName }, 'unhandled mex notification');
163
+ break;
164
+ }
165
+ return;
166
+ }
167
+ await handleLegacyMexNewsletterNotification(node);
168
+ };
169
+ const handleReachoutTimelockNotification = (data) => {
170
+ const payload = data.xwa2_notify_account_reachout_timelock;
171
+ if (!payload) {
172
+ logger.warn('reachout timelock notification missing payload');
173
+ return;
174
+ }
175
+ if (!payload.is_active) {
176
+ logger.info('reachout timelock restriction lifted');
177
+ ev.emit('connection.update', {
178
+ reachoutTimeLock: {
179
+ isActive: false,
180
+ enforcementType: ReachoutTimelockEnforcementType.DEFAULT
181
+ }
182
+ });
183
+ return;
184
+ }
185
+ // WA Web defaults to now+60s when the server omits the expiry
186
+ const timeEnforcementEnds = payload.time_enforcement_ends
187
+ ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
188
+ : new Date(Date.now() + 60000);
189
+ const enforcementType = isValidEnforcementType(payload.enforcement_type)
190
+ ? payload.enforcement_type
191
+ : ReachoutTimelockEnforcementType.DEFAULT;
192
+ logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set');
193
+ ev.emit('connection.update', {
194
+ reachoutTimeLock: {
195
+ isActive: true,
196
+ timeEnforcementEnds,
197
+ enforcementType
198
+ }
199
+ });
200
+ };
201
+ const handleMessageCappingNotification = (data) => {
202
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
203
+ if (!payload) {
204
+ logger.warn('message capping notification missing payload');
205
+ return;
206
+ }
207
+ logger.info({ payload }, 'received message capping update');
208
+ ev.emit('message-capping.update', payload);
209
+ };
210
+ const handleLegacyMexNewsletterNotification = async (node) => {
211
+ const mexNode = getBinaryNodeChild(node, 'mex');
212
+ const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
213
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
214
+ if (!payloadNode?.content) {
215
+ logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
216
+ return;
217
+ }
218
+ let data;
219
+ try {
220
+ const payloadContent = payloadNode.content;
221
+ if (Array.isArray(payloadContent)) {
222
+ logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
223
+ return;
224
+ }
225
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
226
+ data = JSON.parse(contentBuf.toString());
227
+ }
228
+ catch (error) {
229
+ logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
230
+ return;
231
+ }
232
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
233
+ let updates = data?.updates;
234
+ if (!updates) {
235
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
236
+ if (linkedProfiles) {
237
+ updates = [linkedProfiles];
238
+ }
239
+ }
240
+ if (!updates || !operation) {
241
+ logger.warn({ data }, 'invalid mex newsletter notification content');
242
+ return;
243
+ }
244
+ logger.info({ operation, updates }, 'got mex newsletter notification');
245
+ switch (operation) {
246
+ case 'NotificationNewsletterUpdate':
247
+ for (const update of updates) {
248
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
249
+ ev.emit('newsletter-settings.update', {
250
+ id: update.jid,
251
+ update: update.settings
252
+ });
253
+ }
254
+ }
255
+ break;
256
+ case 'NotificationNewsletterAdminPromote':
257
+ for (const update of updates) {
258
+ if (update.jid && update.user) {
259
+ ev.emit('newsletter-participants.update', {
260
+ id: update.jid,
261
+ author: node.attrs.from,
262
+ user: update.user,
263
+ new_role: 'ADMIN',
264
+ action: 'promote'
265
+ });
266
+ }
267
+ }
268
+ break;
269
+ case 'NotificationLinkedProfilesUpdates':
270
+ for (const update of updates) {
271
+ const lid = update?.jid;
272
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
273
+ const mappings = [];
274
+ for (const profile of addedProfiles) {
275
+ const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
276
+ if (lid && pn) {
277
+ const mapping = { lid, pn };
278
+ ev.emit('lid-mapping.update', mapping);
279
+ mappings.push(mapping);
280
+ }
281
+ }
282
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
283
+ }
284
+ break;
285
+ default:
286
+ logger.info({ operation, data }, 'unhandled mex newsletter notification');
287
+ break;
288
+ }
289
+ };
290
+ // Handles newsletter notifications
291
+ const handleNewsletterNotification = async (node) => {
292
+ const from = node.attrs.from;
293
+ const children = getAllBinaryNodeChildren(node);
294
+ const author = node.attrs.participant;
295
+ for (const child of children) {
296
+ logger.debug({ from, child }, 'got newsletter notification');
297
+ switch (child.tag) {
298
+ case 'reaction': {
299
+ const reactionUpdate = {
300
+ id: from,
301
+ server_id: child.attrs.message_id,
302
+ reaction: {
303
+ code: getBinaryNodeChildString(child, 'reaction'),
304
+ count: 1
305
+ }
306
+ };
307
+ ev.emit('newsletter.reaction', reactionUpdate);
308
+ break;
309
+ }
310
+ case 'view': {
311
+ const viewUpdate = {
312
+ id: from,
313
+ server_id: child.attrs.message_id,
314
+ count: parseInt(child.content?.toString() || '0', 10)
315
+ };
316
+ ev.emit('newsletter.view', viewUpdate);
317
+ break;
318
+ }
319
+ case 'participant': {
320
+ const participantUpdate = {
321
+ id: from,
322
+ author,
323
+ user: child.attrs.jid,
324
+ action: child.attrs.action,
325
+ new_role: child.attrs.role
326
+ };
327
+ ev.emit('newsletter-participants.update', participantUpdate);
328
+ break;
329
+ }
330
+ case 'update': {
331
+ const settingsNode = getBinaryNodeChild(child, 'settings');
332
+ if (settingsNode) {
333
+ const update = {};
334
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
335
+ if (nameNode?.content)
336
+ update.name = nameNode.content.toString();
337
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
338
+ if (descriptionNode?.content)
339
+ update.description = descriptionNode.content.toString();
340
+ ev.emit('newsletter-settings.update', {
341
+ id: from,
342
+ update
343
+ });
344
+ }
345
+ break;
346
+ }
347
+ case 'message': {
348
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
349
+ if (plaintextNode?.content) {
350
+ try {
351
+ const contentBuf = typeof plaintextNode.content === 'string'
352
+ ? Buffer.from(plaintextNode.content, 'binary')
353
+ : Buffer.from(plaintextNode.content);
354
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
355
+ const fullMessage = proto.WebMessageInfo.fromObject({
356
+ key: {
357
+ remoteJid: from,
358
+ id: child.attrs.message_id || child.attrs.server_id,
359
+ fromMe: false // TODO: is this really true though
360
+ },
361
+ message: messageProto,
362
+ messageTimestamp: +child.attrs.t
363
+ }).toJSON();
364
+ await upsertMessage(fullMessage, 'append');
365
+ logger.debug('Processed plaintext newsletter message');
366
+ }
367
+ catch (error) {
368
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
369
+ }
370
+ }
371
+ break;
372
+ }
373
+ default:
374
+ logger.warn({ node, child }, 'Unknown newsletter notification child');
375
+ break;
376
+ }
377
+ }
378
+ };
379
+ const sendMessageAck = async (node, errorCode) => {
380
+ const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
381
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
382
+ await sendNode(stanza);
383
+ };
384
+ const rejectCall = async (callId, callFrom) => {
385
+ const stanza = {
386
+ tag: 'call',
387
+ attrs: {
388
+ from: authState.creds.me.id,
389
+ to: callFrom
390
+ },
391
+ content: [
392
+ {
393
+ tag: 'reject',
394
+ attrs: {
395
+ 'call-id': callId,
396
+ 'call-creator': callFrom,
397
+ count: '0'
398
+ },
399
+ content: undefined
400
+ }
401
+ ]
402
+ };
403
+ await query(stanza);
404
+ };
405
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
406
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
407
+ const { key: msgKey } = fullMessage;
408
+ const msgId = msgKey.id;
409
+ if (messageRetryManager) {
410
+ const key = `${msgId}:${msgKey?.participant}`;
411
+ const cachedRetryCount = await getRetryCount(key, 0);
412
+ messageRetryManager.restoreRetryCount(msgId, cachedRetryCount);
413
+ // Check if we've exceeded max retries using the new system
414
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
415
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
416
+ messageRetryManager.markRetryFailed(msgId);
417
+ return;
418
+ }
419
+ // Increment retry count using new system
420
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
421
+ // Use the new retry count for the rest of the logic
422
+ await msgRetryCache.set(key, retryCount);
423
+ }
424
+ else {
425
+ // Fallback to old system
426
+ const key = `${msgId}:${msgKey?.participant}`;
427
+ let retryCount = await getRetryCount(key, 0);
428
+ if (retryCount >= maxMsgRetryCount) {
429
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
430
+ return;
431
+ }
432
+ retryCount += 1;
433
+ await msgRetryCache.set(key, retryCount);
434
+ }
435
+ const key = `${msgId}:${msgKey?.participant}`;
436
+ const retryCount = (await msgRetryCache.get(key)) || 1;
437
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
438
+ const fromJid = node.attrs.from;
439
+ // Check if we should recreate the session
440
+ let shouldRecreateSession = false;
441
+ let recreateReason = '';
442
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
443
+ try {
444
+ // Check if we have a session with this JID
445
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
446
+ const hasSession = await signalRepository.validateSession(fromJid);
447
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
448
+ shouldRecreateSession = result.recreate;
449
+ recreateReason = result.reason;
450
+ if (shouldRecreateSession) {
451
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
452
+ // Delete existing session to force recreation
453
+ await authState.keys.set({ session: { [sessionId]: null } });
454
+ forceIncludeKeys = true;
455
+ }
456
+ }
457
+ catch (error) {
458
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
459
+ }
460
+ }
461
+ if (retryCount <= 2) {
462
+ // Use new retry manager for phone requests if available
463
+ if (messageRetryManager) {
464
+ // Schedule phone request with delay (like whatsmeow)
465
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
466
+ try {
467
+ const requestId = await requestPlaceholderResend(msgKey);
468
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
469
+ }
470
+ catch (error) {
471
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
472
+ }
473
+ });
474
+ }
475
+ else {
476
+ // Fallback to immediate request
477
+ const msgId = await requestPlaceholderResend(msgKey);
478
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
479
+ }
480
+ }
481
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
482
+ await authState.keys.transaction(async () => {
483
+ const receipt = {
484
+ tag: 'receipt',
485
+ attrs: {
486
+ id: msgId,
487
+ type: 'retry',
488
+ to: node.attrs.from
489
+ },
490
+ content: [
491
+ {
492
+ tag: 'retry',
493
+ attrs: {
494
+ count: retryCount.toString(),
495
+ id: node.attrs.id,
496
+ t: node.attrs.t,
497
+ v: '1',
498
+ // ADD ERROR FIELD
499
+ error: '0'
500
+ }
501
+ },
502
+ {
503
+ tag: 'registration',
504
+ attrs: {},
505
+ content: encodeBigEndian(authState.creds.registrationId)
506
+ }
507
+ ]
508
+ };
509
+ if (node.attrs.recipient) {
510
+ receipt.attrs.recipient = node.attrs.recipient;
511
+ }
512
+ if (node.attrs.participant) {
513
+ receipt.attrs.participant = node.attrs.participant;
514
+ }
515
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
516
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
517
+ const [keyId] = Object.keys(preKeys);
518
+ const key = preKeys[+keyId];
519
+ const content = receipt.content;
520
+ content.push({
521
+ tag: 'keys',
522
+ attrs: {},
523
+ content: [
524
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
525
+ { tag: 'identity', attrs: {}, content: identityKey.public },
526
+ xmppPreKey(key, +keyId),
527
+ xmppSignedPreKey(signedPreKey),
528
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
529
+ ]
530
+ });
531
+ ev.emit('creds.update', update);
532
+ }
533
+ await sendNode(receipt);
534
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
535
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
536
+ };
537
+ // Mirrors WAWeb/Handle/PreKeyLow.js: skip a re-issued notification with the same stanza id.
538
+ const inFlightPreKeyLow = new Set();
539
+ /**
540
+ * Fire-and-forget tctoken re-issuance after a peer's device identity changed.
541
+ * Mirrors WAWebSendTcTokenWhenDeviceIdentityChange — runs in parallel with
542
+ * the session refresh (not after it).
543
+ */
544
+ const reissueTcTokenAfterIdentityChange = (from) => {
545
+ void (async () => {
546
+ const normalizedJid = jidNormalizedUser(from);
547
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
548
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
549
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
550
+ if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
551
+ return;
552
+ }
553
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
554
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
555
+ const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
556
+ const result = await issuePrivacyTokens([issueJid], senderTs);
557
+ await storeTcTokensFromIqResult({
558
+ result,
559
+ fallbackJid: tcJid,
560
+ keys: authState.keys,
561
+ getLIDForPN,
562
+ onNewJidStored: trackTcTokenJid
563
+ });
564
+ })().catch(err => {
565
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
566
+ });
567
+ };
568
+ const handleEncryptNotification = async (node) => {
569
+ const from = node.attrs.from;
570
+ if (from === S_WHATSAPP_NET) {
571
+ const stanzaId = node.attrs.id;
572
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
573
+ return;
574
+ }
575
+ const countChild = getBinaryNodeChild(node, 'count');
576
+ const count = +countChild.attrs.value;
577
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
578
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
579
+ if (shouldUploadMorePreKeys) {
580
+ if (stanzaId)
581
+ inFlightPreKeyLow.add(stanzaId);
582
+ try {
583
+ await uploadPreKeys();
584
+ }
585
+ finally {
586
+ if (stanzaId)
587
+ inFlightPreKeyLow.delete(stanzaId);
588
+ }
589
+ }
590
+ }
591
+ else {
592
+ const result = await handleIdentityChange(node, {
593
+ meId: authState.creds.me?.id,
594
+ meLid: authState.creds.me?.lid,
595
+ validateSession: signalRepository.validateSession,
596
+ assertSessions,
597
+ debounceCache: identityAssertDebounce,
598
+ logger,
599
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
600
+ });
601
+ if (result.action === 'no_identity_node') {
602
+ logger.info({ node }, 'unknown encrypt notification');
603
+ }
604
+ }
605
+ };
606
+ const handleGroupNotification = (fullNode, child, msg) => {
607
+ // TODO: Support PN/LID (Here is only LID now)
608
+ const actingParticipantLid = fullNode.attrs.participant;
609
+ const actingParticipantPn = fullNode.attrs.participant_pn;
610
+ const actingParticipantUsername = fullNode.attrs.participant_username;
611
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
612
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
613
+ switch (child?.tag) {
614
+ case 'create':
615
+ const metadata = extractGroupMetadata(child);
616
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
617
+ msg.messageStubParameters = [metadata.subject];
618
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
619
+ ev.emit('chats.upsert', [
620
+ {
621
+ id: metadata.id,
622
+ name: metadata.subject,
623
+ conversationTimestamp: metadata.creation
624
+ }
625
+ ]);
626
+ ev.emit('groups.upsert', [
627
+ {
628
+ ...metadata,
629
+ author: actingParticipantLid,
630
+ authorPn: actingParticipantPn,
631
+ authorUsername: actingParticipantUsername
632
+ }
633
+ ]);
634
+ break;
635
+ case 'ephemeral':
636
+ case 'not_ephemeral':
637
+ msg.message = {
638
+ protocolMessage: {
639
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
640
+ ephemeralExpiration: +(child.attrs.expiration || 0)
641
+ }
642
+ };
643
+ break;
644
+ case 'modify':
645
+ // 'modify' is not only a number change: the same w:g2
646
+ // notification carries member tag / role changes (the
647
+ // official app's GroupNotificationHandler lists "modify"
648
+ // alongside add/promote/demote/remove). Build the same
649
+ // full participant objects as promote/demote/add so the
650
+ // attributes (incl. the new admin/tag type) survive into
651
+ // messageStubParameters instead of bare JID strings.
652
+ const modifyParticipants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
653
+ return {
654
+ id: attrs.jid,
655
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
656
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
657
+ username: attrs.participant_username || attrs.username || undefined,
658
+ tag: attrs.tag || undefined,
659
+ admin: (attrs.type || null)
660
+ };
661
+ });
662
+ msg.messageStubParameters = modifyParticipants.map(a => JSON.stringify(a));
663
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
664
+ break;
665
+ case 'promote':
666
+ case 'demote':
667
+ case 'remove':
668
+ case 'add':
669
+ case 'leave':
670
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
671
+ msg.messageStubType = WAMessageStubType[stubType];
672
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
673
+ // TODO: Store LID MAPPINGS
674
+ return {
675
+ id: attrs.jid,
676
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
677
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
678
+ username: attrs.participant_username || attrs.username || undefined,
679
+ tag: attrs.tag || undefined,
680
+ admin: (attrs.type || null)
681
+ };
682
+ });
683
+ if (participants.length === 1 &&
684
+ // if recv. "remove" message and sender removed themselves
685
+ // mark as left
686
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
687
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
688
+ child.tag === 'remove') {
689
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
690
+ }
691
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
692
+ break;
693
+ case 'subject':
694
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
695
+ msg.messageStubParameters = [child.attrs.subject];
696
+ break;
697
+ case 'description':
698
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
699
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
700
+ msg.messageStubParameters = description ? [description] : undefined;
701
+ break;
702
+ case 'announcement':
703
+ case 'not_announcement':
704
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
705
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
706
+ break;
707
+ case 'locked':
708
+ case 'unlocked':
709
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
710
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
711
+ break;
712
+ case 'invite':
713
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
714
+ msg.messageStubParameters = [child.attrs.code];
715
+ break;
716
+ case 'member_add_mode':
717
+ const addMode = child.content;
718
+ if (addMode) {
719
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
720
+ msg.messageStubParameters = [addMode.toString()];
721
+ }
722
+ break;
723
+ case 'membership_approval_mode':
724
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
725
+ if (approvalMode) {
726
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
727
+ msg.messageStubParameters = [approvalMode.attrs.state];
728
+ }
729
+ break;
730
+ case 'created_membership_requests':
731
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
732
+ msg.messageStubParameters = [
733
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
734
+ 'created',
735
+ child.attrs.request_method
736
+ ];
737
+ break;
738
+ case 'revoked_membership_requests':
739
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
740
+ // TODO: LIDMAPPING SUPPORT
741
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
742
+ msg.messageStubParameters = [
743
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
744
+ isDenied ? 'revoked' : 'rejected'
745
+ ];
746
+ break;
747
+ }
748
+ };
749
+ const handleDevicesNotification = async (node) => {
750
+ const [child] = getAllBinaryNodeChildren(node);
751
+ const from = jidNormalizedUser(node.attrs.from);
752
+ if (!child) {
753
+ logger.debug({ from }, 'devices notification missing child, skipping');
754
+ return;
755
+ }
756
+ const tag = child.tag;
757
+ const deviceHash = child.attrs.device_hash;
758
+ const devices = getBinaryNodeChildren(child, 'device');
759
+ if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
760
+ const deviceJids = devices.map(d => d.attrs.jid);
761
+ logger.info({ deviceJids }, 'got my own devices');
762
+ }
763
+ if (!devices.length) {
764
+ logger.debug({ from, tag }, 'no devices in notification, skipping');
765
+ return;
766
+ }
767
+ const decoded = [];
768
+ for (const d of devices) {
769
+ const jid = d.attrs.jid;
770
+ if (!jid)
771
+ continue;
772
+ const parts = jidDecode(jid);
773
+ if (!parts) {
774
+ logger.debug({ jid }, 'failed to decode device jid, skipping');
775
+ continue;
776
+ }
777
+ decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
778
+ }
779
+ if (!decoded.length)
780
+ return;
781
+ await devicesMutex.mutex(async () => {
782
+ const byUser = new Map();
783
+ for (const d of decoded) {
784
+ const list = byUser.get(d.user) || [];
785
+ list.push(d);
786
+ byUser.set(d.user, list);
787
+ }
788
+ for (const [user, entries] of byUser) {
789
+ if (tag === 'update') {
790
+ logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
791
+ await userDevicesCache?.del(user);
792
+ continue;
793
+ }
794
+ if (tag === 'remove') {
795
+ await signalRepository.deleteSession(entries.map(e => e.jid));
796
+ }
797
+ const existingCache = (await userDevicesCache?.get(user)) || [];
798
+ if (!existingCache.length) {
799
+ // No baseline yet; skip applying the delta so getUSyncDevices can
800
+ // later fetch the full device list. Caching just the notification
801
+ // entries would make a partial list look authoritative.
802
+ logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
803
+ continue;
804
+ }
805
+ const affected = new Set(entries.map(e => e.device));
806
+ let updatedDevices;
807
+ switch (tag) {
808
+ case 'add':
809
+ logger.info({ deviceHash, count: entries.length }, 'devices added');
810
+ updatedDevices = [
811
+ ...existingCache.filter(d => !affected.has(d.device)),
812
+ ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
813
+ ];
814
+ break;
815
+ case 'remove':
816
+ logger.info({ deviceHash, count: entries.length }, 'devices removed');
817
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
818
+ break;
819
+ default:
820
+ logger.debug({ tag }, 'Unknown device list change tag');
821
+ continue;
822
+ }
823
+ if (updatedDevices.length === 0) {
824
+ await userDevicesCache?.del(user);
825
+ }
826
+ else {
827
+ await userDevicesCache?.set(user, updatedDevices);
828
+ }
829
+ }
830
+ });
831
+ };
832
+ const processNotification = async (node) => {
833
+ const result = {};
834
+ const [child] = getAllBinaryNodeChildren(node);
835
+ const nodeType = node.attrs.type;
836
+ const from = jidNormalizedUser(node.attrs.from);
837
+ switch (nodeType) {
838
+ case 'newsletter':
839
+ await handleNewsletterNotification(node);
840
+ break;
841
+ case 'mex':
842
+ await handleMexNotification(node);
843
+ break;
844
+ case 'w:gp2':
845
+ // TODO: HANDLE PARTICIPANT_PN
846
+ handleGroupNotification(node, child, result);
847
+ break;
848
+ case 'mediaretry':
849
+ const event = decodeMediaRetryNode(node);
850
+ ev.emit('messages.media-update', [event]);
851
+ break;
852
+ case 'encrypt':
853
+ await handleEncryptNotification(node);
854
+ break;
855
+ case 'devices':
856
+ try {
857
+ await handleDevicesNotification(node);
858
+ }
859
+ catch (error) {
860
+ logger.error({ error, node }, 'failed to handle devices notification');
861
+ }
862
+ break;
863
+ case 'server_sync':
864
+ const update = getBinaryNodeChild(node, 'collection');
865
+ if (update) {
866
+ const name = update.attrs.name;
867
+ await resyncAppState([name], false);
868
+ }
869
+ break;
870
+ case 'picture':
871
+ const setPicture = getBinaryNodeChild(node, 'set');
872
+ const delPicture = getBinaryNodeChild(node, 'delete');
873
+ // TODO: WAJIDHASH stuff proper support inhouse
874
+ ev.emit('contacts.update', [
875
+ {
876
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
877
+ imgUrl: setPicture ? 'changed' : 'removed'
878
+ }
879
+ ]);
880
+ if (isJidGroup(from)) {
881
+ const node = setPicture || delPicture;
882
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
883
+ if (setPicture) {
884
+ result.messageStubParameters = [setPicture.attrs.id];
885
+ }
886
+ result.participant = node?.attrs.author;
887
+ result.key = {
888
+ ...(result.key || {}),
889
+ participant: setPicture?.attrs.author
890
+ };
891
+ }
892
+ break;
893
+ case 'account_sync':
894
+ if (child.tag === 'disappearing_mode') {
895
+ const newDuration = +child.attrs.duration;
896
+ const timestamp = +child.attrs.t;
897
+ logger.info({ newDuration }, 'updated account disappearing mode');
898
+ ev.emit('creds.update', {
899
+ accountSettings: {
900
+ ...authState.creds.accountSettings,
901
+ defaultDisappearingMode: {
902
+ ephemeralExpiration: newDuration,
903
+ ephemeralSettingTimestamp: timestamp
904
+ }
905
+ }
906
+ });
907
+ }
908
+ else if (child.tag === 'blocklist') {
909
+ const blocklists = getBinaryNodeChildren(child, 'item');
910
+ for (const { attrs } of blocklists) {
911
+ const blocklist = [attrs.jid];
912
+ const type = attrs.action === 'block' ? 'add' : 'remove';
913
+ ev.emit('blocklist.update', { blocklist, type });
914
+ }
915
+ }
916
+ break;
917
+ case 'link_code_companion_reg': {
918
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
919
+ // Server sends two notifications: immediately after companion_hello (stage=undefined,
920
+ // only link_code_pairing_ref) and after phone enters code (stage="primary_hello",
921
+ // all 3 crypto fields). Only process the latter.
922
+ if (linkCodeCompanionReg?.attrs?.stage !== 'primary_hello')
923
+ break;
924
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
925
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
926
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
927
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
928
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
929
+ const random = randomBytes(32);
930
+ const linkCodeSalt = randomBytes(32);
931
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
932
+ salt: linkCodeSalt,
933
+ info: 'link_code_pairing_key_bundle_encryption_key'
934
+ });
935
+ const encryptPayload = Buffer.concat([
936
+ Buffer.from(authState.creds.signedIdentityKey.public),
937
+ primaryIdentityPublicKey,
938
+ random
939
+ ]);
940
+ const encryptIv = randomBytes(12);
941
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
942
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
943
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
944
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
945
+ authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
946
+ await query({
947
+ tag: 'iq',
948
+ attrs: {
949
+ to: S_WHATSAPP_NET,
950
+ type: 'set',
951
+ id: sock.generateMessageTag(),
952
+ xmlns: 'md'
953
+ },
954
+ content: [
955
+ {
956
+ tag: 'link_code_companion_reg',
957
+ attrs: {
958
+ jid: authState.creds.me.id,
959
+ stage: 'companion_finish'
960
+ },
961
+ content: [
962
+ {
963
+ tag: 'link_code_pairing_wrapped_key_bundle',
964
+ attrs: {},
965
+ content: encryptedPayload
966
+ },
967
+ {
968
+ tag: 'companion_identity_public',
969
+ attrs: {},
970
+ content: authState.creds.signedIdentityKey.public
971
+ },
972
+ {
973
+ tag: 'link_code_pairing_ref',
974
+ attrs: {},
975
+ content: ref
976
+ }
977
+ ]
978
+ }
979
+ ]
980
+ });
981
+ authState.creds.registered = true;
982
+ ev.emit('creds.update', authState.creds);
983
+ break;
984
+ }
985
+ case 'privacy_token':
986
+ await handlePrivacyTokenNotification(node);
987
+ break;
988
+ }
989
+ if (Object.keys(result).length) {
990
+ return result;
991
+ }
992
+ };
993
+ /**
994
+ * In-memory cache of storage JIDs with stored tctokens, seeded from the persisted index.
995
+ * Used to coalesce writes during a session; pruning always re-reads the persisted index
996
+ * to cover writes made by other layers (e.g. history sync).
997
+ */
998
+ const tcTokenKnownJids = new Set();
999
+ const tcTokenIndexLoaded = (async () => {
1000
+ try {
1001
+ const jids = await readTcTokenIndex(authState.keys);
1002
+ for (const jid of jids)
1003
+ tcTokenKnownJids.add(jid);
1004
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
1005
+ }
1006
+ catch (err) {
1007
+ logger.warn({ err: err?.message }, 'failed to load tctoken index');
1008
+ }
1009
+ })();
1010
+ let tcTokenIndexTimer;
1011
+ async function flushTcTokenIndex() {
1012
+ if (tcTokenIndexTimer) {
1013
+ clearTimeout(tcTokenIndexTimer);
1014
+ tcTokenIndexTimer = undefined;
1015
+ }
1016
+ // Merge with whatever is already persisted so we don't clobber writes from other
1017
+ // paths (history sync, concurrent sessions on the same store).
1018
+ const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
1019
+ return authState.keys.set({ tctoken: write });
1020
+ }
1021
+ function scheduleTcTokenIndexSave() {
1022
+ if (tcTokenIndexTimer) {
1023
+ clearTimeout(tcTokenIndexTimer);
1024
+ }
1025
+ tcTokenIndexTimer = setTimeout(() => {
1026
+ tcTokenIndexTimer = undefined;
1027
+ flushTcTokenIndex().catch(err => {
1028
+ logger.warn({ err: err?.message }, 'failed to save tctoken index');
1029
+ });
1030
+ }, 5000);
1031
+ }
1032
+ function trackTcTokenJid(jid) {
1033
+ if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
1034
+ tcTokenKnownJids.add(jid);
1035
+ scheduleTcTokenIndexSave();
1036
+ }
1037
+ }
1038
+ const handlePrivacyTokenNotification = async (node) => {
1039
+ const tokensNode = getBinaryNodeChild(node, 'tokens');
1040
+ if (!tokensNode)
1041
+ return;
1042
+ const from = jidNormalizedUser(node.attrs.from);
1043
+ // WA Web uses: senderLid ?? toLid(from) for the storage key
1044
+ // The sender_lid attribute provides the LID directly when available
1045
+ const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
1046
+ ? jidNormalizedUser(node.attrs.sender_lid)
1047
+ : undefined;
1048
+ const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
1049
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
1050
+ await storeTcTokensFromIqResult({
1051
+ result: node,
1052
+ fallbackJid,
1053
+ keys: authState.keys,
1054
+ getLIDForPN,
1055
+ onNewJidStored: trackTcTokenJid
1056
+ });
1057
+ };
1058
+ async function decipherLinkPublicKey(data) {
1059
+ const buffer = toRequiredBuffer(data);
1060
+ const salt = buffer.slice(0, 32);
1061
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
1062
+ const iv = buffer.slice(32, 48);
1063
+ const payload = buffer.slice(48, 80);
1064
+ return aesDecryptCTR(payload, secretKey, iv);
1065
+ }
1066
+ function toRequiredBuffer(data) {
1067
+ if (data === undefined) {
1068
+ throw new Boom('Invalid buffer', { statusCode: 400 });
1069
+ }
1070
+ return data instanceof Buffer ? data : Buffer.from(data);
1071
+ }
1072
+ const willSendMessageAgain = async (id, participant) => {
1073
+ const key = `${id}:${participant}`;
1074
+ const retryCount = await getRetryCount(key, 0);
1075
+ return retryCount < maxMsgRetryCount;
1076
+ };
1077
+ const updateSendMessageAgainCount = async (id, participant) => {
1078
+ const key = `${id}:${participant}`;
1079
+ const newValue = (await getRetryCount(key, 0)) + 1;
1080
+ await msgRetryCache.set(key, newValue);
1081
+ };
1082
+ const acceptRetryIds = async (ids, participant) => {
1083
+ const accepted = [];
1084
+ for (const id of ids) {
1085
+ if (id && (await willSendMessageAgain(id, participant))) {
1086
+ accepted.push(id);
1087
+ await updateSendMessageAgainCount(id, participant);
1088
+ }
1089
+ }
1090
+ return accepted;
1091
+ };
1092
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1093
+ const remoteJid = key.remoteJid;
1094
+ const participant = key.participant || remoteJid;
1095
+ const retryCount = +retryNode.attrs.count || 1;
1096
+ const msgId = ids[0];
1097
+ // Try to get messages from cache first, then fallback to getMessage
1098
+ const msgs = [];
1099
+ for (const id of ids) {
1100
+ let msg;
1101
+ // Try to get from retry cache first if enabled
1102
+ if (messageRetryManager) {
1103
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1104
+ if (cachedMsg) {
1105
+ msg = cachedMsg.message;
1106
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
1107
+ // Mark retry as successful since we found the message
1108
+ messageRetryManager.markRetrySuccess(id);
1109
+ }
1110
+ }
1111
+ // Fallback to getMessage if not found in cache
1112
+ if (!msg) {
1113
+ msg = await getMessage({ ...key, id });
1114
+ if (msg) {
1115
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
1116
+ // Also mark as successful if found via getMessage
1117
+ if (messageRetryManager) {
1118
+ messageRetryManager.markRetrySuccess(id);
1119
+ }
1120
+ }
1121
+ }
1122
+ msgs.push(msg);
1123
+ }
1124
+ // if it's the primary jid sending the request
1125
+ // just re-send the message to everyone
1126
+ // prevents the first message decryption failure
1127
+ const sendToAll = !jidDecode(participant)?.device;
1128
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1129
+ let injectedFromBundle = false;
1130
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
1131
+ if (bundle) {
1132
+ try {
1133
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
1134
+ injectedFromBundle = true;
1135
+ logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
1136
+ }
1137
+ catch (error) {
1138
+ logger.warn({ error, participant }, 'failed to inject session from retry receipt');
1139
+ }
1140
+ }
1141
+ if (!injectedFromBundle) {
1142
+ const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
1143
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
1144
+ const info = await signalRepository.getSessionInfo(participant);
1145
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
1146
+ logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
1147
+ await authState.keys.set({ session: { [sessionId]: null } });
1148
+ }
1149
+ }
1150
+ }
1151
+ const BASE_KEY_CHECK_RETRY = 2;
1152
+ if (msgId && messageRetryManager) {
1153
+ const info = await signalRepository.getSessionInfo(participant);
1154
+ if (info) {
1155
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1156
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1157
+ }
1158
+ else if (retryCount > BASE_KEY_CHECK_RETRY) {
1159
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
1160
+ logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
1161
+ await authState.keys.set({ session: { [sessionId]: null } });
1162
+ }
1163
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1164
+ }
1165
+ }
1166
+ }
1167
+ let shouldRecreateSession = false;
1168
+ let recreateReason = '';
1169
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
1170
+ try {
1171
+ const hasSession = await signalRepository.validateSession(participant);
1172
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists);
1173
+ shouldRecreateSession = result.recreate;
1174
+ recreateReason = result.reason;
1175
+ if (shouldRecreateSession) {
1176
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
1177
+ await authState.keys.set({ session: { [sessionId]: null } });
1178
+ }
1179
+ }
1180
+ catch (error) {
1181
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
1182
+ }
1183
+ }
1184
+ if (!injectedFromBundle) {
1185
+ await assertSessions([participant], true);
1186
+ }
1187
+ if (isJidGroup(remoteJid)) {
1188
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1189
+ }
1190
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
1191
+ for (const [i, msg] of msgs.entries()) {
1192
+ const id = ids[i];
1193
+ if (!id)
1194
+ continue;
1195
+ if (msg) {
1196
+ const msgRelayOpts = { messageId: id };
1197
+ if (sendToAll) {
1198
+ msgRelayOpts.useUserDevicesCache = false;
1199
+ }
1200
+ else {
1201
+ msgRelayOpts.participant = {
1202
+ jid: participant,
1203
+ count: +retryNode.attrs.count
1204
+ };
1205
+ }
1206
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1207
+ }
1208
+ else {
1209
+ logger.debug({ jid: key.remoteJid, id }, 'recv retry request, but message not available');
1210
+ }
1211
+ }
1212
+ };
1213
+ const handleReceipt = async (node) => {
1214
+ const { attrs, content } = node;
1215
+ const isLid = attrs.from.includes('lid');
1216
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1217
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1218
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
1219
+ const key = {
1220
+ remoteJid,
1221
+ id: '',
1222
+ fromMe,
1223
+ participant: attrs.participant
1224
+ };
1225
+ const ids = [attrs.id];
1226
+ if (Array.isArray(content)) {
1227
+ const items = getBinaryNodeChildren(content[0], 'item');
1228
+ ids.push(...items.map(i => i.attrs.id));
1229
+ }
1230
+ try {
1231
+ await Promise.all([
1232
+ receiptMutex.mutex(async () => {
1233
+ const status = getStatusFromReceiptType(attrs.type);
1234
+ if (typeof status !== 'undefined' &&
1235
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
1236
+ // or another device of ours has read some messages
1237
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
1238
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
1239
+ if (attrs.participant) {
1240
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
1241
+ ev.emit('message-receipt.update', ids.map(id => ({
1242
+ key: { ...key, id },
1243
+ receipt: {
1244
+ userJid: jidNormalizedUser(attrs.participant),
1245
+ [updateKey]: +attrs.t
1246
+ }
1247
+ })));
1248
+ }
1249
+ }
1250
+ else {
1251
+ ev.emit('messages.update', ids.map(id => ({
1252
+ key: { ...key, id },
1253
+ update: { status }
1254
+ })));
1255
+ const timestamp = Number(attrs.t);
1256
+ const timestampField = status === proto.WebMessageInfo.Status.DELIVERY_ACK
1257
+ ? 'receiptTimestamp'
1258
+ : status === proto.WebMessageInfo.Status.READ
1259
+ ? 'readTimestamp'
1260
+ : status === proto.WebMessageInfo.Status.PLAYED
1261
+ ? 'playedTimestamp'
1262
+ : undefined;
1263
+ if (!isJidBroadcast(remoteJid) &&
1264
+ !isJidBroadcast(attrs.from) &&
1265
+ timestampField &&
1266
+ Number.isSafeInteger(timestamp) &&
1267
+ timestamp > 0) {
1268
+ ev.emit('message-receipt.update', ids.map(id => ({
1269
+ key: { ...key, id },
1270
+ receipt: { userJid: jidNormalizedUser(attrs.from), [timestampField]: timestamp }
1271
+ })));
1272
+ }
1273
+ }
1274
+ }
1275
+ if (attrs.type === 'retry') {
1276
+ // correctly set who is asking for the retry
1277
+ key.participant = key.participant || attrs.from;
1278
+ const retryNode = getBinaryNodeChild(node, 'retry');
1279
+ if (!key.fromMe) {
1280
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
1281
+ return;
1282
+ }
1283
+ try {
1284
+ const acceptedIds = key.participant ? await acceptRetryIds(ids, key.participant) : [];
1285
+ if (acceptedIds.length === 0) {
1286
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
1287
+ return;
1288
+ }
1289
+ logger.debug({ attrs, key }, 'recv retry request');
1290
+ await sendMessagesAgain(key, acceptedIds, retryNode, node);
1291
+ }
1292
+ catch (error) {
1293
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
1294
+ }
1295
+ }
1296
+ })
1297
+ ]);
1298
+ }
1299
+ finally {
1300
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
1301
+ }
1302
+ };
1303
+ const handleNotification = async (node) => {
1304
+ const remoteJid = node.attrs.from;
1305
+ try {
1306
+ await Promise.all([
1307
+ notificationMutex.mutex(async () => {
1308
+ const msg = await processNotification(node);
1309
+ if (msg) {
1310
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
1311
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
1312
+ msg.key = {
1313
+ remoteJid,
1314
+ fromMe,
1315
+ participant: node.attrs.participant,
1316
+ participantAlt,
1317
+ participantUsername: node.attrs.participant_username,
1318
+ addressingMode,
1319
+ id: node.attrs.id,
1320
+ ...(msg.key || {})
1321
+ };
1322
+ msg.participant ?? (msg.participant = node.attrs.participant);
1323
+ msg.messageTimestamp = +node.attrs.t;
1324
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
1325
+ await upsertMessage(fullMsg, 'append');
1326
+ }
1327
+ })
1328
+ ]);
1329
+ }
1330
+ finally {
1331
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
1332
+ }
1333
+ };
1334
+ const handleMessage = async (node) => {
1335
+ const encNode = getBinaryNodeChild(node, 'enc');
1336
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1337
+ if (encNode?.attrs.type === 'msmsg') {
1338
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
1339
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
1340
+ return;
1341
+ }
1342
+ let acked = false;
1343
+ try {
1344
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1345
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1346
+ // store new mappings we didn't have before
1347
+ if (!!alt) {
1348
+ const altServer = jidDecode(alt)?.server;
1349
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1350
+ if (altServer === 'lid') {
1351
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1352
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1353
+ await signalRepository.migrateSession(primaryJid, alt);
1354
+ }
1355
+ }
1356
+ else {
1357
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1358
+ await signalRepository.migrateSession(alt, primaryJid);
1359
+ }
1360
+ }
1361
+ await messageMutex.mutex(async () => {
1362
+ await decrypt();
1363
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1364
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1365
+ }
1366
+ // message failed to decrypt
1367
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1368
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1369
+ acked = true;
1370
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
1371
+ }
1372
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1373
+ // Message arrived without encryption (e.g. CTWA ads messages).
1374
+ // Check if this is eligible for placeholder resend (matching WA Web filters).
1375
+ const unavailableNode = getBinaryNodeChild(node, 'unavailable');
1376
+ const unavailableType = unavailableNode?.attrs?.type;
1377
+ if (unavailableType === 'bot_unavailable_fanout' ||
1378
+ unavailableType === 'hosted_unavailable_fanout' ||
1379
+ unavailableType === 'view_once_unavailable_fanout') {
1380
+ logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1381
+ acked = true;
1382
+ return sendMessageAck(node);
1383
+ }
1384
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1385
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1386
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
1387
+ acked = true;
1388
+ return sendMessageAck(node);
1389
+ }
1390
+ // Request the real content from the phone via placeholder resend PDO.
1391
+ // Upsert the CIPHERTEXT stub as a placeholder (like WA Web's processPlaceholderMsg),
1392
+ // and store the requestId in stubParameters[1] so users can correlate
1393
+ // with the incoming PDO response event.
1394
+ const cleanKey = {
1395
+ remoteJid: msg.key.remoteJid,
1396
+ fromMe: msg.key.fromMe,
1397
+ id: msg.key.id,
1398
+ participant: msg.key.participant
1399
+ };
1400
+ // Cache the original message metadata so the PDO response handler
1401
+ // can preserve key fields (LID details etc.) that the phone may omit
1402
+ const msgData = {
1403
+ key: msg.key,
1404
+ messageTimestamp: msg.messageTimestamp,
1405
+ pushName: msg.pushName,
1406
+ participant: msg.participant,
1407
+ verifiedBizName: msg.verifiedBizName
1408
+ };
1409
+ requestPlaceholderResend(cleanKey, msgData)
1410
+ .then(requestId => {
1411
+ if (requestId && requestId !== 'RESOLVED') {
1412
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
1413
+ ev.emit('messages.update', [
1414
+ {
1415
+ key: msg.key,
1416
+ update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
1417
+ }
1418
+ ]);
1419
+ }
1420
+ })
1421
+ .catch(err => {
1422
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1423
+ });
1424
+ acked = true;
1425
+ await sendMessageAck(node);
1426
+ // Don't return — fall through to upsertMessage so the stub is emitted
1427
+ }
1428
+ else {
1429
+ // A retry receipt only makes sense for a message from SOMEONE ELSE.
1430
+ // An undecryptable `fromMe` message is the echo of our own account
1431
+ // synced from another of our devices (sender fanout / deviceSentMessage),
1432
+ // encrypted under the ORIGINATING device's session — not under a session
1433
+ // this client holds. Asking for a resend is asking ourselves; the server
1434
+ // answers with `<stream:error><ack/>` and tears the stream down (surfaces
1435
+ // as a 500 "bad session" close, which it is not). Ack and move on: a retry
1436
+ // for our own message cannot bring the content back, and keeping the
1437
+ // connection alive is what matters.
1438
+ if (msg.key.fromMe) {
1439
+ logger.debug({ key: msg.key }, 'undecryptable fromMe message: acking without a retry receipt');
1440
+ acked = true;
1441
+ return sendMessageAck(node);
1442
+ }
1443
+ // Skip retry for expired status messages (>24h old)
1444
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
1445
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1446
+ if (messageAge > STATUS_EXPIRY_SECONDS) {
1447
+ logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1448
+ acked = true;
1449
+ return sendMessageAck(node);
1450
+ }
1451
+ }
1452
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1453
+ // WAWeb only retry-receipts here; server emits PreKeyLow if prekeys run low.
1454
+ await retryMutex.mutex(async () => {
1455
+ try {
1456
+ if (!ws.isOpen) {
1457
+ logger.debug({ node }, 'Connection closed, skipping retry');
1458
+ return;
1459
+ }
1460
+ const encNode = getBinaryNodeChild(node, 'enc');
1461
+ await sendRetryRequest(node, !encNode);
1462
+ if (retryRequestDelayMs) {
1463
+ await delay(retryRequestDelayMs);
1464
+ }
1465
+ }
1466
+ catch (err) {
1467
+ logger.error({ err }, 'Failed to send retry');
1468
+ }
1469
+ acked = true;
1470
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1471
+ });
1472
+ }
1473
+ }
1474
+ else {
1475
+ if (messageRetryManager && msg.key.id) {
1476
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1477
+ }
1478
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1479
+ if (!isNewsletter) {
1480
+ // no type in the receipt => message delivered
1481
+ let type = undefined;
1482
+ let participant = msg.key.participant;
1483
+ if (category === 'peer') {
1484
+ // special peer message
1485
+ type = 'peer_msg';
1486
+ }
1487
+ else if (msg.key.fromMe) {
1488
+ // message was sent by us from a different device
1489
+ type = 'sender';
1490
+ // need to specially handle this case
1491
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1492
+ participant = author; // TODO: investigate sending receipts to LIDs and not PNs
1493
+ }
1494
+ }
1495
+ else if (!sendActiveReceipts) {
1496
+ type = 'inactive';
1497
+ }
1498
+ acked = true;
1499
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1500
+ // send ack for history message
1501
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1502
+ if (isAnyHistoryMsg) {
1503
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1504
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync'); // TODO: investigate
1505
+ }
1506
+ }
1507
+ else {
1508
+ acked = true;
1509
+ await sendMessageAck(node);
1510
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1511
+ }
1512
+ }
1513
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1514
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1515
+ });
1516
+ }
1517
+ catch (error) {
1518
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1519
+ if (!acked) {
1520
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
1521
+ }
1522
+ }
1523
+ };
1524
+ const handleCall = async (node) => {
1525
+ try {
1526
+ const { attrs } = node;
1527
+ const [infoChild] = getAllBinaryNodeChildren(node);
1528
+ if (!infoChild) {
1529
+ throw new Boom('Missing call info in call node');
1530
+ }
1531
+ const status = getCallStatusFromNode(infoChild);
1532
+ const callId = infoChild.attrs['call-id'];
1533
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1534
+ const call = {
1535
+ chatId: attrs.from,
1536
+ from,
1537
+ callerPn: infoChild.attrs['caller_pn'],
1538
+ id: callId,
1539
+ date: new Date(+attrs.t * 1000),
1540
+ offline: !!attrs.offline,
1541
+ status
1542
+ };
1543
+ if (status === 'relaylatency') {
1544
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
1545
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1546
+ if (Number.isFinite(latencyMs)) {
1547
+ call.latencyMs = latencyMs;
1548
+ }
1549
+ }
1550
+ if (status === 'offer') {
1551
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1552
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1553
+ call.groupJid = infoChild.attrs['group-jid'];
1554
+ await callOfferCache.set(call.id, call);
1555
+ }
1556
+ const existingCall = await callOfferCache.get(call.id);
1557
+ // use existing call info to populate this event
1558
+ if (existingCall) {
1559
+ call.isVideo = existingCall.isVideo;
1560
+ call.isGroup = existingCall.isGroup;
1561
+ call.callerPn = call.callerPn || existingCall.callerPn;
1562
+ }
1563
+ // delete data once call has ended
1564
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1565
+ await callOfferCache.del(call.id);
1566
+ }
1567
+ ev.emit('call', [call]);
1568
+ }
1569
+ catch (error) {
1570
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1571
+ }
1572
+ finally {
1573
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1574
+ }
1575
+ };
1576
+ const handleBadAck = async ({ attrs }) => {
1577
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1578
+ // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1579
+ // // current hypothesis is that if pash is sent in the ack
1580
+ // // it means -- the message hasn't reached all devices yet
1581
+ // // we'll retry sending the message here
1582
+ // if(attrs.phash) {
1583
+ // logger.info({ attrs }, 'received phash in ack, resending message...')
1584
+ // const msg = await getMessage(key)
1585
+ // if(msg) {
1586
+ // await relayMessage(key.remoteJid!, msg, { messageId: key.id!, useUserDevicesCache: false })
1587
+ // } else {
1588
+ // logger.warn({ attrs }, 'could not send message again, as it was not found')
1589
+ // }
1590
+ // }
1591
+ // error in acknowledgement,
1592
+ // device could not display the message
1593
+ if (attrs.error) {
1594
+ const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
1595
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
1596
+ // 463 = 1:1 message missing privacy token (tctoken). Usually means the
1597
+ // account is restricted: WhatsApp blocks starting new chats but preserves
1598
+ // existing ones, since established chats already carry a tctoken.
1599
+ // WA Web prevents this client-side (disables the compose bar).
1600
+ // No retry — retrying counts as another "reach out" and worsens the restriction.
1601
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
1602
+ const ackFrom = attrs.from;
1603
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
1604
+ inFlight463Recoveries.add(ackFrom);
1605
+ void (async () => {
1606
+ try {
1607
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1608
+ const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
1609
+ const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
1610
+ const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
1611
+ await storeTcTokensFromIqResult({
1612
+ result,
1613
+ fallbackJid: tcStorageJid,
1614
+ keys: authState.keys,
1615
+ getLIDForPN,
1616
+ onNewJidStored: trackTcTokenJid
1617
+ });
1618
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
1619
+ }
1620
+ catch (err) {
1621
+ logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
1622
+ }
1623
+ finally {
1624
+ inFlight463Recoveries.delete(ackFrom);
1625
+ }
1626
+ })();
1627
+ }
1628
+ }
1629
+ else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
1630
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1631
+ }
1632
+ else if (isReachoutTimelocked) {
1633
+ // user is temporarily restricted, fetch current restriction details
1634
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
1635
+ logger.warn({ attrs }, 'received error in ack');
1636
+ }
1637
+ else {
1638
+ logger.warn({ attrs }, 'received error in ack');
1639
+ }
1640
+ ev.emit('messages.update', [
1641
+ {
1642
+ key,
1643
+ update: {
1644
+ status: WAMessageStatus.ERROR,
1645
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1646
+ }
1647
+ }
1648
+ ]);
1649
+ }
1650
+ };
1651
+ /// processes a node with the given function
1652
+ /// and adds the task to the existing buffer if we're buffering events
1653
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1654
+ ev.buffer();
1655
+ await execTask();
1656
+ ev.flush();
1657
+ function execTask() {
1658
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1659
+ }
1660
+ };
1661
+ const handleChannelStatus = async (node) => {
1662
+ const status = decodeChannelStatus(node);
1663
+ if (!status) {
1664
+ try {
1665
+ await sendMessageAck(node);
1666
+ }
1667
+ catch (error) {
1668
+ onUnexpectedError(error, 'acking status stanza');
1669
+ }
1670
+ return;
1671
+ }
1672
+ ev.buffer();
1673
+ ev.emit('newsletter.status', status);
1674
+ ev.flush();
1675
+ };
1676
+ const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1677
+ ['message', handleMessage],
1678
+ ['call', handleCall],
1679
+ ['receipt', handleReceipt],
1680
+ ['notification', handleNotification],
1681
+ ['status', handleChannelStatus]
1682
+ ]), {
1683
+ isWsOpen: () => ws.isOpen,
1684
+ onUnexpectedError,
1685
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1686
+ });
1687
+ const processNode = async (type, node, identifier, exec) => {
1688
+ // Fast path: ack and drop ignored JIDs before entering the buffer/queue
1689
+ const from = node.attrs.from;
1690
+ let ignoreJid = from;
1691
+ if (type === 'receipt' && from) {
1692
+ const attrs = node.attrs;
1693
+ const isLid = attrs.from.includes('lid');
1694
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1695
+ ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1696
+ }
1697
+ if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
1698
+ await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
1699
+ return;
1700
+ }
1701
+ const isOffline = !!node.attrs.offline;
1702
+ if (isOffline) {
1703
+ offlineNodeProcessor.enqueue(type, node);
1704
+ }
1705
+ else {
1706
+ await processNodeWithBuffer(node, identifier, exec);
1707
+ }
1708
+ };
1709
+ // channel statuses arrive as top-level <status> stanzas from a channel's
1710
+ // @newsletter JID, not as messages — see Socket/channelStatus.ts. A newsletter
1711
+ // status is not acked: the socket delivers live and offline ones without it,
1712
+ // and acking a newsletter status is not part of the protocol here. But a
1713
+ // CONTACT's status can arrive the same way (top-level <status> instead of
1714
+ // <message from="status@broadcast">) and that one MUST be acked, or the server
1715
+ // ends the stream ~50 minutes later and redelivers it on reconnect
1716
+ // (upstream #2883). decodeChannelStatus returns null for non-@newsletter
1717
+ // senders, so a null here means "contact status: ack it".
1718
+ // recv a message
1719
+ ws.on('CB:message', async (node) => {
1720
+ await processNode('message', node, 'processing message', handleMessage);
1721
+ });
1722
+ ws.on('CB:status', async (node) => {
1723
+ await handleChannelStatus(node).catch(error => onUnexpectedError(error, 'handling channel status'));
1724
+ });
1725
+ ws.on('CB:call', async (node) => {
1726
+ await processNode('call', node, 'handling call', handleCall);
1727
+ });
1728
+ ws.on('CB:receipt', async (node) => {
1729
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
1730
+ });
1731
+ ws.on('CB:notification', async (node) => {
1732
+ await processNode('notification', node, 'handling notification', handleNotification);
1733
+ });
1734
+ ws.on('CB:ack,class:message', (node) => {
1735
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1736
+ });
1737
+ ev.on('call', async ([call]) => {
1738
+ if (!call) {
1739
+ return;
1740
+ }
1741
+ // missed call + group call notification message generation
1742
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1743
+ const msg = {
1744
+ key: {
1745
+ remoteJid: call.chatId,
1746
+ id: call.id,
1747
+ fromMe: false
1748
+ },
1749
+ messageTimestamp: unixTimestampSeconds(call.date)
1750
+ };
1751
+ if (call.status === 'timeout') {
1752
+ if (call.isGroup) {
1753
+ msg.messageStubType = call.isVideo
1754
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1755
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1756
+ }
1757
+ else {
1758
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1759
+ }
1760
+ }
1761
+ else {
1762
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1763
+ }
1764
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
1765
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1766
+ }
1767
+ });
1768
+ /** timestamp of last tctoken prune run — throttles to once per 24h */
1769
+ let lastTcTokenPruneTs = 0;
1770
+ /** dedupe in-flight 463 recovery token issuance by target JID */
1771
+ const inFlight463Recoveries = new Set();
1772
+ ev.on('connection.update', ({ isOnline, connection }) => {
1773
+ if (typeof isOnline !== 'undefined') {
1774
+ sendActiveReceipts = isOnline;
1775
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1776
+ }
1777
+ // Flush pending tctoken index save on disconnect to avoid writing after close
1778
+ if (connection === 'close' && tcTokenIndexTimer) {
1779
+ clearTimeout(tcTokenIndexTimer);
1780
+ tcTokenIndexTimer = undefined;
1781
+ // Best-effort flush — may fail if store is already closed
1782
+ try {
1783
+ void Promise.resolve(flushTcTokenIndex()).catch(() => { });
1784
+ }
1785
+ catch {
1786
+ /* ignore sync errors */
1787
+ }
1788
+ }
1789
+ // Prune expired tctokens when coming online, at most once per 24 hours
1790
+ // Matches WA Web's CLEAN_TC_TOKENS task
1791
+ // Note: don't gate on tcTokenKnownJids.size — the index may still be loading
1792
+ if (isOnline) {
1793
+ const now = Date.now();
1794
+ const DAY_MS = 24 * 60 * 60 * 1000;
1795
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
1796
+ lastTcTokenPruneTs = now;
1797
+ void pruneExpiredTcTokens();
1798
+ }
1799
+ }
1800
+ });
1801
+ registerSocketEndHandler(() => {
1802
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
1803
+ msgRetryCache.close();
1804
+ }
1805
+ if (!config.callOfferCache && callOfferCache.close) {
1806
+ callOfferCache.close();
1807
+ }
1808
+ identityAssertDebounce.close();
1809
+ sendActiveReceipts = false;
1810
+ });
1811
+ async function pruneExpiredTcTokens() {
1812
+ try {
1813
+ await tcTokenIndexLoaded;
1814
+ // Union with the persisted index picks up JIDs added by other layers
1815
+ // (history sync) without needing inter-module wiring.
1816
+ const persisted = await readTcTokenIndex(authState.keys);
1817
+ const allJids = new Set(tcTokenKnownJids);
1818
+ for (const jid of persisted)
1819
+ allJids.add(jid);
1820
+ if (!allJids.size)
1821
+ return;
1822
+ const jids = [...allJids];
1823
+ const allTokens = await authState.keys.get('tctoken', jids);
1824
+ const writes = {};
1825
+ const survivors = new Set();
1826
+ let mutated = 0;
1827
+ for (const jid of jids) {
1828
+ const entry = allTokens[jid];
1829
+ if (!entry) {
1830
+ // Tracked but nothing in store — drop from index.
1831
+ mutated++;
1832
+ continue;
1833
+ }
1834
+ const hasPeerToken = !!entry.token?.length;
1835
+ const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
1836
+ const hasSenderTs = entry.senderTimestamp !== undefined;
1837
+ const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
1838
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
1839
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
1840
+ if (!keepPeerToken && !keepSenderTs) {
1841
+ writes[jid] = null;
1842
+ mutated++;
1843
+ }
1844
+ else if (peerTokenExpired && keepSenderTs) {
1845
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
1846
+ survivors.add(jid);
1847
+ mutated++;
1848
+ }
1849
+ else {
1850
+ survivors.add(jid);
1851
+ }
1852
+ }
1853
+ if (mutated === 0)
1854
+ return;
1855
+ await authState.keys.set({
1856
+ tctoken: {
1857
+ ...writes,
1858
+ [TC_TOKEN_INDEX_KEY]: {
1859
+ token: Buffer.from(JSON.stringify([...survivors]))
1860
+ }
1861
+ }
1862
+ });
1863
+ tcTokenKnownJids.clear();
1864
+ for (const jid of survivors)
1865
+ tcTokenKnownJids.add(jid);
1866
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
1867
+ }
1868
+ catch (err) {
1869
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
1870
+ }
1871
+ }
1872
+ return {
1873
+ ...sock,
1874
+ sendArticleCard: (jid, card) => sock.sendMessage(jid, {
1875
+ text: card.text ?? '',
1876
+ contextInfo: {
1877
+ externalAdReply: {
1878
+ title: card.title,
1879
+ body: card.body,
1880
+ mediaType: card.mediaType ?? proto.ContextInfo.ExternalAdReplyInfo.MediaType.IMAGE,
1881
+ thumbnailUrl: card.thumbnailUrl,
1882
+ sourceUrl: card.url,
1883
+ containsAutoReply: card.containsAutoReply,
1884
+ renderLargerThumbnail: card.renderLargerThumbnail,
1885
+ showAdAttribution: card.showAdAttribution
1886
+ }
1887
+ }
1888
+ }),
1889
+ sendMessageAck,
1890
+ sendRetryRequest,
1891
+ rejectCall,
1892
+ fetchMessageHistory,
1893
+ requestPlaceholderResend,
1894
+ messageRetryManager
1895
+ };
1896
+ };
1897
+ //# sourceMappingURL=messages-recv.js.map