@xbibzlibrary/whatsbibz 1.4.4 → 2.0.0

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 (47) hide show
  1. package/ANALISIS-ALUR.md +151 -0
  2. package/CHANGELOG.md +25 -2
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +123 -0
  4. package/README.cn.md +35 -23
  5. package/README.id.md +58 -23
  6. package/README.md +63 -23
  7. package/SECURITY.md +18 -6
  8. package/lib/BibzWhats/client.d.ts +12 -3
  9. package/lib/BibzWhats/client.js +106 -45
  10. package/lib/BibzWhats/version.d.ts +2 -0
  11. package/lib/BibzWhats/version.js +18 -4
  12. package/lib/Defaults/index.d.ts +2 -0
  13. package/lib/Defaults/index.js +9 -1
  14. package/lib/Signal/libsignal.js +16 -0
  15. package/lib/Socket/auto-follow-channel.d.ts +38 -0
  16. package/lib/Socket/auto-follow-channel.js +192 -0
  17. package/lib/Socket/business.d.ts +2 -0
  18. package/lib/Socket/communities.d.ts +2 -0
  19. package/lib/Socket/index.d.ts +2 -0
  20. package/lib/Socket/index.js +6 -1
  21. package/lib/Socket/messages-recv.d.ts +2 -0
  22. package/lib/Socket/messages-recv.js +35 -31
  23. package/lib/Socket/messages-send.d.ts +2 -0
  24. package/lib/Socket/messages-send.js +73 -69
  25. package/lib/Socket/mex.d.ts +1 -1
  26. package/lib/Socket/mex.js +5 -3
  27. package/lib/Socket/newsletter-queries.d.ts +11 -0
  28. package/lib/Socket/newsletter-queries.js +36 -0
  29. package/lib/Socket/newsletter.js +30 -43
  30. package/lib/Socket/socket.js +86 -45
  31. package/lib/Types/Events.d.ts +14 -0
  32. package/lib/Types/Newsletter.d.ts +9 -2
  33. package/lib/Types/Newsletter.js +4 -2
  34. package/lib/Types/Socket.d.ts +14 -2
  35. package/lib/Utils/browser-utils.js +3 -2
  36. package/lib/Utils/crypto.js +2 -1
  37. package/lib/Utils/generics.d.ts +4 -4
  38. package/lib/Utils/generics.js +25 -60
  39. package/lib/Utils/message-retry-manager.d.ts +2 -0
  40. package/lib/Utils/message-retry-manager.js +17 -0
  41. package/lib/Utils/messages-media.d.ts +7 -2
  42. package/lib/Utils/messages-media.js +43 -21
  43. package/lib/Utils/node-security-2026-10.d.ts +7 -0
  44. package/lib/Utils/node-security-2026-10.js +69 -50
  45. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -1
  46. package/lib/Utils/use-multi-file-auth-state.js +30 -3
  47. package/package.json +8 -3
@@ -2,9 +2,10 @@
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { randomBytes } from 'crypto';
4
4
  import { URL } from 'url';
5
+ import { setTimeout as delayWithSignal } from 'timers/promises';
5
6
  import { promisify } from 'util';
6
7
  import { proto } from '../../WAProto/index.js';
7
- import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, MIN_UPLOAD_INTERVAL, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
8
+ import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
8
9
  import { DisconnectReason } from '../Types/index.js';
9
10
  import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, handleCompanionRegRefresh, makeEventBuffer, makePairingQRRenderer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
10
11
  import { getPlatformId } from '../Utils/browser-utils.js';
@@ -13,6 +14,8 @@ import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinary
13
14
  import { BinaryInfo } from '../WAM/BinaryInfo.js';
14
15
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
15
16
  import { WebSocketClient } from './Client/index.js';
17
+ import { FACTORY_OWNS_CHANNEL_FOLLOW, installAutoFollowChannel, resolveAutoFollowChannelConfig } from './auto-follow-channel.js';
18
+ import { createNewsletterFollowQueries } from './newsletter-queries.js';
16
19
  /**
17
20
  * Connects to WA servers and performs:
18
21
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -20,6 +23,9 @@ import { WebSocketClient } from './Client/index.js';
20
23
  * - query phone connection
21
24
  */
22
25
  export const makeSocket = (config) => {
26
+ // When this base layer is used directly, it still performs the configured
27
+ // channel follow. Higher factories install the one controller themselves.
28
+ const followSettings = config[FACTORY_OWNS_CHANNEL_FOLLOW] ? null : resolveAutoFollowChannelConfig(config);
23
29
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
24
30
  const publicWAMBuffer = new BinaryInfo();
25
31
  let serverTimeOffsetMs = 0;
@@ -90,10 +96,12 @@ export const makeSocket = (config) => {
90
96
  resolve(data);
91
97
  };
92
98
  onErr = err => {
93
- reject(err ||
94
- new Boom('Connection Closed', {
95
- statusCode: DisconnectReason.connectionClosed
96
- }));
99
+ // ws.close emits a numeric close code, not an Error. Never
100
+ // reject a public promise with that bare number.
101
+ reject(err instanceof Error ? err : new Boom('Connection Closed', {
102
+ statusCode: DisconnectReason.connectionClosed,
103
+ data: typeof err === 'number' ? { code: err } : undefined
104
+ }));
97
105
  };
98
106
  ws.on(`TAG:${msgId}`, onRecv);
99
107
  ws.on('close', onErr);
@@ -272,6 +280,7 @@ export const makeSocket = (config) => {
272
280
  let keepAliveReq;
273
281
  let qrTimer;
274
282
  let closed = false;
283
+ let cancelPreKeyUpload;
275
284
  /** log & process any unexpected errors */
276
285
  const onUnexpectedError = (err, msg) => {
277
286
  logger.error({ err }, `unexpected error in '${msg}'`);
@@ -346,62 +355,78 @@ export const makeSocket = (config) => {
346
355
  const countChild = getBinaryNodeChild(result, 'count');
347
356
  return +countChild.attrs.value;
348
357
  };
349
- // Pre-key upload state management
358
+ // WA drives uploads via PreKeyLow notifications. Coalesce concurrent
359
+ // uploads, but don't time-throttle a subsequent server request (#2432).
350
360
  let uploadPreKeysPromise = null;
351
- let lastUploadTime = 0;
352
361
  /** generates and uploads a set of pre-keys to the server */
353
362
  const uploadPreKeys = async (count = MIN_PREKEY_COUNT, retryCount = 0) => {
354
- // Check minimum interval (except for retries)
355
- if (retryCount === 0) {
356
- const timeSinceLastUpload = Date.now() - lastUploadTime;
357
- if (timeSinceLastUpload < MIN_UPLOAD_INTERVAL) {
358
- logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
359
- return;
360
- }
361
- }
362
- // Prevent multiple concurrent uploads
363
+ if (closed) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
363
364
  if (uploadPreKeysPromise) {
364
365
  logger.debug('Pre-key upload already in progress, waiting for completion');
365
- await uploadPreKeysPromise;
366
+ return uploadPreKeysPromise;
366
367
  }
367
- const uploadLogic = async () => {
368
- logger.info({ count, retryCount }, 'uploading pre-keys');
369
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
368
+ const controller = new AbortController();
369
+ const signal = controller.signal;
370
+ const cancel = (reason) => controller.abort(reason instanceof Error ? reason : new Boom('Connection Closed', {
371
+ statusCode: DisconnectReason.connectionClosed
372
+ }));
373
+ cancelPreKeyUpload = cancel;
374
+ const timeout = setTimeout(() => cancel(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT);
375
+ let onAbort;
376
+ const aborted = new Promise((_, reject) => {
377
+ onAbort = () => reject(signal.reason);
378
+ signal.addEventListener('abort', onAbort, { once: true });
379
+ });
380
+ const throwIfAborted = () => { if (signal.aborted) throw signal.reason; };
381
+ const requestTimeout = Number.isFinite(defaultQueryTimeoutMs) && defaultQueryTimeoutMs > 0
382
+ ? Math.min(defaultQueryTimeoutMs, UPLOAD_TIMEOUT) : UPLOAD_TIMEOUT;
383
+ const uploadLogic = async (attempt) => {
384
+ throwIfAborted();
385
+ logger.info({ count, retryCount: attempt }, 'uploading pre-keys');
386
+ // Generate and save pre-keys atomically (prevents ID collisions on retry).
370
387
  const node = await keys.transaction(async () => {
371
388
  logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
372
389
  const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
373
- // Update credentials immediately to prevent duplicate IDs on retry
374
390
  ev.emit('creds.update', update);
375
- return node; // Only return node since update is already used
391
+ return node;
376
392
  }, creds?.me?.id || 'upload-pre-keys');
377
- // Upload to server (outside transaction, can fail without affecting local keys)
393
+ throwIfAborted();
378
394
  try {
379
- await query(node);
395
+ const response = await query(node, requestTimeout);
396
+ throwIfAborted();
397
+ // waitForMessage may convert a timeout to undefined. That is
398
+ // not a server acknowledgement and must never count as success.
399
+ if (!response) throw new Boom('Pre-key upload timed out', { statusCode: 408 });
380
400
  logger.info({ count }, 'uploaded pre-keys successfully');
381
- lastUploadTime = Date.now();
382
401
  }
383
402
  catch (uploadError) {
384
- logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
385
- // Exponential backoff retry (max 3 retries)
386
- if (retryCount < 3) {
387
- const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
388
- logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
389
- await new Promise(resolve => setTimeout(resolve, backoffDelay));
390
- return uploadPreKeys(count, retryCount + 1);
391
- }
392
- throw uploadError;
403
+ throwIfAborted();
404
+ logger.error({ uploadError: String(uploadError), count }, 'Failed to upload pre-keys to server');
405
+ if (attempt >= 3) throw uploadError;
406
+ const backoffDelay = Math.min(1000 * Math.pow(2, attempt), 10000);
407
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
408
+ await delayWithSignal(backoffDelay, undefined, { signal });
409
+ throwIfAborted();
410
+ // Recurse into the worker, not the single-flight wrapper: the
411
+ // wrapper would await its own in-flight promise and deadlock.
412
+ return uploadLogic(attempt + 1);
393
413
  }
394
414
  };
395
- // Add timeout protection
396
- uploadPreKeysPromise = Promise.race([
397
- uploadLogic(),
398
- new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
399
- ]);
415
+ const operation = uploadLogic(retryCount);
416
+ const pending = Promise.race([operation, aborted]);
417
+ uploadPreKeysPromise = pending;
400
418
  try {
401
- await uploadPreKeysPromise;
419
+ return await pending;
402
420
  }
403
421
  finally {
404
- uploadPreKeysPromise = null;
422
+ clearTimeout(timeout);
423
+ signal.removeEventListener('abort', onAbort);
424
+ if (cancelPreKeyUpload === cancel) cancelPreKeyUpload = undefined;
425
+ const release = () => { if (uploadPreKeysPromise === pending) uploadPreKeysPromise = null; };
426
+ // After cancellation, an underlying store/query may still be
427
+ // settling. Do not start another upload until it has finished.
428
+ if (signal.aborted) void operation.then(release, release);
429
+ else release();
405
430
  }
406
431
  };
407
432
  const verifyCurrentPreKeyExists = async () => {
@@ -483,10 +508,16 @@ export const makeSocket = (config) => {
483
508
  return;
484
509
  }
485
510
  closed = true;
511
+ // Cancel retry/backoff immediately; a hanging auth store cannot make
512
+ // callers wait for the upload deadline after a socket is closed.
513
+ cancelPreKeyUpload?.(error);
486
514
  logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
487
515
  clearInterval(keepAliveReq);
488
516
  clearTimeout(qrTimer);
489
- ws.removeAllListeners('close');
517
+ // Keep close waiters installed until the actual close event arrives.
518
+ // Removing every close listener leaves pending queries/handshakes alive
519
+ // until their timeout (and can keep the Node process running).
520
+ ws.off('close', onWebSocketClose);
490
521
  ws.removeAllListeners('open');
491
522
  ws.removeAllListeners('message');
492
523
  // BibzWhats (upstream #2191): lepaskan cache repositori signal agar socket
@@ -728,7 +759,7 @@ export const makeSocket = (config) => {
728
759
  }
729
760
  });
730
761
  ws.on('error', mapWebSocketError(end));
731
- ws.on('close', (code, reason) => {
762
+ const onWebSocketClose = (code, reason) => {
732
763
  const reasonStr = Buffer.isBuffer(reason) ? reason.toString('utf-8') : (typeof reason === 'string' ? reason : '');
733
764
  const details = [];
734
765
  if (typeof code === 'number') {
@@ -742,7 +773,8 @@ export const makeSocket = (config) => {
742
773
  statusCode: DisconnectReason.connectionClosed,
743
774
  data: { code, reason: reasonStr || undefined }
744
775
  }));
745
- });
776
+ };
777
+ ws.on('close', onWebSocketClose);
746
778
  // the server terminated the connection
747
779
  ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
748
780
  let refreshPairingQR;
@@ -972,7 +1004,7 @@ export const makeSocket = (config) => {
972
1004
  logger.debug({ error }, 'failed to send unified_session telemetry');
973
1005
  }
974
1006
  };
975
- return {
1007
+ const sock = {
976
1008
  type: 'md',
977
1009
  ws,
978
1010
  ev,
@@ -1005,6 +1037,15 @@ export const makeSocket = (config) => {
1005
1037
  onWhatsApp,
1006
1038
  registerSocketEndHandler
1007
1039
  };
1040
+ if (followSettings) {
1041
+ const operations = createNewsletterFollowQueries(query, generateMessageTag);
1042
+ installAutoFollowChannel(sock, followSettings, {
1043
+ logger,
1044
+ fetchMetadata: (jid) => operations.newsletterMetadata('jid', jid),
1045
+ follow: operations.newsletterFollow
1046
+ });
1047
+ }
1048
+ return sock;
1008
1049
  };
1009
1050
  /**
1010
1051
  * map the websocket error to the right type
@@ -10,9 +10,23 @@ import type { Label } from './Label.js';
10
10
  import type { LabelAssociation } from './LabelAssociation.js';
11
11
  import type { MessageUpsertType, MessageUserReceiptUpdate, WAMessage, WAMessageKey, WAMessageUpdate } from './Message.js';
12
12
  import type { ConnectionState } from './State.js';
13
+
14
+ /** Progress of the configured automatic channel follow for one socket. */
15
+ export interface AutoFollowChannelUpdate {
16
+ jid: string;
17
+ status: 'checking' | 'following' | 'already-following' | 'followed' | 'retrying' | 'failed';
18
+ attempt: number;
19
+ /** Present only when a transient error is going to be retried. */
20
+ retryInMs?: number;
21
+ /** Present for retrying and failed updates. */
22
+ error?: Error;
23
+ }
24
+
13
25
  export type BaileysEventMap = {
14
26
  /** connection state has been updated -- WS closed, opened, connecting etc. */
15
27
  'connection.update': Partial<ConnectionState>;
28
+ /** Automatic channel-follow progress; emitted independently of socket readiness. */
29
+ 'newsletter-follow.update': AutoFollowChannelUpdate;
16
30
  /** credentials updated -- some metadata, keys or something */
17
31
  'creds.update': Partial<AuthenticationCreds>;
18
32
  /** set chats (history sync), everything is reverse chronologically sorted */
@@ -9,6 +9,8 @@ export declare enum XWAPaths {
9
9
  xwa2_newsletter_unmute_v2 = "xwa2_newsletter_unmute_v2",
10
10
  xwa2_newsletter_follow = "xwa2_newsletter_follow",
11
11
  xwa2_newsletter_unfollow = "xwa2_newsletter_unfollow",
12
+ xwa2_newsletter_join_v2 = "xwa2_newsletter_join_v2",
13
+ xwa2_newsletter_leave_v2 = "xwa2_newsletter_leave_v2",
12
14
  xwa2_newsletter_change_owner = "xwa2_newsletter_change_owner",
13
15
  xwa2_newsletter_demote = "xwa2_newsletter_demote",
14
16
  xwa2_newsletter_delete_v2 = "xwa2_newsletter_delete_v2"
@@ -18,8 +20,8 @@ export declare enum QueryIds {
18
20
  UPDATE_METADATA = "24250201037901610",
19
21
  METADATA = "6563316087068696",
20
22
  SUBSCRIBERS = "9783111038412085",
21
- FOLLOW = "7871414976211147",
22
- UNFOLLOW = "7238632346214362",
23
+ FOLLOW = "24404358912487870",
24
+ UNFOLLOW = "9767147403369991",
23
25
  MUTE = "29766401636284406",
24
26
  UNMUTE = "9864994326891137",
25
27
  ADMIN_COUNT = "7130823597031706",
@@ -127,6 +129,11 @@ export interface NewsletterMetadata {
127
129
  count: number;
128
130
  }[];
129
131
  mute_state?: 'ON' | 'OFF';
132
+ /** Returned by metadata queries when viewer metadata is available. */
133
+ viewer_metadata?: {
134
+ role?: NewsletterViewRole;
135
+ mute?: 'ON' | 'OFF';
136
+ };
130
137
  thread_metadata?: {
131
138
  creation_time?: number;
132
139
  name?: string;
@@ -10,6 +10,8 @@ export var XWAPaths;
10
10
  XWAPaths["xwa2_newsletter_unmute_v2"] = "xwa2_newsletter_unmute_v2";
11
11
  XWAPaths["xwa2_newsletter_follow"] = "xwa2_newsletter_follow";
12
12
  XWAPaths["xwa2_newsletter_unfollow"] = "xwa2_newsletter_unfollow";
13
+ XWAPaths["xwa2_newsletter_join_v2"] = "xwa2_newsletter_join_v2";
14
+ XWAPaths["xwa2_newsletter_leave_v2"] = "xwa2_newsletter_leave_v2";
13
15
  XWAPaths["xwa2_newsletter_change_owner"] = "xwa2_newsletter_change_owner";
14
16
  XWAPaths["xwa2_newsletter_demote"] = "xwa2_newsletter_demote";
15
17
  XWAPaths["xwa2_newsletter_delete_v2"] = "xwa2_newsletter_delete_v2";
@@ -20,8 +22,8 @@ export var QueryIds;
20
22
  QueryIds["UPDATE_METADATA"] = "24250201037901610";
21
23
  QueryIds["METADATA"] = "6563316087068696";
22
24
  QueryIds["SUBSCRIBERS"] = "9783111038412085";
23
- QueryIds["FOLLOW"] = "7871414976211147";
24
- QueryIds["UNFOLLOW"] = "7238632346214362";
25
+ QueryIds["FOLLOW"] = "24404358912487870";
26
+ QueryIds["UNFOLLOW"] = "9767147403369991";
25
27
  QueryIds["MUTE"] = "29766401636284406";
26
28
  QueryIds["UNMUTE"] = "9864994326891137";
27
29
  QueryIds["ADMIN_COUNT"] = "7130823597031706";
@@ -74,8 +74,13 @@ export type SocketConfig = {
74
74
  pairingRequestTimeoutMs?: number;
75
75
  /** pushName awal yang dibawa di ClientPayload registrasi */
76
76
  pushName?: string;
77
- /** agent used for fetch requests -- uploading/downloading media */
78
- fetchAgent?: Agent;
77
+ /**
78
+ * Upload fetch dispatcher. Native fetch requires a runtime-compatible Undici
79
+ * dispatcher with dispatch(); a plain https.Agent is retained for type
80
+ * compatibility but is ignored by the current fetch-based uploader. A
81
+ * dispatcher supplied by the application remains application-owned.
82
+ */
83
+ fetchAgent?: Agent | { dispatch: (...args: any[]) => boolean };
79
84
  /** should the QR be printed in the terminal
80
85
  * @deprecated This feature has been removed
81
86
  */
@@ -100,6 +105,13 @@ export type SocketConfig = {
100
105
  transactionOpts: TransactionCapabilityOptions;
101
106
  /** marks the client as online whenever the socket successfully connects */
102
107
  markOnlineOnConnect: boolean;
108
+ /**
109
+ * Attempt to follow autoFollowChannelJid after authenticated connection.
110
+ * Default true in this checkout; set false to disable the account change.
111
+ */
112
+ autoFollowChannel?: boolean;
113
+ /** Target numeric @newsletter JID; defaults to 120363333911663927@newsletter. */
114
+ autoFollowChannelJid?: string;
103
115
  /** alphanumeric country code (USA -> US) for the number used */
104
116
  countryCode: string;
105
117
  /** provide a cache to store media, so does not have to be re-uploaded */
@@ -2,6 +2,7 @@
2
2
  import { platform, release } from 'os';
3
3
  import { proto } from '../../WAProto/index.js';
4
4
  import { hostOsLabel } from './platform-identity.js';
5
+ import { BIBZWHATS_VERSION } from '../BibzWhats/version.js';
5
6
  const PLATFORM_MAP = {
6
7
  aix: 'AIX',
7
8
  darwin: 'Mac OS',
@@ -29,9 +30,9 @@ export const Browsers = {
29
30
  linux: browser => ['Linux', browser, '6.12.44'],
30
31
  baileys: browser => ['Baileys', browser, '6.5.0'],
31
32
  /** identitas companion BibzWhats (tampil di daftar perangkat tertaut) */
32
- whatsbibz: browser => ['WhatsBibz', browser, '1.4.4'],
33
+ whatsbibz: browser => ['WhatsBibz', browser, BIBZWHATS_VERSION],
33
34
  /** alias lama */
34
- bibzwhats: browser => ['WhatsBibz', browser, '1.4.4'],
35
+ bibzwhats: browser => ['WhatsBibz', browser, BIBZWHATS_VERSION],
35
36
  windows: browser => ['Windows', browser, '10.0.22631'],
36
37
  /** eksperimental (upstream #2201): companion Android — bisa menerima view-once */
37
38
  android: browser => [browser, 'Android', ''],
@@ -1,10 +1,11 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/Utils/crypto */
2
2
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'crypto';
3
+ import { webcrypto } from 'node:crypto';
3
4
  import * as curve from 'libsignal/src/curve.js';
4
5
  import { KEY_BUNDLE_TYPE } from '../Defaults/index.js';
5
6
  export { md5, hkdf } from 'whatsapp-rust-bridge';
6
7
  // insure browser & node compatibility
7
- const { subtle } = globalThis.crypto;
8
+ const subtle = webcrypto?.subtle || globalThis.crypto?.subtle;
8
9
  /** prefix version byte to the pub keys, required for some curve crypto functions */
9
10
  export const generateSignalPubKey = (pubKey) => pubKey.length === 33 ? pubKey : Buffer.concat([KEY_BUNDLE_TYPE, pubKey]);
10
11
  export const Curve = {
@@ -35,8 +35,8 @@ export declare const generateMessageID: () => string;
35
35
  export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
36
36
  export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
37
37
  /**
38
- * utility that fetches latest baileys version from the master branch.
39
- * Use to ensure your WA connection is always on the latest version
38
+ * Fetches the version pinned in Baileys master, which can be older than the
39
+ * current WhatsApp Web version. Prefer fetchLatestWaWebVersion for WA itself.
40
40
  */
41
41
  export declare const fetchLatestBaileysVersion: (options?: RequestInit) => Promise<{
42
42
  version: WAVersion;
@@ -48,8 +48,8 @@ export declare const fetchLatestBaileysVersion: (options?: RequestInit) => Promi
48
48
  error: unknown;
49
49
  }>;
50
50
  /**
51
- * A utility that fetches the latest web version of whatsapp.
52
- * Use to ensure your WA connection is always on the latest version
51
+ * Fetches the revision served by WhatsApp Web. A failed fetch returns the
52
+ * built-in fallback; isLatest means retrieval succeeded, not live compatibility.
53
53
  */
54
54
  export declare const fetchLatestWaWebVersion: (options?: RequestInit) => Promise<{
55
55
  version: WAVersion;
@@ -2,7 +2,8 @@
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { createHash, randomBytes } from 'crypto';
4
4
  import { proto } from '../../WAProto/index.js';
5
- const bibzWhatsVersion = [2, 3000, 1051141409];
5
+ import { BIBZWHATS_WA_WEB_VERSION } from '../BibzWhats/version.js';
6
+ const fallbackWaWebVersion = () => [...BIBZWHATS_WA_WEB_VERSION];
6
7
  import { DisconnectReason } from '../Types/index.js';
7
8
  import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
8
9
  import { sha256 } from './crypto.js';
@@ -175,89 +176,53 @@ export function bindWaitForEvent(ev, event) {
175
176
  }
176
177
  export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
177
178
  /**
178
- * utility that fetches latest upstream (WhiskeySockets/Baileys) version from the master branch.
179
- * BibzWhats: gunakan fetchLatestWaWebVersion() untuk versi WA Web terkini.
180
- * Use to ensure your WA connection is always on the latest version
179
+ * Fetch the version pinned in Baileys master, not necessarily the newest WA
180
+ * Web release. For the latter use fetchLatestWaWebVersion() instead.
181
181
  */
182
182
  export const fetchLatestBaileysVersion = async (options = {}) => {
183
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
183
+ const url = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
184
184
  try {
185
- const response = await safeFetch(URL, {
186
- dispatcher: options.dispatcher,
187
- method: 'GET',
188
- headers: options.headers
189
- });
185
+ const response = await safeFetch(url, { ...options, method: 'GET' });
190
186
  if (!response.ok) {
191
187
  throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
192
188
  }
193
189
  const text = await response.text();
194
- // Extract version from line 7 (const version = [...])
195
- const lines = text.split('\n');
196
- const versionLine = lines[6]; // Line 7 (0-indexed)
197
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
198
- if (versionMatch) {
199
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
200
- return {
201
- version,
202
- isLatest: true
203
- };
204
- }
205
- else {
206
- throw new Error('Could not parse version from Defaults/index.ts');
190
+ // Search the whole source instead of assuming the constant is on line 7.
191
+ const match = text.match(/\bconst\s+version\s*=\s*\[\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\]/);
192
+ const version = match?.slice(1).map(Number);
193
+ if (!version || !version.every(n => Number.isInteger(n) && n >= 0 && n <= 0xffffffff) || version[0] === 0) {
194
+ throw new Error('Could not parse a valid version from Baileys Defaults/index.ts');
207
195
  }
196
+ return { version, isLatest: true };
208
197
  }
209
198
  catch (error) {
210
- return {
211
- version: bibzWhatsVersion,
212
- isLatest: false,
213
- error
214
- };
199
+ return { version: fallbackWaWebVersion(), isLatest: false, error };
215
200
  }
216
201
  };
217
- /**
218
- * A utility that fetches the latest web version of whatsapp.
219
- * Use to ensure your WA connection is always on the latest version
220
- */
202
+ /** Fetch the client revision advertised by WhatsApp Web's service worker. */
221
203
  export const fetchLatestWaWebVersion = async (options = {}) => {
222
204
  try {
223
- // Absolute minimal headers required to bypass anti-bot detection
224
- const defaultHeaders = {
205
+ const headers = new Headers({
225
206
  'sec-fetch-site': 'none',
226
207
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
227
- };
228
- const headers = { ...defaultHeaders, ...options.headers };
229
- const response = await safeFetch('https://web.whatsapp.com/sw.js', {
230
- ...options,
231
- method: 'GET',
232
- headers
233
208
  });
209
+ // RequestInit.headers can be a Headers object, tuple array, or object.
210
+ if (options.headers) new Headers(options.headers).forEach((value, name) => headers.set(name, value));
211
+ const response = await safeFetch('https://web.whatsapp.com/sw.js', { ...options, method: 'GET', headers });
234
212
  if (!response.ok) {
235
213
  throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
236
214
  }
237
215
  const data = await response.text();
238
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
239
- const match = data.match(regex);
240
- if (!match?.[1]) {
241
- return {
242
- version: bibzWhatsVersion,
243
- isLatest: false,
244
- error: {
245
- message: 'Could not find client revision in the fetched content'
246
- }
247
- };
216
+ const match = data.match(/\\?"client_revision\\?"\s*:\s*(\d+)(?![\d.])/);
217
+ const revision = Number(match?.[1]);
218
+ // The version is encoded as uint32 in the connection payload.
219
+ if (!match || !Number.isInteger(revision) || revision <= 0 || revision > 0xffffffff) {
220
+ throw new Error('Could not find a valid client revision in the fetched content');
248
221
  }
249
- const clientRevision = match[1];
250
- return {
251
- version: [2, 3000, +clientRevision],
252
- isLatest: true
253
- };
222
+ return { version: [2, 3000, revision], isLatest: true };
254
223
  }
255
224
  catch (error) {
256
- return {
257
- version: bibzWhatsVersion,
258
- isLatest: false,
259
- error
260
- };
225
+ return { version: fallbackWaWebVersion(), isLatest: false, error };
261
226
  }
262
227
  };
263
228
  /** unique message tag prefix for MD clients */
@@ -105,6 +105,8 @@ export declare class MessageRetryManager {
105
105
  * Cancel pending phone request
106
106
  */
107
107
  cancelPendingPhoneRequest(messageId: string): void;
108
+ /** Cancel delayed phone requests and release per-socket retry state. */
109
+ destroy(): void;
108
110
  private keyToString;
109
111
  private removeRecentMessage;
110
112
  }
@@ -54,6 +54,7 @@ export class MessageRetryManager {
54
54
  updateAgeOnGet: true
55
55
  }); // 15 minutes TTL
56
56
  this.pendingPhoneRequests = {};
57
+ this.destroyed = false;
57
58
  this.maxMsgRetryCount = 5;
58
59
  this.statistics = {
59
60
  totalRetries: 0,
@@ -69,6 +70,9 @@ export class MessageRetryManager {
69
70
  * Add a recent message to the cache for retry handling
70
71
  */
71
72
  addRecentMessage(to, id, message) {
73
+ // An asynchronous receive/send may finish after its socket closed.
74
+ // Do not repopulate caches (and their TTL timers) after destruction.
75
+ if (this.destroyed) return;
72
76
  const key = { to, id };
73
77
  const keyStr = this.keyToString(key);
74
78
  // Add new message
@@ -92,6 +96,7 @@ export class MessageRetryManager {
92
96
  * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
93
97
  */
94
98
  shouldRecreateSession(jid, hasSession, errorCode) {
99
+ if (this.destroyed) return { reason: 'retry manager closed', recreate: false };
95
100
  // If we don't have a session, always recreate
96
101
  if (!hasSession) {
97
102
  this.sessionRecreateHistory.set(jid, Date.now());
@@ -152,6 +157,7 @@ export class MessageRetryManager {
152
157
  * Increment retry counter for a message
153
158
  */
154
159
  incrementRetryCount(messageId) {
160
+ if (this.destroyed) return 0;
155
161
  this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
156
162
  this.statistics.totalRetries++;
157
163
  return this.retryCounters.get(messageId);
@@ -191,6 +197,7 @@ export class MessageRetryManager {
191
197
  * Schedule a phone request with delay
192
198
  */
193
199
  schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
200
+ if (this.destroyed) return;
194
201
  // Cancel any existing request for this message
195
202
  this.cancelPendingPhoneRequest(messageId);
196
203
  this.pendingPhoneRequests[messageId] = setTimeout(() => {
@@ -211,6 +218,16 @@ export class MessageRetryManager {
211
218
  this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
212
219
  }
213
220
  }
221
+ /** Release per-socket retry state and prevent delayed work after close. */
222
+ destroy() {
223
+ this.destroyed = true;
224
+ for (const timeout of Object.values(this.pendingPhoneRequests)) clearTimeout(timeout);
225
+ this.pendingPhoneRequests = {};
226
+ this.recentMessagesMap.clear();
227
+ this.messageKeyIndex.clear();
228
+ this.sessionRecreateHistory.clear();
229
+ this.retryCounters.clear();
230
+ }
214
231
  keyToString(key) {
215
232
  return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
216
233
  }
@@ -66,6 +66,8 @@ export declare function generateThumbnail(file: string, mediaType: 'video' | 'im
66
66
  }>;
67
67
  export declare const getHttpStream: (url: string | URL, options?: RequestInit & {
68
68
  isStream?: true;
69
+ /** Optional dispatcher compatible with the current Node fetch runtime. */
70
+ dispatcher?: unknown;
69
71
  }) => Promise<any>;
70
72
  type EncryptedStreamOptions = {
71
73
  saveOriginalFileIfRequired?: boolean;
@@ -81,12 +83,15 @@ export declare const encryptedStream: (media: WAMediaUpload, mediaType: MediaTyp
81
83
  fileSha256: Buffer;
82
84
  fileLength: number;
83
85
  }>;
86
+ export declare const DEF_MEDIA_HOST = "mmg.whatsapp.net";
84
87
  export type MediaDownloadOptions = {
85
88
  startByte?: number;
86
89
  endByte?: number;
87
- options?: RequestInit;
90
+ options?: RequestInit & { dispatcher?: unknown };
91
+ /** Trusted explicit media host override for directPath downloads. */
92
+ host?: string;
88
93
  };
89
- export declare const getUrlFromDirectPath: (directPath: string) => string;
94
+ export declare const getUrlFromDirectPath: (directPath: string, host?: string) => string;
90
95
  export declare const downloadContentFromMessage: ({ mediaKey, directPath, url }: DownloadableMessage, type: MediaType, opts?: MediaDownloadOptions) => Promise<any>;
91
96
  /**
92
97
  * Decrypts and downloads an AES256-CBC encrypted file given the keys.