xero-wa 1.0.10

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