@modzneverdie/baileys 17.1.2 → 17.1.3

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6035 -0
  4. package/WAProto/fix-imports.js +81 -0
  5. package/WAProto/index.d.ts +2 -0
  6. package/WAProto/index.js +59469 -96804
  7. package/lib/Defaults/index.d.ts +29 -8
  8. package/lib/Defaults/index.d.ts.map +1 -0
  9. package/lib/Defaults/index.js +134 -141
  10. package/lib/Defaults/index.js.map +1 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.js +2 -5
  14. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +4 -3
  16. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.js +7 -41
  18. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  20. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  21. package/lib/Signal/Group/group_cipher.js +37 -51
  22. package/lib/Signal/Group/group_cipher.js.map +1 -0
  23. package/lib/Signal/Group/index.d.ts +12 -11
  24. package/lib/Signal/Group/index.d.ts.map +1 -0
  25. package/lib/Signal/Group/index.js +12 -57
  26. package/lib/Signal/Group/index.js.map +1 -0
  27. package/lib/Signal/Group/keyhelper.d.ts +2 -1
  28. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  29. package/lib/Signal/Group/keyhelper.js +7 -44
  30. package/lib/Signal/Group/keyhelper.js.map +1 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts +3 -2
  32. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.js +7 -15
  34. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts +2 -1
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  38. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts +2 -1
  40. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.js +9 -12
  42. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.js +2 -5
  46. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts +3 -2
  48. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.js +9 -21
  50. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts +7 -6
  52. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.js +27 -42
  54. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.js +4 -7
  58. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  59. package/lib/Signal/libsignal.d.ts +5 -3
  60. package/lib/Signal/libsignal.d.ts.map +1 -0
  61. package/lib/Signal/libsignal.js +319 -90
  62. package/lib/Signal/libsignal.js.map +1 -0
  63. package/lib/Signal/lid-mapping.d.ts +19 -0
  64. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  65. package/lib/Signal/lid-mapping.js +271 -0
  66. package/lib/Signal/lid-mapping.js.map +1 -0
  67. package/lib/Socket/Client/index.d.ts +3 -3
  68. package/lib/Socket/Client/index.d.ts.map +1 -0
  69. package/lib/Socket/Client/index.js +3 -19
  70. package/lib/Socket/Client/index.js.map +1 -0
  71. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +4 -5
  72. package/lib/Socket/Client/types.d.ts.map +1 -0
  73. package/lib/Socket/Client/types.js +11 -0
  74. package/lib/Socket/Client/types.js.map +1 -0
  75. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +3 -2
  76. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  77. package/lib/Socket/Client/websocket.js +54 -0
  78. package/lib/Socket/Client/websocket.js.map +1 -0
  79. package/lib/Socket/business.d.ts +533 -168
  80. package/lib/Socket/business.d.ts.map +1 -0
  81. package/lib/Socket/business.js +405 -243
  82. package/lib/Socket/business.js.map +1 -0
  83. package/lib/Socket/chats.d.ts +84 -240
  84. package/lib/Socket/chats.d.ts.map +1 -0
  85. package/lib/Socket/chats.js +406 -385
  86. package/lib/Socket/chats.js.map +1 -0
  87. package/lib/Socket/communities.d.ts +645 -0
  88. package/lib/Socket/communities.d.ts.map +1 -0
  89. package/lib/Socket/communities.js +431 -0
  90. package/lib/Socket/communities.js.map +1 -0
  91. package/lib/Socket/dugong.d.ts +125 -249
  92. package/lib/Socket/dugong.d.ts.map +1 -0
  93. package/lib/Socket/dugong.js +749 -465
  94. package/lib/Socket/dugong.js.map +1 -0
  95. package/lib/Socket/groups.d.ts +93 -58
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +105 -95
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +632 -169
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +15 -11
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +162 -85
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +806 -608
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +576 -146
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1563 -861
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +48 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +129 -86
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +438 -297
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +31 -19
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +512 -241
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Types/Auth.d.ts +18 -12
  124. package/lib/Types/Auth.d.ts.map +1 -0
  125. package/lib/Types/Auth.js +2 -2
  126. package/lib/Types/Auth.js.map +1 -0
  127. package/lib/Types/Bussines.d.ts +37 -0
  128. package/lib/Types/Bussines.d.ts.map +1 -0
  129. package/lib/Types/Bussines.js +2 -0
  130. package/lib/Types/Bussines.js.map +1 -0
  131. package/lib/Types/Call.d.ts +3 -1
  132. package/lib/Types/Call.d.ts.map +1 -0
  133. package/lib/Types/Call.js +2 -2
  134. package/lib/Types/Call.js.map +1 -0
  135. package/lib/Types/Chat.d.ts +34 -13
  136. package/lib/Types/Chat.d.ts.map +1 -0
  137. package/lib/Types/Chat.js +8 -4
  138. package/lib/Types/Chat.js.map +1 -0
  139. package/lib/Types/Contact.d.ts +6 -1
  140. package/lib/Types/Contact.d.ts.map +1 -0
  141. package/lib/Types/Contact.js +2 -2
  142. package/lib/Types/Contact.js.map +1 -0
  143. package/lib/Types/Events.d.ts +97 -17
  144. package/lib/Types/Events.d.ts.map +1 -0
  145. package/lib/Types/Events.js +2 -2
  146. package/lib/Types/Events.js.map +1 -0
  147. package/lib/Types/GroupMetadata.d.ts +18 -5
  148. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  149. package/lib/Types/GroupMetadata.js +2 -2
  150. package/lib/Types/GroupMetadata.js.map +1 -0
  151. package/lib/Types/Label.d.ts +12 -0
  152. package/lib/Types/Label.d.ts.map +1 -0
  153. package/lib/Types/Label.js +3 -5
  154. package/lib/Types/Label.js.map +1 -0
  155. package/lib/Types/LabelAssociation.d.ts +1 -0
  156. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  157. package/lib/Types/LabelAssociation.js +3 -5
  158. package/lib/Types/LabelAssociation.js.map +1 -0
  159. package/lib/Types/Message.d.ts +355 -206
  160. package/lib/Types/Message.d.ts.map +1 -0
  161. package/lib/Types/Message.js +11 -9
  162. package/lib/Types/Message.js.map +1 -0
  163. package/lib/Types/Newsletter.d.ts +130 -98
  164. package/lib/Types/Newsletter.d.ts.map +1 -0
  165. package/lib/Types/Newsletter.js +31 -38
  166. package/lib/Types/Newsletter.js.map +1 -0
  167. package/lib/Types/Product.d.ts +2 -1
  168. package/lib/Types/Product.d.ts.map +1 -0
  169. package/lib/Types/Product.js +2 -2
  170. package/lib/Types/Product.js.map +1 -0
  171. package/lib/Types/Signal.d.ts +20 -1
  172. package/lib/Types/Signal.d.ts.map +1 -0
  173. package/lib/Types/Signal.js +2 -2
  174. package/lib/Types/Signal.js.map +1 -0
  175. package/lib/Types/Socket.d.ts +152 -105
  176. package/lib/Types/Socket.d.ts.map +1 -0
  177. package/lib/Types/Socket.js +3 -2
  178. package/lib/Types/Socket.js.map +1 -0
  179. package/lib/Types/State.d.ts +14 -2
  180. package/lib/Types/State.d.ts.map +1 -0
  181. package/lib/Types/State.js +13 -2
  182. package/lib/Types/State.js.map +1 -0
  183. package/lib/Types/USync.d.ts +3 -2
  184. package/lib/Types/USync.d.ts.map +1 -0
  185. package/lib/Types/USync.js +2 -2
  186. package/lib/Types/USync.js.map +1 -0
  187. package/lib/Types/index.d.ts +54 -45
  188. package/lib/Types/index.d.ts.map +1 -0
  189. package/lib/Types/index.js +32 -41
  190. package/lib/Types/index.js.map +1 -0
  191. package/lib/Utils/auth-utils.d.ts +7 -6
  192. package/lib/Utils/auth-utils.d.ts.map +1 -0
  193. package/lib/Utils/auth-utils.js +228 -144
  194. package/lib/Utils/auth-utils.js.map +1 -0
  195. package/lib/Utils/browser-utils.d.ts +4 -0
  196. package/lib/Utils/browser-utils.d.ts.map +1 -0
  197. package/lib/Utils/browser-utils.js +28 -0
  198. package/lib/Utils/browser-utils.js.map +1 -0
  199. package/lib/Utils/business.d.ts +3 -2
  200. package/lib/Utils/business.d.ts.map +1 -0
  201. package/lib/Utils/business.js +66 -69
  202. package/lib/Utils/business.js.map +1 -0
  203. package/lib/Utils/chat-utils.d.ts +19 -20
  204. package/lib/Utils/chat-utils.d.ts.map +1 -0
  205. package/lib/Utils/chat-utils.js +331 -248
  206. package/lib/Utils/chat-utils.js.map +1 -0
  207. package/lib/Utils/crypto.d.ts +10 -14
  208. package/lib/Utils/crypto.d.ts.map +1 -0
  209. package/lib/Utils/crypto.js +57 -90
  210. package/lib/Utils/crypto.js.map +1 -0
  211. package/lib/Utils/decode-wa-message.d.ts +37 -8
  212. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  213. package/lib/Utils/decode-wa-message.js +169 -84
  214. package/lib/Utils/decode-wa-message.js.map +1 -0
  215. package/lib/Utils/event-buffer.d.ts +7 -8
  216. package/lib/Utils/event-buffer.d.ts.map +1 -0
  217. package/lib/Utils/event-buffer.js +138 -78
  218. package/lib/Utils/event-buffer.js.map +1 -0
  219. package/lib/Utils/generics.d.ts +26 -27
  220. package/lib/Utils/generics.d.ts.map +1 -0
  221. package/lib/Utils/generics.js +170 -209
  222. package/lib/Utils/generics.js.map +1 -0
  223. package/lib/Utils/history.d.ts +16 -9
  224. package/lib/Utils/history.d.ts.map +1 -0
  225. package/lib/Utils/history.js +83 -48
  226. package/lib/Utils/history.js.map +1 -0
  227. package/lib/Utils/identity-change-handler.d.ts +37 -0
  228. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  229. package/lib/Utils/identity-change-handler.js +49 -0
  230. package/lib/Utils/identity-change-handler.js.map +1 -0
  231. package/lib/Utils/index.d.ts +23 -17
  232. package/lib/Utils/index.d.ts.map +1 -0
  233. package/lib/Utils/index.js +23 -33
  234. package/lib/Utils/index.js.map +1 -0
  235. package/lib/Utils/link-preview.d.ts +5 -5
  236. package/lib/Utils/link-preview.d.ts.map +1 -0
  237. package/lib/Utils/link-preview.js +14 -22
  238. package/lib/Utils/link-preview.js.map +1 -0
  239. package/lib/Utils/logger.d.ts +12 -3
  240. package/lib/Utils/logger.d.ts.map +1 -0
  241. package/lib/Utils/logger.js +3 -7
  242. package/lib/Utils/logger.js.map +1 -0
  243. package/lib/Utils/lt-hash.d.ts +8 -12
  244. package/lib/Utils/lt-hash.d.ts.map +1 -0
  245. package/lib/Utils/lt-hash.js +3 -46
  246. package/lib/Utils/lt-hash.js.map +1 -0
  247. package/lib/Utils/make-mutex.d.ts +4 -2
  248. package/lib/Utils/make-mutex.d.ts.map +1 -0
  249. package/lib/Utils/make-mutex.js +24 -34
  250. package/lib/Utils/make-mutex.js.map +1 -0
  251. package/lib/Utils/message-retry-manager.d.ts +110 -0
  252. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  253. package/lib/Utils/message-retry-manager.js +225 -0
  254. package/lib/Utils/message-retry-manager.js.map +1 -0
  255. package/lib/Utils/messages-media.d.ts +56 -42
  256. package/lib/Utils/messages-media.d.ts.map +1 -0
  257. package/lib/Utils/messages-media.js +411 -448
  258. package/lib/Utils/messages-media.js.map +1 -0
  259. package/lib/Utils/messages.d.ts +32 -18
  260. package/lib/Utils/messages.d.ts.map +1 -0
  261. package/lib/Utils/messages.js +1132 -710
  262. package/lib/Utils/messages.js.map +1 -0
  263. package/lib/Utils/noise-handler.d.ts +12 -13
  264. package/lib/Utils/noise-handler.d.ts.map +1 -0
  265. package/lib/Utils/noise-handler.js +145 -99
  266. package/lib/Utils/noise-handler.js.map +1 -0
  267. package/lib/Utils/offline-node-processor.d.ts +17 -0
  268. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  269. package/lib/Utils/offline-node-processor.js +40 -0
  270. package/lib/Utils/offline-node-processor.js.map +1 -0
  271. package/lib/Utils/pre-key-manager.d.ts +28 -0
  272. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  273. package/lib/Utils/pre-key-manager.js +106 -0
  274. package/lib/Utils/pre-key-manager.js.map +1 -0
  275. package/lib/Utils/process-message.d.ts +31 -12
  276. package/lib/Utils/process-message.d.ts.map +1 -0
  277. package/lib/Utils/process-message.js +357 -150
  278. package/lib/Utils/process-message.js.map +1 -0
  279. package/lib/Utils/reporting-utils.d.ts +11 -0
  280. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  281. package/lib/Utils/reporting-utils.js +258 -0
  282. package/lib/Utils/reporting-utils.js.map +1 -0
  283. package/lib/Utils/rich-messages.d.ts +277 -0
  284. package/lib/Utils/rich-messages.d.ts.map +1 -0
  285. package/lib/Utils/rich-messages.js +1144 -0
  286. package/lib/Utils/rich-messages.js.map +1 -0
  287. package/lib/Utils/signal.d.ts +7 -5
  288. package/lib/Utils/signal.d.ts.map +1 -0
  289. package/lib/Utils/signal.js +78 -72
  290. package/lib/Utils/signal.js.map +1 -0
  291. package/lib/Utils/stanza-ack.d.ts +11 -0
  292. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  293. package/lib/Utils/stanza-ack.js +38 -0
  294. package/lib/Utils/stanza-ack.js.map +1 -0
  295. package/lib/Utils/sticker-pack.d.ts +10 -0
  296. package/lib/Utils/sticker-pack.js +111 -0
  297. package/lib/Utils/sync-action-utils.d.ts +19 -0
  298. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  299. package/lib/Utils/sync-action-utils.js +48 -0
  300. package/lib/Utils/sync-action-utils.js.map +1 -0
  301. package/lib/Utils/tc-token-utils.d.ts +12 -0
  302. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  303. package/lib/Utils/tc-token-utils.js +18 -0
  304. package/lib/Utils/tc-token-utils.js.map +1 -0
  305. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  306. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  307. package/lib/Utils/use-multi-file-auth-state.js +29 -27
  308. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  309. package/lib/Utils/validate-connection.d.ts +7 -7
  310. package/lib/Utils/validate-connection.d.ts.map +1 -0
  311. package/lib/Utils/validate-connection.js +70 -99
  312. package/lib/Utils/validate-connection.js.map +1 -0
  313. package/lib/WABinary/constants.d.ts +25 -27
  314. package/lib/WABinary/constants.d.ts.map +1 -0
  315. package/lib/WABinary/constants.js +1281 -20
  316. package/lib/WABinary/constants.js.map +1 -0
  317. package/lib/WABinary/decode.d.ts +5 -5
  318. package/lib/WABinary/decode.d.ts.map +1 -0
  319. package/lib/WABinary/decode.js +52 -42
  320. package/lib/WABinary/decode.js.map +1 -0
  321. package/lib/WABinary/encode.d.ts +3 -3
  322. package/lib/WABinary/encode.d.ts.map +1 -0
  323. package/lib/WABinary/encode.js +110 -155
  324. package/lib/WABinary/encode.js.map +1 -0
  325. package/lib/WABinary/generic-utils.d.ts +8 -8
  326. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  327. package/lib/WABinary/generic-utils.js +142 -149
  328. package/lib/WABinary/generic-utils.js.map +1 -0
  329. package/lib/WABinary/index.d.ts +6 -5
  330. package/lib/WABinary/index.d.ts.map +1 -0
  331. package/lib/WABinary/index.js +6 -21
  332. package/lib/WABinary/index.js.map +1 -0
  333. package/lib/WABinary/jid-utils.d.ts +25 -8
  334. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  335. package/lib/WABinary/jid-utils.js +74 -40
  336. package/lib/WABinary/jid-utils.js.map +1 -0
  337. package/lib/WABinary/types.d.ts +2 -1
  338. package/lib/WABinary/types.d.ts.map +1 -0
  339. package/lib/WABinary/types.js +2 -2
  340. package/lib/WABinary/types.js.map +1 -0
  341. package/lib/WAM/BinaryInfo.d.ts +3 -11
  342. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  343. package/lib/WAM/BinaryInfo.js +2 -5
  344. package/lib/WAM/BinaryInfo.js.map +1 -0
  345. package/lib/WAM/constants.d.ts +5 -3
  346. package/lib/WAM/constants.d.ts.map +1 -0
  347. package/lib/WAM/constants.js +19071 -11568
  348. package/lib/WAM/constants.js.map +1 -0
  349. package/lib/WAM/encode.d.ts +2 -2
  350. package/lib/WAM/encode.d.ts.map +1 -0
  351. package/lib/WAM/encode.js +17 -22
  352. package/lib/WAM/encode.js.map +1 -0
  353. package/lib/WAM/index.d.ts +4 -3
  354. package/lib/WAM/index.d.ts.map +1 -0
  355. package/lib/WAM/index.js +4 -19
  356. package/lib/WAM/index.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  358. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  360. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  362. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  364. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  366. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  368. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  370. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +5 -4
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +5 -20
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +5 -4
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +40 -35
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +6 -5
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +2 -5
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -3
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -19
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +10 -9
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +12 -33
  400. package/lib/index.js.map +1 -0
  401. package/package.json +64 -105
  402. package/README.md +0 -364
  403. package/engine-requirements.js +0 -10
  404. package/lib/Defaults/baileys-version.json +0 -3
  405. package/lib/Defaults/phonenumber-mcc.json +0 -223
  406. package/lib/Signal/Group/queue-job.d.ts +0 -1
  407. package/lib/Signal/Group/queue-job.js +0 -57
  408. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  409. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  410. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  411. package/lib/Socket/Client/web-socket-client.js +0 -62
  412. package/lib/Socket/registration.d.ts +0 -267
  413. package/lib/Socket/registration.js +0 -166
  414. package/lib/Socket/usync.d.ts +0 -36
  415. package/lib/Socket/usync.js +0 -70
  416. package/lib/Store/index.d.ts +0 -3
  417. package/lib/Store/index.js +0 -10
  418. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  419. package/lib/Store/make-cache-manager-store.js +0 -83
  420. package/lib/Store/make-in-memory-store.d.ts +0 -118
  421. package/lib/Store/make-in-memory-store.js +0 -427
  422. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  423. package/lib/Store/make-ordered-dictionary.js +0 -81
  424. package/lib/Store/object-repository.d.ts +0 -10
  425. package/lib/Store/object-repository.js +0 -27
  426. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  427. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -1,65 +1,62 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeSocket = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const crypto_1 = require("crypto");
6
- const url_1 = require("url");
7
- const util_1 = require("util");
8
- const WAProto_1 = require("../../WAProto");
9
- const Defaults_1 = require("../Defaults");
10
- const Types_1 = require("../Types");
11
- const Utils_1 = require("../Utils");
12
- const WABinary_1 = require("../WABinary");
13
- const Client_1 = require("./Client");
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes } from 'crypto';
3
+ import { URL } from 'url';
4
+ import { promisify } from 'util';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, MIN_UPLOAD_INTERVAL, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
7
+ import { DisconnectReason } from '../Types/index.js';
8
+ import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
9
+ import { getPlatformId } from '../Utils/browser-utils.js';
10
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { BinaryInfo } from '../WAM/BinaryInfo.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { WebSocketClient } from './Client/index.js';
14
14
  /**
15
15
  * Connects to WA servers and performs:
16
16
  * - simple queries (no retry mechanism, wait for connection establishment)
17
17
  * - listen to messages and emit events
18
18
  * - query phone connection
19
19
  */
20
- const makeSocket = (config) => {
21
- var _a, _b;
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
- const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
20
+ export const makeSocket = (config) => {
21
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
22
+ const publicWAMBuffer = new BinaryInfo();
23
+ let serverTimeOffsetMs = 0;
24
+ const uqTagId = generateMdTagPrefix();
25
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
26
+ if (printQRInTerminal) {
27
+ logger.warn({}, '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
28
+ }
29
+ const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
30
+ .length === PROCESSABLE_HISTORY_TYPES.length;
31
+ if (syncDisabled) {
32
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
33
+ }
34
+ const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
24
35
  if (config.mobile || url.protocol === 'tcp:') {
25
- throw new boom_1.Boom('Mobile API is not supported anymore', {
26
- statusCode: Types_1.DisconnectReason.loggedOut
27
- });
36
+ throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
28
37
  }
29
- if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
38
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
30
39
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
31
40
  }
32
- const ws = new Client_1.WebSocketClient(url, config);
33
- ws.connect();
34
- const ev = (0, Utils_1.makeEventBuffer)(logger);
35
41
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
36
- const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
42
+ const ephemeralKeyPair = Curve.generateKeyPair();
37
43
  /** WA noise protocol wrapper */
38
- const noise = (0, Utils_1.makeNoiseHandler)({
44
+ const noise = makeNoiseHandler({
39
45
  keyPair: ephemeralKeyPair,
40
- NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
46
+ NOISE_HEADER: NOISE_WA_HEADER,
41
47
  logger,
42
- routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
48
+ routingInfo: authState?.creds?.routingInfo
43
49
  });
44
- const { creds } = authState;
45
- // add transaction capability
46
- const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
47
- const signalRepository = makeSignalRepository({ creds, keys });
48
- let lastDateRecv;
49
- let epoch = 1;
50
- let keepAliveReq;
51
- let qrTimer;
52
- let closed = false;
53
- const uqTagId = (0, Utils_1.generateMdTagPrefix)();
54
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
55
- const sendPromise = (0, util_1.promisify)(ws.send);
50
+ const ws = new WebSocketClient(url, config);
51
+ ws.connect();
52
+ const sendPromise = promisify(ws.send);
56
53
  /** send a raw buffer */
57
54
  const sendRawMessage = async (data) => {
58
55
  if (!ws.isOpen) {
59
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
56
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
60
57
  }
61
58
  const bytes = noise.encodeFrame(data);
62
- await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
59
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
63
60
  try {
64
61
  await sendPromise.call(ws, bytes);
65
62
  resolve();
@@ -72,60 +69,11 @@ const makeSocket = (config) => {
72
69
  /** send a binary node */
73
70
  const sendNode = (frame) => {
74
71
  if (logger.level === 'trace') {
75
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
72
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
76
73
  }
77
- const buff = (0, WABinary_1.encodeBinaryNode)(frame);
74
+ const buff = encodeBinaryNode(frame);
78
75
  return sendRawMessage(buff);
79
76
  };
80
- /** log & process any unexpected errors */
81
- const onUnexpectedError = (err, msg) => {
82
- logger.error({ err }, `unexpected error in '${msg}'`);
83
- const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
84
- // auto recover from cryptographic desyncs by re-uploading prekeys
85
- if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
86
- try {
87
- uploadPreKeysToServerIfRequired(true)
88
- .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
89
- }
90
- catch (_e) {
91
- // ignore
92
- }
93
- }
94
- // gently back off when encountering rate limits (429)
95
- if (message.includes('429') || message.includes('rate limit')) {
96
- const wait = Math.min(30000, (config.backoffDelayMs || 5000));
97
- logger.info({ wait }, 'backing off due to rate limit');
98
- setTimeout(() => {
99
- // intentionally empty; wait to delay further sends
100
- }, wait);
101
- }
102
- };
103
- /** await the next incoming message */
104
- const awaitNextMessage = async (sendMsg) => {
105
- if (!ws.isOpen) {
106
- throw new boom_1.Boom('Connection Closed', {
107
- statusCode: Types_1.DisconnectReason.connectionClosed
108
- });
109
- }
110
- let onOpen;
111
- let onClose;
112
- const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
113
- onOpen = resolve;
114
- onClose = mapWebSocketError(reject);
115
- ws.on('frame', onOpen);
116
- ws.on('close', onClose);
117
- ws.on('error', onClose);
118
- })
119
- .finally(() => {
120
- ws.off('frame', onOpen);
121
- ws.off('close', onClose);
122
- ws.off('error', onClose);
123
- });
124
- if (sendMsg) {
125
- sendRawMessage(sendMsg).catch(onClose);
126
- }
127
- return result;
128
- };
129
77
  /**
130
78
  * Wait for a message with a certain tag to be received
131
79
  * @param msgId the message tag to await
@@ -135,21 +83,38 @@ const makeSocket = (config) => {
135
83
  let onRecv;
136
84
  let onErr;
137
85
  try {
138
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
139
- onRecv = resolve;
86
+ const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
87
+ onRecv = data => {
88
+ resolve(data);
89
+ };
140
90
  onErr = err => {
141
- reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
91
+ reject(err ||
92
+ new Boom('Connection Closed', {
93
+ statusCode: DisconnectReason.connectionClosed
94
+ }));
142
95
  };
143
96
  ws.on(`TAG:${msgId}`, onRecv);
144
- ws.on('close', onErr); // if the socket closes, you'll never receive the message
145
- ws.off('error', onErr);
97
+ ws.on('close', onErr);
98
+ ws.on('error', onErr);
99
+ return () => reject(new Boom('Query Cancelled'));
146
100
  });
147
101
  return result;
148
102
  }
103
+ catch (error) {
104
+ // Catch timeout and return undefined instead of throwing
105
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
106
+ logger?.warn?.({ msgId }, 'timed out waiting for message');
107
+ return undefined;
108
+ }
109
+ throw error;
110
+ }
149
111
  finally {
150
- ws.off(`TAG:${msgId}`, onRecv);
151
- ws.off('close', onErr); // if the socket closes, you'll never receive the message
152
- ws.off('error', onErr);
112
+ if (onRecv)
113
+ ws.off(`TAG:${msgId}`, onRecv);
114
+ if (onErr) {
115
+ ws.off('close', onErr);
116
+ ws.off('error', onErr);
117
+ }
153
118
  }
154
119
  };
155
120
  /** send a query, and wait for its response. auto-generates message ID if not provided */
@@ -158,12 +123,179 @@ const makeSocket = (config) => {
158
123
  node.attrs.id = generateMessageTag();
159
124
  }
160
125
  const msgId = node.attrs.id;
161
- const [result] = await Promise.all([
162
- waitForMessage(msgId, timeoutMs),
126
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
127
+ const result = waitForMessage(msgId, timeoutMs).catch(reject);
163
128
  sendNode(node)
164
- ]);
165
- if ('tag' in result) {
166
- (0, WABinary_1.assertNodeErrorFree)(result);
129
+ .then(async () => resolve(await result))
130
+ .catch(reject);
131
+ });
132
+ if (result && 'tag' in result) {
133
+ assertNodeErrorFree(result);
134
+ }
135
+ return result;
136
+ };
137
+ // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
138
+ const digestKeyBundle = async () => {
139
+ const res = await query({
140
+ tag: 'iq',
141
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
142
+ content: [{ tag: 'digest', attrs: {} }]
143
+ });
144
+ const digestNode = getBinaryNodeChild(res, 'digest');
145
+ if (!digestNode) {
146
+ await uploadPreKeys();
147
+ throw new Error('encrypt/get digest returned no digest node');
148
+ }
149
+ };
150
+ // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
151
+ const rotateSignedPreKey = async () => {
152
+ const newId = (creds.signedPreKey.keyId || 0) + 1;
153
+ const skey = await signedKeyPair(creds.signedIdentityKey, newId);
154
+ await query({
155
+ tag: 'iq',
156
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
157
+ content: [
158
+ {
159
+ tag: 'rotate',
160
+ attrs: {},
161
+ content: [xmppSignedPreKey(skey)]
162
+ }
163
+ ]
164
+ });
165
+ // Persist new signed pre-key in creds
166
+ ev.emit('creds.update', { signedPreKey: skey });
167
+ };
168
+ const executeUSyncQuery = async (usyncQuery) => {
169
+ if (usyncQuery.protocols.length === 0) {
170
+ throw new Boom('USyncQuery must have at least one protocol');
171
+ }
172
+ // todo: validate users, throw WARNING on no valid users
173
+ // variable below has only validated users
174
+ const validUsers = usyncQuery.users;
175
+ const userNodes = validUsers.map(user => {
176
+ return {
177
+ tag: 'user',
178
+ attrs: {
179
+ jid: !user.phone ? user.id : undefined
180
+ },
181
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
182
+ };
183
+ });
184
+ const listNode = {
185
+ tag: 'list',
186
+ attrs: {},
187
+ content: userNodes
188
+ };
189
+ const queryNode = {
190
+ tag: 'query',
191
+ attrs: {},
192
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
193
+ };
194
+ const iq = {
195
+ tag: 'iq',
196
+ attrs: {
197
+ to: S_WHATSAPP_NET,
198
+ type: 'get',
199
+ xmlns: 'usync'
200
+ },
201
+ content: [
202
+ {
203
+ tag: 'usync',
204
+ attrs: {
205
+ context: usyncQuery.context,
206
+ mode: usyncQuery.mode,
207
+ sid: generateMessageTag(),
208
+ last: 'true',
209
+ index: '0'
210
+ },
211
+ content: [queryNode, listNode]
212
+ }
213
+ ]
214
+ };
215
+ const result = await query(iq);
216
+ return usyncQuery.parseUSyncQueryResult(result);
217
+ };
218
+ const onWhatsApp = async (...phoneNumber) => {
219
+ let usyncQuery = new USyncQuery();
220
+ let contactEnabled = false;
221
+ for (const jid of phoneNumber) {
222
+ if (isLidUser(jid)) {
223
+ logger?.warn('LIDs are not supported with onWhatsApp');
224
+ continue;
225
+ }
226
+ else {
227
+ if (!contactEnabled) {
228
+ contactEnabled = true;
229
+ usyncQuery = usyncQuery.withContactProtocol();
230
+ }
231
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
232
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
233
+ }
234
+ }
235
+ if (usyncQuery.users.length === 0) {
236
+ return []; // return early without forcing an empty query
237
+ }
238
+ const results = await executeUSyncQuery(usyncQuery);
239
+ if (results) {
240
+ return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
241
+ }
242
+ };
243
+ const pnFromLIDUSync = async (jids) => {
244
+ const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
245
+ for (const jid of jids) {
246
+ if (isLidUser(jid)) {
247
+ logger?.warn('LID user found in LID fetch call');
248
+ continue;
249
+ }
250
+ else {
251
+ usyncQuery.withUser(new USyncUser().withId(jid));
252
+ }
253
+ }
254
+ if (usyncQuery.users.length === 0) {
255
+ return []; // return early without forcing an empty query
256
+ }
257
+ const results = await executeUSyncQuery(usyncQuery);
258
+ if (results) {
259
+ return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
260
+ }
261
+ return [];
262
+ };
263
+ const ev = makeEventBuffer(logger);
264
+ const { creds } = authState;
265
+ // add transaction capability
266
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
267
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
268
+ let lastDateRecv;
269
+ let epoch = 1;
270
+ let keepAliveReq;
271
+ let qrTimer;
272
+ let closed = false;
273
+ /** log & process any unexpected errors */
274
+ const onUnexpectedError = (err, msg) => {
275
+ logger.error({ err }, `unexpected error in '${msg}'`);
276
+ };
277
+ /** await the next incoming message */
278
+ const awaitNextMessage = async (sendMsg) => {
279
+ if (!ws.isOpen) {
280
+ throw new Boom('Connection Closed', {
281
+ statusCode: DisconnectReason.connectionClosed
282
+ });
283
+ }
284
+ let onOpen;
285
+ let onClose;
286
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
287
+ onOpen = resolve;
288
+ onClose = mapWebSocketError(reject);
289
+ ws.on('frame', onOpen);
290
+ ws.on('close', onClose);
291
+ ws.on('error', onClose);
292
+ }).finally(() => {
293
+ ws.off('frame', onOpen);
294
+ ws.off('close', onClose);
295
+ ws.off('error', onClose);
296
+ });
297
+ if (sendMsg) {
298
+ sendRawMessage(sendMsg).catch(onClose);
167
299
  }
168
300
  return result;
169
301
  };
@@ -172,30 +304,30 @@ const makeSocket = (config) => {
172
304
  let helloMsg = {
173
305
  clientHello: { ephemeral: ephemeralKeyPair.public }
174
306
  };
175
- helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
307
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
176
308
  logger.info({ browser, helloMsg }, 'connected to WA');
177
- const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
309
+ const init = proto.HandshakeMessage.encode(helloMsg).finish();
178
310
  const result = await awaitNextMessage(init);
179
- const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
311
+ const handshake = proto.HandshakeMessage.decode(result);
180
312
  logger.trace({ handshake }, 'handshake recv from WA');
181
- const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
313
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
182
314
  let node;
183
315
  if (!creds.me) {
184
- node = (0, Utils_1.generateRegistrationNode)(creds, config);
316
+ node = generateRegistrationNode(creds, config);
185
317
  logger.info({ node }, 'not logged in, attempting registration...');
186
318
  }
187
319
  else {
188
- node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
320
+ node = generateLoginNode(creds.me.id, config);
189
321
  logger.info({ node }, 'logging in...');
190
322
  }
191
- const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
192
- await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
323
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
324
+ await sendRawMessage(proto.HandshakeMessage.encode({
193
325
  clientFinish: {
194
326
  static: keyEnc,
195
- payload: payloadEnc,
196
- },
327
+ payload: payloadEnc
328
+ }
197
329
  }).finish());
198
- noise.finishInit();
330
+ await noise.finishInit();
199
331
  startKeepAliveRequest();
200
332
  };
201
333
  const getAvailablePreKeysOnServer = async () => {
@@ -205,35 +337,114 @@ const makeSocket = (config) => {
205
337
  id: generateMessageTag(),
206
338
  xmlns: 'encrypt',
207
339
  type: 'get',
208
- to: WABinary_1.S_WHATSAPP_NET
340
+ to: S_WHATSAPP_NET
209
341
  },
210
- content: [
211
- { tag: 'count', attrs: {} }
212
- ]
342
+ content: [{ tag: 'count', attrs: {} }]
213
343
  });
214
- const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
344
+ const countChild = getBinaryNodeChild(result, 'count');
215
345
  return +countChild.attrs.value;
216
346
  };
347
+ // Pre-key upload state management
348
+ let uploadPreKeysPromise = null;
349
+ let lastUploadTime = 0;
217
350
  /** generates and uploads a set of pre-keys to the server */
218
- const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
219
- await keys.transaction(async () => {
220
- logger.info({ count }, 'uploading pre-keys');
221
- const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
222
- await query(node);
223
- ev.emit('creds.update', update);
224
- logger.info({ count }, 'uploaded pre-keys');
225
- });
351
+ const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
352
+ // Check minimum interval (except for retries)
353
+ if (retryCount === 0) {
354
+ const timeSinceLastUpload = Date.now() - lastUploadTime;
355
+ if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
356
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
357
+ return;
358
+ }
359
+ }
360
+ // Prevent multiple concurrent uploads
361
+ if (uploadPreKeysPromise) {
362
+ logger.debug('Pre-key upload already in progress, waiting for completion');
363
+ await uploadPreKeysPromise;
364
+ }
365
+ const uploadLogic = async () => {
366
+ logger.info({ count, retryCount }, 'uploading pre-keys');
367
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
368
+ const node = await keys.transaction(async () => {
369
+ logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
370
+ const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
371
+ // Update credentials immediately to prevent duplicate IDs on retry
372
+ ev.emit('creds.update', update);
373
+ return node; // Only return node since update is already used
374
+ }, creds?.me?.id || 'upload-pre-keys');
375
+ // Upload to server (outside transaction, can fail without affecting local keys)
376
+ try {
377
+ await query(node);
378
+ logger.info({ count }, 'uploaded pre-keys successfully');
379
+ lastUploadTime = Date.now();
380
+ }
381
+ catch (uploadError) {
382
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
383
+ // Exponential backoff retry (max 3 retries)
384
+ if (retryCount < 3) {
385
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
386
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
387
+ await new Promise(resolve => setTimeout(resolve, backoffDelay));
388
+ return uploadPreKeys(count, retryCount + 1);
389
+ }
390
+ throw uploadError;
391
+ }
392
+ };
393
+ // Add timeout protection
394
+ uploadPreKeysPromise = Promise.race([
395
+ uploadLogic(),
396
+ new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
397
+ ]);
398
+ try {
399
+ await uploadPreKeysPromise;
400
+ }
401
+ finally {
402
+ uploadPreKeysPromise = null;
403
+ }
404
+ };
405
+ const verifyCurrentPreKeyExists = async () => {
406
+ const currentPreKeyId = creds.nextPreKeyId - 1;
407
+ if (currentPreKeyId <= 0) {
408
+ return { exists: false, currentPreKeyId: 0 };
409
+ }
410
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
411
+ const exists = !!preKeys[currentPreKeyId.toString()];
412
+ return { exists, currentPreKeyId };
226
413
  };
227
414
  const uploadPreKeysToServerIfRequired = async () => {
228
- const preKeyCount = await getAvailablePreKeysOnServer();
229
- logger.info(`${preKeyCount} pre-keys found on server`);
230
- if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
231
- await uploadPreKeys();
415
+ try {
416
+ let count = 0;
417
+ const preKeyCount = await getAvailablePreKeysOnServer();
418
+ if (preKeyCount === 0)
419
+ count = INITIAL_PREKEY_COUNT;
420
+ else
421
+ count = MIN_PREKEY_COUNT;
422
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
423
+ logger.info(`${preKeyCount} pre-keys found on server`);
424
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
425
+ const lowServerCount = preKeyCount <= count;
426
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
427
+ const shouldUpload = lowServerCount || missingCurrentPreKey;
428
+ if (shouldUpload) {
429
+ const reasons = [];
430
+ if (lowServerCount)
431
+ reasons.push(`server count low (${preKeyCount})`);
432
+ if (missingCurrentPreKey)
433
+ reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
434
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
435
+ await uploadPreKeys(count);
436
+ }
437
+ else {
438
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
439
+ }
440
+ }
441
+ catch (error) {
442
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
443
+ // Don't throw - allow connection to continue even if pre-key check fails
232
444
  }
233
445
  };
234
- const onMessageReceived = (data) => {
235
- noise.decodeFrame(data, frame => {
236
- var _a;
446
+ const onMessageReceived = async (data) => {
447
+ await noise.decodeFrame(data, frame => {
237
448
  // reset ping timeout
238
449
  lastDateRecv = new Date();
239
450
  let anyTriggered = false;
@@ -242,45 +453,44 @@ const makeSocket = (config) => {
242
453
  if (!(frame instanceof Uint8Array)) {
243
454
  const msgId = frame.attrs.id;
244
455
  if (logger.level === 'trace') {
245
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
456
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
246
457
  }
247
458
  /* Check if this is a response to a message we sent */
248
- anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
459
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
249
460
  /* Check if this is a response to a message we are expecting */
250
461
  const l0 = frame.tag;
251
462
  const l1 = frame.attrs || {};
252
- const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
463
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
253
464
  for (const key of Object.keys(l1)) {
254
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
255
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
256
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
465
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
466
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
467
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
257
468
  }
258
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
259
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
469
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
470
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
260
471
  if (!anyTriggered && logger.level === 'debug') {
261
472
  logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
262
473
  }
263
474
  }
264
475
  });
265
476
  };
266
- const end = (error) => {
477
+ const end = async (error) => {
267
478
  if (closed) {
268
- logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
479
+ logger.trace({ trace: error?.stack }, 'connection already closed');
269
480
  return;
270
481
  }
271
482
  closed = true;
272
- logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
483
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
273
484
  clearInterval(keepAliveReq);
274
485
  clearTimeout(qrTimer);
275
486
  ws.removeAllListeners('close');
276
- ws.removeAllListeners('error');
277
487
  ws.removeAllListeners('open');
278
488
  ws.removeAllListeners('message');
279
489
  if (!ws.isClosed && !ws.isClosing) {
280
490
  try {
281
- ws.close();
491
+ await ws.close();
282
492
  }
283
- catch (_a) { }
493
+ catch { }
284
494
  }
285
495
  ev.emit('connection.update', {
286
496
  connection: 'close',
@@ -296,7 +506,7 @@ const makeSocket = (config) => {
296
506
  return;
297
507
  }
298
508
  if (ws.isClosed || ws.isClosing) {
299
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
509
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
300
510
  }
301
511
  let onOpen;
302
512
  let onClose;
@@ -306,8 +516,7 @@ const makeSocket = (config) => {
306
516
  ws.on('open', onOpen);
307
517
  ws.on('close', onClose);
308
518
  ws.on('error', onClose);
309
- })
310
- .finally(() => {
519
+ }).finally(() => {
311
520
  ws.off('open', onOpen);
312
521
  ws.off('close', onClose);
313
522
  ws.off('error', onClose);
@@ -323,7 +532,7 @@ const makeSocket = (config) => {
323
532
  it could be that the network is down
324
533
  */
325
534
  if (diff > keepAliveIntervalMs + 5000) {
326
- end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
535
+ void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
327
536
  }
328
537
  else if (ws.isOpen) {
329
538
  // if its all good, send a keep alive request
@@ -331,13 +540,12 @@ const makeSocket = (config) => {
331
540
  tag: 'iq',
332
541
  attrs: {
333
542
  id: generateMessageTag(),
334
- to: WABinary_1.S_WHATSAPP_NET,
543
+ to: S_WHATSAPP_NET,
335
544
  type: 'get',
336
- xmlns: 'w:p',
545
+ xmlns: 'w:p'
337
546
  },
338
547
  content: [{ tag: 'ping', attrs: {} }]
339
- })
340
- .catch(err => {
548
+ }).catch(err => {
341
549
  logger.error({ trace: err.stack }, 'error in sending keep alive');
342
550
  });
343
551
  }
@@ -346,26 +554,23 @@ const makeSocket = (config) => {
346
554
  }
347
555
  }, keepAliveIntervalMs));
348
556
  /** i have no idea why this exists. pls enlighten me */
349
- const sendPassiveIq = (tag) => (query({
557
+ const sendPassiveIq = (tag) => query({
350
558
  tag: 'iq',
351
559
  attrs: {
352
- to: WABinary_1.S_WHATSAPP_NET,
560
+ to: S_WHATSAPP_NET,
353
561
  xmlns: 'passive',
354
- type: 'set',
562
+ type: 'set'
355
563
  },
356
- content: [
357
- { tag, attrs: {} }
358
- ]
359
- }));
564
+ content: [{ tag, attrs: {} }]
565
+ });
360
566
  /** logout & invalidate connection */
361
567
  const logout = async (msg) => {
362
- var _a;
363
- const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
568
+ const jid = authState.creds.me?.id;
364
569
  if (jid) {
365
570
  await sendNode({
366
571
  tag: 'iq',
367
572
  attrs: {
368
- to: WABinary_1.S_WHATSAPP_NET,
573
+ to: S_WHATSAPP_NET,
369
574
  type: 'set',
370
575
  id: generateMessageTag(),
371
576
  xmlns: 'md'
@@ -381,30 +586,23 @@ const makeSocket = (config) => {
381
586
  ]
382
587
  });
383
588
  }
384
- end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
589
+ void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
385
590
  };
386
-
387
- /** This method was created by snowi, and implemented by KyuuRzy */
388
- /** hey bro, if you delete this text */
389
- /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
390
- const requestPairingCode = async (phoneNumber, pairKey) => {
391
- if (pairKey) {
392
- authState.creds.pairingCode = pairKey.toUpperCase();
393
- } else {
394
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
395
- }
396
-
591
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
592
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
593
+ if (customPairingCode && customPairingCode?.length !== 8) {
594
+ throw new Error('Custom pairing code must be exactly 8 chars');
595
+ }
596
+ authState.creds.pairingCode = pairingCode;
397
597
  authState.creds.me = {
398
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
598
+ id: jidEncode(phoneNumber, 's.whatsapp.net'),
399
599
  name: '~'
400
600
  };
401
-
402
601
  ev.emit('creds.update', authState.creds);
403
-
404
602
  await sendNode({
405
603
  tag: 'iq',
406
604
  attrs: {
407
- to: WABinary_1.S_WHATSAPP_NET,
605
+ to: S_WHATSAPP_NET,
408
606
  type: 'set',
409
607
  id: generateMessageTag(),
410
608
  xmlns: 'md'
@@ -431,7 +629,7 @@ const makeSocket = (config) => {
431
629
  {
432
630
  tag: 'companion_platform_id',
433
631
  attrs: {},
434
- content: (0, Utils_1.getPlatformId)(browser[1])
632
+ content: getPlatformId(browser[1])
435
633
  },
436
634
  {
437
635
  tag: 'companion_platform_display',
@@ -441,34 +639,33 @@ const makeSocket = (config) => {
441
639
  {
442
640
  tag: 'link_code_pairing_nonce',
443
641
  attrs: {},
444
- content: "0"
642
+ content: '0'
445
643
  }
446
644
  ]
447
645
  }
448
646
  ]
449
647
  });
450
-
451
648
  return authState.creds.pairingCode;
452
- }
649
+ };
453
650
  async function generatePairingKey() {
454
- const salt = (0, crypto_1.randomBytes)(32);
455
- const randomIv = (0, crypto_1.randomBytes)(16);
456
- const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
457
- const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
651
+ const salt = randomBytes(32);
652
+ const randomIv = randomBytes(16);
653
+ const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
654
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
458
655
  return Buffer.concat([salt, randomIv, ciphered]);
459
656
  }
460
657
  const sendWAMBuffer = (wamBuffer) => {
461
658
  return query({
462
659
  tag: 'iq',
463
660
  attrs: {
464
- to: WABinary_1.S_WHATSAPP_NET,
661
+ to: S_WHATSAPP_NET,
465
662
  id: generateMessageTag(),
466
663
  xmlns: 'w:stats'
467
664
  },
468
665
  content: [
469
666
  {
470
667
  tag: 'add',
471
- attrs: {},
668
+ attrs: { t: Math.round(Date.now() / 1000) + '' },
472
669
  content: wamBuffer
473
670
  }
474
671
  ]
@@ -481,26 +678,26 @@ const makeSocket = (config) => {
481
678
  }
482
679
  catch (err) {
483
680
  logger.error({ err }, 'error in validating connection');
484
- end(err);
681
+ void end(err);
485
682
  }
486
683
  });
487
684
  ws.on('error', mapWebSocketError(end));
488
- ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
685
+ ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
489
686
  // the server terminated the connection
490
- ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
687
+ ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
491
688
  // QR gen
492
689
  ws.on('CB:iq,type:set,pair-device', async (stanza) => {
493
690
  const iq = {
494
691
  tag: 'iq',
495
692
  attrs: {
496
- to: WABinary_1.S_WHATSAPP_NET,
693
+ to: S_WHATSAPP_NET,
497
694
  type: 'result',
498
- id: stanza.attrs.id,
695
+ id: stanza.attrs.id
499
696
  }
500
697
  };
501
698
  await sendNode(iq);
502
- const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
503
- const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
699
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
700
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
504
701
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
505
702
  const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
506
703
  const advB64 = creds.advSecretKey;
@@ -511,7 +708,7 @@ const makeSocket = (config) => {
511
708
  }
512
709
  const refNode = refNodes.shift();
513
710
  if (!refNode) {
514
- end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
711
+ void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
515
712
  return;
516
713
  }
517
714
  const ref = refNode.content.toString('utf-8');
@@ -527,65 +724,98 @@ const makeSocket = (config) => {
527
724
  ws.on('CB:iq,,pair-success', async (stanza) => {
528
725
  logger.debug('pair success recv');
529
726
  try {
530
- const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
727
+ updateServerTimeOffset(stanza);
728
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
531
729
  logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
532
730
  ev.emit('creds.update', updatedCreds);
533
731
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
534
732
  await sendNode(reply);
733
+ void sendUnifiedSession();
535
734
  }
536
735
  catch (error) {
537
736
  logger.info({ trace: error.stack }, 'error in pairing');
538
- end(error);
737
+ void end(error);
539
738
  }
540
739
  });
541
740
  // login complete
542
741
  ws.on('CB:success', async (node) => {
543
742
  try {
743
+ updateServerTimeOffset(node);
544
744
  await uploadPreKeysToServerIfRequired();
545
745
  await sendPassiveIq('active');
546
- logger.info('opened connection to WA');
547
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
548
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
549
- ev.emit('connection.update', { connection: 'open' });
746
+ // After successful login, validate our key-bundle against server
747
+ try {
748
+ await digestKeyBundle();
749
+ }
750
+ catch (e) {
751
+ logger.warn({ e }, 'failed to run digest after login');
752
+ }
550
753
  }
551
754
  catch (err) {
552
- logger.error({ err }, 'error opening connection');
553
- end(err);
755
+ logger.warn({ err }, 'failed to send initial passive iq');
756
+ }
757
+ logger.info('opened connection to WA');
758
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
759
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
760
+ ev.emit('connection.update', { connection: 'open' });
761
+ void sendUnifiedSession();
762
+ if (node.attrs.lid && authState.creds.me?.id) {
763
+ const myLID = node.attrs.lid;
764
+ process.nextTick(async () => {
765
+ try {
766
+ const myPN = authState.creds.me.id;
767
+ // Store our own LID-PN mapping
768
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
769
+ // Create device list for our own user (needed for bulk migration)
770
+ const { user, device } = jidDecode(myPN);
771
+ await authState.keys.set({
772
+ 'device-list': {
773
+ [user]: [device?.toString() || '0']
774
+ }
775
+ });
776
+ // migrate our own session
777
+ await signalRepository.migrateSession(myPN, myLID);
778
+ logger.info({ myPN, myLID }, 'Own LID session created successfully');
779
+ }
780
+ catch (error) {
781
+ logger.error({ error, lid: myLID }, 'Failed to create own LID session');
782
+ }
783
+ });
554
784
  }
555
785
  });
556
786
  ws.on('CB:stream:error', (node) => {
557
- logger.error({ node }, 'stream errored out');
558
- const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
559
- end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
787
+ const [reasonNode] = getAllBinaryNodeChildren(node);
788
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
789
+ const { reason, statusCode } = getErrorCodeFromStreamError(node);
790
+ void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
560
791
  });
561
792
  // stream fail, possible logout
562
793
  ws.on('CB:failure', (node) => {
563
794
  const reason = +(node.attrs.reason || 500);
564
- end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
795
+ void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
565
796
  });
566
797
  ws.on('CB:ib,,downgrade_webclient', () => {
567
- end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
798
+ void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
568
799
  });
569
- ws.on('CB:ib,,offline_preview', (node) => {
800
+ ws.on('CB:ib,,offline_preview', async (node) => {
570
801
  logger.info('offline preview received', JSON.stringify(node));
571
- sendNode({
802
+ await sendNode({
572
803
  tag: 'ib',
573
804
  attrs: {},
574
805
  content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
575
806
  });
576
807
  });
577
808
  ws.on('CB:ib,,edge_routing', (node) => {
578
- const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
579
- const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
580
- if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
581
- authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
809
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
810
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
811
+ if (routingInfo?.content) {
812
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content);
582
813
  ev.emit('creds.update', authState.creds);
583
814
  }
584
815
  });
585
816
  let didStartBuffer = false;
586
817
  process.nextTick(() => {
587
- var _a;
588
- if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
818
+ if (creds.me?.id) {
589
819
  // start buffering important events
590
820
  // if we're logged in
591
821
  ev.buffer();
@@ -595,8 +825,8 @@ const makeSocket = (config) => {
595
825
  });
596
826
  // called when all offline notifs are handled
597
827
  ws.on('CB:ib,,offline', (node) => {
598
- const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
599
- const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
828
+ const child = getBinaryNodeChild(node, 'offline');
829
+ const offlineNotifs = +(child?.attrs.count || 0);
600
830
  logger.info(`handled ${offlineNotifs} offline messages/notifications`);
601
831
  if (didStartBuffer) {
602
832
  ev.flush();
@@ -606,32 +836,66 @@ const makeSocket = (config) => {
606
836
  });
607
837
  // update credentials when required
608
838
  ev.on('creds.update', update => {
609
- var _a, _b;
610
- const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
839
+ const name = update.me?.name;
611
840
  // if name has just been received
612
- if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
841
+ if (creds.me?.name !== name) {
613
842
  logger.debug({ name }, 'updated pushName');
614
843
  sendNode({
615
844
  tag: 'presence',
616
845
  attrs: { name: name }
617
- })
618
- .catch(err => {
846
+ }).catch(err => {
619
847
  logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
620
848
  });
621
849
  }
622
850
  Object.assign(creds, update);
623
851
  });
624
- if (printQRInTerminal) {
625
- (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
626
- }
852
+ const updateServerTimeOffset = ({ attrs }) => {
853
+ const tValue = attrs?.t;
854
+ if (!tValue) {
855
+ return;
856
+ }
857
+ const parsed = Number(tValue);
858
+ if (Number.isNaN(parsed) || parsed <= 0) {
859
+ return;
860
+ }
861
+ const localMs = Date.now();
862
+ serverTimeOffsetMs = parsed * 1000 - localMs;
863
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
864
+ };
865
+ const getUnifiedSessionId = () => {
866
+ const offsetMs = 3 * TimeMs.Day;
867
+ const now = Date.now() + serverTimeOffsetMs;
868
+ const id = (now + offsetMs) % TimeMs.Week;
869
+ return id.toString();
870
+ };
871
+ const sendUnifiedSession = async () => {
872
+ if (!ws.isOpen) {
873
+ return;
874
+ }
875
+ const node = {
876
+ tag: 'ib',
877
+ attrs: {},
878
+ content: [
879
+ {
880
+ tag: 'unified_session',
881
+ attrs: {
882
+ id: getUnifiedSessionId()
883
+ }
884
+ }
885
+ ]
886
+ };
887
+ try {
888
+ await sendNode(node);
889
+ }
890
+ catch (error) {
891
+ logger.debug({ error }, 'failed to send unified_session telemetry');
892
+ }
893
+ };
627
894
  return {
628
895
  type: 'md',
629
896
  ws,
630
897
  ev,
631
- authState: {
632
- creds,
633
- keys
634
- },
898
+ authState: { creds, keys },
635
899
  signalRepository,
636
900
  get user() {
637
901
  return authState.creds.me;
@@ -647,19 +911,26 @@ const makeSocket = (config) => {
647
911
  onUnexpectedError,
648
912
  uploadPreKeys,
649
913
  uploadPreKeysToServerIfRequired,
914
+ digestKeyBundle,
915
+ rotateSignedPreKey,
650
916
  requestPairingCode,
917
+ updateServerTimeOffset,
918
+ sendUnifiedSession,
919
+ wamBuffer: publicWAMBuffer,
651
920
  /** Waits for the connection to WA to reach a state */
652
- waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
921
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
653
922
  sendWAMBuffer,
923
+ executeUSyncQuery,
924
+ onWhatsApp
654
925
  };
655
926
  };
656
- exports.makeSocket = makeSocket;
657
927
  /**
658
928
  * map the websocket error to the right type
659
929
  * so it can be retried by the caller
660
930
  * */
661
931
  function mapWebSocketError(handler) {
662
932
  return (error) => {
663
- handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
933
+ handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
664
934
  };
665
935
  }
936
+ //# sourceMappingURL=socket.js.map