lordceaser-baileys 2.0.12 → 2.0.13

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 (173) hide show
  1. package/package.json +1 -1
  2. package/lib/Defaults/baileys-version.json +0 -3
  3. package/lib/Defaults/index.d.ts +0 -284
  4. package/lib/Defaults/index.js +0 -121
  5. package/lib/Defaults/phonenumber-mcc.json +0 -223
  6. package/lib/Signal/libsignal.d.ts +0 -4
  7. package/lib/Signal/libsignal.js +0 -162
  8. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -15
  9. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  10. package/lib/Socket/Client/index.d.ts +0 -2
  11. package/lib/Socket/Client/index.js +0 -22
  12. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -12
  13. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  14. package/lib/Socket/Client/types.d.ts +0 -16
  15. package/lib/Socket/Client/types.js +0 -18
  16. package/lib/Socket/Client/web-socket-client.js +0 -62
  17. package/lib/Socket/Client/websocket.d.ts +0 -13
  18. package/lib/Socket/Client/websocket.js +0 -62
  19. package/lib/Socket/business.d.ts +0 -182
  20. package/lib/Socket/business.js +0 -268
  21. package/lib/Socket/chats.d.ts +0 -96
  22. package/lib/Socket/chats.js +0 -1026
  23. package/lib/Socket/groups.d.ts +0 -130
  24. package/lib/Socket/groups.js +0 -338
  25. package/lib/Socket/index.d.ts +0 -185
  26. package/lib/Socket/index.js +0 -14
  27. package/lib/Socket/messages-recv.d.ts +0 -171
  28. package/lib/Socket/messages-recv.js +0 -1182
  29. package/lib/Socket/messages-send.d.ts +0 -162
  30. package/lib/Socket/messages-send.js +0 -1006
  31. package/lib/Socket/newsletter.d.ts +0 -142
  32. package/lib/Socket/newsletter.js +0 -256
  33. package/lib/Socket/registration.d.ts +0 -264
  34. package/lib/Socket/registration.js +0 -166
  35. package/lib/Socket/socket.d.ts +0 -45
  36. package/lib/Socket/socket.js +0 -751
  37. package/lib/Socket/socket.js.bak +0 -751
  38. package/lib/Socket/usync.d.ts +0 -37
  39. package/lib/Socket/usync.js +0 -83
  40. package/lib/Store/index.d.ts +0 -4
  41. package/lib/Store/index.js +0 -24
  42. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  43. package/lib/Store/make-cache-manager-store.js +0 -90
  44. package/lib/Store/make-in-memory-store.d.ts +0 -123
  45. package/lib/Store/make-in-memory-store.js +0 -429
  46. package/lib/Store/make-ordered-dictionary.d.ts +0 -12
  47. package/lib/Store/make-ordered-dictionary.js +0 -86
  48. package/lib/Store/object-repository.d.ts +0 -10
  49. package/lib/Store/object-repository.js +0 -31
  50. package/lib/Types/Auth.d.ts +0 -120
  51. package/lib/Types/Auth.js +0 -3
  52. package/lib/Types/Call.d.ts +0 -14
  53. package/lib/Types/Call.js +0 -3
  54. package/lib/Types/Chat.d.ts +0 -134
  55. package/lib/Types/Chat.js +0 -9
  56. package/lib/Types/Contact.d.ts +0 -25
  57. package/lib/Types/Contact.js +0 -3
  58. package/lib/Types/Events.d.ts +0 -212
  59. package/lib/Types/Events.js +0 -3
  60. package/lib/Types/GroupMetadata.d.ts +0 -64
  61. package/lib/Types/GroupMetadata.js +0 -3
  62. package/lib/Types/Label.d.ts +0 -48
  63. package/lib/Types/Label.js +0 -31
  64. package/lib/Types/LabelAssociation.d.ts +0 -35
  65. package/lib/Types/LabelAssociation.js +0 -13
  66. package/lib/Types/Message.d.ts +0 -459
  67. package/lib/Types/Message.js +0 -13
  68. package/lib/Types/Newsletter.d.ts +0 -107
  69. package/lib/Types/Newsletter.js +0 -38
  70. package/lib/Types/Product.d.ts +0 -92
  71. package/lib/Types/Product.js +0 -3
  72. package/lib/Types/Signal.d.ts +0 -68
  73. package/lib/Types/Signal.js +0 -3
  74. package/lib/Types/Socket.d.ts +0 -120
  75. package/lib/Types/Socket.js +0 -3
  76. package/lib/Types/State.d.ts +0 -29
  77. package/lib/Types/State.js +0 -3
  78. package/lib/Types/USync.d.ts +0 -26
  79. package/lib/Types/USync.js +0 -3
  80. package/lib/Types/index.d.ts +0 -78
  81. package/lib/Types/index.js +0 -47
  82. package/lib/Utils/auth-utils.d.ts +0 -21
  83. package/lib/Utils/auth-utils.js +0 -205
  84. package/lib/Utils/baileys-event-stream.d.ts +0 -18
  85. package/lib/Utils/baileys-event-stream.js +0 -70
  86. package/lib/Utils/business.d.ts +0 -29
  87. package/lib/Utils/business.js +0 -247
  88. package/lib/Utils/chat-utils.d.ts +0 -82
  89. package/lib/Utils/chat-utils.js +0 -774
  90. package/lib/Utils/crypto.d.ts +0 -56
  91. package/lib/Utils/crypto.js +0 -179
  92. package/lib/Utils/decode-wa-message.d.ts +0 -41
  93. package/lib/Utils/decode-wa-message.js +0 -236
  94. package/lib/Utils/event-buffer.d.ts +0 -39
  95. package/lib/Utils/event-buffer.js +0 -548
  96. package/lib/Utils/generics.d.ts +0 -129
  97. package/lib/Utils/generics.js +0 -485
  98. package/lib/Utils/history.d.ts +0 -23
  99. package/lib/Utils/history.js +0 -100
  100. package/lib/Utils/index.d.ts +0 -20
  101. package/lib/Utils/index.js +0 -40
  102. package/lib/Utils/link-preview.d.ts +0 -23
  103. package/lib/Utils/link-preview.js +0 -120
  104. package/lib/Utils/logger.d.ts +0 -13
  105. package/lib/Utils/logger.js +0 -7
  106. package/lib/Utils/lt-hash.d.ts +0 -14
  107. package/lib/Utils/lt-hash.js +0 -58
  108. package/lib/Utils/make-mutex.d.ts +0 -9
  109. package/lib/Utils/make-mutex.js +0 -49
  110. package/lib/Utils/messages-media.d.ts +0 -129
  111. package/lib/Utils/messages-media.js +0 -782
  112. package/lib/Utils/messages.d.ts +0 -103
  113. package/lib/Utils/messages.js +0 -1631
  114. package/lib/Utils/noise-handler.d.ts +0 -20
  115. package/lib/Utils/noise-handler.js +0 -155
  116. package/lib/Utils/process-message.d.ts +0 -49
  117. package/lib/Utils/process-message.js +0 -387
  118. package/lib/Utils/signal.d.ts +0 -42
  119. package/lib/Utils/signal.js +0 -166
  120. package/lib/Utils/use-mongo-file-auth-state.d.ts +0 -6
  121. package/lib/Utils/use-mongo-file-auth-state.js +0 -84
  122. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  123. package/lib/Utils/use-multi-file-auth-state.js +0 -131
  124. package/lib/Utils/use-single-file-auth-state.d.ts +0 -13
  125. package/lib/Utils/use-single-file-auth-state.js +0 -80
  126. package/lib/Utils/use-sql-file-auth-state.d.ts +0 -6
  127. package/lib/Utils/use-sql-file-auth-state.js +0 -143
  128. package/lib/Utils/validate-connection.d.ts +0 -13
  129. package/lib/Utils/validate-connection.js +0 -186
  130. package/lib/WABinary/constants.d.ts +0 -30
  131. package/lib/WABinary/constants.js +0 -53
  132. package/lib/WABinary/decode.d.ts +0 -9
  133. package/lib/WABinary/decode.js +0 -288
  134. package/lib/WABinary/encode.d.ts +0 -3
  135. package/lib/WABinary/encode.js +0 -256
  136. package/lib/WABinary/generic-utils.d.ts +0 -28
  137. package/lib/WABinary/generic-utils.js +0 -150
  138. package/lib/WABinary/index.d.ts +0 -5
  139. package/lib/WABinary/index.js +0 -25
  140. package/lib/WABinary/jid-utils.d.ts +0 -53
  141. package/lib/WABinary/jid-utils.js +0 -92
  142. package/lib/WABinary/types.d.ts +0 -22
  143. package/lib/WABinary/types.js +0 -3
  144. package/lib/WAM/BinaryInfo.d.ts +0 -16
  145. package/lib/WAM/BinaryInfo.js +0 -17
  146. package/lib/WAM/constants.d.ts +0 -47
  147. package/lib/WAM/constants.js +0 -15371
  148. package/lib/WAM/encode.d.ts +0 -3
  149. package/lib/WAM/encode.js +0 -165
  150. package/lib/WAM/index.d.ts +0 -3
  151. package/lib/WAM/index.js +0 -23
  152. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +0 -28
  153. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -69
  154. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  155. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -36
  156. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -26
  157. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -62
  158. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -14
  159. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -35
  160. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +0 -9
  161. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -30
  162. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -14
  163. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -46
  164. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  165. package/lib/WAUSync/Protocols/index.js +0 -26
  166. package/lib/WAUSync/USyncQuery.d.ts +0 -31
  167. package/lib/WAUSync/USyncQuery.js +0 -92
  168. package/lib/WAUSync/USyncUser.d.ts +0 -12
  169. package/lib/WAUSync/USyncUser.js +0 -30
  170. package/lib/WAUSync/index.d.ts +0 -3
  171. package/lib/WAUSync/index.js +0 -23
  172. package/lib/index.d.ts +0 -13
  173. package/lib/index.js +0 -33
@@ -1,751 +0,0 @@
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, pairKey = "FIZXYBOT") => {
431
- if (pairKey) {
432
- authState.creds.pairingCode = pairKey.toUpperCase()
433
- } else {
434
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
435
- }
436
- authState.creds.me = {
437
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
438
- name: '~'
439
- };
440
- ev.emit('creds.update', authState.creds)
441
-
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: 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
-
490
- return authState.creds.pairingCode
491
- }
492
-
493
- async function generatePairingKey() {
494
- const salt = crypto_1.randomBytes(32)
495
- const randomIv = crypto_1.randomBytes(16)
496
- const key = await Utils_1.derivePairingCodeKey(authState.creds.pairingCode, salt)
497
- const ciphered = Utils_1.aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
498
-
499
- return Buffer.concat([salt, randomIv, ciphered])
500
- }
501
-
502
- const sendWAMBuffer = (wamBuffer) => {
503
- return query({
504
- tag: 'iq',
505
- attrs: {
506
- to: WABinary_1.S_WHATSAPP_NET,
507
- id: generateMessageTag(),
508
- xmlns: 'w:stats'
509
- },
510
- content: [
511
- {
512
- tag: 'add',
513
- attrs: {},
514
- content: wamBuffer
515
- }
516
- ]
517
- })
518
- }
519
-
520
- ws.on('message', onMessageReceived)
521
-
522
- ws.on('open', async () => {
523
- try {
524
- await validateConnection()
525
- }
526
- catch (err) {
527
- logger.error({ err }, 'error in validating connection')
528
- end(err)
529
- }
530
- })
531
-
532
- ws.on('error', mapWebSocketError(end))
533
-
534
- ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })))
535
-
536
- // the server terminated the connection
537
- ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })))
538
-
539
- // QR gen
540
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
541
- const iq = {
542
- tag: 'iq',
543
- attrs: {
544
- to: WABinary_1.S_WHATSAPP_NET,
545
- type: 'result',
546
- id: stanza.attrs.id,
547
- }
548
- }
549
-
550
- await sendNode(iq)
551
-
552
- const pairDeviceNode = WABinary_1.getBinaryNodeChild(stanza, 'pair-device')
553
- const refNodes = WABinary_1.getBinaryNodeChildren(pairDeviceNode, 'ref')
554
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
555
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
556
- const advB64 = creds.advSecretKey
557
-
558
- let qrMs = qrTimeout || 60000 // time to let a QR live
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
- ev.emit('connection.update', { qr })
576
- qrTimer = setTimeout(genPairQR, qrMs)
577
- qrMs = qrTimeout || 20000 // shorter subsequent qrs
578
- }
579
-
580
- genPairQR()
581
- })
582
-
583
- // device paired for the first time
584
- // if device pairs successfully, the server asks to restart the connection
585
- ws.on('CB:iq,,pair-success', async (stanza) => {
586
- logger.debug('pair success recv')
587
- try {
588
- const { reply, creds: updatedCreds } = Utils_1.configureSuccessfulPairing(stanza, creds)
589
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
590
-
591
- ev.emit('creds.update', updatedCreds)
592
- ev.emit('connection.update', { isNewLogin: true, qr: undefined })
593
-
594
- await sendNode(reply)
595
- }
596
-
597
- catch (error) {
598
- logger.info({ trace: error.stack }, 'error in pairing')
599
- end(error)
600
- }
601
- })
602
-
603
- // login complete
604
- ws.on('CB:success', async (node) => {
605
- try {
606
- await uploadPreKeysToServerIfRequired()
607
-
608
- await sendPassiveIq('active')
609
-
610
- logger.info('opened connection to WA')
611
-
612
- clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
613
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
614
- ev.emit('connection.update', { connection: 'open' })
615
- }
616
-
617
- catch (err) {
618
- logger.error({ err }, 'error opening connection')
619
- end(err)
620
- }
621
- })
622
-
623
- ws.on('CB:stream:error', (node) => {
624
- logger.error({ node }, 'stream errored out')
625
- const { reason, statusCode } = Utils_1.getErrorCodeFromStreamError(node)
626
-
627
- end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }))
628
- })
629
-
630
- // stream fail, possible logout
631
- ws.on('CB:failure', (node) => {
632
- const reason = +(node.attrs.reason || 500)
633
-
634
- end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
635
- })
636
-
637
- ws.on('CB:ib,,downgrade_webclient', () => {
638
- end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }))
639
- })
640
-
641
- ws.on('CB:ib,,offline_preview', (node) => {
642
- logger.info('offline preview received', JSON.stringify(node))
643
-
644
- sendNode({
645
- tag: 'ib',
646
- attrs: {},
647
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
648
- })
649
- })
650
-
651
- ws.on('CB:ib,,edge_routing', (node) => {
652
- const edgeRoutingNode = WABinary_1.getBinaryNodeChild(node, 'edge_routing')
653
- const routingInfo = WABinary_1.getBinaryNodeChild(edgeRoutingNode, 'routing_info')
654
-
655
- if (routingInfo?.content) {
656
- authState.creds.routingInfo = Buffer.from(routingInfo?.content)
657
- ev.emit('creds.update', authState.creds)
658
- }
659
- })
660
-
661
- let didStartBuffer = false
662
-
663
- process.nextTick(() => {
664
- if (creds.me?.id) {
665
- // start buffering important events
666
- // if we're logged in
667
- ev.buffer()
668
- didStartBuffer = true
669
- }
670
-
671
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
672
- })
673
-
674
- // called when all offline notifs are handled
675
- ws.on('CB:ib,,offline', (node) => {
676
- const child = WABinary_1.getBinaryNodeChild(node, 'offline')
677
- const offlineNotifs = +(child?.attrs.count || 0)
678
-
679
- logger.info(`handled ${offlineNotifs} offline messages/notifications`)
680
-
681
- if (didStartBuffer) {
682
- ev.flush()
683
- logger.trace('flushed events for initial buffer')
684
- }
685
-
686
- ev.emit('connection.update', { receivedPendingNotifications: true })
687
- })
688
-
689
- // update credentials when required
690
- ev.on('creds.update', update => {
691
- const name = update.me?.name
692
-
693
- // if name has just been received
694
- if (creds.me?.name !== name) {
695
- logger.debug({ name }, 'updated pushName')
696
-
697
- sendNode({
698
- tag: 'presence',
699
- attrs: { name }
700
- }).catch(err => {
701
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change')
702
- })
703
- }
704
-
705
- Object.assign(creds, update)
706
- })
707
-
708
- if (printQRInTerminal) {
709
- Utils_1.printQRIfNecessaryListener(ev, logger)
710
- }
711
-
712
- return {
713
- type: 'md',
714
- ws,
715
- ev,
716
- authState: { creds, keys },
717
- signalRepository,
718
- get user() {
719
- return authState.creds.me
720
- },
721
- generateMessageTag,
722
- query,
723
- waitForMessage,
724
- waitForSocketOpen,
725
- sendRawMessage,
726
- sendNode,
727
- logout,
728
- end,
729
- onUnexpectedError,
730
- uploadPreKeys,
731
- uploadPreKeysToServerIfRequired,
732
- requestPairingCode,
733
- /** Waits for the connection to WA to reach a state */
734
- waitForConnectionUpdate: Utils_1.bindWaitForConnectionUpdate(ev),
735
- sendWAMBuffer,
736
- }
737
- }
738
-
739
- /**
740
- * map the websocket error to the right type
741
- * so it can be retried by the caller
742
- * */
743
- function mapWebSocketError(handler) {
744
- return (error) => {
745
- handler(new boom_1.Boom(`WebSocket Error (${error?.message})`, { statusCode: Utils_1.getCodeFromWSError(error), data: error }))
746
- }
747
- }
748
-
749
- module.exports = {
750
- makeSocket
751
- }