@vinzsocket/baileys 2.0.0-pre.1

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