@neelegirl/baileys 1.5.5 → 1.5.7

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