@zervonexx/baileys 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4113 -3
  3. package/WAProto/WAProtoCompile.js +323 -0
  4. package/WAProto/fetcher.js +68 -0
  5. package/WAProto/index.js +96 -0
  6. package/WAProto/parser.js +334 -0
  7. package/lib/Builders/AIRich.js +674 -0
  8. package/lib/Builders/auto.js +50 -0
  9. package/lib/Builders/base.js +145 -0
  10. package/lib/Builders/builders.js +589 -0
  11. package/lib/Builders/index.js +4 -0
  12. package/lib/Defaults/index.js +248 -0
  13. package/lib/Signal/index.js +2 -0
  14. package/lib/Signal/libsignal.js +527 -0
  15. package/lib/Signal/lid-mapping.js +283 -0
  16. package/lib/Socket/Client/index.js +2 -0
  17. package/lib/Socket/Client/types.js +10 -0
  18. package/lib/Socket/Client/websocket.js +84 -0
  19. package/lib/Socket/business.js +152 -0
  20. package/lib/Socket/chats.js +855 -0
  21. package/lib/Socket/communities.js +147 -0
  22. package/lib/Socket/groups.js +294 -0
  23. package/lib/Socket/index.js +15 -0
  24. package/lib/Socket/messages-recv.js +994 -0
  25. package/lib/Socket/messages-send.js +723 -0
  26. package/lib/Socket/mex.js +34 -0
  27. package/lib/Socket/newsletter.js +784 -0
  28. package/lib/Socket/registration.js +155 -0
  29. package/lib/Socket/socket.js +798 -0
  30. package/lib/Socket/spam-report.js +144 -0
  31. package/lib/Socket/username.js +82 -0
  32. package/lib/Socket/zervonex-handler.js +58 -0
  33. package/lib/Store/index.js +6 -0
  34. package/lib/Store/make-cache-manager-store.js +80 -0
  35. package/lib/Store/make-in-memory-store.js +426 -0
  36. package/lib/Store/make-ordered-dictionary.js +82 -0
  37. package/lib/Store/object-repository.js +31 -0
  38. package/lib/Store/reporting-info-store.js +38 -0
  39. package/lib/Types/Auth.js +2 -0
  40. package/lib/Types/Bussines.js +2 -0
  41. package/lib/Types/Call.js +2 -0
  42. package/lib/Types/Chat.js +8 -0
  43. package/lib/Types/Contact.js +2 -0
  44. package/lib/Types/Events.js +2 -0
  45. package/lib/Types/GroupMetadata.js +2 -0
  46. package/lib/Types/Label.js +25 -0
  47. package/lib/Types/LabelAssociation.js +7 -0
  48. package/lib/Types/Message.js +15 -0
  49. package/lib/Types/Newsletter.js +100 -0
  50. package/lib/Types/Product.js +2 -0
  51. package/lib/Types/Signal.js +2 -0
  52. package/lib/Types/Socket.js +14 -0
  53. package/lib/Types/State.js +26 -0
  54. package/lib/Types/USync.js +2 -0
  55. package/lib/Types/index.js +30 -0
  56. package/lib/Utils/auth-utils.js +159 -0
  57. package/lib/Utils/baileys-event-stream.js +33 -0
  58. package/lib/Utils/bot-capabilities.js +41 -0
  59. package/lib/Utils/bot-planning-replay.js +44 -0
  60. package/lib/Utils/browser-utils.js +30 -0
  61. package/lib/Utils/business.js +75 -0
  62. package/lib/Utils/chat-utils.js +317 -0
  63. package/lib/Utils/companion-reg-client-utils.js +20 -0
  64. package/lib/Utils/consumer-application.js +38 -0
  65. package/lib/Utils/crypto.js +53 -0
  66. package/lib/Utils/cstoken.js +15 -0
  67. package/lib/Utils/decode-wa-message.js +200 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +40 -0
  74. package/lib/Utils/link-preview.js +51 -0
  75. package/lib/Utils/logger.js +3 -0
  76. package/lib/Utils/lt-hash.js +3 -0
  77. package/lib/Utils/make-mutex.js +16 -0
  78. package/lib/Utils/message-composer.js +62 -0
  79. package/lib/Utils/message-retry-manager.js +48 -0
  80. package/lib/Utils/messages-media.js +502 -0
  81. package/lib/Utils/messages.js +943 -0
  82. package/lib/Utils/meta-ai-msmsg.js +122 -0
  83. package/lib/Utils/meta-compositing.js +75 -0
  84. package/lib/Utils/modern-messages.js +235 -0
  85. package/lib/Utils/native-flow.js +81 -0
  86. package/lib/Utils/noise-handler.js +161 -0
  87. package/lib/Utils/pre-key-manager.js +76 -0
  88. package/lib/Utils/process-message.js +401 -0
  89. package/lib/Utils/reporting-utils.js +171 -0
  90. package/lib/Utils/signal.js +167 -0
  91. package/lib/Utils/spam-report-utils.js +166 -0
  92. package/lib/Utils/sync-action-utils.js +33 -0
  93. package/lib/Utils/tc-token-utils.js +154 -0
  94. package/lib/Utils/use-keyv-auth-state.js +200 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +84 -0
  96. package/lib/Utils/validate-connection.js +172 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +203 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +88 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +67 -0
  125. package/package.json +191 -5
@@ -0,0 +1,161 @@
1
+ import { Boom } from '@hapi/boom'
2
+ import { proto } from '../../WAProto/index.js'
3
+ import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults/index.js'
4
+ import { decodeBinaryNode } from '../WABinary/index.js'
5
+ import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto.js'
6
+
7
+ const IV_LENGTH = 12
8
+ const EMPTY_BUFFER = Buffer.alloc(0)
9
+
10
+ class TransportState {
11
+ constructor(encKey, decKey) {
12
+ this.encKey = encKey
13
+ this.decKey = decKey
14
+ this.readCounter = 0
15
+ this.writeCounter = 0
16
+ this.iv = new Uint8Array(IV_LENGTH)
17
+ }
18
+
19
+ #writeIV(c) {
20
+ this.iv[8] = (c >>> 24) & 0xff
21
+ this.iv[9] = (c >>> 16) & 0xff
22
+ this.iv[10] = (c >>> 8) & 0xff
23
+ this.iv[11] = c & 0xff
24
+ }
25
+
26
+ encrypt(plaintext) { this.#writeIV(this.writeCounter++); return aesEncryptGCM(plaintext, this.encKey, this.iv, EMPTY_BUFFER) }
27
+ decrypt(ciphertext) { this.#writeIV(this.readCounter++); return aesDecryptGCM(ciphertext, this.decKey, this.iv, EMPTY_BUFFER) }
28
+ }
29
+
30
+ const buildIntroHeader = (NOISE_HEADER, routingInfo) => {
31
+ if (!routingInfo) return Buffer.from(NOISE_HEADER)
32
+ const buf = Buffer.alloc(7 + routingInfo.byteLength + NOISE_HEADER.length)
33
+ buf.write('ED', 0, 'utf8')
34
+ buf.writeUint8(0, 2)
35
+ buf.writeUint8(1, 3)
36
+ buf.writeUint8(routingInfo.byteLength >> 16, 4)
37
+ buf.writeUint16BE(routingInfo.byteLength & 65535, 5)
38
+ buf.set(routingInfo, 7)
39
+ buf.set(NOISE_HEADER, 7 + routingInfo.byteLength)
40
+ return buf
41
+ }
42
+
43
+ export const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
44
+ logger = logger.child({ class: 'ns' })
45
+
46
+ const data = Buffer.from(NOISE_MODE)
47
+ let hash = data.byteLength === 32 ? data : sha256(data)
48
+ let salt = hash
49
+ let encKey = hash
50
+ let decKey = hash
51
+ let counter = 0
52
+ let sentIntro = false
53
+
54
+ let inBytes = Buffer.alloc(0)
55
+ let transport = null
56
+ let isWaitingForTransport = false
57
+ let pendingOnFrame = null
58
+
59
+ const introHeader = buildIntroHeader(NOISE_HEADER, routingInfo)
60
+
61
+ const generateIV = c => {
62
+ const iv = new ArrayBuffer(IV_LENGTH)
63
+ new DataView(iv).setUint32(8, c)
64
+ return new Uint8Array(iv)
65
+ }
66
+
67
+ const authenticate = d => { if (!transport) hash = sha256(Buffer.concat([hash, d])) }
68
+
69
+ const localHKDF = d => {
70
+ const key = hkdf(Buffer.from(d), 64, { salt, info: '' })
71
+ return [key.subarray(0, 32), key.subarray(32)]
72
+ }
73
+
74
+ const mixIntoKey = d => {
75
+ const [write, read] = localHKDF(d)
76
+ salt = write; encKey = read; decKey = read; counter = 0
77
+ }
78
+
79
+ const encrypt = plaintext => {
80
+ if (transport) return transport.encrypt(plaintext)
81
+ const result = aesEncryptGCM(plaintext, encKey, generateIV(counter++), hash)
82
+ authenticate(result)
83
+ return result
84
+ }
85
+
86
+ const decrypt = ciphertext => {
87
+ if (transport) return transport.decrypt(ciphertext)
88
+ const result = aesDecryptGCM(ciphertext, decKey, generateIV(counter++), hash)
89
+ authenticate(ciphertext)
90
+ return result
91
+ }
92
+
93
+ const processData = async onFrame => {
94
+ while (inBytes.length >= 3) {
95
+ const size = (inBytes[0] << 16) | (inBytes[1] << 8) | inBytes[2]
96
+ if (inBytes.length < size + 3) return
97
+ let frame = inBytes.subarray(3, size + 3)
98
+ inBytes = inBytes.subarray(size + 3)
99
+ if (transport) frame = await decodeBinaryNode(transport.decrypt(frame))
100
+ onFrame(frame)
101
+ }
102
+ }
103
+
104
+ const finishInit = async () => {
105
+ isWaitingForTransport = true
106
+ const [write, read] = localHKDF(new Uint8Array(0))
107
+ transport = new TransportState(write, read)
108
+ isWaitingForTransport = false
109
+ if (pendingOnFrame) { await processData(pendingOnFrame); pendingOnFrame = null }
110
+ }
111
+
112
+ authenticate(NOISE_HEADER)
113
+ authenticate(publicKey)
114
+
115
+ return {
116
+ encrypt,
117
+ decrypt,
118
+ authenticate,
119
+ mixIntoKey,
120
+ finishInit,
121
+ processHandshake: ({ serverHello }, noiseKey) => {
122
+ authenticate(serverHello.ephemeral)
123
+ mixIntoKey(Curve.sharedKey(privateKey, serverHello.ephemeral))
124
+
125
+ const decStaticContent = decrypt(serverHello.static)
126
+ mixIntoKey(Curve.sharedKey(privateKey, decStaticContent))
127
+
128
+ const { intermediate: certIntermediate, leaf } = proto.CertChain.decode(decrypt(serverHello.payload))
129
+
130
+ if (!leaf?.details || !leaf?.signature) throw new Boom('invalid noise leaf certificate', { statusCode: 400 })
131
+ if (!certIntermediate?.details || !certIntermediate?.signature) throw new Boom('invalid noise intermediate certificate', { statusCode: 400 })
132
+
133
+ const details = proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details)
134
+
135
+ if (!Curve.verify(details.key, leaf.details, leaf.signature)) throw new Boom('noise certificate signature invalid', { statusCode: 400 })
136
+ if (!Curve.verify(WA_CERT_DETAILS.PUBLIC_KEY, certIntermediate.details, certIntermediate.signature)) throw new Boom('noise intermediate certificate signature invalid', { statusCode: 400 })
137
+ if (details.issuerSerial !== WA_CERT_DETAILS.SERIAL) throw new Boom('certification match failed', { statusCode: 400 })
138
+
139
+ const keyEnc = encrypt(noiseKey.public)
140
+ mixIntoKey(Curve.sharedKey(noiseKey.private, serverHello.ephemeral))
141
+ return keyEnc
142
+ },
143
+ encodeFrame: data => {
144
+ if (transport) data = transport.encrypt(data)
145
+ const dataLen = data.byteLength
146
+ const introSize = sentIntro ? 0 : introHeader.length
147
+ const frame = Buffer.allocUnsafe(introSize + 3 + dataLen)
148
+ if (!sentIntro) { frame.set(introHeader); sentIntro = true }
149
+ frame[introSize] = (dataLen >>> 16) & 0xff
150
+ frame[introSize + 1] = (dataLen >>> 8) & 0xff
151
+ frame[introSize + 2] = dataLen & 0xff
152
+ frame.set(data, introSize + 3)
153
+ return frame
154
+ },
155
+ decodeFrame: async (newData, onFrame) => {
156
+ if (isWaitingForTransport) { inBytes = Buffer.concat([inBytes, newData]); pendingOnFrame = onFrame; return }
157
+ inBytes = inBytes.length === 0 ? Buffer.from(newData) : Buffer.concat([inBytes, newData])
158
+ await processData(onFrame)
159
+ },
160
+ }
161
+ }
@@ -0,0 +1,76 @@
1
+ import PQueue from 'p-queue'
2
+
3
+ export class PreKeyManager {
4
+ constructor(store, logger) {
5
+ this.store = store
6
+ this.logger = logger
7
+ this.queues = new Map()
8
+ }
9
+
10
+ getQueue(keyType) {
11
+ if (!this.queues.has(keyType)) this.queues.set(keyType, new PQueue({ concurrency: 1 }))
12
+ return this.queues.get(keyType)
13
+ }
14
+
15
+ async processOperations(data, keyType, transactionCache, mutations, isInTransaction) {
16
+ const keyData = data[keyType]
17
+ if (!keyData) return
18
+ return this.getQueue(keyType).add(async () => {
19
+ transactionCache[keyType] ||= {}
20
+ mutations[keyType] ||= {}
21
+
22
+ const deletions = []
23
+ const updates = {}
24
+ for (const keyId in keyData) {
25
+ if (keyData[keyId] === null) deletions.push(keyId)
26
+ else updates[keyId] = keyData[keyId]
27
+ }
28
+
29
+ if (Object.keys(updates).length > 0) {
30
+ Object.assign(transactionCache[keyType], updates)
31
+ Object.assign(mutations[keyType], updates)
32
+ }
33
+
34
+ if (deletions.length > 0) await this.processDeletions(keyType, deletions, transactionCache, mutations, isInTransaction)
35
+ })
36
+ }
37
+
38
+ async processDeletions(keyType, ids, transactionCache, mutations, isInTransaction) {
39
+ if (isInTransaction) {
40
+ for (const keyId of ids) {
41
+ if (transactionCache[keyType]?.[keyId]) {
42
+ transactionCache[keyType][keyId] = null
43
+ mutations[keyType][keyId] = null
44
+ } else {
45
+ this.logger.warn(`Skipping deletion of non-existent ${keyType} in transaction: ${keyId}`)
46
+ }
47
+ }
48
+ } else {
49
+ const existingKeys = await this.store.get(keyType, ids)
50
+ for (const keyId of ids) {
51
+ if (existingKeys[keyId]) {
52
+ transactionCache[keyType][keyId] = null
53
+ mutations[keyType][keyId] = null
54
+ } else {
55
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ async validateDeletions(data, keyType) {
62
+ const keyData = data[keyType]
63
+ if (!keyData) return
64
+ return this.getQueue(keyType).add(async () => {
65
+ const deletionIds = Object.keys(keyData).filter(id => keyData[id] === null)
66
+ if (deletionIds.length === 0) return
67
+ const existingKeys = await this.store.get(keyType, deletionIds)
68
+ for (const keyId of deletionIds) {
69
+ if (!existingKeys[keyId]) {
70
+ this.logger.warn(`Skipping deletion of non-existent ${keyType}: ${keyId}`)
71
+ delete data[keyType][keyId]
72
+ }
73
+ }
74
+ })
75
+ }
76
+ }
@@ -0,0 +1,401 @@
1
+ import { proto } from '../../WAProto/index.js'
2
+ import { Boom } from '@hapi/boom'
3
+ import { WAMessageStubType } from '../Types/index.js'
4
+ import { getContentType, normalizeMessageContent } from './messages.js'
5
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js'
6
+ import { aesDecryptGCM, hmacSign } from './crypto.js'
7
+ import { getKeyAuthor, toNumber } from './generics.js'
8
+ import { downloadAndProcessHistorySyncNotification } from './history.js'
9
+ import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './tc-token-utils.js'
10
+
11
+ const REAL_MSG_STUB_TYPES = new Set([
12
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
13
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
14
+ WAMessageStubType.CALL_MISSED_VIDEO,
15
+ WAMessageStubType.CALL_MISSED_VOICE,
16
+ ])
17
+
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
19
+
20
+ // Self-only protocol types: drop if not fromMe to prevent local-state spoofing.
21
+ // Cross-user types (REVOKE, MESSAGE_EDIT, EPHEMERAL_SETTING, GROUP_MEMBER_LABEL_CHANGE) must NOT be listed here.
22
+ const SELF_ONLY_PROTOCOL_TYPES = new Set([
23
+ proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
24
+ proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
25
+ proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
26
+ proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE,
27
+ ])
28
+
29
+ async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger) {
30
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
31
+ const candidates = []
32
+ for (const chat of chats) {
33
+ const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0
34
+ if (!chat.tcToken?.length || ts <= 0) continue
35
+ const jid = jidNormalizedUser(chat.id)
36
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
37
+ candidates.push({ storageJid, token: Buffer.from(chat.tcToken), ts, senderTs: chat.tcTokenSenderTimestamp ? toNumber(chat.tcTokenSenderTimestamp) : undefined })
38
+ }
39
+ if (!candidates.length) return
40
+
41
+ const existing = await keyStore.get('tctoken', candidates.map(c => c.storageJid))
42
+ const entries = {}
43
+ for (const c of candidates) {
44
+ const existingTs = existing[c.storageJid]?.timestamp ? Number(existing[c.storageJid].timestamp) : 0
45
+ if (existingTs > 0 && existingTs >= c.ts) continue
46
+ entries[c.storageJid] = { ...existing[c.storageJid], token: c.token, timestamp: String(c.ts), ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {}) }
47
+ }
48
+ if (!Object.keys(entries).length) return
49
+
50
+ try {
51
+ const indexWrite = await buildMergedTcTokenIndexWrite(keyStore, Object.keys(entries)) // keeps __index in sync for cross-session pruning
52
+ await keyStore.set({ tctoken: { ...entries, ...indexWrite } })
53
+ } catch (err) {
54
+ logger?.warn({ err }, 'failed to store tctokens from history sync')
55
+ }
56
+ }
57
+
58
+ export const cleanMessage = (message, meId, meLid) => {
59
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
60
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid')
61
+ } else {
62
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid)
63
+ }
64
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
65
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid')
66
+ } else {
67
+ message.key.participant = jidNormalizedUser(message.key.participant)
68
+ }
69
+
70
+ const content = normalizeMessageContent(message.message)
71
+ if (content?.reactionMessage) normaliseKey(content.reactionMessage.key)
72
+ if (content?.pollUpdateMessage) normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
73
+
74
+ function normaliseKey(msgKey) {
75
+ if (message.key.fromMe) return
76
+ msgKey.fromMe = !msgKey.fromMe
77
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) || areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
78
+ : false
79
+ msgKey.remoteJid = message.key.remoteJid // TODO: investigate inconsistencies
80
+ msgKey.participant = msgKey.participant || message.key.participant
81
+ }
82
+ }
83
+
84
+ export const isRealMessage = message => {
85
+ const normalizedContent = normalizeMessageContent(message.message)
86
+ return (
87
+ (!!normalizedContent || REAL_MSG_STUB_TYPES.has(message.messageStubType) || REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
88
+ !!getContentType(normalizedContent) &&
89
+ !normalizedContent?.protocolMessage &&
90
+ !normalizedContent?.reactionMessage &&
91
+ !normalizedContent?.pollUpdateMessage
92
+ )
93
+ }
94
+
95
+ export const shouldIncrementChatUnread = message => !message.key.fromMe && !message.messageStubType
96
+
97
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
98
+ if (!remoteJid) throw new Boom('Cannot derive chat id: message key is missing remoteJid', { data: { remoteJid, participant, fromMe } })
99
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
100
+ if (!participant) throw new Boom('Cannot derive chat id: broadcast message key is missing participant', { data: { remoteJid, fromMe } })
101
+ return participant
102
+ }
103
+ return remoteJid
104
+ }
105
+
106
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
107
+ const toBinary = txt => Buffer.from(txt)
108
+ const sign = Buffer.concat([toBinary(pollMsgId), toBinary(pollCreatorJid), toBinary(voterJid), toBinary('Poll Vote'), new Uint8Array([1])])
109
+ const decKey = hmacSign(sign, hmacSign(pollEncKey, new Uint8Array(32), 'sha256'), 'sha256')
110
+ return proto.Message.PollVoteMessage.decode(aesDecryptGCM(encPayload, decKey, encIv, toBinary(`${pollMsgId}\u0000${voterJid}`)))
111
+ }
112
+
113
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
114
+ const toBinary = txt => Buffer.from(txt)
115
+ const sign = Buffer.concat([toBinary(eventMsgId), toBinary(eventCreatorJid), toBinary(responderJid), toBinary('Event Response'), new Uint8Array([1])])
116
+ const decKey = hmacSign(sign, hmacSign(eventEncKey, new Uint8Array(32), 'sha256'), 'sha256')
117
+ return proto.Message.EventResponseMessage.decode(aesDecryptGCM(encPayload, decKey, encIv, toBinary(`${eventMsgId}\u0000${responderJid}`)))
118
+ }
119
+
120
+ export const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
121
+ const meId = creds.me.id
122
+ const { accountSettings } = creds
123
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) }
124
+ const isRealMsg = isRealMessage(message)
125
+
126
+ if (isRealMsg) {
127
+ chat.messages = [{ message }]
128
+ chat.conversationTimestamp = toNumber(message.messageTimestamp)
129
+ if (shouldIncrementChatUnread(message)) chat.unreadCount = (chat.unreadCount || 0) + 1
130
+ }
131
+
132
+ const content = normalizeMessageContent(message.message)
133
+
134
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
135
+ chat.archived = false
136
+ chat.readOnly = false
137
+ }
138
+
139
+ const protocolMsg = content?.protocolMessage
140
+ if (protocolMsg) {
141
+ if (protocolMsg.type !== null && protocolMsg.type !== undefined && SELF_ONLY_PROTOCOL_TYPES.has(protocolMsg.type) && !message.key.fromMe) {
142
+ 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')
143
+ return
144
+ }
145
+
146
+ switch (protocolMsg.type) {
147
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION: {
148
+ const histNotification = protocolMsg.historySyncNotification
149
+ const isLatest = !creds.processedHistoryMessages?.length
150
+ if (shouldProcessHistoryMsg) {
151
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
152
+ ev.emit('creds.update', { processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }] })
153
+ }
154
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
155
+ if (data.nctSalt?.length && Buffer.compare(Buffer.from(creds.nctSalt ?? []), Buffer.from(data.nctSalt)) !== 0)
156
+ ev.emit('creds.update', { nctSalt: data.nctSalt })
157
+ if (data.lidPnMappings?.length) {
158
+ await signalRepository.lidMapping.storeLIDPNMappings(data.lidPnMappings).catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'))
159
+ }
160
+ await storeTcTokensFromHistorySync(data.chats, signalRepository, keyStore, logger)
161
+ ev.emit('messaging-history.set', { ...data, isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined, chunkOrder: histNotification.chunkOrder, peerDataRequestSessionId: histNotification.peerDataRequestSessionId })
162
+ }
163
+ break
164
+ }
165
+
166
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE: {
167
+ const keys = protocolMsg.appStateSyncKeyShare.keys
168
+ if (keys?.length) {
169
+ let newAppStateSyncKeyId = ''
170
+ await keyStore.transaction(async () => {
171
+ const newKeys = []
172
+ for (const { keyData, keyId } of keys) {
173
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64')
174
+ newKeys.push(strKeyId)
175
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
176
+ newAppStateSyncKeyId = strKeyId
177
+ }
178
+ }, meId)
179
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
180
+ }
181
+ break
182
+ }
183
+
184
+ case proto.Message.ProtocolMessage.Type.REVOKE: {
185
+ ev.emit('messages.update', [{ key: { ...message.key, id: protocolMsg.key.id }, update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key } }])
186
+ break
187
+ }
188
+
189
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING: {
190
+ Object.assign(chat, { ephemeralSettingTimestamp: toNumber(message.messageTimestamp), ephemeralExpiration: protocolMsg.ephemeralExpiration || null })
191
+ break
192
+ }
193
+
194
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT: {
195
+ ev.emit('messages.update', [{
196
+ key: { ...message.key, id: protocolMsg.key?.id }, // key is in sender's perspective; fromMe flip happens at read time
197
+ update: {
198
+ message: { editedMessage: { message: protocolMsg.editedMessage } },
199
+ messageTimestamp: protocolMsg.timestampMs ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000) : message.messageTimestamp,
200
+ },
201
+ }])
202
+ break
203
+ }
204
+
205
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE: {
206
+ const labelAssociationMsg = protocolMsg.memberLabel
207
+ if (labelAssociationMsg?.label) {
208
+ ev.emit('group.member-tag.update', { groupId: chat.id, label: labelAssociationMsg.label, participant: message.key.participant, participantAlt: message.key.participantAlt, messageTimestamp: Number(message.messageTimestamp) })
209
+ }
210
+ break
211
+ }
212
+
213
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE: {
214
+ const response = protocolMsg.peerDataOperationRequestResponseMessage
215
+ if (!response) break
216
+ for (const result of (response.peerDataOperationResult || [])) {
217
+ const retryResponse = result?.placeholderMessageResendResponse
218
+ if (!retryResponse?.webMessageInfoBytes) continue
219
+ try {
220
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
221
+ const msgId = webMessageInfo.key?.id
222
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined // preserves LID, timestamps etc. that phone may omit in PDO response
223
+ if (msgId) await placeholderResendCache?.del(msgId)
224
+ let finalMsg
225
+ if (cachedData && typeof cachedData === 'object') {
226
+ cachedData.message = webMessageInfo.message
227
+ if (webMessageInfo.messageTimestamp) cachedData.messageTimestamp = webMessageInfo.messageTimestamp
228
+ finalMsg = cachedData
229
+ } else {
230
+ finalMsg = webMessageInfo
231
+ }
232
+ ev.emit('messages.upsert', { messages: [finalMsg], type: 'notify', requestId: response.stanzaId })
233
+ } catch (err) {
234
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response')
235
+ }
236
+ }
237
+ break
238
+ }
239
+
240
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC: {
241
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload
242
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
243
+ const pairs = []
244
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
245
+ pairs.push({ lid: `${latestLid || assignedLid}@lid`, pn: `${pn}@s.whatsapp.net` }) // latestLid takes priority over assignedLid
246
+ }
247
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs)
248
+ for (const { pn, lid } of pairs) await signalRepository.migrateSession(pn, lid)
249
+ break
250
+ }
251
+
252
+ case proto.Message.ProtocolMessage.Type.STOP_GENERATION_MESSAGE: {
253
+ ev.emit('messages.update', [{ key: { remoteJid: message.key.remoteJid, id: protocolMsg.key?.id }, update: { generationStopped: true } }])
254
+ break
255
+ }
256
+
257
+ case proto.Message.ProtocolMessage.Type.CHAT_THEME_SETTING: {
258
+ ev.emit('chats.update', [{ id: message.key.remoteJid, theme: protocolMsg.chatThemeSetting }])
259
+ break
260
+ }
261
+
262
+ case proto.Message.ProtocolMessage.Type.MARK_AS_VERIFIED_ACTION: {
263
+ ev.emit('contacts.update', [{ id: message.key.remoteJid, verified: protocolMsg.markAsVerifiedAction?.verified }])
264
+ break
265
+ }
266
+
267
+ case proto.Message.ProtocolMessage.Type.MESSAGE_UNSCHEDULE: {
268
+ ev.emit('messages.update', [{ key: { remoteJid: message.key.remoteJid, id: protocolMsg.key?.id }, update: { messageStubType: WAMessageStubType.SCHEDULED_MESSAGE_CREATED, scheduled: false } }])
269
+ break
270
+ }
271
+ }
272
+ } else if (content?.reactionMessage) {
273
+ ev.emit('messages.reaction', [{ reaction: { ...content.reactionMessage, key: message.key }, key: content.reactionMessage?.key }])
274
+ } /*else if (content?.pollUpdateMessage) {
275
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey
276
+ const pollMsg = await getMessage(creationMsgKey)
277
+ if (pollMsg) {
278
+ try {
279
+ const meIdNormalised = jidNormalizedUser(meId)
280
+ const pollCreatorJid = getKeyAuthor(creationMsgKey, meIdNormalised)
281
+ const voterJid = getKeyAuthor(message.key, meIdNormalised)
282
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret
283
+ if (!pollEncKey) {
284
+ logger?.warn({ creationMsgKey }, 'poll vote: missing messageSecret for decryption')
285
+ } else {
286
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, { pollEncKey, pollCreatorJid, pollMsgId: creationMsgKey.id, voterJid })
287
+ ev.emit('messages.update', [{ key: creationMsgKey, update: { pollUpdates: [{ pollUpdateMessageKey: message.key, vote: voteMsg, senderTimestampMs: toNumber(content.pollUpdateMessage.senderTimestampMs) }] } }])
288
+ }
289
+ } catch (err) {
290
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt poll vote')
291
+ }
292
+ } else {
293
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update')
294
+ }
295
+ }*/ else if (content?.encEventResponseMessage) {
296
+ const encEventResponse = content.encEventResponseMessage
297
+ const creationMsgKey = encEventResponse.eventCreationMessageKey
298
+ const eventMsg = await getMessage(creationMsgKey)
299
+ if (eventMsg) {
300
+ try {
301
+ const meIdNormalised = jidNormalizedUser(meId)
302
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid
303
+ const eventCreatorPn = isLidUser(eventCreatorKey) ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey) : eventCreatorKey // event creator must be PN; resolve from LID if necessary
304
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised)
305
+ const responderJid = getKeyAuthor(message.key, meIdNormalised)
306
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret
307
+ if (!eventEncKey) {
308
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption')
309
+ } else {
310
+ const responseMsg = decryptEventResponse(encEventResponse, { eventEncKey, eventCreatorJid, eventMsgId: creationMsgKey.id, responderJid })
311
+ ev.emit('messages.update', [{ key: creationMsgKey, update: { eventResponses: [{ eventResponseMessageKey: message.key, senderTimestampMs: responseMsg.timestampMs, response: responseMsg }] } }])
312
+ }
313
+ } catch (err) {
314
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response')
315
+ }
316
+ } else {
317
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response')
318
+ }
319
+ } else if (message.messageStubType) {
320
+ const jid = message.key?.remoteJid
321
+ let participants
322
+ const emitParticipantsUpdate = action => ev.emit('group-participants.update', { id: jid, author: message.key.participant, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername, participants, action })
323
+ const emitGroupUpdate = update => ev.emit('groups.update', [{ id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername }])
324
+ const emitGroupRequestJoin = (participant, action, method) => ev.emit('group.join-request', { id: jid, author: message.key.participant, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername, participant: participant.lid, participantPn: participant.pn, action, method })
325
+
326
+ const participantsIncludesMe = () => participants.find(p => areJidsSameUser(meId, p.phoneNumber)) // TODO: ADD SUPPORT FOR LID
327
+
328
+ switch (message.messageStubType) {
329
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
330
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
331
+ emitParticipantsUpdate('modify')
332
+ break
333
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
334
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
335
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
336
+ emitParticipantsUpdate('remove')
337
+ if (participantsIncludesMe()) chat.readOnly = true
338
+ break
339
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
340
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
341
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
342
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
343
+ if (participantsIncludesMe()) chat.readOnly = false
344
+ emitParticipantsUpdate('add')
345
+ break
346
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
347
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
348
+ emitParticipantsUpdate('demote')
349
+ break
350
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
351
+ participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
352
+ emitParticipantsUpdate('promote')
353
+ break
354
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE: {
355
+ const announceValue = message.messageStubParameters?.[0]
356
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
357
+ break
358
+ }
359
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT: {
360
+ const restrictValue = message.messageStubParameters?.[0]
361
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
362
+ break
363
+ }
364
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT: {
365
+ const name = message.messageStubParameters?.[0]
366
+ chat.name = name
367
+ emitGroupUpdate({ subject: name })
368
+ break
369
+ }
370
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION: {
371
+ const description = message.messageStubParameters?.[0]
372
+ chat.description = description
373
+ emitGroupUpdate({ desc: description })
374
+ break
375
+ }
376
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK: {
377
+ emitGroupUpdate({ inviteCode: message.messageStubParameters?.[0] })
378
+ break
379
+ }
380
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE: {
381
+ const memberAddValue = message.messageStubParameters?.[0]
382
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
383
+ break
384
+ }
385
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE: {
386
+ const approvalMode = message.messageStubParameters?.[0]
387
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
388
+ break
389
+ }
390
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: {
391
+ const participant = JSON.parse(message.messageStubParameters?.[0])
392
+ emitGroupRequestJoin(participant, message.messageStubParameters?.[1], message.messageStubParameters?.[2])
393
+ break
394
+ }
395
+ }
396
+ }
397
+
398
+ if (Object.keys(chat).length > 1) ev.emit('chats.update', [chat])
399
+ }
400
+
401
+ export default processMessage