dcodeindra-baileyspro 2.3.9

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 (286) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2534 -0
  3. package/WAProto/Adv/Adv.d.ts +518 -0
  4. package/WAProto/Adv/Adv.js +1734 -0
  5. package/WAProto/Adv/Adv.proto +36 -0
  6. package/WAProto/BotMetadata/BotMetadata.d.ts +5745 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +16291 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +463 -0
  9. package/WAProto/Cert/Cert.d.ts +497 -0
  10. package/WAProto/Cert/Cert.js +1503 -0
  11. package/WAProto/Cert/Cert.proto +28 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +391 -0
  13. package/WAProto/ChatLockSettings/ChatLockSettings.js +1155 -0
  14. package/WAProto/ChatLockSettings/ChatLockSettings.proto +7 -0
  15. package/WAProto/CompanionReg/CompanionReg.d.ts +1055 -0
  16. package/WAProto/CompanionReg/CompanionReg.js +3532 -0
  17. package/WAProto/CompanionReg/CompanionReg.proto +89 -0
  18. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +187 -0
  19. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +520 -0
  20. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +14 -0
  21. package/WAProto/E2E/E2E.d.ts +28417 -0
  22. package/WAProto/E2E/E2E.js +98438 -0
  23. package/WAProto/E2E/E2E.proto +2289 -0
  24. package/WAProto/Ephemeral/Ephemeral.d.ts +95 -0
  25. package/WAProto/Ephemeral/Ephemeral.js +269 -0
  26. package/WAProto/Ephemeral/Ephemeral.proto +6 -0
  27. package/WAProto/HistorySync/HistorySync.d.ts +40728 -0
  28. package/WAProto/HistorySync/HistorySync.js +142980 -0
  29. package/WAProto/HistorySync/HistorySync.proto +207 -0
  30. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +189 -0
  31. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +585 -0
  32. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +11 -0
  33. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +461 -0
  34. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +1559 -0
  35. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +37 -0
  36. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +29294 -0
  37. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +101732 -0
  38. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +76 -0
  39. package/WAProto/MmsRetry/MmsRetry.d.ts +200 -0
  40. package/WAProto/MmsRetry/MmsRetry.js +586 -0
  41. package/WAProto/MmsRetry/MmsRetry.proto +17 -0
  42. package/WAProto/Protocol/Protocol.d.ts +218 -0
  43. package/WAProto/Protocol/Protocol.js +701 -0
  44. package/WAProto/Protocol/Protocol.proto +20 -0
  45. package/WAProto/Reporting/Reporting.d.ts +301 -0
  46. package/WAProto/Reporting/Reporting.js +989 -0
  47. package/WAProto/Reporting/Reporting.proto +19 -0
  48. package/WAProto/ServerSync/ServerSync.d.ts +1050 -0
  49. package/WAProto/ServerSync/ServerSync.js +3176 -0
  50. package/WAProto/ServerSync/ServerSync.proto +59 -0
  51. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +1507 -0
  52. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +4756 -0
  53. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +88 -0
  54. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +617 -0
  55. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1940 -0
  56. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +38 -0
  57. package/WAProto/StatusAttributions/StatusAttributions.d.ts +636 -0
  58. package/WAProto/StatusAttributions/StatusAttributions.js +2037 -0
  59. package/WAProto/StatusAttributions/StatusAttributions.proto +61 -0
  60. package/WAProto/SyncAction/SyncAction.d.ts +7227 -0
  61. package/WAProto/SyncAction/SyncAction.js +22271 -0
  62. package/WAProto/SyncAction/SyncAction.proto +423 -0
  63. package/WAProto/UserPassword/UserPassword.d.ts +298 -0
  64. package/WAProto/UserPassword/UserPassword.js +898 -0
  65. package/WAProto/UserPassword/UserPassword.proto +27 -0
  66. package/WAProto/VnameCert/VnameCert.d.ts +658 -0
  67. package/WAProto/VnameCert/VnameCert.js +2225 -0
  68. package/WAProto/VnameCert/VnameCert.proto +60 -0
  69. package/WAProto/Wa6/Wa6.d.ts +1613 -0
  70. package/WAProto/Wa6/Wa6.js +6299 -0
  71. package/WAProto/Wa6/Wa6.proto +229 -0
  72. package/WAProto/Web/Web.d.ts +31718 -0
  73. package/WAProto/Web/Web.js +113402 -0
  74. package/WAProto/Web/Web.proto +545 -0
  75. package/WAProto/index.d.ts +49 -0
  76. package/WAProto/index.js +28 -0
  77. package/WASignalGroup/GroupProtocol.js +1771 -0
  78. package/WASignalGroup/ciphertext_message.js +10 -0
  79. package/WASignalGroup/group_cipher.js +103 -0
  80. package/WASignalGroup/group_session_builder.js +39 -0
  81. package/WASignalGroup/index.js +5 -0
  82. package/WASignalGroup/keyhelper.js +17 -0
  83. package/WASignalGroup/protobufs.js +2 -0
  84. package/WASignalGroup/queue_job.js +64 -0
  85. package/WASignalGroup/sender_chain_key.js +38 -0
  86. package/WASignalGroup/sender_key_distribution_message.js +68 -0
  87. package/WASignalGroup/sender_key_message.js +79 -0
  88. package/WASignalGroup/sender_key_name.js +59 -0
  89. package/WASignalGroup/sender_key_record.js +47 -0
  90. package/WASignalGroup/sender_key_state.js +110 -0
  91. package/WASignalGroup/sender_message_key.js +30 -0
  92. package/check-node-version.js +10 -0
  93. package/lib/Defaults/baileys-version.json +3 -0
  94. package/lib/Defaults/index.d.ts +51 -0
  95. package/lib/Defaults/index.js +108 -0
  96. package/lib/Defaults/phonenumber-mcc.json +223 -0
  97. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  98. package/lib/Signal/Group/ciphertext-message.js +19 -0
  99. package/lib/Signal/Group/group-session-builder.d.ts +17 -0
  100. package/lib/Signal/Group/group-session-builder.js +72 -0
  101. package/lib/Signal/Group/group_cipher.d.ts +19 -0
  102. package/lib/Signal/Group/group_cipher.js +99 -0
  103. package/lib/Signal/Group/index.d.ts +11 -0
  104. package/lib/Signal/Group/index.js +61 -0
  105. package/lib/Signal/Group/keyhelper.d.ts +16 -0
  106. package/lib/Signal/Group/keyhelper.js +66 -0
  107. package/lib/Signal/Group/queue-job.d.ts +1 -0
  108. package/lib/Signal/Group/queue-job.js +64 -0
  109. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  110. package/lib/Signal/Group/sender-chain-key.js +39 -0
  111. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  112. package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
  113. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  114. package/lib/Signal/Group/sender-key-message.js +73 -0
  115. package/lib/Signal/Group/sender-key-name.d.ts +19 -0
  116. package/lib/Signal/Group/sender-key-name.js +59 -0
  117. package/lib/Signal/Group/sender-key-record.d.ts +32 -0
  118. package/lib/Signal/Group/sender-key-record.js +53 -0
  119. package/lib/Signal/Group/sender-key-record.ts +77 -0
  120. package/lib/Signal/Group/sender-key-state.d.ts +44 -0
  121. package/lib/Signal/Group/sender-key-state.js +104 -0
  122. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  123. package/lib/Signal/Group/sender-message-key.js +33 -0
  124. package/lib/Signal/libsignal.d.ts +3 -0
  125. package/lib/Signal/libsignal.js +153 -0
  126. package/lib/Socket/Client/index.d.ts +2 -0
  127. package/lib/Socket/Client/index.js +18 -0
  128. package/lib/Socket/Client/types.d.ts +15 -0
  129. package/lib/Socket/Client/types.js +14 -0
  130. package/lib/Socket/Client/websocket.d.ts +12 -0
  131. package/lib/Socket/Client/websocket.js +57 -0
  132. package/lib/Socket/business.d.ts +181 -0
  133. package/lib/Socket/business.js +259 -0
  134. package/lib/Socket/chats.d.ts +95 -0
  135. package/lib/Socket/chats.js +906 -0
  136. package/lib/Socket/community.d.ts +131 -0
  137. package/lib/Socket/community.js +369 -0
  138. package/lib/Socket/groups.d.ts +122 -0
  139. package/lib/Socket/groups.js +360 -0
  140. package/lib/Socket/index.d.ts +183 -0
  141. package/lib/Socket/index.js +10 -0
  142. package/lib/Socket/messages-recv.d.ts +170 -0
  143. package/lib/Socket/messages-recv.js +1074 -0
  144. package/lib/Socket/messages-send.d.ts +161 -0
  145. package/lib/Socket/messages-send.js +982 -0
  146. package/lib/Socket/newsletter.d.ts +140 -0
  147. package/lib/Socket/newsletter.js +242 -0
  148. package/lib/Socket/socket.d.ts +43 -0
  149. package/lib/Socket/socket.js +749 -0
  150. package/lib/Socket/usync.d.ts +36 -0
  151. package/lib/Socket/usync.js +71 -0
  152. package/lib/Store/index.d.ts +4 -0
  153. package/lib/Store/index.js +20 -0
  154. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  155. package/lib/Store/make-cache-manager-store.js +77 -0
  156. package/lib/Store/make-in-memory-store.d.ts +117 -0
  157. package/lib/Store/make-in-memory-store.js +420 -0
  158. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  159. package/lib/Store/make-ordered-dictionary.js +83 -0
  160. package/lib/Store/object-repository.d.ts +10 -0
  161. package/lib/Store/object-repository.js +28 -0
  162. package/lib/Types/Auth.d.ts +103 -0
  163. package/lib/Types/Auth.js +2 -0
  164. package/lib/Types/Call.d.ts +13 -0
  165. package/lib/Types/Call.js +2 -0
  166. package/lib/Types/Chat.d.ts +115 -0
  167. package/lib/Types/Chat.js +6 -0
  168. package/lib/Types/Contact.d.ts +35 -0
  169. package/lib/Types/Contact.js +2 -0
  170. package/lib/Types/Events.d.ts +208 -0
  171. package/lib/Types/Events.js +2 -0
  172. package/lib/Types/GroupMetadata.d.ts +81 -0
  173. package/lib/Types/GroupMetadata.js +2 -0
  174. package/lib/Types/Label.d.ts +46 -0
  175. package/lib/Types/Label.js +28 -0
  176. package/lib/Types/LabelAssociation.d.ts +29 -0
  177. package/lib/Types/LabelAssociation.js +10 -0
  178. package/lib/Types/Message.d.ts +480 -0
  179. package/lib/Types/Message.js +9 -0
  180. package/lib/Types/MexUpdates.d.ts +9 -0
  181. package/lib/Types/MexUpdates.js +18 -0
  182. package/lib/Types/Newsletter.d.ts +92 -0
  183. package/lib/Types/Newsletter.js +33 -0
  184. package/lib/Types/Product.d.ts +78 -0
  185. package/lib/Types/Product.js +2 -0
  186. package/lib/Types/Signal.d.ts +57 -0
  187. package/lib/Types/Signal.js +2 -0
  188. package/lib/Types/Socket.d.ts +116 -0
  189. package/lib/Types/Socket.js +2 -0
  190. package/lib/Types/State.d.ts +27 -0
  191. package/lib/Types/State.js +2 -0
  192. package/lib/Types/USync.d.ts +25 -0
  193. package/lib/Types/USync.js +2 -0
  194. package/lib/Types/index.d.ts +70 -0
  195. package/lib/Types/index.js +42 -0
  196. package/lib/Utils/auth-utils.d.ts +18 -0
  197. package/lib/Utils/auth-utils.js +198 -0
  198. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  199. package/lib/Utils/baileys-event-stream.js +64 -0
  200. package/lib/Utils/business.d.ts +22 -0
  201. package/lib/Utils/business.js +243 -0
  202. package/lib/Utils/chat-utils.d.ts +72 -0
  203. package/lib/Utils/chat-utils.js +762 -0
  204. package/lib/Utils/crypto.d.ts +40 -0
  205. package/lib/Utils/crypto.js +150 -0
  206. package/lib/Utils/decode-wa-message.d.ts +252 -0
  207. package/lib/Utils/decode-wa-message.js +232 -0
  208. package/lib/Utils/event-buffer.d.ts +35 -0
  209. package/lib/Utils/event-buffer.js +539 -0
  210. package/lib/Utils/generics.d.ts +96 -0
  211. package/lib/Utils/generics.js +553 -0
  212. package/lib/Utils/history.d.ts +29 -0
  213. package/lib/Utils/history.js +109 -0
  214. package/lib/Utils/index.d.ts +19 -0
  215. package/lib/Utils/index.js +35 -0
  216. package/lib/Utils/link-preview.d.ts +21 -0
  217. package/lib/Utils/link-preview.js +112 -0
  218. package/lib/Utils/logger.d.ts +11 -0
  219. package/lib/Utils/logger.js +7 -0
  220. package/lib/Utils/lt-hash.d.ts +12 -0
  221. package/lib/Utils/lt-hash.js +53 -0
  222. package/lib/Utils/make-mutex.d.ts +7 -0
  223. package/lib/Utils/make-mutex.js +45 -0
  224. package/lib/Utils/messages-media.d.ts +104 -0
  225. package/lib/Utils/messages-media.js +751 -0
  226. package/lib/Utils/messages.d.ts +80 -0
  227. package/lib/Utils/messages.js +1741 -0
  228. package/lib/Utils/noise-handler.d.ts +19 -0
  229. package/lib/Utils/noise-handler.js +150 -0
  230. package/lib/Utils/process-message.d.ts +41 -0
  231. package/lib/Utils/process-message.js +391 -0
  232. package/lib/Utils/signal.d.ts +33 -0
  233. package/lib/Utils/signal.js +154 -0
  234. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -0
  235. package/lib/Utils/use-mongo-file-auth-state.js +75 -0
  236. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  237. package/lib/Utils/use-multi-file-auth-state.js +123 -0
  238. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  239. package/lib/Utils/use-single-file-auth-state.js +75 -0
  240. package/lib/Utils/validate-connection.d.ts +10 -0
  241. package/lib/Utils/validate-connection.js +174 -0
  242. package/lib/WABinary/constants.d.ts +27 -0
  243. package/lib/WABinary/constants.js +45 -0
  244. package/lib/WABinary/decode.d.ts +6 -0
  245. package/lib/WABinary/decode.js +255 -0
  246. package/lib/WABinary/encode.d.ts +2 -0
  247. package/lib/WABinary/encode.js +243 -0
  248. package/lib/WABinary/generic-utils.d.ts +16 -0
  249. package/lib/WABinary/generic-utils.js +125 -0
  250. package/lib/WABinary/index.d.ts +5 -0
  251. package/lib/WABinary/index.js +21 -0
  252. package/lib/WABinary/jid-utils.d.ts +34 -0
  253. package/lib/WABinary/jid-utils.js +73 -0
  254. package/lib/WABinary/types.d.ts +18 -0
  255. package/lib/WABinary/types.js +2 -0
  256. package/lib/WAM/BinaryInfo.d.ts +16 -0
  257. package/lib/WAM/BinaryInfo.js +14 -0
  258. package/lib/WAM/constants.d.ts +39 -0
  259. package/lib/WAM/constants.js +15362 -0
  260. package/lib/WAM/encode.d.ts +2 -0
  261. package/lib/WAM/encode.js +156 -0
  262. package/lib/WAM/index.d.ts +3 -0
  263. package/lib/WAM/index.js +19 -0
  264. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +25 -0
  265. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +60 -0
  266. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  267. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  268. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  269. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +58 -0
  270. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  271. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  272. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +8 -0
  273. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +26 -0
  274. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  275. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  276. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  277. package/lib/WAUSync/Protocols/index.js +22 -0
  278. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  279. package/lib/WAUSync/USyncQuery.js +88 -0
  280. package/lib/WAUSync/USyncUser.d.ts +12 -0
  281. package/lib/WAUSync/USyncUser.js +27 -0
  282. package/lib/WAUSync/index.d.ts +3 -0
  283. package/lib/WAUSync/index.js +19 -0
  284. package/lib/index.d.ts +13 -0
  285. package/lib/index.js +45 -0
  286. package/package.json +63 -0
@@ -0,0 +1,749 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const boom_1 = require("@hapi/boom")
6
+ const crypto_1 = require("crypto")
7
+ const url_1 = require("url")
8
+ const util_1 = require("util")
9
+ const WAProto_1 = require("../../WAProto")
10
+ const Defaults_1 = require("../Defaults")
11
+ const Types_1 = require("../Types")
12
+ const Utils_1 = require("../Utils")
13
+ const WABinary_1 = require("../WABinary")
14
+ const Client_1 = require("./Client")
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
+ const makeSocket = (config) => {
23
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config
24
+
25
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl
26
+
27
+ if (config.mobile || url.protocol === 'tcp:') {
28
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut })
29
+ }
30
+
31
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
32
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
33
+ }
34
+
35
+ const ws = new Client_1.WebSocketClient(url, config)
36
+
37
+ ws.connect()
38
+ const ev = Utils_1.makeEventBuffer(logger)
39
+
40
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
41
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair()
42
+
43
+ /** WA noise protocol wrapper */
44
+ const noise = Utils_1.makeNoiseHandler({
45
+ keyPair: ephemeralKeyPair,
46
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
47
+ logger,
48
+ routingInfo: authState?.creds?.routingInfo
49
+ })
50
+
51
+ const { creds } = authState
52
+
53
+ // add transaction capability
54
+ const keys = Utils_1.addTransactionCapability(authState.keys, logger, transactionOpts)
55
+ const signalRepository = makeSignalRepository({ creds, keys })
56
+
57
+ let lastDateRecv
58
+ let epoch = 1
59
+ let keepAliveReq
60
+ let qrTimer
61
+ let closed = false
62
+
63
+ const uqTagId = Utils_1.generateMdTagPrefix()
64
+ const generateMessageTag = () => `${uqTagId}${epoch++}`
65
+ const sendPromise = util_1.promisify(ws.send)
66
+
67
+ /** send a raw buffer */
68
+ const sendRawMessage = async (data) => {
69
+ if (!ws.isOpen) {
70
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
71
+ }
72
+
73
+ const bytes = noise.encodeFrame(data)
74
+ await Utils_1.promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
75
+ try {
76
+ await sendPromise.call(ws, bytes)
77
+ resolve()
78
+ }
79
+ catch (error) {
80
+ reject(error)
81
+ }
82
+ })
83
+ }
84
+
85
+ /** send a binary node */
86
+ const sendNode = (frame) => {
87
+ if (logger.level === 'trace') {
88
+ logger.trace({ xml: WABinary_1.binaryNodeToString(frame), msg: 'xml send' })
89
+ }
90
+
91
+ const buff = WABinary_1.encodeBinaryNode(frame)
92
+
93
+ return sendRawMessage(buff)
94
+ }
95
+
96
+ /** log & process any unexpected errors */
97
+ const onUnexpectedError = (err, msg) => {
98
+ logger.error({ err }, `unexpected error in '${msg}'`)
99
+ }
100
+
101
+ /** await the next incoming message */
102
+ const awaitNextMessage = async (sendMsg) => {
103
+ if (!ws.isOpen) {
104
+ throw new boom_1.Boom('Connection Closed', {
105
+ statusCode: Types_1.DisconnectReason.connectionClosed
106
+ })
107
+ }
108
+
109
+ let onOpen
110
+ let onClose
111
+
112
+ const result = Utils_1.promiseTimeout(connectTimeoutMs, (resolve, reject) => {
113
+ onOpen = resolve
114
+ onClose = mapWebSocketError(reject)
115
+ ws.on('frame', onOpen)
116
+ ws.on('close', onClose)
117
+ ws.on('error', onClose)
118
+ }).finally(() => {
119
+ ws.off('frame', onOpen)
120
+ ws.off('close', onClose)
121
+ ws.off('error', onClose)
122
+ })
123
+
124
+ if (sendMsg) {
125
+ sendRawMessage(sendMsg).catch(onClose)
126
+ }
127
+
128
+ return result
129
+ }
130
+
131
+ /**
132
+ * Wait for a message with a certain tag to be received
133
+ * @param msgId the message tag to await
134
+ * @param timeoutMs timeout after which the promise will reject
135
+ */
136
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
137
+ let onRecv
138
+ let onErr
139
+ try {
140
+ return await Utils_1.promiseTimeout(timeoutMs, (resolve, reject) => {
141
+ onRecv = resolve
142
+ onErr = err => {
143
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }))
144
+ }
145
+ ws.on(`TAG:${msgId}`, onRecv)
146
+ ws.on('close', onErr) // if the socket closes, you'll never receive the message
147
+ ws.off('error', onErr)
148
+ })
149
+ }
150
+
151
+ finally {
152
+ ws.off(`TAG:${msgId}`, onRecv)
153
+ ws.off('close', onErr) // if the socket closes, you'll never receive the message
154
+ ws.off('error', onErr)
155
+ }
156
+ }
157
+
158
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
159
+ const query = async (node, timeoutMs) => {
160
+ if (!node.attrs.id) {
161
+ node.attrs.id = generateMessageTag()
162
+ }
163
+
164
+ const msgId = node.attrs.id
165
+ const wait = waitForMessage(msgId, timeoutMs)
166
+
167
+ await sendNode(node)
168
+
169
+ const result = await wait
170
+
171
+ if ('tag' in result) {
172
+ WABinary_1.assertNodeErrorFree(result)
173
+ }
174
+
175
+ return result
176
+ }
177
+ /** connection handshake */
178
+ const validateConnection = async () => {
179
+ let helloMsg = {
180
+ clientHello: { ephemeral: ephemeralKeyPair.public }
181
+ }
182
+
183
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg)
184
+ logger.info({ browser, helloMsg }, 'connected to WA')
185
+
186
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish()
187
+ const result = await awaitNextMessage(init)
188
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result)
189
+
190
+ logger.trace({ handshake }, 'handshake recv from WA')
191
+
192
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey)
193
+ let node
194
+
195
+ if (!creds.me) {
196
+ node = Utils_1.generateRegistrationNode(creds, config)
197
+ logger.info({ node }, 'not logged in, attempting registration...')
198
+ }
199
+
200
+ else {
201
+ node = Utils_1.generateLoginNode(creds.me.id, config)
202
+ logger.info({ node }, 'logging in...')
203
+ }
204
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish())
205
+
206
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
207
+ clientFinish: {
208
+ static: keyEnc,
209
+ payload: payloadEnc,
210
+ },
211
+ }).finish())
212
+ noise.finishInit()
213
+ startKeepAliveRequest()
214
+ }
215
+
216
+ const getAvailablePreKeysOnServer = async () => {
217
+ const result = await query({
218
+ tag: 'iq',
219
+ attrs: {
220
+ id: generateMessageTag(),
221
+ xmlns: 'encrypt',
222
+ type: 'get',
223
+ to: WABinary_1.S_WHATSAPP_NET
224
+ },
225
+ content: [
226
+ { tag: 'count', attrs: {} }
227
+ ]
228
+ })
229
+
230
+ const countChild = WABinary_1.getBinaryNodeChild(result, 'count')
231
+
232
+ return +countChild.attrs.value
233
+ }
234
+
235
+ /** generates and uploads a set of pre-keys to the server */
236
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
237
+ await keys.transaction(async () => {
238
+ logger.info({ count }, 'uploading pre-keys')
239
+ const { update, node } = await Utils_1.getNextPreKeysNode({ creds, keys }, count)
240
+ await query(node)
241
+ ev.emit('creds.update', update)
242
+ logger.info({ count }, 'uploaded pre-keys')
243
+ })
244
+ }
245
+
246
+ const uploadPreKeysToServerIfRequired = async () => {
247
+ const preKeyCount = await getAvailablePreKeysOnServer()
248
+ logger.info(`${preKeyCount} pre-keys found on server`)
249
+
250
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
251
+ await uploadPreKeys()
252
+ }
253
+ }
254
+
255
+ const onMessageReceived = (data) => {
256
+ noise.decodeFrame(data, frame => {
257
+ // reset ping timeout
258
+ lastDateRecv = new Date()
259
+ let anyTriggered = false
260
+ anyTriggered = ws.emit('frame', frame)
261
+
262
+ // if it's a binary node
263
+ if (!(frame instanceof Uint8Array)) {
264
+ const msgId = frame.attrs.id
265
+
266
+ if (logger.level === 'trace') {
267
+ logger.trace({ xml: WABinary_1.binaryNodeToString(frame), msg: 'recv xml' })
268
+ }
269
+
270
+ /* Check if this is a response to a message we sent */
271
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered
272
+
273
+ /* Check if this is a response to a message we are expecting */
274
+ const l0 = frame.tag
275
+ const l1 = frame.attrs || {}
276
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
277
+
278
+ for (const key of Object.keys(l1)) {
279
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
280
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
281
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
282
+ }
283
+
284
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
285
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
286
+
287
+ if (!anyTriggered && logger.level === 'debug') {
288
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
289
+ }
290
+ }
291
+ })
292
+ }
293
+
294
+ const end = (error) => {
295
+ if (closed) {
296
+ logger.trace({ trace: error?.stack }, 'connection already closed')
297
+ return
298
+ }
299
+
300
+ closed = true
301
+
302
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
303
+ clearInterval(keepAliveReq)
304
+ clearTimeout(qrTimer)
305
+ ws.removeAllListeners('close')
306
+ ws.removeAllListeners('error')
307
+ ws.removeAllListeners('open')
308
+ ws.removeAllListeners('message')
309
+
310
+ if (!ws.isClosed && !ws.isClosing) {
311
+ try {
312
+ ws.close()
313
+ }
314
+ catch (_a) { }
315
+ }
316
+
317
+ ev.emit('connection.update', {
318
+ connection: 'close',
319
+ lastDisconnect: {
320
+ error,
321
+ date: new Date()
322
+ }
323
+ })
324
+
325
+ ev.removeAllListeners('connection.update')
326
+ }
327
+
328
+ const waitForSocketOpen = async () => {
329
+ if (ws.isOpen) {
330
+ return
331
+ }
332
+
333
+ if (ws.isClosed || ws.isClosing) {
334
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed })
335
+ }
336
+
337
+ let onOpen
338
+ let onClose
339
+
340
+ await new Promise((resolve, reject) => {
341
+ onOpen = () => resolve(undefined)
342
+ onClose = mapWebSocketError(reject)
343
+ ws.on('open', onOpen)
344
+ ws.on('close', onClose)
345
+ ws.on('error', onClose)
346
+ }).finally(() => {
347
+ ws.off('open', onOpen)
348
+ ws.off('close', onClose)
349
+ ws.off('error', onClose)
350
+ })
351
+ }
352
+
353
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
354
+ if (!lastDateRecv) {
355
+ lastDateRecv = new Date()
356
+ }
357
+
358
+ const diff = Date.now() - lastDateRecv.getTime()
359
+
360
+ /*
361
+ check if it's been a suspicious amount of time since the server responded with our last seen
362
+ it could be that the network is down
363
+ */
364
+ if (diff > keepAliveIntervalMs + 5000) {
365
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }))
366
+ }
367
+
368
+ else if (ws.isOpen) {
369
+ // if its all good, send a keep alive request
370
+ query({
371
+ tag: 'iq',
372
+ attrs: {
373
+ id: generateMessageTag(),
374
+ to: WABinary_1.S_WHATSAPP_NET,
375
+ type: 'get',
376
+ xmlns: 'w:p',
377
+ },
378
+ content: [{ tag: 'ping', attrs: {} }]
379
+ }).catch(err => {
380
+ logger.error({ trace: err.stack }, 'error in sending keep alive')
381
+ })
382
+ }
383
+
384
+ else {
385
+ logger.warn('keep alive called when WS not open')
386
+ }
387
+ }, keepAliveIntervalMs))
388
+
389
+ /** i have no idea why this exists. pls enlighten me */
390
+ const sendPassiveIq = (tag) => (query({
391
+ tag: 'iq',
392
+ attrs: {
393
+ to: WABinary_1.S_WHATSAPP_NET,
394
+ xmlns: 'passive',
395
+ type: 'set',
396
+ },
397
+ content: [
398
+ { tag, attrs: {} }
399
+ ]
400
+ }))
401
+
402
+ /** logout & invalidate connection */
403
+ const logout = async (msg) => {
404
+ const jid = authState.creds.me?.id
405
+
406
+ if (jid) {
407
+ await sendNode({
408
+ tag: 'iq',
409
+ attrs: {
410
+ to: WABinary_1.S_WHATSAPP_NET,
411
+ type: 'set',
412
+ id: generateMessageTag(),
413
+ xmlns: 'md'
414
+ },
415
+ content: [
416
+ {
417
+ tag: 'remove-companion-device',
418
+ attrs: {
419
+ jid,
420
+ reason: 'user_initiated'
421
+ }
422
+ }
423
+ ]
424
+ })
425
+ }
426
+
427
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }))
428
+ }
429
+
430
+ const requestPairingCode = async (phoneNumber, code) => {
431
+ authState.creds.pairingCode = code?.toUpperCase() || Utils_1.asciiDecode([66, 65, 73, 76, 83, 78, 75, 65])
432
+
433
+ authState.creds.me = {
434
+ id: WABinary_1.jidEncode(phoneNumber, 's.whatsapp.net'),
435
+ name: '~'
436
+ }
437
+
438
+ ev.emit('creds.update', authState.creds)
439
+
440
+ await sendNode({
441
+ tag: 'iq',
442
+ attrs: {
443
+ to: WABinary_1.S_WHATSAPP_NET,
444
+ type: 'set',
445
+ id: generateMessageTag(),
446
+ xmlns: 'md'
447
+ },
448
+ content: [
449
+ {
450
+ tag: 'link_code_companion_reg',
451
+ attrs: {
452
+ jid: authState.creds.me.id,
453
+ stage: 'companion_hello',
454
+ // eslint-disable-next-line camelcase
455
+ should_show_push_notification: 'true'
456
+ },
457
+ content: [
458
+ {
459
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
460
+ attrs: {},
461
+ content: await generatePairingKey()
462
+ },
463
+ {
464
+ tag: 'companion_server_auth_key_pub',
465
+ attrs: {},
466
+ content: authState.creds.noiseKey.public
467
+ },
468
+ {
469
+ tag: 'companion_platform_id',
470
+ attrs: {},
471
+ content: Utils_1.getPlatformId(browser[1])
472
+ },
473
+ {
474
+ tag: 'companion_platform_display',
475
+ attrs: {},
476
+ content: `${browser[1]} (${browser[0]})`
477
+ },
478
+ {
479
+ tag: 'link_code_pairing_nonce',
480
+ attrs: {},
481
+ content: '0'
482
+ }
483
+ ]
484
+ }
485
+ ]
486
+ })
487
+
488
+ return authState.creds.pairingCode
489
+ }
490
+
491
+ async function generatePairingKey() {
492
+ const salt = crypto_1.randomBytes(32)
493
+ const randomIv = crypto_1.randomBytes(16)
494
+ const key = await Utils_1.derivePairingCodeKey(authState.creds.pairingCode, salt)
495
+ const ciphered = Utils_1.aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
496
+
497
+ return Buffer.concat([salt, randomIv, ciphered])
498
+ }
499
+
500
+ const sendWAMBuffer = (wamBuffer) => {
501
+ return query({
502
+ tag: 'iq',
503
+ attrs: {
504
+ to: WABinary_1.S_WHATSAPP_NET,
505
+ id: generateMessageTag(),
506
+ xmlns: 'w:stats'
507
+ },
508
+ content: [
509
+ {
510
+ tag: 'add',
511
+ attrs: {},
512
+ content: wamBuffer
513
+ }
514
+ ]
515
+ })
516
+ }
517
+
518
+ ws.on('message', onMessageReceived)
519
+
520
+ ws.on('open', async () => {
521
+ try {
522
+ await validateConnection()
523
+ }
524
+ catch (err) {
525
+ logger.error({ err }, 'error in validating connection')
526
+ end(err)
527
+ }
528
+ })
529
+
530
+ ws.on('error', mapWebSocketError(end))
531
+
532
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })))
533
+
534
+ // the server terminated the connection
535
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })))
536
+
537
+ // QR gen
538
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
539
+ const iq = {
540
+ tag: 'iq',
541
+ attrs: {
542
+ to: WABinary_1.S_WHATSAPP_NET,
543
+ type: 'result',
544
+ id: stanza.attrs.id,
545
+ }
546
+ }
547
+
548
+ await sendNode(iq)
549
+
550
+ const pairDeviceNode = WABinary_1.getBinaryNodeChild(stanza, 'pair-device')
551
+ const refNodes = WABinary_1.getBinaryNodeChildren(pairDeviceNode, 'ref')
552
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
553
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
554
+ const advB64 = creds.advSecretKey
555
+
556
+ let qrMs = qrTimeout || 60000 // time to let a QR live
557
+
558
+ const genPairQR = () => {
559
+ if (!ws.isOpen) {
560
+ return
561
+ }
562
+
563
+ const refNode = refNodes.shift()
564
+
565
+ if (!refNode) {
566
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }))
567
+ return
568
+ }
569
+
570
+ const ref = refNode.content.toString('utf-8')
571
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',')
572
+
573
+ ev.emit('connection.update', { qr })
574
+ qrTimer = setTimeout(genPairQR, qrMs)
575
+ qrMs = qrTimeout || 20000 // shorter subsequent qrs
576
+ }
577
+
578
+ genPairQR()
579
+ })
580
+
581
+ // device paired for the first time
582
+ // if device pairs successfully, the server asks to restart the connection
583
+ ws.on('CB:iq,,pair-success', async (stanza) => {
584
+ logger.debug('pair success recv')
585
+ try {
586
+ const { reply, creds: updatedCreds } = Utils_1.configureSuccessfulPairing(stanza, creds)
587
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
588
+
589
+ ev.emit('creds.update', updatedCreds)
590
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined })
591
+
592
+ await sendNode(reply)
593
+ }
594
+
595
+ catch (error) {
596
+ logger.info({ trace: error.stack }, 'error in pairing')
597
+ end(error)
598
+ }
599
+ })
600
+
601
+ // login complete
602
+ ws.on('CB:success', async (node) => {
603
+ try {
604
+ await uploadPreKeysToServerIfRequired()
605
+
606
+ await sendPassiveIq('active')
607
+
608
+ logger.info('opened connection to WA')
609
+
610
+ clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
611
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
612
+ ev.emit('connection.update', { connection: 'open' })
613
+ }
614
+
615
+ catch (err) {
616
+ logger.error({ err }, 'error opening connection')
617
+ end(err)
618
+ }
619
+ })
620
+
621
+ ws.on('CB:stream:error', (node) => {
622
+ logger.error({ node }, 'stream errored out')
623
+ const { reason, statusCode } = Utils_1.getErrorCodeFromStreamError(node)
624
+
625
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }))
626
+ })
627
+
628
+ // stream fail, possible logout
629
+ ws.on('CB:failure', (node) => {
630
+ const reason = +(node.attrs.reason || 500)
631
+
632
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
633
+ })
634
+
635
+ ws.on('CB:ib,,downgrade_webclient', () => {
636
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }))
637
+ })
638
+
639
+ ws.on('CB:ib,,offline_preview', (node) => {
640
+ logger.info('offline preview received', JSON.stringify(node))
641
+
642
+ sendNode({
643
+ tag: 'ib',
644
+ attrs: {},
645
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
646
+ })
647
+ })
648
+
649
+ ws.on('CB:ib,,edge_routing', (node) => {
650
+ const edgeRoutingNode = WABinary_1.getBinaryNodeChild(node, 'edge_routing')
651
+ const routingInfo = WABinary_1.getBinaryNodeChild(edgeRoutingNode, 'routing_info')
652
+
653
+ if (routingInfo?.content) {
654
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content)
655
+ ev.emit('creds.update', authState.creds)
656
+ }
657
+ })
658
+
659
+ let didStartBuffer = false
660
+
661
+ process.nextTick(() => {
662
+ if (creds.me?.id) {
663
+ // start buffering important events
664
+ // if we're logged in
665
+ ev.buffer()
666
+ didStartBuffer = true
667
+ }
668
+
669
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
670
+ })
671
+
672
+ // called when all offline notifs are handled
673
+ ws.on('CB:ib,,offline', (node) => {
674
+ const child = WABinary_1.getBinaryNodeChild(node, 'offline')
675
+ const offlineNotifs = +(child?.attrs.count || 0)
676
+
677
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`)
678
+
679
+ if (didStartBuffer) {
680
+ ev.flush()
681
+ logger.trace('flushed events for initial buffer')
682
+ }
683
+
684
+ ev.emit('connection.update', { receivedPendingNotifications: true })
685
+ })
686
+
687
+ // update credentials when required
688
+ ev.on('creds.update', update => {
689
+ const name = update.me?.name
690
+
691
+ // if name has just been received
692
+ if (creds.me?.name !== name) {
693
+ logger.debug({ name }, 'updated pushName')
694
+
695
+ sendNode({
696
+ tag: 'presence',
697
+ attrs: { name }
698
+ }).catch(err => {
699
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
700
+ })
701
+ }
702
+
703
+ Object.assign(creds, update)
704
+ })
705
+
706
+ if (printQRInTerminal) {
707
+ Utils_1.printQRIfNecessaryListener(ev, logger)
708
+ }
709
+
710
+ return {
711
+ type: 'md',
712
+ ws,
713
+ ev,
714
+ authState: { creds, keys },
715
+ signalRepository,
716
+ get user() {
717
+ return authState.creds.me
718
+ },
719
+ generateMessageTag,
720
+ query,
721
+ waitForMessage,
722
+ waitForSocketOpen,
723
+ sendRawMessage,
724
+ sendNode,
725
+ logout,
726
+ end,
727
+ onUnexpectedError,
728
+ uploadPreKeys,
729
+ uploadPreKeysToServerIfRequired,
730
+ requestPairingCode,
731
+ /** Waits for the connection to WA to reach a state */
732
+ waitForConnectionUpdate: Utils_1.bindWaitForConnectionUpdate(ev),
733
+ sendWAMBuffer,
734
+ }
735
+ }
736
+
737
+ /**
738
+ * map the websocket error to the right type
739
+ * so it can be retried by the caller
740
+ * */
741
+ function mapWebSocketError(handler) {
742
+ return (error) => {
743
+ handler(new boom_1.Boom(`WebSocket Error (${error?.message})`, { statusCode: Utils_1.getCodeFromWSError(error), data: error }))
744
+ }
745
+ }
746
+
747
+ module.exports = {
748
+ makeSocket
749
+ }