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