@neelegirl/baileys 1.5.6 → 1.5.8

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