@neykoor/baileys 7.0.0-rc13

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 (465) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +78 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +145 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +83 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +31 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +431 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +20 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +281 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +271 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +128 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1150 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +316 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +415 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +160 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +498 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +314 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +12 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +257 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1697 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +253 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1309 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +4 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +62 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +192 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +419 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +59 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +983 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Store/index.d.ts +5 -0
  122. package/lib/Store/index.d.ts.map +1 -0
  123. package/lib/Store/index.js +5 -0
  124. package/lib/Store/index.js.map +1 -0
  125. package/lib/Store/make-in-memory-store.d.ts +115 -0
  126. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  127. package/lib/Store/make-in-memory-store.js +428 -0
  128. package/lib/Store/make-in-memory-store.js.map +1 -0
  129. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  130. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  131. package/lib/Store/make-ordered-dictionary.js +87 -0
  132. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  133. package/lib/Store/make-sqlite-store.d.ts +41 -0
  134. package/lib/Store/make-sqlite-store.d.ts.map +1 -0
  135. package/lib/Store/make-sqlite-store.js +254 -0
  136. package/lib/Store/make-sqlite-store.js.map +1 -0
  137. package/lib/Store/object-repository.d.ts +13 -0
  138. package/lib/Store/object-repository.d.ts.map +1 -0
  139. package/lib/Store/object-repository.js +24 -0
  140. package/lib/Store/object-repository.js.map +1 -0
  141. package/lib/Types/Auth.d.ts +117 -0
  142. package/lib/Types/Auth.d.ts.map +1 -0
  143. package/lib/Types/Auth.js +2 -0
  144. package/lib/Types/Auth.js.map +1 -0
  145. package/lib/Types/Bussines.d.ts +25 -0
  146. package/lib/Types/Bussines.d.ts.map +1 -0
  147. package/lib/Types/Bussines.js +2 -0
  148. package/lib/Types/Bussines.js.map +1 -0
  149. package/lib/Types/Call.d.ts +15 -0
  150. package/lib/Types/Call.d.ts.map +1 -0
  151. package/lib/Types/Call.js +2 -0
  152. package/lib/Types/Call.js.map +1 -0
  153. package/lib/Types/Chat.d.ts +124 -0
  154. package/lib/Types/Chat.d.ts.map +1 -0
  155. package/lib/Types/Chat.js +8 -0
  156. package/lib/Types/Chat.js.map +1 -0
  157. package/lib/Types/Contact.d.ts +26 -0
  158. package/lib/Types/Contact.d.ts.map +1 -0
  159. package/lib/Types/Contact.js +2 -0
  160. package/lib/Types/Contact.js.map +1 -0
  161. package/lib/Types/Events.d.ts +256 -0
  162. package/lib/Types/Events.d.ts.map +1 -0
  163. package/lib/Types/Events.js +2 -0
  164. package/lib/Types/Events.js.map +1 -0
  165. package/lib/Types/GroupMetadata.d.ts +71 -0
  166. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  167. package/lib/Types/GroupMetadata.js +2 -0
  168. package/lib/Types/GroupMetadata.js.map +1 -0
  169. package/lib/Types/Label.d.ts +47 -0
  170. package/lib/Types/Label.d.ts.map +1 -0
  171. package/lib/Types/Label.js +25 -0
  172. package/lib/Types/Label.js.map +1 -0
  173. package/lib/Types/LabelAssociation.d.ts +30 -0
  174. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  175. package/lib/Types/LabelAssociation.js +7 -0
  176. package/lib/Types/LabelAssociation.js.map +1 -0
  177. package/lib/Types/Message.d.ts +302 -0
  178. package/lib/Types/Message.d.ts.map +1 -0
  179. package/lib/Types/Message.js +10 -0
  180. package/lib/Types/Message.js.map +1 -0
  181. package/lib/Types/Mex.d.ts +154 -0
  182. package/lib/Types/Mex.d.ts.map +1 -0
  183. package/lib/Types/Mex.js +39 -0
  184. package/lib/Types/Mex.js.map +1 -0
  185. package/lib/Types/Product.d.ts +79 -0
  186. package/lib/Types/Product.d.ts.map +1 -0
  187. package/lib/Types/Product.js +2 -0
  188. package/lib/Types/Product.js.map +1 -0
  189. package/lib/Types/Signal.d.ts +87 -0
  190. package/lib/Types/Signal.d.ts.map +1 -0
  191. package/lib/Types/Signal.js +2 -0
  192. package/lib/Types/Signal.js.map +1 -0
  193. package/lib/Types/Socket.d.ts +141 -0
  194. package/lib/Types/Socket.d.ts.map +1 -0
  195. package/lib/Types/Socket.js +3 -0
  196. package/lib/Types/Socket.js.map +1 -0
  197. package/lib/Types/State.d.ts +100 -0
  198. package/lib/Types/State.d.ts.map +1 -0
  199. package/lib/Types/State.js +56 -0
  200. package/lib/Types/State.js.map +1 -0
  201. package/lib/Types/USync.d.ts +26 -0
  202. package/lib/Types/USync.d.ts.map +1 -0
  203. package/lib/Types/USync.js +2 -0
  204. package/lib/Types/USync.js.map +1 -0
  205. package/lib/Types/index.d.ts +66 -0
  206. package/lib/Types/index.d.ts.map +1 -0
  207. package/lib/Types/index.js +26 -0
  208. package/lib/Types/index.js.map +1 -0
  209. package/lib/Utils/auth-utils.d.ts +24 -0
  210. package/lib/Utils/auth-utils.d.ts.map +1 -0
  211. package/lib/Utils/auth-utils.js +302 -0
  212. package/lib/Utils/auth-utils.js.map +1 -0
  213. package/lib/Utils/browser-utils.d.ts +4 -0
  214. package/lib/Utils/browser-utils.d.ts.map +1 -0
  215. package/lib/Utils/browser-utils.js +29 -0
  216. package/lib/Utils/browser-utils.js.map +1 -0
  217. package/lib/Utils/business.d.ts +17 -0
  218. package/lib/Utils/business.d.ts.map +1 -0
  219. package/lib/Utils/business.js +226 -0
  220. package/lib/Utils/business.js.map +1 -0
  221. package/lib/Utils/chat-utils.d.ts +100 -0
  222. package/lib/Utils/chat-utils.d.ts.map +1 -0
  223. package/lib/Utils/chat-utils.js +872 -0
  224. package/lib/Utils/chat-utils.js.map +1 -0
  225. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  226. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  227. package/lib/Utils/companion-reg-client-utils.js +35 -0
  228. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  229. package/lib/Utils/crypto.d.ts +38 -0
  230. package/lib/Utils/crypto.d.ts.map +1 -0
  231. package/lib/Utils/crypto.js +118 -0
  232. package/lib/Utils/crypto.js.map +1 -0
  233. package/lib/Utils/decode-wa-message.d.ts +66 -0
  234. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  235. package/lib/Utils/decode-wa-message.js +321 -0
  236. package/lib/Utils/decode-wa-message.js.map +1 -0
  237. package/lib/Utils/event-buffer.d.ts +14 -0
  238. package/lib/Utils/event-buffer.d.ts.map +1 -0
  239. package/lib/Utils/event-buffer.js +597 -0
  240. package/lib/Utils/event-buffer.js.map +1 -0
  241. package/lib/Utils/generics.d.ts +92 -0
  242. package/lib/Utils/generics.d.ts.map +1 -0
  243. package/lib/Utils/generics.js +393 -0
  244. package/lib/Utils/generics.js.map +1 -0
  245. package/lib/Utils/history.d.ts +24 -0
  246. package/lib/Utils/history.d.ts.map +1 -0
  247. package/lib/Utils/history.js +134 -0
  248. package/lib/Utils/history.js.map +1 -0
  249. package/lib/Utils/identity-change-handler.d.ts +38 -0
  250. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  251. package/lib/Utils/identity-change-handler.js +50 -0
  252. package/lib/Utils/identity-change-handler.js.map +1 -0
  253. package/lib/Utils/index.d.ts +33 -0
  254. package/lib/Utils/index.d.ts.map +1 -0
  255. package/lib/Utils/index.js +33 -0
  256. package/lib/Utils/index.js.map +1 -0
  257. package/lib/Utils/link-preview.d.ts +21 -0
  258. package/lib/Utils/link-preview.d.ts.map +1 -0
  259. package/lib/Utils/link-preview.js +85 -0
  260. package/lib/Utils/link-preview.js.map +1 -0
  261. package/lib/Utils/logger-sinks.d.ts +9 -0
  262. package/lib/Utils/logger-sinks.d.ts.map +1 -0
  263. package/lib/Utils/logger-sinks.js +30 -0
  264. package/lib/Utils/logger-sinks.js.map +1 -0
  265. package/lib/Utils/logger.d.ts +13 -0
  266. package/lib/Utils/logger.d.ts.map +1 -0
  267. package/lib/Utils/logger.js +3 -0
  268. package/lib/Utils/logger.js.map +1 -0
  269. package/lib/Utils/lt-hash.d.ts +8 -0
  270. package/lib/Utils/lt-hash.d.ts.map +1 -0
  271. package/lib/Utils/lt-hash.js +8 -0
  272. package/lib/Utils/lt-hash.js.map +1 -0
  273. package/lib/Utils/make-mutex.d.ts +9 -0
  274. package/lib/Utils/make-mutex.d.ts.map +1 -0
  275. package/lib/Utils/make-mutex.js +33 -0
  276. package/lib/Utils/make-mutex.js.map +1 -0
  277. package/lib/Utils/media-cache.d.ts +17 -0
  278. package/lib/Utils/media-cache.d.ts.map +1 -0
  279. package/lib/Utils/media-cache.js +72 -0
  280. package/lib/Utils/media-cache.js.map +1 -0
  281. package/lib/Utils/message-composer.d.ts +93 -0
  282. package/lib/Utils/message-composer.d.ts.map +1 -0
  283. package/lib/Utils/message-composer.js +311 -0
  284. package/lib/Utils/message-composer.js.map +1 -0
  285. package/lib/Utils/message-retry-manager.d.ts +75 -0
  286. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  287. package/lib/Utils/message-retry-manager.js +239 -0
  288. package/lib/Utils/message-retry-manager.js.map +1 -0
  289. package/lib/Utils/messages-media.d.ts +162 -0
  290. package/lib/Utils/messages-media.d.ts.map +1 -0
  291. package/lib/Utils/messages-media.js +977 -0
  292. package/lib/Utils/messages-media.js.map +1 -0
  293. package/lib/Utils/messages-newsletter.d.ts +40 -0
  294. package/lib/Utils/messages-newsletter.d.ts.map +1 -0
  295. package/lib/Utils/messages-newsletter.js +61 -0
  296. package/lib/Utils/messages-newsletter.js.map +1 -0
  297. package/lib/Utils/messages.d.ts +92 -0
  298. package/lib/Utils/messages.d.ts.map +1 -0
  299. package/lib/Utils/messages.js +1050 -0
  300. package/lib/Utils/messages.js.map +1 -0
  301. package/lib/Utils/middleware.d.ts +29 -0
  302. package/lib/Utils/middleware.d.ts.map +1 -0
  303. package/lib/Utils/middleware.js +72 -0
  304. package/lib/Utils/middleware.js.map +1 -0
  305. package/lib/Utils/noise-handler.d.ts +20 -0
  306. package/lib/Utils/noise-handler.d.ts.map +1 -0
  307. package/lib/Utils/noise-handler.js +201 -0
  308. package/lib/Utils/noise-handler.js.map +1 -0
  309. package/lib/Utils/offline-node-processor.d.ts +12 -0
  310. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  311. package/lib/Utils/offline-node-processor.js +47 -0
  312. package/lib/Utils/offline-node-processor.js.map +1 -0
  313. package/lib/Utils/pre-key-manager.d.ts +13 -0
  314. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  315. package/lib/Utils/pre-key-manager.js +99 -0
  316. package/lib/Utils/pre-key-manager.js.map +1 -0
  317. package/lib/Utils/process-message.d.ts +60 -0
  318. package/lib/Utils/process-message.d.ts.map +1 -0
  319. package/lib/Utils/process-message.js +633 -0
  320. package/lib/Utils/process-message.js.map +1 -0
  321. package/lib/Utils/reconnect-manager.d.ts +21 -0
  322. package/lib/Utils/reconnect-manager.d.ts.map +1 -0
  323. package/lib/Utils/reconnect-manager.js +71 -0
  324. package/lib/Utils/reconnect-manager.js.map +1 -0
  325. package/lib/Utils/reporting-utils.d.ts +11 -0
  326. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  327. package/lib/Utils/reporting-utils.js +258 -0
  328. package/lib/Utils/reporting-utils.js.map +1 -0
  329. package/lib/Utils/session-manager.d.ts +22 -0
  330. package/lib/Utils/session-manager.d.ts.map +1 -0
  331. package/lib/Utils/session-manager.js +70 -0
  332. package/lib/Utils/session-manager.js.map +1 -0
  333. package/lib/Utils/shortcake-crypto.d.ts +27 -0
  334. package/lib/Utils/shortcake-crypto.d.ts.map +1 -0
  335. package/lib/Utils/shortcake-crypto.js +65 -0
  336. package/lib/Utils/shortcake-crypto.js.map +1 -0
  337. package/lib/Utils/shortcake.d.ts +31 -0
  338. package/lib/Utils/shortcake.d.ts.map +1 -0
  339. package/lib/Utils/shortcake.js +156 -0
  340. package/lib/Utils/shortcake.js.map +1 -0
  341. package/lib/Utils/signal.d.ts +47 -0
  342. package/lib/Utils/signal.d.ts.map +1 -0
  343. package/lib/Utils/signal.js +201 -0
  344. package/lib/Utils/signal.js.map +1 -0
  345. package/lib/Utils/stanza-ack.d.ts +11 -0
  346. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  347. package/lib/Utils/stanza-ack.js +38 -0
  348. package/lib/Utils/stanza-ack.js.map +1 -0
  349. package/lib/Utils/sync-action-utils.d.ts +19 -0
  350. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  351. package/lib/Utils/sync-action-utils.js +49 -0
  352. package/lib/Utils/sync-action-utils.js.map +1 -0
  353. package/lib/Utils/tc-token-utils.d.ts +37 -0
  354. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  355. package/lib/Utils/tc-token-utils.js +164 -0
  356. package/lib/Utils/tc-token-utils.js.map +1 -0
  357. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  358. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  359. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  360. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  361. package/lib/Utils/use-single-file-auth-state.d.ts +6 -0
  362. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  363. package/lib/Utils/use-single-file-auth-state.js +111 -0
  364. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  365. package/lib/Utils/use-sqlite-auth-state.d.ts +14 -0
  366. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  367. package/lib/Utils/use-sqlite-auth-state.js +107 -0
  368. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  369. package/lib/Utils/validate-connection.d.ts +12 -0
  370. package/lib/Utils/validate-connection.d.ts.map +1 -0
  371. package/lib/Utils/validate-connection.js +210 -0
  372. package/lib/Utils/validate-connection.js.map +1 -0
  373. package/lib/WABinary/constants.d.ts +28 -0
  374. package/lib/WABinary/constants.d.ts.map +1 -0
  375. package/lib/WABinary/constants.js +1301 -0
  376. package/lib/WABinary/constants.js.map +1 -0
  377. package/lib/WABinary/decode.d.ts +7 -0
  378. package/lib/WABinary/decode.d.ts.map +1 -0
  379. package/lib/WABinary/decode.js +262 -0
  380. package/lib/WABinary/decode.js.map +1 -0
  381. package/lib/WABinary/encode.d.ts +3 -0
  382. package/lib/WABinary/encode.d.ts.map +1 -0
  383. package/lib/WABinary/encode.js +220 -0
  384. package/lib/WABinary/encode.js.map +1 -0
  385. package/lib/WABinary/generic-utils.d.ts +15 -0
  386. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  387. package/lib/WABinary/generic-utils.js +113 -0
  388. package/lib/WABinary/generic-utils.js.map +1 -0
  389. package/lib/WABinary/index.d.ts +6 -0
  390. package/lib/WABinary/index.d.ts.map +1 -0
  391. package/lib/WABinary/index.js +6 -0
  392. package/lib/WABinary/index.js.map +1 -0
  393. package/lib/WABinary/jid-utils.d.ts +48 -0
  394. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  395. package/lib/WABinary/jid-utils.js +96 -0
  396. package/lib/WABinary/jid-utils.js.map +1 -0
  397. package/lib/WABinary/types.d.ts +19 -0
  398. package/lib/WABinary/types.d.ts.map +1 -0
  399. package/lib/WABinary/types.js +2 -0
  400. package/lib/WABinary/types.js.map +1 -0
  401. package/lib/WAM/BinaryInfo.d.ts +9 -0
  402. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  403. package/lib/WAM/BinaryInfo.js +10 -0
  404. package/lib/WAM/BinaryInfo.js.map +1 -0
  405. package/lib/WAM/constants.d.ts +40 -0
  406. package/lib/WAM/constants.d.ts.map +1 -0
  407. package/lib/WAM/constants.js +22853 -0
  408. package/lib/WAM/constants.js.map +1 -0
  409. package/lib/WAM/encode.d.ts +3 -0
  410. package/lib/WAM/encode.d.ts.map +1 -0
  411. package/lib/WAM/encode.js +150 -0
  412. package/lib/WAM/encode.js.map +1 -0
  413. package/lib/WAM/index.d.ts +4 -0
  414. package/lib/WAM/index.d.ts.map +1 -0
  415. package/lib/WAM/index.js +4 -0
  416. package/lib/WAM/index.js.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  418. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  419. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  420. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  421. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  422. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  423. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  424. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  425. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  426. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  427. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  428. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  429. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  430. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  432. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  434. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  436. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  437. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  438. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  439. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  440. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  441. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  442. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  443. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  444. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  445. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  446. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  447. package/lib/WAUSync/Protocols/index.js +6 -0
  448. package/lib/WAUSync/Protocols/index.js.map +1 -0
  449. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  450. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  451. package/lib/WAUSync/USyncQuery.js +98 -0
  452. package/lib/WAUSync/USyncQuery.js.map +1 -0
  453. package/lib/WAUSync/USyncUser.d.ts +17 -0
  454. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  455. package/lib/WAUSync/USyncUser.js +31 -0
  456. package/lib/WAUSync/USyncUser.js.map +1 -0
  457. package/lib/WAUSync/index.d.ts +4 -0
  458. package/lib/WAUSync/index.d.ts.map +1 -0
  459. package/lib/WAUSync/index.js +4 -0
  460. package/lib/WAUSync/index.js.map +1 -0
  461. package/lib/index.d.ts +13 -0
  462. package/lib/index.d.ts.map +1 -0
  463. package/lib/index.js +12 -0
  464. package/lib/index.js.map +1 -0
  465. package/package.json +83 -0
@@ -0,0 +1,1697 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import Long from 'long';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_AGE_SECONDS, STATUS_EXPIRY_SECONDS } from '../Defaults/index.js';
7
+ import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
+ import { ACCOUNT_RESTRICTED_TEXT, aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getPlatformType, getStatusFromReceiptType, handleIdentityChange, hkdf, makeShortcakeFlow, 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 } = sock;
24
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
25
+ const shortcakeFlow = config.signPasskeyAssertion
26
+ ? makeShortcakeFlow({
27
+ logger,
28
+ query,
29
+ signAssertion: config.signPasskeyAssertion,
30
+ getCreds: () => authState.creds,
31
+ updateCreds: patch => ev.emit('creds.update', patch),
32
+ deviceType: getPlatformType(config.browser[1]),
33
+ emitVerificationCode: code => logger.debug({ code }, 'shortcake verification code')
34
+ })
35
+ : null;
36
+ registerSocketEndHandler(() => shortcakeFlow?.clearSession());
37
+ const shortcakeMutex = makeMutex();
38
+ const handleShortcakeNotification = (node) => {
39
+ if (node.attrs.type === 'passkey_prologue_request') {
40
+ ev.emit('connection.update', { passkeyRequired: { hasSigner: !!shortcakeFlow } });
41
+ }
42
+ if (!shortcakeFlow) {
43
+ if (node.attrs.type === 'passkey_prologue_request') {
44
+ logger.warn({ id: node.attrs.id }, 'server requested passkey prologue but no signPasskeyAssertion configured');
45
+ }
46
+ return;
47
+ }
48
+ shortcakeMutex
49
+ .mutex(() => shortcakeFlow.handleIncomingNotification(node))
50
+ .catch(err => logger.error({ err, id: node.attrs.id }, 'shortcake handshake failed'));
51
+ };
52
+ const retryMutex = makeMutex();
53
+ const msgRetryCache = config.msgRetryCounterCache ||
54
+ new NodeCache({
55
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY,
56
+ useClones: false
57
+ });
58
+ const callOfferCache = config.callOfferCache ||
59
+ new NodeCache({
60
+ stdTTL: DEFAULT_CACHE_TTLS.CALL_OFFER,
61
+ useClones: false
62
+ });
63
+ const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
64
+ let sendActiveReceipts = false;
65
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
66
+ if (!authState.creds.me?.id) {
67
+ throw new Boom('Not authenticated');
68
+ }
69
+ const pdoMessage = {
70
+ historySyncOnDemandRequest: {
71
+ chatJid: oldestMsgKey.remoteJid,
72
+ oldestMsgFromMe: oldestMsgKey.fromMe,
73
+ oldestMsgId: oldestMsgKey.id,
74
+ oldestMsgTimestampMs: oldestMsgTimestamp,
75
+ onDemandMsgCount: count
76
+ },
77
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
78
+ };
79
+ return sendPeerDataOperationMessage(pdoMessage);
80
+ };
81
+ const requestPlaceholderResend = async (messageKey, msgData) => {
82
+ if (!authState.creds.me?.id) {
83
+ throw new Boom('Not authenticated');
84
+ }
85
+ if (await placeholderResendCache.get(messageKey?.id)) {
86
+ logger.debug({ messageKey }, 'already requested resend');
87
+ return;
88
+ }
89
+ else {
90
+ await placeholderResendCache.set(messageKey?.id, msgData || true);
91
+ }
92
+ await delay(2000);
93
+ if (!(await placeholderResendCache.get(messageKey?.id))) {
94
+ logger.debug({ messageKey }, 'message received while resend requested');
95
+ return 'RESOLVED';
96
+ }
97
+ const pdoMessage = {
98
+ placeholderMessageResendRequest: [
99
+ {
100
+ messageKey
101
+ }
102
+ ],
103
+ peerDataOperationRequestType: proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
104
+ };
105
+ setTimeout(async () => {
106
+ if (await placeholderResendCache.get(messageKey?.id)) {
107
+ logger.debug({ messageKey }, 'PDO message without response after 8 seconds. Phone possibly offline');
108
+ await placeholderResendCache.del(messageKey?.id);
109
+ }
110
+ }, 8000);
111
+ return sendPeerDataOperationMessage(pdoMessage);
112
+ };
113
+ const handleMexNotification = async (node) => {
114
+ const updateNode = getBinaryNodeChild(node, 'update');
115
+ if (updateNode) {
116
+ const opName = updateNode.attrs?.op_name;
117
+ if (!opName) {
118
+ logger.warn({ node: binaryNodeToString(node) }, 'mex notification missing op_name, fallback to legacy');
119
+ await handleLegacyMexNewsletterNotification(node);
120
+ return;
121
+ }
122
+ let mexResponse;
123
+ try {
124
+ mexResponse = JSON.parse(updateNode.content.toString());
125
+ }
126
+ catch (error) {
127
+ logger.error({ err: error, opName }, 'failed to parse mex notification JSON');
128
+ return;
129
+ }
130
+ if (mexResponse.errors?.length) {
131
+ logger.warn({ errors: mexResponse.errors, opName }, 'mex notification has GQL errors');
132
+ return;
133
+ }
134
+ const data = mexResponse.data;
135
+ if (!data) {
136
+ logger.warn({ opName }, 'mex notification has null data');
137
+ return;
138
+ }
139
+ logger.debug({ opName }, 'processing mex notification');
140
+ switch (opName) {
141
+ case 'NotificationUserReachoutTimelockUpdate':
142
+ handleReachoutTimelockNotification(data);
143
+ break;
144
+ case 'MessageCappingInfoNotification':
145
+ handleMessageCappingNotification(data);
146
+ break;
147
+ case 'NotificationNewsletterUpdate':
148
+ case 'NotificationLinkedProfilesUpdates':
149
+ case 'NotificationNewsletterAdminPromote':
150
+ case 'NotificationNewsletterAdminDemote':
151
+ case 'NotificationNewsletterUserSettingChange':
152
+ case 'NotificationNewsletterJoin':
153
+ case 'NotificationNewsletterLeave':
154
+ case 'NotificationNewsletterStateChange':
155
+ case 'NotificationNewsletterAdminMetadataUpdate':
156
+ case 'NotificationNewsletterOwnerUpdate':
157
+ case 'NotificationNewsletterAdminInviteRevoke':
158
+ case 'NotificationNewsletterWamoSubStatusChange':
159
+ case 'NotificationNewsletterBlockUser':
160
+ case 'NotificationNewsletterPaidPartnership':
161
+ case 'NotificationNewsletterMilestone':
162
+ case 'NewsletterResponseStateUpdate':
163
+ await handleLegacyMexNewsletterNotification(node);
164
+ break;
165
+ default:
166
+ logger.debug({ opName }, 'unhandled mex notification');
167
+ break;
168
+ }
169
+ return;
170
+ }
171
+ await handleLegacyMexNewsletterNotification(node);
172
+ };
173
+ const handleReachoutTimelockNotification = (data) => {
174
+ const payload = data.xwa2_notify_account_reachout_timelock;
175
+ if (!payload) {
176
+ logger.warn('reachout timelock notification missing payload');
177
+ return;
178
+ }
179
+ if (!payload.is_active) {
180
+ logger.info('reachout timelock restriction lifted');
181
+ ev.emit('connection.update', {
182
+ reachoutTimeLock: {
183
+ isActive: false,
184
+ enforcementType: ReachoutTimelockEnforcementType.DEFAULT
185
+ }
186
+ });
187
+ return;
188
+ }
189
+ const timeEnforcementEnds = payload.time_enforcement_ends
190
+ ? new Date(parseInt(payload.time_enforcement_ends, 10) * 1000)
191
+ : new Date(Date.now() + 60000);
192
+ const enforcementType = isValidEnforcementType(payload.enforcement_type)
193
+ ? payload.enforcement_type
194
+ : ReachoutTimelockEnforcementType.DEFAULT;
195
+ logger.info({ enforcementType, timeEnforcementEnds }, 'reachout timelock restriction set');
196
+ ev.emit('connection.update', {
197
+ reachoutTimeLock: {
198
+ isActive: true,
199
+ timeEnforcementEnds,
200
+ enforcementType
201
+ }
202
+ });
203
+ };
204
+ const handleMessageCappingNotification = (data) => {
205
+ const payload = data.xwa2_notify_new_chat_messages_capping_info_update;
206
+ if (!payload) {
207
+ logger.warn('message capping notification missing payload');
208
+ return;
209
+ }
210
+ logger.info({ payload }, 'received message capping update');
211
+ ev.emit('message-capping.update', payload);
212
+ };
213
+ const handleLegacyMexNewsletterNotification = async (node) => {
214
+ const mexNode = getBinaryNodeChild(node, 'mex');
215
+ const updateNode = mexNode?.content ? null : getBinaryNodeChild(node, 'update') || getAllBinaryNodeChildren(node)[0];
216
+ const payloadNode = mexNode?.content ? mexNode : updateNode;
217
+ if (!payloadNode?.content) {
218
+ logger.warn({ node: binaryNodeToString(node) }, 'invalid mex newsletter notification');
219
+ return;
220
+ }
221
+ let data;
222
+ try {
223
+ const payloadContent = payloadNode.content;
224
+ if (Array.isArray(payloadContent)) {
225
+ logger.warn({ payloadNode }, 'invalid mex newsletter notification payload format');
226
+ return;
227
+ }
228
+ const contentBuf = typeof payloadContent === 'string' ? Buffer.from(payloadContent, 'binary') : Buffer.from(payloadContent);
229
+ data = JSON.parse(contentBuf.toString());
230
+ }
231
+ catch (error) {
232
+ logger.error({ err: error, node: binaryNodeToString(node) }, 'failed to parse mex newsletter notification');
233
+ return;
234
+ }
235
+ const operation = data?.operation ?? payloadNode?.attrs?.op_name;
236
+ let updates = data?.updates;
237
+ if (!updates) {
238
+ const linkedProfiles = data?.data?.xwa2_notify_linked_profiles;
239
+ if (linkedProfiles) {
240
+ updates = [linkedProfiles];
241
+ }
242
+ }
243
+ if (!updates || !operation) {
244
+ logger.warn({ data }, 'invalid mex newsletter notification content');
245
+ return;
246
+ }
247
+ logger.info({ operation, updates }, 'got mex newsletter notification');
248
+ switch (operation) {
249
+ case 'NotificationNewsletterUpdate':
250
+ for (const update of updates) {
251
+ if (update.jid && update.settings && Object.keys(update.settings).length > 0) {
252
+ ev.emit('newsletter-settings.update', {
253
+ id: update.jid,
254
+ update: update.settings
255
+ });
256
+ }
257
+ }
258
+ break;
259
+ case 'NotificationNewsletterAdminPromote':
260
+ for (const update of updates) {
261
+ if (update.jid && update.user) {
262
+ ev.emit('newsletter-participants.update', {
263
+ id: update.jid,
264
+ author: node.attrs.from,
265
+ user: update.user,
266
+ new_role: 'ADMIN',
267
+ action: 'promote'
268
+ });
269
+ }
270
+ }
271
+ break;
272
+ case 'NotificationLinkedProfilesUpdates':
273
+ for (const update of updates) {
274
+ const lid = update?.jid;
275
+ const addedProfiles = Array.isArray(update?.added_profiles) ? update.added_profiles : [];
276
+ const mappings = [];
277
+ for (const profile of addedProfiles) {
278
+ const pn = typeof profile === 'string' ? profile : (profile?.pn ?? profile?.jid ?? null);
279
+ if (lid && pn) {
280
+ const mapping = { lid, pn };
281
+ ev.emit('lid-mapping.update', mapping);
282
+ mappings.push(mapping);
283
+ }
284
+ }
285
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
286
+ }
287
+ break;
288
+ default:
289
+ logger.info({ operation, data }, 'unhandled mex newsletter notification');
290
+ break;
291
+ }
292
+ };
293
+ const handleNewsletterNotification = async (node) => {
294
+ const from = node.attrs.from;
295
+ const children = getAllBinaryNodeChildren(node);
296
+ const author = node.attrs.participant;
297
+ for (const child of children) {
298
+ logger.debug({ from, child }, 'got newsletter notification');
299
+ switch (child.tag) {
300
+ case 'reaction': {
301
+ const reactionUpdate = {
302
+ id: from,
303
+ server_id: child.attrs.message_id,
304
+ reaction: {
305
+ code: getBinaryNodeChildString(child, 'reaction'),
306
+ count: 1
307
+ }
308
+ };
309
+ ev.emit('newsletter.reaction', reactionUpdate);
310
+ break;
311
+ }
312
+ case 'view': {
313
+ const viewUpdate = {
314
+ id: from,
315
+ server_id: child.attrs.message_id,
316
+ count: parseInt(child.content?.toString() || '0', 10)
317
+ };
318
+ ev.emit('newsletter.view', viewUpdate);
319
+ break;
320
+ }
321
+ case 'participant': {
322
+ const participantUpdate = {
323
+ id: from,
324
+ author,
325
+ user: child.attrs.jid,
326
+ action: child.attrs.action,
327
+ new_role: child.attrs.role
328
+ };
329
+ ev.emit('newsletter-participants.update', participantUpdate);
330
+ break;
331
+ }
332
+ case 'update': {
333
+ const settingsNode = getBinaryNodeChild(child, 'settings');
334
+ if (settingsNode) {
335
+ const update = {};
336
+ const nameNode = getBinaryNodeChild(settingsNode, 'name');
337
+ if (nameNode?.content)
338
+ update.name = nameNode.content.toString();
339
+ const descriptionNode = getBinaryNodeChild(settingsNode, 'description');
340
+ if (descriptionNode?.content)
341
+ update.description = descriptionNode.content.toString();
342
+ ev.emit('newsletter-settings.update', {
343
+ id: from,
344
+ update
345
+ });
346
+ }
347
+ break;
348
+ }
349
+ case 'message': {
350
+ const plaintextNode = getBinaryNodeChild(child, 'plaintext');
351
+ if (plaintextNode?.content) {
352
+ try {
353
+ const contentBuf = typeof plaintextNode.content === 'string'
354
+ ? Buffer.from(plaintextNode.content, 'binary')
355
+ : Buffer.from(plaintextNode.content);
356
+ const messageProto = proto.Message.decode(contentBuf).toJSON();
357
+ const fullMessage = proto.WebMessageInfo.fromObject({
358
+ key: {
359
+ remoteJid: from,
360
+ id: child.attrs.message_id || child.attrs.server_id,
361
+ fromMe: false
362
+ },
363
+ message: messageProto,
364
+ messageTimestamp: +child.attrs.t
365
+ }).toJSON();
366
+ await upsertMessage(fullMessage, 'append');
367
+ logger.debug('Processed plaintext newsletter message');
368
+ }
369
+ catch (error) {
370
+ logger.error({ error }, 'Failed to decode plaintext newsletter message');
371
+ }
372
+ }
373
+ break;
374
+ }
375
+ default:
376
+ logger.warn({ node, child }, 'Unknown newsletter notification child');
377
+ break;
378
+ }
379
+ }
380
+ };
381
+ const sendMessageAck = async (node, errorCode) => {
382
+ const stanza = buildAckStanza(node, errorCode, authState.creds.me.id);
383
+ logger.debug({ recv: { tag: node.tag, attrs: node.attrs }, sent: stanza.attrs }, 'sent ack');
384
+ await sendNode(stanza);
385
+ };
386
+ const rejectCall = async (callId, callFrom) => {
387
+ const stanza = {
388
+ tag: 'call',
389
+ attrs: {
390
+ from: authState.creds.me.id,
391
+ to: callFrom
392
+ },
393
+ content: [
394
+ {
395
+ tag: 'reject',
396
+ attrs: {
397
+ 'call-id': callId,
398
+ 'call-creator': callFrom,
399
+ count: '0'
400
+ },
401
+ content: undefined
402
+ }
403
+ ]
404
+ };
405
+ await query(stanza);
406
+ };
407
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
408
+ const { fullMessage } = decodeMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '');
409
+ const { key: msgKey } = fullMessage;
410
+ const msgId = msgKey.id;
411
+ if (messageRetryManager) {
412
+ if (messageRetryManager.hasExceededMaxRetries(msgId)) {
413
+ logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
414
+ messageRetryManager.markRetryFailed(msgId, msgKey?.remoteJid || undefined);
415
+ return;
416
+ }
417
+ const retryCount = messageRetryManager.incrementRetryCount(msgId);
418
+ const key = `${msgId}:${msgKey?.participant}`;
419
+ await msgRetryCache.set(key, retryCount);
420
+ }
421
+ else {
422
+ const key = `${msgId}:${msgKey?.participant}`;
423
+ let retryCount = (await msgRetryCache.get(key)) || 0;
424
+ if (retryCount >= maxMsgRetryCount) {
425
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
426
+ await msgRetryCache.del(key);
427
+ return;
428
+ }
429
+ retryCount += 1;
430
+ await msgRetryCache.set(key, retryCount);
431
+ }
432
+ const key = `${msgId}:${msgKey?.participant}`;
433
+ const retryCount = (await msgRetryCache.get(key)) || 1;
434
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
435
+ const fromJid = node.attrs.from;
436
+ let shouldRecreateSession = false;
437
+ let recreateReason = '';
438
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
439
+ try {
440
+ const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
441
+ const hasSession = await signalRepository.validateSession(fromJid);
442
+ const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
443
+ shouldRecreateSession = result.recreate;
444
+ recreateReason = result.reason;
445
+ if (shouldRecreateSession) {
446
+ logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
447
+ await authState.keys.set({ session: { [sessionId]: null } });
448
+ forceIncludeKeys = true;
449
+ }
450
+ }
451
+ catch (error) {
452
+ logger.warn({ error, fromJid }, 'failed to check session recreation');
453
+ }
454
+ }
455
+ if (retryCount <= 2) {
456
+ if (messageRetryManager) {
457
+ messageRetryManager.schedulePhoneRequest(msgId, async () => {
458
+ try {
459
+ const requestId = await requestPlaceholderResend(msgKey);
460
+ logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
461
+ }
462
+ catch (error) {
463
+ logger.warn({ error, msgId }, 'failed to send scheduled phone request');
464
+ }
465
+ });
466
+ }
467
+ else {
468
+ const msgId = await requestPlaceholderResend(msgKey);
469
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
470
+ }
471
+ }
472
+ const deviceIdentity = encodeSignedDeviceIdentity(account, true);
473
+ await authState.keys.transaction(async () => {
474
+ const receipt = {
475
+ tag: 'receipt',
476
+ attrs: {
477
+ id: msgId,
478
+ type: 'retry',
479
+ to: node.attrs.from
480
+ },
481
+ content: [
482
+ {
483
+ tag: 'retry',
484
+ attrs: {
485
+ count: retryCount.toString(),
486
+ id: node.attrs.id,
487
+ t: node.attrs.t,
488
+ v: '1',
489
+ error: '0'
490
+ }
491
+ },
492
+ {
493
+ tag: 'registration',
494
+ attrs: {},
495
+ content: encodeBigEndian(authState.creds.registrationId)
496
+ }
497
+ ]
498
+ };
499
+ if (node.attrs.recipient) {
500
+ receipt.attrs.recipient = node.attrs.recipient;
501
+ }
502
+ if (node.attrs.participant) {
503
+ receipt.attrs.participant = node.attrs.participant;
504
+ }
505
+ if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
506
+ const { update, preKeys } = await getNextPreKeys(authState, 1);
507
+ const [keyId] = Object.keys(preKeys);
508
+ const key = preKeys[+keyId];
509
+ const content = receipt.content;
510
+ content.push({
511
+ tag: 'keys',
512
+ attrs: {},
513
+ content: [
514
+ { tag: 'type', attrs: {}, content: Buffer.from(KEY_BUNDLE_TYPE) },
515
+ { tag: 'identity', attrs: {}, content: identityKey.public },
516
+ xmppPreKey(key, +keyId),
517
+ xmppSignedPreKey(signedPreKey),
518
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
519
+ ]
520
+ });
521
+ ev.emit('creds.update', update);
522
+ }
523
+ await sendNode(receipt);
524
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
525
+ }, authState?.creds?.me?.id || 'sendRetryRequest');
526
+ };
527
+ const inFlightPreKeyLow = new Set();
528
+ const reissueTcTokenAfterIdentityChange = (from) => {
529
+ void (async () => {
530
+ const normalizedJid = jidNormalizedUser(from);
531
+ const tcJid = await resolveTcTokenJid(normalizedJid, getLIDForPN);
532
+ const tcTokenData = await authState.keys.get('tctoken', [tcJid]);
533
+ const senderTs = tcTokenData?.[tcJid]?.senderTimestamp;
534
+ if (senderTs === null || senderTs === undefined || isTcTokenExpired(senderTs)) {
535
+ return;
536
+ }
537
+ logger.debug({ jid: normalizedJid, senderTimestamp: senderTs }, 'identity changed, re-issuing tctoken');
538
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
539
+ const issueJid = await resolveIssuanceJid(normalizedJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
540
+ const result = await issuePrivacyTokens([issueJid], senderTs);
541
+ await storeTcTokensFromIqResult({
542
+ result,
543
+ fallbackJid: tcJid,
544
+ keys: authState.keys,
545
+ getLIDForPN,
546
+ onNewJidStored: trackTcTokenJid
547
+ });
548
+ })().catch(err => {
549
+ logger.debug({ jid: from, err: err?.message }, 'failed to re-issue tctoken after identity change');
550
+ });
551
+ };
552
+ const handleEncryptNotification = async (node) => {
553
+ const from = node.attrs.from;
554
+ if (from === S_WHATSAPP_NET) {
555
+ const stanzaId = node.attrs.id;
556
+ if (stanzaId && inFlightPreKeyLow.has(stanzaId)) {
557
+ return;
558
+ }
559
+ const countChild = getBinaryNodeChild(node, 'count');
560
+ const count = +countChild.attrs.value;
561
+ const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
562
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
563
+ if (shouldUploadMorePreKeys) {
564
+ if (stanzaId)
565
+ inFlightPreKeyLow.add(stanzaId);
566
+ try {
567
+ await uploadPreKeys();
568
+ }
569
+ finally {
570
+ if (stanzaId)
571
+ inFlightPreKeyLow.delete(stanzaId);
572
+ }
573
+ }
574
+ }
575
+ else {
576
+ const result = await handleIdentityChange(node, {
577
+ meId: authState.creds.me?.id,
578
+ meLid: authState.creds.me?.lid,
579
+ validateSession: signalRepository.validateSession,
580
+ assertSessions,
581
+ debounceCache: identityAssertDebounce,
582
+ logger,
583
+ onBeforeSessionRefresh: reissueTcTokenAfterIdentityChange
584
+ });
585
+ if (result.action === 'no_identity_node') {
586
+ logger.info({ node }, 'unknown encrypt notification');
587
+ }
588
+ }
589
+ };
590
+ const handleGroupNotification = (fullNode, child, msg) => {
591
+ const actingParticipantLid = fullNode.attrs.participant;
592
+ const actingParticipantPn = fullNode.attrs.participant_pn;
593
+ const actingParticipantUsername = fullNode.attrs.participant_username;
594
+ const affectedParticipantLid = getBinaryNodeChild(child, 'participant')?.attrs?.jid || actingParticipantLid;
595
+ const affectedParticipantPn = getBinaryNodeChild(child, 'participant')?.attrs?.phone_number || actingParticipantPn;
596
+ switch (child?.tag) {
597
+ case 'create':
598
+ const metadata = extractGroupMetadata(child);
599
+ msg.messageStubType = WAMessageStubType.GROUP_CREATE;
600
+ msg.messageStubParameters = [metadata.subject];
601
+ msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
602
+ ev.emit('chats.upsert', [
603
+ {
604
+ id: metadata.id,
605
+ name: metadata.subject,
606
+ conversationTimestamp: metadata.creation
607
+ }
608
+ ]);
609
+ ev.emit('groups.upsert', [
610
+ {
611
+ ...metadata,
612
+ author: actingParticipantLid,
613
+ authorPn: actingParticipantPn,
614
+ authorUsername: actingParticipantUsername
615
+ }
616
+ ]);
617
+ break;
618
+ case 'ephemeral':
619
+ case 'not_ephemeral':
620
+ msg.message = {
621
+ protocolMessage: {
622
+ type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
623
+ ephemeralExpiration: +(child.attrs.expiration || 0)
624
+ }
625
+ };
626
+ break;
627
+ case 'modify':
628
+ const oldNumber = getBinaryNodeChildren(child, 'participant').map(p => p.attrs.jid);
629
+ msg.messageStubParameters = oldNumber || [];
630
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
631
+ break;
632
+ case 'promote':
633
+ case 'demote':
634
+ case 'remove':
635
+ case 'add':
636
+ case 'leave':
637
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
638
+ msg.messageStubType = WAMessageStubType[stubType];
639
+ const participants = getBinaryNodeChildren(child, 'participant').map(({ attrs }) => {
640
+ const isLid = isLidUser(attrs.jid);
641
+ const hasPn = isPnUser(attrs.phone_number);
642
+ return {
643
+ id: isLid && hasPn ? attrs.phone_number : attrs.jid,
644
+ phoneNumber: isLid && hasPn ? attrs.phone_number : undefined,
645
+ lid: isLid ? attrs.jid : isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
646
+ username: attrs.participant_username || attrs.username || undefined,
647
+ admin: (attrs.type || null)
648
+ };
649
+ });
650
+ if (participants.length === 1 &&
651
+ (areJidsSameUser(participants[0].id, actingParticipantLid) ||
652
+ areJidsSameUser(participants[0].id, actingParticipantPn)) &&
653
+ child.tag === 'remove') {
654
+ msg.messageStubType = WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
655
+ }
656
+ msg.messageStubParameters = participants.map(a => JSON.stringify(a));
657
+ break;
658
+ case 'subject':
659
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_SUBJECT;
660
+ msg.messageStubParameters = [child.attrs.subject];
661
+ break;
662
+ case 'description':
663
+ const description = getBinaryNodeChild(child, 'body')?.content?.toString();
664
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
665
+ msg.messageStubParameters = description ? [description] : undefined;
666
+ break;
667
+ case 'announcement':
668
+ case 'not_announcement':
669
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
670
+ msg.messageStubParameters = [child.tag === 'announcement' ? 'on' : 'off'];
671
+ break;
672
+ case 'locked':
673
+ case 'unlocked':
674
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_RESTRICT;
675
+ msg.messageStubParameters = [child.tag === 'locked' ? 'on' : 'off'];
676
+ break;
677
+ case 'invite':
678
+ msg.messageStubType = WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
679
+ msg.messageStubParameters = [child.attrs.code];
680
+ break;
681
+ case 'member_add_mode':
682
+ const addMode = child.content;
683
+ if (addMode) {
684
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBER_ADD_MODE;
685
+ msg.messageStubParameters = [addMode.toString()];
686
+ }
687
+ break;
688
+ case 'membership_approval_mode':
689
+ const approvalMode = getBinaryNodeChild(child, 'group_join');
690
+ if (approvalMode) {
691
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
692
+ msg.messageStubParameters = [approvalMode.attrs.state];
693
+ }
694
+ break;
695
+ case 'created_membership_requests':
696
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
697
+ msg.messageStubParameters = [
698
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
699
+ 'created',
700
+ child.attrs.request_method
701
+ ];
702
+ break;
703
+ case 'revoked_membership_requests':
704
+ const isDenied = areJidsSameUser(affectedParticipantLid, actingParticipantLid);
705
+ msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
706
+ msg.messageStubParameters = [
707
+ JSON.stringify({ lid: affectedParticipantLid, pn: affectedParticipantPn }),
708
+ isDenied ? 'revoked' : 'rejected'
709
+ ];
710
+ break;
711
+ }
712
+ };
713
+ const handleDevicesNotification = async (node) => {
714
+ const [child] = getAllBinaryNodeChildren(node);
715
+ const from = jidNormalizedUser(node.attrs.from);
716
+ if (!child) {
717
+ logger.debug({ from }, 'devices notification missing child, skipping');
718
+ return;
719
+ }
720
+ const tag = child.tag;
721
+ const deviceHash = child.attrs.device_hash;
722
+ const devices = getBinaryNodeChildren(child, 'device');
723
+ if (areJidsSameUser(from, authState.creds.me.id) || areJidsSameUser(from, authState.creds.me.lid)) {
724
+ const deviceJids = devices.map(d => d.attrs.jid);
725
+ logger.info({ deviceJids }, 'got my own devices');
726
+ }
727
+ if (!devices.length) {
728
+ logger.debug({ from, tag }, 'no devices in notification, skipping');
729
+ return;
730
+ }
731
+ const decoded = [];
732
+ for (const d of devices) {
733
+ const jid = d.attrs.jid;
734
+ if (!jid)
735
+ continue;
736
+ const parts = jidDecode(jid);
737
+ if (!parts) {
738
+ logger.debug({ jid }, 'failed to decode device jid, skipping');
739
+ continue;
740
+ }
741
+ decoded.push({ jid, user: parts.user, server: parts.server, device: parts.device });
742
+ }
743
+ if (!decoded.length)
744
+ return;
745
+ await devicesMutex.mutex(async () => {
746
+ const byUser = new Map();
747
+ for (const d of decoded) {
748
+ const list = byUser.get(d.user) || [];
749
+ list.push(d);
750
+ byUser.set(d.user, list);
751
+ }
752
+ for (const [user, entries] of byUser) {
753
+ if (tag === 'update') {
754
+ logger.debug({ user }, `${user}'s device list updated, dropping cached devices`);
755
+ await userDevicesCache?.del(user);
756
+ continue;
757
+ }
758
+ if (tag === 'remove') {
759
+ await signalRepository.deleteSession(entries.map(e => e.jid));
760
+ }
761
+ const existingCache = (await userDevicesCache?.get(user)) || [];
762
+ if (!existingCache.length) {
763
+ logger.debug({ user, tag }, 'device list not cached, deferring to USync refresh');
764
+ continue;
765
+ }
766
+ const affected = new Set(entries.map(e => e.device));
767
+ let updatedDevices;
768
+ switch (tag) {
769
+ case 'add':
770
+ logger.info({ deviceHash, count: entries.length }, 'devices added');
771
+ updatedDevices = [
772
+ ...existingCache.filter(d => !affected.has(d.device)),
773
+ ...entries.map(e => ({ user: e.user, server: e.server, device: e.device }))
774
+ ];
775
+ break;
776
+ case 'remove':
777
+ logger.info({ deviceHash, count: entries.length }, 'devices removed');
778
+ updatedDevices = existingCache.filter(d => !affected.has(d.device));
779
+ break;
780
+ default:
781
+ logger.debug({ tag }, 'Unknown device list change tag');
782
+ continue;
783
+ }
784
+ if (updatedDevices.length === 0) {
785
+ await userDevicesCache?.del(user);
786
+ }
787
+ else {
788
+ await userDevicesCache?.set(user, updatedDevices);
789
+ }
790
+ }
791
+ });
792
+ };
793
+ const processNotification = async (node) => {
794
+ const result = {};
795
+ const [child] = getAllBinaryNodeChildren(node);
796
+ const nodeType = node.attrs.type;
797
+ const from = jidNormalizedUser(node.attrs.from);
798
+ switch (nodeType) {
799
+ case 'newsletter':
800
+ await handleNewsletterNotification(node);
801
+ break;
802
+ case 'mex':
803
+ await handleMexNotification(node);
804
+ break;
805
+ case 'w:gp2':
806
+ handleGroupNotification(node, child, result);
807
+ break;
808
+ case 'mediaretry':
809
+ const event = decodeMediaRetryNode(node);
810
+ ev.emit('messages.media-update', [event]);
811
+ break;
812
+ case 'encrypt':
813
+ await handleEncryptNotification(node);
814
+ break;
815
+ case 'devices':
816
+ try {
817
+ await handleDevicesNotification(node);
818
+ }
819
+ catch (error) {
820
+ logger.error({ error, node }, 'failed to handle devices notification');
821
+ }
822
+ break;
823
+ case 'server_sync':
824
+ const update = getBinaryNodeChild(node, 'collection');
825
+ if (update) {
826
+ const name = update.attrs.name;
827
+ await resyncAppState([name], false);
828
+ }
829
+ break;
830
+ case 'picture':
831
+ const setPicture = getBinaryNodeChild(node, 'set');
832
+ const delPicture = getBinaryNodeChild(node, 'delete');
833
+ ev.emit('contacts.update', [
834
+ {
835
+ id: jidNormalizedUser(node?.attrs?.from) || (setPicture || delPicture)?.attrs?.hash || '',
836
+ imgUrl: setPicture ? 'changed' : 'removed'
837
+ }
838
+ ]);
839
+ if (isJidGroup(from)) {
840
+ const node = setPicture || delPicture;
841
+ result.messageStubType = WAMessageStubType.GROUP_CHANGE_ICON;
842
+ if (setPicture) {
843
+ result.messageStubParameters = [setPicture.attrs.id];
844
+ }
845
+ result.participant = node?.attrs.author;
846
+ result.key = {
847
+ ...(result.key || {}),
848
+ participant: setPicture?.attrs.author
849
+ };
850
+ }
851
+ break;
852
+ case 'account_sync':
853
+ if (child.tag === 'disappearing_mode') {
854
+ const newDuration = +child.attrs.duration;
855
+ const timestamp = +child.attrs.t;
856
+ logger.info({ newDuration }, 'updated account disappearing mode');
857
+ ev.emit('creds.update', {
858
+ accountSettings: {
859
+ ...authState.creds.accountSettings,
860
+ defaultDisappearingMode: {
861
+ ephemeralExpiration: newDuration,
862
+ ephemeralSettingTimestamp: timestamp
863
+ }
864
+ }
865
+ });
866
+ }
867
+ else if (child.tag === 'blocklist') {
868
+ const blocklists = getBinaryNodeChildren(child, 'item');
869
+ for (const { attrs } of blocklists) {
870
+ const blocklist = [attrs.jid];
871
+ const type = attrs.action === 'block' ? 'add' : 'remove';
872
+ ev.emit('blocklist.update', { blocklist, type });
873
+ }
874
+ }
875
+ break;
876
+ case 'link_code_companion_reg':
877
+ const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
878
+ const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
879
+ const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
880
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
881
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
882
+ const companionSharedKey = Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
883
+ const random = randomBytes(32);
884
+ const linkCodeSalt = randomBytes(32);
885
+ const linkCodePairingExpanded = hkdf(companionSharedKey, 32, {
886
+ salt: linkCodeSalt,
887
+ info: 'link_code_pairing_key_bundle_encryption_key'
888
+ });
889
+ const encryptPayload = Buffer.concat([
890
+ Buffer.from(authState.creds.signedIdentityKey.public),
891
+ primaryIdentityPublicKey,
892
+ random
893
+ ]);
894
+ const encryptIv = randomBytes(12);
895
+ const encrypted = aesEncryptGCM(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
896
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
897
+ const identitySharedKey = Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
898
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
899
+ authState.creds.advSecretKey = Buffer.from(hkdf(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
900
+ await query({
901
+ tag: 'iq',
902
+ attrs: {
903
+ to: S_WHATSAPP_NET,
904
+ type: 'set',
905
+ id: sock.generateMessageTag(),
906
+ xmlns: 'md'
907
+ },
908
+ content: [
909
+ {
910
+ tag: 'link_code_companion_reg',
911
+ attrs: {
912
+ jid: authState.creds.me.id,
913
+ stage: 'companion_finish'
914
+ },
915
+ content: [
916
+ {
917
+ tag: 'link_code_pairing_wrapped_key_bundle',
918
+ attrs: {},
919
+ content: encryptedPayload
920
+ },
921
+ {
922
+ tag: 'companion_identity_public',
923
+ attrs: {},
924
+ content: authState.creds.signedIdentityKey.public
925
+ },
926
+ {
927
+ tag: 'link_code_pairing_ref',
928
+ attrs: {},
929
+ content: ref
930
+ }
931
+ ]
932
+ }
933
+ ]
934
+ });
935
+ authState.creds.registered = true;
936
+ ev.emit('creds.update', authState.creds);
937
+ break;
938
+ case 'passkey_prologue_request':
939
+ case 'crsc_continuation':
940
+ handleShortcakeNotification(node);
941
+ break;
942
+ case 'privacy_token':
943
+ await handlePrivacyTokenNotification(node);
944
+ break;
945
+ }
946
+ if (Object.keys(result).length) {
947
+ return result;
948
+ }
949
+ };
950
+ const tcTokenKnownJids = new Set();
951
+ const tcTokenIndexLoaded = (async () => {
952
+ try {
953
+ const jids = await readTcTokenIndex(authState.keys);
954
+ for (const jid of jids)
955
+ tcTokenKnownJids.add(jid);
956
+ logger.debug({ count: tcTokenKnownJids.size }, 'loaded tctoken index');
957
+ }
958
+ catch (err) {
959
+ logger.warn({ err: err?.message }, 'failed to load tctoken index');
960
+ }
961
+ })();
962
+ let tcTokenIndexTimer;
963
+ async function flushTcTokenIndex() {
964
+ if (tcTokenIndexTimer) {
965
+ clearTimeout(tcTokenIndexTimer);
966
+ tcTokenIndexTimer = undefined;
967
+ }
968
+ const write = await buildMergedTcTokenIndexWrite(authState.keys, tcTokenKnownJids);
969
+ return authState.keys.set({ tctoken: write });
970
+ }
971
+ function scheduleTcTokenIndexSave() {
972
+ if (tcTokenIndexTimer) {
973
+ clearTimeout(tcTokenIndexTimer);
974
+ }
975
+ tcTokenIndexTimer = setTimeout(() => {
976
+ tcTokenIndexTimer = undefined;
977
+ flushTcTokenIndex().catch(err => {
978
+ logger.warn({ err: err?.message }, 'failed to save tctoken index');
979
+ });
980
+ }, 5000);
981
+ }
982
+ function trackTcTokenJid(jid) {
983
+ if (jid && jid !== TC_TOKEN_INDEX_KEY && !tcTokenKnownJids.has(jid)) {
984
+ tcTokenKnownJids.add(jid);
985
+ scheduleTcTokenIndexSave();
986
+ }
987
+ }
988
+ const handlePrivacyTokenNotification = async (node) => {
989
+ const tokensNode = getBinaryNodeChild(node, 'tokens');
990
+ if (!tokensNode)
991
+ return;
992
+ const from = jidNormalizedUser(node.attrs.from);
993
+ const senderLid = node.attrs.sender_lid && isLidUser(jidNormalizedUser(node.attrs.sender_lid))
994
+ ? jidNormalizedUser(node.attrs.sender_lid)
995
+ : undefined;
996
+ const fallbackJid = senderLid ?? (await resolveTcTokenJid(from, getLIDForPN));
997
+ logger.debug({ from, storageJid: fallbackJid }, 'processing privacy token notification');
998
+ await storeTcTokensFromIqResult({
999
+ result: node,
1000
+ fallbackJid,
1001
+ keys: authState.keys,
1002
+ getLIDForPN,
1003
+ onNewJidStored: trackTcTokenJid
1004
+ });
1005
+ };
1006
+ async function decipherLinkPublicKey(data) {
1007
+ const buffer = toRequiredBuffer(data);
1008
+ const salt = buffer.slice(0, 32);
1009
+ const secretKey = await derivePairingCodeKey(authState.creds.pairingCode, salt);
1010
+ const iv = buffer.slice(32, 48);
1011
+ const payload = buffer.slice(48, 80);
1012
+ return aesDecryptCTR(payload, secretKey, iv);
1013
+ }
1014
+ function toRequiredBuffer(data) {
1015
+ if (data === undefined) {
1016
+ throw new Boom('Invalid buffer', { statusCode: 400 });
1017
+ }
1018
+ return data instanceof Buffer ? data : Buffer.from(data);
1019
+ }
1020
+ const willSendMessageAgain = async (id, participant) => {
1021
+ const key = `${id}:${participant}`;
1022
+ const retryCount = (await msgRetryCache.get(key)) || 0;
1023
+ return retryCount < maxMsgRetryCount;
1024
+ };
1025
+ const updateSendMessageAgainCount = async (id, participant) => {
1026
+ const key = `${id}:${participant}`;
1027
+ const newValue = ((await msgRetryCache.get(key)) || 0) + 1;
1028
+ await msgRetryCache.set(key, newValue);
1029
+ };
1030
+ const sendMessagesAgain = async (key, ids, retryNode, receiptNode) => {
1031
+ const remoteJid = key.remoteJid;
1032
+ const participant = key.participant || remoteJid;
1033
+ const retryCount = +retryNode.attrs.count || 1;
1034
+ const msgId = ids[0];
1035
+ const msgs = [];
1036
+ for (const id of ids) {
1037
+ let msg;
1038
+ if (messageRetryManager) {
1039
+ const cachedMsg = messageRetryManager.getRecentMessage(remoteJid, id);
1040
+ if (cachedMsg) {
1041
+ msg = cachedMsg.message;
1042
+ logger.debug({ jid: remoteJid, id }, 'found message in retry cache');
1043
+ messageRetryManager.markRetrySuccess(id, remoteJid);
1044
+ }
1045
+ }
1046
+ if (!msg) {
1047
+ msg = await getMessage({ ...key, id });
1048
+ if (msg) {
1049
+ logger.debug({ jid: remoteJid, id }, 'found message via getMessage');
1050
+ if (messageRetryManager) {
1051
+ messageRetryManager.markRetrySuccess(id, remoteJid);
1052
+ }
1053
+ }
1054
+ }
1055
+ msgs.push(msg);
1056
+ }
1057
+ const sendToAll = !jidDecode(participant)?.device;
1058
+ const sessionId = signalRepository.jidToSignalProtocolAddress(participant);
1059
+ let injectedFromBundle = false;
1060
+ const bundle = extractE2ESessionFromRetryReceipt(receiptNode);
1061
+ if (bundle) {
1062
+ try {
1063
+ await signalRepository.injectE2ESession({ jid: participant, session: bundle });
1064
+ injectedFromBundle = true;
1065
+ logger.debug({ participant, retryCount }, 'injected session from retry receipt key bundle');
1066
+ }
1067
+ catch (error) {
1068
+ logger.warn({ error, participant }, 'failed to inject session from retry receipt');
1069
+ }
1070
+ }
1071
+ if (!injectedFromBundle) {
1072
+ const receivedRegId = getBinaryNodeChildUInt(receiptNode, 'registration', 4);
1073
+ if (typeof receivedRegId === 'number' && Number.isInteger(receivedRegId)) {
1074
+ const info = await signalRepository.getSessionInfo(participant);
1075
+ if (info && info.registrationId !== 0 && info.registrationId !== receivedRegId) {
1076
+ logger.info({ participant, stored: info.registrationId, received: receivedRegId }, 'reg id mismatch on retry without bundle, deleting session');
1077
+ await authState.keys.set({ session: { [sessionId]: null } });
1078
+ }
1079
+ }
1080
+ }
1081
+ const BASE_KEY_CHECK_RETRY = 2;
1082
+ if (msgId && messageRetryManager) {
1083
+ const info = await signalRepository.getSessionInfo(participant);
1084
+ if (info) {
1085
+ if (retryCount === BASE_KEY_CHECK_RETRY) {
1086
+ messageRetryManager.saveBaseKey(sessionId, msgId, info.baseKey);
1087
+ }
1088
+ else if (retryCount > BASE_KEY_CHECK_RETRY) {
1089
+ if (messageRetryManager.hasSameBaseKey(sessionId, msgId, info.baseKey)) {
1090
+ logger.warn({ participant, retryCount }, 'base key collision on retry, forcing fresh session');
1091
+ await authState.keys.set({ session: { [sessionId]: null } });
1092
+ }
1093
+ messageRetryManager.deleteBaseKey(sessionId, msgId);
1094
+ }
1095
+ }
1096
+ }
1097
+ let shouldRecreateSession = false;
1098
+ let recreateReason = '';
1099
+ if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1 && !injectedFromBundle) {
1100
+ try {
1101
+ const hasSession = await signalRepository.validateSession(participant);
1102
+ const errorCode = messageRetryManager.parseRetryErrorCode(retryNode.attrs.error);
1103
+ const result = messageRetryManager.shouldRecreateSession(participant, hasSession.exists, errorCode);
1104
+ shouldRecreateSession = result.recreate;
1105
+ recreateReason = result.reason;
1106
+ if (shouldRecreateSession) {
1107
+ logger.debug({ participant, retryCount, reason: recreateReason }, 'recreating session for outgoing retry');
1108
+ await authState.keys.set({ session: { [sessionId]: null } });
1109
+ }
1110
+ }
1111
+ catch (error) {
1112
+ logger.warn({ error, participant }, 'failed to check session recreation for outgoing retry');
1113
+ }
1114
+ }
1115
+ if (!injectedFromBundle) {
1116
+ await assertSessions([participant], true);
1117
+ }
1118
+ if (isJidGroup(remoteJid)) {
1119
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1120
+ }
1121
+ logger.debug({ participant, sendToAll, shouldRecreateSession, recreateReason, injectedFromBundle }, 'prepared session for retry resend');
1122
+ for (const [i, msg] of msgs.entries()) {
1123
+ if (!ids[i])
1124
+ continue;
1125
+ if (msg && (await willSendMessageAgain(ids[i], participant))) {
1126
+ await updateSendMessageAgainCount(ids[i], participant);
1127
+ const msgRelayOpts = { messageId: ids[i] };
1128
+ if (sendToAll) {
1129
+ msgRelayOpts.useUserDevicesCache = false;
1130
+ }
1131
+ else {
1132
+ msgRelayOpts.participant = {
1133
+ jid: participant,
1134
+ count: +retryNode.attrs.count
1135
+ };
1136
+ }
1137
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
1138
+ }
1139
+ else {
1140
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
1141
+ }
1142
+ }
1143
+ };
1144
+ const handleReceipt = async (node) => {
1145
+ const { attrs, content } = node;
1146
+ const isLid = attrs.from.includes('lid');
1147
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1148
+ const remoteJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1149
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
1150
+ const key = {
1151
+ remoteJid,
1152
+ id: '',
1153
+ fromMe,
1154
+ participant: attrs.participant
1155
+ };
1156
+ const ids = [attrs.id];
1157
+ if (Array.isArray(content)) {
1158
+ const items = getBinaryNodeChildren(content[0], 'item');
1159
+ ids.push(...items.map(i => i.attrs.id));
1160
+ }
1161
+ try {
1162
+ await Promise.all([
1163
+ receiptMutex.mutex(async () => {
1164
+ const status = getStatusFromReceiptType(attrs.type);
1165
+ if (typeof status !== 'undefined' &&
1166
+ (status >= proto.WebMessageInfo.Status.SERVER_ACK || !isNodeFromMe)) {
1167
+ if (isJidGroup(remoteJid) || isJidStatusBroadcast(remoteJid)) {
1168
+ if (attrs.participant) {
1169
+ const updateKey = status === proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
1170
+ ev.emit('message-receipt.update', ids.map(id => ({
1171
+ key: { ...key, id },
1172
+ receipt: {
1173
+ userJid: jidNormalizedUser(attrs.participant),
1174
+ [updateKey]: +attrs.t
1175
+ }
1176
+ })));
1177
+ }
1178
+ }
1179
+ else {
1180
+ ev.emit('messages.update', ids.map(id => ({
1181
+ key: { ...key, id },
1182
+ update: { status, messageTimestamp: toNumber(+(attrs.t ?? 0)) }
1183
+ })));
1184
+ }
1185
+ }
1186
+ if (attrs.type === 'retry') {
1187
+ key.participant = key.participant || attrs.from;
1188
+ const retryNode = getBinaryNodeChild(node, 'retry');
1189
+ if (ids[0] && key.participant && (await willSendMessageAgain(ids[0], key.participant))) {
1190
+ if (key.fromMe) {
1191
+ try {
1192
+ await updateSendMessageAgainCount(ids[0], key.participant);
1193
+ logger.debug({ attrs, key }, 'recv retry request');
1194
+ await sendMessagesAgain(key, ids, retryNode, node);
1195
+ }
1196
+ catch (error) {
1197
+ logger.error({ key, ids, trace: error instanceof Error ? error.stack : 'Unknown error' }, 'error in sending message again');
1198
+ }
1199
+ }
1200
+ else {
1201
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
1202
+ }
1203
+ }
1204
+ else {
1205
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
1206
+ }
1207
+ }
1208
+ })
1209
+ ]);
1210
+ }
1211
+ finally {
1212
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack receipt'));
1213
+ }
1214
+ };
1215
+ const handleNotification = async (node) => {
1216
+ const remoteJid = node.attrs.from;
1217
+ try {
1218
+ await Promise.all([
1219
+ notificationMutex.mutex(async () => {
1220
+ const msg = await processNotification(node);
1221
+ if (msg) {
1222
+ const fromMe = areJidsSameUser(node.attrs.participant || remoteJid, authState.creds.me.id);
1223
+ const { senderAlt: participantAlt, addressingMode } = extractAddressingContext(node);
1224
+ msg.key = {
1225
+ remoteJid,
1226
+ fromMe,
1227
+ participant: node.attrs.participant,
1228
+ participantAlt,
1229
+ participantUsername: node.attrs.participant_username,
1230
+ addressingMode,
1231
+ id: node.attrs.id,
1232
+ ...(msg.key || {})
1233
+ };
1234
+ msg.participant ?? (msg.participant = node.attrs.participant);
1235
+ msg.messageTimestamp = +node.attrs.t;
1236
+ const fullMsg = proto.WebMessageInfo.fromObject(msg);
1237
+ await upsertMessage(fullMsg, 'append');
1238
+ }
1239
+ })
1240
+ ]);
1241
+ }
1242
+ finally {
1243
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
1244
+ }
1245
+ };
1246
+ const handleMessage = async (node) => {
1247
+ const encNode = getBinaryNodeChild(node, 'enc');
1248
+ if (encNode?.attrs.type === 'msmsg') {
1249
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
1250
+ await sendMessageAck(node, NACK_REASONS.MissingMessageSecret);
1251
+ return;
1252
+ }
1253
+ let acked = false;
1254
+ try {
1255
+ const { fullMessage: msg, category, author, decrypt } = decryptMessageNode(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
1256
+ const alt = msg.key.participantAlt || msg.key.remoteJidAlt;
1257
+ if (!!alt) {
1258
+ const altServer = jidDecode(alt)?.server;
1259
+ const primaryJid = msg.key.participant || msg.key.remoteJid;
1260
+ if (altServer === 'lid') {
1261
+ if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1262
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1263
+ await signalRepository.migrateSession(primaryJid, alt);
1264
+ }
1265
+ }
1266
+ else if (!(await signalRepository.lidMapping.getLIDForPN(alt))) {
1267
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1268
+ await signalRepository.migrateSession(alt, primaryJid);
1269
+ }
1270
+ }
1271
+ await messageMutex.mutex(async () => {
1272
+ await decrypt();
1273
+ if (msg.key?.remoteJid && msg.key?.id && msg.message && messageRetryManager) {
1274
+ messageRetryManager.addRecentMessage(msg.key.remoteJid, msg.key.id, msg.message);
1275
+ }
1276
+ if (msg.messageStubType === proto.WebMessageInfo.StubType.CIPHERTEXT && msg.category !== 'peer') {
1277
+ if (msg?.messageStubParameters?.[0] === MISSING_KEYS_ERROR_TEXT) {
1278
+ acked = true;
1279
+ return sendMessageAck(node, NACK_REASONS.ParsingError);
1280
+ }
1281
+ if (msg.messageStubParameters?.[0] === NO_MESSAGE_FOUND_ERROR_TEXT) {
1282
+ const unavailableNode = getBinaryNodeChild(node, 'unavailable');
1283
+ const unavailableType = unavailableNode?.attrs?.type;
1284
+ if (unavailableType === 'bot_unavailable_fanout' ||
1285
+ unavailableType === 'hosted_unavailable_fanout' ||
1286
+ unavailableType === 'view_once_unavailable_fanout') {
1287
+ logger.debug({ msgId: msg.key.id, unavailableType }, 'skipping placeholder resend for excluded unavailable type');
1288
+ acked = true;
1289
+ return sendMessageAck(node);
1290
+ }
1291
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1292
+ if (messageAge > PLACEHOLDER_MAX_AGE_SECONDS) {
1293
+ logger.debug({ msgId: msg.key.id, messageAge }, 'skipping placeholder resend for old message');
1294
+ acked = true;
1295
+ return sendMessageAck(node);
1296
+ }
1297
+ const cleanKey = {
1298
+ remoteJid: msg.key.remoteJid,
1299
+ fromMe: msg.key.fromMe,
1300
+ id: msg.key.id,
1301
+ participant: msg.key.participant
1302
+ };
1303
+ const msgData = {
1304
+ key: msg.key,
1305
+ messageTimestamp: msg.messageTimestamp,
1306
+ pushName: msg.pushName,
1307
+ participant: msg.participant,
1308
+ verifiedBizName: msg.verifiedBizName
1309
+ };
1310
+ requestPlaceholderResend(cleanKey, msgData)
1311
+ .then(requestId => {
1312
+ if (requestId && requestId !== 'RESOLVED') {
1313
+ logger.debug({ msgId: msg.key.id, requestId }, 'requested placeholder resend for unavailable message');
1314
+ ev.emit('messages.update', [
1315
+ {
1316
+ key: msg.key,
1317
+ update: { messageStubParameters: [NO_MESSAGE_FOUND_ERROR_TEXT, requestId] }
1318
+ }
1319
+ ]);
1320
+ }
1321
+ })
1322
+ .catch(err => {
1323
+ logger.warn({ err, msgId: msg.key.id }, 'failed to request placeholder resend for unavailable message');
1324
+ });
1325
+ acked = true;
1326
+ await sendMessageAck(node);
1327
+ }
1328
+ else {
1329
+ if (isJidStatusBroadcast(msg.key.remoteJid)) {
1330
+ const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
1331
+ if (messageAge > STATUS_EXPIRY_SECONDS) {
1332
+ logger.debug({ msgId: msg.key.id, messageAge, remoteJid: msg.key.remoteJid }, 'skipping retry for expired status message');
1333
+ acked = true;
1334
+ return sendMessageAck(node);
1335
+ }
1336
+ }
1337
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1338
+ await retryMutex.mutex(async () => {
1339
+ try {
1340
+ if (!ws.isOpen) {
1341
+ logger.debug({ node }, 'Connection closed, skipping retry');
1342
+ return;
1343
+ }
1344
+ const encNode = getBinaryNodeChild(node, 'enc');
1345
+ await sendRetryRequest(node, !encNode);
1346
+ if (retryRequestDelayMs) {
1347
+ await delay(retryRequestDelayMs);
1348
+ }
1349
+ }
1350
+ catch (err) {
1351
+ logger.error({ err }, 'Failed to send retry');
1352
+ }
1353
+ acked = true;
1354
+ await sendMessageAck(node, NACK_REASONS.UnhandledError);
1355
+ });
1356
+ }
1357
+ }
1358
+ else {
1359
+ if (messageRetryManager && msg.key.id) {
1360
+ messageRetryManager.cancelPendingPhoneRequest(msg.key.id);
1361
+ }
1362
+ const isNewsletter = isJidNewsletter(msg.key.remoteJid);
1363
+ if (!isNewsletter) {
1364
+ let type = undefined;
1365
+ let participant = msg.key.participant;
1366
+ if (category === 'peer') {
1367
+ type = 'peer_msg';
1368
+ }
1369
+ else if (msg.key.fromMe) {
1370
+ type = 'sender';
1371
+ if (isLidUser(msg.key.remoteJid) || isLidUser(msg.key.remoteJidAlt)) {
1372
+ participant = author;
1373
+ }
1374
+ }
1375
+ else if (!sendActiveReceipts) {
1376
+ type = 'inactive';
1377
+ }
1378
+ acked = true;
1379
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
1380
+ const isAnyHistoryMsg = getHistoryMsg(msg.message);
1381
+ if (isAnyHistoryMsg) {
1382
+ const jid = jidNormalizedUser(msg.key.remoteJid);
1383
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
1384
+ }
1385
+ }
1386
+ else {
1387
+ acked = true;
1388
+ await sendMessageAck(node);
1389
+ logger.debug({ key: msg.key }, 'processed newsletter message without receipts');
1390
+ }
1391
+ }
1392
+ cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1393
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1394
+ });
1395
+ }
1396
+ catch (error) {
1397
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling message');
1398
+ if (!acked) {
1399
+ await sendMessageAck(node, NACK_REASONS.UnhandledError).catch(ackErr => logger.error({ ackErr }, 'failed to ack message after error'));
1400
+ }
1401
+ }
1402
+ };
1403
+ const handleCall = async (node) => {
1404
+ try {
1405
+ const { attrs } = node;
1406
+ const [infoChild] = getAllBinaryNodeChildren(node);
1407
+ if (!infoChild) {
1408
+ throw new Boom('Missing call info in call node');
1409
+ }
1410
+ const status = getCallStatusFromNode(infoChild);
1411
+ const callId = infoChild.attrs['call-id'];
1412
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
1413
+ const call = {
1414
+ chatId: attrs.from,
1415
+ from,
1416
+ callerPn: infoChild.attrs['caller_pn'],
1417
+ id: callId,
1418
+ date: new Date(+attrs.t * 1000),
1419
+ offline: !!attrs.offline,
1420
+ status
1421
+ };
1422
+ if (status === 'relaylatency') {
1423
+ const latencyValue = infoChild.attrs.latency || infoChild.attrs['latency_ms'] || infoChild.attrs['latency-ms'];
1424
+ const latencyMs = latencyValue ? Number(latencyValue) : undefined;
1425
+ if (Number.isFinite(latencyMs)) {
1426
+ call.latencyMs = latencyMs;
1427
+ }
1428
+ }
1429
+ if (status === 'offer') {
1430
+ call.isVideo = !!getBinaryNodeChild(infoChild, 'video');
1431
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
1432
+ call.groupJid = infoChild.attrs['group-jid'];
1433
+ await callOfferCache.set(call.id, call);
1434
+ }
1435
+ const existingCall = await callOfferCache.get(call.id);
1436
+ if (existingCall) {
1437
+ call.isVideo = existingCall.isVideo;
1438
+ call.isGroup = existingCall.isGroup;
1439
+ call.callerPn = call.callerPn || existingCall.callerPn;
1440
+ }
1441
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
1442
+ await callOfferCache.del(call.id);
1443
+ }
1444
+ ev.emit('call', [call]);
1445
+ }
1446
+ catch (error) {
1447
+ logger.error({ error, node: binaryNodeToString(node) }, 'error in handling call');
1448
+ }
1449
+ finally {
1450
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack call'));
1451
+ }
1452
+ };
1453
+ const handleBadAck = async ({ attrs }) => {
1454
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1455
+ if (attrs.error) {
1456
+ const isReachoutTimelocked = attrs.error === String(NACK_REASONS.SenderReachoutTimelocked);
1457
+ if (attrs.error === SERVER_ERROR_CODES.MessageAccountRestriction) {
1458
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'error 463: account restricted or missing tctoken for contact');
1459
+ const ackFrom = attrs.from;
1460
+ if (ackFrom && !inFlight463Recoveries.has(ackFrom)) {
1461
+ inFlight463Recoveries.add(ackFrom);
1462
+ void (async () => {
1463
+ try {
1464
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1465
+ const tcStorageJid = await resolveTcTokenJid(ackFrom, getLIDForPN);
1466
+ const issueJid = await resolveIssuanceJid(ackFrom, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID);
1467
+ const result = await issuePrivacyTokens([issueJid], unixTimestampSeconds());
1468
+ await storeTcTokensFromIqResult({
1469
+ result,
1470
+ fallbackJid: tcStorageJid,
1471
+ keys: authState.keys,
1472
+ getLIDForPN,
1473
+ onNewJidStored: trackTcTokenJid
1474
+ });
1475
+ logger.debug({ from: ackFrom }, 'completed 463 token recovery issuance');
1476
+ }
1477
+ catch (err) {
1478
+ logger.debug({ from: ackFrom, err: err?.message }, 'failed 463 token recovery issuance');
1479
+ }
1480
+ finally {
1481
+ inFlight463Recoveries.delete(ackFrom);
1482
+ }
1483
+ })();
1484
+ }
1485
+ }
1486
+ else if (attrs.error === SERVER_ERROR_CODES.SmaxInvalid) {
1487
+ logger.warn({ msgId: attrs.id, from: attrs.from }, 'smax-invalid (479): stanza rejected by server — likely stale device session or malformed addressing');
1488
+ }
1489
+ else if (isReachoutTimelocked) {
1490
+ await fetchAccountReachoutTimelock().catch(err => logger.warn({ err }, 'failed to fetch reachout timelock'));
1491
+ logger.warn({ attrs }, 'received error in ack');
1492
+ }
1493
+ else {
1494
+ logger.warn({ attrs }, 'received error in ack');
1495
+ }
1496
+ ev.emit('messages.update', [
1497
+ {
1498
+ key,
1499
+ update: {
1500
+ status: WAMessageStatus.ERROR,
1501
+ messageStubParameters: isReachoutTimelocked ? [attrs.error, ACCOUNT_RESTRICTED_TEXT] : [attrs.error]
1502
+ }
1503
+ }
1504
+ ]);
1505
+ }
1506
+ };
1507
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1508
+ ev.buffer();
1509
+ await execTask();
1510
+ ev.flush();
1511
+ function execTask() {
1512
+ return exec(node, false).catch(err => onUnexpectedError(err, identifier));
1513
+ }
1514
+ };
1515
+ const offlineNodeProcessor = makeOfflineNodeProcessor(new Map([
1516
+ ['message', handleMessage],
1517
+ ['call', handleCall],
1518
+ ['receipt', handleReceipt],
1519
+ ['notification', handleNotification]
1520
+ ]), {
1521
+ isWsOpen: () => ws.isOpen,
1522
+ onUnexpectedError,
1523
+ yieldToEventLoop: () => new Promise(resolve => setImmediate(resolve))
1524
+ });
1525
+ const processNode = async (type, node, identifier, exec) => {
1526
+ const from = node.attrs.from;
1527
+ let ignoreJid = from;
1528
+ if (type === 'receipt' && from) {
1529
+ const attrs = node.attrs;
1530
+ const isLid = attrs.from.includes('lid');
1531
+ const isNodeFromMe = areJidsSameUser(attrs.participant || attrs.from, isLid ? authState.creds.me?.lid : authState.creds.me?.id);
1532
+ ignoreJid = !isNodeFromMe || isJidGroup(attrs.from) ? attrs.from : attrs.recipient;
1533
+ }
1534
+ if (ignoreJid && ignoreJid !== S_WHATSAPP_NET && shouldIgnoreJid(ignoreJid)) {
1535
+ await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
1536
+ return;
1537
+ }
1538
+ const isOffline = !!node.attrs.offline;
1539
+ if (isOffline) {
1540
+ offlineNodeProcessor.enqueue(type, node);
1541
+ }
1542
+ else {
1543
+ await processNodeWithBuffer(node, identifier, exec);
1544
+ }
1545
+ };
1546
+ ws.on('CB:message', async (node) => {
1547
+ await processNode('message', node, 'processing message', handleMessage);
1548
+ });
1549
+ ws.on('CB:call', async (node) => {
1550
+ await processNode('call', node, 'handling call', handleCall);
1551
+ });
1552
+ ws.on('CB:receipt', async (node) => {
1553
+ await processNode('receipt', node, 'handling receipt', handleReceipt);
1554
+ });
1555
+ ws.on('CB:notification', async (node) => {
1556
+ await processNode('notification', node, 'handling notification', handleNotification);
1557
+ });
1558
+ ws.on('CB:ack,class:message', (node) => {
1559
+ handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1560
+ });
1561
+ ev.on('call', async ([call]) => {
1562
+ if (!call) {
1563
+ return;
1564
+ }
1565
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1566
+ const msg = {
1567
+ key: {
1568
+ remoteJid: call.chatId,
1569
+ id: call.id,
1570
+ fromMe: false
1571
+ },
1572
+ messageTimestamp: unixTimestampSeconds(call.date)
1573
+ };
1574
+ if (call.status === 'timeout') {
1575
+ if (call.isGroup) {
1576
+ msg.messageStubType = call.isVideo
1577
+ ? WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1578
+ : WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1579
+ }
1580
+ else {
1581
+ msg.messageStubType = call.isVideo ? WAMessageStubType.CALL_MISSED_VIDEO : WAMessageStubType.CALL_MISSED_VOICE;
1582
+ }
1583
+ }
1584
+ else {
1585
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1586
+ }
1587
+ const protoMsg = proto.WebMessageInfo.fromObject(msg);
1588
+ await upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1589
+ }
1590
+ });
1591
+ let lastTcTokenPruneTs = 0;
1592
+ const inFlight463Recoveries = new Set();
1593
+ ev.on('connection.update', ({ isOnline, connection }) => {
1594
+ if (typeof isOnline !== 'undefined') {
1595
+ sendActiveReceipts = isOnline;
1596
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1597
+ }
1598
+ if (connection === 'open') {
1599
+ offlineNodeProcessor.resume();
1600
+ }
1601
+ if (connection === 'close' && tcTokenIndexTimer) {
1602
+ clearTimeout(tcTokenIndexTimer);
1603
+ tcTokenIndexTimer = undefined;
1604
+ try {
1605
+ void Promise.resolve(flushTcTokenIndex()).catch(() => { });
1606
+ }
1607
+ catch {
1608
+ }
1609
+ }
1610
+ if (isOnline) {
1611
+ const now = Date.now();
1612
+ const DAY_MS = 24 * 60 * 60 * 1000;
1613
+ if (now - lastTcTokenPruneTs >= DAY_MS) {
1614
+ lastTcTokenPruneTs = now;
1615
+ void pruneExpiredTcTokens();
1616
+ }
1617
+ }
1618
+ });
1619
+ registerSocketEndHandler(() => {
1620
+ if (!config.msgRetryCounterCache && msgRetryCache.close) {
1621
+ msgRetryCache.close();
1622
+ }
1623
+ if (!config.callOfferCache && callOfferCache.close) {
1624
+ callOfferCache.close();
1625
+ }
1626
+ identityAssertDebounce.close();
1627
+ sendActiveReceipts = false;
1628
+ });
1629
+ async function pruneExpiredTcTokens() {
1630
+ try {
1631
+ await tcTokenIndexLoaded;
1632
+ const persisted = await readTcTokenIndex(authState.keys);
1633
+ const allJids = new Set(tcTokenKnownJids);
1634
+ for (const jid of persisted)
1635
+ allJids.add(jid);
1636
+ if (!allJids.size)
1637
+ return;
1638
+ const jids = [...allJids];
1639
+ const allTokens = await authState.keys.get('tctoken', jids);
1640
+ const writes = {};
1641
+ const survivors = new Set();
1642
+ let mutated = 0;
1643
+ for (const jid of jids) {
1644
+ const entry = allTokens[jid];
1645
+ if (!entry) {
1646
+ mutated++;
1647
+ continue;
1648
+ }
1649
+ const hasPeerToken = !!entry.token?.length;
1650
+ const peerTokenExpired = hasPeerToken && isTcTokenExpired(entry.timestamp);
1651
+ const hasSenderTs = entry.senderTimestamp !== undefined;
1652
+ const senderTsExpired = hasSenderTs && isTcTokenExpired(entry.senderTimestamp);
1653
+ const keepPeerToken = hasPeerToken && !peerTokenExpired;
1654
+ const keepSenderTs = hasSenderTs && !senderTsExpired;
1655
+ if (!keepPeerToken && !keepSenderTs) {
1656
+ writes[jid] = null;
1657
+ mutated++;
1658
+ }
1659
+ else if (peerTokenExpired && keepSenderTs) {
1660
+ writes[jid] = { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp };
1661
+ survivors.add(jid);
1662
+ mutated++;
1663
+ }
1664
+ else {
1665
+ survivors.add(jid);
1666
+ }
1667
+ }
1668
+ if (mutated === 0)
1669
+ return;
1670
+ await authState.keys.set({
1671
+ tctoken: {
1672
+ ...writes,
1673
+ [TC_TOKEN_INDEX_KEY]: {
1674
+ token: Buffer.from(JSON.stringify([...survivors]))
1675
+ }
1676
+ }
1677
+ });
1678
+ tcTokenKnownJids.clear();
1679
+ for (const jid of survivors)
1680
+ tcTokenKnownJids.add(jid);
1681
+ logger.debug({ mutated, remaining: survivors.size }, 'pruned expired tctokens');
1682
+ }
1683
+ catch (err) {
1684
+ logger.warn({ err: err?.message }, 'failed to prune expired tctokens');
1685
+ }
1686
+ }
1687
+ return {
1688
+ ...sock,
1689
+ sendMessageAck,
1690
+ sendRetryRequest,
1691
+ rejectCall,
1692
+ fetchMessageHistory,
1693
+ requestPlaceholderResend,
1694
+ messageRetryManager
1695
+ };
1696
+ };
1697
+ //# sourceMappingURL=messages-recv.js.map