@onedevil405/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +4633 -0
  4. package/WAProto/fix-imports.js +29 -0
  5. package/WAProto/index.d.ts +10688 -0
  6. package/WAProto/index.js +37306 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.d.ts +58 -0
  9. package/lib/Defaults/index.d.ts.map +1 -0
  10. package/lib/Defaults/index.js +108 -0
  11. package/lib/Defaults/index.js.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  14. package/lib/Signal/Group/ciphertext-message.js +12 -0
  15. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  20. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  21. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  22. package/lib/Signal/Group/group_cipher.js +82 -0
  23. package/lib/Signal/Group/group_cipher.js.map +1 -0
  24. package/lib/Signal/Group/index.d.ts +12 -0
  25. package/lib/Signal/Group/index.d.ts.map +1 -0
  26. package/lib/Signal/Group/index.js +12 -0
  27. package/lib/Signal/Group/index.js.map +1 -0
  28. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  29. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  30. package/lib/Signal/Group/keyhelper.js +18 -0
  31. package/lib/Signal/Group/keyhelper.js.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.js +26 -0
  35. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.js +58 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.js +64 -0
  43. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.js +48 -0
  47. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.js +41 -0
  51. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.js +84 -0
  55. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  58. package/lib/Signal/Group/sender-message-key.js +26 -0
  59. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  60. package/lib/Signal/libsignal.d.ts +5 -0
  61. package/lib/Signal/libsignal.d.ts.map +1 -0
  62. package/lib/Signal/libsignal.js +345 -0
  63. package/lib/Signal/libsignal.js.map +1 -0
  64. package/lib/Signal/lid-mapping.d.ts +24 -0
  65. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  66. package/lib/Signal/lid-mapping.js +126 -0
  67. package/lib/Signal/lid-mapping.js.map +1 -0
  68. package/lib/Socket/Client/index.d.ts +3 -0
  69. package/lib/Socket/Client/index.d.ts.map +1 -0
  70. package/lib/Socket/Client/index.js +3 -0
  71. package/lib/Socket/Client/index.js.map +1 -0
  72. package/lib/Socket/Client/types.d.ts +16 -0
  73. package/lib/Socket/Client/types.d.ts.map +1 -0
  74. package/lib/Socket/Client/types.js +11 -0
  75. package/lib/Socket/Client/types.js.map +1 -0
  76. package/lib/Socket/Client/websocket.d.ts +13 -0
  77. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  78. package/lib/Socket/Client/websocket.js +50 -0
  79. package/lib/Socket/Client/websocket.js.map +1 -0
  80. package/lib/Socket/business.d.ts +188 -0
  81. package/lib/Socket/business.d.ts.map +1 -0
  82. package/lib/Socket/business.js +376 -0
  83. package/lib/Socket/business.js.map +1 -0
  84. package/lib/Socket/chats.d.ts +98 -0
  85. package/lib/Socket/chats.d.ts.map +1 -0
  86. package/lib/Socket/chats.js +959 -0
  87. package/lib/Socket/chats.js.map +1 -0
  88. package/lib/Socket/communities.d.ts +233 -0
  89. package/lib/Socket/communities.d.ts.map +1 -0
  90. package/lib/Socket/communities.js +395 -0
  91. package/lib/Socket/communities.js.map +1 -0
  92. package/lib/Socket/groups.d.ts +137 -0
  93. package/lib/Socket/groups.d.ts.map +1 -0
  94. package/lib/Socket/groups.js +325 -0
  95. package/lib/Socket/groups.js.map +1 -0
  96. package/lib/Socket/index.d.ts +220 -0
  97. package/lib/Socket/index.d.ts.map +1 -0
  98. package/lib/Socket/index.js +17 -0
  99. package/lib/Socket/index.js.map +1 -0
  100. package/lib/Socket/messages-recv.d.ts +173 -0
  101. package/lib/Socket/messages-recv.d.ts.map +1 -0
  102. package/lib/Socket/messages-recv.js +1229 -0
  103. package/lib/Socket/messages-recv.js.map +1 -0
  104. package/lib/Socket/messages-send.d.ts +169 -0
  105. package/lib/Socket/messages-send.d.ts.map +1 -0
  106. package/lib/Socket/messages-send.js +930 -0
  107. package/lib/Socket/messages-send.js.map +1 -0
  108. package/lib/Socket/mex.d.ts +3 -0
  109. package/lib/Socket/mex.d.ts.map +1 -0
  110. package/lib/Socket/mex.js +42 -0
  111. package/lib/Socket/mex.js.map +1 -0
  112. package/lib/Socket/newsletter.d.ts +147 -0
  113. package/lib/Socket/newsletter.d.ts.map +1 -0
  114. package/lib/Socket/newsletter.js +181 -0
  115. package/lib/Socket/newsletter.js.map +1 -0
  116. package/lib/Socket/socket.d.ts +50 -0
  117. package/lib/Socket/socket.d.ts.map +1 -0
  118. package/lib/Socket/socket.js +824 -0
  119. package/lib/Socket/socket.js.map +1 -0
  120. package/lib/Types/Auth.d.ts +106 -0
  121. package/lib/Types/Auth.d.ts.map +1 -0
  122. package/lib/Types/Auth.js +2 -0
  123. package/lib/Types/Auth.js.map +1 -0
  124. package/lib/Types/Bussines.d.ts +25 -0
  125. package/lib/Types/Bussines.d.ts.map +1 -0
  126. package/lib/Types/Bussines.js +2 -0
  127. package/lib/Types/Bussines.js.map +1 -0
  128. package/lib/Types/Call.d.ts +14 -0
  129. package/lib/Types/Call.d.ts.map +1 -0
  130. package/lib/Types/Call.js +2 -0
  131. package/lib/Types/Call.js.map +1 -0
  132. package/lib/Types/Chat.d.ts +123 -0
  133. package/lib/Types/Chat.d.ts.map +1 -0
  134. package/lib/Types/Chat.js +8 -0
  135. package/lib/Types/Chat.js.map +1 -0
  136. package/lib/Types/Contact.d.ts +24 -0
  137. package/lib/Types/Contact.d.ts.map +1 -0
  138. package/lib/Types/Contact.js +2 -0
  139. package/lib/Types/Contact.js.map +1 -0
  140. package/lib/Types/Events.d.ts +199 -0
  141. package/lib/Types/Events.d.ts.map +1 -0
  142. package/lib/Types/Events.js +2 -0
  143. package/lib/Types/Events.js.map +1 -0
  144. package/lib/Types/GroupMetadata.d.ts +66 -0
  145. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  146. package/lib/Types/GroupMetadata.js +2 -0
  147. package/lib/Types/GroupMetadata.js.map +1 -0
  148. package/lib/Types/Label.d.ts +47 -0
  149. package/lib/Types/Label.d.ts.map +1 -0
  150. package/lib/Types/Label.js +25 -0
  151. package/lib/Types/Label.js.map +1 -0
  152. package/lib/Types/LabelAssociation.d.ts +30 -0
  153. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  154. package/lib/Types/LabelAssociation.js +7 -0
  155. package/lib/Types/LabelAssociation.js.map +1 -0
  156. package/lib/Types/Message.d.ts +301 -0
  157. package/lib/Types/Message.d.ts.map +1 -0
  158. package/lib/Types/Message.js +11 -0
  159. package/lib/Types/Message.js.map +1 -0
  160. package/lib/Types/Newsletter.d.ts +135 -0
  161. package/lib/Types/Newsletter.d.ts.map +1 -0
  162. package/lib/Types/Newsletter.js +31 -0
  163. package/lib/Types/Newsletter.js.map +1 -0
  164. package/lib/Types/Product.d.ts +79 -0
  165. package/lib/Types/Product.d.ts.map +1 -0
  166. package/lib/Types/Product.js +2 -0
  167. package/lib/Types/Product.js.map +1 -0
  168. package/lib/Types/Signal.d.ts +76 -0
  169. package/lib/Types/Signal.d.ts.map +1 -0
  170. package/lib/Types/Signal.js +2 -0
  171. package/lib/Types/Signal.js.map +1 -0
  172. package/lib/Types/Socket.d.ts +138 -0
  173. package/lib/Types/Socket.d.ts.map +1 -0
  174. package/lib/Types/Socket.js +3 -0
  175. package/lib/Types/Socket.js.map +1 -0
  176. package/lib/Types/State.d.ts +39 -0
  177. package/lib/Types/State.d.ts.map +1 -0
  178. package/lib/Types/State.js +13 -0
  179. package/lib/Types/State.js.map +1 -0
  180. package/lib/Types/USync.d.ts +26 -0
  181. package/lib/Types/USync.d.ts.map +1 -0
  182. package/lib/Types/USync.js +2 -0
  183. package/lib/Types/USync.js.map +1 -0
  184. package/lib/Types/index.d.ts +65 -0
  185. package/lib/Types/index.d.ts.map +1 -0
  186. package/lib/Types/index.js +26 -0
  187. package/lib/Types/index.js.map +1 -0
  188. package/lib/Utils/auth-utils.d.ts +19 -0
  189. package/lib/Utils/auth-utils.d.ts.map +1 -0
  190. package/lib/Utils/auth-utils.js +474 -0
  191. package/lib/Utils/auth-utils.js.map +1 -0
  192. package/lib/Utils/baileys-event-stream.d.ts +17 -0
  193. package/lib/Utils/baileys-event-stream.d.ts.map +1 -0
  194. package/lib/Utils/baileys-event-stream.js +56 -0
  195. package/lib/Utils/baileys-event-stream.js.map +1 -0
  196. package/lib/Utils/browser-utils.d.ts +4 -0
  197. package/lib/Utils/browser-utils.d.ts.map +1 -0
  198. package/lib/Utils/browser-utils.js +28 -0
  199. package/lib/Utils/browser-utils.js.map +1 -0
  200. package/lib/Utils/business.d.ts +23 -0
  201. package/lib/Utils/business.d.ts.map +1 -0
  202. package/lib/Utils/business.js +231 -0
  203. package/lib/Utils/business.js.map +1 -0
  204. package/lib/Utils/chat-utils.d.ts +71 -0
  205. package/lib/Utils/chat-utils.d.ts.map +1 -0
  206. package/lib/Utils/chat-utils.js +764 -0
  207. package/lib/Utils/chat-utils.js.map +1 -0
  208. package/lib/Utils/crypto.d.ts +41 -0
  209. package/lib/Utils/crypto.d.ts.map +1 -0
  210. package/lib/Utils/crypto.js +142 -0
  211. package/lib/Utils/crypto.js.map +1 -0
  212. package/lib/Utils/decode-wa-message.d.ts +47 -0
  213. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  214. package/lib/Utils/decode-wa-message.js +269 -0
  215. package/lib/Utils/decode-wa-message.js.map +1 -0
  216. package/lib/Utils/event-buffer.d.ts +34 -0
  217. package/lib/Utils/event-buffer.d.ts.map +1 -0
  218. package/lib/Utils/event-buffer.js +547 -0
  219. package/lib/Utils/event-buffer.js.map +1 -0
  220. package/lib/Utils/generics.d.ts +91 -0
  221. package/lib/Utils/generics.d.ts.map +1 -0
  222. package/lib/Utils/generics.js +366 -0
  223. package/lib/Utils/generics.js.map +1 -0
  224. package/lib/Utils/history.d.ts +20 -0
  225. package/lib/Utils/history.d.ts.map +1 -0
  226. package/lib/Utils/history.js +85 -0
  227. package/lib/Utils/history.js.map +1 -0
  228. package/lib/Utils/index.d.ts +21 -0
  229. package/lib/Utils/index.d.ts.map +1 -0
  230. package/lib/Utils/index.js +21 -0
  231. package/lib/Utils/index.js.map +1 -0
  232. package/lib/Utils/link-preview.d.ts +22 -0
  233. package/lib/Utils/link-preview.d.ts.map +1 -0
  234. package/lib/Utils/link-preview.js +85 -0
  235. package/lib/Utils/link-preview.js.map +1 -0
  236. package/lib/Utils/logger.d.ts +12 -0
  237. package/lib/Utils/logger.d.ts.map +1 -0
  238. package/lib/Utils/logger.js +3 -0
  239. package/lib/Utils/logger.js.map +1 -0
  240. package/lib/Utils/lt-hash.d.ts +13 -0
  241. package/lib/Utils/lt-hash.d.ts.map +1 -0
  242. package/lib/Utils/lt-hash.js +48 -0
  243. package/lib/Utils/lt-hash.js.map +1 -0
  244. package/lib/Utils/make-mutex.d.ts +8 -0
  245. package/lib/Utils/make-mutex.d.ts.map +1 -0
  246. package/lib/Utils/make-mutex.js +40 -0
  247. package/lib/Utils/make-mutex.js.map +1 -0
  248. package/lib/Utils/message-retry-manager.d.ts +82 -0
  249. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  250. package/lib/Utils/message-retry-manager.js +149 -0
  251. package/lib/Utils/message-retry-manager.js.map +1 -0
  252. package/lib/Utils/messages-media.d.ts +113 -0
  253. package/lib/Utils/messages-media.d.ts.map +1 -0
  254. package/lib/Utils/messages-media.js +643 -0
  255. package/lib/Utils/messages-media.js.map +1 -0
  256. package/lib/Utils/messages.d.ts +76 -0
  257. package/lib/Utils/messages.d.ts.map +1 -0
  258. package/lib/Utils/messages.js +810 -0
  259. package/lib/Utils/messages.js.map +1 -0
  260. package/lib/Utils/noise-handler.d.ts +20 -0
  261. package/lib/Utils/noise-handler.d.ts.map +1 -0
  262. package/lib/Utils/noise-handler.js +147 -0
  263. package/lib/Utils/noise-handler.js.map +1 -0
  264. package/lib/Utils/process-message.d.ts +43 -0
  265. package/lib/Utils/process-message.d.ts.map +1 -0
  266. package/lib/Utils/process-message.js +384 -0
  267. package/lib/Utils/process-message.js.map +1 -0
  268. package/lib/Utils/proto-utils.d.ts +7 -0
  269. package/lib/Utils/proto-utils.d.ts.map +1 -0
  270. package/lib/Utils/proto-utils.js +7 -0
  271. package/lib/Utils/proto-utils.js.map +1 -0
  272. package/lib/Utils/signal.d.ts +34 -0
  273. package/lib/Utils/signal.d.ts.map +1 -0
  274. package/lib/Utils/signal.js +150 -0
  275. package/lib/Utils/signal.js.map +1 -0
  276. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  277. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  278. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  279. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  280. package/lib/Utils/validate-connection.d.ts +11 -0
  281. package/lib/Utils/validate-connection.d.ts.map +1 -0
  282. package/lib/Utils/validate-connection.js +166 -0
  283. package/lib/Utils/validate-connection.js.map +1 -0
  284. package/lib/WABinary/constants.d.ts +28 -0
  285. package/lib/WABinary/constants.d.ts.map +1 -0
  286. package/lib/WABinary/constants.js +1301 -0
  287. package/lib/WABinary/constants.js.map +1 -0
  288. package/lib/WABinary/decode.d.ts +7 -0
  289. package/lib/WABinary/decode.d.ts.map +1 -0
  290. package/lib/WABinary/decode.js +228 -0
  291. package/lib/WABinary/decode.js.map +1 -0
  292. package/lib/WABinary/encode.d.ts +3 -0
  293. package/lib/WABinary/encode.d.ts.map +1 -0
  294. package/lib/WABinary/encode.js +216 -0
  295. package/lib/WABinary/encode.js.map +1 -0
  296. package/lib/WABinary/generic-utils.d.ts +15 -0
  297. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  298. package/lib/WABinary/generic-utils.js +103 -0
  299. package/lib/WABinary/generic-utils.js.map +1 -0
  300. package/lib/WABinary/index.d.ts +6 -0
  301. package/lib/WABinary/index.d.ts.map +1 -0
  302. package/lib/WABinary/index.js +6 -0
  303. package/lib/WABinary/index.js.map +1 -0
  304. package/lib/WABinary/jid-utils.d.ts +37 -0
  305. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  306. package/lib/WABinary/jid-utils.js +58 -0
  307. package/lib/WABinary/jid-utils.js.map +1 -0
  308. package/lib/WABinary/types.d.ts +19 -0
  309. package/lib/WABinary/types.d.ts.map +1 -0
  310. package/lib/WABinary/types.js +2 -0
  311. package/lib/WABinary/types.js.map +1 -0
  312. package/lib/WAM/BinaryInfo.d.ts +9 -0
  313. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  314. package/lib/WAM/BinaryInfo.js +10 -0
  315. package/lib/WAM/BinaryInfo.js.map +1 -0
  316. package/lib/WAM/constants.d.ts +40 -0
  317. package/lib/WAM/constants.d.ts.map +1 -0
  318. package/lib/WAM/constants.js +15241 -0
  319. package/lib/WAM/constants.js.map +1 -0
  320. package/lib/WAM/encode.d.ts +3 -0
  321. package/lib/WAM/encode.d.ts.map +1 -0
  322. package/lib/WAM/encode.js +150 -0
  323. package/lib/WAM/encode.js.map +1 -0
  324. package/lib/WAM/index.d.ts +4 -0
  325. package/lib/WAM/index.d.ts.map +1 -0
  326. package/lib/WAM/index.js +4 -0
  327. package/lib/WAM/index.js.map +1 -0
  328. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  329. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  330. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  331. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  332. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  333. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  334. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  335. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  336. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  337. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  338. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  339. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  340. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  341. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  342. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  343. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  344. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  345. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  346. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  347. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  348. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  349. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  350. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  351. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  352. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  353. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  354. package/lib/WAUSync/Protocols/index.js +5 -0
  355. package/lib/WAUSync/Protocols/index.js.map +1 -0
  356. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  357. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  358. package/lib/WAUSync/USyncQuery.js +91 -0
  359. package/lib/WAUSync/USyncQuery.js.map +1 -0
  360. package/lib/WAUSync/USyncUser.d.ts +13 -0
  361. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  362. package/lib/WAUSync/USyncUser.js +23 -0
  363. package/lib/WAUSync/USyncUser.js.map +1 -0
  364. package/lib/WAUSync/index.d.ts +4 -0
  365. package/lib/WAUSync/index.d.ts.map +1 -0
  366. package/lib/WAUSync/index.js +4 -0
  367. package/lib/WAUSync/index.js.map +1 -0
  368. package/lib/index.d.ts +12 -0
  369. package/lib/index.d.ts.map +1 -0
  370. package/lib/index.js +11 -0
  371. package/lib/index.js.map +1 -0
  372. package/package.json +37 -0
@@ -0,0 +1,764 @@
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, hkdf, 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 { decodeAndHydrate } from './proto-utils.js';
10
+ const mutationKeys = async (keydata) => {
11
+ const expanded = await hkdf(keydata, 160, { info: 'WhatsApp Mutation Keys' });
12
+ return {
13
+ indexKey: expanded.slice(0, 32),
14
+ valueEncryptionKey: expanded.slice(32, 64),
15
+ valueMacKey: expanded.slice(64, 96),
16
+ snapshotMacKey: expanded.slice(96, 128),
17
+ patchMacKey: expanded.slice(128, 160)
18
+ };
19
+ };
20
+ const generateMac = (operation, data, keyId, key) => {
21
+ const getKeyData = () => {
22
+ let r;
23
+ switch (operation) {
24
+ case proto.SyncdMutation.SyncdOperation.SET:
25
+ r = 0x01;
26
+ break;
27
+ case proto.SyncdMutation.SyncdOperation.REMOVE:
28
+ r = 0x02;
29
+ break;
30
+ }
31
+ const buff = Buffer.from([r]);
32
+ return Buffer.concat([buff, Buffer.from(keyId, 'base64')]);
33
+ };
34
+ const keyData = getKeyData();
35
+ const last = Buffer.alloc(8); // 8 bytes
36
+ last.set([keyData.length], last.length - 1);
37
+ const total = Buffer.concat([keyData, data, last]);
38
+ const hmac = hmacSign(total, key, 'sha512');
39
+ return hmac.slice(0, 32);
40
+ };
41
+ const to64BitNetworkOrder = (e) => {
42
+ const buff = Buffer.alloc(8);
43
+ buff.writeUint32BE(e, 4);
44
+ return buff;
45
+ };
46
+ const makeLtHashGenerator = ({ indexValueMap, hash }) => {
47
+ indexValueMap = { ...indexValueMap };
48
+ const addBuffs = [];
49
+ const subBuffs = [];
50
+ return {
51
+ mix: ({ indexMac, valueMac, operation }) => {
52
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64');
53
+ const prevOp = indexValueMap[indexMacBase64];
54
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
55
+ if (!prevOp) {
56
+ throw new Boom('tried remove, but no previous op', { data: { indexMac, valueMac } });
57
+ }
58
+ // remove from index value mac, since this mutation is erased
59
+ delete indexValueMap[indexMacBase64];
60
+ }
61
+ else {
62
+ addBuffs.push(new Uint8Array(valueMac).buffer);
63
+ // add this index into the history map
64
+ indexValueMap[indexMacBase64] = { valueMac };
65
+ }
66
+ if (prevOp) {
67
+ subBuffs.push(new Uint8Array(prevOp.valueMac).buffer);
68
+ }
69
+ },
70
+ finish: async () => {
71
+ const hashArrayBuffer = new Uint8Array(hash).buffer;
72
+ const result = await LT_HASH_ANTI_TAMPERING.subtractThenAdd(hashArrayBuffer, addBuffs, subBuffs);
73
+ const buffer = Buffer.from(result);
74
+ return {
75
+ hash: buffer,
76
+ indexValueMap
77
+ };
78
+ }
79
+ };
80
+ };
81
+ const generateSnapshotMac = (lthash, version, name, key) => {
82
+ const total = Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]);
83
+ return hmacSign(total, key, 'sha256');
84
+ };
85
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => {
86
+ const total = Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]);
87
+ return hmacSign(total, key);
88
+ };
89
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} });
90
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
91
+ const key = !!myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined;
92
+ if (!key) {
93
+ throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { statusCode: 404 });
94
+ }
95
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64');
96
+ state = { ...state, indexValueMap: { ...state.indexValueMap } };
97
+ const indexBuffer = Buffer.from(JSON.stringify(index));
98
+ const dataProto = proto.SyncActionData.create({
99
+ index: indexBuffer,
100
+ value: syncAction,
101
+ padding: new Uint8Array(0),
102
+ version: apiVersion
103
+ });
104
+ const encoded = proto.SyncActionData.encode(dataProto).finish();
105
+ const keyValue = await mutationKeys(key.keyData);
106
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey);
107
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey);
108
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey);
109
+ // update LT hash
110
+ const generator = makeLtHashGenerator(state);
111
+ generator.mix({ indexMac, valueMac, operation });
112
+ Object.assign(state, await generator.finish());
113
+ state.version += 1;
114
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey);
115
+ const patch = {
116
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
117
+ snapshotMac: snapshotMac,
118
+ keyId: { id: encKeyId },
119
+ mutations: [
120
+ {
121
+ operation: operation,
122
+ record: {
123
+ index: {
124
+ blob: indexMac
125
+ },
126
+ value: {
127
+ blob: Buffer.concat([encValue, valueMac])
128
+ },
129
+ keyId: { id: encKeyId }
130
+ }
131
+ }
132
+ ]
133
+ };
134
+ const base64Index = indexMac.toString('base64');
135
+ state.indexValueMap[base64Index] = { valueMac };
136
+ return { patch, state };
137
+ };
138
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
139
+ const ltGenerator = makeLtHashGenerator(initialState);
140
+ // indexKey used to HMAC sign record.index.blob
141
+ // valueEncryptionKey used to AES-256-CBC encrypt record.value.blob[0:-32]
142
+ // 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
143
+ for (const msgMutation of msgMutations) {
144
+ // if it's a syncdmutation, get the operation property
145
+ // otherwise, if it's only a record -- it'll be a SET mutation
146
+ const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET;
147
+ const record = 'record' in msgMutation && !!msgMutation.record ? msgMutation.record : msgMutation;
148
+ const key = await getKey(record.keyId.id);
149
+ const content = Buffer.from(record.value.blob);
150
+ const encContent = content.slice(0, -32);
151
+ const ogValueMac = content.slice(-32);
152
+ if (validateMacs) {
153
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey);
154
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) {
155
+ throw new Boom('HMAC content verification failed');
156
+ }
157
+ }
158
+ const result = aesDecrypt(encContent, key.valueEncryptionKey);
159
+ const syncAction = decodeAndHydrate(proto.SyncActionData, result);
160
+ if (validateMacs) {
161
+ const hmac = hmacSign(syncAction.index, key.indexKey);
162
+ if (Buffer.compare(hmac, record.index.blob) !== 0) {
163
+ throw new Boom('HMAC index verification failed');
164
+ }
165
+ }
166
+ const indexStr = Buffer.from(syncAction.index).toString();
167
+ onMutation({ syncAction, index: JSON.parse(indexStr) });
168
+ ltGenerator.mix({
169
+ indexMac: record.index.blob,
170
+ valueMac: ogValueMac,
171
+ operation: operation
172
+ });
173
+ }
174
+ return await ltGenerator.finish();
175
+ async function getKey(keyId) {
176
+ const base64Key = Buffer.from(keyId).toString('base64');
177
+ const keyEnc = await getAppStateSyncKey(base64Key);
178
+ if (!keyEnc) {
179
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`, {
180
+ statusCode: 404,
181
+ data: { msgMutations }
182
+ });
183
+ }
184
+ return mutationKeys(keyEnc.keyData);
185
+ }
186
+ };
187
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
188
+ if (validateMacs) {
189
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64');
190
+ const mainKeyObj = await getAppStateSyncKey(base64Key);
191
+ if (!mainKeyObj) {
192
+ throw new Boom(`failed to find key "${base64Key}" to decode patch`, { statusCode: 404, data: { msg } });
193
+ }
194
+ const mainKey = await mutationKeys(mainKeyObj.keyData);
195
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32));
196
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey);
197
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) {
198
+ throw new Boom('Invalid patch mac');
199
+ }
200
+ }
201
+ const result = await decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs);
202
+ return result;
203
+ };
204
+ export const extractSyncdPatches = async (result, options) => {
205
+ const syncNode = getBinaryNodeChild(result, 'sync');
206
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection');
207
+ const final = {};
208
+ await Promise.all(collectionNodes.map(async (collectionNode) => {
209
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches');
210
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch');
211
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot');
212
+ const syncds = [];
213
+ const name = collectionNode.attrs.name;
214
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true';
215
+ let snapshot = undefined;
216
+ if (snapshotNode && !!snapshotNode.content) {
217
+ if (!Buffer.isBuffer(snapshotNode)) {
218
+ snapshotNode.content = Buffer.from(Object.values(snapshotNode.content));
219
+ }
220
+ const blobRef = decodeAndHydrate(proto.ExternalBlobReference, snapshotNode.content);
221
+ const data = await downloadExternalBlob(blobRef, options);
222
+ snapshot = decodeAndHydrate(proto.SyncdSnapshot, data);
223
+ }
224
+ for (let { content } of patches) {
225
+ if (content) {
226
+ if (!Buffer.isBuffer(content)) {
227
+ content = Buffer.from(Object.values(content));
228
+ }
229
+ const syncd = decodeAndHydrate(proto.SyncdPatch, content);
230
+ if (!syncd.version) {
231
+ syncd.version = { version: +collectionNode.attrs.version + 1 };
232
+ }
233
+ syncds.push(syncd);
234
+ }
235
+ }
236
+ final[name] = { patches: syncds, hasMorePatches, snapshot };
237
+ }));
238
+ return final;
239
+ };
240
+ export const downloadExternalBlob = async (blob, options) => {
241
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options });
242
+ const bufferArray = [];
243
+ for await (const chunk of stream) {
244
+ bufferArray.push(chunk);
245
+ }
246
+ return Buffer.concat(bufferArray);
247
+ };
248
+ export const downloadExternalPatch = async (blob, options) => {
249
+ const buffer = await downloadExternalBlob(blob, options);
250
+ const syncData = decodeAndHydrate(proto.SyncdMutations, buffer);
251
+ return syncData;
252
+ };
253
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true) => {
254
+ const newState = newLTHashState();
255
+ newState.version = toNumber(snapshot.version.version);
256
+ const mutationMap = {};
257
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber;
258
+ const { hash, indexValueMap } = await decodeSyncdMutations(snapshot.records, newState, getAppStateSyncKey, areMutationsRequired
259
+ ? mutation => {
260
+ const index = mutation.syncAction.index?.toString();
261
+ mutationMap[index] = mutation;
262
+ }
263
+ : () => { }, validateMacs);
264
+ newState.hash = hash;
265
+ newState.indexValueMap = indexValueMap;
266
+ if (validateMacs) {
267
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64');
268
+ const keyEnc = await getAppStateSyncKey(base64Key);
269
+ if (!keyEnc) {
270
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
271
+ }
272
+ const result = await mutationKeys(keyEnc.keyData);
273
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
274
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
275
+ throw new Boom(`failed to verify LTHash at ${newState.version} of ${name} from snapshot`);
276
+ }
277
+ }
278
+ return {
279
+ state: newState,
280
+ mutationMap
281
+ };
282
+ };
283
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
284
+ const newState = {
285
+ ...initial,
286
+ indexValueMap: { ...initial.indexValueMap }
287
+ };
288
+ const mutationMap = {};
289
+ for (const syncd of syncds) {
290
+ const { version, keyId, snapshotMac } = syncd;
291
+ if (syncd.externalMutations) {
292
+ logger?.trace({ name, version }, 'downloading external patch');
293
+ const ref = await downloadExternalPatch(syncd.externalMutations, options);
294
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch');
295
+ syncd.mutations?.push(...ref.mutations);
296
+ }
297
+ const patchVersion = toNumber(version.version);
298
+ newState.version = patchVersion;
299
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber;
300
+ const decodeResult = await decodeSyncdPatch(syncd, name, newState, getAppStateSyncKey, shouldMutate
301
+ ? mutation => {
302
+ const index = mutation.syncAction.index?.toString();
303
+ mutationMap[index] = mutation;
304
+ }
305
+ : () => { }, true);
306
+ newState.hash = decodeResult.hash;
307
+ newState.indexValueMap = decodeResult.indexValueMap;
308
+ if (validateMacs) {
309
+ const base64Key = Buffer.from(keyId.id).toString('base64');
310
+ const keyEnc = await getAppStateSyncKey(base64Key);
311
+ if (!keyEnc) {
312
+ throw new Boom(`failed to find key "${base64Key}" to decode mutation`);
313
+ }
314
+ const result = await mutationKeys(keyEnc.keyData);
315
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey);
316
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
317
+ throw new Boom(`failed to verify LTHash at ${newState.version} of ${name}`);
318
+ }
319
+ }
320
+ // clear memory used up by the mutations
321
+ syncd.mutations = [];
322
+ }
323
+ return { state: newState, mutationMap };
324
+ };
325
+ export const chatModificationToAppPatch = (mod, jid) => {
326
+ const OP = proto.SyncdMutation.SyncdOperation;
327
+ const getMessageRange = (lastMessages) => {
328
+ let messageRange;
329
+ if (Array.isArray(lastMessages)) {
330
+ const lastMsg = lastMessages[lastMessages.length - 1];
331
+ messageRange = {
332
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
333
+ messages: lastMessages?.length
334
+ ? lastMessages.map(m => {
335
+ if (!m.key?.id || !m.key?.remoteJid) {
336
+ throw new Boom('Incomplete key', { statusCode: 400, data: m });
337
+ }
338
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
339
+ throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m });
340
+ }
341
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) {
342
+ throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m });
343
+ }
344
+ if (m.key.participant) {
345
+ m.key.participant = jidNormalizedUser(m.key.participant);
346
+ }
347
+ return m;
348
+ })
349
+ : undefined
350
+ };
351
+ }
352
+ else {
353
+ messageRange = lastMessages;
354
+ }
355
+ return messageRange;
356
+ };
357
+ let patch;
358
+ if ('mute' in mod) {
359
+ patch = {
360
+ syncAction: {
361
+ muteAction: {
362
+ muted: !!mod.mute,
363
+ muteEndTimestamp: mod.mute || undefined
364
+ }
365
+ },
366
+ index: ['mute', jid],
367
+ type: 'regular_high',
368
+ apiVersion: 2,
369
+ operation: OP.SET
370
+ };
371
+ }
372
+ else if ('archive' in mod) {
373
+ patch = {
374
+ syncAction: {
375
+ archiveChatAction: {
376
+ archived: !!mod.archive,
377
+ messageRange: getMessageRange(mod.lastMessages)
378
+ }
379
+ },
380
+ index: ['archive', jid],
381
+ type: 'regular_low',
382
+ apiVersion: 3,
383
+ operation: OP.SET
384
+ };
385
+ }
386
+ else if ('markRead' in mod) {
387
+ patch = {
388
+ syncAction: {
389
+ markChatAsReadAction: {
390
+ read: mod.markRead,
391
+ messageRange: getMessageRange(mod.lastMessages)
392
+ }
393
+ },
394
+ index: ['markChatAsRead', jid],
395
+ type: 'regular_low',
396
+ apiVersion: 3,
397
+ operation: OP.SET
398
+ };
399
+ }
400
+ else if ('deleteForMe' in mod) {
401
+ const { timestamp, key, deleteMedia } = mod.deleteForMe;
402
+ patch = {
403
+ syncAction: {
404
+ deleteMessageForMeAction: {
405
+ deleteMedia,
406
+ messageTimestamp: timestamp
407
+ }
408
+ },
409
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
410
+ type: 'regular_high',
411
+ apiVersion: 3,
412
+ operation: OP.SET
413
+ };
414
+ }
415
+ else if ('clear' in mod) {
416
+ patch = {
417
+ syncAction: {
418
+ clearChatAction: {
419
+ messageRange: getMessageRange(mod.lastMessages)
420
+ }
421
+ },
422
+ index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
423
+ type: 'regular_high',
424
+ apiVersion: 6,
425
+ operation: OP.SET
426
+ };
427
+ }
428
+ else if ('pin' in mod) {
429
+ patch = {
430
+ syncAction: {
431
+ pinAction: {
432
+ pinned: !!mod.pin
433
+ }
434
+ },
435
+ index: ['pin_v1', jid],
436
+ type: 'regular_low',
437
+ apiVersion: 5,
438
+ operation: OP.SET
439
+ };
440
+ }
441
+ else if ('contact' in mod) {
442
+ patch = {
443
+ syncAction: {
444
+ contactAction: mod.contact || {}
445
+ },
446
+ index: ['contact', jid],
447
+ type: 'critical_unblock_low',
448
+ apiVersion: 2,
449
+ operation: mod.contact ? OP.SET : OP.REMOVE
450
+ };
451
+ }
452
+ else if ('disableLinkPreviews' in mod) {
453
+ patch = {
454
+ syncAction: {
455
+ privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {}
456
+ },
457
+ index: ['setting_disableLinkPreviews'],
458
+ type: 'regular',
459
+ apiVersion: 8,
460
+ operation: OP.SET
461
+ };
462
+ }
463
+ else if ('star' in mod) {
464
+ const key = mod.star.messages[0];
465
+ patch = {
466
+ syncAction: {
467
+ starAction: {
468
+ starred: !!mod.star.star
469
+ }
470
+ },
471
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
472
+ type: 'regular_low',
473
+ apiVersion: 2,
474
+ operation: OP.SET
475
+ };
476
+ }
477
+ else if ('delete' in mod) {
478
+ patch = {
479
+ syncAction: {
480
+ deleteChatAction: {
481
+ messageRange: getMessageRange(mod.lastMessages)
482
+ }
483
+ },
484
+ index: ['deleteChat', jid, '1'],
485
+ type: 'regular_high',
486
+ apiVersion: 6,
487
+ operation: OP.SET
488
+ };
489
+ }
490
+ else if ('pushNameSetting' in mod) {
491
+ patch = {
492
+ syncAction: {
493
+ pushNameSetting: {
494
+ name: mod.pushNameSetting
495
+ }
496
+ },
497
+ index: ['setting_pushName'],
498
+ type: 'critical_block',
499
+ apiVersion: 1,
500
+ operation: OP.SET
501
+ };
502
+ }
503
+ else if ('quickReply' in mod) {
504
+ patch = {
505
+ syncAction: {
506
+ quickReplyAction: {
507
+ count: 0,
508
+ deleted: mod.quickReply.deleted || false,
509
+ keywords: [],
510
+ message: mod.quickReply.message || '',
511
+ shortcut: mod.quickReply.shortcut || ''
512
+ }
513
+ },
514
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
515
+ type: 'regular',
516
+ apiVersion: 2,
517
+ operation: OP.SET
518
+ };
519
+ }
520
+ else if ('addLabel' in mod) {
521
+ patch = {
522
+ syncAction: {
523
+ labelEditAction: {
524
+ name: mod.addLabel.name,
525
+ color: mod.addLabel.color,
526
+ predefinedId: mod.addLabel.predefinedId,
527
+ deleted: mod.addLabel.deleted
528
+ }
529
+ },
530
+ index: ['label_edit', mod.addLabel.id],
531
+ type: 'regular',
532
+ apiVersion: 3,
533
+ operation: OP.SET
534
+ };
535
+ }
536
+ else if ('addChatLabel' in mod) {
537
+ patch = {
538
+ syncAction: {
539
+ labelAssociationAction: {
540
+ labeled: true
541
+ }
542
+ },
543
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
544
+ type: 'regular',
545
+ apiVersion: 3,
546
+ operation: OP.SET
547
+ };
548
+ }
549
+ else if ('removeChatLabel' in mod) {
550
+ patch = {
551
+ syncAction: {
552
+ labelAssociationAction: {
553
+ labeled: false
554
+ }
555
+ },
556
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
557
+ type: 'regular',
558
+ apiVersion: 3,
559
+ operation: OP.SET
560
+ };
561
+ }
562
+ else if ('addMessageLabel' in mod) {
563
+ patch = {
564
+ syncAction: {
565
+ labelAssociationAction: {
566
+ labeled: true
567
+ }
568
+ },
569
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
570
+ type: 'regular',
571
+ apiVersion: 3,
572
+ operation: OP.SET
573
+ };
574
+ }
575
+ else if ('removeMessageLabel' in mod) {
576
+ patch = {
577
+ syncAction: {
578
+ labelAssociationAction: {
579
+ labeled: false
580
+ }
581
+ },
582
+ index: [
583
+ LabelAssociationType.Message,
584
+ mod.removeMessageLabel.labelId,
585
+ jid,
586
+ mod.removeMessageLabel.messageId,
587
+ '0',
588
+ '0'
589
+ ],
590
+ type: 'regular',
591
+ apiVersion: 3,
592
+ operation: OP.SET
593
+ };
594
+ }
595
+ else {
596
+ throw new Boom('not supported');
597
+ }
598
+ patch.syncAction.timestamp = Date.now();
599
+ return patch;
600
+ };
601
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
602
+ const isInitialSync = !!initialSyncOpts;
603
+ const accountSettings = initialSyncOpts?.accountSettings;
604
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action');
605
+ const { syncAction: { value: action }, index: [type, id, msgId, fromMe] } = syncAction;
606
+ if (action?.muteAction) {
607
+ ev.emit('chats.update', [
608
+ {
609
+ id,
610
+ muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null,
611
+ conditional: getChatUpdateConditional(id, undefined)
612
+ }
613
+ ]);
614
+ }
615
+ else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
616
+ // okay so we've to do some annoying computation here
617
+ // when we're initially syncing the app state
618
+ // there are a few cases we need to handle
619
+ // 1. if the account unarchiveChats setting is true
620
+ // a. if the chat is archived, and no further messages have been received -- simple, keep archived
621
+ // b. if the chat was archived, and the user received messages from the other person afterwards
622
+ // then the chat should be marked unarchved --
623
+ // we compare the timestamp of latest message from the other person to determine this
624
+ // 2. if the account unarchiveChats setting is false -- then it doesn't matter,
625
+ // it'll always take an app state action to mark in unarchived -- which we'll get anyway
626
+ const archiveAction = action?.archiveChatAction;
627
+ const isArchived = archiveAction ? archiveAction.archived : type === 'archive';
628
+ // // basically we don't need to fire an "archive" update if the chat is being marked unarchvied
629
+ // // this only applies for the initial sync
630
+ // if(isInitialSync && !isArchived) {
631
+ // isArchived = false
632
+ // }
633
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange;
634
+ // logger?.debug({ chat: id, syncAction }, 'message range archive')
635
+ ev.emit('chats.update', [
636
+ {
637
+ id,
638
+ archived: isArchived,
639
+ conditional: getChatUpdateConditional(id, msgRange)
640
+ }
641
+ ]);
642
+ }
643
+ else if (action?.markChatAsReadAction) {
644
+ const markReadAction = action.markChatAsReadAction;
645
+ // basically we don't need to fire an "read" update if the chat is being marked as read
646
+ // because the chat is read by default
647
+ // this only applies for the initial sync
648
+ const isNullUpdate = isInitialSync && markReadAction.read;
649
+ ev.emit('chats.update', [
650
+ {
651
+ id,
652
+ unreadCount: isNullUpdate ? null : !!markReadAction?.read ? 0 : -1,
653
+ conditional: getChatUpdateConditional(id, markReadAction?.messageRange)
654
+ }
655
+ ]);
656
+ }
657
+ else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
658
+ ev.emit('messages.delete', {
659
+ keys: [
660
+ {
661
+ remoteJid: id,
662
+ id: msgId,
663
+ fromMe: fromMe === '1'
664
+ }
665
+ ]
666
+ });
667
+ }
668
+ else if (action?.contactAction) {
669
+ ev.emit('contacts.upsert', [
670
+ {
671
+ id: id,
672
+ name: action.contactAction.fullName,
673
+ lid: action.contactAction.lidJid || undefined,
674
+ phoneNumber: action.contactAction.pnJid || undefined
675
+ }
676
+ ]);
677
+ }
678
+ else if (action?.pushNameSetting) {
679
+ const name = action?.pushNameSetting?.name;
680
+ if (name && me?.name !== name) {
681
+ ev.emit('creds.update', { me: { ...me, name } });
682
+ }
683
+ }
684
+ else if (action?.pinAction) {
685
+ ev.emit('chats.update', [
686
+ {
687
+ id,
688
+ pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null,
689
+ conditional: getChatUpdateConditional(id, undefined)
690
+ }
691
+ ]);
692
+ }
693
+ else if (action?.unarchiveChatsSetting) {
694
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats;
695
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } });
696
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`);
697
+ if (accountSettings) {
698
+ accountSettings.unarchiveChats = unarchiveChats;
699
+ }
700
+ }
701
+ else if (action?.starAction || type === 'star') {
702
+ let starred = action?.starAction?.starred;
703
+ if (typeof starred !== 'boolean') {
704
+ starred = syncAction.index[syncAction.index.length - 1] === '1';
705
+ }
706
+ ev.emit('messages.update', [
707
+ {
708
+ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' },
709
+ update: { starred }
710
+ }
711
+ ]);
712
+ }
713
+ else if (action?.deleteChatAction || type === 'deleteChat') {
714
+ if (!isInitialSync) {
715
+ ev.emit('chats.delete', [id]);
716
+ }
717
+ }
718
+ else if (action?.labelEditAction) {
719
+ const { name, color, deleted, predefinedId } = action.labelEditAction;
720
+ ev.emit('labels.edit', {
721
+ id: id,
722
+ name: name,
723
+ color: color,
724
+ deleted: deleted,
725
+ predefinedId: predefinedId ? String(predefinedId) : undefined
726
+ });
727
+ }
728
+ else if (action?.labelAssociationAction) {
729
+ ev.emit('labels.association', {
730
+ type: action.labelAssociationAction.labeled ? 'add' : 'remove',
731
+ association: type === LabelAssociationType.Chat
732
+ ? {
733
+ type: LabelAssociationType.Chat,
734
+ chatId: syncAction.index[2],
735
+ labelId: syncAction.index[1]
736
+ }
737
+ : {
738
+ type: LabelAssociationType.Message,
739
+ chatId: syncAction.index[2],
740
+ messageId: syncAction.index[3],
741
+ labelId: syncAction.index[1]
742
+ }
743
+ });
744
+ }
745
+ else {
746
+ logger?.debug({ syncAction, id }, 'unprocessable update');
747
+ }
748
+ function getChatUpdateConditional(id, msgRange) {
749
+ return isInitialSync
750
+ ? data => {
751
+ const chat = data.historySets.chats[id] || data.chatUpserts[id];
752
+ if (chat) {
753
+ return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true;
754
+ }
755
+ }
756
+ : undefined;
757
+ }
758
+ function isValidPatchBasedOnMessageRange(chat, msgRange) {
759
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0);
760
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0);
761
+ return lastMsgTimestamp >= chatLastMsgTimestamp;
762
+ }
763
+ };
764
+ //# sourceMappingURL=chat-utils.js.map