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