@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,885 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import { LabelAssociationType } from '../Types/LabelAssociation.js';
4
+ import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary/index.js';
5
+ import { aesDecrypt, aesEncrypt, hmacSign } from './crypto.js';
6
+ import { toNumber } from './generics.js';
7
+ import { LT_HASH_ANTI_TAMPERING } from './lt-hash.js';
8
+ import { downloadContentFromMessage } from './messages-media.js';
9
+ import { emitSyncActionResults, processContactAction } from './sync-action-utils.js';
10
+ // JAP@Fix (bug 36 follow-up): same top-level-await try/catch treatment as crypto.js and
11
+ // lt-hash.js — avoid crashing the whole library at import time if the whatsapp-rust-bridge
12
+ // native binary is missing on this platform (ARM musl/Alpine/Termux/some Pterodactyl nodes);
13
+ // only throw when app-state sync actually needs it. Kept synchronous (not async) because
14
+ // mutationKeys() is called synchronously throughout this file — making it async would be
15
+ // a breaking change for those call sites.
16
+ let expandAppStateKeys;
17
+ try {
18
+ ({ expandAppStateKeys } = await import('whatsapp-rust-bridge'));
19
+ }
20
+ catch (err) {
21
+ const message = '`whatsapp-rust-bridge` failed to load (no prebuilt binary for this platform/arch). ' +
22
+ 'App-state sync is unavailable here. Original error: ' + (err?.message || err);
23
+ expandAppStateKeys = () => { throw new Error(message); };
24
+ }
25
+ const mutationKeys = (keydata) => {
26
+ const keys = expandAppStateKeys(keydata);
27
+ return {
28
+ indexKey: keys.indexKey,
29
+ valueEncryptionKey: keys.valueEncryptionKey,
30
+ valueMacKey: keys.valueMacKey,
31
+ snapshotMacKey: keys.snapshotMacKey,
32
+ patchMacKey: keys.patchMacKey
33
+ };
34
+ };
35
+ const generateMac = (operation, data, keyId, key) => {
36
+ const opByte = operation === proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02;
37
+ const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId;
38
+ const keyData = new Uint8Array(1 + keyIdBuffer.length);
39
+ keyData[0] = opByte;
40
+ keyData.set(keyIdBuffer, 1);
41
+ const last = new Uint8Array(8);
42
+ last[7] = keyData.length;
43
+ const total = new Uint8Array(keyData.length + data.length + last.length);
44
+ total.set(keyData, 0);
45
+ total.set(data, keyData.length);
46
+ total.set(last, keyData.length + data.length);
47
+ const hmac = hmacSign(total, key, 'sha512');
48
+ return hmac.subarray(0, 32);
49
+ };
50
+ const to64BitNetworkOrder = (e) => {
51
+ const buff = Buffer.alloc(8);
52
+ buff.writeUint32BE(e, 4);
53
+ return buff;
54
+ };
55
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
56
+ indexValueMap = { ...indexValueMap };
57
+ const addBuffs = [];
58
+ const subBuffs = [];
59
+ return {
60
+ mix: ({ indexMac, valueMac, operation }) => {
61
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64');
62
+ const prevOp = indexValueMap[indexMacBase64];
63
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
64
+ if (!prevOp) {
65
+ // WA Web does not throw here — it logs a warning and skips the subtract.
66
+ // The missing REMOVE will cause an LTHash mismatch, which is handled
67
+ // by the MAC validation layer (snapshot recovery or retry).
68
+ return;
69
+ }
70
+ // remove from index value mac, since this mutation is erased
71
+ delete indexValueMap[indexMacBase64];
72
+ }
73
+ else {
74
+ addBuffs.push(valueMac);
75
+ // add this index into the history map
76
+ indexValueMap[indexMacBase64] = { valueMac };
77
+ }
78
+ if (prevOp) {
79
+ subBuffs.push(prevOp.valueMac);
80
+ }
81
+ },
82
+ finish: () => {
83
+ const result = LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs);
84
+ return {
85
+ hash: Buffer.from(result),
86
+ indexValueMap
87
+ };
88
+ }
89
+ };
90
+ };
91
+ const generateSnapshotMac = (lthash, version, name, key) => {
92
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
93
+ return hmacSign(total, key, 'sha256');
94
+ };
95
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
96
+ const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
97
+ return hmacSign(total, key);
98
+ };
99
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
100
+ export const ensureLTHashStateVersion = (state) => {
101
+ if (typeof state.version !== 'number' || isNaN(state.version)) {
102
+ state.version = 0;
103
+ }
104
+ return state;
105
+ };
106
+ export const MAX_SYNC_ATTEMPTS = 2;
107
+ /**
108
+ * Check if an error is a missing app state sync key.
109
+ * WA Web treats these as "Blocked" (waits for key arrival), not fatal.
110
+ * In Baileys we retry with a snapshot which may use a different key.
111
+ */
112
+ export const isMissingKeyError = (error) => {
113
+ return error?.data?.isMissingKey === true;
114
+ };
115
+ /**
116
+ * Determines if an app state sync error is unrecoverable.
117
+ * TypeError indicates a WASM crash; otherwise we give up after MAX_SYNC_ATTEMPTS.
118
+ * Missing keys are NOT checked here — they are handled separately as "Blocked".
119
+ */
120
+ export const isAppStateSyncIrrecoverable = (error, attempts) => {
121
+ return attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError';
122
+ };
123
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
124
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
125
+ if (!key) {
126
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } });
127
+ }
128
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
129
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
130
+ const indexBuffer = Buffer.from(JSON.stringify(index));
131
+ const dataProto = proto.SyncActionData.fromObject({
132
+ index: indexBuffer,
133
+ value: syncAction,
134
+ padding: new Uint8Array(0),
135
+ version: apiVersion
136
+ });
137
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
138
+ const keyValue = mutationKeys(key.keyData);
139
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
140
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
141
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
142
+ // update LT hash
143
+ const generator = makeLtHashGenerator(state);
144
+ generator.mix({ indexMac, valueMac, operation });
145
+ Object.assign(state, generator.finish());
146
+ state.version += 1;
147
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
148
+ const patch = {
149
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
150
+ snapshotMac: snapshotMac,
151
+ keyId: { id: encKeyId },
152
+ mutations: [
153
+ {
154
+ operation: operation,
155
+ record: {
156
+ index: {
157
+ blob: indexMac
158
+ },
159
+ value: {
160
+ blob: Buffer.concat([encValue, valueMac])
161
+ },
162
+ keyId: { id: encKeyId }
163
+ }
164
+ }
165
+ ]
166
+ };
167
+ const base64Index = indexMac.toString('base64');
168
+ state.indexValueMap[base64Index] = { valueMac };
169
+ return { patch, state };
170
+ };
171
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
172
+ const ltGenerator = makeLtHashGenerator(initialState);
173
+ const derivedKeyCache = new Map();
174
+ // indexKey used to HMAC sign record.index.blob
175
+ // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
176
+ // the remaining record.value.blob[0:-32] is the mac, it the HMAC sign of key.keyId + decoded proto data + length of bytes in keyId
177
+ for (const msgMutation of msgMutations) {
178
+ // if it's a syncdmutation, get the operation property
179
+ // otherwise, if it's only a record -- it'll be a SET mutation
180
+ const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
181
+ const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
182
+ let key;
183
+ try {
184
+ key = await getKey(record.keyId.id);
185
+ }
186
+ catch (err) {
187
+ // Missing-key errors must propagate so the orchestrator can park the
188
+ // collection (Blocked) and retry when APP_STATE_SYNC_KEY_SHARE arrives.
189
+ // Other errors → individual record corruption, skip and keep going.
190
+ if (isMissingKeyError(err))
191
+ throw err;
192
+ continue;
193
+ }
194
+ const content = record.value.blob;
195
+ const encContent = content.subarray(0, -32);
196
+ const ogValueMac = content.subarray(-32);
197
+ if (validateMacs) {
198
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
199
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
200
+ // HMAC verification failed — skip this record
201
+ continue;
202
+ }
203
+ }
204
+ let result;
205
+ try {
206
+ result = aesDecrypt(encContent, key.valueEncryptionKey);
207
+ }
208
+ catch {
209
+ // decrypt failed — skip this record instead of aborting
210
+ continue;
211
+ }
212
+ const syncAction = proto.SyncActionData.decode(result);
213
+ if (validateMacs) {
214
+ const hmac = hmacSign(syncAction.index, key.indexKey);
215
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
216
+ throw new Boom('HMAC index verification failed');
217
+ }
218
+ }
219
+ const indexStr = Buffer.from(syncAction.index).toString();
220
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
221
+ ltGenerator.mix({
222
+ indexMac: record.index.blob,
223
+ valueMac: ogValueMac,
224
+ operation: operation
225
+ });
226
+ }
227
+ return ltGenerator.finish();
228
+ async function getKey(keyId) {
229
+ const base64Key = Buffer.from(keyId).toString('base64');
230
+ const cached = derivedKeyCache.get(base64Key);
231
+ if (cached) {
232
+ return cached;
233
+ }
234
+ const keyEnc = await getAppStateSyncKey(base64Key);
235
+ if (!keyEnc) {
236
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
237
+ data: { isMissingKey: true, msgMutations }
238
+ });
239
+ }
240
+ const keys = mutationKeys(keyEnc.keyData);
241
+ derivedKeyCache.set(base64Key, keys);
242
+ return keys;
243
+ }
244
+ };
245
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
246
+ if (validateMacs) {
247
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64');
248
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
249
+ if (!mainKeyObj) {
250
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } });
251
+ }
252
+ const mainKey = mutationKeys(mainKeyObj.keyData);
253
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
254
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
255
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
256
+ throw new Boom('Invalid patch mac');
257
+ }
258
+ }
259
+ const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
260
+ return result;
261
+ };
262
+ export const extractSyncdPatches = async (result, options) => {
263
+ const syncNode = getBinaryNodeChild(result, 'sync');
264
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection');
265
+ const final = {};
266
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
267
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches');
268
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch');
269
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot');
270
+ const syncds = [];
271
+ const name = collectionNode.attrs.name;
272
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
273
+ let snapshot = undefined;
274
+ if (snapshotNode && !!snapshotNode.content) {
275
+ if (!Buffer.isBuffer(snapshotNode)) {
276
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
277
+ }
278
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content);
279
+ const data = await downloadExternalBlob(blobRef, options);
280
+ snapshot = proto.SyncdSnapshot.decode(data);
281
+ }
282
+ for (let { content } of patches) {
283
+ if (content) {
284
+ if (!Buffer.isBuffer(content)) {
285
+ content = Buffer.from(Object.values(content));
286
+ }
287
+ const syncd = proto.SyncdPatch.decode(content);
288
+ if (!syncd.version) {
289
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
290
+ }
291
+ syncds.push(syncd);
292
+ }
293
+ }
294
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
295
+ }));
296
+ return final;
297
+ };
298
+ export const downloadExternalBlob = async (blob, options) => {
299
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options });
300
+ const bufferArray = [];
301
+ for await (const chunk of stream) {
302
+ bufferArray.push(chunk);
303
+ }
304
+ return Buffer.concat(bufferArray);
305
+ };
306
+ export const downloadExternalPatch = async (blob, options) => {
307
+ const buffer = await downloadExternalBlob(blob, options);
308
+ const syncData = proto.SyncdMutations.decode(buffer);
309
+ return syncData;
310
+ };
311
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
312
+ const newState = newLTHashState();
313
+ newState.version = toNumber(snapshot.version.version);
314
+ const mutationMap = {};
315
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
316
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
317
+ ? mutation => {
318
+ const index = mutation.syncAction.index?.toString();
319
+ mutationMap[index] = mutation;
320
+ }
321
+ : () => { }, validateMacs);
322
+ newState.hash = hash;
323
+ newState.indexValueMap = indexValueMap;
324
+ if (validateMacs) {
325
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
326
+ const keyEnc = await getAppStateSyncKey(base64Key);
327
+ if (!keyEnc) {
328
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
329
+ }
330
+ const result = mutationKeys(keyEnc.keyData);
331
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
332
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
333
+ // LTHash verification may fail when decodeSyncdMutations skipped undecryptable
334
+ // records (poisoned server-side snapshot); the aggregate client hash diverges
335
+ // from the server-computed mac. Fall through with a warning so the session stays
336
+ // alive with partial state, symmetric to how decodePatches handles its own
337
+ // LTHash mismatch a few lines below.
338
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state');
339
+ }
340
+ }
341
+ return {
342
+ state: newState,
343
+ mutationMap
344
+ };
345
+ };
346
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
347
+ const newState = {
348
+ ...initial,
349
+ indexValueMap: { ...initial.indexValueMap }
350
+ };
351
+ const mutationMap = {};
352
+ for (const syncd of syncds) {
353
+ const { version, keyId, snapshotMac } = syncd;
354
+ if (syncd.externalMutations) {
355
+ logger?.trace({ name, version }, 'downloading external patch');
356
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
357
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
358
+ syncd.mutations?.push(...ref.mutations);
359
+ }
360
+ const patchVersion = toNumber(version.version);
361
+ newState.version = patchVersion;
362
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
363
+ let decodeResult;
364
+ try {
365
+ decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
366
+ ? mutation => {
367
+ const index = mutation.syncAction.index?.toString();
368
+ mutationMap[index] = mutation;
369
+ }
370
+ : () => { }, validateMacs);
371
+ }
372
+ catch (err) {
373
+ if (isMissingKeyError(err))
374
+ throw err;
375
+ logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping');
376
+ continue;
377
+ }
378
+ newState.hash = decodeResult.hash;
379
+ newState.indexValueMap = decodeResult.indexValueMap;
380
+ if (validateMacs) {
381
+ const base64Key = Buffer.from(keyId.id).toString('base64');
382
+ const keyEnc = await getAppStateSyncKey(base64Key);
383
+ if (!keyEnc) {
384
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } });
385
+ }
386
+ const result = mutationKeys(keyEnc.keyData);
387
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
388
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
389
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches');
390
+ break;
391
+ }
392
+ }
393
+ // clear memory used up by the mutations
394
+ syncd.mutations = [];
395
+ }
396
+ return { state: newState, mutationMap };
397
+ };
398
+ export const chatModificationToAppPatch = (mod, jid) => {
399
+ const OP = proto.SyncdMutation.SyncdOperation;
400
+ const getMessageRange = (lastMessages) => {
401
+ let messageRange;
402
+ if (Array.isArray(lastMessages)) {
403
+ const lastMsg = lastMessages[lastMessages.length - 1];
404
+ messageRange = {
405
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
406
+ messages: lastMessages?.length
407
+ ? lastMessages.map(m => {
408
+ if (!m.key?.id || !m.key?.remoteJid) {
409
+ throw new Boom('Incomplete key', { statusCode: 400, data: m });
410
+ }
411
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
412
+ throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
413
+ }
414
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
415
+ throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
416
+ }
417
+ if (m.key.participant) {
418
+ m.key.participant = jidNormalizedUser(m.key.participant);
419
+ }
420
+ return m;
421
+ })
422
+ : undefined
423
+ };
424
+ }
425
+ else {
426
+ messageRange = lastMessages;
427
+ }
428
+ return messageRange;
429
+ };
430
+ let patch;
431
+ if ('mute' in mod) {
432
+ patch = {
433
+ syncAction: {
434
+ muteAction: {
435
+ muted: !!mod.mute,
436
+ muteEndTimestamp: mod.mute || undefined
437
+ }
438
+ },
439
+ index: ['mute', jid],
440
+ type: 'regular_high',
441
+ apiVersion: 2,
442
+ operation: OP.SET
443
+ };
444
+ }
445
+ else if ('archive' in mod) {
446
+ patch = {
447
+ syncAction: {
448
+ archiveChatAction: {
449
+ archived: !!mod.archive,
450
+ messageRange: getMessageRange(mod.lastMessages)
451
+ }
452
+ },
453
+ index: ['archive', jid],
454
+ type: 'regular_low',
455
+ apiVersion: 3,
456
+ operation: OP.SET
457
+ };
458
+ }
459
+ else if ('markRead' in mod) {
460
+ patch = {
461
+ syncAction: {
462
+ markChatAsReadAction: {
463
+ read: mod.markRead,
464
+ messageRange: getMessageRange(mod.lastMessages)
465
+ }
466
+ },
467
+ index: ['markChatAsRead', jid],
468
+ type: 'regular_low',
469
+ apiVersion: 3,
470
+ operation: OP.SET
471
+ };
472
+ }
473
+ else if ('deleteForMe' in mod) {
474
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
475
+ patch = {
476
+ syncAction: {
477
+ deleteMessageForMeAction: {
478
+ deleteMedia,
479
+ messageTimestamp: timestamp
480
+ }
481
+ },
482
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
483
+ type: 'regular_high',
484
+ apiVersion: 3,
485
+ operation: OP.SET
486
+ };
487
+ }
488
+ else if ('clear' in mod) {
489
+ patch = {
490
+ syncAction: {
491
+ clearChatAction: {
492
+ messageRange: getMessageRange(mod.lastMessages)
493
+ }
494
+ },
495
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
496
+ type: 'regular_high',
497
+ apiVersion: 6,
498
+ operation: OP.SET
499
+ };
500
+ }
501
+ else if ('pin' in mod) {
502
+ patch = {
503
+ syncAction: {
504
+ pinAction: {
505
+ pinned: !!mod.pin
506
+ }
507
+ },
508
+ index: ['pin_v1', jid],
509
+ type: 'regular_low',
510
+ apiVersion: 5,
511
+ operation: OP.SET
512
+ };
513
+ }
514
+ else if ('contact' in mod) {
515
+ patch = {
516
+ syncAction: {
517
+ contactAction: mod.contact || {}
518
+ },
519
+ index: ['contact', jid],
520
+ type: 'critical_unblock_low',
521
+ apiVersion: 2,
522
+ operation: mod.contact ? OP.SET : OP.REMOVE
523
+ };
524
+ }
525
+ else if ('disableLinkPreviews' in mod) {
526
+ patch = {
527
+ syncAction: {
528
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
529
+ },
530
+ index: ['setting_disableLinkPreviews'],
531
+ type: 'regular',
532
+ apiVersion: 8,
533
+ operation: OP.SET
534
+ };
535
+ }
536
+ else if ('star' in mod) {
537
+ const key = mod.star.messages[0];
538
+ patch = {
539
+ syncAction: {
540
+ starAction: {
541
+ starred: !!mod.star.star
542
+ }
543
+ },
544
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
545
+ type: 'regular_low',
546
+ apiVersion: 2,
547
+ operation: OP.SET
548
+ };
549
+ }
550
+ else if ('delete' in mod) {
551
+ patch = {
552
+ syncAction: {
553
+ deleteChatAction: {
554
+ messageRange: getMessageRange(mod.lastMessages)
555
+ }
556
+ },
557
+ index: ['deleteChat', jid, '1'],
558
+ type: 'regular_high',
559
+ apiVersion: 6,
560
+ operation: OP.SET
561
+ };
562
+ }
563
+ else if ('pushNameSetting' in mod) {
564
+ patch = {
565
+ syncAction: {
566
+ pushNameSetting: {
567
+ name: mod.pushNameSetting
568
+ }
569
+ },
570
+ index: ['setting_pushName'],
571
+ type: 'critical_block',
572
+ apiVersion: 1,
573
+ operation: OP.SET
574
+ };
575
+ }
576
+ else if ('quickReply' in mod) {
577
+ patch = {
578
+ syncAction: {
579
+ quickReplyAction: {
580
+ count: 0,
581
+ deleted: mod.quickReply.deleted || false,
582
+ keywords: [],
583
+ message: mod.quickReply.message || '',
584
+ shortcut: mod.quickReply.shortcut || ''
585
+ }
586
+ },
587
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
588
+ type: 'regular',
589
+ apiVersion: 2,
590
+ operation: OP.SET
591
+ };
592
+ }
593
+ else if ('addLabel' in mod) {
594
+ patch = {
595
+ syncAction: {
596
+ labelEditAction: {
597
+ name: mod.addLabel.name,
598
+ color: mod.addLabel.color,
599
+ predefinedId: mod.addLabel.predefinedId,
600
+ deleted: mod.addLabel.deleted
601
+ }
602
+ },
603
+ index: ['label_edit', mod.addLabel.id],
604
+ type: 'regular',
605
+ apiVersion: 3,
606
+ operation: OP.SET
607
+ };
608
+ }
609
+ else if ('addChatLabel' in mod) {
610
+ patch = {
611
+ syncAction: {
612
+ labelAssociationAction: {
613
+ labeled: true
614
+ }
615
+ },
616
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
617
+ type: 'regular',
618
+ apiVersion: 3,
619
+ operation: OP.SET
620
+ };
621
+ }
622
+ else if ('removeChatLabel' in mod) {
623
+ patch = {
624
+ syncAction: {
625
+ labelAssociationAction: {
626
+ labeled: false
627
+ }
628
+ },
629
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
630
+ type: 'regular',
631
+ apiVersion: 3,
632
+ operation: OP.SET
633
+ };
634
+ }
635
+ else if ('addMessageLabel' in mod) {
636
+ patch = {
637
+ syncAction: {
638
+ labelAssociationAction: {
639
+ labeled: true
640
+ }
641
+ },
642
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
643
+ type: 'regular',
644
+ apiVersion: 3,
645
+ operation: OP.SET
646
+ };
647
+ }
648
+ else if ('removeMessageLabel' in mod) {
649
+ patch = {
650
+ syncAction: {
651
+ labelAssociationAction: {
652
+ labeled: false
653
+ }
654
+ },
655
+ index: [
656
+ LabelAssociationType.Message,
657
+ mod.removeMessageLabel.labelId,
658
+ jid,
659
+ mod.removeMessageLabel.messageId,
660
+ '0',
661
+ '0'
662
+ ],
663
+ type: 'regular',
664
+ apiVersion: 3,
665
+ operation: OP.SET
666
+ };
667
+ }
668
+ else {
669
+ throw new Boom('not supported');
670
+ }
671
+ patch.syncAction.timestamp = Date.now();
672
+ return patch;
673
+ };
674
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
675
+ const isInitialSync = !!initialSyncOpts;
676
+ const accountSettings = initialSyncOpts?.accountSettings;
677
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
678
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
679
+ if (action?.muteAction) {
680
+ ev.emit('chats.update', [
681
+ {
682
+ id,
683
+ muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
684
+ conditional: getChatUpdateConditional(id, undefined)
685
+ }
686
+ ]);
687
+ }
688
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
689
+ // okay so we've to do some annoying computation here
690
+ // when we're initially syncing the app state
691
+ // there are a few cases we need to handle
692
+ // 1. if the account unarchiveChats setting is true
693
+ // a. if the chat is archived, and no further messages have been received -- simple, keep archived
694
+ // b. if the chat was archived, and the user received messages from the other person afterwards
695
+ // then the chat should be marked unarchved --
696
+ // we compare the timestamp of latest message from the other person to determine this
697
+ // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
698
+ // it'll always take an app state action to mark in unarchived -- which we'll get anyway
699
+ const archiveAction = action?.archiveChatAction;
700
+ const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
701
+ // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
702
+ // // this only applies for the initial sync
703
+ // if(isInitialSync && !isArchived) {
704
+ // isArchived = false
705
+ // }
706
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
707
+ // logger?.debug({ chat: id, syncAction }, 'message range archive')
708
+ ev.emit('chats.update', [
709
+ {
710
+ id,
711
+ archived: isArchived,
712
+ conditional: getChatUpdateConditional(id, msgRange)
713
+ }
714
+ ]);
715
+ }
716
+ else if (action?.markChatAsReadAction) {
717
+ const markReadAction = action.markChatAsReadAction;
718
+ // basically we don't need to fire an "read" update if the chat is being marked as read
719
+ // because the chat is read by default
720
+ // this only applies for the initial sync
721
+ const isNullUpdate = isInitialSync && markReadAction.read;
722
+ ev.emit('chats.update', [
723
+ {
724
+ id,
725
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
726
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
727
+ }
728
+ ]);
729
+ }
730
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
731
+ ev.emit('messages.delete', {
732
+ keys: [
733
+ {
734
+ remoteJid: id,
735
+ id: msgId,
736
+ fromMe: fromMe === '1'
737
+ }
738
+ ]
739
+ });
740
+ }
741
+ else if (action?.contactAction) {
742
+ const results = processContactAction(action.contactAction, id, logger);
743
+ emitSyncActionResults(ev, results);
744
+ }
745
+ else if (action?.pushNameSetting) {
746
+ const name = action?.pushNameSetting?.name;
747
+ if (name && me?.name !== name) {
748
+ ev.emit('creds.update', { me: { ...me, name } });
749
+ }
750
+ }
751
+ else if (action?.pinAction) {
752
+ ev.emit('chats.update', [
753
+ {
754
+ id,
755
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
756
+ conditional: getChatUpdateConditional(id, undefined)
757
+ }
758
+ ]);
759
+ }
760
+ else if (action?.unarchiveChatsSetting) {
761
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
762
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } });
763
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
764
+ if (accountSettings) {
765
+ accountSettings.unarchiveChats = unarchiveChats;
766
+ }
767
+ }
768
+ else if (action?.starAction || type === 'star') {
769
+ let starred = action?.starAction?.starred;
770
+ if (typeof starred !== 'boolean') {
771
+ starred = syncAction.index[syncAction.index.length - 1] === '1';
772
+ }
773
+ ev.emit('messages.update', [
774
+ {
775
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
776
+ update: { starred }
777
+ }
778
+ ]);
779
+ }
780
+ else if (action?.deleteChatAction || type === 'deleteChat') {
781
+ if (!isInitialSync) {
782
+ ev.emit('chats.delete', [id]);
783
+ }
784
+ }
785
+ else if (action?.labelEditAction) {
786
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
787
+ ev.emit('labels.edit', {
788
+ id: id,
789
+ name: name,
790
+ color: color,
791
+ deleted: deleted,
792
+ predefinedId: predefinedId ? String(predefinedId) : undefined
793
+ });
794
+ }
795
+ else if (action?.labelAssociationAction) {
796
+ ev.emit('labels.association', {
797
+ type: action.labelAssociationAction.labeled ? 'add' : 'remove',
798
+ association: type === LabelAssociationType.Chat
799
+ ? {
800
+ type: LabelAssociationType.Chat,
801
+ chatId: syncAction.index[2],
802
+ labelId: syncAction.index[1]
803
+ }
804
+ : {
805
+ type: LabelAssociationType.Message,
806
+ chatId: syncAction.index[2],
807
+ messageId: syncAction.index[3],
808
+ labelId: syncAction.index[1]
809
+ }
810
+ });
811
+ }
812
+ else if (action?.localeSetting?.locale) {
813
+ ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale });
814
+ }
815
+ else if (action?.timeFormatAction) {
816
+ ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction });
817
+ }
818
+ else if (action?.pnForLidChatAction) {
819
+ if (action.pnForLidChatAction.pnJid) {
820
+ ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid });
821
+ }
822
+ }
823
+ else if (action?.privacySettingRelayAllCalls) {
824
+ ev.emit('settings.update', {
825
+ setting: 'privacySettingRelayAllCalls',
826
+ value: action.privacySettingRelayAllCalls
827
+ });
828
+ }
829
+ else if (action?.statusPrivacy) {
830
+ ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy });
831
+ }
832
+ else if (action?.lockChatAction) {
833
+ ev.emit('chats.lock', { id: id, locked: !!action.lockChatAction.locked });
834
+ }
835
+ else if (action?.privacySettingDisableLinkPreviewsAction) {
836
+ ev.emit('settings.update', {
837
+ setting: 'disableLinkPreviews',
838
+ value: action.privacySettingDisableLinkPreviewsAction
839
+ });
840
+ }
841
+ else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
842
+ ev.emit('settings.update', {
843
+ setting: 'notificationActivitySetting',
844
+ value: action.notificationActivitySettingAction.notificationActivitySetting
845
+ });
846
+ }
847
+ else if (action?.lidContactAction) {
848
+ ev.emit('contacts.upsert', [
849
+ {
850
+ id: id,
851
+ name: action.lidContactAction.fullName ||
852
+ action.lidContactAction.firstName ||
853
+ action.lidContactAction.username ||
854
+ undefined,
855
+ username: action.lidContactAction.username || undefined,
856
+ lid: id,
857
+ phoneNumber: undefined
858
+ }
859
+ ]);
860
+ }
861
+ else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
862
+ ev.emit('settings.update', {
863
+ setting: 'channelsPersonalisedRecommendation',
864
+ value: action.privacySettingChannelsPersonalisedRecommendationAction
865
+ });
866
+ }
867
+ else {
868
+ logger?.debug({ syncAction, id }, 'unprocessable update');
869
+ }
870
+ function getChatUpdateConditional(id, msgRange) {
871
+ return isInitialSync
872
+ ? data => {
873
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
874
+ if (chat) {
875
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
876
+ }
877
+ }
878
+ : undefined;
879
+ }
880
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
881
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
882
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
883
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
884
+ }
885
+ };