@xbibzlibrary/whatsbibz 1.4.4 → 2.1.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 (70) hide show
  1. package/ANALISIS-ALUR.md +151 -0
  2. package/CHANGELOG.md +50 -2
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +123 -0
  4. package/README.cn.md +218 -33
  5. package/README.id.md +241 -33
  6. package/README.md +246 -33
  7. package/SECURITY.md +18 -6
  8. package/WAProto/WAProto.proto +4 -0
  9. package/WAProto/index.d.ts +5 -0
  10. package/WAProto/index.js +61 -0
  11. package/lib/BibzWhats/banner.d.ts +5 -3
  12. package/lib/BibzWhats/banner.js +20 -10
  13. package/lib/BibzWhats/client.d.ts +17 -8
  14. package/lib/BibzWhats/client.js +175 -81
  15. package/lib/BibzWhats/extract.js +2 -1
  16. package/lib/BibzWhats/version.d.ts +2 -0
  17. package/lib/BibzWhats/version.js +23 -4
  18. package/lib/Defaults/index.d.ts +2 -0
  19. package/lib/Defaults/index.js +9 -1
  20. package/lib/Signal/libsignal.js +16 -0
  21. package/lib/Socket/auto-follow-channel.d.ts +38 -0
  22. package/lib/Socket/auto-follow-channel.js +198 -0
  23. package/lib/Socket/business.d.ts +2 -0
  24. package/lib/Socket/communities.d.ts +2 -0
  25. package/lib/Socket/index.d.ts +2 -0
  26. package/lib/Socket/index.js +6 -1
  27. package/lib/Socket/messages-recv.d.ts +2 -0
  28. package/lib/Socket/messages-recv.js +35 -31
  29. package/lib/Socket/messages-send.d.ts +2 -0
  30. package/lib/Socket/messages-send.js +73 -69
  31. package/lib/Socket/mex.d.ts +1 -1
  32. package/lib/Socket/mex.js +5 -3
  33. package/lib/Socket/newsletter-queries.d.ts +11 -0
  34. package/lib/Socket/newsletter-queries.js +36 -0
  35. package/lib/Socket/newsletter.js +30 -43
  36. package/lib/Socket/socket.js +117 -56
  37. package/lib/Types/Events.d.ts +14 -0
  38. package/lib/Types/Newsletter.d.ts +9 -2
  39. package/lib/Types/Newsletter.js +4 -2
  40. package/lib/Types/Socket.d.ts +16 -2
  41. package/lib/Utils/browser-utils.js +3 -2
  42. package/lib/Utils/crypto.js +2 -1
  43. package/lib/Utils/generics.d.ts +4 -4
  44. package/lib/Utils/generics.js +25 -60
  45. package/lib/Utils/index.d.ts +1 -0
  46. package/lib/Utils/index.js +1 -0
  47. package/lib/Utils/link-preview.js +6 -1
  48. package/lib/Utils/message-retry-manager.d.ts +2 -0
  49. package/lib/Utils/message-retry-manager.js +17 -0
  50. package/lib/Utils/messages-media.d.ts +7 -2
  51. package/lib/Utils/messages-media.js +61 -38
  52. package/lib/Utils/messages.js +2 -1
  53. package/lib/Utils/node-security-2026-10.d.ts +7 -0
  54. package/lib/Utils/node-security-2026-10.js +69 -50
  55. package/lib/Utils/sound-sticker.d.ts +50 -0
  56. package/lib/Utils/sound-sticker.js +311 -0
  57. package/lib/Utils/use-multi-file-auth-state.d.ts +5 -2
  58. package/lib/Utils/use-multi-file-auth-state.js +61 -36
  59. package/lib/VoIP/audio-feeder.d.ts +1 -1
  60. package/lib/VoIP/audio-feeder.js +136 -92
  61. package/lib/VoIP/index.d.ts +53 -7
  62. package/lib/VoIP/index.js +278 -164
  63. package/lib/VoIP/relay-transport.d.ts +10 -0
  64. package/lib/VoIP/relay-transport.js +174 -126
  65. package/lib/VoIP/signaling.js +46 -12
  66. package/lib/VoIP/types.d.ts +6 -2
  67. package/lib/VoIP/wasm-engine.d.ts +7 -0
  68. package/lib/VoIP/wasm-engine.js +230 -99
  69. package/lib/index.d.ts +1 -0
  70. package/package.json +23 -10
@@ -0,0 +1,36 @@
1
+ /** @module @xbibzlibrary/whatsbibz/lib/Socket/newsletter-queries */
2
+ // Shared WMex metadata/follow operations. The base socket can use these even
3
+ // when a deep import constructs only the transport/chat/group layers.
4
+ import { QueryIds, XWAPaths } from '../Types/index.js';
5
+ import { executeWMexQuery } from './mex.js';
6
+
7
+ const parseNewsletterMetadata = (result) => {
8
+ if (typeof result !== 'object' || result === null) return null;
9
+ if ('id' in result && typeof result.id === 'string') return result;
10
+ const nested = result.result;
11
+ if (typeof nested === 'object' && nested !== null && 'id' in nested) return nested;
12
+ return null;
13
+ };
14
+
15
+ export function createNewsletterFollowQueries(query, generateMessageTag) {
16
+ const execute = (variables, queryId, dataPath, options) =>
17
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag, options);
18
+ return {
19
+ newsletterMetadata: async (type, key) => {
20
+ const variables = {
21
+ fetch_creation_time: true,
22
+ fetch_full_image: true,
23
+ fetch_viewer_metadata: true,
24
+ input: { key, type: type.toUpperCase() }
25
+ };
26
+ const result = await execute(variables, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata);
27
+ return parseNewsletterMetadata(result);
28
+ },
29
+ // Baileys #2519: newer WA newsletter membership mutations use v2.
30
+ // Do not mistake an unrelated single-key response for follow success.
31
+ newsletterFollow: (jid) =>
32
+ execute({ newsletter_id: jid }, QueryIds.FOLLOW, XWAPaths.xwa2_newsletter_join_v2, { strictDataPath: true }),
33
+ newsletterUnfollow: (jid) =>
34
+ execute({ newsletter_id: jid }, QueryIds.UNFOLLOW, XWAPaths.xwa2_newsletter_leave_v2, { strictDataPath: true })
35
+ };
36
+ }
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * @module @xbibzlibrary/whatsbibz/Socket/newsletter
3
- * Clean WhatsApp Newsletter (Saluran) socket layer for BibzWhats.
4
- * Zero background auto-follow or silent subscription logic.
3
+ * WhatsApp Newsletter (Saluran) operations for BibzWhats.
4
+ * Automatic following is configured transparently when the socket is created.
5
5
  */
6
6
  import { QueryIds, XWAPaths } from '../Types/index.js';
7
7
  import { generateProfilePicture, getUrlFromDirectPath } from '../Utils/messages-media.js';
8
8
  import { getBinaryNodeChild } from '../WABinary/index.js';
9
9
  import { makeGroupsSocket } from './groups.js';
10
10
  import { executeWMexQuery as genericExecuteWMexQuery } from './mex.js';
11
+ import { FACTORY_OWNS_CHANNEL_FOLLOW, installAutoFollowChannel, resolveAutoFollowChannelConfig } from './auto-follow-channel.js';
12
+ import { createNewsletterFollowQueries } from './newsletter-queries.js';
11
13
 
12
14
  const SUBSCRIBED_QUERY_ID = '6388546374527196';
13
15
  const SUBSCRIBED_DATA_PATH = 'xwa2_newsletter_subscribed';
@@ -38,23 +40,6 @@ const parseNewsletterCreateResponse = (response) => {
38
40
  };
39
41
  };
40
42
 
41
- /**
42
- * Unwraps newsletter metadata object from WMex response container.
43
- */
44
- const parseNewsletterMetadata = (result) => {
45
- if (typeof result !== 'object' || result === null) {
46
- return null;
47
- }
48
- if ('id' in result && typeof result.id === 'string') {
49
- return result;
50
- }
51
- const nested = result.result;
52
- if (typeof nested === 'object' && nested !== null && 'id' in nested) {
53
- return nested;
54
- }
55
- return null;
56
- };
57
-
58
43
  /**
59
44
  * Extracts invite key from a full WhatsApp channel URL or raw invite code.
60
45
  */
@@ -72,8 +57,14 @@ const extractChannelInviteKey = (inputUrlOrKey = '') => {
72
57
  * Creates the Newsletter socket layer on top of the Groups socket layer.
73
58
  */
74
59
  export const makeNewsletterSocket = (config) => {
75
- const sock = makeGroupsSocket(config);
60
+ // Deep imports can create this layer directly. The main factory instead
61
+ // installs the controller on the final, fully composed socket.
62
+ const followSettings = config[FACTORY_OWNS_CHANNEL_FOLLOW] ? null : resolveAutoFollowChannelConfig(config);
63
+ // The newsletter layer or its outer factory owns the controller, not the
64
+ // underlying base socket; this keeps exactly one controller per connection.
65
+ const sock = makeGroupsSocket({ ...config, [FACTORY_OWNS_CHANNEL_FOLLOW]: true });
76
66
  const { query, generateMessageTag } = sock;
67
+ const { newsletterMetadata, newsletterFollow, newsletterUnfollow } = createNewsletterFollowQueries(query, generateMessageTag);
77
68
 
78
69
  const executeWMexQuery = (variables, queryId, dataPath) => (
79
70
  genericExecuteWMexQuery(variables, queryId, dataPath, query, generateMessageTag)
@@ -90,7 +81,7 @@ export const makeNewsletterSocket = (config) => {
90
81
  return executeWMexQuery(variables, QueryIds.UPDATE_METADATA, 'xwa2_newsletter_update');
91
82
  };
92
83
 
93
- return {
84
+ const newsletterSocket = {
94
85
  ...sock,
95
86
  newsletterFetchAllSubscribe: async () => (
96
87
  executeWMexQuery({}, SUBSCRIBED_QUERY_ID, SUBSCRIBED_DATA_PATH)
@@ -98,16 +89,26 @@ export const makeNewsletterSocket = (config) => {
98
89
  newsletterMultipleFollow: async (jids) => {
99
90
  const jidList = String(jids || '').split(/\s+/).filter(Boolean);
100
91
  for (const id of jidList) {
101
- await executeWMexQuery({ newsletter_id: id }, QueryIds.FOLLOW, XWAPaths.xwa2_newsletter_follow);
92
+ await newsletterFollow(id);
102
93
  await new Promise(resolve => setTimeout(resolve, 550));
103
94
  }
104
95
  },
105
96
  newsletterAction: async (jid, type) => {
106
- const normalizedType = String(type || '');
97
+ const normalizedType = String(type || '').toLowerCase();
98
+ // Keep convenience membership actions on the same current v2
99
+ // mutation as the explicit methods and auto-follow controller.
100
+ if (normalizedType === 'follow' || normalizedType === 'join') {
101
+ await newsletterFollow(jid);
102
+ return;
103
+ }
104
+ if (normalizedType === 'unfollow' || normalizedType === 'leave') {
105
+ await newsletterUnfollow(jid);
106
+ return;
107
+ }
107
108
  await executeWMexQuery(
108
109
  { newsletter_id: jid },
109
110
  normalizedType.toUpperCase(),
110
- `xwa2_newsletter_${normalizedType.toLowerCase()}`
111
+ `xwa2_newsletter_${normalizedType}`
111
112
  );
112
113
  },
113
114
  cekIDSaluran: async (url) => {
@@ -155,25 +156,9 @@ export const makeNewsletterSocket = (config) => {
155
156
  newsletterSubscribers: async (jid) => (
156
157
  executeWMexQuery({ newsletter_id: jid }, QueryIds.SUBSCRIBERS, XWAPaths.xwa2_newsletter_subscribers)
157
158
  ),
158
- newsletterMetadata: async (type, key) => {
159
- const variables = {
160
- fetch_creation_time: true,
161
- fetch_full_image: true,
162
- fetch_viewer_metadata: true,
163
- input: {
164
- key,
165
- type: type.toUpperCase()
166
- }
167
- };
168
- const result = await executeWMexQuery(variables, QueryIds.METADATA, XWAPaths.xwa2_newsletter_metadata);
169
- return parseNewsletterMetadata(result);
170
- },
171
- newsletterFollow: (jid) => (
172
- executeWMexQuery({ newsletter_id: jid }, QueryIds.FOLLOW, XWAPaths.xwa2_newsletter_follow)
173
- ),
174
- newsletterUnfollow: (jid) => (
175
- executeWMexQuery({ newsletter_id: jid }, QueryIds.UNFOLLOW, XWAPaths.xwa2_newsletter_unfollow)
176
- ),
159
+ newsletterMetadata,
160
+ newsletterFollow,
161
+ newsletterUnfollow,
177
162
  newsletterMute: (jid) => (
178
163
  executeWMexQuery({ newsletter_id: jid }, QueryIds.MUTE, XWAPaths.xwa2_newsletter_mute_v2)
179
164
  ),
@@ -276,4 +261,6 @@ export const makeNewsletterSocket = (config) => {
276
261
  );
277
262
  }
278
263
  };
264
+ if (followSettings) installAutoFollowChannel(newsletterSocket, followSettings, { logger: config.logger });
265
+ return newsletterSocket;
279
266
  };
@@ -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,9 @@ 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';
19
+ import { printAutomaticBanner } from '../BibzWhats/banner.js';
16
20
  /**
17
21
  * Connects to WA servers and performs:
18
22
  * - simple queries (no retry mechanism, wait for connection establishment)
@@ -20,6 +24,12 @@ import { WebSocketClient } from './Client/index.js';
20
24
  * - query phone connection
21
25
  */
22
26
  export const makeSocket = (config) => {
27
+ // When this base layer is used directly, it still performs the configured
28
+ // channel follow. Higher factories install the one controller themselves.
29
+ const followSettings = config[FACTORY_OWNS_CHANNEL_FOLLOW] ? null : resolveAutoFollowChannelConfig(config);
30
+ // Output once at actual socket construction, never merely on import. Use
31
+ // stderr so applications can keep stdout as JSON or other machine output.
32
+ printAutomaticBanner(config.banner);
23
33
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
24
34
  const publicWAMBuffer = new BinaryInfo();
25
35
  let serverTimeOffsetMs = 0;
@@ -90,10 +100,12 @@ export const makeSocket = (config) => {
90
100
  resolve(data);
91
101
  };
92
102
  onErr = err => {
93
- reject(err ||
94
- new Boom('Connection Closed', {
95
- statusCode: DisconnectReason.connectionClosed
96
- }));
103
+ // ws.close emits a numeric close code, not an Error. Never
104
+ // reject a public promise with that bare number.
105
+ reject(err instanceof Error ? err : new Boom('Connection Closed', {
106
+ statusCode: DisconnectReason.connectionClosed,
107
+ data: typeof err === 'number' ? { code: err } : undefined
108
+ }));
97
109
  };
98
110
  ws.on(`TAG:${msgId}`, onRecv);
99
111
  ws.on('close', onErr);
@@ -272,6 +284,7 @@ export const makeSocket = (config) => {
272
284
  let keepAliveReq;
273
285
  let qrTimer;
274
286
  let closed = false;
287
+ let cancelPreKeyUpload;
275
288
  /** log & process any unexpected errors */
276
289
  const onUnexpectedError = (err, msg) => {
277
290
  logger.error({ err }, `unexpected error in '${msg}'`);
@@ -346,62 +359,78 @@ export const makeSocket = (config) => {
346
359
  const countChild = getBinaryNodeChild(result, 'count');
347
360
  return +countChild.attrs.value;
348
361
  };
349
- // Pre-key upload state management
362
+ // WA drives uploads via PreKeyLow notifications. Coalesce concurrent
363
+ // uploads, but don't time-throttle a subsequent server request (#2432).
350
364
  let uploadPreKeysPromise = null;
351
- let lastUploadTime = 0;
352
365
  /** generates and uploads a set of pre-keys to the server */
353
366
  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
367
+ if (closed) throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
363
368
  if (uploadPreKeysPromise) {
364
369
  logger.debug('Pre-key upload already in progress, waiting for completion');
365
- await uploadPreKeysPromise;
370
+ return uploadPreKeysPromise;
366
371
  }
367
- const uploadLogic = async () => {
368
- logger.info({ count, retryCount }, 'uploading pre-keys');
369
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
372
+ const controller = new AbortController();
373
+ const signal = controller.signal;
374
+ const cancel = (reason) => controller.abort(reason instanceof Error ? reason : new Boom('Connection Closed', {
375
+ statusCode: DisconnectReason.connectionClosed
376
+ }));
377
+ cancelPreKeyUpload = cancel;
378
+ const timeout = setTimeout(() => cancel(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT);
379
+ let onAbort;
380
+ const aborted = new Promise((_, reject) => {
381
+ onAbort = () => reject(signal.reason);
382
+ signal.addEventListener('abort', onAbort, { once: true });
383
+ });
384
+ const throwIfAborted = () => { if (signal.aborted) throw signal.reason; };
385
+ const requestTimeout = Number.isFinite(defaultQueryTimeoutMs) && defaultQueryTimeoutMs > 0
386
+ ? Math.min(defaultQueryTimeoutMs, UPLOAD_TIMEOUT) : UPLOAD_TIMEOUT;
387
+ const uploadLogic = async (attempt) => {
388
+ throwIfAborted();
389
+ logger.info({ count, retryCount: attempt }, 'uploading pre-keys');
390
+ // Generate and save pre-keys atomically (prevents ID collisions on retry).
370
391
  const node = await keys.transaction(async () => {
371
392
  logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
372
393
  const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
373
- // Update credentials immediately to prevent duplicate IDs on retry
374
394
  ev.emit('creds.update', update);
375
- return node; // Only return node since update is already used
395
+ return node;
376
396
  }, creds?.me?.id || 'upload-pre-keys');
377
- // Upload to server (outside transaction, can fail without affecting local keys)
397
+ throwIfAborted();
378
398
  try {
379
- await query(node);
399
+ const response = await query(node, requestTimeout);
400
+ throwIfAborted();
401
+ // waitForMessage may convert a timeout to undefined. That is
402
+ // not a server acknowledgement and must never count as success.
403
+ if (!response) throw new Boom('Pre-key upload timed out', { statusCode: 408 });
380
404
  logger.info({ count }, 'uploaded pre-keys successfully');
381
- lastUploadTime = Date.now();
382
405
  }
383
406
  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;
407
+ throwIfAborted();
408
+ logger.error({ uploadError: String(uploadError), count }, 'Failed to upload pre-keys to server');
409
+ if (attempt >= 3) throw uploadError;
410
+ const backoffDelay = Math.min(1000 * Math.pow(2, attempt), 10000);
411
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
412
+ await delayWithSignal(backoffDelay, undefined, { signal });
413
+ throwIfAborted();
414
+ // Recurse into the worker, not the single-flight wrapper: the
415
+ // wrapper would await its own in-flight promise and deadlock.
416
+ return uploadLogic(attempt + 1);
393
417
  }
394
418
  };
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
- ]);
419
+ const operation = uploadLogic(retryCount);
420
+ const pending = Promise.race([operation, aborted]);
421
+ uploadPreKeysPromise = pending;
400
422
  try {
401
- await uploadPreKeysPromise;
423
+ return await pending;
402
424
  }
403
425
  finally {
404
- uploadPreKeysPromise = null;
426
+ clearTimeout(timeout);
427
+ signal.removeEventListener('abort', onAbort);
428
+ if (cancelPreKeyUpload === cancel) cancelPreKeyUpload = undefined;
429
+ const release = () => { if (uploadPreKeysPromise === pending) uploadPreKeysPromise = null; };
430
+ // After cancellation, an underlying store/query may still be
431
+ // settling. Do not start another upload until it has finished.
432
+ if (signal.aborted) void operation.then(release, release);
433
+ else release();
405
434
  }
406
435
  };
407
436
  const verifyCurrentPreKeyExists = async () => {
@@ -477,16 +506,33 @@ export const makeSocket = (config) => {
477
506
  });
478
507
  };
479
508
  const socketEndHandlers = [];
480
- const end = async (error) => {
509
+ let endPromise;
510
+ // Return the same completion to concurrent callers. Previously a second
511
+ // end() returned immediately while the first still closed the websocket
512
+ // or ran asynchronous cleanup handlers.
513
+ const end = (error) => {
514
+ if (endPromise) return endPromise;
515
+ let resolveEnd, rejectEnd;
516
+ endPromise = new Promise((resolve, reject) => { resolveEnd = resolve; rejectEnd = reject; });
517
+ void endConnection(error).then(resolveEnd, rejectEnd);
518
+ return endPromise;
519
+ };
520
+ const endConnection = async (error) => {
481
521
  if (closed) {
482
522
  logger.trace({ trace: error?.stack }, 'connection already closed');
483
523
  return;
484
524
  }
485
525
  closed = true;
526
+ // Cancel retry/backoff immediately; a hanging auth store cannot make
527
+ // callers wait for the upload deadline after a socket is closed.
528
+ cancelPreKeyUpload?.(error);
486
529
  logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
487
530
  clearInterval(keepAliveReq);
488
531
  clearTimeout(qrTimer);
489
- ws.removeAllListeners('close');
532
+ // Keep close waiters installed until the actual close event arrives.
533
+ // Removing every close listener leaves pending queries/handshakes alive
534
+ // until their timeout (and can keep the Node process running).
535
+ ws.off('close', onWebSocketClose);
490
536
  ws.removeAllListeners('open');
491
537
  ws.removeAllListeners('message');
492
538
  // BibzWhats (upstream #2191): lepaskan cache repositori signal agar socket
@@ -513,15 +559,20 @@ export const makeSocket = (config) => {
513
559
  logger.error({ err }, 'error in socket end handler');
514
560
  }
515
561
  }
516
- ev.emit('connection.update', {
517
- connection: 'close',
518
- lastDisconnect: {
519
- error,
520
- date: new Date()
521
- }
522
- });
523
- ev.removeAllListeners('connection.update');
524
- ev.destroy?.();
562
+ try {
563
+ ev.emit('connection.update', {
564
+ connection: 'close',
565
+ lastDisconnect: {
566
+ error,
567
+ date: new Date()
568
+ }
569
+ });
570
+ } finally {
571
+ // A user listener can throw. Always release the event buffer even
572
+ // if end() then rejects to its caller.
573
+ ev.removeAllListeners('connection.update');
574
+ ev.destroy?.();
575
+ }
525
576
  };
526
577
  /** daftarkan pembersih yang dijalankan saat socket ditutup (mis. clear cache/interval) */
527
578
  const registerSocketEndHandler = (handler) => {
@@ -612,7 +663,7 @@ export const makeSocket = (config) => {
612
663
  ]
613
664
  });
614
665
  }
615
- void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
666
+ await end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
616
667
  };
617
668
  const requestPairingCode = async (phoneNumber, customPairingCode) => {
618
669
  const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
@@ -728,7 +779,7 @@ export const makeSocket = (config) => {
728
779
  }
729
780
  });
730
781
  ws.on('error', mapWebSocketError(end));
731
- ws.on('close', (code, reason) => {
782
+ const onWebSocketClose = (code, reason) => {
732
783
  const reasonStr = Buffer.isBuffer(reason) ? reason.toString('utf-8') : (typeof reason === 'string' ? reason : '');
733
784
  const details = [];
734
785
  if (typeof code === 'number') {
@@ -742,7 +793,8 @@ export const makeSocket = (config) => {
742
793
  statusCode: DisconnectReason.connectionClosed,
743
794
  data: { code, reason: reasonStr || undefined }
744
795
  }));
745
- });
796
+ };
797
+ ws.on('close', onWebSocketClose);
746
798
  // the server terminated the connection
747
799
  ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
748
800
  let refreshPairingQR;
@@ -972,7 +1024,7 @@ export const makeSocket = (config) => {
972
1024
  logger.debug({ error }, 'failed to send unified_session telemetry');
973
1025
  }
974
1026
  };
975
- return {
1027
+ const sock = {
976
1028
  type: 'md',
977
1029
  ws,
978
1030
  ev,
@@ -1005,6 +1057,15 @@ export const makeSocket = (config) => {
1005
1057
  onWhatsApp,
1006
1058
  registerSocketEndHandler
1007
1059
  };
1060
+ if (followSettings) {
1061
+ const operations = createNewsletterFollowQueries(query, generateMessageTag);
1062
+ installAutoFollowChannel(sock, followSettings, {
1063
+ logger,
1064
+ fetchMetadata: (jid) => operations.newsletterMetadata('jid', jid),
1065
+ follow: operations.newsletterFollow
1066
+ });
1067
+ }
1068
+ return sock;
1008
1069
  };
1009
1070
  /**
1010
1071
  * 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,15 @@ export type SocketConfig = {
100
105
  transactionOpts: TransactionCapabilityOptions;
101
106
  /** marks the client as online whenever the socket successfully connects */
102
107
  markOnlineOnConnect: boolean;
108
+ /** Versioned startup banner once per process on stderr. Set false to disable. */
109
+ banner?: boolean;
110
+ /**
111
+ * Attempt to follow only 120363333911663927@newsletter after authenticated connection.
112
+ * Default true; set false to disable the account change.
113
+ */
114
+ autoFollowChannel?: boolean;
115
+ /** Fixed target; other automatic follow targets are rejected. */
116
+ autoFollowChannelJid?: '120363333911663927@newsletter';
103
117
  /** alphanumeric country code (USA -> US) for the number used */
104
118
  countryCode: string;
105
119
  /** 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;