lordceaser-baileys 3.3.8 → 3.4.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/WAProto/index.js +1 -2
  2. package/index.js +4 -16
  3. package/lib/Socket/Client/index.js +0 -1
  4. package/lib/Socket/Client/types.js +1 -2
  5. package/lib/Socket/Client/websocket.js +1 -2
  6. package/lib/Socket/business.js +70 -42
  7. package/lib/Socket/chats.js +731 -21
  8. package/lib/Socket/communities.js +1 -1
  9. package/lib/Socket/groups.js +207 -5
  10. package/lib/Socket/index.js +28 -3
  11. package/lib/Socket/messages-recv.js +381 -9
  12. package/lib/Socket/messages-send.js +2189 -157
  13. package/lib/Socket/mex.js +1 -2
  14. package/lib/Socket/newsletter.js +98 -19
  15. package/lib/Socket/socket.js +64 -17
  16. package/lib/Utils/crypto.js +6 -5
  17. package/lib/Utils/lt-hash.js +3 -8
  18. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -3
  19. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +1 -2
  20. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -2
  21. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +1 -2
  22. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +2 -3
  23. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -2
  24. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +1 -2
  25. package/lib/WAUSync/Protocols/index.js +7 -1
  26. package/lib/WAUSync/USyncQuery.js +126 -23
  27. package/lib/WAUSync/USyncUser.js +24 -1
  28. package/lib/WAUSync/index.js +1 -2
  29. package/package.json +2 -6
  30. package/lib/Socket/Socket/Client/index.js +0 -2
  31. package/lib/Socket/Socket/Client/types.js +0 -10
  32. package/lib/Socket/Socket/Client/websocket.js +0 -53
  33. package/lib/Socket/Socket/business.js +0 -407
  34. package/lib/Socket/Socket/chats.js +0 -1908
  35. package/lib/Socket/Socket/communities.js +0 -431
  36. package/lib/Socket/Socket/groups.js +0 -549
  37. package/lib/Socket/Socket/index.js +0 -37
  38. package/lib/Socket/Socket/messages-recv.js +0 -2144
  39. package/lib/Socket/Socket/messages-send.js +0 -3177
  40. package/lib/Socket/Socket/mex.js +0 -41
  41. package/lib/Socket/Socket/newsletter.js +0 -260
  42. package/lib/Socket/Socket/socket.js +0 -1017
  43. package/lib/Utils/_crypto_orig.js +0 -118
  44. package/lib/WAUSync/WAUSync/Protocols/USyncContactProtocol.js +0 -56
  45. package/lib/WAUSync/WAUSync/Protocols/USyncDeviceProtocol.js +0 -53
  46. package/lib/WAUSync/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -26
  47. package/lib/WAUSync/WAUSync/Protocols/USyncStatusProtocol.js +0 -37
  48. package/lib/WAUSync/WAUSync/Protocols/USyncUsernameProtocol.js +0 -24
  49. package/lib/WAUSync/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -50
  50. package/lib/WAUSync/WAUSync/Protocols/UsyncLIDProtocol.js +0 -28
  51. package/lib/WAUSync/WAUSync/Protocols/index.js +0 -12
  52. package/lib/WAUSync/WAUSync/USyncQuery.js +0 -201
  53. package/lib/WAUSync/WAUSync/USyncUser.js +0 -54
  54. package/lib/WAUSync/WAUSync/index.js +0 -3
  55. /package/lib/Socket/{Socket/aigroups.js → aigroups.js} +0 -0
  56. /package/lib/Socket/{Socket/ban-checker.js → ban-checker.js} +0 -0
  57. /package/lib/Socket/{Socket/chats.js[old] → chats.js[old]} +0 -0
  58. /package/lib/Socket/{Socket/graphql.js → graphql.js} +0 -0
  59. /package/lib/Socket/{Socket/groups.js[old] → groups.js[old]} +0 -0
  60. /package/lib/Socket/{Socket/interactive-handler.js → interactive-handler.js} +0 -0
  61. /package/lib/Socket/{Socket/interop.js → interop.js} +0 -0
  62. /package/lib/Socket/{Socket/managed-account.js → managed-account.js} +0 -0
  63. /package/lib/Socket/{Socket/privacy.js → privacy.js} +0 -0
  64. /package/lib/Socket/{Socket/registration.js → registration.js} +0 -0
  65. /package/lib/Socket/{Socket/username.js → username.js} +0 -0
  66. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncBusinessProtocol.js +0 -0
  67. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncFeatureProtocol.js +0 -0
  68. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncPictureProtocol.js +0 -0
  69. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncSidelistProtocol.js +0 -0
  70. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncTextStatusProtocol.js +0 -0
@@ -1,28 +1,24 @@
1
1
  import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
4
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES, WA_ADV_HOSTED_KEY_INDEX_LIST_SIG_PREFIX, WA_ADV_KEY_INDEX_LIST_SIG_PREFIX } from '../Defaults/index.js';
5
5
  import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
6
  import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
7
+ import { chatModificationToAppPatch, Curve, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { generateProfilePictureHD } from '../Utils/messages-media.js';
8
9
  import { makeMutex } from '../Utils/make-mutex.js';
9
10
  import processMessage from '../Utils/process-message.js';
10
11
  import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
13
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
14
  import { makeSocket } from './socket.js';
14
- export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
15
- const picture = { tag: 'picture', attrs: { type, query: 'url' } };
16
- if (tcTokenContent?.length) {
17
- picture.content = tcTokenContent;
18
- }
19
- return [picture];
20
- };
21
15
  export const makeChatsSocket = (config) => {
22
16
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
23
17
  const sock = makeSocket(config);
24
18
  const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
25
19
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
20
+ // Cache newsletter messageId → server_id so quoted posts can be enriched later
21
+ const _nlServerIdCache = new Map();
26
22
  let privacySettings;
27
23
  /** Server-assigned AB props for protocol behavior. */
28
24
  const serverProps = {
@@ -143,6 +139,609 @@ export const makeChatsSocket = (config) => {
143
139
  ]
144
140
  });
145
141
  };
142
+ const getStatusPrivacy = async () => {
143
+ const result = await query({
144
+ tag: 'iq',
145
+ attrs: {
146
+ xmlns: 'status',
147
+ to: S_WHATSAPP_NET,
148
+ type: 'get'
149
+ },
150
+ content: [{ tag: 'privacy', attrs: {} }]
151
+ });
152
+ const privacyNode = result?.content?.[0];
153
+ if (!privacyNode)
154
+ return null;
155
+ const lists = [];
156
+ for (const listNode of privacyNode.content || []) {
157
+ const { type, id, listname, emoji, selected, deleted } = listNode.attrs || {};
158
+ const members = (listNode.content || []).map(u => u.attrs?.jid).filter(Boolean);
159
+ lists.push({ type, id, listname, emoji, selected: selected === 'true', deleted: deleted === 'true', members });
160
+ }
161
+ return lists;
162
+ };
163
+ /**
164
+ * Set status privacy via `xmlns="status"` IQ SET.
165
+ * Supports simple distribution types and contact-level whitelist/blacklist/customlist.
166
+ *
167
+ * @param {'contacts'|'whitelist'|'blacklist'|'null'} type - Distribution type
168
+ * @param {string[]} [jids] - JIDs for the list (whitelist/blacklist)
169
+ * @param {Array<{id: string, listname: string, emoji?: string, selected?: boolean, deleted?: boolean, members?: string[]}>} [customLists]
170
+ */
171
+ const setStatusPrivacy = async (type, jids = [], customLists = []) => {
172
+ const content = [];
173
+ // main distribution list
174
+ const mainList = {
175
+ tag: 'list',
176
+ attrs: { type },
177
+ content: jids.map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
178
+ };
179
+ content.push(mainList);
180
+ // custom named lists
181
+ for (const cl of customLists) {
182
+ const attrs = { type: 'customlist', id: cl.id, listname: cl.listname };
183
+ if (cl.emoji)
184
+ attrs.emoji = cl.emoji;
185
+ if (cl.selected)
186
+ attrs.selected = 'true';
187
+ if (cl.deleted)
188
+ attrs.deleted = 'true';
189
+ content.push({
190
+ tag: 'list',
191
+ attrs,
192
+ content: (cl.members || []).map(jid => ({ tag: 'user', attrs: { jid }, content: [] }))
193
+ });
194
+ }
195
+ await query({
196
+ tag: 'iq',
197
+ attrs: {
198
+ xmlns: 'status',
199
+ to: S_WHATSAPP_NET,
200
+ type: 'set'
201
+ },
202
+ content: [{ tag: 'privacy', attrs: {}, content }]
203
+ });
204
+ };
205
+ /**
206
+ * Fetch broadcast list quota from the server (xmlns="w:biz").
207
+ *
208
+ * Returns: { messagesLeft, totalLimit, isHeavySender, startTs, endTs, resetTs }
209
+ */
210
+ const fetchBroadcastListQuota = async () => {
211
+ const result = await query({
212
+ tag: 'iq',
213
+ attrs: {
214
+ xmlns: 'w:biz',
215
+ to: S_WHATSAPP_NET,
216
+ type: 'get'
217
+ },
218
+ content: [{ tag: 'broadcast_list_quota', attrs: {}, content: [] }]
219
+ }, 32000);
220
+ const limitsNode = getBinaryNodeChild(result, 'limits');
221
+ const timeframeNode = getBinaryNodeChild(result, 'timeframe');
222
+ if (!limitsNode)
223
+ return null;
224
+ return {
225
+ messagesLeft: parseInt(limitsNode.attrs?.messages_left ?? getBinaryNodeChild(limitsNode, 'messages_left')?.content ?? '0', 10),
226
+ totalLimit: parseInt(limitsNode.attrs?.total_limit ?? getBinaryNodeChild(limitsNode, 'total_limit')?.content ?? '0', 10),
227
+ isHeavySender: (limitsNode.attrs?.is_heavy_sender ?? getBinaryNodeChild(limitsNode, 'is_heavy_sender')?.content) === 'true',
228
+ startTs: parseInt(timeframeNode?.attrs?.start_ts_s ?? getBinaryNodeChild(timeframeNode, 'start_ts_s')?.content ?? '0', 10),
229
+ endTs: parseInt(timeframeNode?.attrs?.end_ts_s ?? getBinaryNodeChild(timeframeNode, 'end_ts_s')?.content ?? '0', 10),
230
+ resetTs: parseInt(timeframeNode?.attrs?.reset_ts_s ?? getBinaryNodeChild(timeframeNode, 'reset_ts_s')?.content ?? '0', 10)
231
+ };
232
+ };
233
+ /**
234
+ * Get the global chat-blocking status (block messages from unknown accounts).
235
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockGetRPC (xmlns `w:comms:chat`).
236
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>}
237
+ */
238
+ const getChatBlockingStatus = async () => {
239
+ const result = await query({
240
+ tag: 'iq',
241
+ attrs: {
242
+ to: S_WHATSAPP_NET,
243
+ xmlns: 'w:comms:chat',
244
+ type: 'get'
245
+ },
246
+ content: [{ tag: 'query', attrs: {}, content: [{ tag: 'blocking_status', attrs: {} }] }]
247
+ });
248
+ const blocking = getBinaryNodeChild(result, 'blocking') ||
249
+ getBinaryNodeChild(getBinaryNodeChild(result, 'query'), 'blocking');
250
+ return blocking?.attrs?.status;
251
+ };
252
+ /**
253
+ * Set the global chat-blocking status (block messages from unknown accounts).
254
+ * Ported from WhatsApp Web's WASmaxPsaChatBlockSetRPC (xmlns `w:comms:chat`).
255
+ * @param {'block' | 'unblock'} action
256
+ * @returns {Promise<'blocked' | 'unblocked' | undefined>} the resulting status
257
+ */
258
+ const updateChatBlockingStatus = async (action) => {
259
+ const result = await query({
260
+ tag: 'iq',
261
+ attrs: {
262
+ to: S_WHATSAPP_NET,
263
+ xmlns: 'w:comms:chat',
264
+ type: 'set'
265
+ },
266
+ content: [{ tag: 'blocking', attrs: { action } }]
267
+ });
268
+ const blocking = getBinaryNodeChild(result, 'blocking');
269
+ return blocking?.attrs?.status;
270
+ };
271
+ /**
272
+ * Get the user's pending TOS disclosures / notices (xmlns="tos").
273
+ * @param {number} [t] last-seen disclosure timestamp
274
+ * @returns {Promise<Array<Record<string, string>>>} the `<notice>` attributes
275
+ */
276
+ const getUserDisclosures = async (t = 0) => {
277
+ const result = await query({
278
+ tag: 'iq',
279
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'tos', type: 'get' },
280
+ content: [{ tag: 'get_user_disclosures', attrs: { t: String(t) } }]
281
+ });
282
+ return getBinaryNodeChildren(result, 'notice').map(n => ({ ...n.attrs }));
283
+ };
284
+ /**
285
+ * Accept a TOS/disclosure notice (`xmlns="tos"` set with `<trackable>`).
286
+ * @param {string} noticeId the notice id (e.g. "20250211")
287
+ * @param {string|number} result the result code (e.g. "105")
288
+ */
289
+ const acceptTosNotice = async (noticeId, result = '105') => {
290
+ await query({
291
+ tag: 'iq',
292
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'tos', type: 'set' },
293
+ content: [{ tag: 'trackable', attrs: { id: String(noticeId), result: String(result) } }]
294
+ });
295
+ };
296
+ /**
297
+ * Report spam for a chat/group with sample messages (xmlns="spam").
298
+ * @param {string} jid the JID of the chat or group being reported
299
+ * @param {Array<{id:string, from:string, t:number}>} messages up to ~5 recent messages as evidence
300
+ * @param {string} [spamFlow] e.g. "group_info_report" or "contact_info_report"
301
+ * @param {string} [subject] human-readable subject string (group name or contact name)
302
+ */
303
+ const reportSpam = async (jid, messages, spamFlow = 'contact_info_report', subject) => {
304
+ const msgNodes = (messages || []).map(m => ({
305
+ tag: 'message',
306
+ attrs: {
307
+ from: String(jid),
308
+ t: String(m.t),
309
+ id: String(m.id)
310
+ }
311
+ }));
312
+ await query({
313
+ tag: 'iq',
314
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'spam', type: 'set' },
315
+ content: [
316
+ {
317
+ tag: 'spam_list',
318
+ attrs: {
319
+ jid: String(jid),
320
+ spam_flow: String(spamFlow),
321
+ ...(subject ? { subject: String(subject) } : {})
322
+ },
323
+ content: msgNodes
324
+ }
325
+ ]
326
+ });
327
+ };
328
+ /** Report a user through WhatsApp's w:report IQ endpoint. */
329
+ const reportUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
330
+ const resolvedJid = jidNormalizedUser(jid);
331
+ const reasonCodes = { spam: 1, harassment: 2, impersonation: 3, scam: 4, other: 5 };
332
+ const node = {
333
+ tag: 'iq',
334
+ attrs: { id: generateMessageTag(), xmlns: 'w:report', to: S_WHATSAPP_NET.replace(/^@/, ''), type: 'set' },
335
+ content: [{ tag: 'user', attrs: { jid: resolvedJid, reason: String(reasonCodes[reason] || 1) } }]
336
+ };
337
+ try {
338
+ await query(node, waitForAckMs);
339
+ logger.info({ jid: resolvedJid, reason }, 'reported user (ack received)');
340
+ return true;
341
+ }
342
+ catch (error) {
343
+ const statusCode = error?.output?.statusCode || error?.statusCode;
344
+ if (statusCode === 408 || error?.message?.toLowerCase?.().includes('timed out')) {
345
+ logger.warn({ jid: resolvedJid, reason }, 'reported user (no ack; request likely sent)');
346
+ return false;
347
+ }
348
+ throw error;
349
+ }
350
+ };
351
+ /** Report one message through WhatsApp's w:report IQ endpoint. */
352
+ const reportMessage = async (jid, messageId, reason = 'spam', participantJid, waitForAckMs = 5000) => {
353
+ const resolvedJid = jidNormalizedUser(jid);
354
+ const participant = participantJid ? jidNormalizedUser(participantJid) : undefined;
355
+ const reasonCodes = { spam: 1, harassment: 2, impersonation: 3, scam: 4, other: 5 };
356
+ const attrs = { id: String(messageId), reason: String(reasonCodes[reason] || 1) };
357
+ if (participant) attrs.participant = participant;
358
+ const node = {
359
+ tag: 'iq',
360
+ attrs: { id: generateMessageTag(), xmlns: 'w:report', to: S_WHATSAPP_NET.replace(/^@/, ''), type: 'set' },
361
+ content: [{ tag: 'message', attrs }]
362
+ };
363
+ try {
364
+ await query(node, waitForAckMs);
365
+ logger.info({ jid: resolvedJid, messageId, reason, participant }, 'reported message (ack received)');
366
+ return true;
367
+ }
368
+ catch (error) {
369
+ const statusCode = error?.output?.statusCode || error?.statusCode;
370
+ if (statusCode === 408 || error?.message?.toLowerCase?.().includes('timed out')) {
371
+ logger.warn({ jid: resolvedJid, messageId, reason, participant }, 'reported message (no ack; request likely sent)');
372
+ return false;
373
+ }
374
+ throw error;
375
+ }
376
+ };
377
+ const reportAndBlockUser = async (jid, reason = 'spam', waitForAckMs = 5000) => {
378
+ const resolvedJid = jidNormalizedUser(jid);
379
+ const acknowledged = await reportUser(resolvedJid, reason, waitForAckMs);
380
+ await updateBlockStatus(resolvedJid, 'block');
381
+ return acknowledged;
382
+ };
383
+ /** Toggle group member-share-history mode through the MEX endpoint. */
384
+ const toggleGroupHistory = async (jid, enable = true) => {
385
+ if (!jid) throw new Boom('toggleGroupHistory requires a group JID', { statusCode: 400 });
386
+ return query({
387
+ tag: 'iq',
388
+ attrs: { type: 'get', to: S_WHATSAPP_NET, xmlns: 'w:mex' },
389
+ content: [{
390
+ tag: 'query',
391
+ attrs: { query_id: '24688994337458819' },
392
+ content: Buffer.from(JSON.stringify({
393
+ variables: {
394
+ group_id: jid,
395
+ input: { member_share_group_history_mode: enable ? 'ALL_MEMBER_SHARE' : 'ADMIN_SHARE' }
396
+ }
397
+ }), 'utf-8')
398
+ }]
399
+ });
400
+ };
401
+ /**
402
+ * Get the account opt-out list (`optoutlist` IQ). Returns the raw result node.
403
+ */
404
+ const getOptOutList = async () => {
405
+ return query({
406
+ tag: 'iq',
407
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'optoutlist', type: 'get' }
408
+ });
409
+ };
410
+ /**
411
+ * Sign a blinded credential for privacy-preserving anonymous stats (xmlns `privatestats`).
412
+ * @param {Buffer} blindedCredential 32-byte blinded credential
413
+ * @returns {Promise<Buffer|undefined>} signed credential bytes from server
414
+ */
415
+ const signPrivateCredential = async (blindedCredential) => {
416
+ const result = await query({
417
+ tag: 'iq',
418
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'privatestats', type: 'get' },
419
+ content: [
420
+ {
421
+ tag: 'sign_credential',
422
+ attrs: { version: '1' },
423
+ content: [{ tag: 'blinded_credential', attrs: {}, content: blindedCredential }]
424
+ }
425
+ ]
426
+ });
427
+ const signedNode = getBinaryNodeChild(result, 'sign_credential');
428
+ const signedBytes = getBinaryNodeChild(signedNode, 'signed_credential');
429
+ return signedBytes?.content instanceof Uint8Array ? Buffer.from(signedBytes.content) : undefined;
430
+ };
431
+ /**
432
+ * Get push-notification settings (`urn:xmpp:whatsapp:push`).
433
+ */
434
+ const getPushConfig = async () => {
435
+ const result = await query({
436
+ tag: 'iq',
437
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'get' },
438
+ content: [{ tag: 'settings', attrs: {} }]
439
+ });
440
+ return getBinaryNodeChild(result, 'settings');
441
+ };
442
+ /**
443
+ * Set push-notification config (`urn:xmpp:whatsapp:push`). Mainly web push —
444
+ * pass the FCM-style config (platform / endpoint / auth / p256dh).
445
+ * @param {Record<string, string>} config
446
+ */
447
+ const setPushConfig = async (config) => {
448
+ await query({
449
+ tag: 'iq',
450
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'urn:xmpp:whatsapp:push', type: 'set' },
451
+ content: [{ tag: 'config', attrs: config }]
452
+ });
453
+ };
454
+ /**
455
+ * Toggle the waiting room for a call link.
456
+ * @param {string} linkToken call-link token
457
+ * @param {boolean} enabled whether the waiting room is on
458
+ * @param {string} [media] "audio" | "video"
459
+ */
460
+ const toggleCallLinkWaitingRoom = async (linkToken, enabled, media = 'audio') => {
461
+ const result = await query({
462
+ tag: 'call',
463
+ attrs: { id: generateMessageTag(), to: '@call' },
464
+ content: [
465
+ {
466
+ tag: 'waiting_room_toggle',
467
+ attrs: { enabled: enabled ? '1' : '0', 'link-token': linkToken, media }
468
+ }
469
+ ]
470
+ });
471
+ const child = getBinaryNodeChild(result, 'waiting_room_toggle');
472
+ return child?.attrs;
473
+ };
474
+ /**
475
+ * Store privacy tokens received from a usync response per-contact.
476
+ * @param {Array<{jid: string, privacyToken: Buffer, privacyModeTs: number|string}>} entries
477
+ */
478
+ const storePrivacyTokens = async (entries) => {
479
+ if (!entries?.length)
480
+ return;
481
+ const write = {};
482
+ for (const { jid, privacyToken, privacyModeTs } of entries) {
483
+ if (!jid || !privacyToken?.length)
484
+ continue;
485
+ write[jid] = {
486
+ token: Buffer.isBuffer(privacyToken) ? privacyToken : Buffer.from(privacyToken),
487
+ ts: String(privacyModeTs || '')
488
+ };
489
+ }
490
+ if (Object.keys(write).length) {
491
+ await authState.keys.set({ 'privacy-token': write });
492
+ }
493
+ };
494
+ /**
495
+ * Wrapper around sock.executeUSyncQuery that automatically persists any per-contact
496
+ * privacy tokens (privacy_mode_ts + privacy_token) present in the usync result list,
497
+ * and emits contacts.update for any entries flagged isBlockedByContact.
498
+ * @param {import('../WAUSync/USyncQuery.js').USyncQuery} usyncQuery
499
+ */
500
+ const executeUSyncQuery = async (usyncQuery) => {
501
+ const result = await sock.executeUSyncQuery(usyncQuery);
502
+ if (!result)
503
+ return result;
504
+ // auto-persist privacy tokens found in any usync response
505
+ const privacyEntries = [];
506
+ const blockedContacts = [];
507
+ for (const entry of [...(result.list || []), ...(result.sideList || [])]) {
508
+ if (entry.privacy?.token) {
509
+ privacyEntries.push({
510
+ jid: entry.id,
511
+ privacyToken: entry.privacy.token,
512
+ privacyModeTs: entry.privacy.modeTs
513
+ });
514
+ }
515
+ // emit contacts.update for contacts that blocked us
516
+ if (entry.isBlockedByContact) {
517
+ blockedContacts.push({ id: entry.id, isBlockedByContact: true });
518
+ }
519
+ }
520
+ if (privacyEntries.length) {
521
+ storePrivacyTokens(privacyEntries).catch(err => logger.warn({ err }, 'failed to store privacy tokens from usync'));
522
+ }
523
+ if (blockedContacts.length) {
524
+ ev.emit('contacts.update', blockedContacts);
525
+ }
526
+ return result;
527
+ };
528
+ const updateBioPrivacy = async (value) => {
529
+ await privacyQuery('about', value);
530
+ };
531
+ /**
532
+ * Block a bot JID
533
+ */
534
+ const blockBot = async (botJid) => {
535
+ await query({
536
+ tag: 'iq',
537
+ attrs: {
538
+ xmlns: 'disappearing_mode',
539
+ to: S_WHATSAPP_NET,
540
+ type: 'set'
541
+ },
542
+ content: [
543
+ {
544
+ tag: 'block',
545
+ attrs: { jid: botJid }
546
+ }
547
+ ]
548
+ });
549
+ };
550
+ /**
551
+ * Unblock a bot JID
552
+ */
553
+ const unblockBot = async (botJid) => {
554
+ await updateBlockStatus(botJid, 'unblock');
555
+ };
556
+ const getBotProfile = async (botJid) => {
557
+ const resp = await query({
558
+ tag: 'iq',
559
+ attrs: {
560
+ xmlns: 'bot',
561
+ to: S_WHATSAPP_NET,
562
+ type: 'get'
563
+ },
564
+ content: [
565
+ {
566
+ tag: 'bot',
567
+ attrs: { v: '2', jid: botJid }
568
+ }
569
+ ]
570
+ });
571
+ const botNode = getBinaryNodeChild(resp, 'bot');
572
+ if (!botNode)
573
+ return null;
574
+ return {
575
+ jid: botNode.attrs.jid,
576
+ personaId: botNode.attrs['persona_id'],
577
+ name: botNode.attrs.name,
578
+ description: botNode.attrs.description
579
+ };
580
+ };
581
+ /**
582
+ * Fetch AB-test (abt) props from server (xmlns="abt").
583
+ * @param {string} [protocol] e.g. "1" or "2"
584
+ * @param {string} [hash]
585
+ * @param {string|null} [refreshId]
586
+ * @param {string|null} [group] group-scoped query when set
587
+ */
588
+ const fetchABProps = async (protocol = '1', hash = '', refreshId = null, group = null) => {
589
+ const propAttrs = group != null
590
+ ? { group: String(group) }
591
+ : {
592
+ protocol,
593
+ ...(hash ? { hash } : {}),
594
+ ...(refreshId != null ? { refresh_id: String(refreshId) } : {})
595
+ };
596
+ const result = await query({
597
+ tag: 'iq',
598
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'abt', type: 'get' },
599
+ content: [{ tag: 'props', attrs: propAttrs }]
600
+ });
601
+ const propsNode = getBinaryNodeChild(result, 'props');
602
+ if (!propsNode)
603
+ return {};
604
+ return reduceBinaryNodeToDictionary(propsNode, 'prop');
605
+ };
606
+ /**
607
+ * Remove a companion (linked) device from the account (xmlns="md").
608
+ * @param {string} jid full device JID of the companion to remove
609
+ * @param {string} [reason] e.g. "user_initiated" | "unknown_companion"
610
+ */
611
+ const removeCompanionDevice = async (jid, reason = 'user_initiated') => {
612
+ await query({
613
+ tag: 'iq',
614
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
615
+ content: [
616
+ {
617
+ tag: 'remove-companion-device',
618
+ attrs: { jid, reason }
619
+ }
620
+ ]
621
+ });
622
+ };
623
+ /**
624
+ * Push an updated key-index-list to the server (xmlns="md", child "key-index-list").
625
+ * @param {number|string} ts unix timestamp seconds
626
+ * @param {Buffer} content serialized proto KeyIndexList
627
+ */
628
+ const updateKeyIndexList = async (ts, content) => {
629
+ await query({
630
+ tag: 'iq',
631
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'md', type: 'set' },
632
+ content: [
633
+ {
634
+ tag: 'key-index-list',
635
+ attrs: { ts: String(ts) },
636
+ content
637
+ }
638
+ ]
639
+ });
640
+ };
641
+ /**
642
+ * Build and push the companion's signed key-index-list on (re)connect (xmlns="md").
643
+ * Mirrors CompanionDeviceAdvUtil.A02 from the APK: the details proto is signed with
644
+ * our own device identity key (the same key that produces the ADV deviceSignature).
645
+ */
646
+ const sendKeyIndexList = async () => {
647
+ const account = authState.creds.account;
648
+ const signedIdentityKey = authState.creds.signedIdentityKey;
649
+ if (!account?.details || !signedIdentityKey?.private) {
650
+ logger.debug('no ADV account / signed identity key, skipping key-index-list');
651
+ return;
652
+ }
653
+ const deviceIdentity = proto.ADVDeviceIdentity.decode(account.details);
654
+ const keyIndex = deviceIdentity.keyIndex || 0;
655
+ const accountType = deviceIdentity.accountType ?? proto.ADVEncryptionType.E2EE;
656
+ const isHosted = accountType === proto.ADVEncryptionType.HOSTED;
657
+ const ts = Math.floor(Date.now() / 1000);
658
+ const details = proto.ADVKeyIndexList.encode({
659
+ rawId: deviceIdentity.rawId || 0,
660
+ timestamp: ts,
661
+ currentIndex: keyIndex,
662
+ validIndexes: [keyIndex],
663
+ accountType
664
+ }).finish();
665
+ const sigPrefix = isHosted ? WA_ADV_HOSTED_KEY_INDEX_LIST_SIG_PREFIX : WA_ADV_KEY_INDEX_LIST_SIG_PREFIX;
666
+ const accountSignature = Curve.sign(signedIdentityKey.private, Buffer.concat([sigPrefix, details]));
667
+ const signedKeyIndexList = { details, accountSignature };
668
+ if (isHosted && account.accountSignatureKey?.length) {
669
+ signedKeyIndexList.accountSignatureKey = account.accountSignatureKey;
670
+ }
671
+ const content = proto.ADVSignedKeyIndexList.encode(signedKeyIndexList).finish();
672
+ await updateKeyIndexList(ts, Buffer.from(content));
673
+ logger.info({ ts, keyIndex }, 'sent key-index-list');
674
+ };
675
+ /**
676
+ * Request a media upload connection token from the server (xmlns="w:m").
677
+ * @param {string|null} [lastId]
678
+ */
679
+ const fetchMediaConn = async (lastId = null) => {
680
+ const attrs = {};
681
+ if (lastId != null)
682
+ attrs.last_id = String(lastId);
683
+ const result = await query({
684
+ tag: 'iq',
685
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:m', type: 'set' },
686
+ content: [{ tag: 'media_conn', attrs }]
687
+ });
688
+ return getBinaryNodeChild(result, 'media_conn') || null;
689
+ };
690
+ /**
691
+ * Delete a broadcast list by ID (xmlns="w:b").
692
+ */
693
+ const deleteBroadcastList = async (listId) => {
694
+ await query({
695
+ tag: 'iq',
696
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:b', type: 'set' },
697
+ content: [
698
+ {
699
+ tag: 'delete',
700
+ attrs: {},
701
+ content: [{ tag: 'list', attrs: { id: String(listId) } }]
702
+ }
703
+ ]
704
+ });
705
+ };
706
+ /**
707
+ * Fetch a QR code from the server (e.g. for linked-device linking) (xmlns="w:qr").
708
+ * @param {string} code
709
+ * @param {'lid'|null} [addressingMode] set to "lid" for LID-addressed QR
710
+ */
711
+ const fetchQRCode = async (code, addressingMode = null) => {
712
+ const attrs = { code };
713
+ if (addressingMode)
714
+ attrs.addressing_mode = addressingMode;
715
+ const result = await query({
716
+ tag: 'iq',
717
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'w:qr', type: 'get' },
718
+ content: [{ tag: 'qr', attrs }]
719
+ });
720
+ return getBinaryNodeChild(result, 'qr') || null;
721
+ };
722
+ /**
723
+ * Confirm or deny a device-logout request from the server (xmlns="w:account_defence").
724
+ * @param {string|number} id the challenge id
725
+ * @param {boolean} [approve] true to confirm the logout, false to deny
726
+ */
727
+ const confirmDeviceLogout = async (id, approve = true) => {
728
+ await query({
729
+ tag: 'iq',
730
+ attrs: {
731
+ id: String(id),
732
+ to: S_WHATSAPP_NET,
733
+ xmlns: 'w:account_defence',
734
+ type: 'set',
735
+ smax_id: '87'
736
+ },
737
+ content: [
738
+ {
739
+ tag: 'device_logout',
740
+ attrs: { approve: approve ? 'true' : 'false', id: String(id) }
741
+ }
742
+ ]
743
+ });
744
+ };
146
745
  const getBotListV2 = async () => {
147
746
  const resp = await query({
148
747
  tag: 'iq',
@@ -194,7 +793,37 @@ export const makeChatsSocket = (config) => {
194
793
  return result.list;
195
794
  }
196
795
  };
197
- /** update the profile picture for yourself or a group */
796
+ // Lia@Note 06-02-26 --- Quick helper only. This function exists solely for faster lookup with caching.
797
+ const findUserId = async (pnLid) => {
798
+ const normalizedJid = jidNormalizedUser(pnLid);
799
+ const userId = {
800
+ lid: undefined,
801
+ phoneNumber: undefined
802
+ };
803
+ if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
804
+ userId.phoneNumber = normalizedJid;
805
+ const resolvedLid = (await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid;
806
+ userId.lid = resolvedLid ? jidNormalizedUser(resolvedLid) : undefined;
807
+ }
808
+ else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
809
+ userId.lid = normalizedJid;
810
+ const resolvedPhoneNumber = (await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn;
811
+ userId.phoneNumber = resolvedPhoneNumber ? jidNormalizedUser(resolvedPhoneNumber) : undefined;
812
+ }
813
+ else {
814
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 });
815
+ }
816
+ return userId;
817
+ };
818
+ /** update the profile picture for yourself or a group
819
+ *
820
+ * Standard (crop + resize to 720×720):
821
+ * sock.updateProfilePicture(jid, content)
822
+ * sock.updateProfilePicture(jid, content, { width: 640, height: 640 })
823
+ *
824
+ * HD (full-size, no crop, no resize):
825
+ * sock.updateProfilePicture(jid, content, { hd: true })
826
+ */
198
827
  const updateProfilePicture = async (jid, content, dimensions) => {
199
828
  let targetJid;
200
829
  if (!jid) {
@@ -206,7 +835,12 @@ export const makeChatsSocket = (config) => {
206
835
  else {
207
836
  targetJid = undefined;
208
837
  }
209
- const { img } = await generateProfilePicture(content, dimensions);
838
+ // crysnovax@HD-Profile --- Dual mode:
839
+ // hd:true → generateProfilePictureHD (preserves aspect ratio, caps at 1920, manages file size)
840
+ // standard → generateProfilePicture (720×720 square crop, or custom dimensions)
841
+ const { img } = dimensions?.hd
842
+ ? await generateProfilePictureHD(content)
843
+ : await generateProfilePicture(content, dimensions);
210
844
  await query({
211
845
  tag: 'iq',
212
846
  attrs: {
@@ -248,6 +882,9 @@ export const makeChatsSocket = (config) => {
248
882
  };
249
883
  /** update the profile status for yourself */
250
884
  const updateProfileStatus = async (status) => {
885
+ if (typeof status !== 'string') {
886
+ throw new TypeError('Profile status must be a string');
887
+ }
251
888
  await query({
252
889
  tag: 'iq',
253
890
  attrs: {
@@ -265,6 +902,9 @@ export const makeChatsSocket = (config) => {
265
902
  });
266
903
  };
267
904
  const updateProfileName = async (name) => {
905
+ if (typeof name !== 'string') {
906
+ throw new TypeError('Profile name must be a string');
907
+ }
268
908
  await chatModify({ pushNameSetting: name }, '');
269
909
  };
270
910
  const fetchBlocklist = async () => {
@@ -286,7 +926,7 @@ export const makeChatsSocket = (config) => {
286
926
  if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
287
927
  lid = normalizedJid;
288
928
  if (action === 'block') {
289
- const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
929
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
290
930
  if (!pn) {
291
931
  throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
292
932
  }
@@ -294,7 +934,7 @@ export const makeChatsSocket = (config) => {
294
934
  }
295
935
  }
296
936
  else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
297
- const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
937
+ const mapped = (await findUserId(normalizedJid)).lid;
298
938
  if (!mapped) {
299
939
  throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
300
940
  }
@@ -552,7 +1192,8 @@ export const makeChatsSocket = (config) => {
552
1192
  * type = "preview" for a low res picture
553
1193
  * type = "image for the high res picture"
554
1194
  */
555
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
1195
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = false) => {
1196
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
556
1197
  // WA Web only includes tctoken for user JIDs (not groups/newsletters)
557
1198
  // and never for own profile pic (Chat model for self has no tcToken).
558
1199
  // Including tctoken for own JID causes the server to never respond.
@@ -560,11 +1201,12 @@ export const makeChatsSocket = (config) => {
560
1201
  const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
561
1202
  const me = authState.creds.me;
562
1203
  const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
563
- let tcTokenContent;
564
- if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
565
- tcTokenContent = await buildTcTokenFromJid({
1204
+ let content = baseContent;
1205
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
1206
+ content = await buildTcTokenFromJid({
566
1207
  authState,
567
1208
  jid: normalizedJid,
1209
+ baseContent,
568
1210
  getLIDForPN
569
1211
  });
570
1212
  }
@@ -577,7 +1219,7 @@ export const makeChatsSocket = (config) => {
577
1219
  type: 'get',
578
1220
  xmlns: 'w:profile:picture'
579
1221
  },
580
- content: buildProfilePictureQueryContent(type, tcTokenContent)
1222
+ content
581
1223
  }, timeoutMs);
582
1224
  const child = getBinaryNodeChild(result, 'picture');
583
1225
  return child?.attrs?.url;
@@ -907,6 +1549,26 @@ export const makeChatsSocket = (config) => {
907
1549
  quickReply: { timestamp, deleted: true }
908
1550
  }, '');
909
1551
  };
1552
+ /**
1553
+ * crysnovax@Favorites --- Set complete WhatsApp Favorites list.
1554
+ * Replaces server-side list with the provided array (merging is handled by caller).
1555
+ * @param jids — complete array of JIDs to set as favorites
1556
+ */
1557
+ const addToFavorites = (jids) => {
1558
+ return chatModify({
1559
+ favorites: { jids, add: true }
1560
+ }, '');
1561
+ };
1562
+ /**
1563
+ * crysnovax@Favorites --- Remove all favorites (clear list).
1564
+ */
1565
+ const removeFromFavorites = (jids) => {
1566
+ // For single removal, caller must pass remaining list to addToFavorites
1567
+ // This sends the provided jids array (should be remaining items after filter)
1568
+ return chatModify({
1569
+ favorites: { jids, add: true }
1570
+ }, '');
1571
+ };
910
1572
  /**
911
1573
  * queries need to be fired on connection open
912
1574
  * help ensure parity with WA Web
@@ -914,7 +1576,21 @@ export const makeChatsSocket = (config) => {
914
1576
  const executeInitQueries = async () => {
915
1577
  await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
916
1578
  };
1579
+
917
1580
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
1581
+ // Cache newsletter server_id for use when this message is later quoted
1582
+ if (msg.newsletter && msg.newsletter_server_id && msg.key?.id) {
1583
+ _nlServerIdCache.set(msg.key.id, msg.newsletter_server_id);
1584
+ }
1585
+ // If this message quotes a newsletter post, enrich it with the cached server_id
1586
+ if (msg.message) {
1587
+ const ci = Object.values(msg.message).find(v => v?.contextInfo)?.contextInfo;
1588
+ if (ci?.stanzaId && isJidNewsletter(ci.remoteJid)) {
1589
+ const sid = _nlServerIdCache.get(ci.stanzaId);
1590
+ if (sid != null)
1591
+ msg.quotedNewsletterServerId = sid;
1592
+ }
1593
+ }
918
1594
  ev.emit('messages.upsert', { messages: [msg], type });
919
1595
  if (!!msg.pushName) {
920
1596
  let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
@@ -1147,6 +1823,7 @@ export const makeChatsSocket = (config) => {
1147
1823
  });
1148
1824
  return {
1149
1825
  ...sock,
1826
+ findUserId,
1150
1827
  serverProps,
1151
1828
  createCallLink,
1152
1829
  getBotListV2,
@@ -1178,6 +1855,37 @@ export const makeChatsSocket = (config) => {
1178
1855
  updateReadReceiptsPrivacy,
1179
1856
  updateGroupsAddPrivacy,
1180
1857
  updateDefaultDisappearingMode,
1858
+ getStatusPrivacy,
1859
+ setStatusPrivacy,
1860
+ fetchBroadcastListQuota,
1861
+ getChatBlockingStatus,
1862
+ updateChatBlockingStatus,
1863
+ getUserDisclosures,
1864
+ acceptTosNotice,
1865
+ reportSpam,
1866
+ reportUser,
1867
+ reportMessage,
1868
+ reportAndBlockUser,
1869
+ toggleGroupHistory,
1870
+ getOptOutList,
1871
+ signPrivateCredential,
1872
+ getPushConfig,
1873
+ setPushConfig,
1874
+ toggleCallLinkWaitingRoom,
1875
+ storePrivacyTokens,
1876
+ executeUSyncQuery,
1877
+ updateBioPrivacy,
1878
+ blockBot,
1879
+ unblockBot,
1880
+ getBotProfile,
1881
+ fetchABProps,
1882
+ removeCompanionDevice,
1883
+ updateKeyIndexList,
1884
+ sendKeyIndexList,
1885
+ fetchMediaConn,
1886
+ deleteBroadcastList,
1887
+ fetchQRCode,
1888
+ confirmDeviceLogout,
1181
1889
  getBusinessProfile,
1182
1890
  resyncAppState,
1183
1891
  chatModify,
@@ -1192,7 +1900,9 @@ export const makeChatsSocket = (config) => {
1192
1900
  removeMessageLabel,
1193
1901
  star,
1194
1902
  addOrEditQuickReply,
1195
- removeQuickReply
1903
+ removeQuickReply,
1904
+ addToFavorites,
1905
+ removeFromFavorites,
1906
+ newsletterServerIdCache: _nlServerIdCache
1196
1907
  };
1197
1908
  };
1198
- //# sourceMappingURL=chats.js.map