@violetix/baileys 0.0.0-stage → 0.3.18

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