@violetix/baileys 0.0.0-stage → 0.4.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 (458) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +3017 -2
  3. package/WAProto/index.d.ts +15932 -0
  4. package/WAProto/index.js +115856 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.d.ts +145 -0
  7. package/lib/Defaults/index.d.ts.map +1 -0
  8. package/lib/Defaults/index.js +157 -0
  9. package/lib/Defaults/index.js.map +1 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.js +30 -0
  17. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  18. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  19. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  20. package/lib/Signal/Group/group_cipher.js +82 -0
  21. package/lib/Signal/Group/group_cipher.js.map +1 -0
  22. package/lib/Signal/Group/index.d.ts +12 -0
  23. package/lib/Signal/Group/index.d.ts.map +1 -0
  24. package/lib/Signal/Group/index.js +12 -0
  25. package/lib/Signal/Group/index.js.map +1 -0
  26. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  27. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  28. package/lib/Signal/Group/keyhelper.js +18 -0
  29. package/lib/Signal/Group/keyhelper.js.map +1 -0
  30. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.js +26 -0
  33. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  34. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.js +66 -0
  41. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.js +48 -0
  45. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.js +41 -0
  49. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.js +84 -0
  53. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  54. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.js +26 -0
  57. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  58. package/lib/Signal/libsignal.d.ts +55 -0
  59. package/lib/Signal/libsignal.d.ts.map +1 -0
  60. package/lib/Signal/libsignal.js +403 -0
  61. package/lib/Signal/libsignal.js.map +1 -0
  62. package/lib/Signal/lid-mapping.d.ts +21 -0
  63. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  64. package/lib/Signal/lid-mapping.js +277 -0
  65. package/lib/Signal/lid-mapping.js.map +1 -0
  66. package/lib/Socket/Client/index.d.ts +3 -0
  67. package/lib/Socket/Client/index.d.ts.map +1 -0
  68. package/lib/Socket/Client/index.js +3 -0
  69. package/lib/Socket/Client/index.js.map +1 -0
  70. package/lib/Socket/Client/types.d.ts +6 -0
  71. package/lib/Socket/Client/types.d.ts.map +1 -0
  72. package/lib/Socket/Client/types.js +93 -0
  73. package/lib/Socket/Client/types.js.map +1 -0
  74. package/lib/Socket/Client/websocket.d.ts +13 -0
  75. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  76. package/lib/Socket/Client/websocket.js +57 -0
  77. package/lib/Socket/Client/websocket.js.map +1 -0
  78. package/lib/Socket/business.d.ts +428 -0
  79. package/lib/Socket/business.d.ts.map +1 -0
  80. package/lib/Socket/business.js +380 -0
  81. package/lib/Socket/business.js.map +1 -0
  82. package/lib/Socket/chats.d.ts +176 -0
  83. package/lib/Socket/chats.d.ts.map +1 -0
  84. package/lib/Socket/chats.js +1238 -0
  85. package/lib/Socket/chats.js.map +1 -0
  86. package/lib/Socket/communities.d.ts +595 -0
  87. package/lib/Socket/communities.d.ts.map +1 -0
  88. package/lib/Socket/communities.js +432 -0
  89. package/lib/Socket/communities.js.map +1 -0
  90. package/lib/Socket/graphql.js +908 -0
  91. package/lib/Socket/groups.d.ts +318 -0
  92. package/lib/Socket/groups.d.ts.map +1 -0
  93. package/lib/Socket/groups.js +364 -0
  94. package/lib/Socket/groups.js.map +1 -0
  95. package/lib/Socket/index.d.ts +947 -0
  96. package/lib/Socket/index.d.ts.map +1 -0
  97. package/lib/Socket/index.js +19 -0
  98. package/lib/Socket/index.js.map +1 -0
  99. package/lib/Socket/interop.js +562 -0
  100. package/lib/Socket/managed-account.js +210 -0
  101. package/lib/Socket/messages-recv.d.ts +367 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +2199 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +364 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1631 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +2 -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 +315 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +235 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/privacy.js +448 -0
  118. package/lib/Socket/registration.js +430 -0
  119. package/lib/Socket/socket.d.ts +99 -0
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +1290 -0
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Store/index.d.ts +4 -0
  124. package/lib/Store/index.d.ts.map +1 -0
  125. package/lib/Store/index.js +4 -0
  126. package/lib/Store/index.js.map +1 -0
  127. package/lib/Store/make-in-memory-store.d.ts +63 -0
  128. package/lib/Store/make-in-memory-store.d.ts.map +1 -0
  129. package/lib/Store/make-in-memory-store.js +462 -0
  130. package/lib/Store/make-in-memory-store.js.map +1 -0
  131. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  132. package/lib/Store/make-ordered-dictionary.d.ts.map +1 -0
  133. package/lib/Store/make-ordered-dictionary.js +79 -0
  134. package/lib/Store/make-ordered-dictionary.js.map +1 -0
  135. package/lib/Store/object-repository.d.ts +11 -0
  136. package/lib/Store/object-repository.d.ts.map +1 -0
  137. package/lib/Store/object-repository.js +24 -0
  138. package/lib/Store/object-repository.js.map +1 -0
  139. package/lib/Types/Auth.d.ts +60 -0
  140. package/lib/Types/Auth.d.ts.map +1 -0
  141. package/lib/Types/Auth.js +2 -0
  142. package/lib/Types/Auth.js.map +1 -0
  143. package/lib/Types/Bussines.d.ts +9 -0
  144. package/lib/Types/Bussines.d.ts.map +1 -0
  145. package/lib/Types/Bussines.js +2 -0
  146. package/lib/Types/Bussines.js.map +1 -0
  147. package/lib/Types/Call.d.ts +22 -0
  148. package/lib/Types/Call.d.ts.map +1 -0
  149. package/lib/Types/Call.js +2 -0
  150. package/lib/Types/Call.js.map +1 -0
  151. package/lib/Types/Chat.d.ts +3 -0
  152. package/lib/Types/Chat.d.ts.map +1 -0
  153. package/lib/Types/Chat.js +8 -0
  154. package/lib/Types/Chat.js.map +1 -0
  155. package/lib/Types/Contact.d.ts +11 -0
  156. package/lib/Types/Contact.d.ts.map +1 -0
  157. package/lib/Types/Contact.js +2 -0
  158. package/lib/Types/Contact.js.map +1 -0
  159. package/lib/Types/Events.d.ts +41 -0
  160. package/lib/Types/Events.d.ts.map +1 -0
  161. package/lib/Types/Events.js +2 -0
  162. package/lib/Types/Events.js.map +1 -0
  163. package/lib/Types/GroupMetadata.d.ts +36 -0
  164. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  165. package/lib/Types/GroupMetadata.js +2 -0
  166. package/lib/Types/GroupMetadata.js.map +1 -0
  167. package/lib/Types/Label.d.ts +3 -0
  168. package/lib/Types/Label.d.ts.map +1 -0
  169. package/lib/Types/Label.js +25 -0
  170. package/lib/Types/Label.js.map +1 -0
  171. package/lib/Types/LabelAssociation.d.ts +3 -0
  172. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  173. package/lib/Types/LabelAssociation.js +7 -0
  174. package/lib/Types/LabelAssociation.js.map +1 -0
  175. package/lib/Types/Message.d.ts +22 -0
  176. package/lib/Types/Message.d.ts.map +1 -0
  177. package/lib/Types/Message.js +18 -0
  178. package/lib/Types/Message.js.map +1 -0
  179. package/lib/Types/Mex.d.ts +3 -0
  180. package/lib/Types/Mex.d.ts.map +1 -0
  181. package/lib/Types/Mex.js +49 -0
  182. package/lib/Types/Mex.js.map +1 -0
  183. package/lib/Types/Product.d.ts +5 -0
  184. package/lib/Types/Product.d.ts.map +1 -0
  185. package/lib/Types/Product.js +2 -0
  186. package/lib/Types/Product.js.map +1 -0
  187. package/lib/Types/RichType.d.ts +3 -0
  188. package/lib/Types/RichType.d.ts.map +1 -0
  189. package/lib/Types/RichType.js +23 -0
  190. package/lib/Types/RichType.js.map +1 -0
  191. package/lib/Types/Signal.d.ts +10 -0
  192. package/lib/Types/Signal.d.ts.map +1 -0
  193. package/lib/Types/Signal.js +2 -0
  194. package/lib/Types/Signal.js.map +1 -0
  195. package/lib/Types/Socket.d.ts +33 -0
  196. package/lib/Types/Socket.d.ts.map +1 -0
  197. package/lib/Types/Socket.js +2 -0
  198. package/lib/Types/Socket.js.map +1 -0
  199. package/lib/Types/State.d.ts +6 -0
  200. package/lib/Types/State.d.ts.map +1 -0
  201. package/lib/Types/State.js +56 -0
  202. package/lib/Types/State.js.map +1 -0
  203. package/lib/Types/USync.d.ts +9 -0
  204. package/lib/Types/USync.d.ts.map +1 -0
  205. package/lib/Types/USync.js +2 -0
  206. package/lib/Types/USync.js.map +1 -0
  207. package/lib/Types/index.d.ts +16 -0
  208. package/lib/Types/index.d.ts.map +1 -0
  209. package/lib/Types/index.js +26 -0
  210. package/lib/Types/index.js.map +1 -0
  211. package/lib/Utils/a2ui.d.ts +50 -0
  212. package/lib/Utils/a2ui.js +168 -0
  213. package/lib/Utils/anchor-guard.d.ts +71 -0
  214. package/lib/Utils/anchor-guard.js +404 -0
  215. package/lib/Utils/async-utils.js +7 -0
  216. package/lib/Utils/auth-utils.d.ts +59 -0
  217. package/lib/Utils/auth-utils.d.ts.map +1 -0
  218. package/lib/Utils/auth-utils.js +306 -0
  219. package/lib/Utils/auth-utils.js.map +1 -0
  220. package/lib/Utils/browser-utils.d.ts +10 -0
  221. package/lib/Utils/browser-utils.d.ts.map +1 -0
  222. package/lib/Utils/browser-utils.js +29 -0
  223. package/lib/Utils/browser-utils.js.map +1 -0
  224. package/lib/Utils/business.d.ts +50 -0
  225. package/lib/Utils/business.d.ts.map +1 -0
  226. package/lib/Utils/business.js +245 -0
  227. package/lib/Utils/business.js.map +1 -0
  228. package/lib/Utils/chat-utils.d.ts +409 -0
  229. package/lib/Utils/chat-utils.d.ts.map +1 -0
  230. package/lib/Utils/chat-utils.js +872 -0
  231. package/lib/Utils/chat-utils.js.map +1 -0
  232. package/lib/Utils/companion-reg-client-utils.d.ts +10 -0
  233. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  234. package/lib/Utils/companion-reg-client-utils.js +69 -0
  235. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  236. package/lib/Utils/crypto-worker.js +20 -0
  237. package/lib/Utils/crypto.d.ts +40 -0
  238. package/lib/Utils/crypto.d.ts.map +1 -0
  239. package/lib/Utils/crypto.js +118 -0
  240. package/lib/Utils/crypto.js.map +1 -0
  241. package/lib/Utils/decode-wa-message.d.ts +85 -0
  242. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  243. package/lib/Utils/decode-wa-message.js +467 -0
  244. package/lib/Utils/decode-wa-message.js.map +1 -0
  245. package/lib/Utils/event-buffer.d.ts +13 -0
  246. package/lib/Utils/event-buffer.d.ts.map +1 -0
  247. package/lib/Utils/event-buffer.js +651 -0
  248. package/lib/Utils/event-buffer.js.map +1 -0
  249. package/lib/Utils/generics.d.ts +64 -0
  250. package/lib/Utils/generics.d.ts.map +1 -0
  251. package/lib/Utils/generics.js +442 -0
  252. package/lib/Utils/generics.js.map +1 -0
  253. package/lib/Utils/history.d.ts +77 -0
  254. package/lib/Utils/history.d.ts.map +1 -0
  255. package/lib/Utils/history.js +188 -0
  256. package/lib/Utils/history.js.map +1 -0
  257. package/lib/Utils/identity-change-handler.d.ts +14 -0
  258. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  259. package/lib/Utils/identity-change-handler.js +50 -0
  260. package/lib/Utils/identity-change-handler.js.map +1 -0
  261. package/lib/Utils/ignore-key.d.ts +51 -0
  262. package/lib/Utils/ignore-key.js +174 -0
  263. package/lib/Utils/index.d.ts +29 -0
  264. package/lib/Utils/index.d.ts.map +1 -0
  265. package/lib/Utils/index.js +29 -0
  266. package/lib/Utils/index.js.map +1 -0
  267. package/lib/Utils/link-preview.d.ts +13 -0
  268. package/lib/Utils/link-preview.d.ts.map +1 -0
  269. package/lib/Utils/link-preview.js +85 -0
  270. package/lib/Utils/link-preview.js.map +1 -0
  271. package/lib/Utils/listener-guard.js +48 -0
  272. package/lib/Utils/logger.d.ts +3 -0
  273. package/lib/Utils/logger.d.ts.map +1 -0
  274. package/lib/Utils/logger.js +3 -0
  275. package/lib/Utils/logger.js.map +1 -0
  276. package/lib/Utils/lt-hash.d.ts +7 -0
  277. package/lib/Utils/lt-hash.d.ts.map +1 -0
  278. package/lib/Utils/lt-hash.js +8 -0
  279. package/lib/Utils/lt-hash.js.map +1 -0
  280. package/lib/Utils/make-mutex.d.ts +7 -0
  281. package/lib/Utils/make-mutex.d.ts.map +1 -0
  282. package/lib/Utils/make-mutex.js +33 -0
  283. package/lib/Utils/make-mutex.js.map +1 -0
  284. package/lib/Utils/message-retry-manager.d.ts +80 -0
  285. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  286. package/lib/Utils/message-retry-manager.js +285 -0
  287. package/lib/Utils/message-retry-manager.js.map +1 -0
  288. package/lib/Utils/messages-media.d.ts +166 -0
  289. package/lib/Utils/messages-media.d.ts.map +1 -0
  290. package/lib/Utils/messages-media.js +979 -0
  291. package/lib/Utils/messages-media.js.map +1 -0
  292. package/lib/Utils/messages.d.ts +47 -0
  293. package/lib/Utils/messages.d.ts.map +1 -0
  294. package/lib/Utils/messages.js +1959 -0
  295. package/lib/Utils/messages.js.map +1 -0
  296. package/lib/Utils/meta-ai-msmsg.d.ts +12 -0
  297. package/lib/Utils/meta-ai-msmsg.js +124 -0
  298. package/lib/Utils/noise-handler.d.ts +21 -0
  299. package/lib/Utils/noise-handler.d.ts.map +1 -0
  300. package/lib/Utils/noise-handler.js +206 -0
  301. package/lib/Utils/noise-handler.js.map +1 -0
  302. package/lib/Utils/offline-node-processor.d.ts +10 -0
  303. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  304. package/lib/Utils/offline-node-processor.js +40 -0
  305. package/lib/Utils/offline-node-processor.js.map +1 -0
  306. package/lib/Utils/pre-key-manager.d.ts +26 -0
  307. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  308. package/lib/Utils/pre-key-manager.js +106 -0
  309. package/lib/Utils/pre-key-manager.js.map +1 -0
  310. package/lib/Utils/process-message.d.ts +102 -0
  311. package/lib/Utils/process-message.d.ts.map +1 -0
  312. package/lib/Utils/process-message.js +798 -0
  313. package/lib/Utils/process-message.js.map +1 -0
  314. package/lib/Utils/reporting-utils.d.ts +13 -0
  315. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  316. package/lib/Utils/reporting-utils.js +258 -0
  317. package/lib/Utils/reporting-utils.js.map +1 -0
  318. package/lib/Utils/rich-message-utils.d.ts +49 -0
  319. package/lib/Utils/rich-message-utils.d.ts.map +1 -0
  320. package/lib/Utils/rich-message-utils.js +369 -0
  321. package/lib/Utils/rich-message-utils.js.map +1 -0
  322. package/lib/Utils/session-queue.js +33 -0
  323. package/lib/Utils/signal.d.ts +83 -0
  324. package/lib/Utils/signal.d.ts.map +1 -0
  325. package/lib/Utils/signal.js +201 -0
  326. package/lib/Utils/signal.js.map +1 -0
  327. package/lib/Utils/stanza-ack.d.ts +22 -0
  328. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  329. package/lib/Utils/stanza-ack.js +72 -0
  330. package/lib/Utils/stanza-ack.js.map +1 -0
  331. package/lib/Utils/sync-action-utils.d.ts +3 -0
  332. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  333. package/lib/Utils/sync-action-utils.js +49 -0
  334. package/lib/Utils/sync-action-utils.js.map +1 -0
  335. package/lib/Utils/tc-token-utils.d.ts +30 -0
  336. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  337. package/lib/Utils/tc-token-utils.js +164 -0
  338. package/lib/Utils/tc-token-utils.js.map +1 -0
  339. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  340. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  341. package/lib/Utils/use-multi-file-auth-state.js +196 -0
  342. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  343. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts.map +1 -0
  345. package/lib/Utils/use-single-file-auth-state.js +118 -0
  346. package/lib/Utils/use-single-file-auth-state.js.map +1 -0
  347. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  348. package/lib/Utils/use-sqlite-auth-state.d.ts.map +1 -0
  349. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  350. package/lib/Utils/use-sqlite-auth-state.js.map +1 -0
  351. package/lib/Utils/validate-connection.d.ts +44 -0
  352. package/lib/Utils/validate-connection.d.ts.map +1 -0
  353. package/lib/Utils/validate-connection.js +210 -0
  354. package/lib/Utils/validate-connection.js.map +1 -0
  355. package/lib/Utils/worker-pool.js +73 -0
  356. package/lib/WABinary/constants.d.ts +62 -0
  357. package/lib/WABinary/constants.d.ts.map +1 -0
  358. package/lib/WABinary/constants.js +1467 -0
  359. package/lib/WABinary/constants.js.map +1 -0
  360. package/lib/WABinary/decode.d.ts +10 -0
  361. package/lib/WABinary/decode.d.ts.map +1 -0
  362. package/lib/WABinary/decode.js +262 -0
  363. package/lib/WABinary/decode.js.map +1 -0
  364. package/lib/WABinary/encode.d.ts +3 -0
  365. package/lib/WABinary/encode.d.ts.map +1 -0
  366. package/lib/WABinary/encode.js +220 -0
  367. package/lib/WABinary/encode.js.map +1 -0
  368. package/lib/WABinary/generic-utils.d.ts +77 -0
  369. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  370. package/lib/WABinary/generic-utils.js +226 -0
  371. package/lib/WABinary/generic-utils.js.map +1 -0
  372. package/lib/WABinary/index.d.ts +6 -0
  373. package/lib/WABinary/index.d.ts.map +1 -0
  374. package/lib/WABinary/index.js +6 -0
  375. package/lib/WABinary/index.js.map +1 -0
  376. package/lib/WABinary/jid-utils.d.ts +29 -0
  377. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  378. package/lib/WABinary/jid-utils.js +96 -0
  379. package/lib/WABinary/jid-utils.js.map +1 -0
  380. package/lib/WABinary/types.d.ts +6 -0
  381. package/lib/WABinary/types.d.ts.map +1 -0
  382. package/lib/WABinary/types.js +2 -0
  383. package/lib/WABinary/types.js.map +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +8 -0
  385. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  386. package/lib/WAM/BinaryInfo.js +10 -0
  387. package/lib/WAM/BinaryInfo.js.map +1 -0
  388. package/lib/WAM/constants.d.ts +34927 -0
  389. package/lib/WAM/constants.d.ts.map +1 -0
  390. package/lib/WAM/constants.js +22853 -0
  391. package/lib/WAM/constants.js.map +1 -0
  392. package/lib/WAM/encode.d.ts +2 -0
  393. package/lib/WAM/encode.d.ts.map +1 -0
  394. package/lib/WAM/encode.js +150 -0
  395. package/lib/WAM/encode.js.map +1 -0
  396. package/lib/WAM/index.d.ts +4 -0
  397. package/lib/WAM/index.d.ts.map +1 -0
  398. package/lib/WAM/index.js +4 -0
  399. package/lib/WAM/index.js.map +1 -0
  400. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +8 -0
  401. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +99 -0
  402. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  403. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  404. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -0
  405. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  406. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  407. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  408. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  409. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  410. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  411. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  412. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  413. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  414. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +9 -0
  415. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  416. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  418. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +10 -0
  419. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  420. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  421. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  422. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  423. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  424. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +11 -0
  425. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  426. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  427. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  428. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +31 -0
  429. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  430. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  431. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  432. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  433. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  434. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  435. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  436. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  437. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  438. package/lib/WAUSync/Protocols/index.d.ts +11 -0
  439. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  440. package/lib/WAUSync/Protocols/index.js +11 -0
  441. package/lib/WAUSync/Protocols/index.js.map +1 -0
  442. package/lib/WAUSync/USyncQuery.d.ts +32 -0
  443. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  444. package/lib/WAUSync/USyncQuery.js +185 -0
  445. package/lib/WAUSync/USyncQuery.js.map +1 -0
  446. package/lib/WAUSync/USyncUser.d.ts +25 -0
  447. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  448. package/lib/WAUSync/USyncUser.js +48 -0
  449. package/lib/WAUSync/USyncUser.js.map +1 -0
  450. package/lib/WAUSync/index.d.ts +4 -0
  451. package/lib/WAUSync/index.d.ts.map +1 -0
  452. package/lib/WAUSync/index.js +4 -0
  453. package/lib/WAUSync/index.js.map +1 -0
  454. package/lib/index.d.ts +12 -0
  455. package/lib/index.d.ts.map +1 -0
  456. package/lib/index.js +12 -0
  457. package/lib/index.js.map +1 -0
  458. package/package.json +122 -5
@@ -0,0 +1,1290 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { randomBytes, randomUUID } 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, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
7
+ import { QueryIds, ReachoutTimelockEnforcementType } from '../Types/index.js';
8
+ import { DisconnectReason, XWAPaths } from '../Types/index.js';
9
+ import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, buildPairingQRData, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, fetchLatestWaWebVersion, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, getPairingCodePlatform, invalidPairingCodeChars, makeEventBuffer, makeNoiseHandler, normalizePairingCode, PAIRING_CODE_ALPHABET, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
10
+ import { ignoredStanzaNeedsAck, makeIgnoreKeyRegistry } from '../Utils/ignore-key.js';
11
+ import { buildAckStanza } from '../Utils/stanza-ack.js';
12
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
13
+ import { BinaryInfo } from '../WAM/BinaryInfo.js';
14
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
15
+ import { WebSocketClient } from './Client/index.js';
16
+ import { executeWMexQuery } from './mex.js';
17
+
18
+ /**
19
+ * Connects to WA servers and performs:
20
+ * - simple queries (no retry mechanism, wait for connection establishment)
21
+ * - listen to messages and emit events
22
+ * - query phone connection
23
+ */
24
+ /**
25
+ * Version the server accepted after it rejected the configured one with 405 (client_too_old).
26
+ * Process-wide on purpose: every socket built afterwards with a static `version` reuses it,
27
+ * so a stale hardcoded version heals on the next reconnect instead of looping on 405.
28
+ */
29
+ let latestVersionOverride;
30
+ export const makeSocket = (config) => {
31
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, keepAliveGracePeriodMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
32
+ const publicWAMBuffer = new BinaryInfo();
33
+ let serverTimeOffsetMs = 0;
34
+ const uqTagId = generateMdTagPrefix();
35
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
36
+ if (printQRInTerminal) {
37
+ 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.');
38
+ }
39
+ if (browser[1].toLocaleLowerCase().includes('android')) {
40
+ logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.');
41
+ }
42
+ const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
43
+ .length === PROCESSABLE_HISTORY_TYPES.length;
44
+ if (syncDisabled) {
45
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
46
+ }
47
+ const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
48
+ if (config.mobile || url.protocol === 'tcp:') {
49
+ throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
50
+ }
51
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
52
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
53
+ }
54
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
55
+ const ephemeralKeyPair = Curve.generateKeyPair();
56
+ /** WA noise protocol wrapper */
57
+ const noise = makeNoiseHandler({
58
+ keyPair: ephemeralKeyPair,
59
+ NOISE_HEADER: NOISE_WA_HEADER,
60
+ logger,
61
+ routingInfo: authState?.creds?.routingInfo
62
+ });
63
+ const ws = new WebSocketClient(url, config);
64
+ ws.connect();
65
+ const sendPromise = promisify(ws.send);
66
+ /** send a raw buffer */
67
+ const sendRawMessage = async (data) => {
68
+ if (!ws.isOpen) {
69
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
70
+ }
71
+ const bytes = noise.encodeFrame(data);
72
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
73
+ try {
74
+ await sendPromise.call(ws, bytes);
75
+ resolve();
76
+ }
77
+ catch (error) {
78
+ reject(error);
79
+ }
80
+ });
81
+ };
82
+ /** send a binary node */
83
+ const sendNode = (frame) => {
84
+ if (logger.level === 'trace') {
85
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
86
+ }
87
+ const buff = encodeBinaryNode(frame);
88
+ return sendRawMessage(buff);
89
+ };
90
+ /**
91
+ * Wait for a message with a certain tag to be received
92
+ * @param msgId the message tag to await
93
+ * @param timeoutMs timeout after which the promise will reject
94
+ */
95
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
96
+ let onRecv;
97
+ let onErr;
98
+ try {
99
+ const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
100
+ onRecv = data => {
101
+ resolve(data);
102
+ };
103
+ onErr = err => {
104
+ reject(err ||
105
+ new Boom('Connection Closed', {
106
+ statusCode: DisconnectReason.connectionClosed
107
+ }));
108
+ };
109
+ ws.on(`TAG:${msgId}`, onRecv);
110
+ ws.on('close', onErr);
111
+ ws.on('error', onErr);
112
+ return () => reject(new Boom('Query Cancelled'));
113
+ });
114
+ return result;
115
+ }
116
+ catch (error) {
117
+ // Catch timeout and return undefined instead of throwing
118
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
119
+ logger?.warn?.({ msgId }, 'timed out waiting for message');
120
+ return undefined;
121
+ }
122
+ throw error;
123
+ }
124
+ finally {
125
+ if (onRecv)
126
+ ws.off(`TAG:${msgId}`, onRecv);
127
+ if (onErr) {
128
+ ws.off('close', onErr);
129
+ ws.off('error', onErr);
130
+ }
131
+ }
132
+ };
133
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
134
+ const query = async (node, timeoutMs) => {
135
+ if (!node.attrs.id) {
136
+ node.attrs.id = generateMessageTag();
137
+ }
138
+ const msgId = node.attrs.id;
139
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
140
+ const result = waitForMessage(msgId, timeoutMs).catch(reject);
141
+ sendNode(node)
142
+ .then(async () => resolve(await result))
143
+ .catch(reject);
144
+ });
145
+ if (result && 'tag' in result) {
146
+ assertNodeErrorFree(result);
147
+ }
148
+ return result;
149
+ };
150
+ // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
151
+ const digestKeyBundle = async () => {
152
+ const res = await query({
153
+ tag: 'iq',
154
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
155
+ content: [{ tag: 'digest', attrs: {} }]
156
+ });
157
+ const digestNode = getBinaryNodeChild(res, 'digest');
158
+ if (!digestNode) {
159
+ await uploadPreKeys();
160
+ throw new Error('encrypt/get digest returned no digest node');
161
+ }
162
+ };
163
+ // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
164
+ const rotateSignedPreKey = async () => {
165
+ const newId = (creds.signedPreKey.keyId || 0) + 1;
166
+ const skey = await signedKeyPair(creds.signedIdentityKey, newId);
167
+ await query({
168
+ tag: 'iq',
169
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
170
+ content: [
171
+ {
172
+ tag: 'rotate',
173
+ attrs: {},
174
+ content: [xmppSignedPreKey(skey)]
175
+ }
176
+ ]
177
+ });
178
+ // Persist new signed pre-key in creds
179
+ ev.emit('creds.update', { signedPreKey: skey });
180
+ };
181
+ const executeUSyncQuery = async (usyncQuery) => {
182
+ if (usyncQuery.protocols.length === 0) {
183
+ throw new Boom('USyncQuery must have at least one protocol');
184
+ }
185
+ // todo: validate users, throw WARNING on no valid users
186
+ // variable below has only validated users
187
+ const validUsers = usyncQuery.users;
188
+ const userNodes = validUsers.map(user => {
189
+ return {
190
+ tag: 'user',
191
+ attrs: {
192
+ jid: !user.phone ? user.id : undefined
193
+ },
194
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
195
+ };
196
+ });
197
+ const listNode = {
198
+ tag: 'list',
199
+ attrs: {},
200
+ content: userNodes
201
+ };
202
+ const queryNode = {
203
+ tag: 'query',
204
+ attrs: {},
205
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
206
+ };
207
+ const iq = {
208
+ tag: 'iq',
209
+ attrs: {
210
+ to: S_WHATSAPP_NET,
211
+ type: 'get',
212
+ xmlns: 'usync'
213
+ },
214
+ content: [
215
+ {
216
+ tag: 'usync',
217
+ attrs: {
218
+ context: usyncQuery.context,
219
+ mode: usyncQuery.mode,
220
+ sid: generateMessageTag(),
221
+ last: 'true',
222
+ index: '0'
223
+ },
224
+ content: [queryNode, listNode]
225
+ }
226
+ ]
227
+ };
228
+ const result = await query(iq);
229
+ return usyncQuery.parseUSyncQueryResult(result);
230
+ };
231
+ const onWhatsApp = async (...phoneNumber) => {
232
+ let usyncQuery = new USyncQuery();
233
+ let contactEnabled = false;
234
+ for (const jid of phoneNumber) {
235
+ if (isLidUser(jid)) {
236
+ logger?.warn('LIDs are not supported with onWhatsApp');
237
+ continue;
238
+ }
239
+ else {
240
+ if (!contactEnabled) {
241
+ contactEnabled = true;
242
+ usyncQuery = usyncQuery.withContactProtocol();
243
+ }
244
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
245
+ usyncQuery.withUser(new USyncUser().withPhone(phone));
246
+ }
247
+ }
248
+ if (usyncQuery.users.length === 0) {
249
+ return []; // return early without forcing an empty query
250
+ }
251
+ const results = await executeUSyncQuery(usyncQuery);
252
+ if (results) {
253
+ return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
254
+ }
255
+ };
256
+ /**
257
+ * Look up accounts by their WhatsApp @username instead of a phone number.
258
+ * Each query is either a plain username string, or `{ username, usernameKey, lid }`
259
+ * where usernameKey is the PIN protecting the username.
260
+ */
261
+ const onWhatsAppUsername = async (...queries) => {
262
+ // username users are LID-only; ask for LID addressing like WA Web does
263
+ const usyncQuery = new USyncQuery().withContactProtocol('lid').withUsernameProtocol().withBusinessProtocol(null);
264
+ const normalized = [];
265
+ for (const query of queries) {
266
+ const raw = typeof query === 'string' ? query : query?.username;
267
+ const username = raw?.trim().replace(/^@/, '');
268
+ if (!username) {
269
+ throw new Boom('Username cannot be empty', { statusCode: 400 });
270
+ }
271
+ const user = new USyncUser().withUsername(username);
272
+ if (typeof query !== 'string') {
273
+ if (query.usernameKey) {
274
+ user.withUsernameKey(query.usernameKey);
275
+ }
276
+ if (query.lid) {
277
+ user.withLid(query.lid);
278
+ }
279
+ }
280
+ usyncQuery.withUser(user);
281
+ normalized.push(username);
282
+ }
283
+ if (usyncQuery.users.length === 0) {
284
+ return [];
285
+ }
286
+ const results = await executeUSyncQuery(usyncQuery);
287
+ if (!results) {
288
+ return [];
289
+ }
290
+ return results.list.map((result, index) => ({
291
+ username: typeof result.username === 'string' ? result.username : normalized[index] || '',
292
+ jid: result.id,
293
+ exists: result.contact === true || result.keyRequired === true,
294
+ keyRequired: result.keyRequired === true,
295
+ isBusiness: !!result.business,
296
+ pnJid: result.business?.pnJid || undefined
297
+ }));
298
+ };
299
+ /** fetch the @username of one or more jids, if they have one set */
300
+ const fetchUsername = async (...jids) => {
301
+ const usyncQuery = new USyncQuery().withUsernameProtocol();
302
+ for (const jid of jids) {
303
+ usyncQuery.withUser(new USyncUser().withId(jid));
304
+ }
305
+ if (usyncQuery.users.length === 0) {
306
+ return [];
307
+ }
308
+ const results = await executeUSyncQuery(usyncQuery);
309
+ if (!results) {
310
+ return [];
311
+ }
312
+ return results.list.map(({ id, username }) => ({
313
+ jid: id,
314
+ username: typeof username === 'string' ? username : undefined
315
+ }));
316
+ };
317
+ /**
318
+ * Check whether a username is free before claiming it. Returns the session_id
319
+ * that must be passed to `setUsername` so the server ties both steps together.
320
+ */
321
+ const checkUsername = async (username, includeSuggestions = true, sessionId) => {
322
+ const session_id = sessionId || randomUUID();
323
+ const data = await executeWMexQuery({ username, include_suggestions: includeSuggestions, session_id, source: 'USER_INPUT' }, QueryIds.USERNAME_CHECK, XWAPaths.xwa2_username_check, query, generateMessageTag);
324
+ if (data?.result === 'SUCCESS') {
325
+ return { available: true, username, session_id };
326
+ }
327
+ return {
328
+ available: false,
329
+ username,
330
+ session_id,
331
+ suggestions: data?.suggestions ?? [],
332
+ rejectionReasons: data?.rejection_reasons ?? [],
333
+ suggestionsEligible: data?.suggestions_eligible ?? true
334
+ };
335
+ };
336
+ /** claim a username for ourselves. `source` is one of USER_INPUT | SUGGESTION | FB | IG */
337
+ const setUsername = async (username, options = {}) => {
338
+ const { source = 'USER_INPUT', sessionId, pin } = options;
339
+ return executeWMexQuery({ username, reserved: true, source, session_id: sessionId || randomUUID(), ...(pin ? { pin } : {}) }, QueryIds.USERNAME_SET, XWAPaths.xwa2_username_set, query, generateMessageTag);
340
+ };
341
+ /** remove our own username — a null username is what triggers the server's delete path */
342
+ const deleteUsername = async () => {
343
+ return executeWMexQuery({ username: null }, QueryIds.USERNAME_SET, XWAPaths.xwa2_username_delete, query, generateMessageTag);
344
+ };
345
+ const getMyUsername = async () => {
346
+ const data = await executeWMexQuery({}, QueryIds.USERNAME_GET, XWAPaths.xwa2_username_get, query, generateMessageTag);
347
+ return data?.username ?? null;
348
+ };
349
+ /** set the PIN protecting our username, or pass null to remove it */
350
+ const setUsernamePin = async (pin) => {
351
+ return executeWMexQuery(pin != null ? { pin } : {}, QueryIds.USERNAME_PIN_SET, XWAPaths.xwa2_username_pin_set, query, generateMessageTag);
352
+ };
353
+ const pnFromLIDUSync = async (jids) => {
354
+ const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
355
+ for (const jid of jids) {
356
+ if (isLidUser(jid)) {
357
+ logger?.warn('LID user found in LID fetch call');
358
+ continue;
359
+ }
360
+ else {
361
+ usyncQuery.withUser(new USyncUser().withId(jid));
362
+ }
363
+ }
364
+ if (usyncQuery.users.length === 0) {
365
+ return []; // return early without forcing an empty query
366
+ }
367
+ const results = await executeUSyncQuery(usyncQuery);
368
+ if (results) {
369
+ return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
370
+ }
371
+ return [];
372
+ };
373
+ const ev = makeEventBuffer(logger);
374
+ const { creds } = authState;
375
+ // add transaction capability
376
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
377
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
378
+ let lastDateRecv;
379
+ let epoch = 1;
380
+ let keepAliveReq;
381
+ let qrTimer;
382
+ let closed = false;
383
+ /** set once WhatsApp sends pair-device; requestPairingCode queues until then */
384
+ let pairingReady = false;
385
+ let pairingInProgress = false;
386
+ /** true once a pairing code has been asked for: this session is being linked by code, not QR */
387
+ let pairingCodeMode = false;
388
+ let pendingPairingResolve;
389
+ let pendingPairingReject;
390
+ const socketEndHandlers = [];
391
+ const timers = new Set();
392
+ const safeSetTimeout = (fn, ms) => { const id = setTimeout(fn, ms); timers.add(id); return id; };
393
+ const safeSetInterval = (fn, ms) => { const id = setInterval(fn, ms); timers.add(id); return id; };
394
+ const clearSafeTimer = (id) => { if (id !== undefined && id !== null) { clearTimeout(id); clearInterval(id); timers.delete(id); } };
395
+ const clearAllTimers = () => { for (const id of timers) { clearTimeout(id); clearInterval(id); } timers.clear(); };
396
+ /** log & process any unexpected errors */
397
+ const onUnexpectedError = (err, msg) => {
398
+ logger.error({ err }, `unexpected error in '${msg}'`);
399
+ };
400
+ /** await the next incoming message */
401
+ const awaitNextMessage = async (sendMsg) => {
402
+ if (!ws.isOpen) {
403
+ throw new Boom('Connection Closed', {
404
+ statusCode: DisconnectReason.connectionClosed
405
+ });
406
+ }
407
+ let onOpen;
408
+ let onClose;
409
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
410
+ onOpen = resolve;
411
+ onClose = mapWebSocketError(reject);
412
+ ws.on('frame', onOpen);
413
+ ws.on('close', onClose);
414
+ ws.on('error', onClose);
415
+ }).finally(() => {
416
+ ws.off('frame', onOpen);
417
+ ws.off('close', onClose);
418
+ ws.off('error', onClose);
419
+ });
420
+ if (sendMsg) {
421
+ sendRawMessage(sendMsg).catch(onClose);
422
+ }
423
+ return result;
424
+ };
425
+ /** connection handshake */
426
+ const validateConnection = async () => {
427
+ let helloMsg = {
428
+ clientHello: { ephemeral: ephemeralKeyPair.public }
429
+ };
430
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
431
+ logger.info({ browser, helloMsg }, 'connected to WA');
432
+ const init = proto.HandshakeMessage.encode(helloMsg).finish();
433
+ const result = await awaitNextMessage(init);
434
+ const handshake = proto.HandshakeMessage.decode(result);
435
+ logger.trace({ handshake }, 'handshake recv from WA');
436
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
437
+ // `version` may be a resolver (e.g. () => fetchLatestWaWebVersion().then(r => r.version));
438
+ // a version the server already rejected as too old is replaced by the fetched one
439
+ const resolvedVersion = typeof config.version === 'function'
440
+ ? await config.version()
441
+ : latestVersionOverride ?? config.version;
442
+ const connectConfig = resolvedVersion === config.version ? config : { ...config, version: resolvedVersion };
443
+ let node;
444
+ if (!creds.me) {
445
+ node = generateRegistrationNode(creds, connectConfig);
446
+ logger.info({ node }, 'not logged in, attempting registration...');
447
+ }
448
+ else {
449
+ node = generateLoginNode(creds.me.id, connectConfig);
450
+ logger.info({ node }, 'logging in...');
451
+ }
452
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
453
+ await sendRawMessage(proto.HandshakeMessage.encode({
454
+ clientFinish: {
455
+ static: keyEnc,
456
+ payload: payloadEnc
457
+ }
458
+ }).finish());
459
+ await noise.finishInit();
460
+ startKeepAliveRequest();
461
+ };
462
+ const getAvailablePreKeysOnServer = async () => {
463
+ const result = await query({
464
+ tag: 'iq',
465
+ attrs: {
466
+ id: generateMessageTag(),
467
+ xmlns: 'encrypt',
468
+ type: 'get',
469
+ to: S_WHATSAPP_NET
470
+ },
471
+ content: [{ tag: 'count', attrs: {} }]
472
+ });
473
+ const countChild = getBinaryNodeChild(result, 'count');
474
+ return +countChild.attrs.value;
475
+ };
476
+ // WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
477
+ let uploadPreKeysPromise = null;
478
+ /** generates and uploads a set of pre-keys to the server */
479
+ const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
480
+ if (uploadPreKeysPromise) {
481
+ logger.debug('Pre-key upload already in progress, waiting for completion');
482
+ await uploadPreKeysPromise;
483
+ return;
484
+ }
485
+ const uploadLogic = async (retryCount) => {
486
+ logger.info({ count, retryCount }, 'uploading pre-keys');
487
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
488
+ const node = await keys.transaction(async () => {
489
+ logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
490
+ const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
491
+ // Update credentials immediately to prevent duplicate IDs on retry
492
+ ev.emit('creds.update', update);
493
+ return node;
494
+ }, creds?.me?.id || 'upload-pre-keys');
495
+ // Upload to server (outside transaction, can fail without affecting local keys)
496
+ try {
497
+ await query(node);
498
+ logger.info({ count }, 'uploaded pre-keys successfully');
499
+ }
500
+ catch (uploadError) {
501
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
502
+ // Recurse into uploadLogic; calling uploadPreKeys would await its own in-flight promise.
503
+ if (retryCount < 3) {
504
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
505
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
506
+ await new Promise(resolve => safeSetTimeout(resolve, backoffDelay));
507
+ return uploadLogic(retryCount + 1);
508
+ }
509
+ throw uploadError;
510
+ }
511
+ };
512
+ // Add timeout protection
513
+ uploadPreKeysPromise = Promise.race([
514
+ uploadLogic(0),
515
+ new Promise((_, reject) => safeSetTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
516
+ ]);
517
+ try {
518
+ await uploadPreKeysPromise;
519
+ }
520
+ finally {
521
+ uploadPreKeysPromise = null;
522
+ }
523
+ };
524
+ const verifyCurrentPreKeyExists = async () => {
525
+ const currentPreKeyId = creds.nextPreKeyId - 1;
526
+ if (currentPreKeyId <= 0) {
527
+ return { exists: false, currentPreKeyId: 0 };
528
+ }
529
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
530
+ const exists = !!preKeys[currentPreKeyId.toString()];
531
+ return { exists, currentPreKeyId };
532
+ };
533
+ const uploadPreKeysToServerIfRequired = async () => {
534
+ try {
535
+ let count = 0;
536
+ const preKeyCount = await getAvailablePreKeysOnServer();
537
+ if (preKeyCount === 0)
538
+ count = INITIAL_PREKEY_COUNT;
539
+ else
540
+ count = MIN_PREKEY_COUNT;
541
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
542
+ logger.info(`${preKeyCount} pre-keys found on server`);
543
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
544
+ const lowServerCount = preKeyCount <= count;
545
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
546
+ const shouldUpload = lowServerCount || missingCurrentPreKey;
547
+ if (shouldUpload) {
548
+ const reasons = [];
549
+ if (lowServerCount)
550
+ reasons.push(`server count low (${preKeyCount})`);
551
+ if (missingCurrentPreKey)
552
+ reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
553
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
554
+ await uploadPreKeys(count);
555
+ }
556
+ else {
557
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
558
+ }
559
+ }
560
+ catch (error) {
561
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
562
+ // Don't throw - allow connection to continue even if pre-key check fails
563
+ }
564
+ };
565
+ const ignoreKeyRegistry = makeIgnoreKeyRegistry({
566
+ getMeId: () => authState.creds.me?.id,
567
+ getMeLid: () => authState.creds.me?.lid,
568
+ logger
569
+ });
570
+ const onMessageReceived = async (data) => {
571
+ await noise.decodeFrame(data, frame => {
572
+ lastDateRecv = new Date();
573
+ let anyTriggered = false;
574
+ anyTriggered = ws.emit('frame', frame);
575
+ if (!(frame instanceof Uint8Array)) {
576
+ const msgId = frame.attrs.id;
577
+ if (logger.level === 'trace') {
578
+ logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
579
+ }
580
+ // Filters run before every other handler, so a dropped stanza never reaches the
581
+ // decryption or persistence paths. The ack still goes out, otherwise the server
582
+ // keeps re-delivering what the host just asked to ignore.
583
+ if (ignoreKeyRegistry.shouldDrop(frame)) {
584
+ logger.debug({ tag: frame.tag, id: msgId, from: frame.attrs.from }, 'stanza dropped by ignoreKey');
585
+ if (ignoredStanzaNeedsAck(frame.tag)) {
586
+ sendNode(buildAckStanza(frame, undefined, authState.creds.me?.id)).catch(err => logger.error({ err, id: msgId }, 'failed to ack ignored stanza'));
587
+ }
588
+ return;
589
+ }
590
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
591
+ const l0 = frame.tag;
592
+ const l1 = frame.attrs || {};
593
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
594
+ for (const key of Object.keys(l1)) {
595
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
596
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
597
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
598
+ }
599
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
600
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
601
+ if (!anyTriggered && logger.level === 'debug') {
602
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
603
+ }
604
+ }
605
+ });
606
+ data = null;
607
+ };
608
+ const end = async (error) => {
609
+ if (closed) {
610
+ logger.trace({ trace: error?.stack }, 'connection already closed');
611
+ return;
612
+ }
613
+ closed = true;
614
+ // Name the disconnect reason in the message itself. The code was always on `error.output`,
615
+ // but a host does not always receive the Boom: a wrapper that re-emits this close as its own
616
+ // `error` event forwards `message` and nothing else, and the messages alone cannot be told
617
+ // apart — `CB:failure` says the constant 'Connection Failure' for a 401 device-removal and
618
+ // for a transient 503 alike. A host that cannot distinguish them keeps reconnecting a
619
+ // session that is really gone, which is how an unattended fleet turns one logout into a
620
+ // re-auth loop and gets the number banned.
621
+ //
622
+ // Done here rather than at each `end()` call site because there are a dozen of them and a
623
+ // new one would silently miss it. The existing text is kept as a prefix, so message matching
624
+ // that already works keeps working; the suffix is additive.
625
+ const statusCode = error?.output?.statusCode;
626
+ if (statusCode !== undefined && typeof error?.message === 'string' && !error.message.includes(`[${statusCode} `)) {
627
+ try {
628
+ error.message = `${error.message} [${statusCode} ${DisconnectReason[statusCode] || 'unknown'}]`;
629
+ }
630
+ catch { }
631
+ }
632
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
633
+ // Signal-key writes are debounced (addTransactionCapability). Nothing else in the library
634
+ // called flush, so every ratchet advance from the last window was dropped on close and the
635
+ // next connection decrypted with stale state. Flush first: the close path below can hang.
636
+ try {
637
+ await keys.flush?.();
638
+ }
639
+ catch (err) {
640
+ logger.error({ err }, 'failed to flush signal keys on close');
641
+ }
642
+ // Every caller invokes this as `void end(...)`, so a rejection from anywhere below is an
643
+ // unhandled rejection and Node terminates the process - during a teardown, which is exactly
644
+ // when a host is least able to afford losing every other account it runs. Nothing in a
645
+ // teardown is worth propagating: log and finish tearing down.
646
+ try {
647
+ keepAliveReq?.cancel();
648
+ clearSafeTimer(qrTimer);
649
+ clearAllTimers();
650
+ // a queued requestPairingCode would hang forever otherwise
651
+ pairingReady = false;
652
+ pairingInProgress = false;
653
+ pairingCodeMode = false;
654
+ pendingPairingReject?.(error || new Boom('Connection closed before pairing completed', { statusCode: DisconnectReason.connectionClosed }));
655
+ ws.removeAllListeners('close');
656
+ ws.removeAllListeners('open');
657
+ ws.removeAllListeners('message');
658
+ ws.removeAllListeners('frame');
659
+ ws.removeAllListeners('error');
660
+ signalRepository.close?.();
661
+ if (!ws.isClosed && !ws.isClosing) {
662
+ try {
663
+ await ws.close();
664
+ }
665
+ catch { }
666
+ }
667
+ const handlers = socketEndHandlers.slice();
668
+ socketEndHandlers.length = 0;
669
+ for (const handler of handlers) {
670
+ try {
671
+ await handler(error);
672
+ }
673
+ catch (err) {
674
+ logger.error({ err }, 'error in socket end handler');
675
+ }
676
+ }
677
+ try {
678
+ ev.emit('connection.update', {
679
+ connection: 'close',
680
+ lastDisconnect: {
681
+ error,
682
+ date: new Date()
683
+ }
684
+ });
685
+ } catch { }
686
+ ev.removeAllListeners('connection.update');
687
+ ev.destroy();
688
+ }
689
+ catch (err) {
690
+ logger.error({ err }, 'error while closing connection');
691
+ }
692
+ };
693
+ const waitForSocketOpen = async () => {
694
+ if (ws.isOpen) {
695
+ return;
696
+ }
697
+ if (ws.isClosed || ws.isClosing) {
698
+ throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
699
+ }
700
+ let onOpen;
701
+ let onClose;
702
+ await new Promise((resolve, reject) => {
703
+ onOpen = () => resolve(undefined);
704
+ onClose = mapWebSocketError(reject);
705
+ ws.on('open', onOpen);
706
+ ws.on('close', onClose);
707
+ ws.on('error', onClose);
708
+ }).finally(() => {
709
+ ws.off('open', onOpen);
710
+ ws.off('close', onClose);
711
+ ws.off('error', onClose);
712
+ });
713
+ };
714
+ const startKeepAliveRequest = () => {
715
+ const cb = () => {
716
+ if (!lastDateRecv) {
717
+ lastDateRecv = new Date();
718
+ }
719
+ const diff = Date.now() - lastDateRecv.getTime();
720
+ if (diff > keepAliveIntervalMs + keepAliveGracePeriodMs) {
721
+ void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
722
+ }
723
+ else if (ws.isOpen) {
724
+ query({
725
+ tag: 'iq',
726
+ attrs: {
727
+ id: generateMessageTag(),
728
+ to: S_WHATSAPP_NET,
729
+ type: 'get',
730
+ xmlns: 'w:p'
731
+ },
732
+ content: [{ tag: 'ping', attrs: {} }]
733
+ }).catch(err => {
734
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
735
+ });
736
+ }
737
+ else {
738
+ logger.warn('keep alive called when WS not open');
739
+ }
740
+ };
741
+ // Per socket, so keepAliveIntervalMs from the config is actually the ping interval: the
742
+ // shared process-wide timer ran at a hardcoded 30s while the staleness check below still
743
+ // used the configured value, so any interval other than 30s produced false connectionLost.
744
+ // The random start offset staggers the fleet - on the shared timer every socket in the
745
+ // process pinged in the same tick, which is a self-inflicted burst at 100+ sessions.
746
+ let pinger;
747
+ const starter = safeSetTimeout(() => {
748
+ cb();
749
+ pinger = safeSetInterval(cb, keepAliveIntervalMs);
750
+ }, Math.floor(Math.random() * (keepAliveIntervalMs / 2)));
751
+ keepAliveReq = {
752
+ cb,
753
+ cancel: () => {
754
+ clearSafeTimer(starter);
755
+ clearSafeTimer(pinger);
756
+ }
757
+ };
758
+ };
759
+ /** i have no idea why this exists. pls enlighten me */
760
+ const sendPassiveIq = (tag) => query({
761
+ tag: 'iq',
762
+ attrs: {
763
+ to: S_WHATSAPP_NET,
764
+ xmlns: 'passive',
765
+ type: 'set'
766
+ },
767
+ content: [{ tag, attrs: {} }]
768
+ });
769
+ /** logout & invalidate connection */
770
+ const logout = async (msg) => {
771
+ const jid = authState.creds.me?.id;
772
+ if (jid) {
773
+ await sendNode({
774
+ tag: 'iq',
775
+ attrs: {
776
+ to: S_WHATSAPP_NET,
777
+ type: 'set',
778
+ id: generateMessageTag(),
779
+ xmlns: 'md'
780
+ },
781
+ content: [
782
+ {
783
+ tag: 'remove-companion-device',
784
+ attrs: {
785
+ jid,
786
+ reason: 'user_initiated'
787
+ }
788
+ }
789
+ ]
790
+ });
791
+ }
792
+ void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
793
+ };
794
+ const sendPairingCodeRequest = async (phoneNumber, customPairingCode) => {
795
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
796
+ authState.creds.pairingCode = pairingCode;
797
+ const jid = jidEncode(phoneNumber, 's.whatsapp.net');
798
+ const pairingPlatform = getPairingCodePlatform(browser);
799
+ try {
800
+ // query, not sendNode: the server answers this IQ, and a fire-and-forget send would
801
+ // hand back a code that the server already rejected
802
+ const result = await query({
803
+ tag: 'iq',
804
+ attrs: {
805
+ to: S_WHATSAPP_NET,
806
+ type: 'set',
807
+ xmlns: 'md'
808
+ },
809
+ content: [
810
+ {
811
+ tag: 'link_code_companion_reg',
812
+ attrs: {
813
+ jid,
814
+ stage: 'companion_hello',
815
+ should_show_push_notification: 'true'
816
+ },
817
+ content: [
818
+ {
819
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
820
+ attrs: {},
821
+ content: await generatePairingKey()
822
+ },
823
+ {
824
+ tag: 'companion_server_auth_key_pub',
825
+ attrs: {},
826
+ content: authState.creds.noiseKey.public
827
+ },
828
+ {
829
+ tag: 'companion_platform_id',
830
+ attrs: {},
831
+ content: pairingPlatform.id
832
+ },
833
+ {
834
+ tag: 'companion_platform_display',
835
+ attrs: {},
836
+ content: pairingPlatform.display
837
+ },
838
+ {
839
+ tag: 'link_code_pairing_nonce',
840
+ attrs: {},
841
+ content: '0'
842
+ }
843
+ ]
844
+ }
845
+ ]
846
+ });
847
+ if (!result) {
848
+ throw new Boom('Timed out waiting for pairing code response', { statusCode: DisconnectReason.timedOut });
849
+ }
850
+ }
851
+ catch (error) {
852
+ // roll the code back, otherwise a retry derives its pairing key from a stale code
853
+ if (authState.creds.pairingCode === pairingCode) {
854
+ authState.creds.pairingCode = undefined;
855
+ }
856
+ throw error;
857
+ }
858
+ // only claim the number once the server accepted it, so a failed attempt doesn't
859
+ // leave creds.me pointing at an unregistered account
860
+ authState.creds.me = { id: jid, name: '~' };
861
+ ev.emit('creds.update', authState.creds);
862
+ return pairingCode;
863
+ };
864
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
865
+ if (customPairingCode && customPairingCode.length !== 8) {
866
+ throw new Error('Custom pairing code must be exactly 8 chars');
867
+ }
868
+ // WhatsApp Web rejects these characters up front: the phone normalizes 0/I/O/U before it
869
+ // derives its key, so a code containing them fails on the phone ("Couldn't link device")
870
+ // with nothing on the wire. Fail here instead, where the caller can see it.
871
+ const wantedCode = customPairingCode ? normalizePairingCode(customPairingCode) : undefined;
872
+ if (wantedCode) {
873
+ const invalid = invalidPairingCodeChars(wantedCode);
874
+ if (invalid.length) {
875
+ throw new Boom(`Custom pairing code "${wantedCode}" contains characters WhatsApp does not accept (${invalid.join(', ')}); allowed: ${PAIRING_CODE_ALPHABET}`, { statusCode: 400, data: { pairingCode: wantedCode, invalid } });
876
+ }
877
+ }
878
+ if (pairingInProgress) {
879
+ throw new Boom('A pairing request is already in progress', { statusCode: 400 });
880
+ }
881
+ pairingInProgress = true;
882
+ pairingCodeMode = true;
883
+ try {
884
+ if (!pairingReady) {
885
+ // Called before WhatsApp sent pair-device. The IQ would be dropped, so wait for
886
+ // readiness instead of burning the attempt.
887
+ logger.debug('pairing not ready yet, queuing request until pair-device is received');
888
+ await new Promise((resolve, reject) => {
889
+ // Bounded: without this the caller waits on a pair-device that may never come
890
+ // and gets no answer until the socket happens to close.
891
+ const waitTimer = safeSetTimeout(() => {
892
+ pendingPairingResolve = undefined;
893
+ pendingPairingReject = undefined;
894
+ reject(new Boom('Timed out waiting for WhatsApp to accept pairing requests', { statusCode: DisconnectReason.timedOut }));
895
+ }, connectTimeoutMs);
896
+ pendingPairingResolve = () => {
897
+ clearSafeTimer(waitTimer);
898
+ pendingPairingResolve = undefined;
899
+ pendingPairingReject = undefined;
900
+ resolve();
901
+ };
902
+ pendingPairingReject = (err) => {
903
+ clearSafeTimer(waitTimer);
904
+ pendingPairingResolve = undefined;
905
+ pendingPairingReject = undefined;
906
+ reject(err);
907
+ };
908
+ });
909
+ }
910
+ return await sendPairingCodeRequest(phoneNumber, wantedCode);
911
+ }
912
+ finally {
913
+ pairingInProgress = false;
914
+ }
915
+ };
916
+ async function generatePairingKey() {
917
+ const salt = randomBytes(32);
918
+ const randomIv = randomBytes(16);
919
+ const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
920
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
921
+ return Buffer.concat([salt, randomIv, ciphered]);
922
+ }
923
+ const sendWAMBuffer = (wamBuffer) => {
924
+ return query({
925
+ tag: 'iq',
926
+ attrs: {
927
+ to: S_WHATSAPP_NET,
928
+ id: generateMessageTag(),
929
+ xmlns: 'w:stats'
930
+ },
931
+ content: [
932
+ {
933
+ tag: 'add',
934
+ attrs: { t: Math.round(Date.now() / 1000) + '' },
935
+ content: wamBuffer
936
+ }
937
+ ]
938
+ });
939
+ };
940
+ ws.on('message', onMessageReceived);
941
+ ws.on('open', async () => {
942
+ try {
943
+ await validateConnection();
944
+ }
945
+ catch (err) {
946
+ logger.error({ err }, 'error in validating connection');
947
+ void end(err);
948
+ }
949
+ });
950
+ ws.on('error', mapWebSocketError(end));
951
+ ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
952
+ // the server terminated the connection
953
+ ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
954
+ // QR gen
955
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
956
+ const iq = {
957
+ tag: 'iq',
958
+ attrs: {
959
+ to: S_WHATSAPP_NET,
960
+ type: 'result',
961
+ id: stanza.attrs.id
962
+ }
963
+ };
964
+ await sendNode(iq);
965
+ // from here the server accepts link_code_companion_reg, so release any queued request
966
+ pairingReady = true;
967
+ pendingPairingResolve?.();
968
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
969
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
970
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
971
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
972
+ const advB64 = creds.advSecretKey;
973
+ let qrMs = qrTimeout || 60000; // time to let a QR live
974
+ const genPairQR = () => {
975
+ if (!ws.isOpen) {
976
+ return;
977
+ }
978
+ const refNode = refNodes.shift();
979
+ if (!refNode) {
980
+ // The refs exist for a QR. When the account is being linked by code nobody is
981
+ // looking at one, and ending the socket here cut the attempt off while the user was
982
+ // still walking to Linked devices - about 140s in, on the default timeouts.
983
+ if (pairingCodeMode) {
984
+ logger.debug('QR refs exhausted while pairing by code, keeping the socket open');
985
+ return;
986
+ }
987
+ void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
988
+ return;
989
+ }
990
+ const ref = refNode.content.toString('utf-8');
991
+ const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);
992
+ ev.emit('connection.update', { qr });
993
+ qrTimer = safeSetTimeout(genPairQR, qrMs);
994
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
995
+ };
996
+ genPairQR();
997
+ });
998
+ // device paired for the first time
999
+ // if device pairs successfully, the server asks to restart the connection
1000
+ ws.on('CB:iq,,pair-success', async (stanza) => {
1001
+ logger.debug('pair success recv');
1002
+ try {
1003
+ updateServerTimeOffset(stanza);
1004
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
1005
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
1006
+ ev.emit('creds.update', updatedCreds);
1007
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
1008
+ await sendNode(reply);
1009
+ void sendUnifiedSession();
1010
+ }
1011
+ catch (error) {
1012
+ logger.info({ trace: error.stack }, 'error in pairing');
1013
+ void end(error);
1014
+ }
1015
+ });
1016
+ // login complete
1017
+ ws.on('CB:success', async (node) => {
1018
+ try {
1019
+ updateServerTimeOffset(node);
1020
+ await uploadPreKeysToServerIfRequired();
1021
+ await sendPassiveIq('active');
1022
+ // After successful login, validate our key-bundle against server
1023
+ try {
1024
+ await digestKeyBundle();
1025
+ }
1026
+ catch (e) {
1027
+ logger.warn({ e }, 'failed to run digest after login');
1028
+ }
1029
+ }
1030
+ catch (err) {
1031
+ logger.warn({ err }, 'failed to send initial passive iq');
1032
+ }
1033
+ logger.info('opened connection to WA');
1034
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
1035
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
1036
+ ev.emit('connection.update', { connection: 'open' });
1037
+ void sendUnifiedSession();
1038
+ if (node.attrs.lid && authState.creds.me?.id) {
1039
+ const myLID = node.attrs.lid;
1040
+ setImmediate(async () => {
1041
+ try {
1042
+ const myPN = authState.creds.me.id;
1043
+ // Store our own LID-PN mapping
1044
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
1045
+ // Create device list for our own user (needed for bulk migration)
1046
+ const { user, device } = jidDecode(myPN);
1047
+ await authState.keys.set({
1048
+ 'device-list': {
1049
+ [user]: [device?.toString() || '0']
1050
+ }
1051
+ });
1052
+ // migrate our own session
1053
+ await signalRepository.migrateSession(myPN, myLID);
1054
+ logger.info({ myPN, myLID }, 'Own LID session created successfully');
1055
+ }
1056
+ catch (error) {
1057
+ logger.error({ error, lid: myLID }, 'Failed to create own LID session');
1058
+ }
1059
+ });
1060
+ }
1061
+ });
1062
+ ws.on('CB:stream:error', (node) => {
1063
+ const [reasonNode] = getAllBinaryNodeChildren(node);
1064
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
1065
+ const { reason, statusCode } = getErrorCodeFromStreamError(node);
1066
+ void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
1067
+ });
1068
+ // stream fail, possible logout
1069
+ ws.on('CB:failure', async (node) => {
1070
+ const reason = +(node.attrs.reason || 500);
1071
+ if (reason === 405 && typeof config.version !== 'function') {
1072
+ // client_too_old: fetch the live WA Web build so the caller's reconnect uses it
1073
+ const latest = await fetchLatestWaWebVersion({});
1074
+ if (latest.isLatest) {
1075
+ latestVersionOverride = latest.version;
1076
+ logger.warn({ rejected: latestVersionOverride === config.version ? undefined : config.version, latest: latest.version }, 'server rejected the client version as too old (405); the next connection uses the latest WA Web version');
1077
+ }
1078
+ else {
1079
+ logger.warn({ err: latest.error?.message }, 'server rejected the client version as too old (405) and the latest version could not be fetched; pass a current `version`');
1080
+ }
1081
+ }
1082
+ void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
1083
+ });
1084
+ ws.on('CB:ib,,downgrade_webclient', () => {
1085
+ void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
1086
+ });
1087
+ // The server delivers the offline queue in windows and waits for another <offline_batch/>
1088
+ // before sending the next one. A single request only drained the first 100 stanzas, so a
1089
+ // larger queue never finished and grew on every reconnect. Request the next window each
1090
+ // time a queued stanza (attrs.offline) arrives, debounced so a burst yields one request.
1091
+ // ponytail: no stanza timeout; the terminal 'offline' bulletin ends the loop.
1092
+ let offlineResuming = false;
1093
+ let offlineBatchInFlight = false;
1094
+ let offlineBatchTimer;
1095
+ const requestOfflineBatch = () => {
1096
+ if (!offlineResuming || offlineBatchInFlight) {
1097
+ return;
1098
+ }
1099
+ offlineBatchInFlight = true;
1100
+ sendNode({
1101
+ tag: 'ib',
1102
+ attrs: {},
1103
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
1104
+ }).catch(err => {
1105
+ offlineBatchInFlight = false;
1106
+ logger.debug({ err }, 'offline batch request failed');
1107
+ });
1108
+ };
1109
+ ws.on('CB:ib,,offline_preview', (node) => {
1110
+ logger.info('offline preview received', JSON.stringify(node));
1111
+ offlineResuming = true;
1112
+ offlineBatchInFlight = false;
1113
+ requestOfflineBatch();
1114
+ });
1115
+ ws.on('frame', (frame) => {
1116
+ if (!offlineResuming || frame instanceof Uint8Array || frame.attrs?.offline === undefined) {
1117
+ return;
1118
+ }
1119
+ offlineBatchInFlight = false;
1120
+ clearTimeout(offlineBatchTimer);
1121
+ offlineBatchTimer = setTimeout(requestOfflineBatch, 100);
1122
+ });
1123
+ ws.on('CB:ib,,edge_routing', (node) => {
1124
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
1125
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
1126
+ if (routingInfo?.content) {
1127
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content);
1128
+ ev.emit('creds.update', authState.creds);
1129
+ }
1130
+ });
1131
+ let didStartBuffer = false;
1132
+ setImmediate(() => {
1133
+ if (creds.me?.id) {
1134
+ // start buffering important events
1135
+ // if we're logged in
1136
+ ev.buffer();
1137
+ didStartBuffer = true;
1138
+ }
1139
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
1140
+ });
1141
+ // called when all offline notifs are handled
1142
+ ws.on('CB:ib,,offline', (node) => {
1143
+ offlineResuming = false;
1144
+ clearTimeout(offlineBatchTimer);
1145
+ const child = getBinaryNodeChild(node, 'offline');
1146
+ const offlineNotifs = +(child?.attrs.count || 0);
1147
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
1148
+ if (didStartBuffer) {
1149
+ ev.flush();
1150
+ logger.trace('flushed events for initial buffer');
1151
+ }
1152
+ ev.emit('connection.update', { receivedPendingNotifications: true });
1153
+ });
1154
+ // update credentials when required
1155
+ ev.on('creds.update', update => {
1156
+ const name = update.me?.name;
1157
+ // if name has just been received
1158
+ if (creds.me?.name !== name) {
1159
+ logger.debug({ name }, 'updated pushName');
1160
+ sendNode({
1161
+ tag: 'presence',
1162
+ attrs: { name: name }
1163
+ }).catch(err => {
1164
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
1165
+ });
1166
+ }
1167
+ Object.assign(creds, update);
1168
+ });
1169
+ const updateServerTimeOffset = ({ attrs }) => {
1170
+ const tValue = attrs?.t;
1171
+ if (!tValue) {
1172
+ return;
1173
+ }
1174
+ const parsed = Number(tValue);
1175
+ if (Number.isNaN(parsed) || parsed <= 0) {
1176
+ return;
1177
+ }
1178
+ const localMs = Date.now();
1179
+ serverTimeOffsetMs = parsed * 1000 - localMs;
1180
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
1181
+ };
1182
+ const getUnifiedSessionId = () => {
1183
+ const offsetMs = 3 * TimeMs.Day;
1184
+ const now = Date.now() + serverTimeOffsetMs;
1185
+ const id = (now + offsetMs) % TimeMs.Week;
1186
+ return id.toString();
1187
+ };
1188
+ const sendUnifiedSession = async () => {
1189
+ if (!ws.isOpen) {
1190
+ return;
1191
+ }
1192
+ const node = {
1193
+ tag: 'ib',
1194
+ attrs: {},
1195
+ content: [
1196
+ {
1197
+ tag: 'unified_session',
1198
+ attrs: {
1199
+ id: getUnifiedSessionId()
1200
+ }
1201
+ }
1202
+ ]
1203
+ };
1204
+ try {
1205
+ await sendNode(node);
1206
+ }
1207
+ catch (error) {
1208
+ logger.debug({ error }, 'failed to send unified_session telemetry');
1209
+ }
1210
+ };
1211
+ const registerSocketEndHandler = (handler) => {
1212
+ socketEndHandlers.push(handler);
1213
+ };
1214
+ /**
1215
+ * Fetches your account's standing when it comes to restrictions.
1216
+ * @returns Returns the state of the restrictions.
1217
+ */
1218
+ const fetchAccountReachoutTimelock = async () => {
1219
+ const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
1220
+ const result = {
1221
+ isActive: !!queryResult?.is_active,
1222
+ timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
1223
+ ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
1224
+ : undefined,
1225
+ enforcementType: queryResult?.enforcement_type ?? ReachoutTimelockEnforcementType.DEFAULT
1226
+ };
1227
+ ev.emit('connection.update', { reachoutTimeLock: result });
1228
+ return result;
1229
+ };
1230
+ /**
1231
+ * Fetches your account's new chat limits.
1232
+ * @returns Returns the quota and the usage.
1233
+ */
1234
+ const fetchNewChatMessageCap = async () => {
1235
+ return executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
1236
+ };
1237
+ return {
1238
+ type: 'md',
1239
+ ws,
1240
+ ev,
1241
+ authState: { creds, keys },
1242
+ signalRepository,
1243
+ get user() {
1244
+ return authState.creds.me;
1245
+ },
1246
+ generateMessageTag,
1247
+ ignoreKey: ignoreKeyRegistry.register,
1248
+ query,
1249
+ waitForMessage,
1250
+ waitForSocketOpen,
1251
+ sendRawMessage,
1252
+ sendNode,
1253
+ logout,
1254
+ end,
1255
+ registerSocketEndHandler,
1256
+ onUnexpectedError,
1257
+ uploadPreKeys,
1258
+ uploadPreKeysToServerIfRequired,
1259
+ digestKeyBundle,
1260
+ rotateSignedPreKey,
1261
+ requestPairingCode,
1262
+ updateServerTimeOffset,
1263
+ sendUnifiedSession,
1264
+ wamBuffer: publicWAMBuffer,
1265
+ /** Waits for the connection to WA to reach a state */
1266
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
1267
+ sendWAMBuffer,
1268
+ executeUSyncQuery,
1269
+ onWhatsApp,
1270
+ onWhatsAppUsername,
1271
+ fetchUsername,
1272
+ checkUsername,
1273
+ setUsername,
1274
+ deleteUsername,
1275
+ getMyUsername,
1276
+ setUsernamePin,
1277
+ fetchAccountReachoutTimelock,
1278
+ fetchNewChatMessageCap
1279
+ };
1280
+ };
1281
+ /**
1282
+ * map the websocket error to the right type
1283
+ * so it can be retried by the caller
1284
+ * */
1285
+ function mapWebSocketError(handler) {
1286
+ return (error) => {
1287
+ handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
1288
+ };
1289
+ }
1290
+ //# sourceMappingURL=socket.js.map