@zervonexx/baileys 5.0.0 → 5.0.1

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 +22 -22
  2. package/README.md +4112 -4112
  3. package/WAProto/WAProtoCompile.js +322 -322
  4. package/WAProto/fetcher.js +67 -67
  5. package/WAProto/index.js +95 -95
  6. package/WAProto/parser.js +333 -333
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +248 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +14 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +194 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +2 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +942 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +191 -192
@@ -1,401 +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
-
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
401
  export default processMessage