@eduh_dev021/baileys 0.0.0-stage → 1.1.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 (526) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +1843 -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/cache.js +179 -0
  9. package/cjs/lib/Addon/crc32.js +41 -0
  10. package/cjs/lib/Addon/file-type.js +217 -0
  11. package/cjs/lib/Addon/get-file.js +99 -0
  12. package/cjs/lib/Addon/http-error.d.ts +18 -0
  13. package/cjs/lib/Addon/http-error.js +66 -0
  14. package/cjs/lib/Addon/index.d.ts +96 -0
  15. package/cjs/lib/Addon/index.js +58 -0
  16. package/cjs/lib/Addon/keyed-db.d.ts +14 -0
  17. package/cjs/lib/Addon/keyed-db.js +264 -0
  18. package/cjs/lib/Addon/link-preview.d.ts +15 -0
  19. package/cjs/lib/Addon/link-preview.js +104 -0
  20. package/cjs/lib/Addon/media-info.js +98 -0
  21. package/cjs/lib/Addon/mutex.js +78 -0
  22. package/cjs/lib/Addon/qr.js +464 -0
  23. package/cjs/lib/Addon/queue.js +54 -0
  24. package/cjs/lib/Addon/waveform.js +130 -0
  25. package/cjs/lib/Addon/zip.js +136 -0
  26. package/cjs/lib/Defaults/index.d.ts +184 -0
  27. package/cjs/lib/Defaults/index.js +292 -0
  28. package/cjs/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  29. package/cjs/lib/Signal/Group/ciphertext-message.js +37 -0
  30. package/cjs/lib/Signal/Group/group-cipher.d.ts +10 -0
  31. package/cjs/lib/Signal/Group/group-cipher.js +105 -0
  32. package/cjs/lib/Signal/Group/group-session-builder.d.ts +7 -0
  33. package/cjs/lib/Signal/Group/group-session-builder.js +65 -0
  34. package/cjs/lib/Signal/Group/index.d.ts +11 -0
  35. package/cjs/lib/Signal/Group/index.js +67 -0
  36. package/cjs/lib/Signal/Group/keyhelper.d.ts +6 -0
  37. package/cjs/lib/Signal/Group/keyhelper.js +47 -0
  38. package/cjs/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  39. package/cjs/lib/Signal/Group/sender-chain-key.js +51 -0
  40. package/cjs/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  41. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +80 -0
  42. package/cjs/lib/Signal/Group/sender-key-message.d.ts +18 -0
  43. package/cjs/lib/Signal/Group/sender-key-message.js +87 -0
  44. package/cjs/lib/Signal/Group/sender-key-name.d.ts +11 -0
  45. package/cjs/lib/Signal/Group/sender-key-name.js +73 -0
  46. package/cjs/lib/Signal/Group/sender-key-record.d.ts +12 -0
  47. package/cjs/lib/Signal/Group/sender-key-record.js +66 -0
  48. package/cjs/lib/Signal/Group/sender-key-state.d.ts +16 -0
  49. package/cjs/lib/Signal/Group/sender-key-state.js +106 -0
  50. package/cjs/lib/Signal/Group/sender-message-key.d.ts +11 -0
  51. package/cjs/lib/Signal/Group/sender-message-key.js +51 -0
  52. package/cjs/lib/Signal/libsignal.d.ts +54 -0
  53. package/cjs/lib/Signal/libsignal.js +421 -0
  54. package/cjs/lib/Signal/lid-mapping.d.ts +20 -0
  55. package/cjs/lib/Signal/lid-mapping.js +292 -0
  56. package/cjs/lib/Socket/Client/index.d.ts +2 -0
  57. package/cjs/lib/Socket/Client/index.js +23 -0
  58. package/cjs/lib/Socket/Client/types.d.ts +5 -0
  59. package/cjs/lib/Socket/Client/types.js +36 -0
  60. package/cjs/lib/Socket/Client/websocket.d.ts +12 -0
  61. package/cjs/lib/Socket/Client/websocket.js +143 -0
  62. package/cjs/lib/Socket/business.d.ts +387 -0
  63. package/cjs/lib/Socket/business.js +402 -0
  64. package/cjs/lib/Socket/chats.d.ts +144 -0
  65. package/cjs/lib/Socket/chats.js +1118 -0
  66. package/cjs/lib/Socket/communities.d.ts +554 -0
  67. package/cjs/lib/Socket/communities.js +456 -0
  68. package/cjs/lib/Socket/groups.d.ts +286 -0
  69. package/cjs/lib/Socket/groups.js +366 -0
  70. package/cjs/lib/Socket/index.d.ts +522 -0
  71. package/cjs/lib/Socket/index.js +32 -0
  72. package/cjs/lib/Socket/messages-recv.d.ts +326 -0
  73. package/cjs/lib/Socket/messages-recv.js +1670 -0
  74. package/cjs/lib/Socket/messages-send.d.ts +321 -0
  75. package/cjs/lib/Socket/messages-send.js +1252 -0
  76. package/cjs/lib/Socket/mex.d.ts +1 -0
  77. package/cjs/lib/Socket/mex.js +65 -0
  78. package/cjs/lib/Socket/newsletter.d.ts +283 -0
  79. package/cjs/lib/Socket/newsletter.js +243 -0
  80. package/cjs/lib/Socket/socket.d.ts +61 -0
  81. package/cjs/lib/Socket/socket.js +908 -0
  82. package/cjs/lib/Store/index.d.ts +3 -0
  83. package/cjs/lib/Store/index.js +25 -0
  84. package/cjs/lib/Store/make-in-memory-store.d.ts +63 -0
  85. package/cjs/lib/Store/make-in-memory-store.js +431 -0
  86. package/cjs/lib/Store/make-ordered-dictionary.d.ts +12 -0
  87. package/cjs/lib/Store/make-ordered-dictionary.js +101 -0
  88. package/cjs/lib/Store/object-repository.d.ts +10 -0
  89. package/cjs/lib/Store/object-repository.js +49 -0
  90. package/cjs/lib/Transport/crypto.d.ts +6 -0
  91. package/cjs/lib/Transport/crypto.js +107 -0
  92. package/cjs/lib/Transport/curve.d.ts +8 -0
  93. package/cjs/lib/Transport/curve.js +94 -0
  94. package/cjs/lib/Transport/index.d.ts +16 -0
  95. package/cjs/lib/Transport/index.js +67 -0
  96. package/cjs/lib/Transport/internals.d.ts +57 -0
  97. package/cjs/lib/Transport/internals.js +203 -0
  98. package/cjs/lib/Transport/session-builder.d.ts +40 -0
  99. package/cjs/lib/Transport/session-builder.js +169 -0
  100. package/cjs/lib/Transport/session-cipher.d.ts +26 -0
  101. package/cjs/lib/Transport/session-cipher.js +328 -0
  102. package/cjs/lib/Transport/session-record.d.ts +55 -0
  103. package/cjs/lib/Transport/session-record.js +289 -0
  104. package/cjs/lib/Types/Auth.d.ts +1 -0
  105. package/cjs/lib/Types/Auth.js +15 -0
  106. package/cjs/lib/Types/Bussines.d.ts +1 -0
  107. package/cjs/lib/Types/Bussines.js +15 -0
  108. package/cjs/lib/Types/Call.d.ts +1 -0
  109. package/cjs/lib/Types/Call.js +15 -0
  110. package/cjs/lib/Types/Chat.d.ts +1 -0
  111. package/cjs/lib/Types/Chat.js +33 -0
  112. package/cjs/lib/Types/Contact.d.ts +1 -0
  113. package/cjs/lib/Types/Contact.js +15 -0
  114. package/cjs/lib/Types/Events.d.ts +1 -0
  115. package/cjs/lib/Types/Events.js +1 -0
  116. package/cjs/lib/Types/GroupMetadata.d.ts +1 -0
  117. package/cjs/lib/Types/GroupMetadata.js +15 -0
  118. package/cjs/lib/Types/Label.d.ts +2 -0
  119. package/cjs/lib/Types/Label.js +49 -0
  120. package/cjs/lib/Types/LabelAssociation.d.ts +2 -0
  121. package/cjs/lib/Types/LabelAssociation.js +31 -0
  122. package/cjs/lib/Types/Message.d.ts +11 -0
  123. package/cjs/lib/Types/Message.js +58 -0
  124. package/cjs/lib/Types/Mex.d.ts +2 -0
  125. package/cjs/lib/Types/Mex.js +66 -0
  126. package/cjs/lib/Types/Product.d.ts +1 -0
  127. package/cjs/lib/Types/Product.js +15 -0
  128. package/cjs/lib/Types/RichType.d.ts +2 -0
  129. package/cjs/lib/Types/RichType.js +50 -0
  130. package/cjs/lib/Types/Signal.d.ts +1 -0
  131. package/cjs/lib/Types/Signal.js +1 -0
  132. package/cjs/lib/Types/Socket.d.ts +1 -0
  133. package/cjs/lib/Types/Socket.js +1 -0
  134. package/cjs/lib/Types/State.d.ts +5 -0
  135. package/cjs/lib/Types/State.js +83 -0
  136. package/cjs/lib/Types/USync.d.ts +1 -0
  137. package/cjs/lib/Types/USync.js +1 -0
  138. package/cjs/lib/Types/index.d.ts +13 -0
  139. package/cjs/lib/Types/index.js +64 -0
  140. package/cjs/lib/Utils/auth-utils.d.ts +58 -0
  141. package/cjs/lib/Utils/auth-utils.js +275 -0
  142. package/cjs/lib/Utils/browser-utils.d.ts +9 -0
  143. package/cjs/lib/Utils/browser-utils.js +56 -0
  144. package/cjs/lib/Utils/business.d.ts +49 -0
  145. package/cjs/lib/Utils/business.js +259 -0
  146. package/cjs/lib/Utils/chat-utils.d.ts +408 -0
  147. package/cjs/lib/Utils/chat-utils.js +821 -0
  148. package/cjs/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  149. package/cjs/lib/Utils/companion-reg-client-utils.js +71 -0
  150. package/cjs/lib/Utils/crypto.d.ts +39 -0
  151. package/cjs/lib/Utils/crypto.js +155 -0
  152. package/cjs/lib/Utils/decode-wa-message.d.ts +83 -0
  153. package/cjs/lib/Utils/decode-wa-message.js +316 -0
  154. package/cjs/lib/Utils/event-buffer.d.ts +12 -0
  155. package/cjs/lib/Utils/event-buffer.js +605 -0
  156. package/cjs/lib/Utils/generics.d.ts +63 -0
  157. package/cjs/lib/Utils/generics.js +440 -0
  158. package/cjs/lib/Utils/history.d.ts +75 -0
  159. package/cjs/lib/Utils/history.js +153 -0
  160. package/cjs/lib/Utils/identity-change-handler.d.ts +13 -0
  161. package/cjs/lib/Utils/identity-change-handler.js +73 -0
  162. package/cjs/lib/Utils/index.d.ts +24 -0
  163. package/cjs/lib/Utils/index.js +67 -0
  164. package/cjs/lib/Utils/link-preview.d.ts +13 -0
  165. package/cjs/lib/Utils/link-preview.js +87 -0
  166. package/cjs/lib/Utils/logger.d.ts +12 -0
  167. package/cjs/lib/Utils/logger.js +40 -0
  168. package/cjs/lib/Utils/lt-hash.d.ts +6 -0
  169. package/cjs/lib/Utils/lt-hash.js +28 -0
  170. package/cjs/lib/Utils/make-mutex.d.ts +6 -0
  171. package/cjs/lib/Utils/make-mutex.js +58 -0
  172. package/cjs/lib/Utils/message-retry-manager.d.ts +79 -0
  173. package/cjs/lib/Utils/message-retry-manager.js +274 -0
  174. package/cjs/lib/Utils/messages-media.d.ts +134 -0
  175. package/cjs/lib/Utils/messages-media.js +799 -0
  176. package/cjs/lib/Utils/messages.d.ts +47 -0
  177. package/cjs/lib/Utils/messages.js +1667 -0
  178. package/cjs/lib/Utils/noise-handler.d.ts +20 -0
  179. package/cjs/lib/Utils/noise-handler.js +223 -0
  180. package/cjs/lib/Utils/offline-node-processor.d.ts +10 -0
  181. package/cjs/lib/Utils/offline-node-processor.js +60 -0
  182. package/cjs/lib/Utils/pre-key-manager.d.ts +25 -0
  183. package/cjs/lib/Utils/pre-key-manager.js +116 -0
  184. package/cjs/lib/Utils/process-message.d.ts +83 -0
  185. package/cjs/lib/Utils/process-message.js +607 -0
  186. package/cjs/lib/Utils/reporting-utils.d.ts +12 -0
  187. package/cjs/lib/Utils/reporting-utils.js +282 -0
  188. package/cjs/lib/Utils/rich-message-utils.d.ts +48 -0
  189. package/cjs/lib/Utils/rich-message-utils.js +381 -0
  190. package/cjs/lib/Utils/signal.d.ts +82 -0
  191. package/cjs/lib/Utils/signal.js +232 -0
  192. package/cjs/lib/Utils/stanza-ack.d.ts +16 -0
  193. package/cjs/lib/Utils/stanza-ack.js +53 -0
  194. package/cjs/lib/Utils/sync-action-utils.d.ts +2 -0
  195. package/cjs/lib/Utils/sync-action-utils.js +68 -0
  196. package/cjs/lib/Utils/tc-token-utils.d.ts +29 -0
  197. package/cjs/lib/Utils/tc-token-utils.js +182 -0
  198. package/cjs/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  199. package/cjs/lib/Utils/use-multi-file-auth-state.js +135 -0
  200. package/cjs/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  201. package/cjs/lib/Utils/use-single-file-auth-state.js +115 -0
  202. package/cjs/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  203. package/cjs/lib/Utils/use-sqlite-auth-state.js +140 -0
  204. package/cjs/lib/Utils/validate-connection.d.ts +44 -0
  205. package/cjs/lib/Utils/validate-connection.js +229 -0
  206. package/cjs/lib/WABinary/constants.d.ts +61 -0
  207. package/cjs/lib/WABinary/constants.js +1992 -0
  208. package/cjs/lib/WABinary/decode.d.ts +9 -0
  209. package/cjs/lib/WABinary/decode.js +292 -0
  210. package/cjs/lib/WABinary/encode.d.ts +2 -0
  211. package/cjs/lib/WABinary/encode.js +240 -0
  212. package/cjs/lib/WABinary/generic-utils.d.ts +79 -0
  213. package/cjs/lib/WABinary/generic-utils.js +252 -0
  214. package/cjs/lib/WABinary/index.d.ts +5 -0
  215. package/cjs/lib/WABinary/index.js +29 -0
  216. package/cjs/lib/WABinary/jid-utils.d.ts +28 -0
  217. package/cjs/lib/WABinary/jid-utils.js +151 -0
  218. package/cjs/lib/WABinary/types.d.ts +1 -0
  219. package/cjs/lib/WABinary/types.js +23 -0
  220. package/cjs/lib/WACrypto/appstate-keys.js +39 -0
  221. package/cjs/lib/WACrypto/curves/constants.js +37 -0
  222. package/cjs/lib/WACrypto/hkdf.js +38 -0
  223. package/cjs/lib/WACrypto/index.js +51 -0
  224. package/cjs/lib/WACrypto/lthash.js +59 -0
  225. package/cjs/lib/WACrypto/math/constants.js +53 -0
  226. package/cjs/lib/WACrypto/math/edwards.js +206 -0
  227. package/cjs/lib/WACrypto/math/fe.js +449 -0
  228. package/cjs/lib/WACrypto/math/le.js +44 -0
  229. package/cjs/lib/WACrypto/math/mod.js +36 -0
  230. package/cjs/lib/WACrypto/util/bytes.js +348 -0
  231. package/cjs/lib/WACrypto/x25519.js +157 -0
  232. package/cjs/lib/WACrypto/xeddsa.js +134 -0
  233. package/cjs/lib/WAM/BinaryInfo.d.ts +7 -0
  234. package/cjs/lib/WAM/BinaryInfo.js +35 -0
  235. package/cjs/lib/WAM/constants.d.ts +34926 -0
  236. package/cjs/lib/WAM/constants.js +22890 -0
  237. package/cjs/lib/WAM/encode.d.ts +1 -0
  238. package/cjs/lib/WAM/encode.js +162 -0
  239. package/cjs/lib/WAM/index.d.ts +3 -0
  240. package/cjs/lib/WAM/index.js +25 -0
  241. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  242. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +77 -0
  243. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  244. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +76 -0
  245. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  246. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +52 -0
  247. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  248. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +61 -0
  249. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  250. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +50 -0
  251. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  252. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
  253. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  254. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +53 -0
  255. package/cjs/lib/WAUSync/Protocols/index.d.ts +5 -0
  256. package/cjs/lib/WAUSync/Protocols/index.js +29 -0
  257. package/cjs/lib/WAUSync/USyncQuery.d.ts +20 -0
  258. package/cjs/lib/WAUSync/USyncQuery.js +113 -0
  259. package/cjs/lib/WAUSync/USyncUser.d.ts +16 -0
  260. package/cjs/lib/WAUSync/USyncUser.js +56 -0
  261. package/cjs/lib/WAUSync/index.d.ts +3 -0
  262. package/cjs/lib/WAUSync/index.js +25 -0
  263. package/cjs/lib/index.d.ts +11 -0
  264. package/cjs/lib/index.js +56 -0
  265. package/cjs/package.json +3 -0
  266. package/engine-requirements.js +12 -0
  267. package/lib/Addon/cache.js +201 -0
  268. package/lib/Addon/crc32.js +21 -0
  269. package/lib/Addon/file-type.js +198 -0
  270. package/lib/Addon/get-file.js +98 -0
  271. package/lib/Addon/http-error.d.ts +18 -0
  272. package/lib/Addon/http-error.js +40 -0
  273. package/lib/Addon/index.d.ts +96 -0
  274. package/lib/Addon/index.js +26 -0
  275. package/lib/Addon/keyed-db.d.ts +14 -0
  276. package/lib/Addon/keyed-db.js +241 -0
  277. package/lib/Addon/link-preview.d.ts +15 -0
  278. package/lib/Addon/link-preview.js +79 -0
  279. package/lib/Addon/media-info.js +96 -0
  280. package/lib/Addon/mutex.js +76 -0
  281. package/lib/Addon/qr.js +531 -0
  282. package/lib/Addon/queue.js +44 -0
  283. package/lib/Addon/waveform.js +135 -0
  284. package/lib/Addon/zip.js +144 -0
  285. package/lib/Defaults/index.d.ts +184 -0
  286. package/lib/Defaults/index.js +181 -0
  287. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  288. package/lib/Signal/Group/ciphertext-message.js +11 -0
  289. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  290. package/lib/Signal/Group/group-cipher.js +81 -0
  291. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  292. package/lib/Signal/Group/group-session-builder.js +29 -0
  293. package/lib/Signal/Group/index.d.ts +11 -0
  294. package/lib/Signal/Group/index.js +11 -0
  295. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  296. package/lib/Signal/Group/keyhelper.js +17 -0
  297. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  298. package/lib/Signal/Group/sender-chain-key.js +25 -0
  299. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  300. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  301. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  302. package/lib/Signal/Group/sender-key-message.js +65 -0
  303. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  304. package/lib/Signal/Group/sender-key-name.js +47 -0
  305. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  306. package/lib/Signal/Group/sender-key-record.js +40 -0
  307. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  308. package/lib/Signal/Group/sender-key-state.js +83 -0
  309. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  310. package/lib/Signal/Group/sender-message-key.js +25 -0
  311. package/lib/Signal/libsignal.d.ts +54 -0
  312. package/lib/Signal/libsignal.js +426 -0
  313. package/lib/Signal/lid-mapping.d.ts +20 -0
  314. package/lib/Signal/lid-mapping.js +274 -0
  315. package/lib/Socket/Client/index.d.ts +2 -0
  316. package/lib/Socket/Client/index.js +2 -0
  317. package/lib/Socket/Client/types.d.ts +5 -0
  318. package/lib/Socket/Client/types.js +10 -0
  319. package/lib/Socket/Client/websocket.d.ts +12 -0
  320. package/lib/Socket/Client/websocket.js +119 -0
  321. package/lib/Socket/business.d.ts +387 -0
  322. package/lib/Socket/business.js +379 -0
  323. package/lib/Socket/chats.d.ts +144 -0
  324. package/lib/Socket/chats.js +1216 -0
  325. package/lib/Socket/communities.d.ts +554 -0
  326. package/lib/Socket/communities.js +431 -0
  327. package/lib/Socket/groups.d.ts +286 -0
  328. package/lib/Socket/groups.js +347 -0
  329. package/lib/Socket/index.d.ts +522 -0
  330. package/lib/Socket/index.js +11 -0
  331. package/lib/Socket/messages-recv.d.ts +326 -0
  332. package/lib/Socket/messages-recv.js +1822 -0
  333. package/lib/Socket/messages-send.d.ts +321 -0
  334. package/lib/Socket/messages-send.js +1378 -0
  335. package/lib/Socket/mex.d.ts +1 -0
  336. package/lib/Socket/mex.js +41 -0
  337. package/lib/Socket/newsletter.d.ts +283 -0
  338. package/lib/Socket/newsletter.js +225 -0
  339. package/lib/Socket/socket.d.ts +61 -0
  340. package/lib/Socket/socket.js +992 -0
  341. package/lib/Store/index.d.ts +3 -0
  342. package/lib/Store/index.js +3 -0
  343. package/lib/Store/make-in-memory-store.d.ts +63 -0
  344. package/lib/Store/make-in-memory-store.js +419 -0
  345. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  346. package/lib/Store/make-ordered-dictionary.js +78 -0
  347. package/lib/Store/object-repository.d.ts +10 -0
  348. package/lib/Store/object-repository.js +23 -0
  349. package/lib/Transport/crypto.d.ts +6 -0
  350. package/lib/Transport/crypto.js +61 -0
  351. package/lib/Transport/curve.d.ts +8 -0
  352. package/lib/Transport/curve.js +66 -0
  353. package/lib/Transport/index.d.ts +16 -0
  354. package/lib/Transport/index.js +9 -0
  355. package/lib/Transport/internals.d.ts +57 -0
  356. package/lib/Transport/internals.js +155 -0
  357. package/lib/Transport/session-builder.d.ts +40 -0
  358. package/lib/Transport/session-builder.js +143 -0
  359. package/lib/Transport/session-cipher.d.ts +26 -0
  360. package/lib/Transport/session-cipher.js +301 -0
  361. package/lib/Transport/session-record.d.ts +55 -0
  362. package/lib/Transport/session-record.js +272 -0
  363. package/lib/Types/Auth.d.ts +1 -0
  364. package/lib/Types/Auth.js +1 -0
  365. package/lib/Types/Bussines.d.ts +1 -0
  366. package/lib/Types/Bussines.js +1 -0
  367. package/lib/Types/Call.d.ts +1 -0
  368. package/lib/Types/Call.js +1 -0
  369. package/lib/Types/Chat.d.ts +1 -0
  370. package/lib/Types/Chat.js +7 -0
  371. package/lib/Types/Contact.d.ts +1 -0
  372. package/lib/Types/Contact.js +1 -0
  373. package/lib/Types/Events.d.ts +1 -0
  374. package/lib/Types/Events.js +1 -0
  375. package/lib/Types/GroupMetadata.d.ts +1 -0
  376. package/lib/Types/GroupMetadata.js +1 -0
  377. package/lib/Types/Label.d.ts +2 -0
  378. package/lib/Types/Label.js +24 -0
  379. package/lib/Types/LabelAssociation.d.ts +2 -0
  380. package/lib/Types/LabelAssociation.js +6 -0
  381. package/lib/Types/Message.d.ts +11 -0
  382. package/lib/Types/Message.js +17 -0
  383. package/lib/Types/Mex.d.ts +2 -0
  384. package/lib/Types/Mex.js +38 -0
  385. package/lib/Types/Product.d.ts +1 -0
  386. package/lib/Types/Product.js +1 -0
  387. package/lib/Types/RichType.d.ts +2 -0
  388. package/lib/Types/RichType.js +22 -0
  389. package/lib/Types/Signal.d.ts +1 -0
  390. package/lib/Types/Signal.js +1 -0
  391. package/lib/Types/Socket.d.ts +1 -0
  392. package/lib/Types/Socket.js +1 -0
  393. package/lib/Types/State.d.ts +5 -0
  394. package/lib/Types/State.js +54 -0
  395. package/lib/Types/USync.d.ts +1 -0
  396. package/lib/Types/USync.js +1 -0
  397. package/lib/Types/index.d.ts +13 -0
  398. package/lib/Types/index.js +25 -0
  399. package/lib/Utils/auth-utils.d.ts +58 -0
  400. package/lib/Utils/auth-utils.js +316 -0
  401. package/lib/Utils/browser-utils.d.ts +9 -0
  402. package/lib/Utils/browser-utils.js +28 -0
  403. package/lib/Utils/business.d.ts +49 -0
  404. package/lib/Utils/business.js +230 -0
  405. package/lib/Utils/chat-utils.d.ts +408 -0
  406. package/lib/Utils/chat-utils.js +871 -0
  407. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  408. package/lib/Utils/companion-reg-client-utils.js +39 -0
  409. package/lib/Utils/crypto.d.ts +39 -0
  410. package/lib/Utils/crypto.js +117 -0
  411. package/lib/Utils/decode-wa-message.d.ts +83 -0
  412. package/lib/Utils/decode-wa-message.js +316 -0
  413. package/lib/Utils/event-buffer.d.ts +12 -0
  414. package/lib/Utils/event-buffer.js +621 -0
  415. package/lib/Utils/generics.d.ts +63 -0
  416. package/lib/Utils/generics.js +394 -0
  417. package/lib/Utils/history.d.ts +75 -0
  418. package/lib/Utils/history.js +133 -0
  419. package/lib/Utils/identity-change-handler.d.ts +13 -0
  420. package/lib/Utils/identity-change-handler.js +48 -0
  421. package/lib/Utils/index.d.ts +24 -0
  422. package/lib/Utils/index.js +24 -0
  423. package/lib/Utils/link-preview.d.ts +13 -0
  424. package/lib/Utils/link-preview.js +73 -0
  425. package/lib/Utils/logger.d.ts +12 -0
  426. package/lib/Utils/logger.js +12 -0
  427. package/lib/Utils/lt-hash.d.ts +6 -0
  428. package/lib/Utils/lt-hash.js +7 -0
  429. package/lib/Utils/make-mutex.d.ts +6 -0
  430. package/lib/Utils/make-mutex.js +32 -0
  431. package/lib/Utils/message-retry-manager.d.ts +79 -0
  432. package/lib/Utils/message-retry-manager.js +259 -0
  433. package/lib/Utils/messages-media.d.ts +134 -0
  434. package/lib/Utils/messages-media.js +802 -0
  435. package/lib/Utils/messages.d.ts +47 -0
  436. package/lib/Utils/messages.js +1907 -0
  437. package/lib/Utils/noise-handler.d.ts +20 -0
  438. package/lib/Utils/noise-handler.js +200 -0
  439. package/lib/Utils/offline-node-processor.d.ts +10 -0
  440. package/lib/Utils/offline-node-processor.js +40 -0
  441. package/lib/Utils/pre-key-manager.d.ts +25 -0
  442. package/lib/Utils/pre-key-manager.js +105 -0
  443. package/lib/Utils/process-message.d.ts +83 -0
  444. package/lib/Utils/process-message.js +748 -0
  445. package/lib/Utils/reporting-utils.d.ts +12 -0
  446. package/lib/Utils/reporting-utils.js +257 -0
  447. package/lib/Utils/rich-message-utils.d.ts +48 -0
  448. package/lib/Utils/rich-message-utils.js +366 -0
  449. package/lib/Utils/signal.d.ts +82 -0
  450. package/lib/Utils/signal.js +200 -0
  451. package/lib/Utils/stanza-ack.d.ts +16 -0
  452. package/lib/Utils/stanza-ack.js +37 -0
  453. package/lib/Utils/sync-action-utils.d.ts +2 -0
  454. package/lib/Utils/sync-action-utils.js +48 -0
  455. package/lib/Utils/tc-token-utils.d.ts +29 -0
  456. package/lib/Utils/tc-token-utils.js +163 -0
  457. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  458. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  459. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  460. package/lib/Utils/use-single-file-auth-state.js +94 -0
  461. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  462. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  463. package/lib/Utils/validate-connection.d.ts +44 -0
  464. package/lib/Utils/validate-connection.js +210 -0
  465. package/lib/WABinary/constants.d.ts +61 -0
  466. package/lib/WABinary/constants.js +1466 -0
  467. package/lib/WABinary/decode.d.ts +9 -0
  468. package/lib/WABinary/decode.js +261 -0
  469. package/lib/WABinary/encode.d.ts +2 -0
  470. package/lib/WABinary/encode.js +219 -0
  471. package/lib/WABinary/generic-utils.d.ts +79 -0
  472. package/lib/WABinary/generic-utils.js +226 -0
  473. package/lib/WABinary/index.d.ts +5 -0
  474. package/lib/WABinary/index.js +5 -0
  475. package/lib/WABinary/jid-utils.d.ts +28 -0
  476. package/lib/WABinary/jid-utils.js +95 -0
  477. package/lib/WABinary/types.d.ts +1 -0
  478. package/lib/WABinary/types.js +1 -0
  479. package/lib/WACrypto/appstate-keys.js +26 -0
  480. package/lib/WACrypto/curves/constants.js +12 -0
  481. package/lib/WACrypto/hkdf.js +27 -0
  482. package/lib/WACrypto/index.js +20 -0
  483. package/lib/WACrypto/lthash.js +54 -0
  484. package/lib/WACrypto/math/constants.js +24 -0
  485. package/lib/WACrypto/math/edwards.js +194 -0
  486. package/lib/WACrypto/math/fe.js +698 -0
  487. package/lib/WACrypto/math/le.js +23 -0
  488. package/lib/WACrypto/math/mod.js +15 -0
  489. package/lib/WACrypto/util/bytes.js +339 -0
  490. package/lib/WACrypto/x25519.js +145 -0
  491. package/lib/WACrypto/xeddsa.js +92 -0
  492. package/lib/WAM/BinaryInfo.d.ts +7 -0
  493. package/lib/WAM/BinaryInfo.js +9 -0
  494. package/lib/WAM/constants.d.ts +34926 -0
  495. package/lib/WAM/constants.js +22852 -0
  496. package/lib/WAM/encode.d.ts +1 -0
  497. package/lib/WAM/encode.js +149 -0
  498. package/lib/WAM/index.d.ts +3 -0
  499. package/lib/WAM/index.js +3 -0
  500. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  501. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  502. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  503. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  504. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  505. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  506. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  507. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  508. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  509. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  510. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  511. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  512. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  513. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  514. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  515. package/lib/WAUSync/Protocols/index.js +5 -0
  516. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  517. package/lib/WAUSync/USyncQuery.js +97 -0
  518. package/lib/WAUSync/USyncUser.d.ts +16 -0
  519. package/lib/WAUSync/USyncUser.js +30 -0
  520. package/lib/WAUSync/index.d.ts +3 -0
  521. package/lib/WAUSync/index.js +3 -0
  522. package/lib/index.d.ts +11 -0
  523. package/lib/index.js +11 -0
  524. package/package.json +74 -5
  525. package/tests/addon-test.mjs +162 -0
  526. package/tests/differential-test.mjs +90 -0
@@ -0,0 +1,1378 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { HttpError, createCache } from '../Addon/index.js';
4
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, isViewOnceMessage, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { AssociationType } from '../Types/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
9
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
10
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
11
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeNewsletterSocket } from './newsletter.js';
14
+ export const makeMessagesSocket = (config) => {
15
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
16
+ const sock = makeNewsletterSocket(config);
17
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
18
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
19
+ /**
20
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
21
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
22
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
23
+ */
24
+ const inFlightTcTokenIssuance = new Set();
25
+ const userDevicesCache = config.userDevicesCache ||
26
+ createCache({
27
+ ttl: DEFAULT_CACHE_TTLS.USER_DEVICES // 5 minutes
28
+ });
29
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
+ const devicesMutex = makeMutex();
31
+ // Initialize message retry manager if enabled
32
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
+ // Prevent race conditions in Signal session encryption by user
34
+ const encryptionMutex = makeKeyedMutex();
35
+ // Prevent race conditions in media connection refresh
36
+ const mediaConnMutex = makeKeyedMutex();
37
+ let mediaConn;
38
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
39
+ let mediaHost = DEF_MEDIA_HOST;
40
+ const refreshMediaConn = async (forceGet = false) => {
41
+ return mediaConnMutex.mutex('media-conn', async () => {
42
+ const media = await mediaConn;
43
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
44
+ mediaConn = (async () => {
45
+ const result = await query({
46
+ tag: 'iq',
47
+ attrs: {
48
+ type: 'set',
49
+ xmlns: 'w:m',
50
+ to: S_WHATSAPP_NET
51
+ },
52
+ content: [{ tag: 'media_conn', attrs: {} }]
53
+ });
54
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
55
+ // TODO: explore full length of data that whatsapp provides
56
+ const node = {
57
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
58
+ hostname: attrs.hostname,
59
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
60
+ })),
61
+ auth: mediaConnNode.attrs.auth,
62
+ ttl: +mediaConnNode.attrs.ttl,
63
+ fetchDate: new Date
64
+ };
65
+ logger.debug('fetched media conn');
66
+ if (node.hosts[0]) {
67
+ mediaHost = node.hosts[0].hostname;
68
+ }
69
+ return node;
70
+ })();
71
+ }
72
+ return mediaConn;
73
+ });
74
+ };
75
+ /**
76
+ * generic send receipt function
77
+ * used for receipts of phone call, read, delivery etc.
78
+ * */
79
+ const sendReceipt = async (jid, participant, messageIds, type) => {
80
+ if (!messageIds || messageIds.length === 0) {
81
+ throw new HttpError('missing ids in receipt');
82
+ }
83
+ const node = {
84
+ tag: 'receipt',
85
+ attrs: {
86
+ id: messageIds[0]
87
+ }
88
+ };
89
+ const isReadReceipt = type === 'read' || type === 'read-self';
90
+ if (isReadReceipt) {
91
+ node.attrs.t = unixTimestampSeconds().toString();
92
+ }
93
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
94
+ node.attrs.recipient = jid;
95
+ node.attrs.to = participant;
96
+ }
97
+ else {
98
+ node.attrs.to = jid;
99
+ if (participant) {
100
+ node.attrs.participant = participant;
101
+ }
102
+ }
103
+ if (type) {
104
+ node.attrs.type = type;
105
+ }
106
+ const remainingMessageIds = messageIds.slice(1);
107
+ if (remainingMessageIds.length) {
108
+ node.content = [
109
+ {
110
+ tag: 'list',
111
+ attrs: {},
112
+ content: remainingMessageIds.map(id => ({
113
+ tag: 'item',
114
+ attrs: { id }
115
+ }))
116
+ }
117
+ ];
118
+ }
119
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
120
+ await sendNode(node);
121
+ };
122
+ /** Correctly bulk send receipts to multiple chats, participants */
123
+ const sendReceipts = async (keys, type) => {
124
+ const recps = aggregateMessageKeysNotFromMe(keys);
125
+ for (const { jid, participant, messageIds } of recps) {
126
+ await sendReceipt(jid, participant, messageIds, type);
127
+ }
128
+ };
129
+ /** Bulk read messages. Keys can be from different chats & participants */
130
+ const readMessages = async (keys) => {
131
+ const privacySettings = await fetchPrivacySettings();
132
+ // based on privacy settings, we have to change the read type
133
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
134
+ await sendReceipts(keys, readType);
135
+ };
136
+ /** Fetch all the devices we've to send a message to */
137
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
138
+ const deviceResults = [];
139
+ if (!useCache) {
140
+ logger.debug('not using cache for devices');
141
+ }
142
+ const toFetch = [];
143
+ const jidsWithUser = jids
144
+ .map(jid => {
145
+ const decoded = jidDecode(jid);
146
+ const user = decoded?.user;
147
+ const device = decoded?.device;
148
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
149
+ if (isExplicitDevice && user) {
150
+ deviceResults.push({
151
+ user,
152
+ device,
153
+ jid
154
+ });
155
+ return null;
156
+ }
157
+ jid = jidNormalizedUser(jid);
158
+ return { jid, user };
159
+ })
160
+ .filter(jid => jid !== null);
161
+ let mgetDevices;
162
+ if (useCache && userDevicesCache.mget) {
163
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
164
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
165
+ }
166
+ for (const { jid, user } of jidsWithUser) {
167
+ if (useCache) {
168
+ const devices = mgetDevices?.[user] ||
169
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
170
+ if (devices) {
171
+ const devicesWithJid = devices.map(d => ({
172
+ ...d,
173
+ jid: jidEncode(d.user, d.server, d.device)
174
+ }));
175
+ deviceResults.push(...devicesWithJid);
176
+ logger.trace({ user }, 'using cache for devices');
177
+ }
178
+ else {
179
+ toFetch.push(jid);
180
+ }
181
+ }
182
+ else {
183
+ toFetch.push(jid);
184
+ }
185
+ }
186
+ if (!toFetch.length) {
187
+ return deviceResults;
188
+ }
189
+ const requestedLidUsers = new Set();
190
+ for (const jid of toFetch) {
191
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
192
+ const user = jidDecode(jid)?.user;
193
+ if (user)
194
+ requestedLidUsers.add(user);
195
+ }
196
+ }
197
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
198
+ for (const jid of toFetch) {
199
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
200
+ }
201
+ const result = await sock.executeUSyncQuery(query);
202
+ if (result) {
203
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
204
+ const lidResults = result.list.filter(a => !!a.lid);
205
+ if (lidResults.length > 0) {
206
+ logger.trace('Storing LID maps from device call');
207
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
208
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
209
+ try {
210
+ const lids = lidResults.map(a => a.lid);
211
+ if (lids.length) {
212
+ await assertSessions(lids, true);
213
+ }
214
+ }
215
+ catch (e) {
216
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
217
+ }
218
+ }
219
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
220
+ const deviceMap = {};
221
+ for (const item of extracted) {
222
+ deviceMap[item.user] = deviceMap[item.user] || [];
223
+ deviceMap[item.user]?.push(item);
224
+ }
225
+ // Process each user's devices as a group for bulk LID migration
226
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
227
+ const isLidUser = requestedLidUsers.has(user);
228
+ // Process all devices for this user
229
+ for (const item of userDevices) {
230
+ const finalJid = isLidUser
231
+ ? jidEncode(user, item.server, item.device)
232
+ : jidEncode(item.user, item.server, item.device);
233
+ deviceResults.push({
234
+ ...item,
235
+ jid: finalJid
236
+ });
237
+ logger.debug({
238
+ user: item.user,
239
+ device: item.device,
240
+ finalJid,
241
+ usedLid: isLidUser
242
+ }, 'Processed device with LID priority');
243
+ }
244
+ }
245
+ await devicesMutex.mutex(async () => {
246
+ if (userDevicesCache.mset) {
247
+ // if the cache supports mset, we can set all devices in one go
248
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
249
+ }
250
+ else {
251
+ for (const key in deviceMap) {
252
+ if (deviceMap[key])
253
+ await userDevicesCache.set(key, deviceMap[key]);
254
+ }
255
+ }
256
+ });
257
+ const userDeviceUpdates = {};
258
+ for (const [userId, devices] of Object.entries(deviceMap)) {
259
+ if (devices && devices.length > 0) {
260
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
261
+ }
262
+ }
263
+ if (Object.keys(userDeviceUpdates).length > 0) {
264
+ try {
265
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
266
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
267
+ }
268
+ catch (error) {
269
+ logger.warn({ error }, 'failed to store user device lists');
270
+ }
271
+ }
272
+ }
273
+ return deviceResults;
274
+ };
275
+ /**
276
+ * Update Member Label
277
+ */
278
+ const updateMemberLabel = (jid, memberLabel) => {
279
+ return relayMessage(jid, {
280
+ protocolMessage: {
281
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
282
+ memberLabel: {
283
+ label: memberLabel?.slice(0, 30),
284
+ labelTimestamp: unixTimestampSeconds
285
+ }
286
+ }
287
+ }, {
288
+ additionalNodes: [
289
+ {
290
+ tag: 'meta',
291
+ attrs: {
292
+ tag_reason: 'user_update',
293
+ appdata: 'member_tag'
294
+ },
295
+ content: undefined
296
+ }
297
+ ]
298
+ });
299
+ };
300
+ const assertSessions = async (jids, force) => {
301
+ let didFetchNewSession = false;
302
+ const uniqueJids = [...new Set(jids)];
303
+ const jidsRequiringFetch = [];
304
+ logger.debug({ jids }, 'assertSessions call with jids');
305
+ for (const jid of uniqueJids) {
306
+ if (!force) {
307
+ const sessionValidation = await signalRepository.validateSession(jid);
308
+ if (sessionValidation.exists) {
309
+ continue;
310
+ }
311
+ }
312
+ jidsRequiringFetch.push(jid);
313
+ }
314
+ if (jidsRequiringFetch.length) {
315
+ // LID if mapped, otherwise original
316
+ const wireJids = [
317
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
318
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
319
+ ];
320
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
321
+ const result = await query({
322
+ tag: 'iq',
323
+ attrs: {
324
+ xmlns: 'encrypt',
325
+ type: 'get',
326
+ to: S_WHATSAPP_NET
327
+ },
328
+ content: [
329
+ {
330
+ tag: 'key',
331
+ attrs: {},
332
+ content: wireJids.map(jid => {
333
+ const attrs = { jid };
334
+ if (force)
335
+ attrs.reason = 'identity';
336
+ return { tag: 'user', attrs };
337
+ })
338
+ }
339
+ ]
340
+ });
341
+ await parseAndInjectE2ESessions(result, signalRepository);
342
+ didFetchNewSession = true;
343
+ }
344
+ return didFetchNewSession;
345
+ };
346
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
347
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
348
+ if (!authState.creds.me?.id) {
349
+ throw new HttpError('Not authenticated');
350
+ }
351
+ const protocolMessage = {
352
+ protocolMessage: {
353
+ peerDataOperationRequestMessage: pdoMessage,
354
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
355
+ }
356
+ };
357
+ const meJid = jidNormalizedUser(authState.creds.me.id);
358
+ const msgId = await relayMessage(meJid, protocolMessage, {
359
+ additionalAttributes: {
360
+ category: 'peer',
361
+ push_priority: 'high_force'
362
+ },
363
+ additionalNodes: [
364
+ {
365
+ tag: 'meta',
366
+ attrs: { appdata: 'default' }
367
+ }
368
+ ]
369
+ });
370
+ return msgId;
371
+ };
372
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
373
+ if (!recipientJids.length) {
374
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
375
+ }
376
+ const patched = await patchMessageBeforeSending(message, recipientJids);
377
+ const patchedMessages = Array.isArray(patched)
378
+ ? patched
379
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
380
+ let shouldIncludeDeviceIdentity = false;
381
+ const meId = authState.creds.me.id;
382
+ const meLid = authState.creds.me?.lid;
383
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
384
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
385
+ try {
386
+ if (!jid)
387
+ return null;
388
+ let msgToEncrypt = patchedMessage;
389
+ if (dsmMessage) {
390
+ const { user: targetUser } = jidDecode(jid);
391
+ const { user: ownPnUser } = jidDecode(meId);
392
+ const ownLidUser = meLidUser;
393
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
394
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
395
+ if (isOwnUser && !isExactSenderDevice) {
396
+ msgToEncrypt = dsmMessage;
397
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
398
+ }
399
+ }
400
+ const bytes = encodeWAMessage(msgToEncrypt);
401
+ const mutexKey = jid;
402
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
403
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
404
+ if (type === 'pkmsg') {
405
+ shouldIncludeDeviceIdentity = true;
406
+ }
407
+ return {
408
+ tag: 'to',
409
+ attrs: { jid },
410
+ content: [
411
+ {
412
+ tag: 'enc',
413
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
414
+ content: ciphertext
415
+ }
416
+ ]
417
+ };
418
+ });
419
+ return node;
420
+ }
421
+ catch (err) {
422
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
423
+ return null;
424
+ }
425
+ });
426
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
427
+ if (recipientJids.length > 0 && nodes.length === 0) {
428
+ throw new HttpError('All encryptions failed', { statusCode: 500 });
429
+ }
430
+ return { nodes, shouldIncludeDeviceIdentity };
431
+ };
432
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList } = {}) => {
433
+ const meId = assertMeId(authState.creds);
434
+ const meLid = authState.creds.me?.lid;
435
+ const isRetryResend = Boolean(participant?.jid);
436
+ let shouldIncludeDeviceIdentity = isRetryResend;
437
+ const statusJid = 'status@broadcast';
438
+ const { user, server } = jidDecode(jid);
439
+ const isGroup = server === 'g.us';
440
+ const isStatus = jid === statusJid;
441
+ const isLid = server === 'lid';
442
+ const isNewsletter = server === 'newsletter';
443
+ const isGroupOrStatus = isGroup || isStatus;
444
+ const finalJid = jid;
445
+ msgId = msgId || generateMessageIDV2(meId);
446
+ useUserDevicesCache = useUserDevicesCache !== false;
447
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
448
+ const participants = [];
449
+ const destinationJid = !isStatus ? finalJid : statusJid;
450
+ const binaryNodeContent = [];
451
+ const devices = [];
452
+ let reportingMessage;
453
+ const meMsg = {
454
+ deviceSentMessage: {
455
+ destinationJid,
456
+ message
457
+ },
458
+ messageContextInfo: message.messageContextInfo
459
+ };
460
+ const extraAttrs = {};
461
+ if (participant) {
462
+ // Prevent double encryption by excluding retry resends from regular fan-out (479).
463
+ if (participant && !isGroup && !isStatus) {
464
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
465
+ }
466
+ }
467
+ await authState.keys.transaction(async () => {
468
+ // Normalize message first to extract the original message and valid media type
469
+ const innerMessage = normalizeMessageContent(message);
470
+ const mediaType = getMediaType(innerMessage);
471
+ if (mediaType) {
472
+ extraAttrs['mediatype'] = mediaType;
473
+ }
474
+ if (isNewsletter) {
475
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
476
+ const bytes = encodeNewsletterMessage(patched);
477
+ // Add "additionalNodes" for newsletter too (⁠っ⁠˘̩⁠╭⁠╮⁠˘̩⁠)⁠っ
478
+ if (additionalNodes && additionalNodes.length > 0) {
479
+ ;
480
+ binaryNodeContent.push(...additionalNodes);
481
+ }
482
+ binaryNodeContent.push({
483
+ tag: 'plaintext',
484
+ attrs: extraAttrs, // Add extraAttrs to fix media being rejected when sending to newsletter (⁠◠⁠‿⁠◕⁠)
485
+ content: bytes
486
+ });
487
+ const stanza = {
488
+ tag: 'message',
489
+ attrs: {
490
+ to: jid,
491
+ id: msgId,
492
+ type: getMessageType(innerMessage),
493
+ ...(additionalAttributes || {})
494
+ },
495
+ content: binaryNodeContent
496
+ };
497
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
498
+ await sendNode(stanza);
499
+ return;
500
+ }
501
+ // Add keepInChat, editedMessage, mediaNotifyMessage and pollUpdateMessage
502
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
503
+ // Add groupStatusMessage attributes
504
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
505
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
506
+ const isViewOnce = isViewOnceMessage(message);
507
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate || isViewOnce) {
508
+ const metaAttrs = {};
509
+ if (isNeedMetaAttrs) {
510
+ metaAttrs.content_type = 'add_on';
511
+ }
512
+ if (isPollUpdate && !isGroupStatus) {
513
+ metaAttrs.polltype = 'vote';
514
+ }
515
+ if (isGroupStatus) {
516
+ metaAttrs.is_group_status = 'true';
517
+ }
518
+ if (isViewOnce) {
519
+ metaAttrs.view_once = 'true';
520
+ }
521
+ binaryNodeContent.push({
522
+ tag: 'meta',
523
+ attrs: metaAttrs,
524
+ content: undefined
525
+ });
526
+ }
527
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
528
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
529
+ }
530
+ // Add native_flow_name to extraAttrs when sending interactiveResponseMessage
531
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
532
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
533
+ }
534
+ if (isGroupOrStatus && !isRetryResend) {
535
+ const [groupData, senderKeyMap] = await Promise.all([
536
+ (async () => {
537
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
538
+ if (groupData && Array.isArray(groupData?.participants)) {
539
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
540
+ }
541
+ else if (!isStatus) {
542
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
543
+ }
544
+ return groupData;
545
+ })(),
546
+ (async () => {
547
+ if (!participant && !isStatus) {
548
+ // what if sender memory is less accurate than the cached metadata
549
+ // on participant change in group, we should do sender memory manipulation
550
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
551
+ return result[jid] || {};
552
+ }
553
+ return {};
554
+ })
555
+ ]);
556
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
557
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
558
+ additionalAttributes = {
559
+ ...additionalAttributes,
560
+ expiration: groupData.ephemeralDuration.toString
561
+ };
562
+ }
563
+ if (isStatus && statusJidList) {
564
+ participantsList.push(...statusJidList);
565
+ }
566
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
567
+ devices.push(...additionalDevices);
568
+ if (isGroup) {
569
+ additionalAttributes = {
570
+ ...additionalAttributes,
571
+ addressing_mode: groupData?.addressingMode || 'lid'
572
+ };
573
+ }
574
+ const patched = await patchMessageBeforeSending(message);
575
+ if (Array.isArray(patched)) {
576
+ throw new HttpError('Per-jid patching is not supported in groups');
577
+ }
578
+ const bytes = encodeWAMessage(patched);
579
+ reportingMessage = patched;
580
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
581
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
582
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
583
+ group: destinationJid,
584
+ data: bytes,
585
+ meId: groupSenderIdentity
586
+ });
587
+ const senderKeyRecipients = [];
588
+ for (const device of devices) {
589
+ const deviceJid = device.jid;
590
+ const hasKey = !!senderKeyMap[deviceJid];
591
+ if ((!hasKey || !!participant) &&
592
+ !isHostedLidUser(deviceJid) &&
593
+ !isHostedPnUser(deviceJid) &&
594
+ device.device !== 99) {
595
+ //todo: revamp all this logic
596
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
597
+ senderKeyRecipients.push(deviceJid);
598
+ }
599
+ }
600
+ if (senderKeyRecipients.length) {
601
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
602
+ const senderKeyMsg = {
603
+ senderKeyDistributionMessage: {
604
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
605
+ groupId: destinationJid
606
+ }
607
+ };
608
+ const senderKeySessionTargets = senderKeyRecipients;
609
+ await assertSessions(senderKeySessionTargets);
610
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
611
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
612
+ participants.push(...result.nodes);
613
+ // A prepared SKDM is tracked per device, failed encryptions must be retried on the next send.
614
+ for (const { attrs } of result.nodes) {
615
+ if (attrs.jid) {
616
+ senderKeyMap[attrs.jid] = true;
617
+ }
618
+ }
619
+ }
620
+ binaryNodeContent.push({
621
+ tag: 'enc',
622
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
623
+ content: ciphertext
624
+ });
625
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
626
+ }
627
+ else {
628
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
629
+ // TODO: investigate if this is true
630
+ let ownId = meId;
631
+ if (isLid && meLid) {
632
+ ownId = meLid;
633
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
634
+ }
635
+ else {
636
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
637
+ }
638
+ const { user: ownUser } = jidDecode(ownId);
639
+ if (!participant) {
640
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
641
+ reportingMessage = Array.isArray(patchedForReporting)
642
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
643
+ : patchedForReporting;
644
+ }
645
+ if (!isRetryResend) {
646
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
647
+ devices.push({
648
+ user,
649
+ device: 0,
650
+ jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
651
+ });
652
+ if (user !== ownUser) {
653
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
654
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
655
+ devices.push({
656
+ user: ownUserForAddressing,
657
+ device: 0,
658
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
659
+ });
660
+ }
661
+ if (additionalAttributes?.['category'] !== 'peer') {
662
+ // Clear placeholders and enumerate actual devices
663
+ devices.length = 0;
664
+ // Use conversation-appropriate sender identity
665
+ const senderIdentity = isLid && meLid
666
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
667
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
668
+ // Enumerate devices for sender and target with consistent addressing
669
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
670
+ devices.push(...sessionDevices);
671
+ logger.debug({
672
+ deviceCount: devices.length,
673
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
674
+ }, 'Device enumeration complete with unified addressing');
675
+ }
676
+ }
677
+ const allRecipients = [];
678
+ const meRecipients = [];
679
+ const otherRecipients = [];
680
+ const { user: mePnUser } = jidDecode(meId);
681
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
682
+ for (const { user, jid } of devices) {
683
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
684
+ if (isExactSenderDevice) {
685
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
686
+ continue;
687
+ }
688
+ // Check if this is our device (could match either PN or LID user)
689
+ const isMe = user === mePnUser || user === meLidUser;
690
+ if (isMe) {
691
+ meRecipients.push(jid);
692
+ }
693
+ else {
694
+ otherRecipients.push(jid);
695
+ }
696
+ allRecipients.push(jid);
697
+ }
698
+ await assertSessions(allRecipients);
699
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
700
+ // For own devices: use DSM if available (1:1 chats only)
701
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
702
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
703
+ ]);
704
+ participants.push(...meNodes);
705
+ participants.push(...otherNodes);
706
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
707
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
708
+ }
709
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
710
+ }
711
+ if (isRetryResend) {
712
+ const isParticipantLid = isLidUser(participant.jid);
713
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
714
+ let messageToSend = message;
715
+ if (isGroupOrStatus) {
716
+ let groupSenderIdentity;
717
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
718
+ groupSenderIdentity = meLid;
719
+ }
720
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
721
+ groupSenderIdentity = meId;
722
+ }
723
+ if (groupSenderIdentity) {
724
+ try {
725
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
726
+ group: destinationJid,
727
+ meId: groupSenderIdentity
728
+ });
729
+ messageToSend = {
730
+ ...message,
731
+ senderKeyDistributionMessage: {
732
+ groupId: destinationJid,
733
+ axolotlSenderKeyDistributionMessage: skdm
734
+ }
735
+ };
736
+ }
737
+ catch (err) {
738
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
739
+ }
740
+ }
741
+ }
742
+ const encodedMessageToSend = isMe
743
+ ? encodeWAMessage({
744
+ deviceSentMessage: {
745
+ destinationJid,
746
+ message: messageToSend
747
+ }
748
+ })
749
+ : encodeWAMessage(messageToSend);
750
+ await assertSessions([participant.jid]);
751
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
752
+ data: encodedMessageToSend,
753
+ jid: participant.jid
754
+ });
755
+ binaryNodeContent.push({
756
+ tag: 'enc',
757
+ attrs: {
758
+ v: '2',
759
+ type,
760
+ count: (participant.count || 0).toString
761
+ },
762
+ content: encryptedContent
763
+ });
764
+ }
765
+ if (participants.length) {
766
+ if (additionalAttributes?.['category'] === 'peer') {
767
+ const peerNode = participants[0]?.content?.[0];
768
+ if (peerNode) {
769
+ binaryNodeContent.push(peerNode); // push only enc
770
+ }
771
+ }
772
+ else {
773
+ binaryNodeContent.push({
774
+ tag: 'participants',
775
+ attrs: {},
776
+ content: participants
777
+ });
778
+ }
779
+ }
780
+ const stanza = {
781
+ tag: 'message',
782
+ attrs: {
783
+ id: msgId,
784
+ to: destinationJid,
785
+ type: getMessageType(innerMessage),
786
+ ...(additionalAttributes || {})
787
+ },
788
+ content: binaryNodeContent
789
+ };
790
+ // if the participant to send to is explicitly specified (generally retry recp)
791
+ // ensure the message is only sent to that person
792
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
793
+ if (participant) {
794
+ if (isJidGroup(destinationJid)) {
795
+ stanza.attrs.to = destinationJid;
796
+ stanza.attrs.participant = participant.jid;
797
+ }
798
+ else if (areJidsSameUser(participant.jid, meId)) {
799
+ stanza.attrs.to = participant.jid;
800
+ stanza.attrs.recipient = destinationJid;
801
+ }
802
+ else {
803
+ stanza.attrs.to = participant.jid;
804
+ }
805
+ }
806
+ else {
807
+ stanza.attrs.to = destinationJid;
808
+ }
809
+ if (shouldIncludeDeviceIdentity) {
810
+ ;
811
+ stanza.content.push({
812
+ tag: 'device-identity',
813
+ attrs: {},
814
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
815
+ });
816
+ logger.debug({ jid }, 'adding device identity');
817
+ }
818
+ if (!isNewsletter &&
819
+ !isRetryResend &&
820
+ reportingMessage?.messageContextInfo?.messageSecret &&
821
+ shouldIncludeReportingToken(reportingMessage)) {
822
+ try {
823
+ const encoded = encodeWAMessage(reportingMessage);
824
+ const reportingKey = {
825
+ id: msgId,
826
+ fromMe: true,
827
+ remoteJid: destinationJid,
828
+ participant: participant?.jid
829
+ };
830
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
831
+ if (reportingNode) {
832
+ ;
833
+ stanza.content.push(reportingNode);
834
+ logger.trace({ jid }, 'added reporting token to message');
835
+ }
836
+ }
837
+ catch (error) {
838
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
839
+ }
840
+ }
841
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
842
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
843
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
844
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
845
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
846
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
847
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
848
+ let tcTokenBuffer = existingTokenEntry?.token;
849
+ // Treat expired tokens the same as missing — clear from cache
850
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
851
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
852
+ tcTokenBuffer = undefined;
853
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
854
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
855
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
856
+ : null;
857
+ try {
858
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
859
+ }
860
+ catch (err) {
861
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
862
+ }
863
+ }
864
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
865
+ ;
866
+ stanza.content.push({
867
+ tag: 'tctoken',
868
+ attrs: {},
869
+ content: tcTokenBuffer
870
+ });
871
+ }
872
+ let alreadyHasBizNode = false;
873
+ if (additionalNodes && additionalNodes.length > 0) {
874
+ ;
875
+ stanza.content.push(...additionalNodes);
876
+ alreadyHasBizNode = !addBizAttributes &&
877
+ additionalNodes.some(node => node.tag === 'biz');
878
+ }
879
+ // Add Biz Binary Node to support button messages
880
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
881
+ const bizNode = getBizBinaryNode(innerMessage);
882
+ stanza.content.push(bizNode);
883
+ }
884
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
885
+ await sendNode(stanza);
886
+ // Fire-and-forget: issue our token to the contact AFTER message send.
887
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
888
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
889
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
890
+ if (is1on1Send &&
891
+ !isProtocolMsg &&
892
+ !isBotOrPSA &&
893
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
894
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
895
+ inFlightTcTokenIssuance.add(tcTokenJid);
896
+ const issueTimestamp = unixTimestampSeconds();
897
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
898
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
899
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
900
+ .then(async (result) => {
901
+ await storeTcTokensFromIqResult({
902
+ result,
903
+ fallbackJid: tcTokenJid,
904
+ keys: authState.keys,
905
+ getLIDForPN
906
+ });
907
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
908
+ const currentEntry = currentData[tcTokenJid];
909
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
910
+ await authState.keys.set({
911
+ tctoken: {
912
+ [tcTokenJid]: {
913
+ token: Buffer.alloc(0),
914
+ ...currentEntry,
915
+ senderTimestamp: issueTimestamp
916
+ },
917
+ ...indexWrite
918
+ }
919
+ });
920
+ })
921
+ .catch(err => {
922
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
923
+ })
924
+ .finally(() => {
925
+ inFlightTcTokenIssuance.delete(tcTokenJid);
926
+ });
927
+ }
928
+ // Add message to retry cache if enabled
929
+ if (messageRetryManager && !participant) {
930
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
931
+ }
932
+ }, meId);
933
+ return msgId;
934
+ };
935
+ const getMessageType = (message) => {
936
+ if (!message)
937
+ return 'text';
938
+ if (message.reactionMessage || message.encReactionMessage) {
939
+ return 'reaction';
940
+ }
941
+ if (message.pollCreationMessage ||
942
+ message.pollCreationMessageV2 ||
943
+ message.pollCreationMessageV3 ||
944
+ message.pollCreationMessageV5 ||
945
+ message.pollCreationMessageV6 ||
946
+ message.pollUpdateMessage) {
947
+ return 'poll';
948
+ }
949
+ if (message.eventMessage) {
950
+ return 'event';
951
+ }
952
+ if (getMediaType(message) !== '') {
953
+ return 'media';
954
+ }
955
+ return 'text';
956
+ };
957
+ const getMediaType = (message) => {
958
+ if (message.imageMessage) {
959
+ return 'image';
960
+ }
961
+ else if (message.videoMessage) {
962
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
963
+ }
964
+ else if (message.stickerMessage) {
965
+ const sticker = message.stickerMessage;
966
+ if (sticker.isLottie)
967
+ return '1p_sticker';
968
+ if (sticker.isAvatar)
969
+ return 'avatar_sticker';
970
+ if (sticker.isAiSticker)
971
+ return 'genai_sticker';
972
+ return 'sticker';
973
+ }
974
+ else if (message.audioMessage) {
975
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
976
+ }
977
+ else if (message.albumMessage) {
978
+ return 'collection';
979
+ }
980
+ else if (message.contactMessage) {
981
+ return 'vcard';
982
+ }
983
+ else if (message.documentMessage) {
984
+ return 'document';
985
+ }
986
+ else if (message.contactsArrayMessage) {
987
+ return 'contact_array';
988
+ }
989
+ else if (message.liveLocationMessage) {
990
+ return 'livelocation';
991
+ }
992
+ else if (message.stickerPackMessage) {
993
+ return 'sticker_pack';
994
+ }
995
+ else if (message.listMessage) {
996
+ return 'list';
997
+ }
998
+ else if (message.listResponseMessage) {
999
+ return 'list_response';
1000
+ }
1001
+ else if (message.buttonsResponseMessage) {
1002
+ return 'buttons_response';
1003
+ }
1004
+ else if (message.orderMessage) {
1005
+ return 'order';
1006
+ }
1007
+ else if (message.productMessage) {
1008
+ return 'product';
1009
+ }
1010
+ else if (message.interactiveResponseMessage) {
1011
+ return 'native_flow_response';
1012
+ }
1013
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1014
+ return 'url';
1015
+ }
1016
+ // Add more message type here
1017
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1018
+ return 'cataloglink';
1019
+ }
1020
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1021
+ return 'productlink';
1022
+ }
1023
+ return '';
1024
+ };
1025
+ const issuePrivacyTokens = async (jids, timestamp) => {
1026
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1027
+ const result = await query({
1028
+ tag: 'iq',
1029
+ attrs: {
1030
+ to: S_WHATSAPP_NET,
1031
+ type: 'set',
1032
+ xmlns: 'privacy'
1033
+ },
1034
+ content: [
1035
+ {
1036
+ tag: 'tokens',
1037
+ attrs: {},
1038
+ content: jids.map(jid => ({
1039
+ tag: 'token',
1040
+ attrs: {
1041
+ jid: jidNormalizedUser(jid),
1042
+ t,
1043
+ type: 'trusted_contact'
1044
+ }
1045
+ }))
1046
+ }
1047
+ ]
1048
+ });
1049
+ return result;
1050
+ };
1051
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1052
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1053
+ registerSocketEndHandler(() => {
1054
+ if (!config.userDevicesCache && userDevicesCache.close) {
1055
+ userDevicesCache.close();
1056
+ }
1057
+ mediaConn = undefined;
1058
+ if (messageRetryManager) {
1059
+ messageRetryManager.flushAll();
1060
+ }
1061
+ });
1062
+ return {
1063
+ ...sock,
1064
+ userDevicesCache,
1065
+ devicesMutex,
1066
+ issuePrivacyTokens,
1067
+ assertSessions,
1068
+ relayMessage,
1069
+ sendReceipt,
1070
+ sendReceipts,
1071
+ readMessages,
1072
+ refreshMediaConn,
1073
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1074
+ getMediaHost: () => mediaHost,
1075
+ waUploadToServer,
1076
+ fetchPrivacySettings,
1077
+ sendPeerDataOperationMessage,
1078
+ createParticipantNodes,
1079
+ getUSyncDevices,
1080
+ messageRetryManager,
1081
+ updateMemberLabel,
1082
+ updateMediaMessage: async (message) => {
1083
+ const content = assertMediaContent(message.message);
1084
+ const mediaKey = content.mediaKey;
1085
+ const meId = authState.creds.me.id;
1086
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1087
+ let error = undefined;
1088
+ await Promise.all([
1089
+ sendNode(node),
1090
+ waitForMsgMediaUpdate(async (update) => {
1091
+ const result = update.find(c => c.key.id === message.key.id);
1092
+ if (result) {
1093
+ if (result.error) {
1094
+ error = result.error;
1095
+ }
1096
+ else {
1097
+ try {
1098
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1099
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1100
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1101
+ throw new HttpError(`Media re-upload failed by device (${resultStr})`, {
1102
+ data: media,
1103
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1104
+ });
1105
+ }
1106
+ content.directPath = media.directPath;
1107
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1108
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1109
+ }
1110
+ catch (err) {
1111
+ error = err;
1112
+ }
1113
+ }
1114
+ return true;
1115
+ }
1116
+ })
1117
+ ]);
1118
+ if (error) {
1119
+ throw error;
1120
+ }
1121
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1122
+ return message;
1123
+ },
1124
+ // Add support for modifying additionalNodes and additionalAttributes using "options" in sendMessage
1125
+ sendMessage: async (jid, content, options = {}) => {
1126
+ var _a;
1127
+ const userJid = authState.creds.me.id;
1128
+ // Add status mentions!
1129
+ if (Array.isArray(jid)) {
1130
+ const { delayMs = 1500 } = options;
1131
+ const allUsers = new Set();
1132
+ const fullMsg = await generateWAMessage('status@broadcast', content, {
1133
+ logger,
1134
+ userJid,
1135
+ upload: waUploadToServer,
1136
+ mediaCache: config.mediaCache,
1137
+ options: config.options,
1138
+ ...options,
1139
+ messageId: generateMessageIDV2(userJid)
1140
+ });
1141
+ for (const id of jid) {
1142
+ if (isJidGroup(id)) {
1143
+ try {
1144
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1145
+ for (const participant of groupData.participants) {
1146
+ if (allUsers.has(participant.id))
1147
+ continue;
1148
+ allUsers.add(participant.id);
1149
+ }
1150
+ }
1151
+ catch (error) {
1152
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1153
+ }
1154
+ }
1155
+ else if (!allUsers.has(id)) {
1156
+ allUsers.add(id);
1157
+ }
1158
+ }
1159
+ await relayMessage('status@broadcast', fullMsg.message, {
1160
+ messageId: fullMsg.key.id,
1161
+ statusJidList: Array.from(allUsers),
1162
+ additionalNodes: [
1163
+ {
1164
+ tag: 'meta',
1165
+ attrs: {},
1166
+ content: [
1167
+ {
1168
+ tag: 'mentioned_users',
1169
+ attrs: {},
1170
+ content: jid.map(id => ({
1171
+ tag: 'to',
1172
+ attrs: { jid: id },
1173
+ content: undefined
1174
+ }))
1175
+ }
1176
+ ]
1177
+ }
1178
+ ]
1179
+ });
1180
+ if (config.emitOwnEvents) {
1181
+ process.nextTick(async () => {
1182
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1183
+ });
1184
+ }
1185
+ for (const id of jid) {
1186
+ const isGroup = isJidGroup(id);
1187
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1188
+ const mentionMsg = generateWAMessageFromContent(id, {
1189
+ messageContextInfo: {
1190
+ messageSecret: randomBytes(32)
1191
+ },
1192
+ [sendType]: {
1193
+ message: {
1194
+ protocolMessage: {
1195
+ key: fullMsg.key,
1196
+ type: 25
1197
+ }
1198
+ }
1199
+ }
1200
+ }, {
1201
+ userJid
1202
+ });
1203
+ await relayMessage(id, mentionMsg.message, {
1204
+ additionalNodes: [
1205
+ {
1206
+ tag: 'meta',
1207
+ attrs: isGroup ?
1208
+ { is_group_status_mention: 'true' } :
1209
+ { is_status_mention: 'true' },
1210
+ content: undefined
1211
+ }
1212
+ ]
1213
+ });
1214
+ if (config.emitOwnEvents) {
1215
+ process.nextTick(async () => {
1216
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1217
+ });
1218
+ }
1219
+ await delay(delayMs);
1220
+ }
1221
+ return fullMsg;
1222
+ }
1223
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1224
+ const { disappearingMessagesInChat } = content;
1225
+ const value = typeof disappearingMessagesInChat === 'boolean'
1226
+ ? disappearingMessagesInChat
1227
+ ? WA_DEFAULT_EPHEMERAL
1228
+ : 0
1229
+ : disappearingMessagesInChat;
1230
+ await groupToggleEphemeral(jid, value);
1231
+ }
1232
+ else {
1233
+ const fullMsg = await generateWAMessage(jid, content, {
1234
+ logger,
1235
+ userJid,
1236
+ getUrlInfo: text => getUrlInfo(text, {
1237
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1238
+ fetchOpts: {
1239
+ timeout: 3000,
1240
+ ...(httpRequestOptions || {})
1241
+ },
1242
+ logger,
1243
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1244
+ }),
1245
+ //TODO: CACHE
1246
+ getProfilePicUrl: sock.profilePictureUrl,
1247
+ getCallLink: sock.createCallLink,
1248
+ upload: waUploadToServer,
1249
+ mediaCache: config.mediaCache,
1250
+ options: config.options,
1251
+ ...options,
1252
+ messageId: generateMessageIDV2(userJid)
1253
+ });
1254
+ const isNewsletter = isJidNewsletter(jid);
1255
+ const isEventMsg = 'event' in content && !!content.event;
1256
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1257
+ const isEditMsg = 'edit' in content && !!content.edit;
1258
+ const isPinMsg = 'pin' in content && !!content.pin;
1259
+ const isKeepMsg = 'keep' in content && !!content.keep;
1260
+ const isPollMsg = 'poll' in content && !!content.poll;
1261
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
1262
+ const isAiMsg = 'ai' in content && !!content.ai;
1263
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
1264
+ const additionalAttributes = options.additionalAttributes || {};
1265
+ const additionalNodes = options.additionalNodes || [];
1266
+ // required for delete
1267
+ if (isDeleteMsg || isKeepMsg) {
1268
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1269
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1270
+ additionalAttributes.edit = '8';
1271
+ }
1272
+ else {
1273
+ additionalAttributes.edit = '7';
1274
+ }
1275
+ }
1276
+ else if (isEditMsg) {
1277
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1278
+ }
1279
+ else if (isPinMsg) {
1280
+ additionalAttributes.edit = '2';
1281
+ }
1282
+ else if (isPollMsg) {
1283
+ if (!isNewsletter && isQuizMsg) {
1284
+ throw new HttpError('Quiz are only allowed for newsletter', { statusCode: 400 });
1285
+ }
1286
+ additionalNodes.push({
1287
+ tag: 'meta',
1288
+ attrs: {
1289
+ // Still a hypothesis regarding PollResult ༎ຶ⁠‿⁠༎ຶ
1290
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
1291
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
1292
+ },
1293
+ content: undefined
1294
+ });
1295
+ }
1296
+ else if (isEventMsg) {
1297
+ additionalNodes.push({
1298
+ tag: 'meta',
1299
+ attrs: {
1300
+ event_type: 'creation'
1301
+ },
1302
+ content: undefined
1303
+ });
1304
+ }
1305
+ // Add support for AI label in message when "ai" is true, but works only in private chat
1306
+ else if (isAiMsg) {
1307
+ if (!(isPnUser(jid) || isLidUser(jid))) {
1308
+ throw new HttpError('AI icon on message are only allowed in private chat', { statusCode: 400 });
1309
+ }
1310
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
1311
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
1312
+ }
1313
+ ;
1314
+ additionalNodes.push({
1315
+ tag: 'bot',
1316
+ attrs: {
1317
+ biz_bot: '1'
1318
+ },
1319
+ content: undefined
1320
+ });
1321
+ delete content.ai;
1322
+ }
1323
+ await relayMessage(jid, fullMsg.message, {
1324
+ messageId: fullMsg.key.id,
1325
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1326
+ addBizAttributes: isNeedBizAttrs,
1327
+ statusJidList: options.statusJidList,
1328
+ additionalAttributes,
1329
+ additionalNodes
1330
+ });
1331
+ if (config.emitOwnEvents) {
1332
+ process.nextTick(async () => {
1333
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1334
+ });
1335
+ }
1336
+ // Add support for album messages
1337
+ // Refactored to reduce high RSS usage (⁠╥⁠﹏⁠╥⁠)
1338
+ if ('album' in content) {
1339
+ const { delayMs = 1500 } = options;
1340
+ for (const albumMedia of content.album) {
1341
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
1342
+ logger,
1343
+ userJid,
1344
+ upload: waUploadToServer,
1345
+ mediaCache: config.mediaCache,
1346
+ options: config.options,
1347
+ ...options,
1348
+ messageId: generateMessageIDV2(userJid)
1349
+ });
1350
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
1351
+ throw new HttpError('Invalid message type for album', { statusCode: 400 });
1352
+ }
1353
+ (_a = albumMsg.message).messageContextInfo || (_a.messageContextInfo = {});
1354
+ albumMsg.message.messageContextInfo.messageAssociation = {
1355
+ parentMessageKey: fullMsg.key,
1356
+ associationType: AssociationType.MEDIA_ALBUM
1357
+ };
1358
+ await relayMessage(jid, albumMsg.message, {
1359
+ messageId: albumMsg.key.id,
1360
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1361
+ addBizAttributes: isNeedBizAttrs,
1362
+ statusJidList: options.statusJidList,
1363
+ additionalAttributes,
1364
+ additionalNodes
1365
+ });
1366
+ if (config.emitOwnEvents) {
1367
+ process.nextTick(async () => {
1368
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
1369
+ });
1370
+ }
1371
+ await delay(delayMs);
1372
+ }
1373
+ }
1374
+ return fullMsg;
1375
+ }
1376
+ }
1377
+ };
1378
+ };