@jexkcode/baileys 1.3.0 → 1.3.2

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.
@@ -2,7 +2,7 @@ import { proto } from '../../WAProto/index.js';
2
2
  import { makeLibSignalRepository } from '../Signal/libsignal.js';
3
3
  import { Browsers } from '../Utils/browser-utils.js';
4
4
  import logger from '../Utils/logger.js';
5
- const version = [2, 3000, 1043857760];
5
+ const version = [2, 3000, 1054623785];
6
6
  export const UNAUTHORIZED_CODES = [401, 403, 419];
7
7
  export const BIZ_BOT_SUPPORT_PAYLOAD = '{"version":1,"is_ai_message":true,"should_upload_client_logs":false,"should_show_system_message":false,"ticket_id":"7004947587700716","citation_items":[],"ticket_locale":"us"}';
8
8
  export const DEFAULT_ORIGIN = 'https://web.whatsapp.com';
@@ -7,7 +7,7 @@ import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT, PLACEHOLDER_MAX_
7
7
  import { ReachoutTimelockEnforcementType, WAMessageStatus, WAMessageStubType } from '../Types/index.js';
8
8
  import { ACCOUNT_RESTRICTED_TEXT, aesDecryptCTR, aesEncryptGCM, cleanMessage, Curve, decodeMediaRetryNode, decodeMessageNode, decryptMessageNode, delay, derivePairingCodeKey, encodeBigEndian, encodeSignedDeviceIdentity, extractAddressingContext, extractE2ESessionFromRetryReceipt, getCallStatusFromNode, getHistoryMsg, getNextPreKeys, getStatusFromReceiptType, handleIdentityChange, hkdf, MISSING_KEYS_ERROR_TEXT, NACK_REASONS, NO_MESSAGE_FOUND_ERROR_TEXT, SERVER_ERROR_CODES, toNumber, unixTimestampSeconds, xmppPreKey, xmppSignedPreKey } from '../Utils/index.js';
9
9
  import { makeMutex } from '../Utils/make-mutex.js';
10
- import { makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
10
+ import { isOfflineNode, makeOfflineNodeProcessor } from '../Utils/offline-node-processor.js';
11
11
  import { buildAckStanza } from '../Utils/stanza-ack.js';
12
12
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, readTcTokenIndex, resolveIssuanceJid, resolveTcTokenJid, storeTcTokensFromIqResult, TC_TOKEN_INDEX_KEY } from '../Utils/tc-token-utils.js';
13
13
  import { areJidsSameUser, binaryNodeToString, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildBuffer, getBinaryNodeChildren, getBinaryNodeChildString, getBinaryNodeChildUInt, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isLidUser, isPnUser, jidDecode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
@@ -36,6 +36,7 @@ export const makeMessagesRecvSocket = (config) => {
36
36
  });
37
37
  // Debounce identity-change session refreshes per JID to avoid bursts
38
38
  const identityAssertDebounce = new NodeCache({ stdTTL: 5, useClones: false });
39
+ const pHashMismatchDebounce = new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, useClones: false });
39
40
  let sendActiveReceipts = false;
40
41
  const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
41
42
  if (!authState.creds.me?.id) {
@@ -878,8 +879,10 @@ export const makeMessagesRecvSocket = (config) => {
878
879
  }
879
880
  }
880
881
  break;
881
- case 'link_code_companion_reg':
882
+ case 'link_code_companion_reg': {
882
883
  const linkCodeCompanionReg = getBinaryNodeChild(node, 'link_code_companion_reg');
884
+ if (linkCodeCompanionReg?.attrs?.stage !== 'primary_hello')
885
+ break;
883
886
  const ref = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_ref'));
884
887
  const primaryIdentityPublicKey = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'primary_identity_pub'));
885
888
  const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(getBinaryNodeChildBuffer(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
@@ -940,6 +943,7 @@ export const makeMessagesRecvSocket = (config) => {
940
943
  authState.creds.registered = true;
941
944
  ev.emit('creds.update', authState.creds);
942
945
  break;
946
+ }
943
947
  case 'privacy_token':
944
948
  await handlePrivacyTokenNotification(node);
945
949
  break;
@@ -1158,6 +1162,44 @@ export const makeMessagesRecvSocket = (config) => {
1158
1162
  }
1159
1163
  }
1160
1164
  };
1165
+ const getCachedMessage = async (key) => {
1166
+ let msg;
1167
+ if (messageRetryManager) {
1168
+ const cachedMsg = messageRetryManager.getRecentMessage(key.remoteJid, key.id);
1169
+ if (cachedMsg) {
1170
+ msg = cachedMsg.message;
1171
+ messageRetryManager.markRetrySuccess(key.id);
1172
+ }
1173
+ }
1174
+ if (!msg) {
1175
+ msg = await getMessage(key);
1176
+ if (msg && messageRetryManager) {
1177
+ messageRetryManager.markRetrySuccess(key.id);
1178
+ }
1179
+ }
1180
+ return msg;
1181
+ };
1182
+ const recoverPHashMismatch = async (key) => {
1183
+ const { remoteJid, id } = key;
1184
+ if (!isJidGroup(remoteJid))
1185
+ return false;
1186
+ if (pHashMismatchDebounce.has(remoteJid))
1187
+ return true;
1188
+ pHashMismatchDebounce.set(remoteJid, true);
1189
+ try {
1190
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
1191
+ logger.info({ key }, 'received phash in ack, resending message...');
1192
+ const msg = await getCachedMessage(key);
1193
+ if (!msg)
1194
+ return false;
1195
+ await relayMessage(remoteJid, msg, { messageId: id, useUserDevicesCache: false });
1196
+ return true;
1197
+ }
1198
+ catch (error) {
1199
+ logger?.error({ err: error }, 'error when handling phash mismatch');
1200
+ return false;
1201
+ }
1202
+ };
1161
1203
  const handleReceipt = async (node) => {
1162
1204
  const { attrs, content } = node;
1163
1205
  const isLid = attrs.from.includes('lid');
@@ -1358,6 +1400,11 @@ export const makeMessagesRecvSocket = (config) => {
1358
1400
  // Don't return — fall through to upsertMessage so the stub is emitted
1359
1401
  }
1360
1402
  else {
1403
+ if (msg.key.fromMe) {
1404
+ logger.debug({ key: msg.key }, 'undecryptable fromMe message: acking without a retry receipt');
1405
+ acked = true;
1406
+ return sendMessageAck(node);
1407
+ }
1361
1408
  // Skip retry for expired status messages (>24h old)
1362
1409
  if (isJidStatusBroadcast(msg.key.remoteJid)) {
1363
1410
  const messageAge = unixTimestampSeconds() - toNumber(msg.messageTimestamp);
@@ -1429,7 +1476,7 @@ export const makeMessagesRecvSocket = (config) => {
1429
1476
  }
1430
1477
  }
1431
1478
  cleanMessage(msg, authState.creds.me.id, authState.creds.me.lid);
1432
- await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
1479
+ await upsertMessage(msg, isOfflineNode(node) ? 'append' : 'notify');
1433
1480
  });
1434
1481
  }
1435
1482
  catch (error) {
@@ -1455,7 +1502,7 @@ export const makeMessagesRecvSocket = (config) => {
1455
1502
  callerPn: infoChild.attrs['caller_pn'],
1456
1503
  id: callId,
1457
1504
  date: new Date(+attrs.t * 1000),
1458
- offline: !!attrs.offline,
1505
+ offline: isOfflineNode(node),
1459
1506
  status
1460
1507
  };
1461
1508
  if (status === 'relaylatency') {
@@ -1493,6 +1540,9 @@ export const makeMessagesRecvSocket = (config) => {
1493
1540
  };
1494
1541
  const handleBadAck = async ({ attrs }) => {
1495
1542
  const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id };
1543
+ if (attrs.phash) {
1544
+ await recoverPHashMismatch(key);
1545
+ }
1496
1546
  // WARNING: REFRAIN FROM ENABLING THIS FOR NOW. IT WILL CAUSE A LOOP
1497
1547
  // // current hypothesis is that if pash is sent in the ack
1498
1548
  // // it means -- the message hasn't reached all devices yet
@@ -1600,7 +1650,7 @@ export const makeMessagesRecvSocket = (config) => {
1600
1650
  await sendMessageAck(node, type === 'message' ? NACK_REASONS.UnhandledError : undefined);
1601
1651
  return;
1602
1652
  }
1603
- const isOffline = !!node.attrs.offline;
1653
+ const isOffline = isOfflineNode(node);
1604
1654
  if (isOffline) {
1605
1655
  offlineNodeProcessor.enqueue(type, node);
1606
1656
  }
@@ -1621,6 +1671,9 @@ export const makeMessagesRecvSocket = (config) => {
1621
1671
  ws.on('CB:notification', async (node) => {
1622
1672
  await processNode('notification', node, 'handling notification', handleNotification);
1623
1673
  });
1674
+ ws.on('CB:status', (node) => {
1675
+ sendMessageAck(node).catch(error => onUnexpectedError(error, 'acking status'));
1676
+ });
1624
1677
  ws.on('CB:ack,class:message', (node) => {
1625
1678
  handleBadAck(node).catch(error => onUnexpectedError(error, 'handling bad ack'));
1626
1679
  });
@@ -3,7 +3,7 @@ import { Boom } from '@hapi/boom';
3
3
  import { randomBytes } from 'crypto';
4
4
  import { proto } from '../../WAProto/index.js';
5
5
  import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, isViewOnceMessage, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
7
  import { AssociationType } from '../Types/index.js';
8
8
  import { getUrlInfo } from '../Utils/link-preview.js';
9
9
  import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
@@ -510,7 +510,8 @@ export const makeMessagesSocket = (config) => {
510
510
  // JexkCode@Update - Add groupStatusMessage attributes
511
511
  const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
512
512
  const isPollUpdate = innerMessage?.pollUpdateMessage;
513
- if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
513
+ const isViewOnce = isViewOnceMessage(message);
514
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate || isViewOnce) {
514
515
  const metaAttrs = {};
515
516
  if (isNeedMetaAttrs) {
516
517
  metaAttrs.content_type = 'add_on';
@@ -521,6 +522,9 @@ export const makeMessagesSocket = (config) => {
521
522
  if (isGroupStatus) {
522
523
  metaAttrs.is_group_status = 'true';
523
524
  }
525
+ if (isViewOnce) {
526
+ metaAttrs.view_once = 'true';
527
+ }
524
528
  binaryNodeContent.push({
525
529
  tag: 'meta',
526
530
  attrs: metaAttrs,
@@ -598,7 +602,6 @@ export const makeMessagesSocket = (config) => {
598
602
  //todo: revamp all this logic
599
603
  // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
600
604
  senderKeyRecipients.push(deviceJid);
601
- senderKeyMap[deviceJid] = true;
602
605
  }
603
606
  }
604
607
  if (senderKeyRecipients.length) {
@@ -614,6 +617,11 @@ export const makeMessagesSocket = (config) => {
614
617
  const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
615
618
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
616
619
  participants.push(...result.nodes);
620
+ for (const { attrs } of result.nodes) {
621
+ if (attrs.jid) {
622
+ senderKeyMap[attrs.jid] = true;
623
+ }
624
+ }
617
625
  }
618
626
  binaryNodeContent.push({
619
627
  tag: 'enc',
@@ -959,7 +967,14 @@ export const makeMessagesSocket = (config) => {
959
967
  return message.videoMessage.gifPlayback ? 'gif' : 'video';
960
968
  }
961
969
  else if (message.stickerMessage) {
962
- return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
970
+ const sticker = message.stickerMessage;
971
+ if (sticker.isLottie)
972
+ return '1p_sticker';
973
+ if (sticker.isAvatar)
974
+ return 'avatar_sticker';
975
+ if (sticker.isAiSticker)
976
+ return 'genai_sticker';
977
+ return 'sticker';
963
978
  }
964
979
  else if (message.audioMessage) {
965
980
  return message.audioMessage.ptt ? 'ptt' : 'audio';
package/lib/Socket/mex.js CHANGED
@@ -18,11 +18,22 @@ const wMexQuery = (variables, queryId, query, generateMessageTag) => {
18
18
  ]
19
19
  });
20
20
  };
21
+ const parseMexPayload = (content) => {
22
+ const raw = typeof content === 'string' ? content : Buffer.from(content).toString('utf-8');
23
+ const start = raw.search(/[{[]/);
24
+ try {
25
+ return JSON.parse(start > 0 ? raw.slice(start) : raw);
26
+ }
27
+ catch (err) {
28
+ const head = (typeof content === 'string' ? Buffer.from(content, 'binary') : Buffer.from(content)).subarray(0, 48).toString('hex');
29
+ throw new Boom(`Respon w:mex bukan JSON valid: ${err.message}`, { statusCode: 500, data: { head } });
30
+ }
31
+ };
21
32
  export const executeWMexQuery = async (variables, queryId, dataPath, query, generateMessageTag) => {
22
33
  const result = await wMexQuery(variables, queryId, query, generateMessageTag);
23
34
  const child = getBinaryNodeChild(result, 'result');
24
35
  if (child?.content) {
25
- const data = JSON.parse(child.content.toString());
36
+ const data = parseMexPayload(child.content);
26
37
  if (data.errors && data.errors.length > 0) {
27
38
  const errorMessages = data.errors.map((err) => err.message || 'Unknown error').join(', ');
28
39
  const firstError = data.errors[0];
@@ -687,7 +687,11 @@ export const makeSocket = (config) => {
687
687
  }
688
688
  });
689
689
  ws.on('error', mapWebSocketError(end));
690
- ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
690
+ ws.on('close', (code, reason) => {
691
+ const reasonText = reason ? String(reason).trim() : '';
692
+ const detail = typeof code === 'number' ? ` (ws close ${code}${reasonText ? `: ${reasonText}` : ''})` : '';
693
+ void end(new Boom(`Connection Terminated${detail}`, { statusCode: DisconnectReason.connectionClosed }));
694
+ });
691
695
  // the server terminated the connection
692
696
  ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
693
697
  // QR gen
@@ -843,7 +847,7 @@ export const makeSocket = (config) => {
843
847
  ev.on('creds.update', update => {
844
848
  const name = update.me?.name;
845
849
  // if name has just been received
846
- if (creds.me?.name !== name) {
850
+ if (typeof name === 'string' && name.length > 0 && creds.me?.name !== name) {
847
851
  logger.debug({ name }, 'updated pushName');
848
852
  sendNode({
849
853
  tag: 'presence',
@@ -245,7 +245,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
245
245
  case 'skmsg':
246
246
  msgBuffer = await repository.decryptGroupMessage({
247
247
  group: sender,
248
- authorJid: author,
248
+ authorJid: decryptionJid,
249
249
  msg: content
250
250
  });
251
251
  break;
@@ -269,7 +269,7 @@ export const decryptMessageNode = (stanza, meId, meLid, repository, logger) => {
269
269
  //eslint-disable-next-line max-depth
270
270
  try {
271
271
  await repository.processSenderKeyDistributionMessage({
272
- authorJid: author,
272
+ authorJid: decryptionJid,
273
273
  item: msg.senderKeyDistributionMessage
274
274
  });
275
275
  }
@@ -452,11 +452,13 @@ const toSmallestChunkSize = (num) => {
452
452
  return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
453
453
  };
454
454
  export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
455
+ const PLACEHOLDER_MEDIA_HOST = 'a.whatsapp.net';
455
456
  const extractHost = (url) => {
456
457
  if (!url)
457
458
  return undefined;
458
459
  try {
459
- return new URL(url).host;
460
+ const host = new URL(url).host;
461
+ return host === PLACEHOLDER_MEDIA_HOST ? undefined : host;
460
462
  }
461
463
  catch {
462
464
  return undefined;
@@ -1567,6 +1567,17 @@ export const generateWAMessage = async (jid, content, options) => {
1567
1567
  return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1568
1568
  };
1569
1569
  /** Get the key to access the true type of content */
1570
+ export const isViewOnceMessage = (message) => {
1571
+ if (message?.viewOnce === true ||
1572
+ message?.viewOnceMessage ||
1573
+ message?.viewOnceMessageV2 ||
1574
+ message?.viewOnceMessageV2Extension)
1575
+ return true;
1576
+ const innerMsg = normalizeMessageContent(message);
1577
+ const msgType = getContentType(innerMsg);
1578
+ const msgCtn = innerMsg?.[msgType];
1579
+ return msgCtn?.viewOnce === true;
1580
+ };
1570
1581
  export const getContentType = (content) => {
1571
1582
  if (content) {
1572
1583
  const keys = Object.keys(content);
@@ -1,3 +1,4 @@
1
+ export const isOfflineNode = (node) => node?.attrs?.offline === '1';
1
2
  /**
2
3
  * Creates a processor for offline stanza nodes that:
3
4
  * - Queues nodes for sequential processing
@@ -129,7 +129,9 @@ const FLOWS_MAP = {
129
129
  send_location: true,
130
130
  call_permission_request: true,
131
131
  wa_payment_transaction_details: true,
132
- automated_greeting_message_view_catalog: true
132
+ automated_greeting_message_view_catalog: true,
133
+ form_message: true,
134
+ payment_key_info: true
133
135
  };
134
136
  const DECISION_SOURCE_CONTENT = [
135
137
  {
@@ -189,7 +191,7 @@ export const getBizBinaryNode = (message) => {
189
191
  content: [
190
192
  {
191
193
  tag: 'native_flow',
192
- attrs: { v: '2', name: firstButtonName }
194
+ attrs: firstButtonName === 'form_message' || firstButtonName === 'payment_key_info' ? { name: firstButtonName } : { v: '2', name: firstButtonName }
193
195
  }
194
196
  ]
195
197
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jexkcode/baileys",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "JexkCode Baileys - Enhanced WhatsApp Web API with interactive messages, albums, newsletter support, and AIRich responses.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",