@xbibzlibrary/whatsbibz 1.4.3 → 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 (51) hide show
  1. package/ANALISIS-ALUR.md +151 -0
  2. package/CHANGELOG.md +36 -0
  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/Modded/message_builder.js +2 -1
  15. package/lib/Signal/libsignal.js +16 -0
  16. package/lib/Socket/auto-follow-channel.d.ts +38 -0
  17. package/lib/Socket/auto-follow-channel.js +192 -0
  18. package/lib/Socket/business.d.ts +2 -0
  19. package/lib/Socket/communities.d.ts +2 -0
  20. package/lib/Socket/index.d.ts +2 -0
  21. package/lib/Socket/index.js +6 -1
  22. package/lib/Socket/messages-recv.d.ts +2 -0
  23. package/lib/Socket/messages-recv.js +35 -31
  24. package/lib/Socket/messages-send.d.ts +2 -0
  25. package/lib/Socket/messages-send.js +73 -69
  26. package/lib/Socket/mex.d.ts +1 -1
  27. package/lib/Socket/mex.js +5 -3
  28. package/lib/Socket/newsletter-queries.d.ts +11 -0
  29. package/lib/Socket/newsletter-queries.js +36 -0
  30. package/lib/Socket/newsletter.js +30 -43
  31. package/lib/Socket/socket.js +86 -45
  32. package/lib/Types/Events.d.ts +14 -0
  33. package/lib/Types/Newsletter.d.ts +9 -2
  34. package/lib/Types/Newsletter.js +4 -2
  35. package/lib/Types/Socket.d.ts +14 -2
  36. package/lib/Utils/browser-utils.js +3 -2
  37. package/lib/Utils/crypto.js +2 -1
  38. package/lib/Utils/generics.d.ts +4 -4
  39. package/lib/Utils/generics.js +26 -60
  40. package/lib/Utils/index.d.ts +1 -0
  41. package/lib/Utils/index.js +1 -0
  42. package/lib/Utils/link-preview.js +17 -13
  43. package/lib/Utils/message-retry-manager.d.ts +2 -0
  44. package/lib/Utils/message-retry-manager.js +17 -0
  45. package/lib/Utils/messages-media.d.ts +7 -2
  46. package/lib/Utils/messages-media.js +47 -24
  47. package/lib/Utils/node-security-2026-10.d.ts +25 -0
  48. package/lib/Utils/node-security-2026-10.js +255 -0
  49. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -1
  50. package/lib/Utils/use-multi-file-auth-state.js +30 -3
  51. package/package.json +18 -12
@@ -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.3'],
33
+ whatsbibz: browser => ['WhatsBibz', browser, BIBZWHATS_VERSION],
33
34
  /** alias lama */
34
- bibzwhats: browser => ['WhatsBibz', browser, '1.4.3'],
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,10 +2,12 @@
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';
10
+ import { safeFetch } from './node-security-2026-10.js';
9
11
  export const BufferJSON = {
10
12
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
13
  replacer: (k, value) => {
@@ -174,89 +176,53 @@ export function bindWaitForEvent(ev, event) {
174
176
  }
175
177
  export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
176
178
  /**
177
- * utility that fetches latest upstream (WhiskeySockets/Baileys) version from the master branch.
178
- * BibzWhats: gunakan fetchLatestWaWebVersion() untuk versi WA Web terkini.
179
- * 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.
180
181
  */
181
182
  export const fetchLatestBaileysVersion = async (options = {}) => {
182
- 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';
183
184
  try {
184
- const response = await fetch(URL, {
185
- dispatcher: options.dispatcher,
186
- method: 'GET',
187
- headers: options.headers
188
- });
185
+ const response = await safeFetch(url, { ...options, method: 'GET' });
189
186
  if (!response.ok) {
190
187
  throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
191
188
  }
192
189
  const text = await response.text();
193
- // Extract version from line 7 (const version = [...])
194
- const lines = text.split('\n');
195
- const versionLine = lines[6]; // Line 7 (0-indexed)
196
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
197
- if (versionMatch) {
198
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
199
- return {
200
- version,
201
- isLatest: true
202
- };
203
- }
204
- else {
205
- 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');
206
195
  }
196
+ return { version, isLatest: true };
207
197
  }
208
198
  catch (error) {
209
- return {
210
- version: bibzWhatsVersion,
211
- isLatest: false,
212
- error
213
- };
199
+ return { version: fallbackWaWebVersion(), isLatest: false, error };
214
200
  }
215
201
  };
216
- /**
217
- * A utility that fetches the latest web version of whatsapp.
218
- * Use to ensure your WA connection is always on the latest version
219
- */
202
+ /** Fetch the client revision advertised by WhatsApp Web's service worker. */
220
203
  export const fetchLatestWaWebVersion = async (options = {}) => {
221
204
  try {
222
- // Absolute minimal headers required to bypass anti-bot detection
223
- const defaultHeaders = {
205
+ const headers = new Headers({
224
206
  'sec-fetch-site': 'none',
225
207
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
226
- };
227
- const headers = { ...defaultHeaders, ...options.headers };
228
- const response = await fetch('https://web.whatsapp.com/sw.js', {
229
- ...options,
230
- method: 'GET',
231
- headers
232
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 });
233
212
  if (!response.ok) {
234
213
  throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
235
214
  }
236
215
  const data = await response.text();
237
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
238
- const match = data.match(regex);
239
- if (!match?.[1]) {
240
- return {
241
- version: bibzWhatsVersion,
242
- isLatest: false,
243
- error: {
244
- message: 'Could not find client revision in the fetched content'
245
- }
246
- };
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');
247
221
  }
248
- const clientRevision = match[1];
249
- return {
250
- version: [2, 3000, +clientRevision],
251
- isLatest: true
252
- };
222
+ return { version: [2, 3000, revision], isLatest: true };
253
223
  }
254
224
  catch (error) {
255
- return {
256
- version: bibzWhatsVersion,
257
- isLatest: false,
258
- error
259
- };
225
+ return { version: fallbackWaWebVersion(), isLatest: false, error };
260
226
  }
261
227
  };
262
228
  /** unique message tag prefix for MD clients */
@@ -24,3 +24,4 @@ export * from "./sticker-pack.js";
24
24
  export * from './companion-reg-client-utils.js';
25
25
 
26
26
  export * from "./platform-identity.js";
27
+ export * from "./node-security-2026-10.js";
@@ -23,3 +23,4 @@ export * from './stanza-ack.js';
23
23
  export * from './rich-messages.js';
24
24
  export * from './sticker-pack.js';
25
25
  export * from './companion-reg-client-utils.js';
26
+ export * from './node-security-2026-10.js';
@@ -1,6 +1,7 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/Utils/link-preview */
2
2
  import { prepareWAMessageMedia } from './messages.js';
3
3
  import { extractImageThumb, getHttpStream } from './messages-media.js';
4
+ import { assertSafeUrl, withSafeFetchHeaders } from './node-security-2026-10.js';
4
5
  const THUMBNAIL_WIDTH_PX = 192;
5
6
  /** Fetches an image and generates a thumbnail for it */
6
7
  const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
@@ -19,34 +20,37 @@ export const getUrlInfo = async (text, opts = {
19
20
  fetchOpts: { timeout: 3000 }
20
21
  }) => {
21
22
  try {
22
- // retries
23
- const retries = 0;
23
+ let retries = 0;
24
24
  const maxRetry = 5;
25
25
  const { getLinkPreview } = await import('link-preview-js');
26
26
  let previewLink = text;
27
27
  if (!text.startsWith('https://') && !text.startsWith('http://')) {
28
28
  previewLink = 'https://' + previewLink;
29
29
  }
30
+ assertSafeUrl(previewLink);
30
31
  const info = await getLinkPreview(previewLink, {
31
32
  ...opts.fetchOpts,
32
33
  followRedirects: 'follow',
33
34
  handleRedirects: (baseURL, forwardedURL) => {
34
- const urlObj = new URL(baseURL);
35
- const forwardedURLObj = new URL(forwardedURL);
36
- if (retries >= maxRetry) {
35
+ try {
36
+ const urlObj = assertSafeUrl(baseURL);
37
+ const forwardedURLObj = assertSafeUrl(forwardedURL);
38
+ if (retries >= maxRetry) {
39
+ return false;
40
+ }
41
+ if (forwardedURLObj.hostname === urlObj.hostname ||
42
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
43
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
44
+ retries += 1;
45
+ return true;
46
+ }
37
47
  return false;
38
48
  }
39
- if (forwardedURLObj.hostname === urlObj.hostname ||
40
- forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
41
- 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
42
- retries + 1;
43
- return true;
44
- }
45
- else {
49
+ catch {
46
50
  return false;
47
51
  }
48
52
  },
49
- headers: opts.fetchOpts?.headers
53
+ headers: withSafeFetchHeaders(opts.fetchOpts?.headers)
50
54
  });
51
55
  if (info && 'title' in info && info.title) {
52
56
  const [image] = info.images;
@@ -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
  }