@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,833 @@
1
+ /**
2
+ * Core WA socket. Connects to WA servers and performs:
3
+ * - simple queries (no retry mechanism, wait for connection establishment)
4
+ * - listens to messages and emits events
5
+ * - query phone connection
6
+ *
7
+ * Combines what used to be Socket/socket.js and Socket/mex.js.
8
+ */
9
+ import { randomBytes } from 'node:crypto'
10
+ import { URL } from 'node:url'
11
+ import { promisify } from 'node:util'
12
+ import { proto } from '../../WAProto/index.js'
13
+ import { Boom } from '../foundation/boom.js'
14
+ import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../defaults.js'
15
+ import { QueryIds, ReachoutTimelockEnforcementType, DisconnectReason, XWAPaths } from '../constants.js'
16
+ import {
17
+ aesEncryptCTR,
18
+ bindWaitForConnectionUpdate,
19
+ buildPairingQRData,
20
+ bytesToCrockford,
21
+ configureSuccessfulPairing,
22
+ Curve,
23
+ derivePairingCodeKey,
24
+ generateLoginNode,
25
+ generateMdTagPrefix,
26
+ generateRegistrationNode,
27
+ getCodeFromWSError,
28
+ getCompanionPlatformId,
29
+ getErrorCodeFromStreamError,
30
+ getNextPreKeysNode,
31
+ makeNoiseHandler,
32
+ promiseTimeout,
33
+ signedKeyPair,
34
+ xmppSignedPreKey
35
+ } from '../utils/wa-protocol-core.js'
36
+ import { addTransactionCapability } from '../utils/auth-state-core.js'
37
+ import { makeEventBuffer } from '../utils/chat-sync.js'
38
+ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../binary/wa-binary.js'
39
+ import { BinaryInfo } from '../wam/wam.js'
40
+ import { USyncQuery, USyncUser } from './usync.js'
41
+ import { WebSocketClient } from '../socket-client/websocket-client.js'
42
+
43
+ /* ------------------------------------------------------------------ */
44
+ /* w:mex GraphQL-over-XMPP query helper */
45
+ /* ------------------------------------------------------------------ */
46
+
47
+ const wMexQuery = (variables, queryId, query, generateMessageTag) =>
48
+ query({
49
+ tag: 'iq',
50
+ attrs: { id: generateMessageTag(), type: 'get', to: S_WHATSAPP_NET, xmlns: 'w:mex' },
51
+ content: [{ tag: 'query', attrs: { query_id: queryId }, content: Buffer.from(JSON.stringify({ variables }), 'utf-8') }]
52
+ })
53
+
54
+ export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
55
+ const result = await wMexQuery(variables, queryId, query, generateMessageTag)
56
+ const child = getBinaryNodeChild(result, 'result')
57
+ if (child?.content) {
58
+ const data = JSON.parse(child.content.toString())
59
+ if (data.errors && data.errors.length > 0) {
60
+ const errorMessages = data.errors.map(err => err.message || 'Unknown error').join(', ')
61
+ const firstError = data.errors[0]
62
+ const errorCode = firstError.extensions?.error_code || 400
63
+ throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError })
64
+ }
65
+ const response = dataPath ? data?.data?.[dataPath] : data?.data
66
+ if (typeof response !== 'undefined') return response
67
+ }
68
+ const action = (dataPath || '').startsWith('xwa2_') ? dataPath.substring(5).replace(/_/g, ' ') : dataPath?.replace(/_/g, ' ')
69
+ throw new Boom(`Failed to ${action}, unexpected response structure.`, { statusCode: 400, data: result })
70
+ }
71
+
72
+ /* ------------------------------------------------------------------ */
73
+ /* Core socket */
74
+ /* ------------------------------------------------------------------ */
75
+
76
+ export const makeSocket = config => {
77
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config
78
+ const publicWAMBuffer = new BinaryInfo()
79
+ let serverTimeOffsetMs = 0
80
+ const uqTagId = generateMdTagPrefix()
81
+ const generateMessageTag = () => `${uqTagId}${epoch++}`
82
+
83
+ if (printQRInTerminal) {
84
+ logger.warn(
85
+ {},
86
+ '⚠️ 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.'
87
+ )
88
+ }
89
+ if (browser[1].toLocaleLowerCase().includes('android')) {
90
+ logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.')
91
+ }
92
+
93
+ const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false).length === PROCESSABLE_HISTORY_TYPES.length
94
+ if (syncDisabled) {
95
+ logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS')
96
+ }
97
+
98
+ const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl
99
+ if (config.mobile || url.protocol === 'tcp:') throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut })
100
+ if (url.protocol === 'wss' && authState?.creds?.routingInfo) url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'))
101
+
102
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
103
+ const ephemeralKeyPair = Curve.generateKeyPair()
104
+ /** WA noise protocol wrapper */
105
+ const noise = makeNoiseHandler({ keyPair: ephemeralKeyPair, NOISE_HEADER: NOISE_WA_HEADER, logger, routingInfo: authState?.creds?.routingInfo })
106
+
107
+ const ws = new WebSocketClient(url, config)
108
+ ws.connect()
109
+ const sendPromise = promisify(ws.send)
110
+
111
+ /** send a raw buffer */
112
+ const sendRawMessage = async data => {
113
+ if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
114
+ const bytes = noise.encodeFrame(data)
115
+ await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
116
+ try {
117
+ await sendPromise.call(ws, bytes)
118
+ resolve()
119
+ } catch (error) {
120
+ reject(error)
121
+ }
122
+ })
123
+ }
124
+
125
+ /** send a binary node */
126
+ const sendNode = frame => {
127
+ if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' })
128
+ const buff = encodeBinaryNode(frame)
129
+ return sendRawMessage(buff)
130
+ }
131
+
132
+ /** Wait for a message with a certain tag to be received */
133
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
134
+ let onRecv
135
+ let onErr
136
+ try {
137
+ return await promiseTimeout(timeoutMs, (resolve, reject) => {
138
+ onRecv = data => resolve(data)
139
+ onErr = err => reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }))
140
+ ws.on(`TAG:${msgId}`, onRecv)
141
+ ws.on('close', onErr)
142
+ ws.on('error', onErr)
143
+ return () => reject(new Boom('Query Cancelled'))
144
+ })
145
+ } catch (error) {
146
+ if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
147
+ logger?.warn?.({ msgId }, 'timed out waiting for message')
148
+ return undefined
149
+ }
150
+ throw error
151
+ } finally {
152
+ if (onRecv) ws.off(`TAG:${msgId}`, onRecv)
153
+ if (onErr) {
154
+ ws.off('close', onErr)
155
+ ws.off('error', onErr)
156
+ }
157
+ }
158
+ }
159
+
160
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
161
+ const query = async (node, timeoutMs) => {
162
+ if (!node.attrs.id) node.attrs.id = generateMessageTag()
163
+ const msgId = node.attrs.id
164
+ const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
165
+ const result_ = waitForMessage(msgId, timeoutMs).catch(reject)
166
+ sendNode(node)
167
+ .then(async () => resolve(await result_))
168
+ .catch(reject)
169
+ })
170
+ if (result && 'tag' in result) assertNodeErrorFree(result)
171
+ return result
172
+ }
173
+
174
+ // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
175
+ const digestKeyBundle = async () => {
176
+ const res = await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' }, content: [{ tag: 'digest', attrs: {} }] })
177
+ const digestNode = getBinaryNodeChild(res, 'digest')
178
+ if (!digestNode) {
179
+ await uploadPreKeys()
180
+ throw new Error('encrypt/get digest returned no digest node')
181
+ }
182
+ }
183
+
184
+ // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
185
+ const rotateSignedPreKey = async () => {
186
+ const newId = (creds.signedPreKey.keyId || 0) + 1
187
+ const skey = await signedKeyPair(creds.signedIdentityKey, newId)
188
+ await query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' }, content: [{ tag: 'rotate', attrs: {}, content: [xmppSignedPreKey(skey)] }] })
189
+ ev.emit('creds.update', { signedPreKey: skey })
190
+ }
191
+
192
+ const executeUSyncQuery = async usyncQuery => {
193
+ if (usyncQuery.protocols.length === 0) throw new Boom('USyncQuery must have at least one protocol')
194
+ // todo: validate users, throw WARNING on no valid users -- variable below has only validated users
195
+ const validUsers = usyncQuery.users
196
+ const userNodes = validUsers.map(user => ({
197
+ tag: 'user',
198
+ attrs: { jid: !user.phone ? user.id : undefined },
199
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
200
+ }))
201
+ const listNode = { tag: 'list', attrs: {}, content: userNodes }
202
+ const queryNode = { tag: 'query', attrs: {}, content: usyncQuery.protocols.map(a => a.getQueryElement()) }
203
+ const iq = {
204
+ tag: 'iq',
205
+ attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'usync' },
206
+ content: [{ tag: 'usync', attrs: { context: usyncQuery.context, mode: usyncQuery.mode, sid: generateMessageTag(), last: 'true', index: '0' }, content: [queryNode, listNode] }]
207
+ }
208
+ const result = await query(iq)
209
+ return usyncQuery.parseUSyncQueryResult(result)
210
+ }
211
+
212
+ const onWhatsApp = async (...phoneNumber) => {
213
+ let usyncQuery = new USyncQuery()
214
+ let contactEnabled = false
215
+ for (const jid of phoneNumber) {
216
+ if (isLidUser(jid)) {
217
+ logger?.warn('LIDs are not supported with onWhatsApp')
218
+ continue
219
+ }
220
+ if (!contactEnabled) {
221
+ contactEnabled = true
222
+ usyncQuery = usyncQuery.withContactProtocol()
223
+ }
224
+ const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`
225
+ usyncQuery.withUser(new USyncUser().withPhone(phone))
226
+ }
227
+ if (usyncQuery.users.length === 0) return [] // return early without forcing an empty query
228
+ const results = await executeUSyncQuery(usyncQuery)
229
+ if (results) return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }))
230
+ }
231
+
232
+ const pnFromLIDUSync = async jids => {
233
+ const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background')
234
+ for (const jid of jids) {
235
+ if (isLidUser(jid)) {
236
+ logger?.warn('LID user found in LID fetch call')
237
+ continue
238
+ }
239
+ usyncQuery.withUser(new USyncUser().withId(jid))
240
+ }
241
+ if (usyncQuery.users.length === 0) return []
242
+ const results = await executeUSyncQuery(usyncQuery)
243
+ return results ? results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid })) : []
244
+ }
245
+
246
+ const ev = makeEventBuffer(logger)
247
+ const { creds } = authState
248
+ // add transaction capability
249
+ const keys = addTransactionCapability(authState.keys, logger, transactionOpts)
250
+ const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync)
251
+ let lastDateRecv
252
+ let epoch = 1
253
+ let keepAliveReq
254
+ let qrTimer
255
+ let closed = false
256
+ const socketEndHandlers = []
257
+
258
+ /** log & process any unexpected errors */
259
+ const onUnexpectedError = (err, msg) => {
260
+ logger.error({ err }, `unexpected error in '${msg}'`)
261
+ }
262
+
263
+ /** await the next incoming message */
264
+ const awaitNextMessage = async sendMsg => {
265
+ if (!ws.isOpen) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
266
+ let onOpen
267
+ let onClose
268
+ const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
269
+ onOpen = resolve
270
+ onClose = mapWebSocketError(reject)
271
+ ws.on('frame', onOpen)
272
+ ws.on('close', onClose)
273
+ ws.on('error', onClose)
274
+ }).finally(() => {
275
+ ws.off('frame', onOpen)
276
+ ws.off('close', onClose)
277
+ ws.off('error', onClose)
278
+ })
279
+ if (sendMsg) sendRawMessage(sendMsg).catch(onClose)
280
+ return result
281
+ }
282
+
283
+ /** connection handshake */
284
+ const validateConnection = async () => {
285
+ let helloMsg = { clientHello: { ephemeral: ephemeralKeyPair.public } }
286
+ helloMsg = proto.HandshakeMessage.fromObject(helloMsg)
287
+ logger.info({ browser, helloMsg }, 'connected to WA')
288
+ const init = proto.HandshakeMessage.encode(helloMsg).finish()
289
+ const result = await awaitNextMessage(init)
290
+ const handshake = proto.HandshakeMessage.decode(result)
291
+ logger.trace({ handshake }, 'handshake recv from WA')
292
+ const keyEnc = noise.processHandshake(handshake, creds.noiseKey)
293
+ let node
294
+ if (!creds.me) {
295
+ node = generateRegistrationNode(creds, config)
296
+ logger.info({ node }, 'not logged in, attempting registration...')
297
+ } else {
298
+ node = generateLoginNode(creds.me.id, config)
299
+ logger.info({ node }, 'logging in...')
300
+ }
301
+ const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish())
302
+ await sendRawMessage(proto.HandshakeMessage.encode({ clientFinish: { static: keyEnc, payload: payloadEnc } }).finish())
303
+ await noise.finishInit()
304
+ startKeepAliveRequest()
305
+ }
306
+
307
+ const getAvailablePreKeysOnServer = async () => {
308
+ const result = await query({ tag: 'iq', attrs: { id: generateMessageTag(), xmlns: 'encrypt', type: 'get', to: S_WHATSAPP_NET }, content: [{ tag: 'count', attrs: {} }] })
309
+ const countChild = getBinaryNodeChild(result, 'count')
310
+ return +countChild.attrs.value
311
+ }
312
+
313
+ // WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
314
+ let uploadPreKeysPromise = null
315
+ /** generates and uploads a set of pre-keys to the server */
316
+ const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
317
+ if (uploadPreKeysPromise) {
318
+ logger.debug('Pre-key upload already in progress, waiting for completion')
319
+ await uploadPreKeysPromise
320
+ return
321
+ }
322
+ const uploadLogic = async retryCount => {
323
+ logger.info({ count, retryCount }, 'uploading pre-keys')
324
+ // Generate and save pre-keys atomically (prevents ID collisions on retry)
325
+ const node = await keys.transaction(async () => {
326
+ logger.debug({ requestedCount: count }, 'generating pre-keys with requested count')
327
+ const { update, node: node_ } = await getNextPreKeysNode({ creds, keys }, count)
328
+ ev.emit('creds.update', update) // update credentials immediately to prevent duplicate IDs on retry
329
+ return node_
330
+ }, creds?.me?.id || 'upload-pre-keys')
331
+ try {
332
+ await query(node)
333
+ logger.info({ count }, 'uploaded pre-keys successfully')
334
+ } catch (uploadError) {
335
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server')
336
+ if (retryCount < 3) {
337
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000)
338
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`)
339
+ await new Promise(resolve => setTimeout(resolve, backoffDelay))
340
+ return uploadLogic(retryCount + 1)
341
+ }
342
+ throw uploadError
343
+ }
344
+ }
345
+ uploadPreKeysPromise = Promise.race([
346
+ uploadLogic(0),
347
+ new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
348
+ ])
349
+ try {
350
+ await uploadPreKeysPromise
351
+ } finally {
352
+ uploadPreKeysPromise = null
353
+ }
354
+ }
355
+
356
+ const verifyCurrentPreKeyExists = async () => {
357
+ const currentPreKeyId = creds.nextPreKeyId - 1
358
+ if (currentPreKeyId <= 0) return { exists: false, currentPreKeyId: 0 }
359
+ const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()])
360
+ return { exists: !!preKeys[currentPreKeyId.toString()], currentPreKeyId }
361
+ }
362
+
363
+ const uploadPreKeysToServerIfRequired = async () => {
364
+ try {
365
+ let count = 0
366
+ const preKeyCount = await getAvailablePreKeysOnServer()
367
+ count = preKeyCount === 0 ? INITIAL_PREKEY_COUNT : MIN_PREKEY_COUNT
368
+ const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists()
369
+ logger.info(`${preKeyCount} pre-keys found on server`)
370
+ logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`)
371
+ const lowServerCount = preKeyCount <= count
372
+ const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0
373
+ const shouldUpload = lowServerCount || missingCurrentPreKey
374
+ if (shouldUpload) {
375
+ const reasons = []
376
+ if (lowServerCount) reasons.push(`server count low (${preKeyCount})`)
377
+ if (missingCurrentPreKey) reasons.push(`current prekey ${currentPreKeyId} missing from storage`)
378
+ logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`)
379
+ await uploadPreKeys(count)
380
+ } else {
381
+ logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`)
382
+ }
383
+ } catch (error) {
384
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization')
385
+ // Don't throw - allow connection to continue even if pre-key check fails
386
+ }
387
+ }
388
+
389
+ const onMessageReceived = async data => {
390
+ await noise.decodeFrame(data, frame => {
391
+ lastDateRecv = new Date() // reset ping timeout
392
+ let anyTriggered = false
393
+ anyTriggered = ws.emit('frame', frame)
394
+ if (!(frame instanceof Uint8Array)) {
395
+ const msgId = frame.attrs.id
396
+ if (logger.level === 'trace') logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' })
397
+ anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered // response to a message we sent
398
+ const l0 = frame.tag
399
+ const l1 = frame.attrs || {}
400
+ const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : ''
401
+ for (const key of Object.keys(l1)) {
402
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered
403
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered
404
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered
405
+ }
406
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered
407
+ anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered
408
+ if (!anyTriggered && logger.level === 'debug') logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv')
409
+ }
410
+ })
411
+ }
412
+
413
+ const end = async error => {
414
+ if (closed) {
415
+ logger.trace({ trace: error?.stack }, 'connection already closed')
416
+ return
417
+ }
418
+ closed = true
419
+ logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed')
420
+ clearInterval(keepAliveReq)
421
+ clearTimeout(qrTimer)
422
+ // Reset keepalive failure state so a stale counter can't carry over if the
423
+ // socket object is somehow reused.
424
+ consecutivePingFailures = 0
425
+ // Remove ALL listeners registered on the websocket, not just close/open/message.
426
+ // The CB:/TAG: prefixed listeners registered by messages-recv.js & co. hold
427
+ // closures over the entire socket scope; leaving them attached prevents GC of
428
+ // the old connection's state and can let handlers fire on stale data if a
429
+ // close/reconnect race occurs.
430
+ ws.removeAllListeners()
431
+ // Release noise handler internal state (encryption buffers, transport state,
432
+ // pending frame callbacks) so it can be garbage collected.
433
+ noise.destroy?.()
434
+ signalRepository.close?.()
435
+ if (!ws.isClosed && !ws.isClosing) {
436
+ try {
437
+ // Guard against a stuck TCP socket hanging teardown forever.
438
+ await Promise.race([ws.close(), new Promise(resolve => setTimeout(resolve, 5000))])
439
+ } catch {
440
+ // ignore
441
+ }
442
+ }
443
+ for (const handler of socketEndHandlers) {
444
+ try {
445
+ await handler(error)
446
+ } catch (err) {
447
+ logger.error({ err }, 'error in socket end handler')
448
+ }
449
+ }
450
+ ev.emit('connection.update', { connection: 'close', lastDisconnect: { error, date: new Date() } })
451
+ ev.removeAllListeners('connection.update')
452
+ ev.destroy()
453
+ }
454
+
455
+ const waitForSocketOpen = async () => {
456
+ if (ws.isOpen) return
457
+ if (ws.isClosed || ws.isClosing) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed })
458
+ let onOpen
459
+ let onClose
460
+ await new Promise((resolve, reject) => {
461
+ onOpen = () => resolve(undefined)
462
+ onClose = mapWebSocketError(reject)
463
+ ws.on('open', onOpen)
464
+ ws.on('close', onClose)
465
+ ws.on('error', onClose)
466
+ }).finally(() => {
467
+ ws.off('open', onOpen)
468
+ ws.off('close', onClose)
469
+ ws.off('error', onClose)
470
+ })
471
+ }
472
+
473
+ // A keepalive ping that times out or errors is direct evidence the socket is dead (or the
474
+ // network is down) -- the previous implementation only logged that failure and kept waiting
475
+ // for `lastDateRecv` to go stale by ANOTHER full interval before declaring the connection
476
+ // lost, so a single failed ping could take up to ~2x keepAliveIntervalMs to surface as a
477
+ // disconnect. This mirrors the fix used by more actively-maintained Baileys forks: react to
478
+ // ping failure immediately instead of waiting for a second, independent staleness check.
479
+ let keepAliveInFlight = false
480
+ // CONNECTION STABILITY: a single failed/timed-out ping can be a transient blip
481
+ // (a slow server response, a brief network hiccup) rather than proof the socket
482
+ // is dead. Requiring a few consecutive failures before tearing down the
483
+ // connection avoids reconnect churn from those blips, while the hard staleness
484
+ // check below (diff > 2x interval) still catches a truly dead connection quickly
485
+ // even if pings themselves never fail outright (e.g. event loop stalls).
486
+ let consecutivePingFailures = 0
487
+ const MAX_PING_FAILURES = 3
488
+ const startKeepAliveRequest = () =>
489
+ (keepAliveReq = setInterval(() => {
490
+ if (!lastDateRecv) lastDateRecv = new Date()
491
+ const diff = Date.now() - lastDateRecv.getTime()
492
+ // Hard timeout: if it's been over twice the keepalive interval since we last
493
+ // heard from the server, the connection is almost certainly dead -- don't
494
+ // wait on further ping failures to confirm it.
495
+ if (diff > keepAliveIntervalMs * 2 + 5000) {
496
+ logger.warn({ diff, keepAliveIntervalMs }, 'connection silent for too long')
497
+ void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }))
498
+ return
499
+ }
500
+ if (!ws.isOpen) {
501
+ logger.warn('keep alive called when WS not open')
502
+ return
503
+ }
504
+ if (keepAliveInFlight) {
505
+ logger.trace('keep alive skipped: ping already in flight')
506
+ return
507
+ }
508
+ // skip this tick if the server already proved the connection is alive recently --
509
+ // but only up to half the interval, so a socket that's merely "somewhat recent" still
510
+ // gets pinged well before it could go stale enough to trip the check above.
511
+ if (diff < keepAliveIntervalMs / 2) {
512
+ logger.trace('keep alive skipped: recent inbound activity', { diff })
513
+ return
514
+ }
515
+ keepAliveInFlight = true
516
+ query({ tag: 'iq', attrs: { id: generateMessageTag(), to: S_WHATSAPP_NET, type: 'get', xmlns: 'w:p' }, content: [{ tag: 'ping', attrs: {} }] }, keepAliveIntervalMs)
517
+ .then(() => {
518
+ // Ping succeeded -- reset the failure counter.
519
+ consecutivePingFailures = 0
520
+ })
521
+ .catch(err => {
522
+ consecutivePingFailures++
523
+ logger.warn({ trace: err.stack, consecutivePingFailures, maxFailures: MAX_PING_FAILURES }, 'keep alive ping failed')
524
+ if (consecutivePingFailures >= MAX_PING_FAILURES) {
525
+ logger.warn('max ping failures reached, closing connection')
526
+ void end(new Boom('Connection was lost (ping failures)', { statusCode: DisconnectReason.connectionLost, data: { cause: err } }))
527
+ }
528
+ })
529
+ .finally(() => {
530
+ keepAliveInFlight = false
531
+ })
532
+ }, keepAliveIntervalMs))
533
+
534
+ /** i have no idea why this exists. pls enlighten me */
535
+ const sendPassiveIq = tag => query({ tag: 'iq', attrs: { to: S_WHATSAPP_NET, xmlns: 'passive', type: 'set' }, content: [{ tag, attrs: {} }] })
536
+
537
+ /** logout & invalidate connection */
538
+ const logout = async msg => {
539
+ const jid = authState.creds.me?.id
540
+ if (jid) {
541
+ await sendNode({
542
+ tag: 'iq',
543
+ attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
544
+ content: [{ tag: 'remove-companion-device', attrs: { jid, reason: 'user_initiated' } }]
545
+ })
546
+ }
547
+ void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }))
548
+ }
549
+
550
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
551
+ const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5))
552
+ if (customPairingCode && customPairingCode?.length !== 8) throw new Error('Custom pairing code must be exactly 8 chars')
553
+ authState.creds.pairingCode = pairingCode
554
+ authState.creds.me = { id: jidEncode(phoneNumber, 's.whatsapp.net'), name: '~' }
555
+ ev.emit('creds.update', authState.creds)
556
+ await sendNode({
557
+ tag: 'iq',
558
+ attrs: { to: S_WHATSAPP_NET, type: 'set', id: generateMessageTag(), xmlns: 'md' },
559
+ content: [
560
+ {
561
+ tag: 'link_code_companion_reg',
562
+ attrs: { jid: authState.creds.me.id, stage: 'companion_hello', should_show_push_notification: 'true' },
563
+ content: [
564
+ { tag: 'link_code_pairing_wrapped_companion_ephemeral_pub', attrs: {}, content: await generatePairingKey() },
565
+ { tag: 'companion_server_auth_key_pub', attrs: {}, content: authState.creds.noiseKey.public },
566
+ { tag: 'companion_platform_id', attrs: {}, content: getCompanionPlatformId(browser) },
567
+ { tag: 'companion_platform_display', attrs: {}, content: `${browser[1]} (${browser[0]})` },
568
+ { tag: 'link_code_pairing_nonce', attrs: {}, content: '0' }
569
+ ]
570
+ }
571
+ ]
572
+ })
573
+ return authState.creds.pairingCode
574
+ }
575
+
576
+ async function generatePairingKey() {
577
+ const salt = randomBytes(32)
578
+ const randomIv = randomBytes(16)
579
+ const key = await derivePairingCodeKey(authState.creds.pairingCode, salt)
580
+ const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv)
581
+ return Buffer.concat([salt, randomIv, ciphered])
582
+ }
583
+
584
+ const sendWAMBuffer = wamBuffer =>
585
+ query({
586
+ tag: 'iq',
587
+ attrs: { to: S_WHATSAPP_NET, id: generateMessageTag(), xmlns: 'w:stats' },
588
+ content: [{ tag: 'add', attrs: { t: Math.round(Date.now() / 1000) + '' }, content: wamBuffer }]
589
+ })
590
+
591
+ ws.on('message', onMessageReceived)
592
+ ws.on('open', async () => {
593
+ try {
594
+ await validateConnection()
595
+ } catch (err) {
596
+ logger.error({ err }, 'error in validating connection')
597
+ void end(err)
598
+ }
599
+ })
600
+ ws.on('error', mapWebSocketError(end))
601
+ ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })))
602
+ // the server terminated the connection
603
+ ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })))
604
+ // QR gen
605
+ ws.on('CB:iq,type:set,pair-device', async stanza => {
606
+ const iq = { tag: 'iq', attrs: { to: S_WHATSAPP_NET, type: 'result', id: stanza.attrs.id } }
607
+ await sendNode(iq)
608
+ const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device')
609
+ const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref')
610
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64')
611
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64')
612
+ const advB64 = creds.advSecretKey
613
+ let qrMs = qrTimeout || 60000 // time to let a QR live
614
+ const genPairQR = () => {
615
+ if (!ws.isOpen) return
616
+ const refNode = refNodes.shift()
617
+ if (!refNode) {
618
+ void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }))
619
+ return
620
+ }
621
+ const ref = refNode.content.toString('utf-8')
622
+ const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser)
623
+ ev.emit('connection.update', { qr })
624
+ qrTimer = setTimeout(genPairQR, qrMs)
625
+ qrMs = qrTimeout || 20000 // shorter subsequent qrs
626
+ }
627
+ genPairQR()
628
+ })
629
+ // device paired for the first time; server asks to restart the connection
630
+ ws.on('CB:iq,,pair-success', async stanza => {
631
+ logger.debug('pair success recv')
632
+ try {
633
+ updateServerTimeOffset(stanza)
634
+ const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds)
635
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...')
636
+ ev.emit('creds.update', updatedCreds)
637
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined })
638
+ await sendNode(reply)
639
+ void sendUnifiedSession()
640
+ } catch (error) {
641
+ logger.info({ trace: error.stack }, 'error in pairing')
642
+ void end(error)
643
+ }
644
+ })
645
+ // login complete
646
+ ws.on('CB:success', async node => {
647
+ try {
648
+ updateServerTimeOffset(node)
649
+ await uploadPreKeysToServerIfRequired()
650
+ await sendPassiveIq('active')
651
+ try {
652
+ await digestKeyBundle() // validate our key-bundle against server
653
+ } catch (e) {
654
+ logger.warn({ e }, 'failed to run digest after login')
655
+ }
656
+ } catch (err) {
657
+ logger.warn({ err }, 'failed to send initial passive iq')
658
+ }
659
+ logger.info('opened connection to WA')
660
+ clearTimeout(qrTimer) // will never happen in all likelyhood -- but just in case WA sends success on first try
661
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } })
662
+ ev.emit('connection.update', { connection: 'open' })
663
+ void sendUnifiedSession()
664
+ if (node.attrs.lid && authState.creds.me?.id) {
665
+ const myLID = node.attrs.lid
666
+ process.nextTick(async () => {
667
+ try {
668
+ const myPN = authState.creds.me.id
669
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }])
670
+ const { user, device } = jidDecode(myPN)
671
+ await authState.keys.set({ 'device-list': { [user]: [device?.toString() || '0'] } })
672
+ await signalRepository.migrateSession(myPN, myLID)
673
+ logger.info({ myPN, myLID }, 'Own LID session created successfully')
674
+ } catch (error) {
675
+ logger.error({ error, lid: myLID }, 'Failed to create own LID session')
676
+ }
677
+ })
678
+ }
679
+ })
680
+ ws.on('CB:stream:error', node => {
681
+ const [reasonNode] = getAllBinaryNodeChildren(node)
682
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out')
683
+ const { reason, statusCode } = getErrorCodeFromStreamError(node)
684
+ void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }))
685
+ })
686
+ // stream fail, possible logout
687
+ ws.on('CB:failure', node => {
688
+ const reason = +(node.attrs.reason || 500)
689
+ void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }))
690
+ })
691
+ ws.on('CB:ib,,downgrade_webclient', () => {
692
+ void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }))
693
+ })
694
+ ws.on('CB:ib,,offline_preview', async node => {
695
+ logger.info('offline preview received', JSON.stringify(node))
696
+ await sendNode({ tag: 'ib', attrs: {}, content: [{ tag: 'offline_batch', attrs: { count: '100' } }] })
697
+ })
698
+ ws.on('CB:ib,,edge_routing', node => {
699
+ const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing')
700
+ const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info')
701
+ if (routingInfo?.content) {
702
+ authState.creds.routingInfo = Buffer.from(routingInfo?.content)
703
+ ev.emit('creds.update', authState.creds)
704
+ }
705
+ })
706
+
707
+ let didStartBuffer = false
708
+ process.nextTick(() => {
709
+ if (creds.me?.id) {
710
+ ev.buffer() // start buffering important events if we're logged in
711
+ didStartBuffer = true
712
+ }
713
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined })
714
+ })
715
+ // called when all offline notifs are handled
716
+ ws.on('CB:ib,,offline', node => {
717
+ const child = getBinaryNodeChild(node, 'offline')
718
+ const offlineNotifs = +(child?.attrs.count || 0)
719
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`)
720
+ if (didStartBuffer) {
721
+ ev.flush()
722
+ logger.trace('flushed events for initial buffer')
723
+ }
724
+ ev.emit('connection.update', { receivedPendingNotifications: true })
725
+ })
726
+ // update credentials when required
727
+ ev.on('creds.update', update => {
728
+ const name = update.me?.name
729
+ if (creds.me?.name !== name) {
730
+ logger.debug({ name }, 'updated pushName')
731
+ sendNode({ tag: 'presence', attrs: { name } }).catch(err => logger.warn({ trace: err.stack }, 'error in sending presence update on name change'))
732
+ }
733
+ Object.assign(creds, update)
734
+ })
735
+
736
+ const updateServerTimeOffset = ({ attrs }) => {
737
+ const tValue = attrs?.t
738
+ if (!tValue) return
739
+ const parsed = Number(tValue)
740
+ if (Number.isNaN(parsed) || parsed <= 0) return
741
+ const localMs = Date.now()
742
+ serverTimeOffsetMs = parsed * 1000 - localMs
743
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset')
744
+ }
745
+ const getUnifiedSessionId = () => {
746
+ const offsetMs = 3 * TimeMs.Day
747
+ const now = Date.now() + serverTimeOffsetMs
748
+ return ((now + offsetMs) % TimeMs.Week).toString()
749
+ }
750
+ const sendUnifiedSession = async () => {
751
+ if (!ws.isOpen) return
752
+ const node = { tag: 'ib', attrs: {}, content: [{ tag: 'unified_session', attrs: { id: getUnifiedSessionId() } }] }
753
+ try {
754
+ await sendNode(node)
755
+ } catch (error) {
756
+ logger.debug({ error }, 'failed to send unified_session telemetry')
757
+ }
758
+ }
759
+
760
+ const registerSocketEndHandler = handler => {
761
+ socketEndHandlers.push(handler)
762
+ }
763
+
764
+ /** Fetches your account's standing when it comes to restrictions. */
765
+ const fetchAccountReachoutTimelock = async () => {
766
+ const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag)
767
+ const result = {
768
+ isActive: !!queryResult?.is_active,
769
+ timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0' ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000) : undefined,
770
+ enforcementType: queryResult?.enforcement_type ?? ReachoutTimelockEnforcementType.DEFAULT
771
+ }
772
+ ev.emit('connection.update', { reachoutTimeLock: result })
773
+ return result
774
+ }
775
+
776
+ /** Fetches your account's new chat limits. Returns the quota and the usage. */
777
+ const fetchNewChatMessageCap = async () => executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag)
778
+
779
+ return {
780
+ type: 'md',
781
+ ws,
782
+ ev,
783
+ authState: { creds, keys },
784
+ signalRepository,
785
+ get user() {
786
+ return authState.creds.me
787
+ },
788
+ /**
789
+ * Connection health metrics so consumers can implement their own health
790
+ * checks or monitoring.
791
+ * - lastMessageReceived: timestamp of last data received from the server
792
+ * - consecutivePingFailures: how many keepalive pings have failed in a row
793
+ */
794
+ get connectionHealth() {
795
+ return {
796
+ lastMessageReceived: lastDateRecv,
797
+ consecutivePingFailures
798
+ }
799
+ },
800
+ generateMessageTag,
801
+ query,
802
+ waitForMessage,
803
+ waitForSocketOpen,
804
+ sendRawMessage,
805
+ sendNode,
806
+ logout,
807
+ end,
808
+ registerSocketEndHandler,
809
+ onUnexpectedError,
810
+ uploadPreKeys,
811
+ uploadPreKeysToServerIfRequired,
812
+ digestKeyBundle,
813
+ rotateSignedPreKey,
814
+ requestPairingCode,
815
+ updateServerTimeOffset,
816
+ sendUnifiedSession,
817
+ wamBuffer: publicWAMBuffer,
818
+ /** Waits for the connection to WA to reach a state */
819
+ waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
820
+ sendWAMBuffer,
821
+ executeUSyncQuery,
822
+ onWhatsApp,
823
+ fetchAccountReachoutTimelock,
824
+ fetchNewChatMessageCap
825
+ }
826
+ }
827
+
828
+ /** map the websocket error to the right type so it can be retried by the caller */
829
+ function mapWebSocketError(handler) {
830
+ return error => {
831
+ handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }))
832
+ }
833
+ }