@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
@@ -19,6 +19,8 @@ export declare const makeMessagesRecvSocket: (config: SocketConfig) => {
19
19
  bibz: import("./engine.js").BibzWhatsEngine;
20
20
  readMessages: (keys: WAMessageKey[]) => Promise<void>;
21
21
  refreshMediaConn: (forceGet?: boolean) => Promise<import("../Types/index.js").MediaConnInfo>;
22
+ /** Current media host for this socket; refreshed by refreshMediaConn(). */
23
+ getMediaHost: () => string;
22
24
  waUploadToServer: import("../Types/index.js").WAMediaUploadFunction;
23
25
  fetchPrivacySettings: (force?: boolean) => Promise<{
24
26
  [_: string]: string;
@@ -377,16 +377,28 @@ export const makeMessagesRecvSocket = (config) => {
377
377
  logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
378
378
  }, authState?.creds?.me?.id || 'sendRetryRequest');
379
379
  };
380
+ // Ignore the same PreKeyLow notification while it is still in flight.
381
+ const inFlightPreKeyLow = new Set();
382
+ sock.registerSocketEndHandler(() => {
383
+ if (!config.msgRetryCounterCache) msgRetryCache.close?.();
384
+ if (!config.callOfferCache) callOfferCache.close?.();
385
+ if (!config.placeholderResendCache) placeholderResendCache.close?.();
386
+ identityAssertDebounce.close?.();
387
+ inFlightPreKeyLow.clear();
388
+ });
380
389
  const handleEncryptNotification = async (node) => {
381
390
  const from = node.attrs.from;
382
391
  if (from === S_WHATSAPP_NET) {
383
392
  const countChild = getBinaryNodeChild(node, 'count');
384
- const count = +countChild.attrs.value;
393
+ const rawCount = countChild?.attrs?.value;
394
+ const count = Number(rawCount);
395
+ if (rawCount == null || String(rawCount).trim() === '' || !Number.isSafeInteger(count) || count < 0) {
396
+ logger.warn({ node }, 'invalid pre-key count notification');
397
+ return;
398
+ }
385
399
  const shouldUploadMorePreKeys = count < MIN_PREKEY_COUNT;
386
400
  logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
387
- if (shouldUploadMorePreKeys) {
388
- await uploadPreKeys();
389
- }
401
+ if (shouldUploadMorePreKeys) await uploadPreKeys();
390
402
  }
391
403
  else {
392
404
  const result = await handleIdentityChange(node, {
@@ -894,6 +906,14 @@ export const makeMessagesRecvSocket = (config) => {
894
906
  await sendMessageAck(node);
895
907
  return;
896
908
  }
909
+ // Mark before entering the notification mutex, otherwise a duplicate
910
+ // can sit in the queue until after the first upload has completed.
911
+ const preKeyLowId = node.attrs.type === 'encrypt' && remoteJid === S_WHATSAPP_NET ? node.attrs.id : undefined;
912
+ if (preKeyLowId && inFlightPreKeyLow.has(preKeyLowId)) {
913
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack duplicate notification'));
914
+ return;
915
+ }
916
+ if (preKeyLowId) inFlightPreKeyLow.add(preKeyLowId);
897
917
  try {
898
918
  await Promise.all([
899
919
  notificationMutex.mutex(async () => {
@@ -919,7 +939,12 @@ export const makeMessagesRecvSocket = (config) => {
919
939
  ]);
920
940
  }
921
941
  finally {
922
- await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
942
+ try {
943
+ await sendMessageAck(node).catch(ackErr => logger.error({ ackErr }, 'failed to ack notification'));
944
+ }
945
+ finally {
946
+ if (preKeyLowId) inFlightPreKeyLow.delete(preKeyLowId);
947
+ }
923
948
  }
924
949
  };
925
950
  const handleMessage = async (node) => {
@@ -1036,29 +1061,16 @@ export const makeMessagesRecvSocket = (config) => {
1036
1061
  return sendMessageAck(node);
1037
1062
  }
1038
1063
  }
1039
- const errorMessage = msg?.messageStubParameters?.[0] || '';
1040
- const isPreKeyError = errorMessage.includes('PreKey');
1041
- logger.debug(`[handleMessage] Attempting retry request for failed decryption`);
1042
- // Handle both pre-key and normal retries in single mutex
1064
+ logger.debug('[handleMessage] Attempting retry request for failed decryption');
1065
+ // As in WA Web/upstream #2432, send a retry receipt;
1066
+ // low pre-key counts are handled by server notifications.
1067
+ // Eagerly uploading on every decrypt error causes storms.
1043
1068
  await retryMutex.mutex(async () => {
1044
1069
  try {
1045
1070
  if (!ws.isOpen) {
1046
1071
  logger.debug({ node }, 'Connection closed, skipping retry');
1047
1072
  return;
1048
1073
  }
1049
- // Handle pre-key errors with upload and delay
1050
- if (isPreKeyError) {
1051
- logger.info({ error: errorMessage }, 'PreKey error detected, uploading and retrying');
1052
- try {
1053
- logger.debug('Uploading pre-keys for error recovery');
1054
- await uploadPreKeys(5);
1055
- logger.debug('Waiting for server to process new pre-keys');
1056
- await delay(1000);
1057
- }
1058
- catch (uploadErr) {
1059
- logger.error({ uploadErr }, 'Pre-key upload failed, proceeding with retry anyway');
1060
- }
1061
- }
1062
1074
  const encNode = getBinaryNodeChild(node, 'enc');
1063
1075
  await sendRetryRequest(node, !encNode);
1064
1076
  if (retryRequestDelayMs) {
@@ -1066,15 +1078,7 @@ export const makeMessagesRecvSocket = (config) => {
1066
1078
  }
1067
1079
  }
1068
1080
  catch (err) {
1069
- logger.error({ err, isPreKeyError }, 'Failed to handle retry, attempting basic retry');
1070
- // Still attempt retry even if pre-key upload failed
1071
- try {
1072
- const encNode = getBinaryNodeChild(node, 'enc');
1073
- await sendRetryRequest(node, !encNode);
1074
- }
1075
- catch (retryErr) {
1076
- logger.error({ retryErr }, 'Failed to send retry after error handling');
1077
- }
1081
+ logger.error({ err }, 'Failed to send retry');
1078
1082
  }
1079
1083
  acked = true;
1080
1084
  await sendMessageAck(node, NACK_REASONS.UnhandledError);
@@ -63,6 +63,8 @@ export declare const makeMessagesSocket: (config: SocketConfig) => {
63
63
  bibz: BibzWhatsEngine;
64
64
  readMessages: (keys: WAMessageKey[]) => Promise<void>;
65
65
  refreshMediaConn: (forceGet?: boolean) => Promise<MediaConnInfo>;
66
+ /** Current media host for this socket; refreshed by refreshMediaConn(). */
67
+ getMediaHost: () => string;
66
68
  waUploadToServer: import("../Types/index.js").WAMediaUploadFunction;
67
69
  fetchPrivacySettings: (force?: boolean) => Promise<{
68
70
  [_: string]: string;
@@ -8,6 +8,7 @@ import {
8
8
  assertMediaContent,
9
9
  bindWaitForEvent,
10
10
  decryptMediaRetryData,
11
+ DEF_MEDIA_HOST,
11
12
  encodeNewsletterMessage,
12
13
  encodeSignedDeviceIdentity,
13
14
  encodeWAMessage,
@@ -166,10 +167,8 @@ export const makeMessagesSocket = (config) => {
166
167
  stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
167
168
  useClones: false,
168
169
  });
169
- const peerSessionsCache = new NodeCache({
170
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
171
- useClones: false,
172
- });
170
+ // Do not cache session existence independently of Signal's actual store.
171
+ // Sessions can be removed/replaced after identity changes or retries (#2432).
173
172
  // Initialize message retry manager if enabled
174
173
  const messageRetryManager = enableRecentMessageCache
175
174
  ? new MessageRetryManager(logger, maxMsgRetryCount)
@@ -177,41 +176,54 @@ export const makeMessagesSocket = (config) => {
177
176
  // Prevent race conditions in Signal session encryption by user
178
177
  const encryptionMutex = makeKeyedMutex();
179
178
  let mediaConn;
179
+ // Media hosts are tied to a socket/account, never shared across accounts.
180
+ let mediaHost = DEF_MEDIA_HOST;
181
+ sock.registerSocketEndHandler(() => {
182
+ if (!config.userDevicesCache) userDevicesCache.close?.();
183
+ messageRetryManager?.destroy();
184
+ mediaConn = undefined;
185
+ });
180
186
  const refreshMediaConn = async (forceGet = false) => {
181
- const media = await mediaConn;
182
- if (
183
- !media ||
184
- forceGet ||
185
- new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000
186
- ) {
187
- mediaConn = (async () => {
188
- const result = await query({
189
- tag: "iq",
190
- attrs: {
191
- type: "set",
192
- xmlns: "w:m",
193
- to: S_WHATSAPP_NET,
194
- },
195
- content: [{ tag: "media_conn", attrs: {} }],
196
- });
197
- const mediaConnNode = getBinaryNodeChild(result, "media_conn");
198
- // TODO: explore full length of data that whatsapp provides
199
- const node = {
200
- hosts: getBinaryNodeChildren(mediaConnNode, "host").map(
201
- ({ attrs }) => ({
202
- hostname: attrs.hostname,
203
- maxContentLengthBytes: +attrs.maxContentLengthBytes,
204
- }),
205
- ),
206
- auth: mediaConnNode.attrs.auth,
207
- ttl: +mediaConnNode.attrs.ttl,
208
- fetchDate: new Date(),
209
- };
210
- logger.debug("fetched media conn");
211
- return node;
212
- })();
187
+ const previous = mediaConn;
188
+ if (!forceGet && previous) {
189
+ try {
190
+ const cached = await previous;
191
+ if (Date.now() - cached.fetchDate.getTime() <= cached.ttl * 1000) return cached;
192
+ } catch {
193
+ // A failed lookup must not poison all subsequent attempts.
194
+ }
195
+ // Another caller may already have started a fresh lookup while we waited.
196
+ if (mediaConn && mediaConn !== previous) return mediaConn;
197
+ }
198
+ const next = (async () => {
199
+ const result = await query({
200
+ tag: "iq",
201
+ attrs: { type: "set", xmlns: "w:m", to: S_WHATSAPP_NET },
202
+ content: [{ tag: "media_conn", attrs: {} }],
203
+ });
204
+ const mediaConnNode = getBinaryNodeChild(result, "media_conn");
205
+ if (!mediaConnNode) throw new Boom("Missing media connection response", { statusCode: 502 });
206
+ const node = {
207
+ hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs }) => ({
208
+ hostname: attrs.hostname,
209
+ maxContentLengthBytes: +attrs.maxContentLengthBytes,
210
+ })),
211
+ auth: mediaConnNode.attrs.auth,
212
+ ttl: +mediaConnNode.attrs.ttl,
213
+ fetchDate: new Date(),
214
+ };
215
+ logger.debug("fetched media conn");
216
+ return node;
217
+ })();
218
+ mediaConn = next;
219
+ try {
220
+ const result = await next;
221
+ if (mediaConn === next && result.hosts[0]?.hostname) mediaHost = result.hosts[0].hostname;
222
+ return result;
223
+ } catch (error) {
224
+ if (mediaConn === next) mediaConn = undefined;
225
+ throw error;
213
226
  }
214
- return mediaConn;
215
227
  };
216
228
  /**
217
229
  * generic send receipt function
@@ -467,38 +479,33 @@ export const makeMessagesSocket = (config) => {
467
479
  const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
468
480
  const jidsRequiringFetch = [];
469
481
  logger.debug({ jids }, "assertSessions call with jids");
470
- // Check peerSessionsCache and validate sessions using libsignal loadSession
482
+ // Validate against the current store each time: a cached 'true' may be
483
+ // stale after a peer's identity or Signal session changes.
471
484
  for (const jid of uniqueJids) {
472
- const signalId = signalRepository.jidToSignalProtocolAddress(jid);
473
- const cachedSession = peerSessionsCache.get(signalId);
474
- if (cachedSession !== undefined) {
475
- if (cachedSession && !force) {
476
- continue; // Session exists in cache
477
- }
478
- } else {
485
+ if (!force) {
479
486
  const sessionValidation = await signalRepository.validateSession(jid);
480
- const hasSession = sessionValidation.exists;
481
- peerSessionsCache.set(signalId, hasSession);
482
- if (hasSession && !force) {
483
- continue;
484
- }
487
+ if (sessionValidation.exists) continue;
485
488
  }
486
489
  jidsRequiringFetch.push(jid);
487
490
  }
488
491
  if (jidsRequiringFetch.length) {
489
- // LID if mapped, otherwise original
490
- const wireJids = [
491
- ...jidsRequiringFetch.filter(
492
- (jid) => !!isLidUser(jid) || !!isHostedLidUser(jid),
493
- ),
494
- ...(
495
- (await signalRepository.lidMapping.getLIDsForPNs(
496
- jidsRequiringFetch.filter(
497
- (jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
498
- ),
499
- )) || []
500
- ).map((a) => a.lid),
501
- ];
492
+ // Prefer each resolved LID, but retain a PN when no mapping was returned.
493
+ // Otherwise a partial/missing LID lookup silently produced an empty or
494
+ // incomplete encrypt query despite the 'otherwise original' contract.
495
+ const pns = jidsRequiringFetch.filter(
496
+ (jid) => !!isPnUser(jid) || !!isHostedPnUser(jid),
497
+ );
498
+ const mappings = pns.length
499
+ ? (await signalRepository.lidMapping.getLIDsForPNs(pns)) || []
500
+ : [];
501
+ const lidsByPn = new Map(mappings.filter((a) => a?.pn && a?.lid).map((a) => [a.pn, a.lid]));
502
+ const wireJids = [...new Set([
503
+ ...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
504
+ ...pns.map((jid) => lidsByPn.get(jid) || jid),
505
+ ])];
506
+ if (!wireJids.length) {
507
+ throw new Boom("No supported recipient JIDs for session query", { statusCode: 400 });
508
+ }
502
509
  logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
503
510
  const result = await query({
504
511
  tag: "iq",
@@ -521,11 +528,6 @@ export const makeMessagesSocket = (config) => {
521
528
  });
522
529
  await parseAndInjectE2ESessions(result, signalRepository);
523
530
  didFetchNewSession = true;
524
- // Cache fetched sessions using wire JIDs
525
- for (const wireJid of wireJids) {
526
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
527
- peerSessionsCache.set(signalId, true);
528
- }
529
531
  }
530
532
  return didFetchNewSession;
531
533
  };
@@ -1218,6 +1220,8 @@ export const makeMessagesSocket = (config) => {
1218
1220
  bibz,
1219
1221
  readMessages,
1220
1222
  refreshMediaConn,
1223
+ // A method survives the object spreads used by the upper socket layers.
1224
+ getMediaHost: () => mediaHost,
1221
1225
  waUploadToServer,
1222
1226
  fetchPrivacySettings,
1223
1227
  sendPeerDataOperationMessage,
@@ -1261,7 +1265,7 @@ export const makeMessagesSocket = (config) => {
1261
1265
  );
1262
1266
  }
1263
1267
  content.directPath = media.directPath;
1264
- content.url = getUrlFromDirectPath(content.directPath);
1268
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1265
1269
  logger.debug(
1266
1270
  { directPath: media.directPath, key: result.key },
1267
1271
  "media update successful",
@@ -1,3 +1,3 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/Socket/mex */
2
2
  import type { BinaryNode } from '../WABinary/index.js';
3
- export declare const executeWMexQuery: <T>(variables: Record<string, unknown>, queryId: string, dataPath: string, query: (node: BinaryNode) => Promise<BinaryNode>, generateMessageTag: () => string) => Promise<T>;
3
+ export declare const executeWMexQuery: <T>(variables: Record<string, unknown>, queryId: string, dataPath: string, query: (node: BinaryNode) => Promise<BinaryNode>, generateMessageTag: () => string, options?: { strictDataPath?: boolean }) => Promise<T>;
package/lib/Socket/mex.js CHANGED
@@ -19,7 +19,7 @@ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
19
19
  ]
20
20
  });
21
21
  };
22
- export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
22
+ export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag, { strictDataPath = false } = {}) => {
23
23
  const result = await wMexQuery(variables, queryId, query, generateMessageTag);
24
24
  const child = getBinaryNodeChild(result, 'result');
25
25
  if (child?.content) {
@@ -27,11 +27,13 @@ export const executeWMexQuery = async (variables, queryId, dataPath, query, gene
27
27
  if (data.errors && data.errors.length > 0) {
28
28
  const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
29
29
  const firstError = data.errors[0];
30
- const errorCode = firstError.extensions?.error_code || 400;
30
+ const rawCode = Number(firstError.extensions?.error_code);
31
+ // WMex can return non-HTTP GraphQL codes; Boom only accepts HTTP errors.
32
+ const errorCode = Number.isInteger(rawCode) && rawCode >= 400 && rawCode <= 599 ? rawCode : 400;
31
33
  throw new Boom(`GraphQL server error: ${errorMessages}`, { statusCode: errorCode, data: firstError });
32
34
  }
33
35
  let response = dataPath ? data?.data?.[dataPath] : data?.data;
34
- if (typeof response === 'undefined' && dataPath && data?.data) {
36
+ if (!strictDataPath && typeof response === 'undefined' && dataPath && data?.data) {
35
37
  const keys = Object.keys(data.data);
36
38
  if (keys.length === 1) {
37
39
  response = data.data[keys[0]];
@@ -0,0 +1,11 @@
1
+ /** @internal Shared WMex queries used by complete and partial sockets. */
2
+ import type { BinaryNode, NewsletterMetadata } from '../index.js';
3
+
4
+ export declare function createNewsletterFollowQueries(
5
+ query: (node: BinaryNode) => Promise<unknown>,
6
+ generateMessageTag: () => string,
7
+ ): {
8
+ newsletterMetadata(type: 'jid' | 'invite', key: string): Promise<NewsletterMetadata | null>;
9
+ newsletterFollow(jid: string): Promise<unknown>;
10
+ newsletterUnfollow(jid: string): Promise<unknown>;
11
+ };
@@ -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
  };