@violetix/baileys 0.0.0-stage → 0.3.18

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