kage-baileys 3.0.6 → 3.2.3

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 (216) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/WAProto/WAProto.proto +3395 -415
  4. package/WAProto/compat.cjs +12 -0
  5. package/WAProto/index.d.ts +47104 -19888
  6. package/WAProto/index.js +131979 -57361
  7. package/lib/Addon/http-error.js +43 -0
  8. package/lib/Addon/index.js +32 -0
  9. package/lib/Addon/keyed-db.js +250 -0
  10. package/lib/Addon/link-preview.js +82 -0
  11. package/lib/Defaults/baileys-version.json +3 -0
  12. package/lib/Defaults/connection.js +110 -0
  13. package/lib/Defaults/constants.js +156 -0
  14. package/lib/Defaults/history.js +46 -0
  15. package/lib/Defaults/index.js +230 -0
  16. package/lib/Defaults/media.js +104 -0
  17. package/lib/Defaults/phonenumber-mcc.json +223 -0
  18. package/lib/Defaults/prefix.js +44 -0
  19. package/lib/Extensions/business-advanced.js +382 -0
  20. package/lib/Extensions/business.js +159 -0
  21. package/lib/Extensions/chats-advanced.js +1106 -0
  22. package/lib/Extensions/chats.js +349 -0
  23. package/lib/Extensions/communities-advanced.js +430 -0
  24. package/lib/Extensions/community.js +94 -0
  25. package/lib/Extensions/groups-advanced.js +343 -0
  26. package/lib/Extensions/index.js +30 -0
  27. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  28. package/lib/Extensions/messages-send-advanced.js +622 -0
  29. package/lib/Extensions/messages-send.js +1380 -0
  30. package/lib/Extensions/newsletter-advanced.js +228 -0
  31. package/lib/Extensions/newsletter.js +72 -0
  32. package/lib/Extensions/socket.js +389 -0
  33. package/lib/Modded/message_builder.js +2084 -4
  34. package/lib/Signal/Group/ciphertext-message.js +54 -0
  35. package/lib/Signal/Group/group-session-builder.js +124 -0
  36. package/lib/Signal/Group/group_cipher.js +216 -0
  37. package/lib/Signal/Group/index.js +124 -0
  38. package/lib/Signal/Group/keyhelper.js +108 -0
  39. package/lib/Signal/Group/sender-chain-key.js +83 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  41. package/lib/Signal/Group/sender-key-message.js +166 -0
  42. package/lib/Signal/Group/sender-key-name.js +130 -0
  43. package/lib/Signal/Group/sender-key-record.js +113 -0
  44. package/lib/Signal/Group/sender-key-state.js +208 -0
  45. package/lib/Signal/Group/sender-message-key.js +82 -0
  46. package/lib/Signal/libsignal.js +935 -0
  47. package/lib/Signal/lid-mapping.js +545 -1
  48. package/lib/Socket/Client/index.js +60 -0
  49. package/lib/Socket/Client/types.js +51 -0
  50. package/lib/Socket/Client/websocket.js +152 -0
  51. package/lib/Socket/business.js +831 -0
  52. package/lib/Socket/chats.js +2535 -49
  53. package/lib/Socket/communities.js +450 -1
  54. package/lib/Socket/community.js +1022 -0
  55. package/lib/Socket/dugong.js +1 -1
  56. package/lib/Socket/groups.js +747 -0
  57. package/lib/Socket/index.js +60 -2
  58. package/lib/Socket/messages-recv.js +3450 -5
  59. package/lib/Socket/messages-send.js +3123 -0
  60. package/lib/Socket/mex.js +126 -1
  61. package/lib/Socket/newsletter.js +465 -0
  62. package/lib/Socket/socket.js +2217 -1
  63. package/lib/Store/index.js +79 -0
  64. package/lib/Store/make-cache-manager-store.js +186 -0
  65. package/lib/Store/make-in-memory-store.js +878 -0
  66. package/lib/Store/make-ordered-dictionary.js +187 -0
  67. package/lib/Store/object-repository.js +78 -0
  68. package/lib/Types/Auth.js +25 -0
  69. package/lib/Types/Bussines.js +25 -1
  70. package/lib/Types/Call.js +25 -0
  71. package/lib/Types/Chat.js +39 -0
  72. package/lib/Types/Contact.js +25 -0
  73. package/lib/Types/Events.js +25 -0
  74. package/lib/Types/GroupMetadata.js +25 -0
  75. package/lib/Types/Label.js +76 -0
  76. package/lib/Types/LabelAssociation.js +40 -0
  77. package/lib/Types/Message.js +57 -0
  78. package/lib/Types/Mex.js +56 -1
  79. package/lib/Types/MexUpdates.js +46 -0
  80. package/lib/Types/Newsletter.js +56 -0
  81. package/lib/Types/Product.js +25 -0
  82. package/lib/Types/RichType.js +23 -0
  83. package/lib/Types/Signal.js +25 -0
  84. package/lib/Types/Socket.js +25 -0
  85. package/lib/Types/State.js +92 -0
  86. package/lib/Types/USync.js +25 -0
  87. package/lib/Types/index.js +133 -0
  88. package/lib/Utils/auth-utils.js +703 -0
  89. package/lib/Utils/automation-tools.js +51 -16
  90. package/lib/Utils/baileys-event-stream.js +146 -0
  91. package/lib/Utils/browser-utils.js +95 -0
  92. package/lib/Utils/business.js +525 -0
  93. package/lib/Utils/chat-utils.js +1861 -0
  94. package/lib/Utils/companion-reg-client-utils.js +55 -1
  95. package/lib/Utils/crypto.js +355 -0
  96. package/lib/Utils/decode-wa-message.js +709 -0
  97. package/lib/Utils/event-buffer.js +1323 -8
  98. package/lib/Utils/generics.js +945 -1
  99. package/lib/Utils/history.js +266 -0
  100. package/lib/Utils/identity-change-handler.js +62 -1
  101. package/lib/Utils/index.js +114 -0
  102. package/lib/Utils/link-preview.js +179 -0
  103. package/lib/Utils/logger.js +42 -0
  104. package/lib/Utils/lt-hash.js +73 -0
  105. package/lib/Utils/make-mutex.js +104 -0
  106. package/lib/Utils/message-inspector.js +110 -0
  107. package/lib/Utils/message-retry-manager.js +507 -2
  108. package/lib/Utils/messages-media.js +1931 -1
  109. package/lib/Utils/messages.js +3748 -0
  110. package/lib/Utils/noise-handler.js +423 -0
  111. package/lib/Utils/offline-node-processor.js +53 -1
  112. package/lib/Utils/pre-key-manager.js +255 -1
  113. package/lib/Utils/process-message.js +1592 -0
  114. package/lib/Utils/reporting-utils.js +272 -1
  115. package/lib/Utils/rich-message-utils.js +377 -0
  116. package/lib/Utils/rich-messages.js +1 -1
  117. package/lib/Utils/signal.js +437 -0
  118. package/lib/Utils/stanza-ack.js +51 -1
  119. package/lib/Utils/status-refresh.js +37 -0
  120. package/lib/Utils/status-tools.js +4 -2
  121. package/lib/Utils/sync-action-utils.js +63 -1
  122. package/lib/Utils/tc-token-utils.js +185 -1
  123. package/lib/Utils/terminal-banner.js +31 -0
  124. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  125. package/lib/Utils/use-single-file-auth-state.js +108 -0
  126. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  127. package/lib/Utils/validate-connection.js +497 -1
  128. package/lib/Utils/view-once-compat.js +13 -5
  129. package/lib/VoIP/audio-feeder.js +150 -0
  130. package/lib/VoIP/index.js +289 -0
  131. package/lib/VoIP/relay-transport.js +608 -0
  132. package/lib/VoIP/signaling.js +583 -0
  133. package/lib/VoIP/types.js +30 -0
  134. package/lib/VoIP/wasm-engine.js +1261 -2
  135. package/lib/VoIP/worker-bootstrap.js +1090 -2
  136. package/lib/WABinary/constants.js +2805 -0
  137. package/lib/WABinary/decode.js +649 -2
  138. package/lib/WABinary/encode.js +564 -2
  139. package/lib/WABinary/generic-utils.js +401 -0
  140. package/lib/WABinary/index.js +82 -0
  141. package/lib/WABinary/jid-utils.js +290 -0
  142. package/lib/WABinary/types.js +25 -0
  143. package/lib/WAM/BinaryInfo.js +50 -0
  144. package/lib/WAM/constants.js +45747 -0
  145. package/lib/WAM/encode.js +393 -0
  146. package/lib/WAM/index.js +78 -0
  147. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  148. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  151. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  153. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  154. package/lib/WAUSync/Protocols/index.js +83 -0
  155. package/lib/WAUSync/USyncQuery.js +241 -2
  156. package/lib/WAUSync/USyncUser.js +86 -0
  157. package/lib/WAUSync/index.js +78 -0
  158. package/lib/assets/wasm/loader.js +1875 -1
  159. package/lib/assets/wasm/worker-modules.js +11047 -1
  160. package/lib/index.d.ts +126 -0
  161. package/lib/index.js +53 -21
  162. package/lib/index.mjs +437 -0
  163. package/licenses/upstream-MIT.txt +22 -0
  164. package/maintenance/api-coverage.json +1642 -0
  165. package/maintenance/archivos-sha256.json +207 -0
  166. package/maintenance/consumer-validation.log +3 -0
  167. package/maintenance/dependency-audit.json +4 -4
  168. package/maintenance/extension-inventory.json +57 -0
  169. package/maintenance/protocol-update.json +1101 -0
  170. package/maintenance/protocol-wire-audit.json +4 -0
  171. package/maintenance/reference-socket-surface.json +209 -0
  172. package/maintenance/resumen-validacion.json +50 -0
  173. package/maintenance/validation.log +2725 -0
  174. package/maintenance/verification.json +566 -0
  175. package/package.json +107 -9
  176. package/scripts/check-imports.cjs +10 -0
  177. package/scripts/check-package.cjs +40 -0
  178. package/scripts/check-syntax.cjs +1 -1
  179. package/scripts/generate-protobuf.cjs +6 -1
  180. package/scripts/generate-public-types.cjs +9 -0
  181. package/scripts/kage-base64-fix.cjs +45 -0
  182. package/scripts/maintenance.cjs +10 -0
  183. package/test/advanced.test.cjs +24 -0
  184. package/test/base64-fix.test.cjs +49 -0
  185. package/test/maintenance.test.cjs +1 -1
  186. package/test/npm-publication.test.cjs +141 -0
  187. package/test/recepcion-reparada.test.cjs +98 -0
  188. package/test/resilience-binary.test.cjs +69 -0
  189. package/test/resilience-transport.test.cjs +34 -0
  190. package/test/types.test.ts +5 -0
  191. package/test/upgrade.test.cjs +104 -0
  192. package/tsconfig.json +20 -0
  193. package/WAProto/p.html +0 -1
  194. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  195. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  196. package/lib/KageExtra/VoIP/index.js +0 -282
  197. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  198. package/lib/KageExtra/VoIP/signaling.js +0 -603
  199. package/lib/KageExtra/VoIP/types.js +0 -17
  200. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  201. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  202. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  203. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  204. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  205. package/lib/KageExtra/index.js +0 -3
  206. package/lib/KageExtra/package.json +0 -1
  207. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  209. package/maintenance/revision-full-check.txt +0 -1097
  210. package/maintenance/revision-library-tests.tap +0 -1088
  211. package/maintenance/revision-protobuf.txt +0 -5
  212. package/maintenance/revision-syntax.txt +0 -5
  213. package/maintenance/schema-coverage.json +0 -23
  214. package/maintenance/schema-merge.json +0 -30
  215. package/maintenance/validation-node20.txt +0 -191
  216. package/maintenance/validation-node22.txt +0 -237
@@ -402,3 +402,1595 @@ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderRes
402
402
  }
403
403
  };
404
404
  exports.default = processMessage;
405
+
406
+ // Kage: compatibilidad de API.
407
+ const __kageModule77 = (() => {
408
+ const module = { exports: {} }; const exports = module.exports;
409
+ "use strict"
410
+
411
+ Object.defineProperty(exports, "__esModule", { value: true })
412
+
413
+ const { proto } = require("../../WAProto")
414
+ const { WAMessageStubType } = require("../Types")
415
+ const {
416
+ getDevice,
417
+ getContentType,
418
+ normalizeMessageContent
419
+ } = require("../Utils")
420
+ const {
421
+ areJidsSameUser,
422
+ isHostedLidUser,
423
+ isHostedPnUser,
424
+ isJidBroadcast,
425
+ isJidStatusBroadcast,
426
+ isLidUser,
427
+ jidDecode,
428
+ jidEncode,
429
+ jidNormalizedUser
430
+ } = require("../WABinary")
431
+ const {
432
+ aesDecryptGCM,
433
+ hmacSign
434
+ } = require("./crypto")
435
+ const {
436
+ getKeyAuthor,
437
+ toNumber
438
+ } = require("./generics")
439
+ const { downloadAndProcessHistorySyncNotification } = require("./history")
440
+
441
+ const REAL_MSG_STUB_TYPES = new Set([
442
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
443
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
444
+ WAMessageStubType.CALL_MISSED_VIDEO,
445
+ WAMessageStubType.CALL_MISSED_VOICE
446
+ ])
447
+
448
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
449
+ WAMessageStubType.GROUP_PARTICIPANT_ADD
450
+ ])
451
+
452
+ /** Cleans a received message to further processing */
453
+ const cleanMessage = (message, meId, meLid) => {
454
+ // ensure remoteJid and participant doesn't have device or agent in it
455
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
456
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid')
457
+ }
458
+ else {
459
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid)
460
+ }
461
+
462
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
463
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid')
464
+ }
465
+ else {
466
+ message.key.participant = jidNormalizedUser(message.key.participant)
467
+ }
468
+ const content = normalizeMessageContent(message.message)
469
+
470
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
471
+ if (content?.reactionMessage) {
472
+ normaliseKey(content.reactionMessage.key)
473
+ }
474
+
475
+ if (content?.pollUpdateMessage) {
476
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
477
+ }
478
+
479
+ function normaliseKey(msgKey) {
480
+ // if the reaction is from another user
481
+ // we've to correctly map the key to this user's perspective
482
+ if (!message.key.fromMe) {
483
+ // if the sender believed the message being reacted to is not from them
484
+ // we've to correct the key to be from them, or some other participant
485
+ msgKey.fromMe = !msgKey.fromMe
486
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
487
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
488
+ : // if the message being reacted to, was from them
489
+ // fromMe automatically becomes false
490
+ false
491
+ // set the remoteJid to being the same as the chat the message came from
492
+ // TODO: investigate inconsistencies
493
+ msgKey.remoteJid = message.key.remoteJid
494
+ // set participant of the message
495
+ msgKey.participant = msgKey.participant || message.key.participant
496
+ }
497
+ }
498
+ }
499
+
500
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
501
+ const isRealMessage = (message) => {
502
+ const normalizedContent = normalizeMessageContent(message.message)
503
+ const hasSomeContent = !!getContentType(normalizedContent)
504
+ return ((!!normalizedContent ||
505
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
506
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
507
+ hasSomeContent &&
508
+ !normalizedContent?.protocolMessage &&
509
+ !normalizedContent?.reactionMessage &&
510
+ !normalizedContent?.pollUpdateMessage)
511
+ }
512
+
513
+ const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType
514
+
515
+ /**
516
+ * Get the ID of the chat from the given key.
517
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
518
+ */
519
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
520
+ if (isJidBroadcast(remoteJid)
521
+ && !isJidStatusBroadcast(remoteJid)
522
+ && !fromMe) {
523
+ return participant
524
+ }
525
+ return remoteJid
526
+ }
527
+
528
+ /**
529
+ * Decrypt a poll vote
530
+ * @param vote encrypted vote
531
+ * @param ctx additional info about the poll required for decryption
532
+ * @returns list of SHA256 options
533
+ */
534
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
535
+ const sign = Buffer.concat([
536
+ toBinary(pollMsgId),
537
+ toBinary(pollCreatorJid),
538
+ toBinary(voterJid),
539
+ toBinary('Poll Vote'),
540
+ new Uint8Array([1])
541
+ ])
542
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
543
+ const decKey = hmacSign(sign, key0, 'sha256')
544
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`)
545
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
546
+
547
+ return proto.Message.PollVoteMessage.decode(decrypted)
548
+
549
+ function toBinary(txt) {
550
+ return Buffer.from(txt)
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Decrypt an event edit
556
+ * @param edit encrypted event edit
557
+ * @returns message
558
+ */
559
+ function decryptEventEdit({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
560
+ const sign = Buffer.concat([
561
+ toBinary(eventMsgId),
562
+ toBinary(eventCreatorJid),
563
+ toBinary(responderJid),
564
+ toBinary('Event Edit'),
565
+ new Uint8Array([1])
566
+ ])
567
+
568
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256')
569
+ const decKey = hmacSign(sign, key0, 'sha256')
570
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null)
571
+
572
+ return proto.Message.decode(decrypted)
573
+
574
+ function toBinary(txt) {
575
+ return Buffer.from(txt)
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Decrypt an event response
581
+ * @param response encrypted event response
582
+ * @param ctx additional info about the event required for decryption
583
+ * @returns event response message
584
+ */
585
+ function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
586
+ const sign = Buffer.concat([
587
+ toBinary(eventMsgId),
588
+ toBinary(eventCreatorJid),
589
+ toBinary(responderJid),
590
+ toBinary('Event Response'),
591
+ new Uint8Array([1])
592
+ ])
593
+
594
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256')
595
+ const decKey = hmacSign(sign, key0, 'sha256')
596
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`)
597
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
598
+
599
+ return proto.Message.EventResponseMessage.decode(decrypted)
600
+
601
+ function toBinary(txt) {
602
+ return Buffer.from(txt)
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Decrypt an comment message
608
+ * @param comment encrypted comment message
609
+ * @returns message
610
+ */
611
+ function decryptComment({ encPayload, encIv }, { commentCreatorJid, commentMsgId, commentEncKey, commentJid }) {
612
+ const sign = Buffer.concat([
613
+ toBinary(commentMsgId),
614
+ toBinary(commentCreatorJid),
615
+ toBinary(commentJid),
616
+ toBinary('Enc Comment'),
617
+ new Uint8Array([1])
618
+ ])
619
+
620
+ const key0 = hmacSign(commentEncKey, new Uint8Array(32), 'sha256')
621
+ const decKey = hmacSign(sign, key0, 'sha256')
622
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null)
623
+
624
+ return proto.Message.decode(decrypted)
625
+
626
+ function toBinary(txt) {
627
+ return Buffer.from(txt)
628
+ }
629
+ }
630
+
631
+ /**
632
+ * Decrypt an reaction
633
+ * @param reaction encrypted reaction
634
+ * @returns reaction message
635
+ */
636
+ function decryptReaction({ encPayload, encIv }, { reactionCreatorJid, reactionMsgId, reactionEncKey, reactionJid }) {
637
+ const sign = Buffer.concat([
638
+ toBinary(reactionMsgId),
639
+ toBinary(reactionCreatorJid),
640
+ toBinary(reactionJid),
641
+ toBinary('Enc Reaction'),
642
+ new Uint8Array([1])
643
+ ])
644
+
645
+ const key0 = hmacSign(reactionEncKey, new Uint8Array(32), 'sha256')
646
+ const decKey = hmacSign(sign, key0, 'sha256')
647
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null)
648
+
649
+ return proto.Message.ReactionMessage.decode(decrypted)
650
+
651
+ function toBinary(txt) {
652
+ return Buffer.from(txt)
653
+ }
654
+ }
655
+
656
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
657
+ const meId = creds.me.id
658
+ const meLid = creds.me.lid
659
+ const { accountSettings } = creds
660
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) }
661
+ const isRealMsg = isRealMessage(message)
662
+ if (isRealMsg) {
663
+ chat.messages = [{ message }]
664
+ chat.conversationTimestamp = toNumber(message.messageTimestamp)
665
+ // only increment unread count if not CIPHERTEXT and from another person
666
+ if (shouldIncrementChatUnread(message)) {
667
+ chat.unreadCount = (chat.unreadCount || 0) + 1
668
+ }
669
+ }
670
+ const content = normalizeMessageContent(message.message)
671
+ // unarchive chat if it's a real message, or someone reacted to our message
672
+ // and we've the unarchive chats setting on
673
+ if (isRealMsg || content?.reactionMessage?.key?.fromMe
674
+ && accountSettings?.unarchiveChats) {
675
+ chat.archived = false
676
+ chat.readOnly = false
677
+ }
678
+ const protocolMsg = content?.protocolMessage
679
+ if (protocolMsg) {
680
+ switch (protocolMsg.type) {
681
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
682
+ const histNotification = protocolMsg.historySyncNotification
683
+ const process = shouldProcessHistoryMsg
684
+ const isLatest = !creds.processedHistoryMessages?.length
685
+
686
+ logger?.info({
687
+ histNotification,
688
+ process,
689
+ id: message.key.id,
690
+ isLatest
691
+ }, 'got history notification')
692
+
693
+ if (process) {
694
+ // TODO: investigate
695
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
696
+ ev.emit('creds.update', {
697
+ processedHistoryMessages: [
698
+ ...(creds.processedHistoryMessages || []),
699
+ { key: message.key, messageTimestamp: message.messageTimestamp }
700
+ ]
701
+ })
702
+ }
703
+
704
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options)
705
+ ev.emit('messaging-history.set', {
706
+ ...data,
707
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
708
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
709
+ })
710
+ }
711
+ break
712
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
713
+ const keys = protocolMsg.appStateSyncKeyShare.keys
714
+
715
+ if (keys?.length) {
716
+ let newAppStateSyncKeyId = ''
717
+
718
+ await keyStore.transaction(async () => {
719
+ const newKeys = []
720
+
721
+ for (const { keyData, keyId } of keys) {
722
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64')
723
+
724
+ newKeys.push(strKeyId)
725
+
726
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
727
+
728
+ newAppStateSyncKeyId = strKeyId
729
+ }
730
+
731
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
732
+ }, meId)
733
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
734
+ }
735
+
736
+ else {
737
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
738
+ }
739
+ break
740
+ case proto.Message.ProtocolMessage.Type.REVOKE:
741
+ ev.emit('messages.update', [
742
+ {
743
+ key: {
744
+ ...message.key,
745
+ id: protocolMsg.key.id
746
+ },
747
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
748
+ }
749
+ ])
750
+ break
751
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
752
+ Object.assign(chat, {
753
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
754
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
755
+ })
756
+ break
757
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
758
+ const response = protocolMsg.peerDataOperationRequestResponseMessage
759
+
760
+ if (response) {
761
+ await placeholderResendCache?.del(response.stanzaId)
762
+
763
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
764
+ const { peerDataOperationResult } = response
765
+
766
+ for (const result of peerDataOperationResult) {
767
+ const { placeholderMessageResendResponse: retryResponse } = result
768
+
769
+ //eslint-disable-next-line max-depth
770
+ if (retryResponse) {
771
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
772
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
773
+ // TODO: parse through proper message handling utilities (to add relevant key fields)
774
+ setTimeout(() => {
775
+ ev.emit('messages.upsert', {
776
+ messages: [webMessageInfo],
777
+ type: 'notify',
778
+ requestId: response.stanzaId
779
+ })
780
+ }, 500)
781
+ }
782
+ }
783
+ }
784
+ break
785
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
786
+ ev.emit('messages.update', [
787
+ {
788
+ // flip the sender / fromMe properties because they're in the perspective of the sender
789
+ key: { ...message.key, id: protocolMsg.key?.id },
790
+ update: {
791
+ message: {
792
+ editedMessage: {
793
+ message: protocolMsg.editedMessage
794
+ }
795
+ },
796
+ messageTimestamp: protocolMsg.timestampMs
797
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
798
+ : message.messageTimestamp
799
+ }
800
+ }
801
+ ])
802
+ break
803
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
804
+ const labelAssociationMsg = protocolMsg.memberLabel
805
+
806
+ if (labelAssociationMsg?.label) {
807
+ ev.emit('group.member-tag.update', {
808
+ groupId: chat.id,
809
+ label: labelAssociationMsg.label,
810
+ participant: message.key.participant,
811
+ participantAlt: message.key.participantAlt,
812
+ messageTimestamp: Number(message.messageTimestamp)
813
+ })
814
+ }
815
+ break
816
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
817
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload
818
+
819
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
820
+
821
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp')
822
+
823
+ const pairs = []
824
+
825
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
826
+ const lid = latestLid || assignedLid
827
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` })
828
+ }
829
+
830
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs)
831
+
832
+ if (pairs.length) {
833
+ for (const { pn, lid } of pairs) {
834
+ await signalRepository.migrateSession(pn, lid)
835
+ }
836
+ }
837
+ break
838
+ case proto.Message.ProtocolMessage.Type.LIMIT_SHARING:
839
+ ev.emit('limit-sharing.update', {
840
+ id: message.key.remoteJid,
841
+ author: areJidsSameUser(message.key.remoteJid, protocolMsg.key.remoteJid) ? jidNormalizedUser(meId) : message.key.remoteJid,
842
+ action: `${protocolMsg.limitSharing.sharingLimited ? 'on' : 'off'}`,
843
+ trigger: protocolMsg.limitSharing.trigger,
844
+ update_time: protocolMsg.limitSharing.limitSharingSettingTimestamp
845
+ })
846
+ break
847
+ }
848
+ }
849
+ else if (content?.reactionMessage) {
850
+ const reaction = {
851
+ ...content.reactionMessage,
852
+ key: message.key,
853
+ }
854
+ ev.emit('messages.reaction', [{
855
+ reaction,
856
+ key: content.reactionMessage?.key
857
+ }])
858
+ }
859
+ else if (message.messageStubType) {
860
+ const jid = message.key?.remoteJid
861
+
862
+ let participants
863
+
864
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
865
+ id: jid,
866
+ author: message.key.participant,
867
+ authorPn: message.key.participantAlt,
868
+ participants,
869
+ action
870
+ })
871
+
872
+ const emitGroupUpdate = (update) => {
873
+ ev.emit('groups.update', [
874
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
875
+ ])
876
+ }
877
+
878
+ const emitGroupRequestJoin = (participant, action, method) => {
879
+ ev.emit('group.join-request', {
880
+ id: jid,
881
+ author: message.key.participant,
882
+ authorPn: message.key.participantAlt,
883
+ participant: participant.lid,
884
+ participantPn: participant.pn,
885
+ action,
886
+ method: method
887
+ })
888
+ }
889
+
890
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)) // ADD SUPPORT FOR LID
891
+ switch (message.messageStubType) {
892
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
893
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || []
894
+ emitParticipantsUpdate('modify')
895
+ break
896
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
897
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
898
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || []
899
+ emitParticipantsUpdate('remove')
900
+
901
+ // mark the chat read only if you left the group
902
+ if (participantsIncludesMe()) {
903
+ chat.readOnly = true
904
+ }
905
+ break
906
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
907
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
908
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
909
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || []
910
+
911
+ if (participantsIncludesMe()) {
912
+ chat.readOnly = false
913
+ }
914
+
915
+ emitParticipantsUpdate('add')
916
+ break
917
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
918
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || []
919
+ emitParticipantsUpdate('demote')
920
+ break
921
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
922
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || []
923
+ emitParticipantsUpdate('promote')
924
+ break
925
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
926
+ const announceValue = message.messageStubParameters?.[0]
927
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
928
+ break
929
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
930
+ const restrictValue = message.messageStubParameters?.[0]
931
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
932
+ break
933
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
934
+ const name = message.messageStubParameters?.[0]
935
+ chat.name = name
936
+ emitGroupUpdate({ subject: name })
937
+ break
938
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
939
+ const description = message.messageStubParameters?.[0]
940
+ chat.description = description
941
+ emitGroupUpdate({ desc: description })
942
+ break
943
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
944
+ const code = message.messageStubParameters?.[0]
945
+ emitGroupUpdate({ inviteCode: code })
946
+ break
947
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
948
+ const memberAddValue = message.messageStubParameters?.[0]
949
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
950
+ break
951
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
952
+ const approvalMode = message.messageStubParameters?.[0]
953
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
954
+ break
955
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
956
+ const participant = JSON.parse(message.messageStubParameters?.[0])
957
+ const action = message.messageStubParameters?.[1]
958
+ const method = message.messageStubParameters?.[2]
959
+ emitGroupRequestJoin(participant, action, method)
960
+ break
961
+ }
962
+ }
963
+ else if (content?.pollUpdateMessage) {
964
+ const pollUpdate = content.pollUpdateMessage
965
+ const creationMsgKey = pollUpdate.pollCreationMessageKey
966
+
967
+ // we need to fetch the poll creation message to get the poll enc key
968
+ const pollMsg = await getMessage(creationMsgKey)
969
+ if (pollMsg) {
970
+ try {
971
+ const meLidNormalised = jidNormalizedUser(meLid)
972
+ const deviceType = getDevice(creationMsgKey.id)
973
+ const pollCreationFromMe = deviceType === 'baileys' ? true : false
974
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret
975
+ const voterJid = getKeyAuthor(message.key, meLidNormalised)
976
+
977
+ let pollCreatorJid = getKeyAuthor(creationMsgKey, meLidNormalised)
978
+
979
+ if (pollCreationFromMe) {
980
+ pollCreatorJid = meLidNormalised
981
+ }
982
+
983
+ if (!pollEncKey) {
984
+ logger?.warn({ vote: pollUpdate.vote, creationMsgKey }, 'poll creation: missing messageSecret for decryption')
985
+ } else {
986
+ const voteMsg = decryptPollVote(pollUpdate.vote, {
987
+ pollEncKey,
988
+ pollCreatorJid,
989
+ pollMsgId: creationMsgKey.id,
990
+ voterJid
991
+ })
992
+
993
+ ev.emit('messages.update', [
994
+ {
995
+ key: creationMsgKey,
996
+ update: {
997
+ pollUpdates: [
998
+ {
999
+ pollUpdateMessageKey: message.key,
1000
+ vote: voteMsg,
1001
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber()
1002
+ }
1003
+ ]
1004
+ }
1005
+ }
1006
+ ])
1007
+ }
1008
+ }
1009
+ catch (err) {
1010
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt poll vote')
1011
+ }
1012
+ }
1013
+ else {
1014
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update')
1015
+ }
1016
+ }
1017
+ else if (content?.secretEncryptedMessage) {
1018
+ const encEventEdit = content.secretEncryptedMessage
1019
+ const creationMsgKey = encEventEdit.targetMessageKey
1020
+
1021
+ if (proto.Message.SecretEncryptedMessage.SecretEncType[encEventEdit.secretEncType] !== 'EVENT_EDIT') return
1022
+
1023
+ // we need to fetch the event creation message to get the event enc key
1024
+ const eventMsg = await getMessage(creationMsgKey)
1025
+ if (eventMsg) {
1026
+ try {
1027
+ const meLidNormalised = jidNormalizedUser(meLid)
1028
+ const eventCreatorJid = getKeyAuthor(message.key, meLidNormalised)
1029
+ const responderJid = getKeyAuthor(message.key, meLidNormalised)
1030
+ const eventEncKey = eventMsg.messageContextInfo?.messageSecret
1031
+
1032
+ if (!eventEncKey) {
1033
+ logger?.warn({ encEventEdit, creationMsgKey }, 'event edit: missing messageSecret for decryption')
1034
+ } else {
1035
+ const responseMsg = decryptEventEdit(encEventEdit, {
1036
+ eventEncKey,
1037
+ eventCreatorJid,
1038
+ eventMsgId: creationMsgKey.id,
1039
+ responderJid
1040
+ })
1041
+ const content = normalizeMessageContent(responseMsg)
1042
+ const protocolMsg = content?.protocolMessage
1043
+
1044
+ ev.emit('messages.update', [
1045
+ {
1046
+ key: { ...message.key, id: protocolMsg.key?.id },
1047
+ update: {
1048
+ message: {
1049
+ messageContextInfo: responseMsg.messageContextInfo,
1050
+ editedMessage: {
1051
+ message: protocolMsg.editedMessage
1052
+ }
1053
+ },
1054
+ messageTimestamp: protocolMsg.timestampMs
1055
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
1056
+ : message.messageTimestamp
1057
+ }
1058
+ }
1059
+ ])
1060
+ }
1061
+ }
1062
+ catch (err) {
1063
+ logger?.warn({ err, creationMsgKey, encEventEdit }, 'failed to decrypt event edit')
1064
+ }
1065
+ }
1066
+ else {
1067
+ logger?.warn({ encEventEdit, creationMsgKey }, 'event creation message not found, cannot decrypt update')
1068
+ }
1069
+ }
1070
+ else if (content?.encEventResponseMessage) {
1071
+ const encEventResponse = content.encEventResponseMessage
1072
+ const creationMsgKey = encEventResponse.eventCreationMessageKey
1073
+
1074
+ // we need to fetch the event creation message to get the event enc key
1075
+ const eventMsg = await getMessage(creationMsgKey)
1076
+ if (eventMsg) {
1077
+ try {
1078
+ const meLidNormalised = jidNormalizedUser(meLid)
1079
+ const eventCreatorJid = getKeyAuthor(creationMsgKey, meLidNormalised)
1080
+ const responderJid = getKeyAuthor(message.key, meLidNormalised)
1081
+ const eventEncKey = eventMsg.messageContextInfo?.messageSecret
1082
+
1083
+ if (!eventEncKey) {
1084
+ logger?.warn({ encEventResponse, creationMsgKey }, 'event response: missing messageSecret for decryption')
1085
+ } else {
1086
+ const responseMsg = decryptEventResponse(encEventResponse, {
1087
+ eventEncKey,
1088
+ eventCreatorJid,
1089
+ eventMsgId: creationMsgKey.id,
1090
+ responderJid
1091
+ })
1092
+
1093
+ const eventResponse = {
1094
+ eventResponseMessageKey: message.key,
1095
+ senderTimestampMs: responseMsg.timestampMs,
1096
+ response: responseMsg
1097
+ }
1098
+
1099
+ ev.emit('messages.update', [
1100
+ {
1101
+ key: creationMsgKey,
1102
+ update: {
1103
+ eventResponses: [eventResponse]
1104
+ }
1105
+ }
1106
+ ])
1107
+ }
1108
+ }
1109
+ catch (err) {
1110
+ logger?.warn({ err, creationMsgKey, encEventResponse }, 'failed to decrypt event response')
1111
+ }
1112
+ }
1113
+ else {
1114
+ logger?.warn({ encEventResponse, creationMsgKey }, 'event creation message not found, cannot decrypt update')
1115
+ }
1116
+ }
1117
+ else if (content?.encCommentMessage) {
1118
+ const encComment = content.encCommentMessage
1119
+ const creationMsgKey = encComment.targetMessageKey
1120
+
1121
+ // we need to fetch the message to get the comment enc key
1122
+ const commentMsg = await getMessage(creationMsgKey)
1123
+ if (commentMsg) {
1124
+ try {
1125
+ const meLidNormalised = jidNormalizedUser(meLid)
1126
+ const commentCreatorJid = creationMsgKey.participant ? creationMsgKey.participant : message.key?.participant ? message.key.participant : meLidNormalised
1127
+ const commentJid = message.key?.participant ? message.key.participant : creationMsgKey.participant ? creationMsgKey.participant : meLidNormalised
1128
+ const commentEncKey = commentMsg.messageContextInfo?.messageSecret
1129
+
1130
+ if (!commentEncKey) {
1131
+ logger?.warn({ encComment, creationMsgKey }, 'comment message: missing messageSecret for decryption')
1132
+ } else {
1133
+ const responseMsg = decryptComment(encComment, {
1134
+ commentEncKey,
1135
+ commentCreatorJid,
1136
+ commentMsgId: creationMsgKey.id,
1137
+ commentJid
1138
+ })
1139
+
1140
+ ev.emit('messages.upsert', {
1141
+ messages: [{
1142
+ key: message.key,
1143
+ message: responseMsg
1144
+ }],
1145
+ type: 'append'
1146
+ })
1147
+ }
1148
+ }
1149
+ catch (err) {
1150
+ logger?.warn({ err, creationMsgKey, encComment }, 'failed to decrypt comment message')
1151
+ }
1152
+ }
1153
+ else {
1154
+ logger?.warn({ encComment, creationMsgKey }, 'creation message not found, cannot decrypt')
1155
+ }
1156
+ }
1157
+ else if (content?.encReactionMessage) {
1158
+ const encReaction = content.encReactionMessage
1159
+ const creationMsgKey = encReaction.targetMessageKey
1160
+
1161
+ // we need to fetch the message to get the reaction enc key
1162
+ const reactMsg = await getMessage(creationMsgKey)
1163
+ if (reactMsg) {
1164
+ try {
1165
+ const meLidNormalised = jidNormalizedUser(meLid)
1166
+ const reactionCreatorJid = creationMsgKey.participant ? creationMsgKey.participant : message.key?.participant ? message.key.participant : meLidNormalised
1167
+ const reactionJid = message.key?.participant ? message.key.participant : creationMsgKey.participant ? creationMsgKey.participant : meLidNormalised
1168
+ const reactionEncKey = reactMsg.messageContextInfo?.messageSecret
1169
+
1170
+ if (!reactionEncKey) {
1171
+ logger?.warn({ encReaction, creationMsgKey }, 'reaction: missing messageSecret for decryption')
1172
+ } else {
1173
+ const responseMsg = decryptReaction(encReaction, {
1174
+ reactionEncKey,
1175
+ reactionCreatorJid,
1176
+ reactionMsgId: creationMsgKey.id,
1177
+ reactionJid
1178
+ })
1179
+
1180
+ const Reaction = {
1181
+ key: message.key,
1182
+ message: {
1183
+ reactionMessage: {
1184
+ key: creationMsgKey,
1185
+ text: responseMsg.text,
1186
+ senderTimestampMs: responseMsg.senderTimestampMs
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ ev.emit('messages.upsert', {
1192
+ messages: [Reaction],
1193
+ type: 'append'
1194
+ })
1195
+ }
1196
+ }
1197
+ catch (err) {
1198
+ logger?.warn({ err, creationMsgKey, encReaction }, 'failed to decrypt reaction')
1199
+ }
1200
+ }
1201
+ else {
1202
+ logger?.warn({ encReaction, creationMsgKey }, 'creation message not found, cannot decrypt')
1203
+ }
1204
+ }
1205
+ if (Object.keys(chat).length > 1) {
1206
+ ev.emit('chats.update', [chat])
1207
+ }
1208
+ }
1209
+
1210
+ module.exports = {
1211
+ cleanMessage,
1212
+ isRealMessage,
1213
+ shouldIncrementChatUnread,
1214
+ getChatId,
1215
+ decryptPollVote,
1216
+ decryptEventEdit,
1217
+ decryptEventResponse,
1218
+ decryptComment,
1219
+ decryptReaction,
1220
+ processMessage
1221
+ }
1222
+
1223
+ return module.exports;
1224
+ })();
1225
+ for (const key of Object.keys(__kageModule77)) {
1226
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule77[key]});
1227
+ }
1228
+
1229
+ // Kage: funciones avanzadas.
1230
+ const __kageModule182 = (() => {
1231
+ const module = { exports: {} }; const exports = module.exports;
1232
+ "use strict";
1233
+ Object.defineProperty(exports, "__esModule", { value: true });
1234
+ exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
1235
+ exports.decryptPollVote = decryptPollVote;
1236
+ exports.decryptEventResponse = decryptEventResponse;
1237
+ exports.decryptMessageEdit = decryptMessageEdit;
1238
+ const index_js_1 = require("../../WAProto/index.js");
1239
+ const index_js_2 = require("../Addon/index.js");
1240
+ const index_js_3 = require("../Types/index.js");
1241
+ const messages_js_1 = require("../Utils/messages.js");
1242
+ const index_js_4 = require("../WABinary/index.js");
1243
+ const crypto_js_1 = require("./crypto.js");
1244
+ const generics_js_1 = require("./generics.js");
1245
+ const history_js_1 = require("./history.js");
1246
+ const tc_token_utils_js_1 = require("./tc-token-utils.js");
1247
+ const REAL_MSG_STUB_TYPES = new Set([
1248
+ index_js_3.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
1249
+ index_js_3.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
1250
+ index_js_3.WAMessageStubType.CALL_MISSED_VIDEO,
1251
+ index_js_3.WAMessageStubType.CALL_MISSED_VOICE
1252
+ ]);
1253
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([index_js_3.WAMessageStubType.GROUP_PARTICIPANT_ADD]);
1254
+ async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger) {
1255
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
1256
+ const candidates = [];
1257
+ for (const chat of chats) {
1258
+ const ts = chat.tcTokenTimestamp ? (0, generics_js_1.toNumber)(chat.tcTokenTimestamp) : 0;
1259
+ if (chat.tcToken?.length && ts > 0) {
1260
+ const jid = (0, index_js_4.jidNormalizedUser)(chat.id);
1261
+ const storageJid = await (0, tc_token_utils_js_1.resolveTcTokenJid)(jid, getLIDForPN);
1262
+ candidates.push({
1263
+ storageJid,
1264
+ token: Buffer.from(chat.tcToken),
1265
+ ts,
1266
+ senderTs: chat.tcTokenSenderTimestamp ? (0, generics_js_1.toNumber)(chat.tcTokenSenderTimestamp) : undefined
1267
+ });
1268
+ }
1269
+ }
1270
+ if (!candidates.length) {
1271
+ return;
1272
+ }
1273
+ const jids = candidates.map(c => c.storageJid);
1274
+ const existing = await keyStore.get('tctoken', jids);
1275
+ const entries = {};
1276
+ for (const c of candidates) {
1277
+ const existingEntry = existing[c.storageJid];
1278
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
1279
+ if (existingTs > 0 && existingTs >= c.ts) {
1280
+ continue;
1281
+ }
1282
+ entries[c.storageJid] = {
1283
+ ...existingEntry,
1284
+ token: c.token,
1285
+ timestamp: String(c.ts),
1286
+ ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {})
1287
+ };
1288
+ }
1289
+ if (Object.keys(entries).length) {
1290
+ logger?.debug({ count: Object.keys(entries).length }, 'storing tctokens from history sync');
1291
+ try {
1292
+ // Include updated __index so cross-session pruning picks these JIDs up.
1293
+ const indexWrite = await (0, tc_token_utils_js_1.buildMergedTcTokenIndexWrite)(keyStore, Object.keys(entries));
1294
+ await keyStore.set({ tctoken: { ...entries, ...indexWrite } });
1295
+ }
1296
+ catch (err) {
1297
+ logger?.warn({ err }, 'failed to store tctokens from history sync');
1298
+ }
1299
+ }
1300
+ }
1301
+ /** Cleans a received message to further processing */
1302
+ const cleanMessage = (message, meId, meLid) => {
1303
+ // ensure remoteJid and participant doesn't have device or agent in it
1304
+ if ((0, index_js_4.isHostedPnUser)(message.key.remoteJid) || (0, index_js_4.isHostedLidUser)(message.key.remoteJid)) {
1305
+ message.key.remoteJid = (0, index_js_4.jidEncode)((0, index_js_4.jidDecode)(message.key?.remoteJid)?.user, (0, index_js_4.isHostedPnUser)(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
1306
+ }
1307
+ else {
1308
+ message.key.remoteJid = (0, index_js_4.jidNormalizedUser)(message.key.remoteJid);
1309
+ }
1310
+ if ((0, index_js_4.isHostedPnUser)(message.key.participant) || (0, index_js_4.isHostedLidUser)(message.key.participant)) {
1311
+ message.key.participant = (0, index_js_4.jidEncode)((0, index_js_4.jidDecode)(message.key.participant)?.user, (0, index_js_4.isHostedPnUser)(message.key.participant) ? 's.whatsapp.net' : 'lid');
1312
+ }
1313
+ else {
1314
+ message.key.participant = (0, index_js_4.jidNormalizedUser)(message.key.participant);
1315
+ }
1316
+ const content = (0, messages_js_1.normalizeMessageContent)(message.message);
1317
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
1318
+ if (content?.reactionMessage) {
1319
+ normaliseKey(content.reactionMessage.key);
1320
+ }
1321
+ if (content?.pollUpdateMessage) {
1322
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
1323
+ }
1324
+ function normaliseKey(msgKey) {
1325
+ // if the reaction is from another user
1326
+ // we've to correctly map the key to this user's perspective
1327
+ if (!message.key.fromMe) {
1328
+ // if the sender believed the message being reacted to is not from them
1329
+ // we've to correct the key to be from them, or some other participant
1330
+ msgKey.fromMe = !msgKey.fromMe
1331
+ ? (0, index_js_4.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId) ||
1332
+ (0, index_js_4.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meLid)
1333
+ : // if the message being reacted to, was from them
1334
+ // fromMe automatically becomes false
1335
+ false;
1336
+ // set the remoteJid to being the same as the chat the message came from
1337
+ // TODO: investigate inconsistencies
1338
+ msgKey.remoteJid = message.key.remoteJid;
1339
+ // set participant of the message
1340
+ msgKey.participant = msgKey.participant || message.key.participant;
1341
+ }
1342
+ }
1343
+ };
1344
+ exports.cleanMessage = cleanMessage;
1345
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
1346
+ const isRealMessage = (message) => {
1347
+ const normalizedContent = (0, messages_js_1.normalizeMessageContent)(message.message);
1348
+ const hasSomeContent = !!(0, messages_js_1.getContentType)(normalizedContent);
1349
+ return ((!!normalizedContent ||
1350
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
1351
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
1352
+ hasSomeContent &&
1353
+ !normalizedContent?.protocolMessage &&
1354
+ !normalizedContent?.reactionMessage &&
1355
+ !normalizedContent?.pollUpdateMessage);
1356
+ };
1357
+ exports.isRealMessage = isRealMessage;
1358
+ const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
1359
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
1360
+ /**
1361
+ * Get the ID of the chat from the given key.
1362
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
1363
+ */
1364
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
1365
+ if (!remoteJid) {
1366
+ throw new index_js_2.HttpError('Cannot derive chat id: message key is missing remoteJid', {
1367
+ data: { remoteJid, participant, fromMe }
1368
+ });
1369
+ }
1370
+ if ((0, index_js_4.isJidBroadcast)(remoteJid) && !(0, index_js_4.isJidStatusBroadcast)(remoteJid) && !fromMe) {
1371
+ if (!participant) {
1372
+ throw new index_js_2.HttpError('Cannot derive chat id: broadcast message key is missing participant', {
1373
+ data: { remoteJid, fromMe }
1374
+ });
1375
+ }
1376
+ return participant;
1377
+ }
1378
+ return remoteJid;
1379
+ };
1380
+ exports.getChatId = getChatId;
1381
+ /**
1382
+ * Decrypt a poll vote
1383
+ * @param vote encrypted vote
1384
+ * @param ctx additional info about the poll required for decryption
1385
+ * @returns list of SHA256 options
1386
+ */
1387
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
1388
+ const sign = Buffer.concat([
1389
+ toBinary(pollMsgId),
1390
+ toBinary(pollCreatorJid),
1391
+ toBinary(voterJid),
1392
+ toBinary('Poll Vote'),
1393
+ new Uint8Array([1])
1394
+ ]);
1395
+ const key0 = (0, crypto_js_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
1396
+ const decKey = (0, crypto_js_1.hmacSign)(sign, key0, 'sha256');
1397
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
1398
+ const decrypted = (0, crypto_js_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
1399
+ return index_js_1.proto.Message.PollVoteMessage.decode(decrypted);
1400
+ function toBinary(txt) {
1401
+ return Buffer.from(txt);
1402
+ }
1403
+ }
1404
+ /**
1405
+ * Decrypt an event response
1406
+ * @param response encrypted event response
1407
+ * @param ctx additional info about the event required for decryption
1408
+ * @returns event response message
1409
+ */
1410
+ function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
1411
+ const sign = Buffer.concat([
1412
+ toBinary(eventMsgId),
1413
+ toBinary(eventCreatorJid),
1414
+ toBinary(responderJid),
1415
+ toBinary('Event Response'),
1416
+ new Uint8Array([1])
1417
+ ]);
1418
+ const key0 = (0, crypto_js_1.hmacSign)(eventEncKey, new Uint8Array(32), 'sha256');
1419
+ const decKey = (0, crypto_js_1.hmacSign)(sign, key0, 'sha256');
1420
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
1421
+ const decrypted = (0, crypto_js_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
1422
+ return index_js_1.proto.Message.EventResponseMessage.decode(decrypted);
1423
+ function toBinary(txt) {
1424
+ return Buffer.from(txt);
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Decrypt a `secretEncryptedMessage` carrying a `MESSAGE_EDIT` payload.
1429
+ *
1430
+ * WhatsApp started wrapping message edits in an E2EE envelope (May 2026).
1431
+ * The new content is encrypted with a key derived from the original
1432
+ * message's `messageContextInfo.messageSecret` using HKDF-SHA256
1433
+ * + AES-256-GCM, same family as polls and event responses but with
1434
+ * different constants (validated against live WhatsApp Android traffic):
1435
+ *
1436
+ * info = msgId || origSenderJid || editorJid || "Message Edit"
1437
+ * aad = (empty) <-- differs from Poll Vote / Event Response
1438
+ * key = HKDF-SHA256(salt=zeros, ikm=messageSecret, info, L=32)
1439
+ *
1440
+ * The decrypted plaintext is a regular `proto.Message` whose
1441
+ * `protocolMessage.editedMessage` field holds the new content — same
1442
+ * shape as the legacy `protocolMessage.editedMessage` edit path, so
1443
+ * consumers can treat the result identically.
1444
+ *
1445
+ * @param edit encrypted edit payload (encPayload + encIv from SecretEncryptedMessage)
1446
+ * @param ctx info about the original message required for decryption
1447
+ * @returns decoded outer `Message` whose `protocolMessage.editedMessage`
1448
+ * carries the new content (extendedTextMessage / conversation / etc.)
1449
+ */
1450
+ function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, originalMsgId, editEncKey, editorJid }) {
1451
+ const sign = Buffer.concat([
1452
+ toBinary(originalMsgId),
1453
+ toBinary(originalSenderJid),
1454
+ toBinary(editorJid),
1455
+ toBinary('Message Edit'),
1456
+ new Uint8Array([1])
1457
+ ]);
1458
+ const key0 = (0, crypto_js_1.hmacSign)(editEncKey, new Uint8Array(32), 'sha256');
1459
+ const decKey = (0, crypto_js_1.hmacSign)(sign, key0, 'sha256');
1460
+ // AAD is intentionally empty for MESSAGE_EDIT — unlike Poll Vote and
1461
+ // Event Response, WA does not include `${msgId}\0${editor}` in the AAD here.
1462
+ const aad = Buffer.alloc(0);
1463
+ const decrypted = (0, crypto_js_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
1464
+ return index_js_1.proto.Message.decode(decrypted);
1465
+ function toBinary(txt) {
1466
+ return Buffer.from(txt);
1467
+ }
1468
+ }
1469
+ const buildEditUpdate = (args) => {
1470
+ const editedInner = decryptMessageEdit({ encPayload: args.encPayload, encIv: args.encIv }, {
1471
+ editEncKey: args.editEncKey,
1472
+ originalSenderJid: args.originalSenderJid,
1473
+ originalMsgId: args.originalMsgId,
1474
+ editorJid: args.editorJid
1475
+ });
1476
+ const editProtocol = editedInner.protocolMessage;
1477
+ const innerEdited = editProtocol?.editedMessage;
1478
+ if (!innerEdited) {
1479
+ args.logger?.warn({ targetKey: args.targetKey }, 'decrypted MESSAGE_EDIT plaintext had no protocolMessage.editedMessage — skipping update');
1480
+ return null;
1481
+ }
1482
+ return {
1483
+ key: { ...args.messageKey, id: args.targetKeyId },
1484
+ update: {
1485
+ message: {
1486
+ editedMessage: {
1487
+ message: innerEdited
1488
+ }
1489
+ },
1490
+ messageTimestamp: editProtocol?.timestampMs
1491
+ ? Math.floor((0, generics_js_1.toNumber)(editProtocol.timestampMs) / 1000)
1492
+ : args.fallbackTimestamp
1493
+ }
1494
+ };
1495
+ };
1496
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
1497
+ const meId = creds.me.id;
1498
+ const { accountSettings } = creds;
1499
+ const chat = { id: (0, index_js_4.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
1500
+ const isRealMsg = (0, exports.isRealMessage)(message);
1501
+ if (isRealMsg) {
1502
+ chat.messages = [{ message }];
1503
+ chat.conversationTimestamp = (0, generics_js_1.toNumber)(message.messageTimestamp);
1504
+ // only increment unread count if not CIPHERTEXT and from another person
1505
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
1506
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
1507
+ }
1508
+ }
1509
+ const content = (0, messages_js_1.normalizeMessageContent)(message.message);
1510
+ // unarchive chat if it's a real message, or someone reacted to our message
1511
+ // and we've the unarchive chats setting on
1512
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
1513
+ chat.archived = false;
1514
+ chat.readOnly = false;
1515
+ }
1516
+ const protocolMsg = content?.protocolMessage;
1517
+ if (protocolMsg) {
1518
+ // Mirror whatsmeow's `handleProtocolMessage` guard, but applied only to
1519
+ // the protocol message types that originate from our own device — an
1520
+ // attacker could otherwise spoof any of these to manipulate local state.
1521
+ //
1522
+ // Self-only types (drop if `!fromMe`):
1523
+ // - HISTORY_SYNC_NOTIFICATION (our phone driving history sync)
1524
+ // - APP_STATE_SYNC_KEY_SHARE (key share between our devices)
1525
+ // - LID_MIGRATION_MAPPING_SYNC (server-initiated via our phone)
1526
+ // - PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE (response from our phone to our PDO request)
1527
+ //
1528
+ // Cross-user types (must NOT be dropped — legitimately arrive from others):
1529
+ // - REVOKE
1530
+ // - MESSAGE_EDIT
1531
+ // - EPHEMERAL_SETTING
1532
+ // - GROUP_MEMBER_LABEL_CHANGE
1533
+ //
1534
+ // See https://github.com/tulir/whatsmeow/blob/8d3700152a/message.go#L842-L845
1535
+ // for the reference architecture — whatsmeow's `handleProtocolMessage`
1536
+ // only contains self-only types because edits are unwrapped from
1537
+ // `EditedMessage` BEFORE this dispatch and revokes aren't routed here.
1538
+ const SELF_ONLY_TYPES = new Set([
1539
+ index_js_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
1540
+ index_js_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
1541
+ index_js_1.proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
1542
+ index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
1543
+ ]);
1544
+ if (protocolMsg.type !== null &&
1545
+ protocolMsg.type !== undefined &&
1546
+ SELF_ONLY_TYPES.has(protocolMsg.type) &&
1547
+ !message.key.fromMe) {
1548
+ logger?.warn({ msgId: message.key.id, type: protocolMsg.type, from: message.key.participant || message.key.remoteJid }, 'dropping spoofed self-only protocolMessage from non-self origin');
1549
+ return;
1550
+ }
1551
+ switch (protocolMsg.type) {
1552
+ case index_js_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
1553
+ const histNotification = protocolMsg.historySyncNotification;
1554
+ const process = shouldProcessHistoryMsg;
1555
+ const isLatest = !creds.processedHistoryMessages?.length;
1556
+ logger?.info({
1557
+ histNotification,
1558
+ process,
1559
+ id: message.key.id,
1560
+ isLatest
1561
+ }, 'got history notification');
1562
+ if (process) {
1563
+ // TODO: investigate
1564
+ if (histNotification.syncType !== index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
1565
+ ev.emit('creds.update', {
1566
+ processedHistoryMessages: [
1567
+ ...(creds.processedHistoryMessages || []),
1568
+ { key: message.key, messageTimestamp: message.messageTimestamp }
1569
+ ]
1570
+ });
1571
+ }
1572
+ const data = await (0, history_js_1.downloadAndProcessHistorySyncNotification)(histNotification, options, logger);
1573
+ if (data.lidPnMappings?.length) {
1574
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
1575
+ await signalRepository.lidMapping
1576
+ .storeLIDPNMappings(data.lidPnMappings)
1577
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
1578
+ }
1579
+ await storeTcTokensFromHistorySync(data.chats, signalRepository, keyStore, logger);
1580
+ ev.emit('messaging-history.set', {
1581
+ ...data,
1582
+ isLatest: histNotification.syncType !== index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
1583
+ chunkOrder: histNotification.chunkOrder,
1584
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
1585
+ });
1586
+ }
1587
+ break;
1588
+ case index_js_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
1589
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
1590
+ if (keys?.length) {
1591
+ let newAppStateSyncKeyId = '';
1592
+ await keyStore.transaction(async () => {
1593
+ const newKeys = [];
1594
+ for (const { keyData, keyId } of keys) {
1595
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
1596
+ newKeys.push(strKeyId);
1597
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
1598
+ newAppStateSyncKeyId = strKeyId;
1599
+ }
1600
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
1601
+ }, meId);
1602
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
1603
+ }
1604
+ else {
1605
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
1606
+ }
1607
+ break;
1608
+ case index_js_1.proto.Message.ProtocolMessage.Type.REVOKE:
1609
+ ev.emit('messages.update', [
1610
+ {
1611
+ key: {
1612
+ ...message.key,
1613
+ id: protocolMsg.key.id
1614
+ },
1615
+ update: { message: null, messageStubType: index_js_3.WAMessageStubType.REVOKE, key: message.key }
1616
+ }
1617
+ ]);
1618
+ break;
1619
+ case index_js_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
1620
+ Object.assign(chat, {
1621
+ ephemeralSettingTimestamp: (0, generics_js_1.toNumber)(message.messageTimestamp),
1622
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
1623
+ });
1624
+ break;
1625
+ case index_js_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
1626
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
1627
+ if (response) {
1628
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
1629
+ const peerDataOperationResult = response.peerDataOperationResult || [];
1630
+ for (const result of peerDataOperationResult) {
1631
+ const retryResponse = result?.placeholderMessageResendResponse;
1632
+ //eslint-disable-next-line max-depth
1633
+ if (!retryResponse?.webMessageInfoBytes) {
1634
+ continue;
1635
+ }
1636
+ //eslint-disable-next-line max-depth
1637
+ try {
1638
+ const webMessageInfo = index_js_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
1639
+ const msgId = webMessageInfo.key?.id;
1640
+ // Retrieve cached original message data (preserves LID details,
1641
+ // timestamps, etc. that the phone may omit in its PDO response)
1642
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
1643
+ //eslint-disable-next-line max-depth
1644
+ if (msgId) {
1645
+ await placeholderResendCache?.del(msgId);
1646
+ }
1647
+ let finalMsg;
1648
+ //eslint-disable-next-line max-depth
1649
+ if (cachedData && typeof cachedData === 'object') {
1650
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
1651
+ cachedData.message = webMessageInfo.message;
1652
+ //eslint-disable-next-line max-depth
1653
+ if (webMessageInfo.messageTimestamp) {
1654
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
1655
+ }
1656
+ finalMsg = cachedData;
1657
+ }
1658
+ else {
1659
+ finalMsg = webMessageInfo;
1660
+ }
1661
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
1662
+ ev.emit('messages.upsert', {
1663
+ messages: [finalMsg],
1664
+ type: 'notify',
1665
+ requestId: response.stanzaId
1666
+ });
1667
+ }
1668
+ catch (err) {
1669
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
1670
+ }
1671
+ }
1672
+ }
1673
+ break;
1674
+ case index_js_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
1675
+ ev.emit('messages.update', [
1676
+ {
1677
+ // flip the sender / fromMe properties because they're in the perspective of the sender
1678
+ key: { ...message.key, id: protocolMsg.key?.id },
1679
+ update: {
1680
+ message: {
1681
+ editedMessage: {
1682
+ message: protocolMsg.editedMessage
1683
+ }
1684
+ },
1685
+ messageTimestamp: protocolMsg.timestampMs
1686
+ ? Math.floor((0, generics_js_1.toNumber)(protocolMsg.timestampMs) / 1000)
1687
+ : message.messageTimestamp
1688
+ }
1689
+ }
1690
+ ]);
1691
+ break;
1692
+ case index_js_1.proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
1693
+ const labelAssociationMsg = protocolMsg.memberLabel;
1694
+ if (labelAssociationMsg?.label) {
1695
+ ev.emit('group.member-tag.update', {
1696
+ groupId: chat.id,
1697
+ label: labelAssociationMsg.label,
1698
+ participant: message.key.participant,
1699
+ participantAlt: message.key.participantAlt,
1700
+ messageTimestamp: Number(message.messageTimestamp)
1701
+ });
1702
+ }
1703
+ break;
1704
+ case index_js_1.proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
1705
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
1706
+ const { pnToLidMappings, chatDbMigrationTimestamp } = index_js_1.proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
1707
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
1708
+ const pairs = [];
1709
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
1710
+ const lid = latestLid || assignedLid;
1711
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
1712
+ }
1713
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
1714
+ if (pairs.length) {
1715
+ for (const { pn, lid } of pairs) {
1716
+ await signalRepository.migrateSession(pn, lid);
1717
+ }
1718
+ }
1719
+ }
1720
+ }
1721
+ else if (content?.reactionMessage) {
1722
+ const reaction = {
1723
+ ...content.reactionMessage,
1724
+ key: message.key
1725
+ };
1726
+ ev.emit('messages.reaction', [
1727
+ {
1728
+ reaction,
1729
+ key: content.reactionMessage?.key
1730
+ }
1731
+ ]);
1732
+ }
1733
+ else if (content?.encEventResponseMessage) {
1734
+ const encEventResponse = content.encEventResponseMessage;
1735
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
1736
+ // we need to fetch the event creation message to get the event enc key
1737
+ const eventMsg = await getMessage(creationMsgKey);
1738
+ if (eventMsg) {
1739
+ try {
1740
+ const meIdNormalised = (0, index_js_4.jidNormalizedUser)(meId);
1741
+ // all jids need to be PN
1742
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid;
1743
+ const eventCreatorPn = (0, index_js_4.isLidUser)(eventCreatorKey)
1744
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
1745
+ : eventCreatorKey;
1746
+ const eventCreatorJid = (0, generics_js_1.getKeyAuthor)({ remoteJid: (0, index_js_4.jidNormalizedUser)(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised);
1747
+ const responderJid = (0, generics_js_1.getKeyAuthor)(message.key, meIdNormalised);
1748
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
1749
+ if (!eventEncKey) {
1750
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
1751
+ }
1752
+ else {
1753
+ const responseMsg = decryptEventResponse(encEventResponse, {
1754
+ eventEncKey,
1755
+ eventCreatorJid,
1756
+ eventMsgId: creationMsgKey.id,
1757
+ responderJid
1758
+ });
1759
+ const eventResponse = {
1760
+ eventResponseMessageKey: message.key,
1761
+ senderTimestampMs: responseMsg.timestampMs,
1762
+ response: responseMsg
1763
+ };
1764
+ ev.emit('messages.update', [
1765
+ {
1766
+ key: creationMsgKey,
1767
+ update: {
1768
+ eventResponses: [eventResponse]
1769
+ }
1770
+ }
1771
+ ]);
1772
+ }
1773
+ }
1774
+ catch (err) {
1775
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
1776
+ }
1777
+ }
1778
+ else {
1779
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
1780
+ }
1781
+ }
1782
+ else if (content?.secretEncryptedMessage &&
1783
+ content.secretEncryptedMessage.secretEncType === index_js_1.proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT) {
1784
+ // E2EE message edit envelope (new in 2026-05). Replaces the older
1785
+ // `protocolMessage.editedMessage` path for direct text edits.
1786
+ // We fetch the target message to obtain its `messageSecret`, derive the
1787
+ // decryption key, and surface the decoded inner Message via the same
1788
+ // `messages.update` event used by the legacy edit path so consumers do
1789
+ // not need a new event type.
1790
+ const secEnc = content.secretEncryptedMessage;
1791
+ const targetKey = secEnc.targetMessageKey;
1792
+ const targetMsg = await getMessage(targetKey);
1793
+ if (targetMsg) {
1794
+ try {
1795
+ const meIdNormalised = (0, index_js_4.jidNormalizedUser)(meId);
1796
+ const origSenderRaw = targetKey.participant || targetKey.remoteJid;
1797
+ const origSenderPn = (0, index_js_4.isLidUser)(origSenderRaw)
1798
+ ? await signalRepository.lidMapping.getPNForLID(origSenderRaw)
1799
+ : origSenderRaw;
1800
+ const originalSenderJid = (0, generics_js_1.getKeyAuthor)({ remoteJid: (0, index_js_4.jidNormalizedUser)(origSenderPn), fromMe: meIdNormalised === origSenderPn }, meIdNormalised);
1801
+ const editorJid = (0, generics_js_1.getKeyAuthor)(message.key, meIdNormalised);
1802
+ const editEncKey = targetMsg?.messageContextInfo?.messageSecret;
1803
+ if (!editEncKey) {
1804
+ logger?.warn({ targetKey }, 'message edit: missing messageSecret on original message — cannot decrypt');
1805
+ return;
1806
+ }
1807
+ const update = buildEditUpdate({
1808
+ editEncKey,
1809
+ encPayload: secEnc.encPayload,
1810
+ encIv: secEnc.encIv,
1811
+ originalSenderJid,
1812
+ originalMsgId: targetKey.id,
1813
+ editorJid,
1814
+ messageKey: message.key,
1815
+ targetKeyId: targetKey.id,
1816
+ fallbackTimestamp: (0, generics_js_1.toNumber)(message.messageTimestamp),
1817
+ logger,
1818
+ targetKey
1819
+ });
1820
+ if (update) {
1821
+ ev.emit('messages.update', [update]);
1822
+ }
1823
+ }
1824
+ catch (err) {
1825
+ logger?.warn({ err, targetKey }, 'failed to decrypt secretEncryptedMessage MESSAGE_EDIT');
1826
+ }
1827
+ }
1828
+ else {
1829
+ logger?.warn({ targetKey }, 'original message not found in store, cannot decrypt secretEncryptedMessage edit');
1830
+ }
1831
+ }
1832
+ else if (message.messageStubType) {
1833
+ const jid = message.key?.remoteJid;
1834
+ //let actor = whatsappID (message.participant)
1835
+ let participants;
1836
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
1837
+ id: jid,
1838
+ author: message.key.participant,
1839
+ authorPn: message.key.participantAlt,
1840
+ authorUsername: message.key.participantUsername,
1841
+ participants,
1842
+ action
1843
+ });
1844
+ const emitGroupUpdate = (update) => {
1845
+ ev.emit('groups.update', [
1846
+ {
1847
+ id: jid,
1848
+ ...update,
1849
+ author: message.key.participant ?? undefined,
1850
+ authorPn: message.key.participantAlt,
1851
+ authorUsername: message.key.participantUsername
1852
+ }
1853
+ ]);
1854
+ };
1855
+ const emitGroupRequestJoin = (participant, action, method) => {
1856
+ ev.emit('group.join-request', {
1857
+ id: jid,
1858
+ author: message.key.participant,
1859
+ authorPn: message.key.participantAlt,
1860
+ authorUsername: message.key.participantUsername,
1861
+ participant: participant.lid,
1862
+ participantPn: participant.pn,
1863
+ action,
1864
+ method: method
1865
+ });
1866
+ };
1867
+ const participantsIncludesMe = () => participants.find(jid => (0, index_js_4.areJidsSameUser)(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
1868
+ switch (message.messageStubType) {
1869
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
1870
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
1871
+ emitParticipantsUpdate('modify');
1872
+ break;
1873
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
1874
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
1875
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
1876
+ emitParticipantsUpdate('remove');
1877
+ // mark the chat read only if you left the group
1878
+ if (participantsIncludesMe()) {
1879
+ chat.readOnly = true;
1880
+ }
1881
+ break;
1882
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_ADD:
1883
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
1884
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
1885
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
1886
+ if (participantsIncludesMe()) {
1887
+ chat.readOnly = false;
1888
+ }
1889
+ emitParticipantsUpdate('add');
1890
+ break;
1891
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
1892
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
1893
+ emitParticipantsUpdate('demote');
1894
+ break;
1895
+ case index_js_3.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
1896
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
1897
+ emitParticipantsUpdate('promote');
1898
+ break;
1899
+ case index_js_3.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
1900
+ const announceValue = message.messageStubParameters?.[0];
1901
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
1902
+ break;
1903
+ case index_js_3.WAMessageStubType.GROUP_CHANGE_RESTRICT:
1904
+ const restrictValue = message.messageStubParameters?.[0];
1905
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
1906
+ break;
1907
+ case index_js_3.WAMessageStubType.GROUP_CHANGE_SUBJECT:
1908
+ const name = message.messageStubParameters?.[0];
1909
+ chat.name = name;
1910
+ emitGroupUpdate({ subject: name });
1911
+ break;
1912
+ case index_js_3.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
1913
+ const description = message.messageStubParameters?.[0];
1914
+ chat.description = description;
1915
+ emitGroupUpdate({ desc: description });
1916
+ break;
1917
+ case index_js_3.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
1918
+ const code = message.messageStubParameters?.[0];
1919
+ emitGroupUpdate({ inviteCode: code });
1920
+ break;
1921
+ case index_js_3.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
1922
+ const memberAddValue = message.messageStubParameters?.[0];
1923
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
1924
+ break;
1925
+ case index_js_3.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
1926
+ const approvalMode = message.messageStubParameters?.[0];
1927
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
1928
+ break;
1929
+ case index_js_3.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
1930
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
1931
+ const action = message.messageStubParameters?.[1];
1932
+ const method = message.messageStubParameters?.[2];
1933
+ emitGroupRequestJoin(participant, action, method);
1934
+ break;
1935
+ }
1936
+ } /* else if(content?.pollUpdateMessage) {
1937
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey!
1938
+ // we need to fetch the poll creation message to get the poll enc key
1939
+ // TODO: make standalone, remove getMessage reference
1940
+ // TODO: Remove entirely
1941
+ const pollMsg = await getMessage(creationMsgKey)
1942
+ if(pollMsg) {
1943
+ const meIdNormalised = jidNormalizedUser(meId)
1944
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
1945
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
1946
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret!
1947
+
1948
+ try {
1949
+ const voteMsg = decryptPollVote(
1950
+ content.pollUpdateMessage.vote!,
1951
+ {
1952
+ pollEncKey,
1953
+ pollCreatorJid,
1954
+ pollMsgId: creationMsgKey.id!,
1955
+ voterJid,
1956
+ }
1957
+ )
1958
+ ev.emit('messages.update', [
1959
+ {
1960
+ key: creationMsgKey,
1961
+ update: {
1962
+ pollUpdates: [
1963
+ {
1964
+ pollUpdateMessageKey: message.key,
1965
+ vote: voteMsg,
1966
+ senderTimestampMs: (content.pollUpdateMessage.senderTimestampMs! as Long).toNumber(),
1967
+ }
1968
+ ]
1969
+ }
1970
+ }
1971
+ ])
1972
+ } catch(err) {
1973
+ logger?.warn(
1974
+ { err, creationMsgKey },
1975
+ 'failed to decrypt poll vote'
1976
+ )
1977
+ }
1978
+ } else {
1979
+ logger?.warn(
1980
+ { creationMsgKey },
1981
+ 'poll creation message not found, cannot decrypt update'
1982
+ )
1983
+ }
1984
+ } */
1985
+ if (Object.keys(chat).length > 1) {
1986
+ ev.emit('chats.update', [chat]);
1987
+ }
1988
+ };
1989
+ exports.default = processMessage;
1990
+
1991
+ return module.exports;
1992
+ })();
1993
+ for (const key of Object.keys(__kageModule182)) {
1994
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule182[key]});
1995
+ }
1996
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule182, configurable:true});