@rosyn/whats 0.1.2 → 0.1.5

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.
@@ -10,7 +10,7 @@ import pb from "protobufjs/minimal.js";
10
10
  import { RosynWhatsClient } from "../client/index.js";
11
11
  import { downloadContentFromMessage, encryptWaMedia, toBuffer } from "../media/index.js";
12
12
  import { proto } from "../proto/index.js";
13
- import { DisconnectReason, generateMessageIDV2, jidDecode, jidNormalizedUser } from "../protocol/jid.js";
13
+ import { DisconnectReason, generateMessageIDV2, isJidBroadcast, isJidGroup, isJidNewsletter, isLidUser, jidDecode, jidNormalizedUser, } from "../protocol/jid.js";
14
14
  const pbkdf2Async = promisify(pbkdf2);
15
15
  import { decodeWABinaryNode, encodeWABinaryNode } from "../protocol/wabin.js";
16
16
  import { jidToSignalAddress, SignalProtocolManager, toSignalPub33, unpadRandomMax16, writeRandomPadMax16, } from "../signal/protocol.js";
@@ -50,8 +50,13 @@ export async function fetchLatestBaileysVersion() {
50
50
  function reviveBuffers(val) {
51
51
  if (!val || typeof val !== "object")
52
52
  return val;
53
- if (val.type === "Buffer" && Array.isArray(val.data)) {
54
- return Buffer.from(val.data);
53
+ if (val instanceof Uint8Array)
54
+ return Buffer.from(val);
55
+ if (val.type === "Buffer") {
56
+ if (Array.isArray(val.data))
57
+ return Buffer.from(val.data);
58
+ if (typeof val.data === "string")
59
+ return Buffer.from(val.data, "base64");
55
60
  }
56
61
  if (Array.isArray(val))
57
62
  return val.map(reviveBuffers);
@@ -107,9 +112,17 @@ export async function useMultiFileAuthState(dir) {
107
112
  flushTimer = setTimeout(() => {
108
113
  flushTimer = undefined;
109
114
  void client.flushSession().catch(() => { });
110
- }, 1500);
115
+ }, 5000);
111
116
  flushTimer.unref();
112
117
  };
118
+ const onExitFlush = () => {
119
+ if (flushTimer) {
120
+ clearTimeout(flushTimer);
121
+ flushTimer = undefined;
122
+ }
123
+ void client.flushSession().catch(() => { });
124
+ };
125
+ process.once("beforeExit", onExitFlush);
113
126
  return {
114
127
  state: {
115
128
  creds,
@@ -130,15 +143,29 @@ export async function useMultiFileAuthState(dir) {
130
143
  return out;
131
144
  },
132
145
  set: async (data) => {
146
+ let changed = false;
133
147
  for (const [type, entries] of Object.entries(data)) {
134
148
  for (const [id, val] of Object.entries(entries)) {
135
- if (val !== undefined && val !== null) {
149
+ const recKey = `key:${type}:${id}`;
150
+ if (val === null || val === undefined) {
151
+ const prev = client.getAuthRecord(recKey);
152
+ if (prev && prev.length > 0) {
153
+ client.putAuthRecord(recKey, Buffer.alloc(0));
154
+ changed = true;
155
+ }
156
+ }
157
+ else {
136
158
  const payload = val instanceof Uint8Array ? Buffer.from(val) : packAuthJson(val);
137
- client.putAuthRecord(`key:${type}:${id}`, payload);
159
+ const prev = client.getAuthRecord(recKey);
160
+ if (!prev || Buffer.compare(prev, payload) !== 0) {
161
+ client.putAuthRecord(recKey, payload);
162
+ changed = true;
163
+ }
138
164
  }
139
165
  }
140
166
  }
141
- scheduleFlush();
167
+ if (changed)
168
+ scheduleFlush();
142
169
  },
143
170
  },
144
171
  },
@@ -201,7 +228,12 @@ export function makeWASocket(config = {}) {
201
228
  return memKeys.get(`${type}:${id}`);
202
229
  };
203
230
  const setKey = async (type, id, val) => {
204
- memKeys.set(`${type}:${id}`, val);
231
+ if (val === null || val === undefined) {
232
+ memKeys.delete(`${type}:${id}`);
233
+ }
234
+ else {
235
+ memKeys.set(`${type}:${id}`, val);
236
+ }
205
237
  if (authKeys?.set) {
206
238
  await authKeys.set({ [type]: { [id]: val } });
207
239
  }
@@ -276,11 +308,84 @@ export function makeWASocket(config = {}) {
276
308
  },
277
309
  }));
278
310
  const pendingQueries = new Map();
311
+ const deviceCache = new Map();
279
312
  const pendingMediaRetries = new Map();
313
+ const ensureSessions = async (devJids) => {
314
+ const checks = await Promise.all(devJids.map(async (dj) => ((await signalMgr.hasSession(jidToSignalAddress(dj))) ? null : dj)));
315
+ const missing = checks.filter((x) => x !== null);
316
+ if (missing.length === 0)
317
+ return;
318
+ const batches = [];
319
+ for (let i = 0; i < missing.length; i += 50)
320
+ batches.push(missing.slice(i, i + 50));
321
+ await Promise.all(batches.map(async (batch) => {
322
+ try {
323
+ const res = await sendQuery({
324
+ tag: "iq",
325
+ attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "encrypt" },
326
+ content: [
327
+ {
328
+ tag: "key",
329
+ attrs: {},
330
+ content: batch.map((dj) => ({ tag: "user", attrs: { jid: dj } })),
331
+ },
332
+ ],
333
+ });
334
+ const list = Array.isArray(res.content) ? res.content.find((c) => c.tag === "list") : undefined;
335
+ if (!Array.isArray(list?.content))
336
+ return;
337
+ for (const u of list.content) {
338
+ if (u.tag !== "user" || !u.attrs?.jid || !Array.isArray(u.content))
339
+ continue;
340
+ const regNode = u.content.find((c) => c.tag === "registration");
341
+ const identNode = u.content.find((c) => c.tag === "identity");
342
+ const skeyNode = u.content.find((c) => c.tag === "skey");
343
+ const keyNode = u.content.find((c) => c.tag === "key");
344
+ if (!(regNode?.content instanceof Uint8Array) || !(identNode?.content instanceof Uint8Array) || !Array.isArray(skeyNode?.content)) {
345
+ continue;
346
+ }
347
+ const skeyIdBuf = skeyNode.content.find((c) => c.tag === "id")?.content;
348
+ const skeyValBuf = skeyNode.content.find((c) => c.tag === "value")?.content;
349
+ if (!(skeyIdBuf instanceof Uint8Array) || !(skeyValBuf instanceof Uint8Array))
350
+ continue;
351
+ const regId = Buffer.from(regNode.content).readUInt32BE(0);
352
+ const skeyId = Buffer.from(skeyIdBuf).readUIntBE(0, skeyIdBuf.length);
353
+ let preKey;
354
+ if (Array.isArray(keyNode?.content)) {
355
+ const pkIdBuf = keyNode.content.find((c) => c.tag === "id")?.content;
356
+ const pkValBuf = keyNode.content.find((c) => c.tag === "value")?.content;
357
+ if (pkIdBuf instanceof Uint8Array && pkValBuf instanceof Uint8Array) {
358
+ preKey = {
359
+ keyId: Buffer.from(pkIdBuf).readUIntBE(0, pkIdBuf.length),
360
+ publicKey: pkValBuf,
361
+ };
362
+ }
363
+ }
364
+ await signalMgr.initOutgoingSession(jidToSignalAddress(u.attrs.jid), {
365
+ registrationId: regId,
366
+ identityKey: identNode.content,
367
+ signedPreKey: { keyId: skeyId, publicKey: skeyValBuf },
368
+ preKey,
369
+ });
370
+ }
371
+ }
372
+ catch {
373
+ }
374
+ }));
375
+ };
376
+ const computePhash = (devs) => {
377
+ const sorted = [...devs].sort();
378
+ const hash = createHash("sha256").update(sorted.join("")).digest("base64");
379
+ return "2:" + hash.slice(0, 6);
380
+ };
280
381
  const lidToPnMap = new Map();
382
+ const pnToLidMap = new Map();
281
383
  const rememberLidPn = (lid, pn) => {
282
384
  if (lid && pn && lid.endsWith("@lid") && pn.endsWith("@s.whatsapp.net")) {
283
- lidToPnMap.set(jidNormalizedUser(lid), jidNormalizedUser(pn));
385
+ const normLid = jidNormalizedUser(lid);
386
+ const normPn = jidNormalizedUser(pn);
387
+ lidToPnMap.set(normLid, normPn);
388
+ pnToLidMap.set(normPn, normLid);
284
389
  }
285
390
  };
286
391
  const resolvePnJid = (jid) => {
@@ -290,6 +395,219 @@ export function makeWASocket(config = {}) {
290
395
  return jid;
291
396
  return lidToPnMap.get(jidNormalizedUser(jid)) ?? jid;
292
397
  };
398
+ const walkContextInfo = (obj, onContext) => {
399
+ if (!obj || typeof obj !== "object" || Array.isArray(obj) || obj instanceof Uint8Array)
400
+ return;
401
+ const rec = obj;
402
+ if (rec.contextInfo && typeof rec.contextInfo === "object") {
403
+ onContext(rec.contextInfo, rec);
404
+ if (rec.contextInfo.quotedMessage && typeof rec.contextInfo.quotedMessage === "object") {
405
+ walkContextInfo(rec.contextInfo.quotedMessage, onContext);
406
+ }
407
+ }
408
+ for (const k of Object.keys(rec)) {
409
+ if (k === "contextInfo")
410
+ continue;
411
+ const v = rec[k];
412
+ if (v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Uint8Array)) {
413
+ walkContextInfo(v, onContext);
414
+ }
415
+ }
416
+ };
417
+ const hasUnresolvedContextLids = (msg) => {
418
+ let found = false;
419
+ walkContextInfo(msg, (ctx) => {
420
+ if (found)
421
+ return;
422
+ if (typeof ctx.participant === "string" && ctx.participant.endsWith("@lid") && !lidToPnMap.has(jidNormalizedUser(ctx.participant))) {
423
+ found = true;
424
+ return;
425
+ }
426
+ if (Array.isArray(ctx.mentionedJid)) {
427
+ for (const jid of ctx.mentionedJid) {
428
+ if (typeof jid === "string" && jid.endsWith("@lid") && !lidToPnMap.has(jidNormalizedUser(jid))) {
429
+ found = true;
430
+ return;
431
+ }
432
+ }
433
+ }
434
+ });
435
+ return found;
436
+ };
437
+ const resolveContextInfoLids = (msg) => {
438
+ walkContextInfo(msg, (ctx, parent) => {
439
+ if (typeof ctx.participant === "string" && ctx.participant.endsWith("@lid")) {
440
+ ctx.participant = resolvePnJid(ctx.participant);
441
+ }
442
+ if (Array.isArray(ctx.mentionedJid)) {
443
+ const replacements = [];
444
+ ctx.mentionedJid = ctx.mentionedJid.map((jid) => {
445
+ if (typeof jid === "string" && jid.endsWith("@lid")) {
446
+ const resolved = resolvePnJid(jid);
447
+ if (resolved !== jid && resolved.endsWith("@s.whatsapp.net")) {
448
+ const lidUser = jidDecode(jid)?.user;
449
+ const pnUser = jidDecode(resolved)?.user;
450
+ if (lidUser && pnUser)
451
+ replacements.push([lidUser, pnUser]);
452
+ }
453
+ return resolved;
454
+ }
455
+ return jid;
456
+ });
457
+ if (replacements.length > 0) {
458
+ for (const field of ["text", "caption", "conversation"]) {
459
+ if (typeof parent[field] === "string") {
460
+ let updated = parent[field];
461
+ for (const [lidUser, pnUser] of replacements) {
462
+ updated = updated.replaceAll(`@${lidUser}`, `@${pnUser}`);
463
+ }
464
+ parent[field] = updated;
465
+ }
466
+ }
467
+ }
468
+ }
469
+ });
470
+ };
471
+ const pickIncomingExpirationSeconds = (msg) => {
472
+ if (!msg || typeof msg !== "object")
473
+ return undefined;
474
+ const inner = msg.ephemeralMessage?.message ??
475
+ msg.viewOnceMessage?.message ??
476
+ msg.viewOnceMessageV2?.message ??
477
+ msg.viewOnceMessageV2Extension?.message ??
478
+ msg.documentWithCaptionMessage?.message ??
479
+ msg.editedMessage?.message ??
480
+ msg;
481
+ for (const key of Object.keys(inner)) {
482
+ const val = inner[key];
483
+ if (val && typeof val === "object" && !Array.isArray(val) && !(val instanceof Uint8Array)) {
484
+ const exp = val.contextInfo?.expiration;
485
+ if (exp !== undefined && exp !== null)
486
+ return Number(exp);
487
+ }
488
+ }
489
+ return undefined;
490
+ };
491
+ const findChild = (node, tag) => Array.isArray(node.content) ? node.content.find((c) => c.tag === tag) : undefined;
492
+ const hasChild = (node, tag) => Boolean(findChild(node, tag));
493
+ const getNodeText = (node) => {
494
+ if (!node)
495
+ return undefined;
496
+ if (typeof node.content === "string")
497
+ return node.content;
498
+ if (node.content instanceof Uint8Array)
499
+ return Buffer.from(node.content).toString("utf8");
500
+ return undefined;
501
+ };
502
+ const INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
503
+ const attachDeepInspect = (obj, seen = new WeakSet()) => {
504
+ if (!obj || typeof obj !== "object" || obj instanceof Uint8Array || ArrayBuffer.isView(obj))
505
+ return;
506
+ if (seen.has(obj))
507
+ return;
508
+ seen.add(obj);
509
+ if (Array.isArray(obj)) {
510
+ for (const item of obj)
511
+ attachDeepInspect(item, seen);
512
+ return;
513
+ }
514
+ const rec = obj;
515
+ if (!Object.prototype.hasOwnProperty.call(rec, INSPECT_CUSTOM)) {
516
+ Object.defineProperty(rec, INSPECT_CUSTOM, {
517
+ enumerable: false,
518
+ configurable: true,
519
+ value(_depth, opts, inspectFn) {
520
+ return inspectFn({ ...this }, { ...opts, depth: null, maxArrayLength: null });
521
+ },
522
+ });
523
+ }
524
+ for (const k of Object.keys(rec)) {
525
+ attachDeepInspect(rec[k], seen);
526
+ }
527
+ };
528
+ const parseGroupMetadataNode = (grp, fallbackJid) => {
529
+ const attrs = grp.attrs ?? {};
530
+ const rawId = attrs.id ?? attrs.jid ?? fallbackJid ?? "";
531
+ const id = rawId && !rawId.includes("@") ? `${rawId}@g.us` : rawId;
532
+ const subject = attrs.subject ?? "";
533
+ const addressingMode = attrs.addressing_mode;
534
+ const descNode = findChild(grp, "description");
535
+ const desc = descNode ? getNodeText(findChild(descNode, "body")) : undefined;
536
+ const ephemeralNode = findChild(grp, "ephemeral");
537
+ const ephemeralDuration = ephemeralNode?.attrs?.expiration
538
+ ? Number(ephemeralNode.attrs.expiration) || undefined
539
+ : undefined;
540
+ const parentNode = findChild(grp, "parent");
541
+ const linkedParentNode = findChild(grp, "linked_parent");
542
+ const membershipNode = findChild(grp, "membership_approval_mode");
543
+ const groupJoinNode = membershipNode ? findChild(membershipNode, "group_join") : undefined;
544
+ const memberAddModeNode = findChild(grp, "member_add_mode");
545
+ const memberLinkModeNode = findChild(grp, "member_link_mode");
546
+ const participants = [];
547
+ if (Array.isArray(grp.content)) {
548
+ for (const c of grp.content) {
549
+ if (c.tag === "participant" && c.attrs?.jid) {
550
+ rememberLidPn(c.attrs.jid, c.attrs.phone_number);
551
+ const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? jidNormalizedUser(c.attrs.jid) : undefined);
552
+ const pnVal = c.attrs.phone_number
553
+ ? jidNormalizedUser(c.attrs.phone_number)
554
+ : c.attrs.jid.endsWith("@s.whatsapp.net")
555
+ ? jidNormalizedUser(c.attrs.jid)
556
+ : undefined;
557
+ rememberLidPn(lidVal, pnVal);
558
+ const pnId = pnVal ?? resolvePnJid(c.attrs.jid);
559
+ const admin = c.attrs.type;
560
+ participants.push({
561
+ id: pnId,
562
+ ...(pnVal ? { phoneNumber: pnVal } : {}),
563
+ ...(lidVal ? { lid: lidVal } : {}),
564
+ admin,
565
+ isAdmin: admin === "admin" || admin === "superadmin",
566
+ isSuperAdmin: admin === "superadmin",
567
+ ...(c.attrs.display_name ? { displayName: c.attrs.display_name } : {}),
568
+ ...(c.attrs.username ? { username: c.attrs.username } : {}),
569
+ });
570
+ }
571
+ }
572
+ }
573
+ const meta = {
574
+ id,
575
+ subject,
576
+ ...(attrs.s_o || attrs.subject_owner ? { subjectOwner: attrs.s_o ?? attrs.subject_owner } : {}),
577
+ ...(attrs.s_o_pn ? { subjectOwnerPhoneNumber: attrs.s_o_pn } : {}),
578
+ ...(attrs.s_o_username ? { subjectOwnerUsername: attrs.s_o_username } : {}),
579
+ ...(attrs.s_t ? { subjectTime: Number(attrs.s_t) } : {}),
580
+ ...(attrs.creation ? { creation: Number(attrs.creation) } : {}),
581
+ ...(attrs.creator || attrs.owner ? { owner: attrs.creator ?? attrs.owner } : {}),
582
+ ...(attrs.creator_pn ? { ownerPhoneNumber: attrs.creator_pn } : {}),
583
+ ...(attrs.creator_username ? { ownerUsername: attrs.creator_username } : {}),
584
+ ...(attrs.creator_country_code ? { ownerCountryCode: attrs.creator_country_code } : {}),
585
+ size: attrs.size ? Number(attrs.size) : participants.length,
586
+ addressingMode,
587
+ ...(desc !== undefined ? { desc } : {}),
588
+ ...(descNode?.attrs?.id ? { descId: descNode.attrs.id } : {}),
589
+ ...(descNode?.attrs?.participant ? { descOwner: descNode.attrs.participant } : {}),
590
+ ...(descNode?.attrs?.t ? { descTime: Number(descNode.attrs.t) } : {}),
591
+ restrict: hasChild(grp, "locked"),
592
+ announce: hasChild(grp, "announcement"),
593
+ isCommunity: parentNode !== undefined,
594
+ isCommunityAnnounce: hasChild(grp, "default_sub_group"),
595
+ joinApprovalMode: groupJoinNode?.attrs?.state === "on",
596
+ ...(memberAddModeNode ? { memberAddMode: getNodeText(memberAddModeNode) } : {}),
597
+ ...(memberLinkModeNode ? { memberLinkMode: getNodeText(memberLinkModeNode) } : {}),
598
+ ...(ephemeralDuration ? { ephemeralDuration } : {}),
599
+ ...(linkedParentNode?.attrs?.jid || parentNode?.attrs?.jid
600
+ ? { linkedParent: linkedParentNode?.attrs?.jid ?? parentNode?.attrs?.jid }
601
+ : {}),
602
+ noFrequentlyForwarded: hasChild(grp, "no_frequently_forwarded"),
603
+ incognito: hasChild(grp, "incognito"),
604
+ support: hasChild(grp, "support"),
605
+ suspended: hasChild(grp, "suspended"),
606
+ participants,
607
+ };
608
+ attachDeepInspect(meta);
609
+ return meta;
610
+ };
293
611
  rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
294
612
  let msgTagCounter = 1;
295
613
  const nextTag = () => `${Math.floor(Date.now() / 1000)}.${msgTagCounter++}`;
@@ -321,7 +639,8 @@ export function makeWASocket(config = {}) {
321
639
  const p = pendingQueries.get(node.attrs.id);
322
640
  pendingQueries.delete(node.attrs.id);
323
641
  if (node.attrs.type === "error") {
324
- p.reject(new Error(`WA IQ error on ${node.attrs.id}`));
642
+ const errNode = Array.isArray(node.content) ? node.content.find((c) => c.tag === "error") : undefined;
643
+ p.reject(new Error(`WA IQ error on ${node.attrs.id}${errNode?.attrs?.code ? ` (${errNode.attrs.code})` : ""}`));
325
644
  }
326
645
  else {
327
646
  p.resolve(node);
@@ -507,8 +826,17 @@ export function makeWASocket(config = {}) {
507
826
  admin: p.attrs.type || null,
508
827
  };
509
828
  });
510
- if (action === "add" || action === "remove") {
511
- senderKeyMemory.delete(groupId);
829
+ if (action === "remove") {
830
+ const mem = senderKeyMemory.get(groupId);
831
+ if (mem) {
832
+ for (const p of participants) {
833
+ for (const dev of Array.from(mem)) {
834
+ const u = dev.split(":")[0]?.split("@")[0];
835
+ if (u && (p.jid?.startsWith(u) || p.lid?.startsWith(u)))
836
+ mem.delete(dev);
837
+ }
838
+ }
839
+ }
512
840
  }
513
841
  groupCache.delete(groupId);
514
842
  if (participants.length > 0) {
@@ -807,7 +1135,8 @@ export function makeWASocket(config = {}) {
807
1135
  meta.addressingMode ||
808
1136
  ((meta.participants ?? []).some((p) => p.id.endsWith("@lid")) ? "lid" : "pn");
809
1137
  const groupSender = retryAddrMode === "lid" && meLid ? meLid : meJid;
810
- const { distributionBytes } = await signalMgr.getOrCreateGroupDistribution(`${cachedMsg.jid}:${jidToSignalAddress(groupSender)}`);
1138
+ const groupKey = `${cachedMsg.jid}:${jidToSignalAddress(groupSender)}`;
1139
+ const { distributionBytes } = await signalMgr.getOrCreateGroupDistribution(groupKey);
811
1140
  payloadToResend = {
812
1141
  ...cachedMsg.message,
813
1142
  senderKeyDistributionMessage: {
@@ -827,6 +1156,11 @@ export function makeWASocket(config = {}) {
827
1156
  },
828
1157
  };
829
1158
  }
1159
+ if (cachedMsg.jid.endsWith("@g.us") && !jidDecode(retryPid)?.device) {
1160
+ senderKeyMemory.delete(cachedMsg.jid);
1161
+ await setKey("sender-key-memory-v3", cachedMsg.jid, []);
1162
+ }
1163
+ await ensureSessions([retryPid]);
830
1164
  const paddedRetry = writeRandomPadMax16(proto.Message.encode(payloadToResend));
831
1165
  const enc = await signalMgr.encryptMessage(jidToSignalAddress(retryPid), paddedRetry);
832
1166
  const getMediaStanzaMeta = (m) => {
@@ -844,12 +1178,16 @@ export function makeWASocket(config = {}) {
844
1178
  return { stanzaType: "media", mediatype: m.audioMessage.ptt ? "ptt" : "audio" };
845
1179
  if (m.documentMessage)
846
1180
  return { stanzaType: "media", mediatype: "document" };
847
- if (m.stickerMessage)
1181
+ if (m.stickerMessage || m.lottieStickerMessage || m.audioStickerMessage)
848
1182
  return { stanzaType: "media", mediatype: "sticker" };
849
1183
  return { stanzaType: "text" };
850
1184
  };
851
1185
  const { stanzaType: retryStanzaType, mediatype: retryMediatype } = getMediaStanzaMeta(cachedMsg.message);
852
1186
  const isLegacyBtnRetry = Boolean(cachedMsg.message?.buttonsMessage);
1187
+ if (cachedMsg.jid.endsWith("@g.us") && !jidDecode(retryPid)?.device) {
1188
+ senderKeyMemory.delete(cachedMsg.jid);
1189
+ await setKey("sender-key-memory-v3", cachedMsg.jid, []);
1190
+ }
853
1191
  const retryContent = [
854
1192
  {
855
1193
  tag: "enc",
@@ -909,6 +1247,7 @@ export function makeWASocket(config = {}) {
909
1247
  id: node.attrs.id,
910
1248
  to: cachedMsg.jid,
911
1249
  ...(cachedMsg.jid.endsWith("@g.us") ? { participant: retryPid } : {}),
1250
+ ...(retryAddrMode ? { addressing_mode: retryAddrMode } : {}),
912
1251
  type: retryStanzaType,
913
1252
  },
914
1253
  content: retryContent,
@@ -919,6 +1258,10 @@ export function makeWASocket(config = {}) {
919
1258
  return;
920
1259
  }
921
1260
  if (node.tag === "ack") {
1261
+ if (node.attrs.error && node.attrs.from?.endsWith("@g.us") && !node.attrs.participant) {
1262
+ senderKeyMemory.delete(node.attrs.from);
1263
+ void setKey("sender-key-memory-v3", node.attrs.from, []).catch(() => { });
1264
+ }
922
1265
  return;
923
1266
  }
924
1267
  if (node.tag === "iq" && node.attrs.type === "get" && node.attrs.xmlns === "w:p") {
@@ -933,16 +1276,22 @@ export function makeWASocket(config = {}) {
933
1276
  const from = node.attrs.from;
934
1277
  const participant = node.attrs.participant;
935
1278
  const recipient = node.attrs.recipient;
936
- const isGroup = from.endsWith("@g.us");
937
- const chatId = isGroup || from === "status@broadcast" ? from : recipient || from;
938
- const author = isGroup || from === "status@broadcast" ? participant || from : from;
1279
+ const isGroup = isJidGroup(from);
1280
+ const isBroadcast = from === "status@broadcast" || isJidBroadcast(from);
1281
+ const isNewsletter = isJidNewsletter(from);
1282
+ const chatId = isGroup || isBroadcast ? from : recipient || from;
1283
+ const author = isGroup || isBroadcast ? participant || from : from;
939
1284
  rememberLidPn(participant, node.attrs.participant_pn);
1285
+ rememberLidPn(node.attrs.participant_lid, participant);
940
1286
  rememberLidPn(from, node.attrs.sender_pn);
1287
+ rememberLidPn(node.attrs.sender_lid, from);
941
1288
  rememberLidPn(authCreds.me?.lid, authCreds.me?.id);
942
1289
  const meId = authCreds.me?.id ?? sock.user?.id;
943
1290
  const meLid = authCreds.me?.lid ?? sock.user?.lid;
944
1291
  const fromMe = Boolean((meId && jidDecode(author)?.user === jidDecode(meId)?.user) ||
945
1292
  (meLid && jidDecode(author)?.user === jidDecode(meLid)?.user));
1293
+ const isSelfSentDirect = fromMe && !isGroup && !isBroadcast;
1294
+ const senderDevice = jidDecode(author)?.device ?? 0;
946
1295
  const ackAttrs = {
947
1296
  to: from,
948
1297
  id: msgId,
@@ -975,42 +1324,92 @@ export function makeWASocket(config = {}) {
975
1324
  else {
976
1325
  continue;
977
1326
  }
978
- let decoded = proto.Message.decode(plainBuf);
979
- decoded = decoded.deviceSentMessage?.message ?? decoded;
980
- if (decoded.senderKeyDistributionMessage?.axolotlSenderKeyDistributionMessage) {
981
- const gId = decoded.senderKeyDistributionMessage.groupId ?? chatId;
982
- await signalMgr.processSenderKeyDistribution(`${gId}:${jidToSignalAddress(author)}`, decoded.senderKeyDistributionMessage.axolotlSenderKeyDistributionMessage);
1327
+ const rawDecoded = proto.Message.decode(plainBuf);
1328
+ const destinationJid = rawDecoded.deviceSentMessage?.destinationJid ?? undefined;
1329
+ const decoded = rawDecoded.deviceSentMessage?.message ?? rawDecoded;
1330
+ const skdm = decoded.senderKeyDistributionMessage ?? decoded.fastRatchetKeySenderKeyDistributionMessage;
1331
+ if (skdm?.axolotlSenderKeyDistributionMessage) {
1332
+ const gId = skdm.groupId ?? chatId;
1333
+ await signalMgr.processSenderKeyDistribution(`${gId}:${jidToSignalAddress(author)}`, skdm.axolotlSenderKeyDistributionMessage);
983
1334
  }
984
- const hasDisplayContent = Boolean(decoded.conversation ||
985
- decoded.extendedTextMessage?.text ||
986
- decoded.buttonsResponseMessage?.selectedButtonId ||
987
- decoded.interactiveResponseMessage?.nativeFlowResponseMessage ||
988
- decoded.ephemeralMessage?.message ||
989
- decoded.viewOnceMessage?.message ||
990
- decoded.viewOnceMessageV2?.message ||
991
- decoded.documentWithCaptionMessage?.message ||
992
- decoded.editedMessage?.message);
1335
+ const hasDisplayContent = Object.keys(decoded).some((k) => k !== "senderKeyDistributionMessage" &&
1336
+ k !== "fastRatchetKeySenderKeyDistributionMessage" &&
1337
+ k !== "messageContextInfo");
993
1338
  if (hasDisplayContent) {
994
1339
  if (isGroup &&
995
- participant?.endsWith("@lid") &&
996
- !node.attrs.participant_pn &&
997
- !lidToPnMap.has(jidNormalizedUser(participant))) {
1340
+ ((participant?.endsWith("@lid") &&
1341
+ !node.attrs.participant_pn &&
1342
+ !lidToPnMap.has(jidNormalizedUser(participant))) ||
1343
+ hasUnresolvedContextLids(decoded))) {
998
1344
  await sock.groupMetadata(chatId).catch(() => undefined);
999
1345
  }
1346
+ resolveContextInfoLids(decoded);
1347
+ attachDeepInspect(decoded);
1348
+ const effectiveChatId = isSelfSentDirect ? (recipient ?? destinationJid ?? chatId) : chatId;
1349
+ const resolvedRemoteJid = !isGroup && !isBroadcast ? resolvePnJid(effectiveChatId) : effectiveChatId;
1350
+ let remoteJidAlt;
1351
+ if (!isGroup && !isBroadcast) {
1352
+ if (isLidUser(resolvedRemoteJid)) {
1353
+ const pn = isSelfSentDirect
1354
+ ? node.attrs.peer_recipient_pn
1355
+ : node.attrs.sender_pn;
1356
+ remoteJidAlt = pn ? jidNormalizedUser(pn) : undefined;
1357
+ }
1358
+ else {
1359
+ const lid = isSelfSentDirect
1360
+ ? node.attrs.peer_recipient_lid ??
1361
+ (isLidUser(effectiveChatId) ? effectiveChatId : pnToLidMap.get(jidNormalizedUser(resolvedRemoteJid)))
1362
+ : node.attrs.sender_lid ??
1363
+ (isLidUser(effectiveChatId) ? effectiveChatId : pnToLidMap.get(jidNormalizedUser(resolvedRemoteJid)));
1364
+ remoteJidAlt = lid ? jidNormalizedUser(lid) : undefined;
1365
+ }
1366
+ }
1367
+ const resolvedParticipant = participant
1368
+ ? jidNormalizedUser(resolvePnJid(node.attrs.participant_pn || participant))
1369
+ : undefined;
1370
+ let participantAlt;
1371
+ if ((isGroup || isBroadcast) && resolvedParticipant) {
1372
+ if (isLidUser(resolvedParticipant)) {
1373
+ participantAlt = node.attrs.participant_pn
1374
+ ? jidNormalizedUser(node.attrs.participant_pn)
1375
+ : undefined;
1376
+ }
1377
+ else {
1378
+ const lid = node.attrs.participant_lid ??
1379
+ (isLidUser(participant) ? participant : pnToLidMap.get(resolvedParticipant));
1380
+ participantAlt = lid ? jidNormalizedUser(lid) : undefined;
1381
+ }
1382
+ }
1383
+ const senderUsername = !isSelfSentDirect
1384
+ ? (node.attrs.participant_username ?? node.attrs.username)?.replace(/^@/, "")
1385
+ : undefined;
1386
+ const recipientUsername = (node.attrs.recipient_username ?? node.attrs.peer_recipient_username)?.replace(/^@/, "");
1387
+ const recipientAlt = node.attrs.peer_recipient_pn ?? node.attrs.peer_recipient_lid;
1388
+ const expirationSeconds = pickIncomingExpirationSeconds(decoded);
1000
1389
  ev.emit("messages.upsert", {
1001
1390
  type: "notify",
1002
1391
  messages: [
1003
1392
  {
1004
1393
  key: {
1005
- remoteJid: !isGroup && chatId !== "status@broadcast" ? resolvePnJid(chatId) : chatId,
1006
- remoteJidAlt: !isGroup
1007
- ? node.attrs.sender_pn || node.attrs.sender_lid || node.attrs.peer_recipient_pn
1008
- : undefined,
1394
+ remoteJid: resolvedRemoteJid,
1395
+ ...(remoteJidAlt ? { remoteJidAlt } : {}),
1009
1396
  fromMe,
1010
1397
  id: msgId,
1011
- participant: participant ? resolvePnJid(node.attrs.participant_pn || participant) : undefined,
1012
- participantAlt: isGroup ? node.attrs.participant_pn || node.attrs.participant_lid : undefined,
1398
+ isGroup,
1399
+ isBroadcast,
1400
+ isNewsletter,
1401
+ senderDevice,
1402
+ ...(resolvedParticipant ? { participant: resolvedParticipant } : {}),
1403
+ ...(participantAlt ? { participantAlt } : {}),
1404
+ ...(senderUsername ? { senderUsername } : {}),
1405
+ ...(recipient ? { recipientJid: jidNormalizedUser(recipient) } : {}),
1406
+ ...(recipientAlt ? { recipientAlt: jidNormalizedUser(recipientAlt) } : {}),
1407
+ ...(recipientUsername ? { recipientUsername } : {}),
1013
1408
  },
1409
+ ...(resolvedParticipant ? { participant: resolvedParticipant } : {}),
1410
+ ...(isBroadcast ? { broadcast: true } : {}),
1411
+ ...(expirationSeconds !== undefined ? { expirationSeconds } : {}),
1412
+ ...(node.attrs.verified_name ? { verifiedBizName: node.attrs.verified_name } : {}),
1014
1413
  message: decoded,
1015
1414
  messageTimestamp: Number(node.attrs.t || Math.floor(Date.now() / 1000)),
1016
1415
  pushName: node.attrs.notify,
@@ -1228,7 +1627,24 @@ export function makeWASocket(config = {}) {
1228
1627
  };
1229
1628
  }
1230
1629
  if (c?.rawMessage && typeof c.rawMessage === "object") {
1231
- return c.rawMessage;
1630
+ const raw = c.rawMessage;
1631
+ if (raw.audioStickerMessage) {
1632
+ const futureProof = raw.audioStickerMessage;
1633
+ const outerMessage = futureProof.message ?? futureProof;
1634
+ const original = outerMessage.message ?? outerMessage;
1635
+ const originalMessage = original.stickerMessage ? original : { stickerMessage: original };
1636
+ const sticker = originalMessage.stickerMessage;
1637
+ const stickerBytes = sticker?.buffer ?? sticker?.data;
1638
+ const stickerMedia = stickerBytes instanceof Uint8Array
1639
+ ? { ...sticker, __rawBytes: stickerBytes }
1640
+ : sticker;
1641
+ return {
1642
+ audioStickerMessage: { message: originalMessage },
1643
+ messageContextInfo: raw.messageContextInfo,
1644
+ __audioStickerMedia: stickerMedia,
1645
+ };
1646
+ }
1647
+ return { ...raw };
1232
1648
  }
1233
1649
  if (c?.stickerPackMessage)
1234
1650
  return { stickerPackMessage: c.stickerPackMessage };
@@ -1321,10 +1737,10 @@ export function makeWASocket(config = {}) {
1321
1737
  ? b.buttonParamsJson
1322
1738
  : JSON.stringify(b.buttonParamsJson ?? {}),
1323
1739
  })),
1324
- messageParamsJson: src.messageParams
1325
- ? typeof src.messageParams === "string"
1326
- ? src.messageParams
1327
- : JSON.stringify(src.messageParams)
1740
+ messageParamsJson: card.messageParams
1741
+ ? typeof card.messageParams === "string"
1742
+ ? card.messageParams
1743
+ : JSON.stringify(card.messageParams)
1328
1744
  : "{}",
1329
1745
  messageVersion: 1,
1330
1746
  },
@@ -1540,6 +1956,30 @@ export function makeWASocket(config = {}) {
1540
1956
  return { conversation: text };
1541
1957
  };
1542
1958
  const waMsg = await buildOutgoingWAMessage(content);
1959
+ if (waMsg.audioStickerMessage?.message) {
1960
+ const envelope = waMsg.audioStickerMessage.message;
1961
+ const outerMessage = envelope.message ?? envelope;
1962
+ const inner = outerMessage.message ?? outerMessage;
1963
+ const sticker = envelope.stickerMessage ?? inner.stickerMessage;
1964
+ const audioMessage = sticker?.audioMessage;
1965
+ if (!sticker || !audioMessage) {
1966
+ throw new Error("Audio sticker payload must contain StickerMessage.audioMessage");
1967
+ }
1968
+ const stickerMedia = waMsg.__audioStickerMedia;
1969
+ const stickerBytes = stickerMedia?.__rawBytes;
1970
+ if (!sticker.url && !sticker.directPath && stickerBytes instanceof Uint8Array && stickerBytes.length > 0) {
1971
+ const uploaded = await uploadWaMedia(stickerBytes, "sticker", "/mms/image", sticker.mediaKey);
1972
+ Object.assign(sticker, uploaded);
1973
+ }
1974
+ delete waMsg.__audioStickerMedia;
1975
+ if (!sticker.url && !sticker.directPath) {
1976
+ throw new Error("Audio sticker needs sticker bytes or uploaded StickerMessage URL/directPath before relay");
1977
+ }
1978
+ if (!audioMessage.url && !audioMessage.directPath) {
1979
+ throw new Error("Audio sticker needs uploaded AudioMessage URL/directPath before relay");
1980
+ }
1981
+ waMsg.audioStickerMessage = { message: { stickerMessage: sticker } };
1982
+ }
1543
1983
  const quotedRaw = options?.quoted;
1544
1984
  const mentionedJid = Array.isArray(content?.mentions)
1545
1985
  ? content.mentions
@@ -1599,23 +2039,25 @@ export function makeWASocket(config = {}) {
1599
2039
  ? "button"
1600
2040
  : isStickerPack
1601
2041
  ? "sticker_pack"
1602
- : waMsg.imageMessage
1603
- ? "image"
1604
- : waMsg.videoMessage
1605
- ? waMsg.videoMessage.gifPlayback
1606
- ? "gif"
1607
- : "video"
1608
- : waMsg.ptvMessage
1609
- ? "ptv"
1610
- : waMsg.audioMessage
1611
- ? waMsg.audioMessage.ptt
1612
- ? "ptt"
1613
- : "audio"
1614
- : waMsg.documentMessage
1615
- ? "document"
1616
- : waMsg.stickerMessage
1617
- ? "sticker"
1618
- : undefined;
2042
+ : waMsg.audioStickerMessage || waMsg.lottieStickerMessage
2043
+ ? "sticker"
2044
+ : waMsg.imageMessage
2045
+ ? "image"
2046
+ : waMsg.videoMessage
2047
+ ? waMsg.videoMessage.gifPlayback
2048
+ ? "gif"
2049
+ : "video"
2050
+ : waMsg.ptvMessage
2051
+ ? "ptv"
2052
+ : waMsg.audioMessage
2053
+ ? waMsg.audioMessage.ptt
2054
+ ? "ptt"
2055
+ : "audio"
2056
+ : waMsg.documentMessage
2057
+ ? "document"
2058
+ : waMsg.stickerMessage
2059
+ ? "sticker"
2060
+ : undefined;
1619
2061
  const stanzaType = encMediatype ? "media" : "text";
1620
2062
  const deleteEditAttr = content?.delete && typeof content.delete === "object"
1621
2063
  ? jid.endsWith("@g.us") && !content.delete.fromMe
@@ -1658,114 +2100,92 @@ export function makeWASocket(config = {}) {
1658
2100
  const text = typeof waMsg.conversation === "string"
1659
2101
  ? waMsg.conversation
1660
2102
  : waMsg.interactiveMessage?.body?.text ?? waMsg.buttonsMessage?.contentText ?? "";
2103
+ if (!waMsg.protocolMessage && !waMsg.reactionMessage && !waMsg.messageContextInfo && !jid.endsWith("@newsletter")) {
2104
+ waMsg.messageContextInfo = {
2105
+ deviceListMetadata: {},
2106
+ deviceListMetadataVersion: 2,
2107
+ ...(waMsg.pollCreationMessage || waMsg.pollCreationMessageV3 ? { messageSecret: randomBytes(32) } : {}),
2108
+ };
2109
+ }
1661
2110
  const padded = writeRandomPadMax16(proto.Message.encode(waMsg));
1662
2111
  const meJid = authCreds.me?.id ?? sock.user?.id ?? "0@s.whatsapp.net";
1663
2112
  const msgId = generateMessageIDV2(meJid);
1664
2113
  sentMessages.set(msgId, { jid, message: waMsg });
1665
2114
  setTimeout(() => sentMessages.delete(msgId), 5 * 60_000).unref();
1666
2115
  const getDevices = async (userJids) => {
1667
- try {
1668
- const res = await sendQuery({
1669
- tag: "iq",
1670
- attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "usync" },
1671
- content: [
1672
- {
1673
- tag: "usync",
1674
- attrs: { sid: nextTag(), mode: "query", last: "true", index: "0", context: "message" },
1675
- content: [
1676
- { tag: "query", attrs: {}, content: [{ tag: "devices", attrs: { version: "2" } }] },
1677
- {
1678
- tag: "list",
1679
- attrs: {},
1680
- content: userJids.map((u) => ({ tag: "user", attrs: { jid: jidNormalizedUser(u) } })),
1681
- },
1682
- ],
1683
- },
1684
- ],
1685
- });
1686
- const out = [];
1687
- const usync = Array.isArray(res.content) ? res.content.find((c) => c.tag === "usync") : undefined;
1688
- const list = Array.isArray(usync?.content) ? usync.content.find((c) => c.tag === "list") : undefined;
1689
- if (Array.isArray(list?.content)) {
1690
- for (const u of list.content) {
1691
- const uJid = u.attrs?.jid;
1692
- const devs = Array.isArray(u.content) ? u.content.find((c) => c.tag === "devices") : undefined;
1693
- const devList = Array.isArray(devs?.content) ? devs.content.find((c) => c.tag === "device-list") : undefined;
1694
- if (uJid && Array.isArray(devList?.content)) {
1695
- const dec = jidDecode(uJid);
1696
- for (const d of devList.content) {
1697
- if (d.tag === "device" && d.attrs?.id !== undefined && dec) {
1698
- const devId = Number(d.attrs.id);
1699
- out.push(devId === 0 ? `${dec.user}@${dec.server}` : `${dec.user}:${devId}@${dec.server}`);
2116
+ const now = Date.now();
2117
+ const cachedOut = [];
2118
+ const uncached = [];
2119
+ for (const u of userJids) {
2120
+ const key = jidNormalizedUser(u);
2121
+ const hit = deviceCache.get(key);
2122
+ if (hit && now - hit.ts < 5 * 60_000) {
2123
+ cachedOut.push(...hit.devices);
2124
+ }
2125
+ else {
2126
+ uncached.push(key);
2127
+ }
2128
+ }
2129
+ if (uncached.length === 0 && cachedOut.length > 0)
2130
+ return cachedOut;
2131
+ const batches = [];
2132
+ for (let i = 0; i < uncached.length; i += 50)
2133
+ batches.push(uncached.slice(i, i + 50));
2134
+ const batchResults = await Promise.all(batches.map(async (batch) => {
2135
+ const batchOut = [];
2136
+ try {
2137
+ const res = await sendQuery({
2138
+ tag: "iq",
2139
+ attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "usync" },
2140
+ content: [
2141
+ {
2142
+ tag: "usync",
2143
+ attrs: { sid: nextTag(), mode: "query", last: "true", index: "0", context: "message" },
2144
+ content: [
2145
+ { tag: "query", attrs: {}, content: [{ tag: "devices", attrs: { version: "2" } }] },
2146
+ {
2147
+ tag: "list",
2148
+ attrs: {},
2149
+ content: batch.map((u) => ({ tag: "user", attrs: { jid: u } })),
2150
+ },
2151
+ ],
2152
+ },
2153
+ ],
2154
+ });
2155
+ const usync = Array.isArray(res.content) ? res.content.find((c) => c.tag === "usync") : undefined;
2156
+ const list = Array.isArray(usync?.content) ? usync.content.find((c) => c.tag === "list") : undefined;
2157
+ if (Array.isArray(list?.content)) {
2158
+ for (const u of list.content) {
2159
+ const uJid = u.attrs?.jid;
2160
+ const devs = Array.isArray(u.content) ? u.content.find((c) => c.tag === "devices") : undefined;
2161
+ const devList = Array.isArray(devs?.content) ? devs.content.find((c) => c.tag === "device-list") : undefined;
2162
+ if (uJid && Array.isArray(devList?.content)) {
2163
+ const dec = jidDecode(uJid);
2164
+ const userDevs = [];
2165
+ for (const d of devList.content) {
2166
+ if (d.tag === "device" && d.attrs?.id !== undefined && dec) {
2167
+ if (d.attrs.is_hosted === "true")
2168
+ continue;
2169
+ const devId = Number(d.attrs.id);
2170
+ if (devId !== 0 && !d.attrs["key-index"])
2171
+ continue;
2172
+ userDevs.push(devId === 0 ? `${dec.user}@${dec.server}` : `${dec.user}:${devId}@${dec.server}`);
2173
+ }
2174
+ }
2175
+ if (userDevs.length > 0) {
2176
+ deviceCache.set(jidNormalizedUser(uJid), { devices: userDevs, ts: now });
2177
+ batchOut.push(...userDevs);
1700
2178
  }
1701
2179
  }
1702
2180
  }
1703
2181
  }
1704
2182
  }
1705
- if (out.length > 0)
1706
- return out;
1707
- }
1708
- catch {
1709
- }
1710
- return userJids.map((u) => jidNormalizedUser(u));
1711
- };
1712
- const ensureSessions = async (devJids) => {
1713
- const missing = [];
1714
- for (const dj of devJids) {
1715
- if (!(await signalMgr.hasSession(jidToSignalAddress(dj)))) {
1716
- missing.push(dj);
1717
- }
1718
- }
1719
- if (missing.length === 0)
1720
- return;
1721
- const res = await sendQuery({
1722
- tag: "iq",
1723
- attrs: { to: "s.whatsapp.net", type: "get", id: nextTag(), xmlns: "encrypt" },
1724
- content: [
1725
- {
1726
- tag: "key",
1727
- attrs: {},
1728
- content: missing.map((dj) => ({ tag: "user", attrs: { jid: dj } })),
1729
- },
1730
- ],
1731
- });
1732
- const list = Array.isArray(res.content) ? res.content.find((c) => c.tag === "list") : undefined;
1733
- if (!Array.isArray(list?.content))
1734
- return;
1735
- for (const u of list.content) {
1736
- if (u.tag !== "user" || !u.attrs?.jid || !Array.isArray(u.content))
1737
- continue;
1738
- const regNode = u.content.find((c) => c.tag === "registration");
1739
- const identNode = u.content.find((c) => c.tag === "identity");
1740
- const skeyNode = u.content.find((c) => c.tag === "skey");
1741
- const keyNode = u.content.find((c) => c.tag === "key");
1742
- if (!(regNode?.content instanceof Uint8Array) || !(identNode?.content instanceof Uint8Array) || !Array.isArray(skeyNode?.content)) {
1743
- continue;
1744
- }
1745
- const skeyIdBuf = skeyNode.content.find((c) => c.tag === "id")?.content;
1746
- const skeyValBuf = skeyNode.content.find((c) => c.tag === "value")?.content;
1747
- if (!(skeyIdBuf instanceof Uint8Array) || !(skeyValBuf instanceof Uint8Array))
1748
- continue;
1749
- const regId = Buffer.from(regNode.content).readUInt32BE(0);
1750
- const skeyId = Buffer.from(skeyIdBuf).readUIntBE(0, skeyIdBuf.length);
1751
- let preKey;
1752
- if (Array.isArray(keyNode?.content)) {
1753
- const pkIdBuf = keyNode.content.find((c) => c.tag === "id")?.content;
1754
- const pkValBuf = keyNode.content.find((c) => c.tag === "value")?.content;
1755
- if (pkIdBuf instanceof Uint8Array && pkValBuf instanceof Uint8Array) {
1756
- preKey = {
1757
- keyId: Buffer.from(pkIdBuf).readUIntBE(0, pkIdBuf.length),
1758
- publicKey: pkValBuf,
1759
- };
1760
- }
2183
+ catch {
1761
2184
  }
1762
- await signalMgr.initOutgoingSession(jidToSignalAddress(u.attrs.jid), {
1763
- registrationId: regId,
1764
- identityKey: identNode.content,
1765
- signedPreKey: { keyId: skeyId, publicKey: skeyValBuf },
1766
- preKey,
1767
- });
1768
- }
2185
+ return batchOut.length > 0 ? batchOut : batch;
2186
+ }));
2187
+ const out = [...cachedOut, ...batchResults.flat()];
2188
+ return out.length > 0 ? out : userJids.map((u) => jidNormalizedUser(u));
1769
2189
  };
1770
2190
  const buildDeviceIdentityNode = () => {
1771
2191
  if (!authCreds.account)
@@ -1779,28 +2199,66 @@ export function makeWASocket(config = {}) {
1779
2199
  });
1780
2200
  return [{ tag: "device-identity", attrs: {}, content: enc }];
1781
2201
  };
1782
- const computePhash = (devs) => {
1783
- const sorted = [...devs].sort();
1784
- const hash = createHash("sha256").update(sorted.join("")).digest("base64");
1785
- return "2:" + hash.slice(0, 6);
1786
- };
1787
2202
  if (jid.endsWith("@newsletter")) {
1788
- transport.sendEncrypted(encodeWABinaryNode({
1789
- tag: "message",
1790
- attrs: {
1791
- id: msgId,
1792
- to: jid,
1793
- type: stanzaType,
1794
- ...(deleteEditAttr ? { edit: deleteEditAttr } : {}),
1795
- },
1796
- content: [
1797
- {
1798
- tag: "plaintext",
1799
- attrs: encMediatype ? { mediatype: encMediatype } : {},
1800
- content: proto.Message.encode(waMsg),
2203
+ const isNlDelete = Boolean(content?.delete && typeof content.delete === "object");
2204
+ const isNlEdit = Boolean(content?.edit && typeof content.edit === "object");
2205
+ const nlMsgId = isNlDelete
2206
+ ? String(content.delete.id ?? msgId)
2207
+ : isNlEdit
2208
+ ? String(content.edit.id ?? msgId)
2209
+ : msgId;
2210
+ const nlEditAttr = isNlDelete ? "8" : isNlEdit ? "3" : deleteEditAttr;
2211
+ const nlSticker = waMsg.audioStickerMessage?.message?.stickerMessage;
2212
+ if (nlSticker && !isNlDelete && !isNlEdit) {
2213
+ const { audioMessage: nlAudio, ...plainSticker } = nlSticker;
2214
+ transport.sendEncrypted(encodeWABinaryNode({
2215
+ tag: "message",
2216
+ attrs: { id: nlMsgId, to: jid, type: "media" },
2217
+ content: [
2218
+ {
2219
+ tag: "plaintext",
2220
+ attrs: { mediatype: "sticker" },
2221
+ content: proto.Message.encode({ stickerMessage: plainSticker }),
2222
+ },
2223
+ ],
2224
+ }));
2225
+ if (nlAudio && (nlAudio.url || nlAudio.directPath)) {
2226
+ transport.sendEncrypted(encodeWABinaryNode({
2227
+ tag: "message",
2228
+ attrs: { id: generateMessageIDV2(meJid), to: jid, type: "media" },
2229
+ content: [
2230
+ {
2231
+ tag: "plaintext",
2232
+ attrs: { mediatype: nlAudio.ptt ? "ptt" : "audio" },
2233
+ content: proto.Message.encode({ audioMessage: nlAudio }),
2234
+ },
2235
+ ],
2236
+ }));
2237
+ }
2238
+ }
2239
+ else {
2240
+ const nlPlaintext = isNlDelete
2241
+ ? Buffer.alloc(0)
2242
+ : isNlEdit && waMsg.protocolMessage?.editedMessage
2243
+ ? proto.Message.encode(waMsg.protocolMessage.editedMessage)
2244
+ : proto.Message.encode(waMsg);
2245
+ transport.sendEncrypted(encodeWABinaryNode({
2246
+ tag: "message",
2247
+ attrs: {
2248
+ id: nlMsgId,
2249
+ to: jid,
2250
+ type: stanzaType,
2251
+ ...(nlEditAttr ? { edit: nlEditAttr } : {}),
1801
2252
  },
1802
- ],
1803
- }));
2253
+ content: [
2254
+ {
2255
+ tag: "plaintext",
2256
+ attrs: !isNlDelete && encMediatype ? { mediatype: encMediatype } : {},
2257
+ content: nlPlaintext,
2258
+ },
2259
+ ],
2260
+ }));
2261
+ }
1804
2262
  }
1805
2263
  else if (jid.endsWith("@g.us")) {
1806
2264
  const meta = await sock.groupMetadata(jid);
@@ -1809,7 +2267,16 @@ export function makeWASocket(config = {}) {
1809
2267
  .filter(Boolean);
1810
2268
  const meLid = authCreds.me?.lid ?? sock.user?.lid;
1811
2269
  const rawDevices = await getDevices(participants.length ? participants : [meJid]);
1812
- const devices = rawDevices.filter((d) => d !== meJid && (!meLid || d !== meLid));
2270
+ const devices = rawDevices.filter((d) => {
2271
+ if (d === meJid || (meLid && d === meLid))
2272
+ return false;
2273
+ const dec = jidDecode(d);
2274
+ if (!dec || dec.device === 99)
2275
+ return false;
2276
+ if (d.endsWith("@hosted") || d.endsWith("@hosted.lid"))
2277
+ return false;
2278
+ return true;
2279
+ });
1813
2280
  const addrMode = meta.addressingMode || (participants.some((p) => p.endsWith("@lid")) ? "lid" : "pn");
1814
2281
  const groupSender = addrMode === "lid" && meLid ? meLid : meJid;
1815
2282
  const groupKey = `${jid}:${jidToSignalAddress(groupSender)}`;
@@ -1817,7 +2284,7 @@ export function makeWASocket(config = {}) {
1817
2284
  const skmsgBytes = await signalMgr.encryptGroupMessage(groupKey, padded);
1818
2285
  let sentTo = senderKeyMemory.get(jid);
1819
2286
  if (!sentTo) {
1820
- const savedMem = (await getKey("sender-key-memory", jid));
2287
+ const savedMem = (await getKey("sender-key-memory-v3", jid));
1821
2288
  sentTo = new Set(Array.isArray(savedMem) ? savedMem : []);
1822
2289
  senderKeyMemory.set(jid, sentTo);
1823
2290
  }
@@ -1847,7 +2314,7 @@ export function makeWASocket(config = {}) {
1847
2314
  catch {
1848
2315
  }
1849
2316
  }
1850
- await setKey("sender-key-memory", jid, Array.from(sentTo));
2317
+ await setKey("sender-key-memory-v3", jid, Array.from(sentTo));
1851
2318
  }
1852
2319
  transport.sendEncrypted(encodeWABinaryNode({
1853
2320
  tag: "message",
@@ -1856,15 +2323,18 @@ export function makeWASocket(config = {}) {
1856
2323
  to: jid,
1857
2324
  type: stanzaType,
1858
2325
  addressing_mode: addrMode,
2326
+ ...(meta.ephemeralDuration && meta.ephemeralDuration > 0
2327
+ ? { expiration: String(meta.ephemeralDuration) }
2328
+ : {}),
1859
2329
  ...(deleteEditAttr ? { edit: deleteEditAttr } : {}),
1860
2330
  },
1861
2331
  content: [
1862
- ...(participantNodes.length ? [{ tag: "participants", attrs: {}, content: participantNodes }] : []),
1863
2332
  {
1864
2333
  tag: "enc",
1865
2334
  attrs: { v: "2", type: "skmsg", ...(encMediatype ? { mediatype: encMediatype } : {}) },
1866
2335
  content: skmsgBytes,
1867
2336
  },
2337
+ ...(participantNodes.length ? [{ tag: "participants", attrs: {}, content: participantNodes }] : []),
1868
2338
  ...(hasPkmsg ? buildDeviceIdentityNode() : []),
1869
2339
  ...buildButtonAddonNodes(),
1870
2340
  ],
@@ -1984,7 +2454,6 @@ export function makeWASocket(config = {}) {
1984
2454
  return { auth: mc?.attrs?.auth ?? "", hosts };
1985
2455
  },
1986
2456
  async waUploadToServer(stream, opts = {}) {
1987
- const buf = stream instanceof Uint8Array ? stream : await toBuffer(stream);
1988
2457
  const mType = opts.mediaType ?? "document";
1989
2458
  const pathMap = {
1990
2459
  image: "/mms/image",
@@ -1994,15 +2463,26 @@ export function makeWASocket(config = {}) {
1994
2463
  sticker: "/mms/image",
1995
2464
  document: "/mms/document",
1996
2465
  };
1997
- const enc = encryptWaMedia(buf, mType);
2466
+ let encData;
2467
+ let fileEncSha256B64;
2468
+ if (opts.encData && opts.fileEncSha256B64) {
2469
+ encData = opts.encData;
2470
+ fileEncSha256B64 = opts.fileEncSha256B64;
2471
+ }
2472
+ else {
2473
+ const buf = stream instanceof Uint8Array ? stream : await toBuffer(stream);
2474
+ const enc = encryptWaMedia(buf, mType);
2475
+ encData = enc.encData;
2476
+ fileEncSha256B64 = enc.fileEncSha256.toString("base64");
2477
+ }
1998
2478
  const mc = await sock.refreshMediaConn();
1999
2479
  const host = mc.hosts[0]?.hostname ?? "mmg.whatsapp.net";
2000
- const token = Buffer.from(enc.fileEncSha256).toString("base64url");
2480
+ const token = Buffer.from(fileEncSha256B64, "base64").toString("base64url");
2001
2481
  const upUrl = `https://${host}${pathMap[mType] ?? "/mms/document"}/${token}?auth=${encodeURIComponent(mc.auth)}&token=${token}`;
2002
2482
  const res = await fetch(upUrl, {
2003
2483
  method: "POST",
2004
2484
  headers: { "Content-Type": "application/octet-stream", Origin: "https://web.whatsapp.com" },
2005
- body: new Uint8Array(enc.encData),
2485
+ body: new Uint8Array(encData),
2006
2486
  });
2007
2487
  if (!res.ok)
2008
2488
  throw new Error(`Media upload failed (${res.status})`);
@@ -2075,29 +2555,8 @@ export function makeWASocket(config = {}) {
2075
2555
  },
2076
2556
  async groupMetadata(jid) {
2077
2557
  const cached = groupCache.get(jid);
2078
- if (cached && cached.participants.length > 0)
2558
+ if (cached && cached.participants?.length > 0)
2079
2559
  return { id: jid, ...cached };
2080
- const parseGroupNode = (grp) => {
2081
- const subject = grp.attrs?.subject ?? "";
2082
- const addressingMode = grp.attrs?.addressing_mode;
2083
- const participants = [];
2084
- if (Array.isArray(grp.content)) {
2085
- for (const c of grp.content) {
2086
- if (c.tag === "participant" && c.attrs?.jid) {
2087
- rememberLidPn(c.attrs.jid, c.attrs.phone_number);
2088
- const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
2089
- const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
2090
- participants.push({
2091
- id: pnId,
2092
- ...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
2093
- ...(lidVal ? { lid: lidVal } : {}),
2094
- admin: c.attrs.type,
2095
- });
2096
- }
2097
- }
2098
- }
2099
- return { subject, addressingMode, participants };
2100
- };
2101
2560
  try {
2102
2561
  const res = await sendQuery({
2103
2562
  tag: "iq",
@@ -2106,11 +2565,11 @@ export function makeWASocket(config = {}) {
2106
2565
  });
2107
2566
  const grp = Array.isArray(res.content) ? res.content.find((c) => c.tag === "group") : undefined;
2108
2567
  if (grp) {
2109
- const parsed = parseGroupNode(grp);
2568
+ const parsed = parseGroupMetadataNode(grp, jid);
2110
2569
  if (parsed.participants.length > 0 || parsed.subject) {
2111
2570
  groupCache.set(jid, parsed);
2112
2571
  }
2113
- return { id: jid, ...parsed };
2572
+ return parsed;
2114
2573
  }
2115
2574
  }
2116
2575
  catch {
@@ -2132,11 +2591,11 @@ export function makeWASocket(config = {}) {
2132
2591
  if (Array.isArray(groupsNode?.content)) {
2133
2592
  for (const g of groupsNode.content) {
2134
2593
  if (g.tag === "group" && (g.attrs?.id === jid || g.attrs?.id === targetId)) {
2135
- const parsed = parseGroupNode(g);
2594
+ const parsed = parseGroupMetadataNode(g, jid);
2136
2595
  if (parsed.participants.length > 0 || parsed.subject) {
2137
2596
  groupCache.set(jid, parsed);
2138
2597
  }
2139
- return { id: jid, ...parsed };
2598
+ return parsed;
2140
2599
  }
2141
2600
  }
2142
2601
  }
@@ -2255,24 +2714,8 @@ export function makeWASocket(config = {}) {
2255
2714
  if (g.tag !== "group" || !g.attrs?.id)
2256
2715
  continue;
2257
2716
  const gid = g.attrs.id.includes("@") ? g.attrs.id : `${g.attrs.id}@g.us`;
2258
- const participants = [];
2259
- if (Array.isArray(g.content)) {
2260
- for (const c of g.content) {
2261
- if (c.tag === "participant" && c.attrs?.jid) {
2262
- rememberLidPn(c.attrs.jid, c.attrs.phone_number);
2263
- const pnId = c.attrs.phone_number ? jidNormalizedUser(c.attrs.phone_number) : resolvePnJid(c.attrs.jid);
2264
- const lidVal = c.attrs.lid || (c.attrs.jid.endsWith("@lid") ? c.attrs.jid : undefined);
2265
- participants.push({
2266
- id: pnId,
2267
- ...(c.attrs.phone_number ? { phoneNumber: c.attrs.phone_number } : {}),
2268
- ...(lidVal ? { lid: lidVal } : {}),
2269
- admin: c.attrs.type,
2270
- });
2271
- }
2272
- }
2273
- }
2274
- const meta = { id: gid, subject: g.attrs.subject ?? "", addressingMode: g.attrs.addressing_mode, participants };
2275
- groupCache.set(gid, { subject: meta.subject, addressingMode: meta.addressingMode, participants });
2717
+ const meta = parseGroupMetadataNode(g, gid);
2718
+ groupCache.set(gid, meta);
2276
2719
  out[gid] = meta;
2277
2720
  }
2278
2721
  }
@@ -2420,42 +2863,125 @@ export function makeWASocket(config = {}) {
2420
2863
  export function normalizeMessageContent(content) {
2421
2864
  if (!content || typeof content !== "object")
2422
2865
  return content;
2423
- for (const key of [
2866
+ const wrapperKeys = [
2424
2867
  "ephemeralMessage",
2425
2868
  "viewOnceMessage",
2426
2869
  "viewOnceMessageV2",
2427
2870
  "viewOnceMessageV2Extension",
2428
2871
  "documentWithCaptionMessage",
2429
2872
  "editedMessage",
2430
- ]) {
2431
- if (content[key]?.message) {
2432
- return normalizeMessageContent(content[key].message);
2873
+ "lottieStickerMessage",
2874
+ "groupMentionedMessage",
2875
+ "botInvokeMessage",
2876
+ "associatedChildMessage",
2877
+ "groupStatusMessage",
2878
+ "groupStatusMessageV2",
2879
+ "groupStatusMentionMessage",
2880
+ "eventCoverImage",
2881
+ "statusMentionMessage",
2882
+ "pollCreationOptionImageMessage",
2883
+ "pollCreationMessageV4",
2884
+ "botForwardedMessage",
2885
+ "audioStickerMessage",
2886
+ ];
2887
+ let cur = content;
2888
+ for (let depth = 0; depth < 5; depth++) {
2889
+ let unwrapped = false;
2890
+ for (const key of wrapperKeys) {
2891
+ if (cur?.[key]?.message) {
2892
+ cur = cur[key].message;
2893
+ unwrapped = true;
2894
+ break;
2895
+ }
2433
2896
  }
2897
+ if (!unwrapped)
2898
+ break;
2434
2899
  }
2435
- return content;
2900
+ return cur;
2436
2901
  }
2437
2902
  export function extractMessageContent(content) {
2438
- return normalizeMessageContent(content);
2903
+ const extractFromTemplate = (msg) => {
2904
+ if (msg?.imageMessage)
2905
+ return { imageMessage: msg.imageMessage };
2906
+ if (msg?.documentMessage)
2907
+ return { documentMessage: msg.documentMessage };
2908
+ if (msg?.videoMessage)
2909
+ return { videoMessage: msg.videoMessage };
2910
+ if (msg?.locationMessage)
2911
+ return { locationMessage: msg.locationMessage };
2912
+ return { conversation: msg?.contentText ?? msg?.hydratedContentText ?? "" };
2913
+ };
2914
+ const norm = normalizeMessageContent(content);
2915
+ if (norm?.buttonsMessage)
2916
+ return extractFromTemplate(norm.buttonsMessage);
2917
+ if (norm?.templateMessage?.hydratedFourRowTemplate)
2918
+ return extractFromTemplate(norm.templateMessage.hydratedFourRowTemplate);
2919
+ if (norm?.templateMessage?.hydratedTemplate)
2920
+ return extractFromTemplate(norm.templateMessage.hydratedTemplate);
2921
+ if (norm?.templateMessage?.fourRowTemplate)
2922
+ return extractFromTemplate(norm.templateMessage.fourRowTemplate);
2923
+ return norm;
2439
2924
  }
2440
- export async function downloadMediaMessage(msg, type = "buffer") {
2441
- const inner = normalizeMessageContent(msg?.message ?? msg);
2442
- const mediaKey = Object.keys(inner || {}).find((k) => k.endsWith("Message")) ?? "imageMessage";
2443
- const mediaType = mediaKey.replace("Message", "");
2925
+ export async function downloadMediaMessage(msg, type = "buffer", _options, _ctx) {
2926
+ const inner = extractMessageContent(msg?.message ?? msg);
2927
+ const mediaKey = Object.keys(inner || {}).find((k) => ["imageMessage", "videoMessage", "ptvMessage", "audioMessage", "documentMessage", "stickerMessage", "stickerPackMessage"].includes(k)) ??
2928
+ Object.keys(inner || {}).find((k) => k.endsWith("Message")) ??
2929
+ "imageMessage";
2930
+ const rawType = mediaKey.replace("Message", "");
2931
+ const mediaType = (rawType === "stickerPack" ? "sticker-pack" : rawType);
2444
2932
  const stream = await downloadContentFromMessage(inner[mediaKey], mediaType);
2445
2933
  return type === "stream" ? stream : await toBuffer(stream);
2446
2934
  }
2447
- export async function prepareWAMessageMedia(media, _options) {
2935
+ export async function prepareWAMessageMedia(media, options) {
2936
+ const defaultMime = {
2937
+ image: "image/jpeg",
2938
+ video: "video/mp4",
2939
+ audio: "audio/mpeg",
2940
+ document: "application/octet-stream",
2941
+ sticker: "image/webp",
2942
+ };
2448
2943
  for (const kind of ["image", "video", "audio", "document", "sticker"]) {
2449
- if (media[kind]) {
2450
- const buf = Buffer.isBuffer(media[kind]) ? media[kind] : Buffer.from(media[kind]);
2451
- const enc = encryptWaMedia(buf, kind);
2944
+ const raw = media[kind];
2945
+ if (raw) {
2946
+ let buf;
2947
+ if (Buffer.isBuffer(raw))
2948
+ buf = raw;
2949
+ else if (raw instanceof Uint8Array)
2950
+ buf = Buffer.from(raw);
2951
+ else if (typeof raw === "object" && typeof raw.url === "string") {
2952
+ const res = await fetch(raw.url);
2953
+ buf = Buffer.from(await res.arrayBuffer());
2954
+ }
2955
+ else {
2956
+ buf = Buffer.from(raw);
2957
+ }
2958
+ const encType = kind === "audio" && media.ptt ? "ptt" : kind;
2959
+ const enc = encryptWaMedia(buf, encType);
2960
+ let uploaded;
2961
+ if (typeof options?.upload === "function") {
2962
+ uploaded = await options.upload(Buffer.from(enc.encData), {
2963
+ mediaType: encType,
2964
+ fileEncSha256B64: enc.fileEncSha256.toString("base64"),
2965
+ encData: enc.encData,
2966
+ });
2967
+ }
2452
2968
  return {
2453
2969
  [`${kind}Message`]: {
2970
+ ...(uploaded?.mediaUrl || uploaded?.url ? { url: uploaded.mediaUrl || uploaded.url } : {}),
2971
+ ...(uploaded?.directPath || uploaded?.direct_path
2972
+ ? { directPath: uploaded.directPath || uploaded.direct_path }
2973
+ : {}),
2454
2974
  mediaKey: enc.mediaKey,
2455
2975
  fileSha256: enc.fileSha256,
2456
2976
  fileEncSha256: enc.fileEncSha256,
2457
2977
  fileLength: buf.length,
2458
- mimetype: media.mimetype,
2978
+ mediaKeyTimestamp: Math.floor(Date.now() / 1000),
2979
+ mimetype: media.mimetype ?? (kind === "audio" && media.ptt ? "audio/ogg; codecs=opus" : defaultMime[kind]),
2980
+ ...(typeof media.ptt === "boolean" ? { ptt: media.ptt } : {}),
2981
+ ...(typeof media.seconds === "number" ? { seconds: media.seconds } : {}),
2982
+ ...(typeof media.isAnimated === "boolean" ? { isAnimated: media.isAnimated } : {}),
2983
+ ...(typeof media.caption === "string" ? { caption: media.caption } : {}),
2984
+ ...(typeof media.fileName === "string" ? { fileName: media.fileName } : {}),
2459
2985
  },
2460
2986
  };
2461
2987
  }