sanka-baileyss 1.9.6 → 1.9.8

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