@vinzsocket/baileys 2.8.35 → 3.0.10

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