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