@eduh_dev021/baileys 0.0.0-stage → 1.0.0

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