@aunucore/baileys 1.0.76 → 1.0.77

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.
@@ -334,12 +334,23 @@ export const makeMessagesSocket = (config) => {
334
334
  // the transport to reopen, bounded by connectTimeoutMs; a connection
335
335
  // that closes for good still fails fast via waitForSocketOpen itself.
336
336
  const waitMs = config.connectTimeoutMs ?? 60000;
337
- await Promise.race([
338
- waitForSocketOpen(),
339
- delay(waitMs).then(() => {
340
- throw new Boom(`Timed out waiting ${waitMs}ms for the connection to open before sending`, { statusCode: 408 }); // 408 = DisconnectReason.timedOut
341
- })
342
- ]);
337
+ const openWait = waitForSocketOpen();
338
+ try {
339
+ await Promise.race([
340
+ openWait,
341
+ delay(waitMs).then(() => {
342
+ throw new Boom(`Timed out waiting ${waitMs}ms for the connection to open before sending`, { statusCode: 408 }); // 408 = DisconnectReason.timedOut
343
+ })
344
+ ]);
345
+ }
346
+ catch (err) {
347
+ // AunuBaileys (1.0.77, HB-167): when the timeout wins,
348
+ // the socket-open waiter is still pending — detach its
349
+ // ws listeners now instead of leaving three behind per
350
+ // failed send until the socket settles on its own.
351
+ openWait.cancel?.();
352
+ throw err;
353
+ }
343
354
  }
344
355
  // AunuBaileys (1.0.68): fail with a clear Boom instead of a raw
345
356
  // TypeError when sending before pairing completes or with a
@@ -92,6 +92,15 @@ export const makeSocket = (config) => {
92
92
  let epoch = 1;
93
93
  let keepAliveReq;
94
94
  let qrTimer;
95
+ // AunuBaileys (1.0.77, HB-243): true while a pair-device QR chain
96
+ // is cycling — a duplicate pair-device IQ must not start a second
97
+ // chain on the shared qrTimer slot.
98
+ let qrChainActive = false;
99
+ // AunuBaileys (1.0.77, HB-213): resolved when the Noise handshake
100
+ // completes (finishInit in validateConnection), so the pairing
101
+ // request can wait for an encrypted channel.
102
+ let resolveHandshakeComplete;
103
+ const handshakeComplete = new Promise((resolve) => { resolveHandshakeComplete = resolve; });
95
104
  let closed = false;
96
105
  let lastDisconnectError;
97
106
  const uqTagId = generateMdTagPrefix();
@@ -226,6 +235,7 @@ export const makeSocket = (config) => {
226
235
  }
227
236
  }).finish());
228
237
  noise.finishInit();
238
+ resolveHandshakeComplete?.();
229
239
  startKeepAliveRequest();
230
240
  };
231
241
  const getAvailablePreKeysOnServer = async () => {
@@ -278,12 +288,17 @@ export const makeSocket = (config) => {
278
288
  await uploadPreKeys();
279
289
  }
280
290
  };
291
+ // AunuBaileys (1.0.77, HB-156): decodeFrame invocations must never
292
+ // overlap — the noise handler slices ONE shared inBytes buffer, so
293
+ // two concurrent calls interleave and deliver stanzas out of wire
294
+ // order. Every WS message is chained through a single queue.
295
+ let frameDecodeChain = Promise.resolve();
281
296
  const onMessageReceived = (data) => {
282
297
  // AunuBaileys (1.0.67): decodeFrame is async — a malformed frame
283
298
  // (bad GCM tag, truncated binary node) or a throwing frame
284
299
  // listener must not become an unhandled rejection that kills
285
300
  // the process; route failures to onUnexpectedError instead.
286
- Promise.resolve(noise.decodeFrame(data, frame => {
301
+ frameDecodeChain = frameDecodeChain.then(() => noise.decodeFrame(data, frame => {
287
302
  // reset ping timeout
288
303
  lastDateRecv = new Date();
289
304
  let anyTriggered = false;
@@ -311,7 +326,20 @@ export const makeSocket = (config) => {
311
326
  logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
312
327
  }
313
328
  }
314
- })).catch(err => onUnexpectedError(err, 'onMessageReceived'));
329
+ })).catch(err => {
330
+ // AunuBaileys (1.0.77, HB-185/HB-207): a frame-layer failure
331
+ // (oversize header, GCM decrypt failure) leaves the noise
332
+ // stream unrecoverable — the header is never consumed, or
333
+ // the read counter desyncs so every later frame fails too.
334
+ // End the connection so the host reconnects at once instead
335
+ // of wedging until the keep-alive watchdog notices (~65s).
336
+ if (err?.isFrameFatal) {
337
+ end(err);
338
+ }
339
+ else {
340
+ onUnexpectedError(err, 'onMessageReceived');
341
+ }
342
+ });
315
343
  };
316
344
  // AunuBaileys: socket end handlers (pola v7) + fetch Mex (dari @itsliaaa/baileys)
317
345
  const socketEndHandlers = [];
@@ -329,6 +357,7 @@ export const makeSocket = (config) => {
329
357
  logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
330
358
  clearInterval(keepAliveReq);
331
359
  clearTimeout(qrTimer);
360
+ qrChainActive = false;
332
361
  ws.removeAllListeners('close');
333
362
  ws.removeAllListeners('open');
334
363
  ws.removeAllListeners('message');
@@ -354,16 +383,20 @@ export const makeSocket = (config) => {
354
383
  ev.removeAllListeners('connection.update');
355
384
  ev.destroy?.();
356
385
  };
357
- const waitForSocketOpen = async () => {
386
+ const waitForSocketOpen = () => {
358
387
  if (ws.isOpen) {
359
- return;
388
+ const resolved = Promise.resolve();
389
+ resolved.cancel = () => { };
390
+ return resolved;
360
391
  }
361
392
  if (ws.isClosed || ws.isClosing) {
362
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
393
+ const rejected = Promise.reject(new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
394
+ rejected.cancel = () => { };
395
+ return rejected;
363
396
  }
364
397
  let onOpen;
365
398
  let onClose;
366
- await new Promise((resolve, reject) => {
399
+ const promise = new Promise((resolve, reject) => {
367
400
  onOpen = () => resolve(undefined);
368
401
  onClose = mapWebSocketError(reject);
369
402
  ws.on('open', onOpen);
@@ -374,6 +407,16 @@ export const makeSocket = (config) => {
374
407
  ws.off('close', onClose);
375
408
  ws.off('error', onClose);
376
409
  });
410
+ // AunuBaileys (1.0.77, HB-167/HB-179): a caller that stops
411
+ // waiting (its own timeout won the race) can detach these
412
+ // listeners immediately instead of leaving them on the ws
413
+ // emitter until the socket happens to open/close/error.
414
+ promise.cancel = () => {
415
+ ws.off('open', onOpen);
416
+ ws.off('close', onClose);
417
+ ws.off('error', onClose);
418
+ };
419
+ return promise;
377
420
  };
378
421
  const keepAliveTick = () => {
379
422
  if (!lastDateRecv) {
@@ -501,15 +544,55 @@ export const makeSocket = (config) => {
501
544
  reject(new Boom(`requestPairingCode: socket did not open within ${PAIRING_READY_TIMEOUT_MS / 1000}s (last disconnect: ${describeLastDisconnect()})`, { statusCode: DisconnectReason.timedOut }));
502
545
  }, PAIRING_READY_TIMEOUT_MS);
503
546
  });
547
+ const rawOpenWait = waitForSocketOpen();
504
548
  try {
505
549
  await Promise.race([
506
- waitForSocketOpen().catch(() => {
550
+ rawOpenWait.catch(() => {
507
551
  throw new Boom(`requestPairingCode: connection closed while waiting for the socket to open (last disconnect: ${describeLastDisconnect()})`, { statusCode: DisconnectReason.connectionClosed });
508
552
  }),
509
553
  closedWhileWaiting,
510
554
  timedOut
511
555
  ]);
512
556
  }
557
+ finally {
558
+ clearTimeout(timer);
559
+ // AunuBaileys (1.0.77, HB-179): if the timeout or the close
560
+ // guard won the race, the socket-open waiter is still
561
+ // pending — detach its ws listeners now instead of leaving
562
+ // them behind until the socket settles on its own.
563
+ rawOpenWait.cancel?.();
564
+ if (onUpdate) {
565
+ try {
566
+ ev.off('connection.update', onUpdate);
567
+ }
568
+ catch { }
569
+ }
570
+ }
571
+ };
572
+ // AunuBaileys (1.0.77, HB-213): the pairing IQ must not leave
573
+ // before the Noise handshake completes — encodeFrame encrypts
574
+ // only once the handshake is finished, so an early IQ travels as
575
+ // a plaintext binary node; a strict server kills the connection
576
+ // over it while requestPairingCode still resolves with the code.
577
+ const waitForHandshakeComplete = async () => {
578
+ let onUpdate;
579
+ const closedWhileWaiting = new Promise((_, reject) => {
580
+ onUpdate = (update) => {
581
+ if (update.connection === 'close') {
582
+ reject(new Boom(`requestPairingCode: connection closed while waiting for the handshake to complete (last disconnect: ${describeLastDisconnect()})`, { statusCode: DisconnectReason.connectionClosed }));
583
+ }
584
+ };
585
+ ev.on('connection.update', onUpdate);
586
+ });
587
+ let timer;
588
+ const timedOut = new Promise((_, reject) => {
589
+ timer = setTimeout(() => {
590
+ reject(new Boom(`requestPairingCode: handshake did not complete within ${PAIRING_READY_TIMEOUT_MS / 1000}s (last disconnect: ${describeLastDisconnect()})`, { statusCode: DisconnectReason.timedOut }));
591
+ }, PAIRING_READY_TIMEOUT_MS);
592
+ });
593
+ try {
594
+ await Promise.race([handshakeComplete, closedWhileWaiting, timedOut]);
595
+ }
513
596
  finally {
514
597
  clearTimeout(timer);
515
598
  if (onUpdate) {
@@ -534,13 +617,20 @@ export const makeSocket = (config) => {
534
617
  pairingCodeRequestInFlight = true;
535
618
  try {
536
619
  await waitForPairingReady();
620
+ await waitForHandshakeComplete();
537
621
  authState.creds.pairingCode = pairingCode;
538
622
  authState.creds.me = {
539
623
  id: jidEncode(phoneNumber, 's.whatsapp.net'),
540
624
  name: '~'
541
625
  };
542
626
  ev.emit('creds.update', authState.creds);
543
- await sendNode({
627
+ // AunuBaileys (1.0.77, HB-191): query(), not sendNode() — the
628
+ // companion_hello result must be awaited and error-checked.
629
+ // sendNode resolved when the bytes hit the wire, so a server
630
+ // rejection left the optimistic creds.me/pairingCode persisted
631
+ // and sent the next boot into a 401 loop; a rejection now
632
+ // lands in the catch below, which rolls the creds back.
633
+ await query({
544
634
  tag: 'iq',
545
635
  attrs: {
546
636
  to: S_WHATSAPP_NET,
@@ -644,6 +734,16 @@ export const makeSocket = (config) => {
644
734
  }
645
735
  });
646
736
  ws.on('error', mapWebSocketError(end));
737
+ // AunuBaileys (1.0.77, HB-189): the ws client forwards
738
+ // 'unexpected-response', which suppresses ws's own handshake
739
+ // abort — without a listener here a non-101 response (403/502,
740
+ // ISP intercept page) wedges the socket in 'connecting' forever:
741
+ // no open, no error, no close, and the host never reconnects.
742
+ ws.on('unexpected-response', (_req, res) => {
743
+ const code = res?.statusCode;
744
+ const statusCode = Number.isFinite(code) && code >= 400 && code <= 599 ? code : 500;
745
+ end(new Boom(`Unexpected server response: ${code}`, { statusCode }));
746
+ });
647
747
  ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
648
748
  // the server terminated the connection
649
749
  ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
@@ -662,6 +762,16 @@ export const makeSocket = (config) => {
662
762
  }
663
763
  };
664
764
  await sendNode(iq);
765
+ // AunuBaileys (1.0.77, HB-243): a duplicate pair-device IQ
766
+ // (server retry) must not start a parallel QR chain — both
767
+ // chains share the single qrTimer slot, so the orphaned first
768
+ // chain keeps cycling after login and its ref exhaustion ends
769
+ // the healthy, freshly logged-in connection.
770
+ if (qrChainActive) {
771
+ logger.warn('ignoring duplicate pair-device IQ: a QR chain is already running');
772
+ return;
773
+ }
774
+ qrChainActive = true;
665
775
  const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
666
776
  const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
667
777
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
@@ -670,6 +780,7 @@ export const makeSocket = (config) => {
670
780
  let qrMs = qrTimeout || 60000; // time to let a QR live
671
781
  const genPairQR = () => {
672
782
  if (!ws.isOpen) {
783
+ qrChainActive = false;
673
784
  return;
674
785
  }
675
786
  const refNode = refNodes.shift();
@@ -726,6 +837,7 @@ export const makeSocket = (config) => {
726
837
  await sendPassiveIq('active');
727
838
  logger.info('opened connection to WA');
728
839
  clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
840
+ qrChainActive = false;
729
841
  ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
730
842
  ev.emit('connection.update', { connection: 'open' });
731
843
  }
@@ -737,9 +849,9 @@ export const makeSocket = (config) => {
737
849
  // AunuBaileys (1.0.71): 405 client_too_old — fetch the live WA Web
738
850
  // build so the caller's reconnect uses it (donor: violetix
739
851
  // lib/Socket/socket.js CB:failure handler). Only for static versions;
740
- // a resolver function re-resolves on the next connect anyway. The
741
- // connection.update signal is best-effort: end() may already have
742
- // torn the listeners down by the time the fetch lands.
852
+ // a resolver function re-resolves on the next connect anyway. Both
853
+ // 405 paths (CB:failure and CB:stream:error) await this before
854
+ // end(), so the clientTooOld signal reaches the host first.
743
855
  const handleClientTooOld = async () => {
744
856
  if (typeof config.version === 'function') {
745
857
  return;
@@ -759,11 +871,16 @@ export const makeSocket = (config) => {
759
871
  logger.warn({ err }, 'failed to fetch the latest WA Web version after a 405');
760
872
  }
761
873
  };
762
- ws.on('CB:stream:error', (node) => {
874
+ ws.on('CB:stream:error', async (node) => {
763
875
  logger.error({ node }, 'stream errored out');
764
876
  const { reason, statusCode } = getErrorCodeFromStreamError(node);
765
877
  if (statusCode === 405) {
766
- void handleClientTooOld();
878
+ // AunuBaileys (1.0.77, HB-148): awaited like the CB:failure
879
+ // path (1.0.72) — firing it void let end() tear the
880
+ // connection.update listeners down before the version
881
+ // fetch landed, so the clientTooOld signal never reached
882
+ // the host and a 405 looked like any other disconnect.
883
+ await handleClientTooOld();
767
884
  }
768
885
  end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
769
886
  });
@@ -802,7 +919,7 @@ export const makeSocket = (config) => {
802
919
  if (offlineDrainBatches >= OFFLINE_DRAIN_MAX_BATCHES) {
803
920
  stopOfflineDrain();
804
921
  logger.warn({ batches: offlineDrainBatches }, 'offline drain hit the batch cap; remaining backlog waits for the next reconnect');
805
- return;
922
+ return false;
806
923
  }
807
924
  offlineDrainBatches += 1;
808
925
  // AunuBaileys (1.0.70): a floating sendNode here could reject
@@ -812,12 +929,19 @@ export const makeSocket = (config) => {
812
929
  attrs: {},
813
930
  content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
814
931
  }).catch(err => logger.warn({ err }, 'failed to request offline batch'));
932
+ return true;
815
933
  };
816
934
  const scheduleOfflineDrain = () => {
817
935
  stopOfflineDrain();
818
936
  offlineDrainTimer = setTimeout(() => {
819
- requestOfflineBatch();
820
- scheduleOfflineDrain();
937
+ // AunuBaileys (1.0.77, HB-109): stop re-arming at the batch
938
+ // cap — the unconditional re-schedule used to undo
939
+ // requestOfflineBatch's stopOfflineDrain(), so when the
940
+ // terminal offline bulletin never arrived the cap warning
941
+ // repeated every 500ms for the life of the socket.
942
+ if (requestOfflineBatch()) {
943
+ scheduleOfflineDrain();
944
+ }
821
945
  }, OFFLINE_DRAIN_INTERVAL_MS);
822
946
  };
823
947
  ws.on('CB:ib,,offline_preview', (node) => {
@@ -374,6 +374,16 @@ export const getCallStatusFromNode = ({ tag, attrs }) => {
374
374
  };
375
375
  const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
376
376
  export const getCodeFromWSError = (error) => {
377
+ // AunuBaileys (1.0.77, HB-133): an error that already carries a
378
+ // valid Boom status code keeps it. Re-deriving the code from the
379
+ // message text lost real codes — promiseTimeout's Boom
380
+ // 'Timed Out' (408) was re-wrapped as a 500 by mapWebSocketError
381
+ // because the textual timeout check below is case-sensitive
382
+ // ('Timed Out' vs 'timed out').
383
+ const existingCode = error?.output?.statusCode;
384
+ if (Number.isFinite(existingCode) && existingCode >= 400 && existingCode <= 599) {
385
+ return existingCode;
386
+ }
377
387
  let statusCode = 500;
378
388
  if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
379
389
  const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
@@ -385,7 +395,7 @@ export const getCodeFromWSError = (error) => {
385
395
  // AunuBaileys (1.0.67): error.code can be numeric (e.g. WS close
386
396
  // 1006) — only call startsWith on strings.
387
397
  (typeof error?.code === 'string' && error.code.startsWith('E')) ||
388
- error?.message?.includes('timed out')) {
398
+ error?.message?.toLowerCase().includes('timed out')) {
389
399
  // handle ETIMEOUT, ENOTFOUND etc
390
400
  statusCode = 408;
391
401
  }
@@ -15,8 +15,8 @@ const generateIV = (counter) => {
15
15
  // corrupt header either wedges the stream forever (size 0: the header
16
16
  // is never consumed, so every later call re-reads it) or buffers
17
17
  // without bound waiting for megabytes that never arrive. Fail loudly
18
- // instead: the socket ends (the caller routes the throw to
19
- // onUnexpectedError) and the host reconnects.
18
+ // instead: the throw is marked frame-fatal (1.0.77, HB-185) and the
19
+ // caller ends the socket, so the host reconnects at once.
20
20
  const MAX_NOISE_FRAME_SIZE = 10 * 1024 * 1024;
21
21
  export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
22
22
  logger = logger.child({ class: 'ns' });
@@ -161,23 +161,55 @@ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publi
161
161
  }
162
162
  if (size > MAX_NOISE_FRAME_SIZE) {
163
163
  // AunuBaileys (1.0.73, HB-91): never wait for a
164
- // frame that cannot exist — throw so the socket
165
- // ends instead of buffering without bound until
166
- // the keep-alive watchdog kills the connection
167
- // ~65s later.
168
- throw new Boom(`noise frame too large: ${size} bytes`, { statusCode: 400 });
164
+ // frame that cannot exist. (1.0.77, HB-185): the
165
+ // throw alone did NOT end the socket — the caller
166
+ // only logged it, the header was never consumed,
167
+ // and the stream wedged until the keep-alive
168
+ // watchdog fired ~65s later. Marked frame-fatal:
169
+ // the caller now ends the connection on it.
170
+ const err = new Boom(`noise frame too large: ${size} bytes`, { statusCode: 400 });
171
+ err.isFrameFatal = true;
172
+ throw err;
169
173
  }
170
174
  if (inBytes.length < size + 3) {
171
175
  break;
172
176
  }
173
177
  let frame = inBytes.slice(3, size + 3);
174
178
  inBytes = inBytes.slice(size + 3);
179
+ let decoded = true;
175
180
  if (isFinished) {
176
- const result = decrypt(frame);
177
- frame = await decodeBinaryNode(result);
181
+ let result;
182
+ try {
183
+ result = decrypt(frame);
184
+ }
185
+ catch (err) {
186
+ // AunuBaileys (1.0.77, HB-207): a GCM failure
187
+ // leaves readCounter behind the server's
188
+ // counter, so every later frame decrypts with
189
+ // the wrong IV and fails too — the stream can
190
+ // never resync. Frame-fatal: the caller ends
191
+ // the connection instead of losing every
192
+ // inbound message until the watchdog fires.
193
+ err.isFrameFatal = true;
194
+ throw err;
195
+ }
196
+ try {
197
+ frame = await decodeBinaryNode(result);
198
+ }
199
+ catch (err) {
200
+ // AunuBaileys (1.0.77): stanza-level corruption
201
+ // is NOT fatal — the frame was consumed and the
202
+ // counter advanced, so the stream is still in
203
+ // sync. Log and skip the frame instead of
204
+ // aborting the rest of the buffered frames.
205
+ logger.error({ err }, 'failed to decode a stanza; skipping the frame');
206
+ decoded = false;
207
+ }
208
+ }
209
+ if (decoded) {
210
+ logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
211
+ onFrame(frame);
178
212
  }
179
- logger.trace({ msg: frame?.attrs?.id }, 'recv frame');
180
- onFrame(frame);
181
213
  size = getBytesSize();
182
214
  }
183
215
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aunucore/baileys",
3
3
  "type": "module",
4
- "version": "1.0.76",
4
+ "version": "1.0.77",
5
5
  "description": "AunuBaileys — the self-healing WhatsApp Web API for Node.js. Bad MAC and \"2000 messages into the future\" errors repair themselves, LID and phone-number identities stay in sync, anti-ban is built in, pairing codes are custom — plus 29 experimental features no other Baileys fork ships: invisible watermarks, per-person tag-all cards, side-profile text, ghost mentions and more. ESM, CJS and full TypeScript types.",
6
6
  "keywords": [
7
7
  "whatsapp",