@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

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 (431) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +25 -0
  3. package/NOTICE.md +158 -0
  4. package/README.md +5294 -2
  5. package/VanzxyBanner.js +134 -0
  6. package/WAProto/index.d.ts +13317 -0
  7. package/WAProto/index.js +147553 -0
  8. package/lib/Builders/A2UI.d.ts +131 -0
  9. package/lib/Builders/A2UI.js +343 -0
  10. package/lib/Builders/AIRich.d.ts +1021 -0
  11. package/lib/Builders/AIRich.js +2889 -0
  12. package/lib/Builders/Album.d.ts +51 -0
  13. package/lib/Builders/Album.js +99 -0
  14. package/lib/Builders/Button.d.ts +137449 -0
  15. package/lib/Builders/Button.js +1054 -0
  16. package/lib/Builders/ButtonV2.d.ts +43 -0
  17. package/lib/Builders/ButtonV2.js +175 -0
  18. package/lib/Builders/ButtonV3.d.ts +35 -0
  19. package/lib/Builders/ButtonV3.js +189 -0
  20. package/lib/Builders/Carousel.d.ts +68 -0
  21. package/lib/Builders/Carousel.js +161 -0
  22. package/lib/Builders/Event.d.ts +61 -0
  23. package/lib/Builders/Event.js +118 -0
  24. package/lib/Builders/Expiring.d.ts +17 -0
  25. package/lib/Builders/Expiring.js +27 -0
  26. package/lib/Builders/Poll.d.ts +63 -0
  27. package/lib/Builders/Poll.js +139 -0
  28. package/lib/Builders/VanzxyBaileys.d.ts +42 -0
  29. package/lib/Builders/VanzxyBaileys.js +110 -0
  30. package/lib/Builders/errors.d.ts +25 -0
  31. package/lib/Builders/errors.js +29 -0
  32. package/lib/Builders/index.d.ts +14 -0
  33. package/lib/Builders/index.js +23 -0
  34. package/lib/Builders/shared.d.ts +395 -0
  35. package/lib/Builders/shared.js +738 -0
  36. package/lib/Defaults/bot-jid.d.ts +1 -0
  37. package/lib/Defaults/bot-jid.js +1 -0
  38. package/lib/Defaults/index.d.ts +161 -0
  39. package/lib/Defaults/index.js +165 -0
  40. package/lib/Defaults/version.d.ts +1 -0
  41. package/lib/Defaults/version.js +1 -0
  42. package/lib/Framework/Bot.d.ts +865 -0
  43. package/lib/Framework/Bot.js +230 -0
  44. package/lib/Framework/Context.d.ts +17 -0
  45. package/lib/Framework/Context.js +90 -0
  46. package/lib/Framework/MediaManager.d.ts +15 -0
  47. package/lib/Framework/MediaManager.js +154 -0
  48. package/lib/Framework/SessionManager.d.ts +10 -0
  49. package/lib/Framework/SessionManager.js +34 -0
  50. package/lib/Framework/StatsManager.d.ts +20 -0
  51. package/lib/Framework/StatsManager.js +117 -0
  52. package/lib/Framework/Store/SQLiteStore.d.ts +13 -0
  53. package/lib/Framework/Store/SQLiteStore.js +68 -0
  54. package/lib/Framework/index.d.ts +6 -0
  55. package/lib/Framework/index.js +11 -0
  56. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  57. package/lib/Signal/Group/ciphertext-message.js +11 -0
  58. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  59. package/lib/Signal/Group/group-session-builder.js +29 -0
  60. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  61. package/lib/Signal/Group/group_cipher.js +81 -0
  62. package/lib/Signal/Group/index.d.ts +11 -0
  63. package/lib/Signal/Group/index.js +11 -0
  64. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  65. package/lib/Signal/Group/keyhelper.js +17 -0
  66. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  67. package/lib/Signal/Group/sender-chain-key.js +25 -0
  68. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  69. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  70. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  71. package/lib/Signal/Group/sender-key-message.js +65 -0
  72. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  73. package/lib/Signal/Group/sender-key-name.js +47 -0
  74. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  75. package/lib/Signal/Group/sender-key-record.js +40 -0
  76. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  77. package/lib/Signal/Group/sender-key-state.js +83 -0
  78. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  79. package/lib/Signal/Group/sender-message-key.js +25 -0
  80. package/lib/Signal/libsignal.d.ts +58 -0
  81. package/lib/Signal/libsignal.js +436 -0
  82. package/lib/Signal/lid-mapping.d.ts +20 -0
  83. package/lib/Signal/lid-mapping.js +276 -0
  84. package/lib/Socket/Client/index.d.ts +2 -0
  85. package/lib/Socket/Client/index.js +2 -0
  86. package/lib/Socket/Client/types.d.ts +5 -0
  87. package/lib/Socket/Client/types.js +10 -0
  88. package/lib/Socket/Client/websocket.d.ts +12 -0
  89. package/lib/Socket/Client/websocket.js +53 -0
  90. package/lib/Socket/business.d.ts +674 -0
  91. package/lib/Socket/business.js +379 -0
  92. package/lib/Socket/chats.d.ts +137 -0
  93. package/lib/Socket/chats.js +1299 -0
  94. package/lib/Socket/communities.d.ts +805 -0
  95. package/lib/Socket/communities.js +454 -0
  96. package/lib/Socket/dugong.d.ts +118 -0
  97. package/lib/Socket/dugong.js +810 -0
  98. package/lib/Socket/groups.d.ts +287 -0
  99. package/lib/Socket/groups.js +386 -0
  100. package/lib/Socket/index.d.ts +826 -0
  101. package/lib/Socket/index.js +35 -0
  102. package/lib/Socket/messages-recv.d.ts +613 -0
  103. package/lib/Socket/messages-recv.js +1851 -0
  104. package/lib/Socket/messages-send.d.ts +608 -0
  105. package/lib/Socket/messages-send.js +1574 -0
  106. package/lib/Socket/mex-fallback.d.ts +51 -0
  107. package/lib/Socket/mex-fallback.js +97 -0
  108. package/lib/Socket/mex.d.ts +1 -0
  109. package/lib/Socket/mex.js +41 -0
  110. package/lib/Socket/newsletter-ext.d.ts +47 -0
  111. package/lib/Socket/newsletter-ext.js +262 -0
  112. package/lib/Socket/newsletter.d.ts +285 -0
  113. package/lib/Socket/newsletter.js +223 -0
  114. package/lib/Socket/socket.d.ts +60 -0
  115. package/lib/Socket/socket.js +1001 -0
  116. package/lib/Socket/username.d.ts +842 -0
  117. package/lib/Socket/username.js +156 -0
  118. package/lib/Store/index.d.ts +3 -0
  119. package/lib/Store/index.js +3 -0
  120. package/lib/Store/make-in-memory-store.d.ts +62 -0
  121. package/lib/Store/make-in-memory-store.js +425 -0
  122. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  123. package/lib/Store/make-ordered-dictionary.js +78 -0
  124. package/lib/Store/object-repository.d.ts +10 -0
  125. package/lib/Store/object-repository.js +23 -0
  126. package/lib/Types/Auth.d.ts +1 -0
  127. package/lib/Types/Auth.js +1 -0
  128. package/lib/Types/Bussines.d.ts +1 -0
  129. package/lib/Types/Bussines.js +1 -0
  130. package/lib/Types/Call.d.ts +1 -0
  131. package/lib/Types/Call.js +1 -0
  132. package/lib/Types/Chat.d.ts +1 -0
  133. package/lib/Types/Chat.js +7 -0
  134. package/lib/Types/Contact.d.ts +1 -0
  135. package/lib/Types/Contact.js +1 -0
  136. package/lib/Types/Events.d.ts +1 -0
  137. package/lib/Types/Events.js +1 -0
  138. package/lib/Types/GroupMetadata.d.ts +1 -0
  139. package/lib/Types/GroupMetadata.js +1 -0
  140. package/lib/Types/Label.d.ts +2 -0
  141. package/lib/Types/Label.js +24 -0
  142. package/lib/Types/LabelAssociation.d.ts +2 -0
  143. package/lib/Types/LabelAssociation.js +6 -0
  144. package/lib/Types/Message.d.ts +11 -0
  145. package/lib/Types/Message.js +17 -0
  146. package/lib/Types/Mex.d.ts +2 -0
  147. package/lib/Types/Mex.js +38 -0
  148. package/lib/Types/Product.d.ts +1 -0
  149. package/lib/Types/Product.js +1 -0
  150. package/lib/Types/RichType.d.ts +2 -0
  151. package/lib/Types/RichType.js +22 -0
  152. package/lib/Types/Signal.d.ts +1 -0
  153. package/lib/Types/Signal.js +1 -0
  154. package/lib/Types/Socket.d.ts +1 -0
  155. package/lib/Types/Socket.js +1 -0
  156. package/lib/Types/State.d.ts +5 -0
  157. package/lib/Types/State.js +55 -0
  158. package/lib/Types/USync.d.ts +1 -0
  159. package/lib/Types/USync.js +1 -0
  160. package/lib/Types/index.d.ts +15 -0
  161. package/lib/Types/index.js +27 -0
  162. package/lib/Utils/PersistentStore.d.ts +83 -0
  163. package/lib/Utils/PersistentStore.js +592 -0
  164. package/lib/Utils/anchor-guard.d.ts +31 -0
  165. package/lib/Utils/anchor-guard.js +329 -0
  166. package/lib/Utils/android-stanza-id.d.ts +4 -0
  167. package/lib/Utils/android-stanza-id.js +21 -0
  168. package/lib/Utils/anti-delete.d.ts +62 -0
  169. package/lib/Utils/anti-delete.js +212 -0
  170. package/lib/Utils/auth-secure.d.ts +180 -0
  171. package/lib/Utils/auth-secure.js +791 -0
  172. package/lib/Utils/auth-utils.d.ts +59 -0
  173. package/lib/Utils/auth-utils.js +326 -0
  174. package/lib/Utils/auto-reconnect.d.ts +8 -0
  175. package/lib/Utils/auto-reconnect.js +204 -0
  176. package/lib/Utils/auto-reply.d.ts +35 -0
  177. package/lib/Utils/auto-reply.js +152 -0
  178. package/lib/Utils/bad-mac-handler.d.ts +59 -0
  179. package/lib/Utils/bad-mac-handler.js +119 -0
  180. package/lib/Utils/baileys-event-stream.d.ts +5 -0
  181. package/lib/Utils/baileys-event-stream.js +62 -0
  182. package/lib/Utils/browser-utils.d.ts +9 -0
  183. package/lib/Utils/browser-utils.js +29 -0
  184. package/lib/Utils/business.d.ts +49 -0
  185. package/lib/Utils/business.js +236 -0
  186. package/lib/Utils/button-helper-utils.d.ts +59 -0
  187. package/lib/Utils/button-helper-utils.js +266 -0
  188. package/lib/Utils/button-sender.d.ts +164 -0
  189. package/lib/Utils/button-sender.js +845 -0
  190. package/lib/Utils/chat-control.d.ts +98 -0
  191. package/lib/Utils/chat-control.js +231 -0
  192. package/lib/Utils/chat-history-helpers.d.ts +4 -0
  193. package/lib/Utils/chat-history-helpers.js +70 -0
  194. package/lib/Utils/chat-utils.d.ts +408 -0
  195. package/lib/Utils/chat-utils.js +879 -0
  196. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  197. package/lib/Utils/companion-reg-client-utils.js +39 -0
  198. package/lib/Utils/connection-watchdog.d.ts +10 -0
  199. package/lib/Utils/connection-watchdog.js +74 -0
  200. package/lib/Utils/crypto.d.ts +41 -0
  201. package/lib/Utils/crypto.js +145 -0
  202. package/lib/Utils/decode-wa-message.d.ts +83 -0
  203. package/lib/Utils/decode-wa-message.js +315 -0
  204. package/lib/Utils/disconnect-reason.d.ts +13 -0
  205. package/lib/Utils/disconnect-reason.js +36 -0
  206. package/lib/Utils/event-buffer.d.ts +12 -0
  207. package/lib/Utils/event-buffer.js +640 -0
  208. package/lib/Utils/fetch-timeout.d.ts +4 -0
  209. package/lib/Utils/fetch-timeout.js +14 -0
  210. package/lib/Utils/ffmpeg-path.d.ts +5 -0
  211. package/lib/Utils/ffmpeg-path.js +130 -0
  212. package/lib/Utils/generics.d.ts +79 -0
  213. package/lib/Utils/generics.js +426 -0
  214. package/lib/Utils/group-metadata-cache.d.ts +3 -0
  215. package/lib/Utils/group-metadata-cache.js +25 -0
  216. package/lib/Utils/group-status-detection.d.ts +5 -0
  217. package/lib/Utils/group-status-detection.js +114 -0
  218. package/lib/Utils/history.d.ts +91 -0
  219. package/lib/Utils/history.js +144 -0
  220. package/lib/Utils/html-app.d.ts +14 -0
  221. package/lib/Utils/html-app.js +97 -0
  222. package/lib/Utils/html-multiplayer.d.ts +8 -0
  223. package/lib/Utils/html-multiplayer.js +90 -0
  224. package/lib/Utils/humanizer.d.ts +8 -0
  225. package/lib/Utils/humanizer.js +74 -0
  226. package/lib/Utils/identity-change-handler.d.ts +13 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/index.d.ts +88 -0
  229. package/lib/Utils/index.js +93 -0
  230. package/lib/Utils/jid-tools.d.ts +3 -0
  231. package/lib/Utils/jid-tools.js +78 -0
  232. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  233. package/lib/Utils/link-preview-metadata.js +90 -0
  234. package/lib/Utils/link-preview.d.ts +12 -0
  235. package/lib/Utils/link-preview.js +84 -0
  236. package/lib/Utils/lock-manager.d.ts +5 -0
  237. package/lib/Utils/lock-manager.js +50 -0
  238. package/lib/Utils/logger.d.ts +2 -0
  239. package/lib/Utils/logger.js +2 -0
  240. package/lib/Utils/lt-hash.d.ts +12 -0
  241. package/lib/Utils/lt-hash.js +26 -0
  242. package/lib/Utils/make-mutex.d.ts +6 -0
  243. package/lib/Utils/make-mutex.js +32 -0
  244. package/lib/Utils/media-messages.d.ts +35 -0
  245. package/lib/Utils/media-messages.js +70 -0
  246. package/lib/Utils/media-processor.d.ts +6 -0
  247. package/lib/Utils/media-processor.js +174 -0
  248. package/lib/Utils/media-set.d.ts +6 -0
  249. package/lib/Utils/media-set.js +169 -0
  250. package/lib/Utils/message-kind.d.ts +26 -0
  251. package/lib/Utils/message-kind.js +138 -0
  252. package/lib/Utils/message-retry-manager.d.ts +79 -0
  253. package/lib/Utils/message-retry-manager.js +264 -0
  254. package/lib/Utils/message-search.d.ts +40 -0
  255. package/lib/Utils/message-search.js +181 -0
  256. package/lib/Utils/messages-media.d.ts +136 -0
  257. package/lib/Utils/messages-media.js +867 -0
  258. package/lib/Utils/messages.d.ts +66 -0
  259. package/lib/Utils/messages.js +2271 -0
  260. package/lib/Utils/meta-ai-msmsg.d.ts +3 -0
  261. package/lib/Utils/meta-ai-msmsg.js +132 -0
  262. package/lib/Utils/meta-ai.d.ts +4 -0
  263. package/lib/Utils/meta-ai.js +75 -0
  264. package/lib/Utils/migrate-auth-state.d.ts +23 -0
  265. package/lib/Utils/migrate-auth-state.js +126 -0
  266. package/lib/Utils/mini-app.d.ts +20 -0
  267. package/lib/Utils/mini-app.js +215 -0
  268. package/lib/Utils/mock-socket.d.ts +67 -0
  269. package/lib/Utils/mock-socket.js +254 -0
  270. package/lib/Utils/modern-messages.d.ts +64 -0
  271. package/lib/Utils/modern-messages.js +497 -0
  272. package/lib/Utils/native-flow.d.ts +19 -0
  273. package/lib/Utils/native-flow.js +112 -0
  274. package/lib/Utils/newsletter-status.d.ts +157 -0
  275. package/lib/Utils/newsletter-status.js +652 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.js +200 -0
  278. package/lib/Utils/offline-node-processor.d.ts +9 -0
  279. package/lib/Utils/offline-node-processor.js +39 -0
  280. package/lib/Utils/pairing-utils.d.ts +5 -0
  281. package/lib/Utils/pairing-utils.js +29 -0
  282. package/lib/Utils/passkey.d.ts +4 -0
  283. package/lib/Utils/passkey.js +11 -0
  284. package/lib/Utils/past-participants.d.ts +2 -0
  285. package/lib/Utils/past-participants.js +40 -0
  286. package/lib/Utils/payment-detection.d.ts +40 -0
  287. package/lib/Utils/payment-detection.js +213 -0
  288. package/lib/Utils/payment-guard.d.ts +28 -0
  289. package/lib/Utils/payment-guard.js +143 -0
  290. package/lib/Utils/payment-messages.d.ts +42 -0
  291. package/lib/Utils/payment-messages.js +161 -0
  292. package/lib/Utils/payment-utils.d.ts +75 -0
  293. package/lib/Utils/payment-utils.js +145 -0
  294. package/lib/Utils/phone-utils.d.ts +3 -0
  295. package/lib/Utils/phone-utils.js +29 -0
  296. package/lib/Utils/pre-key-manager.d.ts +25 -0
  297. package/lib/Utils/pre-key-manager.js +105 -0
  298. package/lib/Utils/process-message.d.ts +103 -0
  299. package/lib/Utils/process-message.js +868 -0
  300. package/lib/Utils/qr-terminal.d.ts +1 -0
  301. package/lib/Utils/qr-terminal.js +16 -0
  302. package/lib/Utils/reconnect-backoff.d.ts +25 -0
  303. package/lib/Utils/reconnect-backoff.js +47 -0
  304. package/lib/Utils/reporting-utils.d.ts +12 -0
  305. package/lib/Utils/reporting-utils.js +257 -0
  306. package/lib/Utils/rich-message-utils.d.ts +54 -0
  307. package/lib/Utils/rich-message-utils.js +435 -0
  308. package/lib/Utils/rich-messages.d.ts +298 -0
  309. package/lib/Utils/rich-messages.js +1145 -0
  310. package/lib/Utils/scheduled-message.d.ts +81 -0
  311. package/lib/Utils/scheduled-message.js +101 -0
  312. package/lib/Utils/scheduling.d.ts +59 -0
  313. package/lib/Utils/scheduling.js +139 -0
  314. package/lib/Utils/signal.d.ts +82 -0
  315. package/lib/Utils/signal.js +200 -0
  316. package/lib/Utils/stanza-ack.d.ts +16 -0
  317. package/lib/Utils/stanza-ack.js +37 -0
  318. package/lib/Utils/status-stickers.d.ts +79 -0
  319. package/lib/Utils/status-stickers.js +261 -0
  320. package/lib/Utils/status.d.ts +107 -0
  321. package/lib/Utils/status.js +131 -0
  322. package/lib/Utils/sticker-pack-maker.d.ts +20 -0
  323. package/lib/Utils/sticker-pack-maker.js +112 -0
  324. package/lib/Utils/stickerpack.d.ts +18 -0
  325. package/lib/Utils/stickerpack.js +316 -0
  326. package/lib/Utils/sync-action-utils.d.ts +2 -0
  327. package/lib/Utils/sync-action-utils.js +48 -0
  328. package/lib/Utils/tag.d.ts +8 -0
  329. package/lib/Utils/tag.js +45 -0
  330. package/lib/Utils/tc-token-utils.d.ts +29 -0
  331. package/lib/Utils/tc-token-utils.js +162 -0
  332. package/lib/Utils/templates.d.ts +86 -0
  333. package/lib/Utils/templates.js +148 -0
  334. package/lib/Utils/text-format.d.ts +13 -0
  335. package/lib/Utils/text-format.js +81 -0
  336. package/lib/Utils/text-tools.d.ts +3 -0
  337. package/lib/Utils/text-tools.js +38 -0
  338. package/lib/Utils/ttl-cache.d.ts +29 -0
  339. package/lib/Utils/ttl-cache.js +123 -0
  340. package/lib/Utils/use-cache-manager-auth-state.d.ts +22 -0
  341. package/lib/Utils/use-cache-manager-auth-state.js +86 -0
  342. package/lib/Utils/use-multi-file-auth-state.d.ts +20 -0
  343. package/lib/Utils/use-multi-file-auth-state.js +201 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  345. package/lib/Utils/use-single-file-auth-state.js +111 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  347. package/lib/Utils/use-sqlite-auth-state.js +171 -0
  348. package/lib/Utils/username.d.ts +22 -0
  349. package/lib/Utils/username.js +59 -0
  350. package/lib/Utils/validate-connection.d.ts +43 -0
  351. package/lib/Utils/validate-connection.js +197 -0
  352. package/lib/Utils/vcard.d.ts +40 -0
  353. package/lib/Utils/vcard.js +92 -0
  354. package/lib/Utils/voice-note.d.ts +13 -0
  355. package/lib/Utils/voice-note.js +47 -0
  356. package/lib/VoIP/audio-feeder.d.ts +15 -0
  357. package/lib/VoIP/audio-feeder.js +132 -0
  358. package/lib/VoIP/index.d.ts +22 -0
  359. package/lib/VoIP/index.js +277 -0
  360. package/lib/VoIP/relay-transport.d.ts +16 -0
  361. package/lib/VoIP/relay-transport.js +559 -0
  362. package/lib/VoIP/signaling.d.ts +16 -0
  363. package/lib/VoIP/signaling.js +624 -0
  364. package/lib/VoIP/types.d.ts +11 -0
  365. package/lib/VoIP/types.js +17 -0
  366. package/lib/VoIP/wasm-engine.d.ts +28 -0
  367. package/lib/VoIP/wasm-engine.js +1214 -0
  368. package/lib/VoIP/worker-bootstrap.d.ts +1 -0
  369. package/lib/VoIP/worker-bootstrap.js +1042 -0
  370. package/lib/WABinary/constants.d.ts +61 -0
  371. package/lib/WABinary/constants.js +1466 -0
  372. package/lib/WABinary/decode.d.ts +9 -0
  373. package/lib/WABinary/decode.js +261 -0
  374. package/lib/WABinary/encode.d.ts +2 -0
  375. package/lib/WABinary/encode.js +219 -0
  376. package/lib/WABinary/generic-utils.d.ts +45 -0
  377. package/lib/WABinary/generic-utils.js +285 -0
  378. package/lib/WABinary/index.d.ts +5 -0
  379. package/lib/WABinary/index.js +5 -0
  380. package/lib/WABinary/jid-utils.d.ts +32 -0
  381. package/lib/WABinary/jid-utils.js +102 -0
  382. package/lib/WABinary/types.d.ts +1 -0
  383. package/lib/WABinary/types.js +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +7 -0
  385. package/lib/WAM/BinaryInfo.js +9 -0
  386. package/lib/WAM/constants.d.ts +34926 -0
  387. package/lib/WAM/constants.js +22852 -0
  388. package/lib/WAM/encode.d.ts +1 -0
  389. package/lib/WAM/encode.js +149 -0
  390. package/lib/WAM/index.d.ts +3 -0
  391. package/lib/WAM/index.js +3 -0
  392. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +43 -0
  393. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  395. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  396. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  397. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +60 -0
  398. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  399. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  400. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +13 -0
  401. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +28 -0
  402. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +22 -0
  403. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  404. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +20 -0
  405. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +23 -0
  406. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  407. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  408. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +14 -0
  409. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +24 -0
  410. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  411. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  412. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  413. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  414. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  415. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  416. package/lib/WAUSync/Protocols/index.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/index.js +12 -0
  418. package/lib/WAUSync/USyncQuery.d.ts +25 -0
  419. package/lib/WAUSync/USyncQuery.js +140 -0
  420. package/lib/WAUSync/USyncUser.d.ts +24 -0
  421. package/lib/WAUSync/USyncUser.js +47 -0
  422. package/lib/WAUSync/index.d.ts +3 -0
  423. package/lib/WAUSync/index.js +3 -0
  424. package/lib/assets/wasm/loader.js +5 -0
  425. package/lib/assets/wasm/whatsapp.wasm +0 -0
  426. package/lib/assets/wasm/worker-modules.js +273 -0
  427. package/lib/exports-extra.d.ts +45 -0
  428. package/lib/exports-extra.js +47 -0
  429. package/lib/index.d.ts +16 -0
  430. package/lib/index.js +24 -0
  431. package/package.json +161 -4
@@ -0,0 +1,868 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import $protobuf from 'protobufjs/minimal.js';
3
+ const { Reader } = $protobuf;
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { WAMessageStubType } from '../Types/index.js';
6
+ import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
7
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
8
+ import { aesDecryptGCM, hmacSign } from './crypto.js';
9
+ import { getKeyAuthor, toNumber } from './generics.js';
10
+ import { downloadAndProcessHistorySyncNotification } from './history.js';
11
+ import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './tc-token-utils.js';
12
+ const REAL_MSG_STUB_TYPES = new Set([
13
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
+ WAMessageStubType.CALL_MISSED_VIDEO,
16
+ WAMessageStubType.CALL_MISSED_VOICE
17
+ ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
19
+ function decodeLidMigrationMappingSyncPayload(buf) {
20
+ const r = Reader.create(buf);
21
+ const out = { pnToLidMappings: [], chatDbMigrationTimestamp: undefined };
22
+ while (r.pos < r.len) {
23
+ const tag = r.uint32();
24
+ switch (tag >>> 3) {
25
+ case 1: {
26
+ const len = r.uint32();
27
+ const end = r.pos + len;
28
+ const entry = { pn: undefined, assignedLid: undefined, latestLid: undefined };
29
+ while (r.pos < end) {
30
+ const t2 = r.uint32();
31
+ switch (t2 >>> 3) {
32
+ case 1:
33
+ entry.pn = r.uint64();
34
+ break;
35
+ case 2:
36
+ entry.assignedLid = r.uint64();
37
+ break;
38
+ case 3:
39
+ entry.latestLid = r.uint64();
40
+ break;
41
+ default:
42
+ r.skipType(t2 & 7);
43
+ }
44
+ }
45
+ out.pnToLidMappings.push(entry);
46
+ break;
47
+ }
48
+ case 2:
49
+ out.chatDbMigrationTimestamp = r.uint64();
50
+ break;
51
+ default:
52
+ r.skipType(tag & 7);
53
+ }
54
+ }
55
+ return out;
56
+ }
57
+ async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger) {
58
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
59
+ const candidates = [];
60
+ for (const chat of chats) {
61
+ const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0;
62
+ if (chat.tcToken?.length && ts > 0) {
63
+ const jid = jidNormalizedUser(chat.id);
64
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
65
+ candidates.push({
66
+ storageJid,
67
+ token: Buffer.from(chat.tcToken),
68
+ ts,
69
+ senderTs: chat.tcTokenSenderTimestamp ? toNumber(chat.tcTokenSenderTimestamp) : undefined
70
+ });
71
+ }
72
+ }
73
+ if (!candidates.length) {
74
+ return;
75
+ }
76
+ const jids = candidates.map(c => c.storageJid);
77
+ const existing = await keyStore.get('tctoken', jids);
78
+ const entries = {};
79
+ for (const c of candidates) {
80
+ const existingEntry = existing[c.storageJid];
81
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
82
+ if (existingTs > 0 && existingTs >= c.ts) {
83
+ continue;
84
+ }
85
+ entries[c.storageJid] = {
86
+ ...existingEntry,
87
+ token: c.token,
88
+ timestamp: String(c.ts),
89
+ ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {})
90
+ };
91
+ }
92
+ if (Object.keys(entries).length) {
93
+ logger?.debug({ count: Object.keys(entries).length }, 'storing tctokens from history sync');
94
+ try {
95
+ // Include updated __index so cross-session pruning picks these JIDs up.
96
+ const indexWrite = await buildMergedTcTokenIndexWrite(keyStore, Object.keys(entries));
97
+ await keyStore.set({ tctoken: { ...entries, ...indexWrite } });
98
+ }
99
+ catch (err) {
100
+ logger?.warn({ err }, 'failed to store tctokens from history sync');
101
+ }
102
+ }
103
+ }
104
+ /** Cleans a received message to further processing */
105
+ export const cleanMessage = (message, meId, meLid) => {
106
+ // ensure remoteJid and participant doesn't have device or agent in it
107
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
108
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
109
+ }
110
+ else {
111
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
112
+ }
113
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
114
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid');
115
+ }
116
+ else {
117
+ message.key.participant = jidNormalizedUser(message.key.participant);
118
+ }
119
+ const content = normalizeMessageContent(message.message);
120
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
121
+ if (content?.reactionMessage) {
122
+ normaliseKey(content.reactionMessage.key);
123
+ }
124
+ if (content?.pollUpdateMessage) {
125
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
126
+ }
127
+ function normaliseKey(msgKey) {
128
+ // if the reaction is from another user
129
+ // we've to correctly map the key to this user's perspective
130
+ if (!message.key.fromMe) {
131
+ // if the sender believed the message being reacted to is not from them
132
+ // we've to correct the key to be from them, or some other participant
133
+ msgKey.fromMe = !msgKey.fromMe
134
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
135
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
136
+ : // if the message being reacted to, was from them
137
+ // fromMe automatically becomes false
138
+ false;
139
+ // set the remoteJid to being the same as the chat the message came from
140
+ // TODO: investigate inconsistencies
141
+ msgKey.remoteJid = message.key.remoteJid;
142
+ // set participant of the message
143
+ msgKey.participant = msgKey.participant || message.key.participant;
144
+ }
145
+ }
146
+ };
147
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
148
+ export const isRealMessage = (message) => {
149
+ const normalizedContent = normalizeMessageContent(message.message);
150
+ const hasSomeContent = !!getContentType(normalizedContent);
151
+ return ((!!normalizedContent ||
152
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
153
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
154
+ hasSomeContent &&
155
+ !normalizedContent?.protocolMessage &&
156
+ !normalizedContent?.reactionMessage &&
157
+ !normalizedContent?.pollUpdateMessage);
158
+ };
159
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
160
+ /**
161
+ * Get the ID of the chat from the given key.
162
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
163
+ */
164
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
165
+ if (!remoteJid) {
166
+ throw new Boom('Cannot derive chat id: message key is missing remoteJid', {
167
+ data: { remoteJid, participant, fromMe }
168
+ });
169
+ }
170
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
171
+ if (!participant) {
172
+ throw new Boom('Cannot derive chat id: broadcast message key is missing participant', {
173
+ data: { remoteJid, fromMe }
174
+ });
175
+ }
176
+ return participant;
177
+ }
178
+ return remoteJid;
179
+ };
180
+ /**
181
+ * Decrypt a poll vote
182
+ * @param vote encrypted vote
183
+ * @param ctx additional info about the poll required for decryption
184
+ * @returns list of SHA256 options
185
+ */
186
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
187
+ const sign = Buffer.concat([
188
+ toBinary(pollMsgId),
189
+ toBinary(pollCreatorJid),
190
+ toBinary(voterJid),
191
+ toBinary('Poll Vote'),
192
+ new Uint8Array([1])
193
+ ]);
194
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
195
+ const decKey = hmacSign(sign, key0, 'sha256');
196
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
197
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
198
+ return proto.Message.PollVoteMessage.decode(decrypted);
199
+ function toBinary(txt) {
200
+ return Buffer.from(txt);
201
+ }
202
+ }
203
+ /**
204
+ * Decrypt an event response
205
+ * @param response encrypted event response
206
+ * @param ctx additional info about the event required for decryption
207
+ * @returns event response message
208
+ */
209
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
210
+ const sign = Buffer.concat([
211
+ toBinary(eventMsgId),
212
+ toBinary(eventCreatorJid),
213
+ toBinary(responderJid),
214
+ toBinary('Event Response'),
215
+ new Uint8Array([1])
216
+ ]);
217
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256');
218
+ const decKey = hmacSign(sign, key0, 'sha256');
219
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
220
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
221
+ return proto.Message.EventResponseMessage.decode(decrypted);
222
+ function toBinary(txt) {
223
+ return Buffer.from(txt);
224
+ }
225
+ }
226
+ /**
227
+ * JID that authored the *target* message, as used in the HMAC input of encrypted modifications
228
+ * (must be a PN). Honours `key.fromMe`: for our own message in a group the old event-response code used
229
+ * `participant || remoteJid` = the GROUP jid, and for our own message in a DM the OTHER user's jid -- both wrong.
230
+ */
231
+ const resolveTargetAuthorPn = async (key, meIdNormalised, signalRepository) => {
232
+ const raw = key.fromMe ? meIdNormalised : (key.participant || key.remoteJid);
233
+ const pn = isLidUser(raw) ? await signalRepository.lidMapping.getPNForLID(raw) : raw;
234
+ if (!pn) throw new Boom('cannot resolve target author to a PN', { statusCode: 400, data: { key } });
235
+ return jidNormalizedUser(pn);
236
+ };
237
+ /**
238
+ * decrypt an `encReactionMessage` (encrypted reaction).
239
+ *
240
+ * Same key-derivation family as Poll Vote / Event Response, use-case string "Enc Reaction" (the constant whatsmeow
241
+ * uses for EncSecretReaction). EXPERIMENTAL: derived from that sibling scheme, not yet validated against a captured
242
+ * encrypted reaction from a live account -- a wrong constant just makes this throw (processMessage catches it and
243
+ * emits `messages.reaction-encrypted` instead).
244
+ * info = targetMsgId || targetSenderJid || reactorJid || "Enc Reaction" || 0x01 ; key = HMAC chain over messageSecret
245
+ * aad = targetMsgId \0 reactorJid
246
+ * @returns {proto.Message.ReactionMessage}
247
+ */
248
+ export function decryptEncReaction({ encPayload, encIv }, { targetSenderJid, targetMsgId, targetEncKey, reactorJid }) {
249
+ const sign = Buffer.concat([
250
+ toBinary(targetMsgId),
251
+ toBinary(targetSenderJid),
252
+ toBinary(reactorJid),
253
+ toBinary('Enc Reaction'),
254
+ new Uint8Array([1])
255
+ ]);
256
+ const key0 = hmacSign(targetEncKey, new Uint8Array(32), 'sha256');
257
+ const decKey = hmacSign(sign, key0, 'sha256');
258
+ const aad = toBinary(`${targetMsgId}\u0000${reactorJid}`);
259
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
260
+ return proto.Message.ReactionMessage.decode(decrypted);
261
+ function toBinary(txt) {
262
+ return Buffer.from(txt);
263
+ }
264
+ }
265
+ /**
266
+ * Decrypt a `secretEncryptedMessage` carrying a `MESSAGE_EDIT` payload.
267
+ *
268
+ * WhatsApp started wrapping message edits in an E2EE envelope (May 2026).
269
+ * The new content is encrypted with a key derived from the original
270
+ * message's `messageContextInfo.messageSecret` using HKDF-SHA256
271
+ * + AES-256-GCM, same family as polls and event responses but with
272
+ * different constants (validated against live WhatsApp Android traffic):
273
+ *
274
+ * info = msgId || origSenderJid || editorJid || "Message Edit"
275
+ * aad = (empty) <-- differs from Poll Vote / Event Response
276
+ * key = HKDF-SHA256(salt=zeros, ikm=messageSecret, info, L=32)
277
+ *
278
+ * The decrypted plaintext is a regular `proto.Message` whose
279
+ * `protocolMessage.editedMessage` field holds the new content — same
280
+ * shape as the legacy `protocolMessage.editedMessage` edit path, so
281
+ * consumers can treat the result identically.
282
+ *
283
+ * @param edit encrypted edit payload (encPayload + encIv from SecretEncryptedMessage)
284
+ * @param ctx info about the original message required for decryption
285
+ * @returns decoded outer `Message` whose `protocolMessage.editedMessage`
286
+ * carries the new content (extendedTextMessage / conversation / etc.)
287
+ */
288
+ export function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, originalMsgId, editEncKey, editorJid }) {
289
+ const sign = Buffer.concat([
290
+ toBinary(originalMsgId),
291
+ toBinary(originalSenderJid),
292
+ toBinary(editorJid),
293
+ toBinary('Message Edit'),
294
+ new Uint8Array([1])
295
+ ]);
296
+ const key0 = hmacSign(editEncKey, new Uint8Array(32), 'sha256');
297
+ const decKey = hmacSign(sign, key0, 'sha256');
298
+ // AAD is intentionally empty for MESSAGE_EDIT — unlike Poll Vote and
299
+ // Event Response, WA does not include `${msgId}\0${editor}` in the AAD here.
300
+ const aad = Buffer.alloc(0);
301
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
302
+ return proto.Message.decode(decrypted);
303
+ function toBinary(txt) {
304
+ return Buffer.from(txt);
305
+ }
306
+ }
307
+ const buildEditUpdate = (args) => {
308
+ const editedInner = decryptMessageEdit({ encPayload: args.encPayload, encIv: args.encIv }, {
309
+ editEncKey: args.editEncKey,
310
+ originalSenderJid: args.originalSenderJid,
311
+ originalMsgId: args.originalMsgId,
312
+ editorJid: args.editorJid
313
+ });
314
+ const editProtocol = editedInner.protocolMessage;
315
+ const innerEdited = editProtocol?.editedMessage;
316
+ if (!innerEdited) {
317
+ args.logger?.warn({ targetKey: args.targetKey }, 'decrypted MESSAGE_EDIT plaintext had no protocolMessage.editedMessage — skipping update');
318
+ return null;
319
+ }
320
+ return {
321
+ key: { ...args.messageKey, id: args.targetKeyId },
322
+ update: {
323
+ message: {
324
+ editedMessage: {
325
+ message: innerEdited
326
+ }
327
+ },
328
+ messageTimestamp: editProtocol?.timestampMs
329
+ ? Math.floor(toNumber(editProtocol.timestampMs) / 1000)
330
+ : args.fallbackTimestamp
331
+ }
332
+ };
333
+ };
334
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
335
+ const meId = creds.me.id;
336
+ const { accountSettings } = creds;
337
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
338
+ const isRealMsg = isRealMessage(message);
339
+ if (isRealMsg) {
340
+ chat.messages = [{ message }];
341
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
342
+ // only increment unread count if not CIPHERTEXT and from another person
343
+ if (shouldIncrementChatUnread(message)) {
344
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
345
+ }
346
+ }
347
+ const content = normalizeMessageContent(message.message);
348
+ // unarchive chat if it's a real message, or someone reacted to our message
349
+ // and we've the unarchive chats setting on
350
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
351
+ chat.archived = false;
352
+ chat.readOnly = false;
353
+ }
354
+ const protocolMsg = content?.protocolMessage;
355
+ if (protocolMsg) {
356
+ // Mirror whatsmeow's `handleProtocolMessage` guard, but applied only to
357
+ // the protocol message types that originate from our own device — an
358
+ // attacker could otherwise spoof any of these to manipulate local state.
359
+ //
360
+ // Self-only types (drop if `!fromMe`):
361
+ // - HISTORY_SYNC_NOTIFICATION (our phone driving history sync)
362
+ // - APP_STATE_SYNC_KEY_SHARE (key share between our devices)
363
+ // - LID_MIGRATION_MAPPING_SYNC (server-initiated via our phone)
364
+ // - PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE (response from our phone to our PDO request)
365
+ //
366
+ // Cross-user types (must NOT be dropped — legitimately arrive from others):
367
+ // - REVOKE
368
+ // - MESSAGE_EDIT
369
+ // - EPHEMERAL_SETTING
370
+ // - GROUP_MEMBER_LABEL_CHANGE
371
+ //
372
+ // See https://github.com/tulir/whatsmeow/blob/8d3700152a/message.go#L842-L845
373
+ // for the reference architecture — whatsmeow's `handleProtocolMessage`
374
+ // only contains self-only types because edits are unwrapped from
375
+ // `EditedMessage` BEFORE this dispatch and revokes aren't routed here.
376
+ const SELF_ONLY_TYPES = new Set([
377
+ proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
378
+ proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
379
+ proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
380
+ proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
381
+ ]);
382
+ if (protocolMsg.type !== null &&
383
+ protocolMsg.type !== undefined &&
384
+ SELF_ONLY_TYPES.has(protocolMsg.type) &&
385
+ !message.key.fromMe) {
386
+ logger?.warn({ msgId: message.key.id, type: protocolMsg.type, from: message.key.participant || message.key.remoteJid }, 'dropping spoofed self-only protocolMessage from non-self origin');
387
+ return;
388
+ }
389
+ switch (protocolMsg.type) {
390
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
391
+ const histNotification = protocolMsg.historySyncNotification;
392
+ const process = shouldProcessHistoryMsg;
393
+ const isLatest = !creds.processedHistoryMessages?.length;
394
+ logger?.info({
395
+ histNotification,
396
+ process,
397
+ id: message.key.id,
398
+ isLatest
399
+ }, 'got history notification');
400
+ if (process) {
401
+ // TODO: investigate
402
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
403
+ ev.emit('creds.update', {
404
+ processedHistoryMessages: [
405
+ ...(creds.processedHistoryMessages || []),
406
+ { key: message.key, messageTimestamp: message.messageTimestamp }
407
+ ]
408
+ });
409
+ }
410
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger);
411
+ if (data.lidPnMappings?.length) {
412
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
413
+ await signalRepository.lidMapping
414
+ .storeLIDPNMappings(data.lidPnMappings)
415
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
416
+ }
417
+ await storeTcTokensFromHistorySync(data.chats, signalRepository, keyStore, logger);
418
+ ev.emit('messaging-history.set', {
419
+ ...data,
420
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
421
+ chunkOrder: histNotification.chunkOrder,
422
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
423
+ });
424
+ }
425
+ break;
426
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
427
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
428
+ if (keys?.length) {
429
+ let newAppStateSyncKeyId = '';
430
+ await keyStore.transaction(async () => {
431
+ const newKeys = [];
432
+ for (const { keyData, keyId } of keys) {
433
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
434
+ newKeys.push(strKeyId);
435
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
436
+ newAppStateSyncKeyId = strKeyId;
437
+ }
438
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
439
+ }, meId);
440
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
441
+ }
442
+ else {
443
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
444
+ }
445
+ break;
446
+ case proto.Message.ProtocolMessage.Type.REVOKE:
447
+ ev.emit('messages.update', [
448
+ {
449
+ key: {
450
+ ...message.key,
451
+ id: protocolMsg.key.id
452
+ },
453
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
454
+ }
455
+ ]);
456
+ break;
457
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
458
+ Object.assign(chat, {
459
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
460
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
461
+ });
462
+ break;
463
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
464
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
465
+ if (response) {
466
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
467
+ const peerDataOperationResult = response.peerDataOperationResult || [];
468
+ for (const result of peerDataOperationResult) {
469
+ const retryResponse = result?.placeholderMessageResendResponse;
470
+ //eslint-disable-next-line max-depth
471
+ if (!retryResponse?.webMessageInfoBytes) {
472
+ continue;
473
+ }
474
+ //eslint-disable-next-line max-depth
475
+ try {
476
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
477
+ const msgId = webMessageInfo.key?.id;
478
+ // Retrieve cached original message data (preserves LID details,
479
+ // timestamps, etc. that the phone may omit in its PDO response)
480
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
481
+ //eslint-disable-next-line max-depth
482
+ if (msgId) {
483
+ await placeholderResendCache?.del(msgId);
484
+ }
485
+ let finalMsg;
486
+ //eslint-disable-next-line max-depth
487
+ if (cachedData && typeof cachedData === 'object') {
488
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
489
+ cachedData.message = webMessageInfo.message;
490
+ //eslint-disable-next-line max-depth
491
+ if (webMessageInfo.messageTimestamp) {
492
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
493
+ }
494
+ finalMsg = cachedData;
495
+ }
496
+ else {
497
+ finalMsg = webMessageInfo;
498
+ }
499
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
500
+ ev.emit('messages.upsert', {
501
+ messages: [finalMsg],
502
+ type: 'notify',
503
+ requestId: response.stanzaId
504
+ });
505
+ }
506
+ catch (err) {
507
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
508
+ }
509
+ }
510
+ }
511
+ break;
512
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
513
+ ev.emit('messages.update', [
514
+ {
515
+ // flip the sender / fromMe properties because they're in the perspective of the sender
516
+ key: { ...message.key, id: protocolMsg.key?.id },
517
+ update: {
518
+ message: {
519
+ editedMessage: {
520
+ message: protocolMsg.editedMessage
521
+ }
522
+ },
523
+ messageTimestamp: protocolMsg.timestampMs
524
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
525
+ : message.messageTimestamp
526
+ }
527
+ }
528
+ ]);
529
+ break;
530
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
531
+ const labelAssociationMsg = protocolMsg.memberLabel;
532
+ if (labelAssociationMsg?.label) {
533
+ ev.emit('group.member-tag.update', {
534
+ groupId: chat.id,
535
+ label: labelAssociationMsg.label,
536
+ participant: message.key.participant,
537
+ participantAlt: message.key.participantAlt,
538
+ messageTimestamp: Number(message.messageTimestamp)
539
+ });
540
+ }
541
+ break;
542
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
543
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
544
+ const { pnToLidMappings, chatDbMigrationTimestamp } = decodeLidMigrationMappingSyncPayload(encodedPayload);
545
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
546
+ const pairs = [];
547
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
548
+ const lid = latestLid || assignedLid;
549
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
550
+ }
551
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
552
+ if (pairs.length) {
553
+ for (const { pn, lid } of pairs) {
554
+ await signalRepository.migrateSession(pn, lid);
555
+ }
556
+ }
557
+ }
558
+ }
559
+ else if (content?.reactionMessage) {
560
+ const reaction = {
561
+ ...content.reactionMessage,
562
+ key: message.key
563
+ };
564
+ ev.emit('messages.reaction', [
565
+ {
566
+ reaction,
567
+ key: content.reactionMessage?.key
568
+ }
569
+ ]);
570
+ }
571
+ else if (content?.encReactionMessage) {
572
+ const encReaction = content.encReactionMessage;
573
+ const targetKey = encReaction.targetMessageKey;
574
+ const fail = (reason) => ev.emit('messages.reaction-encrypted', { key: message.key, targetKey, reason });
575
+ const targetMsg = targetKey ? await getMessage(targetKey) : undefined;
576
+ if (!targetMsg) {
577
+ logger?.warn({ targetKey }, 'encrypted reaction: target message not found, cannot decrypt');
578
+ fail('target-message-not-found');
579
+ }
580
+ else {
581
+ try {
582
+ const meIdNormalised = jidNormalizedUser(meId);
583
+ const targetSenderJid = await resolveTargetAuthorPn(targetKey, meIdNormalised, signalRepository);
584
+ const reactorJid = getKeyAuthor(message.key, meIdNormalised);
585
+ const targetEncKey = targetMsg?.messageContextInfo?.messageSecret;
586
+ if (!targetEncKey) {
587
+ logger?.warn({ targetKey }, 'encrypted reaction: missing messageSecret for decryption');
588
+ fail('missing-message-secret');
589
+ }
590
+ else {
591
+ const reactionMsg = decryptEncReaction(encReaction, {
592
+ targetEncKey,
593
+ targetSenderJid,
594
+ targetMsgId: targetKey.id,
595
+ reactorJid
596
+ });
597
+ ev.emit('messages.reaction', [
598
+ {
599
+ reaction: { ...reactionMsg, key: message.key },
600
+ key: targetKey
601
+ }
602
+ ]);
603
+ }
604
+ }
605
+ catch (err) {
606
+ logger?.warn({ err, targetKey }, 'failed to decrypt encrypted reaction');
607
+ fail('decrypt-failed');
608
+ }
609
+ }
610
+ }
611
+ else if (content?.encEventResponseMessage) {
612
+ const encEventResponse = content.encEventResponseMessage;
613
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
614
+ // we need to fetch the event creation message to get the event enc key
615
+ const eventMsg = await getMessage(creationMsgKey);
616
+ if (eventMsg) {
617
+ try {
618
+ const meIdNormalised = jidNormalizedUser(meId);
619
+ // all jids need to be PN
620
+ const eventCreatorJid = await resolveTargetAuthorPn(creationMsgKey, meIdNormalised, signalRepository);
621
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
622
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
623
+ if (!eventEncKey) {
624
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
625
+ }
626
+ else {
627
+ const responseMsg = decryptEventResponse(encEventResponse, {
628
+ eventEncKey,
629
+ eventCreatorJid,
630
+ eventMsgId: creationMsgKey.id,
631
+ responderJid
632
+ });
633
+ const eventResponse = {
634
+ eventResponseMessageKey: message.key,
635
+ senderTimestampMs: responseMsg.timestampMs,
636
+ response: responseMsg
637
+ };
638
+ ev.emit('messages.update', [
639
+ {
640
+ key: creationMsgKey,
641
+ update: {
642
+ eventResponses: [eventResponse]
643
+ }
644
+ }
645
+ ]);
646
+ }
647
+ }
648
+ catch (err) {
649
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
650
+ }
651
+ }
652
+ else {
653
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
654
+ }
655
+ }
656
+ else if (content?.secretEncryptedMessage &&
657
+ content.secretEncryptedMessage.secretEncType === proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT) {
658
+ // E2EE message edit envelope (new in 2026-05). Replaces the older
659
+ // `protocolMessage.editedMessage` path for direct text edits.
660
+ // We fetch the target message to obtain its `messageSecret`, derive the
661
+ // decryption key, and surface the decoded inner Message via the same
662
+ // `messages.update` event used by the legacy edit path so consumers do
663
+ // not need a new event type.
664
+ const secEnc = content.secretEncryptedMessage;
665
+ const targetKey = secEnc.targetMessageKey;
666
+ const targetMsg = await getMessage(targetKey);
667
+ if (targetMsg) {
668
+ try {
669
+ const meIdNormalised = jidNormalizedUser(meId);
670
+ const origSenderRaw = targetKey.participant || targetKey.remoteJid;
671
+ const origSenderPn = isLidUser(origSenderRaw)
672
+ ? await signalRepository.lidMapping.getPNForLID(origSenderRaw)
673
+ : origSenderRaw;
674
+ const originalSenderJid = getKeyAuthor({ remoteJid: jidNormalizedUser(origSenderPn), fromMe: meIdNormalised === origSenderPn }, meIdNormalised);
675
+ const editorJid = getKeyAuthor(message.key, meIdNormalised);
676
+ const editEncKey = targetMsg?.messageContextInfo?.messageSecret;
677
+ if (!editEncKey) {
678
+ logger?.warn({ targetKey }, 'message edit: missing messageSecret on original message — cannot decrypt');
679
+ return;
680
+ }
681
+ const update = buildEditUpdate({
682
+ editEncKey,
683
+ encPayload: secEnc.encPayload,
684
+ encIv: secEnc.encIv,
685
+ originalSenderJid,
686
+ originalMsgId: targetKey.id,
687
+ editorJid,
688
+ messageKey: message.key,
689
+ targetKeyId: targetKey.id,
690
+ fallbackTimestamp: toNumber(message.messageTimestamp),
691
+ logger,
692
+ targetKey
693
+ });
694
+ if (update) {
695
+ ev.emit('messages.update', [update]);
696
+ }
697
+ }
698
+ catch (err) {
699
+ logger?.warn({ err, targetKey }, 'failed to decrypt secretEncryptedMessage MESSAGE_EDIT');
700
+ }
701
+ }
702
+ else {
703
+ logger?.warn({ targetKey }, 'original message not found in store, cannot decrypt secretEncryptedMessage edit');
704
+ }
705
+ }
706
+ else if (message.messageStubType) {
707
+ const jid = message.key?.remoteJid;
708
+ //let actor = whatsappID (message.participant)
709
+ let participants;
710
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
711
+ id: jid,
712
+ author: message.key.participant,
713
+ authorPn: message.key.participantAlt,
714
+ authorUsername: message.key.participantUsername,
715
+ participants,
716
+ action
717
+ });
718
+ const emitGroupUpdate = (update) => {
719
+ ev.emit('groups.update', [
720
+ {
721
+ id: jid,
722
+ ...update,
723
+ author: message.key.participant ?? undefined,
724
+ authorPn: message.key.participantAlt,
725
+ authorUsername: message.key.participantUsername
726
+ }
727
+ ]);
728
+ };
729
+ const emitGroupRequestJoin = (participant, action, method) => {
730
+ ev.emit('group.join-request', {
731
+ id: jid,
732
+ author: message.key.participant,
733
+ authorPn: message.key.participantAlt,
734
+ authorUsername: message.key.participantUsername,
735
+ participant: participant.lid,
736
+ participantPn: participant.pn,
737
+ action,
738
+ method: method
739
+ });
740
+ };
741
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
742
+ switch (message.messageStubType) {
743
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
744
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
745
+ emitParticipantsUpdate('modify');
746
+ break;
747
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
748
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
749
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
750
+ emitParticipantsUpdate('remove');
751
+ // mark the chat read only if you left the group
752
+ if (participantsIncludesMe()) {
753
+ chat.readOnly = true;
754
+ }
755
+ break;
756
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
757
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
758
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
759
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
760
+ if (participantsIncludesMe()) {
761
+ chat.readOnly = false;
762
+ }
763
+ emitParticipantsUpdate('add');
764
+ break;
765
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
766
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
767
+ emitParticipantsUpdate('demote');
768
+ break;
769
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
770
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
771
+ emitParticipantsUpdate('promote');
772
+ break;
773
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
774
+ const announceValue = message.messageStubParameters?.[0];
775
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
776
+ break;
777
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
778
+ const restrictValue = message.messageStubParameters?.[0];
779
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
780
+ break;
781
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
782
+ const name = message.messageStubParameters?.[0];
783
+ chat.name = name;
784
+ emitGroupUpdate({ subject: name });
785
+ break;
786
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
787
+ const description = message.messageStubParameters?.[0];
788
+ chat.description = description;
789
+ emitGroupUpdate({ desc: description });
790
+ break;
791
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
792
+ const code = message.messageStubParameters?.[0];
793
+ emitGroupUpdate({ inviteCode: code });
794
+ break;
795
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
796
+ const memberAddValue = message.messageStubParameters?.[0];
797
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
798
+ break;
799
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
800
+ const approvalMode = message.messageStubParameters?.[0];
801
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
802
+ break;
803
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
804
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
805
+ const action = message.messageStubParameters?.[1];
806
+ const method = message.messageStubParameters?.[2];
807
+ emitGroupRequestJoin(participant, action, method);
808
+ break;
809
+ case WAMessageStubType.GROUP_CHANGE_ICON:
810
+ emitGroupUpdate({ icon: message.messageStubParameters?.[0] });
811
+ break;
812
+ case WAMessageStubType.GROUP_CHANGE_NO_FREQUENTLY_FORWARDED:
813
+ emitGroupUpdate({ noFrequentlyForwarded: message.messageStubParameters?.[0] === 'on' });
814
+ break;
815
+ case WAMessageStubType.GROUP_V4_ADD_INVITE_SENT:
816
+ // notification that a v4 invite was sent — no group metadata change, but emit for plugin awareness
817
+ ev.emit('groups.update', [{ id: jid, v4AddInviteSent: true }]);
818
+ break;
819
+ case WAMessageStubType.GROUP_CHANGE_RECENT_HISTORY_SHARING:
820
+ emitGroupUpdate({ recentHistorySharing: message.messageStubParameters?.[0] === 'on' });
821
+ break;
822
+ case WAMessageStubType.GROUP_CREATE:
823
+ ev.emit('groups.upsert', [{ id: jid, subject: message.messageStubParameters?.[0] || '' }]);
824
+ break;
825
+ }
826
+ } else if (content?.pollUpdateMessage) {
827
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
828
+ const pollMsg = await getMessage(creationMsgKey);
829
+ if (pollMsg) {
830
+ const meIdNormalised = jidNormalizedUser(meId);
831
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised);
832
+ const voterJid = getKeyAuthor(message.key, meIdNormalised);
833
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret;
834
+ if (pollEncKey) {
835
+ try {
836
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
837
+ pollEncKey,
838
+ pollCreatorJid,
839
+ pollMsgId: creationMsgKey.id,
840
+ voterJid,
841
+ });
842
+ ev.emit('messages.update', [{
843
+ key: creationMsgKey,
844
+ update: {
845
+ pollUpdates: [{
846
+ pollUpdateMessageKey: message.key,
847
+ vote: voteMsg,
848
+ senderTimestampMs: typeof content.pollUpdateMessage.senderTimestampMs === 'object'
849
+ ? content.pollUpdateMessage.senderTimestampMs.toNumber()
850
+ : Number(content.pollUpdateMessage.senderTimestampMs),
851
+ }]
852
+ }
853
+ }]);
854
+ } catch (err) {
855
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
856
+ }
857
+ } else {
858
+ logger?.warn({ creationMsgKey }, 'poll message has no messageSecret — cannot decrypt vote');
859
+ }
860
+ } else {
861
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
862
+ }
863
+ }
864
+ if (Object.keys(chat).length > 1) {
865
+ ev.emit('chats.update', [chat]);
866
+ }
867
+ };
868
+ export default processMessage;