baileys-joss 1.0.0

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