@neelegirl/baileys 1.5.4 → 1.5.5

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 (374) hide show
  1. package/README.md +10 -189
  2. package/index.js +38 -0
  3. package/package.json +11 -94
  4. package/LICENSE +0 -21
  5. package/WAProto/GenerateStatics.sh +0 -3
  6. package/WAProto/WAProto.proto +0 -4633
  7. package/WAProto/fix-imports.js +0 -29
  8. package/WAProto/index.d.ts +0 -11969
  9. package/WAProto/index.js +0 -84368
  10. package/engine-requirements.js +0 -10
  11. package/lib/Defaults/index.d.ts +0 -62
  12. package/lib/Defaults/index.d.ts.map +0 -1
  13. package/lib/Defaults/index.js +0 -115
  14. package/lib/Defaults/index.js.map +0 -1
  15. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  16. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  17. package/lib/Signal/Group/ciphertext-message.js +0 -12
  18. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  19. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  20. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  21. package/lib/Signal/Group/group-session-builder.js +0 -30
  22. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  23. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  24. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  25. package/lib/Signal/Group/group_cipher.js +0 -82
  26. package/lib/Signal/Group/group_cipher.js.map +0 -1
  27. package/lib/Signal/Group/index.d.ts +0 -12
  28. package/lib/Signal/Group/index.d.ts.map +0 -1
  29. package/lib/Signal/Group/index.js +0 -12
  30. package/lib/Signal/Group/index.js.map +0 -1
  31. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  32. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  33. package/lib/Signal/Group/keyhelper.js +0 -18
  34. package/lib/Signal/Group/keyhelper.js.map +0 -1
  35. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  36. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  37. package/lib/Signal/Group/sender-chain-key.js +0 -26
  38. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  39. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  40. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  41. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  42. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  43. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  44. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  45. package/lib/Signal/Group/sender-key-message.js +0 -66
  46. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  47. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  48. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  49. package/lib/Signal/Group/sender-key-name.js +0 -48
  50. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  51. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  52. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  53. package/lib/Signal/Group/sender-key-record.js +0 -41
  54. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  55. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  56. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  57. package/lib/Signal/Group/sender-key-state.js +0 -84
  58. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  59. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  60. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  61. package/lib/Signal/Group/sender-message-key.js +0 -26
  62. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  63. package/lib/Signal/libsignal.d.ts +0 -5
  64. package/lib/Signal/libsignal.d.ts.map +0 -1
  65. package/lib/Signal/libsignal.js +0 -342
  66. package/lib/Signal/libsignal.js.map +0 -1
  67. package/lib/Signal/lid-mapping.d.ts +0 -23
  68. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  69. package/lib/Signal/lid-mapping.js +0 -171
  70. package/lib/Signal/lid-mapping.js.map +0 -1
  71. package/lib/Socket/Client/index.d.ts +0 -3
  72. package/lib/Socket/Client/index.d.ts.map +0 -1
  73. package/lib/Socket/Client/index.js +0 -3
  74. package/lib/Socket/Client/index.js.map +0 -1
  75. package/lib/Socket/Client/types.d.ts +0 -16
  76. package/lib/Socket/Client/types.d.ts.map +0 -1
  77. package/lib/Socket/Client/types.js +0 -11
  78. package/lib/Socket/Client/types.js.map +0 -1
  79. package/lib/Socket/Client/websocket.d.ts +0 -13
  80. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  81. package/lib/Socket/Client/websocket.js +0 -50
  82. package/lib/Socket/Client/websocket.js.map +0 -1
  83. package/lib/Socket/business.d.ts +0 -188
  84. package/lib/Socket/business.d.ts.map +0 -1
  85. package/lib/Socket/business.js +0 -376
  86. package/lib/Socket/business.js.map +0 -1
  87. package/lib/Socket/chats.d.ts +0 -98
  88. package/lib/Socket/chats.d.ts.map +0 -1
  89. package/lib/Socket/chats.js +0 -962
  90. package/lib/Socket/chats.js.map +0 -1
  91. package/lib/Socket/communities.d.ts +0 -244
  92. package/lib/Socket/communities.d.ts.map +0 -1
  93. package/lib/Socket/communities.js +0 -431
  94. package/lib/Socket/communities.js.map +0 -1
  95. package/lib/Socket/groups.d.ts +0 -137
  96. package/lib/Socket/groups.d.ts.map +0 -1
  97. package/lib/Socket/groups.js +0 -327
  98. package/lib/Socket/groups.js.map +0 -1
  99. package/lib/Socket/index.d.ts +0 -231
  100. package/lib/Socket/index.d.ts.map +0 -1
  101. package/lib/Socket/index.js +0 -18
  102. package/lib/Socket/index.js.map +0 -1
  103. package/lib/Socket/messages-recv.d.ts +0 -173
  104. package/lib/Socket/messages-recv.d.ts.map +0 -1
  105. package/lib/Socket/messages-recv.js +0 -1228
  106. package/lib/Socket/messages-recv.js.map +0 -1
  107. package/lib/Socket/messages-send.d.ts +0 -169
  108. package/lib/Socket/messages-send.d.ts.map +0 -1
  109. package/lib/Socket/messages-send.js +0 -953
  110. package/lib/Socket/messages-send.js.map +0 -1
  111. package/lib/Socket/mex.d.ts +0 -3
  112. package/lib/Socket/mex.d.ts.map +0 -1
  113. package/lib/Socket/mex.js +0 -42
  114. package/lib/Socket/mex.js.map +0 -1
  115. package/lib/Socket/newsletter.d.ts +0 -147
  116. package/lib/Socket/newsletter.d.ts.map +0 -1
  117. package/lib/Socket/newsletter.js +0 -181
  118. package/lib/Socket/newsletter.js.map +0 -1
  119. package/lib/Socket/socket.d.ts +0 -51
  120. package/lib/Socket/socket.d.ts.map +0 -1
  121. package/lib/Socket/socket.js +0 -864
  122. package/lib/Socket/socket.js.map +0 -1
  123. package/lib/Types/Auth.d.ts +0 -111
  124. package/lib/Types/Auth.d.ts.map +0 -1
  125. package/lib/Types/Auth.js +0 -2
  126. package/lib/Types/Auth.js.map +0 -1
  127. package/lib/Types/Bussines.d.ts +0 -25
  128. package/lib/Types/Bussines.d.ts.map +0 -1
  129. package/lib/Types/Bussines.js +0 -2
  130. package/lib/Types/Bussines.js.map +0 -1
  131. package/lib/Types/Call.d.ts +0 -14
  132. package/lib/Types/Call.d.ts.map +0 -1
  133. package/lib/Types/Call.js +0 -2
  134. package/lib/Types/Call.js.map +0 -1
  135. package/lib/Types/Chat.d.ts +0 -123
  136. package/lib/Types/Chat.d.ts.map +0 -1
  137. package/lib/Types/Chat.js +0 -8
  138. package/lib/Types/Chat.js.map +0 -1
  139. package/lib/Types/Contact.d.ts +0 -24
  140. package/lib/Types/Contact.d.ts.map +0 -1
  141. package/lib/Types/Contact.js +0 -2
  142. package/lib/Types/Contact.js.map +0 -1
  143. package/lib/Types/Events.d.ts +0 -202
  144. package/lib/Types/Events.d.ts.map +0 -1
  145. package/lib/Types/Events.js +0 -2
  146. package/lib/Types/Events.js.map +0 -1
  147. package/lib/Types/GroupMetadata.d.ts +0 -67
  148. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  149. package/lib/Types/GroupMetadata.js +0 -2
  150. package/lib/Types/GroupMetadata.js.map +0 -1
  151. package/lib/Types/Label.d.ts +0 -47
  152. package/lib/Types/Label.d.ts.map +0 -1
  153. package/lib/Types/Label.js +0 -25
  154. package/lib/Types/Label.js.map +0 -1
  155. package/lib/Types/LabelAssociation.d.ts +0 -30
  156. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  157. package/lib/Types/LabelAssociation.js +0 -7
  158. package/lib/Types/LabelAssociation.js.map +0 -1
  159. package/lib/Types/Message.d.ts +0 -303
  160. package/lib/Types/Message.d.ts.map +0 -1
  161. package/lib/Types/Message.js +0 -11
  162. package/lib/Types/Message.js.map +0 -1
  163. package/lib/Types/Newsletter.d.ts +0 -135
  164. package/lib/Types/Newsletter.d.ts.map +0 -1
  165. package/lib/Types/Newsletter.js +0 -31
  166. package/lib/Types/Newsletter.js.map +0 -1
  167. package/lib/Types/Product.d.ts +0 -79
  168. package/lib/Types/Product.d.ts.map +0 -1
  169. package/lib/Types/Product.js +0 -2
  170. package/lib/Types/Product.js.map +0 -1
  171. package/lib/Types/Signal.d.ts +0 -76
  172. package/lib/Types/Signal.d.ts.map +0 -1
  173. package/lib/Types/Signal.js +0 -2
  174. package/lib/Types/Signal.js.map +0 -1
  175. package/lib/Types/Socket.d.ts +0 -133
  176. package/lib/Types/Socket.d.ts.map +0 -1
  177. package/lib/Types/Socket.js +0 -3
  178. package/lib/Types/Socket.js.map +0 -1
  179. package/lib/Types/State.d.ts +0 -39
  180. package/lib/Types/State.d.ts.map +0 -1
  181. package/lib/Types/State.js +0 -13
  182. package/lib/Types/State.js.map +0 -1
  183. package/lib/Types/USync.d.ts +0 -26
  184. package/lib/Types/USync.d.ts.map +0 -1
  185. package/lib/Types/USync.js +0 -2
  186. package/lib/Types/USync.js.map +0 -1
  187. package/lib/Types/index.d.ts +0 -65
  188. package/lib/Types/index.d.ts.map +0 -1
  189. package/lib/Types/index.js +0 -26
  190. package/lib/Types/index.js.map +0 -1
  191. package/lib/Utils/auth-utils.d.ts +0 -19
  192. package/lib/Utils/auth-utils.d.ts.map +0 -1
  193. package/lib/Utils/auth-utils.js +0 -257
  194. package/lib/Utils/auth-utils.js.map +0 -1
  195. package/lib/Utils/baileys-event-stream.d.ts +0 -17
  196. package/lib/Utils/baileys-event-stream.d.ts.map +0 -1
  197. package/lib/Utils/baileys-event-stream.js +0 -56
  198. package/lib/Utils/baileys-event-stream.js.map +0 -1
  199. package/lib/Utils/browser-utils.d.ts +0 -4
  200. package/lib/Utils/browser-utils.d.ts.map +0 -1
  201. package/lib/Utils/browser-utils.js +0 -28
  202. package/lib/Utils/browser-utils.js.map +0 -1
  203. package/lib/Utils/business.d.ts +0 -23
  204. package/lib/Utils/business.d.ts.map +0 -1
  205. package/lib/Utils/business.js +0 -231
  206. package/lib/Utils/business.js.map +0 -1
  207. package/lib/Utils/chat-utils.d.ts +0 -70
  208. package/lib/Utils/chat-utils.d.ts.map +0 -1
  209. package/lib/Utils/chat-utils.js +0 -763
  210. package/lib/Utils/chat-utils.js.map +0 -1
  211. package/lib/Utils/crypto.d.ts +0 -41
  212. package/lib/Utils/crypto.d.ts.map +0 -1
  213. package/lib/Utils/crypto.js +0 -142
  214. package/lib/Utils/crypto.js.map +0 -1
  215. package/lib/Utils/decode-wa-message.d.ts +0 -48
  216. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  217. package/lib/Utils/decode-wa-message.js +0 -279
  218. package/lib/Utils/decode-wa-message.js.map +0 -1
  219. package/lib/Utils/event-buffer.d.ts +0 -34
  220. package/lib/Utils/event-buffer.d.ts.map +0 -1
  221. package/lib/Utils/event-buffer.js +0 -548
  222. package/lib/Utils/event-buffer.js.map +0 -1
  223. package/lib/Utils/generics.d.ts +0 -90
  224. package/lib/Utils/generics.d.ts.map +0 -1
  225. package/lib/Utils/generics.js +0 -381
  226. package/lib/Utils/generics.js.map +0 -1
  227. package/lib/Utils/history.d.ts +0 -19
  228. package/lib/Utils/history.d.ts.map +0 -1
  229. package/lib/Utils/history.js +0 -84
  230. package/lib/Utils/history.js.map +0 -1
  231. package/lib/Utils/index.d.ts +0 -20
  232. package/lib/Utils/index.d.ts.map +0 -1
  233. package/lib/Utils/index.js +0 -19
  234. package/lib/Utils/index.js.map +0 -1
  235. package/lib/Utils/link-preview.d.ts +0 -21
  236. package/lib/Utils/link-preview.d.ts.map +0 -1
  237. package/lib/Utils/link-preview.js +0 -85
  238. package/lib/Utils/link-preview.js.map +0 -1
  239. package/lib/Utils/logger.d.ts +0 -12
  240. package/lib/Utils/logger.d.ts.map +0 -1
  241. package/lib/Utils/logger.js +0 -3
  242. package/lib/Utils/logger.js.map +0 -1
  243. package/lib/Utils/lt-hash.d.ts +0 -13
  244. package/lib/Utils/lt-hash.d.ts.map +0 -1
  245. package/lib/Utils/lt-hash.js +0 -48
  246. package/lib/Utils/lt-hash.js.map +0 -1
  247. package/lib/Utils/make-mutex.d.ts +0 -8
  248. package/lib/Utils/make-mutex.d.ts.map +0 -1
  249. package/lib/Utils/make-mutex.js +0 -40
  250. package/lib/Utils/make-mutex.js.map +0 -1
  251. package/lib/Utils/message-retry-manager.d.ts +0 -82
  252. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  253. package/lib/Utils/message-retry-manager.js +0 -149
  254. package/lib/Utils/message-retry-manager.js.map +0 -1
  255. package/lib/Utils/messages-media.d.ts +0 -114
  256. package/lib/Utils/messages-media.d.ts.map +0 -1
  257. package/lib/Utils/messages-media.js +0 -663
  258. package/lib/Utils/messages-media.js.map +0 -1
  259. package/lib/Utils/messages.d.ts +0 -76
  260. package/lib/Utils/messages.d.ts.map +0 -1
  261. package/lib/Utils/messages.js +0 -820
  262. package/lib/Utils/messages.js.map +0 -1
  263. package/lib/Utils/noise-handler.d.ts +0 -20
  264. package/lib/Utils/noise-handler.d.ts.map +0 -1
  265. package/lib/Utils/noise-handler.js +0 -147
  266. package/lib/Utils/noise-handler.js.map +0 -1
  267. package/lib/Utils/pre-key-manager.d.ts +0 -28
  268. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  269. package/lib/Utils/pre-key-manager.js +0 -106
  270. package/lib/Utils/pre-key-manager.js.map +0 -1
  271. package/lib/Utils/process-message.d.ts +0 -42
  272. package/lib/Utils/process-message.d.ts.map +0 -1
  273. package/lib/Utils/process-message.js +0 -413
  274. package/lib/Utils/process-message.js.map +0 -1
  275. package/lib/Utils/signal.d.ts +0 -34
  276. package/lib/Utils/signal.d.ts.map +0 -1
  277. package/lib/Utils/signal.js +0 -159
  278. package/lib/Utils/signal.js.map +0 -1
  279. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  280. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  281. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  282. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  283. package/lib/Utils/validate-connection.d.ts +0 -11
  284. package/lib/Utils/validate-connection.d.ts.map +0 -1
  285. package/lib/Utils/validate-connection.js +0 -195
  286. package/lib/Utils/validate-connection.js.map +0 -1
  287. package/lib/WABinary/constants.d.ts +0 -28
  288. package/lib/WABinary/constants.d.ts.map +0 -1
  289. package/lib/WABinary/constants.js +0 -1301
  290. package/lib/WABinary/constants.js.map +0 -1
  291. package/lib/WABinary/decode.d.ts +0 -7
  292. package/lib/WABinary/decode.d.ts.map +0 -1
  293. package/lib/WABinary/decode.js +0 -238
  294. package/lib/WABinary/decode.js.map +0 -1
  295. package/lib/WABinary/encode.d.ts +0 -3
  296. package/lib/WABinary/encode.d.ts.map +0 -1
  297. package/lib/WABinary/encode.js +0 -216
  298. package/lib/WABinary/encode.js.map +0 -1
  299. package/lib/WABinary/generic-utils.d.ts +0 -15
  300. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  301. package/lib/WABinary/generic-utils.js +0 -102
  302. package/lib/WABinary/generic-utils.js.map +0 -1
  303. package/lib/WABinary/index.d.ts +0 -6
  304. package/lib/WABinary/index.d.ts.map +0 -1
  305. package/lib/WABinary/index.js +0 -6
  306. package/lib/WABinary/index.js.map +0 -1
  307. package/lib/WABinary/jid-utils.d.ts +0 -48
  308. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  309. package/lib/WABinary/jid-utils.js +0 -96
  310. package/lib/WABinary/jid-utils.js.map +0 -1
  311. package/lib/WABinary/types.d.ts +0 -19
  312. package/lib/WABinary/types.d.ts.map +0 -1
  313. package/lib/WABinary/types.js +0 -2
  314. package/lib/WABinary/types.js.map +0 -1
  315. package/lib/WAM/BinaryInfo.d.ts +0 -9
  316. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  317. package/lib/WAM/BinaryInfo.js +0 -10
  318. package/lib/WAM/BinaryInfo.js.map +0 -1
  319. package/lib/WAM/constants.d.ts +0 -40
  320. package/lib/WAM/constants.d.ts.map +0 -1
  321. package/lib/WAM/constants.js +0 -22853
  322. package/lib/WAM/constants.js.map +0 -1
  323. package/lib/WAM/encode.d.ts +0 -3
  324. package/lib/WAM/encode.d.ts.map +0 -1
  325. package/lib/WAM/encode.js +0 -150
  326. package/lib/WAM/encode.js.map +0 -1
  327. package/lib/WAM/index.d.ts +0 -4
  328. package/lib/WAM/index.d.ts.map +0 -1
  329. package/lib/WAM/index.js +0 -4
  330. package/lib/WAM/index.js.map +0 -1
  331. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  332. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  333. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -29
  334. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  335. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -23
  336. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  337. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  338. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  339. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -13
  340. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  341. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  342. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  343. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -13
  344. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  345. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  346. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  347. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
  348. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  349. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  350. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  351. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
  352. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  353. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  354. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  355. package/lib/WAUSync/Protocols/index.d.ts +0 -5
  356. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  357. package/lib/WAUSync/Protocols/index.js +0 -5
  358. package/lib/WAUSync/Protocols/index.js.map +0 -1
  359. package/lib/WAUSync/USyncQuery.d.ts +0 -29
  360. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  361. package/lib/WAUSync/USyncQuery.js +0 -94
  362. package/lib/WAUSync/USyncQuery.js.map +0 -1
  363. package/lib/WAUSync/USyncUser.d.ts +0 -13
  364. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  365. package/lib/WAUSync/USyncUser.js +0 -23
  366. package/lib/WAUSync/USyncUser.js.map +0 -1
  367. package/lib/WAUSync/index.d.ts +0 -4
  368. package/lib/WAUSync/index.d.ts.map +0 -1
  369. package/lib/WAUSync/index.js +0 -4
  370. package/lib/WAUSync/index.js.map +0 -1
  371. package/lib/index.d.ts +0 -12
  372. package/lib/index.d.ts.map +0 -1
  373. package/lib/index.js +0 -11
  374. package/lib/index.js.map +0 -1
@@ -1,864 +0,0 @@
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';
14
- /**
15
- * Connects to WA servers and performs:
16
- * - simple queries (no retry mechanism, wait for connection establishment)
17
- * - listen to messages and emit events
18
- * - query phone connection
19
- */
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;
52
- if (config.mobile || url.protocol === 'tcp:') {
53
- throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
54
- }
55
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
56
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
57
- }
58
- /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
59
- const ephemeralKeyPair = Curve.generateKeyPair();
60
- /** WA noise protocol wrapper */
61
- const noise = makeNoiseHandler({
62
- keyPair: ephemeralKeyPair,
63
- NOISE_HEADER: NOISE_WA_HEADER,
64
- logger,
65
- routingInfo: authState?.creds?.routingInfo
66
- });
67
- const ws = new WebSocketClient(url, config);
68
- ws.connect();
69
- const sendPromise = promisify(ws.send);
70
- /** send a raw buffer */
71
- const sendRawMessage = async (data) => {
72
- if (!ws.isOpen) {
73
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
74
- }
75
- const bytes = noise.encodeFrame(data);
76
- await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
77
- try {
78
- await sendPromise.call(ws, bytes);
79
- resolve();
80
- }
81
- catch (error) {
82
- reject(error);
83
- }
84
- });
85
- };
86
- /** send a binary node */
87
- const sendNode = (frame) => {
88
- if (logger.level === 'trace') {
89
- logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
90
- }
91
- const buff = encodeBinaryNode(frame);
92
- return sendRawMessage(buff);
93
- };
94
- /**
95
- * Wait for a message with a certain tag to be received
96
- * @param msgId the message tag to await
97
- * @param timeoutMs timeout after which the promise will reject
98
- */
99
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
100
- let onRecv;
101
- let onErr;
102
- try {
103
- const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
104
- onRecv = data => {
105
- resolve(data);
106
- };
107
- onErr = err => {
108
- 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;
119
- }
120
- catch (error) {
121
- // 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;
125
- }
126
- throw error;
127
- }
128
- finally {
129
- if (onRecv)
130
- ws.off(`TAG:${msgId}`, onRecv);
131
- if (onErr) {
132
- ws.off('close', onErr);
133
- ws.off('error', onErr);
134
- }
135
- }
136
- };
137
- /** send a query, and wait for its response. auto-generates message ID if not provided */
138
- const query = async (node, timeoutMs) => {
139
- if (!node.attrs.id) {
140
- node.attrs.id = generateMessageTag();
141
- }
142
- const msgId = node.attrs.id;
143
- const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
144
- const result = waitForMessage(msgId, timeoutMs).catch(reject);
145
- sendNode(node)
146
- .then(async () => resolve(await result))
147
- .catch(reject);
148
- });
149
- if (result && 'tag' in result) {
150
- assertNodeErrorFree(result);
151
- }
152
- return result;
153
- };
154
- const executeUSyncQuery = async (usyncQuery) => {
155
- if (usyncQuery.protocols.length === 0) {
156
- throw new Boom('USyncQuery must have at least one protocol');
157
- }
158
- // todo: validate users, throw WARNING on no valid users
159
- // variable below has only validated users
160
- const validUsers = usyncQuery.users;
161
- const userNodes = validUsers.map(user => {
162
- return {
163
- tag: 'user',
164
- attrs: {
165
- jid: !user.phone ? user.id : undefined
166
- },
167
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
168
- };
169
- });
170
- const listNode = {
171
- tag: 'list',
172
- attrs: {},
173
- content: userNodes
174
- };
175
- const queryNode = {
176
- tag: 'query',
177
- attrs: {},
178
- content: usyncQuery.protocols.map(a => a.getQueryElement())
179
- };
180
- const iq = {
181
- tag: 'iq',
182
- attrs: {
183
- to: S_WHATSAPP_NET,
184
- type: 'get',
185
- xmlns: 'usync'
186
- },
187
- content: [
188
- {
189
- tag: 'usync',
190
- attrs: {
191
- context: usyncQuery.context,
192
- mode: usyncQuery.mode,
193
- sid: generateMessageTag(),
194
- last: 'true',
195
- index: '0'
196
- },
197
- content: [queryNode, listNode]
198
- }
199
- ]
200
- };
201
- const result = await query(iq);
202
- return usyncQuery.parseUSyncQueryResult(result);
203
- };
204
- const onWhatsApp = async (...phoneNumber) => {
205
- let usyncQuery = new USyncQuery();
206
- let contactEnabled = false;
207
- for (const jid of phoneNumber) {
208
- if (isLidUser(jid)) {
209
- logger?.warn('LIDs are not supported with onWhatsApp');
210
- continue;
211
- }
212
- else {
213
- if (!contactEnabled) {
214
- contactEnabled = true;
215
- usyncQuery = usyncQuery.withContactProtocol();
216
- }
217
- const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
218
- usyncQuery.withUser(new USyncUser().withPhone(phone));
219
- }
220
- }
221
- if (usyncQuery.users.length === 0) {
222
- return []; // return early without forcing an empty query
223
- }
224
- const results = await executeUSyncQuery(usyncQuery);
225
- if (results) {
226
- return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
227
- }
228
- };
229
- const pnFromLIDUSync = async (jids) => {
230
- const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
231
- for (const jid of jids) {
232
- if (isLidUser(jid)) {
233
- logger?.warn('LID user found in LID fetch call');
234
- continue;
235
- }
236
- else {
237
- usyncQuery.withUser(new USyncUser().withId(jid));
238
- }
239
- }
240
- if (usyncQuery.users.length === 0) {
241
- return []; // return early without forcing an empty query
242
- }
243
- const results = await executeUSyncQuery(usyncQuery);
244
- if (results) {
245
- return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
246
- }
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
- };
288
- /** connection handshake */
289
- const validateConnection = async () => {
290
- let helloMsg = {
291
- 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;
301
- if (!creds.me) {
302
- node = generateRegistrationNode(creds, config);
303
- logger.info({ node }, 'not logged in, attempting registration...');
304
- }
305
- else {
306
- node = generateLoginNode(creds.me.id, config);
307
- logger.info({ node }, 'logging in...');
308
- }
309
- const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
310
- await sendRawMessage(proto.HandshakeMessage.encode({
311
- clientFinish: {
312
- static: keyEnc,
313
- payload: payloadEnc
314
- }
315
- }).finish());
316
- noise.finishInit();
317
- startKeepAliveRequest();
318
- };
319
- const getAvailablePreKeysOnServer = async () => {
320
- const result = await query({
321
- tag: 'iq',
322
- attrs: {
323
- id: generateMessageTag(),
324
- xmlns: 'encrypt',
325
- type: 'get',
326
- to: S_WHATSAPP_NET
327
- },
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;
336
- /** 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
- };
400
- 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
- }
426
- }
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 => {
434
- // reset ping timeout
435
- lastDateRecv = new Date();
436
- let anyTriggered = false;
437
- anyTriggered = ws.emit('frame', frame);
438
- // if it's a binary node
439
- if (!(frame instanceof Uint8Array)) {
440
- const msgId = frame.attrs.id;
441
- if (logger.level === 'trace') {
442
- logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
443
- }
444
- /* Check if this is a response to a message we sent */
445
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
446
- /* 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 : '';
450
- 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;
454
- }
455
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
456
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
457
- if (!anyTriggered && logger.level === 'debug') {
458
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
459
- }
460
- }
461
- });
462
- };
463
- const end = (error) => {
464
- 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');
475
- if (!ws.isClosed && !ws.isClosing) {
476
- try {
477
- ws.close();
478
- }
479
- catch { }
480
- }
481
- ev.emit('connection.update', {
482
- connection: 'close',
483
- lastDisconnect: {
484
- error,
485
- date: new Date()
486
- }
487
- });
488
- ev.removeAllListeners('connection.update');
489
- };
490
- const waitForSocketOpen = async () => {
491
- if (ws.isOpen) {
492
- return;
493
- }
494
- if (ws.isClosed || ws.isClosing) {
495
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
496
- }
497
- let onOpen;
498
- let onClose;
499
- 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);
505
- }).finally(() => {
506
- ws.off('open', onOpen);
507
- ws.off('close', onClose);
508
- ws.off('error', onClose);
509
- });
510
- };
511
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
512
- if (!lastDateRecv) {
513
- lastDateRecv = new Date();
514
- }
515
- const diff = Date.now() - lastDateRecv.getTime();
516
- /*
517
- check if it's been a suspicious amount of time since the server responded with our last seen
518
- it could be that the network is down
519
- */
520
- if (diff > keepAliveIntervalMs + 5000) {
521
- end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
522
- }
523
- else if (ws.isOpen) {
524
- // if its all good, send a keep alive request
525
- query({
526
- tag: 'iq',
527
- attrs: {
528
- id: generateMessageTag(),
529
- to: S_WHATSAPP_NET,
530
- type: 'get',
531
- xmlns: 'w:p'
532
- },
533
- content: [{ tag: 'ping', attrs: {} }]
534
- }).catch(err => {
535
- logger.error({ trace: err.stack }, 'error in sending keep alive');
536
- });
537
- }
538
- else {
539
- logger.warn('keep alive called when WS not open');
540
- }
541
- }, keepAliveIntervalMs));
542
- /** i have no idea why this exists. pls enlighten me */
543
- const sendPassiveIq = (tag) => query({
544
- tag: 'iq',
545
- attrs: {
546
- to: S_WHATSAPP_NET,
547
- xmlns: 'passive',
548
- type: 'set'
549
- },
550
- content: [{ tag, attrs: {} }]
551
- });
552
- /** logout & invalidate connection */
553
- const logout = async (msg) => {
554
- const jid = authState.creds.me?.id;
555
- if (jid) {
556
- await sendNode({
557
- tag: 'iq',
558
- attrs: {
559
- to: S_WHATSAPP_NET,
560
- type: 'set',
561
- id: generateMessageTag(),
562
- xmlns: 'md'
563
- },
564
- content: [
565
- {
566
- tag: 'remove-companion-device',
567
- attrs: {
568
- jid,
569
- reason: 'user_initiated'
570
- }
571
- }
572
- ]
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
- };
636
- 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]);
642
- }
643
- const sendWAMBuffer = (wamBuffer) => {
644
- return query({
645
- tag: 'iq',
646
- attrs: {
647
- to: S_WHATSAPP_NET,
648
- id: generateMessageTag(),
649
- xmlns: 'w:stats'
650
- },
651
- content: [
652
- {
653
- tag: 'add',
654
- attrs: { t: Math.round(Date.now() / 1000) + '' },
655
- content: wamBuffer
656
- }
657
- ]
658
- });
659
- };
660
- ws.on('message', onMessageReceived);
661
- ws.on('open', async () => {
662
- try {
663
- await validateConnection();
664
- }
665
- 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 })));
672
- // the server terminated the connection
673
- ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
674
- // QR gen
675
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
676
- const iq = {
677
- tag: 'iq',
678
- attrs: {
679
- to: S_WHATSAPP_NET,
680
- type: 'result',
681
- id: stanza.attrs.id
682
- }
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
691
- const genPairQR = () => {
692
- if (!ws.isOpen) {
693
- return;
694
- }
695
- const refNode = refNodes.shift();
696
- if (!refNode) {
697
- end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
698
- return;
699
- }
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
- });
708
- // device paired for the first time
709
- // if device pairs successfully, the server asks to restart the connection
710
- ws.on('CB:iq,,pair-success', async (stanza) => {
711
- logger.debug('pair success recv');
712
- 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
- }
719
- catch (error) {
720
- logger.info({ trace: error.stack }, 'error in pairing');
721
- end(error);
722
- }
723
- });
724
- // login complete
725
- ws.on('CB:success', async (node) => {
726
- try {
727
- await uploadPreKeysToServerIfRequired();
728
- await sendPassiveIq('active');
729
- }
730
- catch (err) {
731
- logger.warn({ err }, 'failed to send initial passive iq');
732
- }
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' });
737
- if (node.attrs.lid && authState.creds.me?.id) {
738
- const myLID = node.attrs.lid;
739
- process.nextTick(async () => {
740
- try {
741
- const myPN = authState.creds.me.id;
742
- // Store our own LID-PN mapping
743
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
744
- // Create device list for our own user (needed for bulk migration)
745
- const { user, device } = jidDecode(myPN);
746
- await authState.keys.set({
747
- 'device-list': {
748
- [user]: [device?.toString() || '0']
749
- }
750
- });
751
- // migrate our own session
752
- await signalRepository.migrateSession(myPN, myLID);
753
- logger.info({ myPN, myLID }, 'Own LID session created successfully');
754
- }
755
- catch (error) {
756
- logger.error({ error, lid: myLID }, 'Failed to create own LID session');
757
- }
758
- });
759
- }
760
- });
761
- 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
- });
766
- // stream fail, possible logout
767
- ws.on('CB:failure', (node) => {
768
- const reason = +(node.attrs.reason || 500);
769
- end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
770
- });
771
- 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({
777
- tag: 'ib',
778
- attrs: {},
779
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
780
- });
781
- });
782
- ws.on('CB:ib,,edge_routing', (node) => {
783
- const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
784
- const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
785
- if (routingInfo?.content) {
786
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
787
- ev.emit('creds.update', authState.creds);
788
- }
789
- });
790
- let didStartBuffer = false;
791
- process.nextTick(() => {
792
- if (creds.me?.id) {
793
- // start buffering important events
794
- // if we're logged in
795
- ev.buffer();
796
- didStartBuffer = true;
797
- }
798
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
799
- });
800
- // called when all offline notifs are handled
801
- 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`);
805
- if (didStartBuffer) {
806
- ev.flush();
807
- logger.trace('flushed events for initial buffer');
808
- }
809
- ev.emit('connection.update', { receivedPendingNotifications: true });
810
- });
811
- // update credentials when required
812
- ev.on('creds.update', update => {
813
- const name = update.me?.name;
814
- // if name has just been received
815
- if (creds.me?.name !== name) {
816
- logger.debug({ name }, 'updated pushName');
817
- sendNode({
818
- tag: 'presence',
819
- attrs: { name: name }
820
- }).catch(err => {
821
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
822
- });
823
- }
824
- Object.assign(creds, update);
825
- });
826
- return {
827
- type: 'md',
828
- ws,
829
- ev,
830
- authState: { creds, keys },
831
- signalRepository,
832
- get user() {
833
- return authState.creds.me;
834
- },
835
- generateMessageTag,
836
- query,
837
- waitForMessage,
838
- waitForSocketOpen,
839
- sendRawMessage,
840
- sendNode,
841
- logout,
842
- end,
843
- onUnexpectedError,
844
- uploadPreKeys,
845
- uploadPreKeysToServerIfRequired,
846
- requestPairingCode,
847
- wamBuffer: publicWAMBuffer,
848
- /** Waits for the connection to WA to reach a state */
849
- waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
850
- sendWAMBuffer,
851
- executeUSyncQuery,
852
- onWhatsApp
853
- };
854
- };
855
- /**
856
- * map the websocket error to the right type
857
- * so it can be retried by the caller
858
- * */
859
- function mapWebSocketError(handler) {
860
- return (error) => {
861
- handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
862
- };
863
- }
864
- //# sourceMappingURL=socket.js.map