@hiroosy/baileys-lite 0.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.
- package/README.md +25 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +115856 -0
- package/engine-requirements.js +11 -0
- package/package.json +27 -0
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +649 -0
- package/src/constants.js +143 -0
- package/src/defaults.js +102 -0
- package/src/foundation/audio-duration.js +530 -0
- package/src/foundation/audio-samples.js +268 -0
- package/src/foundation/boom.js +46 -0
- package/src/foundation/cache.js +142 -0
- package/src/foundation/concurrency.js +87 -0
- package/src/foundation/curve25519.js +221 -0
- package/src/foundation/link-preview.js +320 -0
- package/src/foundation/logger.js +69 -0
- package/src/foundation/long.js +140 -0
- package/src/foundation/protobuf-minimal.js +619 -0
- package/src/foundation/wa-crypto.js +76 -0
- package/src/foundation/zip.js +124 -0
- package/src/index.js +48 -0
- package/src/signal/libsignal.js +1051 -0
- package/src/signal/signal-group.js +487 -0
- package/src/signal/signal-repository.js +646 -0
- package/src/socket/business-communities.js +830 -0
- package/src/socket/chats.js +674 -0
- package/src/socket/groups-newsletter.js +342 -0
- package/src/socket/messages-recv.js +1835 -0
- package/src/socket/messages-send.js +1202 -0
- package/src/socket/socket-core.js +833 -0
- package/src/socket/usync.js +291 -0
- package/src/socket-client/websocket-client.js +124 -0
- package/src/utils/auth-state-core.js +764 -0
- package/src/utils/auth-state-storage.js +316 -0
- package/src/utils/chat-sync.js +1045 -0
- package/src/utils/media.js +841 -0
- package/src/utils/message-compose.js +1609 -0
- package/src/utils/message-processing.js +958 -0
- package/src/utils/wa-protocol-core.js +1283 -0
- package/src/vendor/jpeg-js/LICENSE +25 -0
- package/src/vendor/jpeg-js/decoder.js +1152 -0
- package/src/vendor/jpeg-js/encoder.js +824 -0
- package/src/vendor/pngjs/LICENSE +20 -0
- package/src/vendor/pngjs/bitmapper.js +273 -0
- package/src/vendor/pngjs/bitpacker.js +167 -0
- package/src/vendor/pngjs/constants.js +38 -0
- package/src/vendor/pngjs/crc.js +47 -0
- package/src/vendor/pngjs/filter-pack.js +179 -0
- package/src/vendor/pngjs/filter-parse-sync.js +27 -0
- package/src/vendor/pngjs/filter-parse.js +185 -0
- package/src/vendor/pngjs/format-normaliser.js +101 -0
- package/src/vendor/pngjs/interlace.js +101 -0
- package/src/vendor/pngjs/packer-sync.js +65 -0
- package/src/vendor/pngjs/packer.js +138 -0
- package/src/vendor/pngjs/paeth-predictor.js +22 -0
- package/src/vendor/pngjs/parser-sync.js +121 -0
- package/src/vendor/pngjs/parser.js +299 -0
- package/src/vendor/pngjs/png-sync.js +19 -0
- package/src/vendor/pngjs/sync-inflate.js +174 -0
- package/src/vendor/pngjs/sync-reader.js +54 -0
- package/src/wam/wam-constants.js +22853 -0
- package/src/wam/wam.js +151 -0
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message processing pipeline. Combines what used to be process-message.js,
|
|
3
|
+
* message-retry-manager.js, offline-node-processor.js, history.js, and business.js.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { createWriteStream, promises as fs } from 'node:fs'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { pipeline } from 'node:stream/promises'
|
|
10
|
+
import { promisify } from 'node:util'
|
|
11
|
+
import { createInflate, inflate } from 'node:zlib'
|
|
12
|
+
import { proto } from '../../WAProto/index.js'
|
|
13
|
+
import { Boom } from '../foundation/boom.js'
|
|
14
|
+
import { Cache } from '../foundation/cache.js'
|
|
15
|
+
import { WAMessageStubType } from '../constants.js'
|
|
16
|
+
import {
|
|
17
|
+
areJidsSameUser,
|
|
18
|
+
getBinaryNodeChild,
|
|
19
|
+
getBinaryNodeChildren,
|
|
20
|
+
getBinaryNodeChildString,
|
|
21
|
+
isHostedLidUser,
|
|
22
|
+
isHostedPnUser,
|
|
23
|
+
isJidBroadcast,
|
|
24
|
+
isJidStatusBroadcast,
|
|
25
|
+
isLidUser,
|
|
26
|
+
isPnUser,
|
|
27
|
+
jidDecode,
|
|
28
|
+
jidEncode,
|
|
29
|
+
jidNormalizedUser
|
|
30
|
+
} from '../binary/wa-binary.js'
|
|
31
|
+
import { aesDecryptGCM, hmacSign, getKeyAuthor, toNumber, generateMessageIDV2 } from './wa-protocol-core.js'
|
|
32
|
+
import { getContentType, normalizeMessageContent } from './message-compose.js'
|
|
33
|
+
import { downloadContentFromMessage, getStream, getUrlFromDirectPath } from './media.js'
|
|
34
|
+
import { buildMergedTcTokenIndexWrite, resolveTcTokenJid } from './auth-state-core.js'
|
|
35
|
+
|
|
36
|
+
const inflatePromise = promisify(inflate)
|
|
37
|
+
|
|
38
|
+
/* ------------------------------------------------------------------ */
|
|
39
|
+
/* Incoming-message cleanup / classification */
|
|
40
|
+
/* ------------------------------------------------------------------ */
|
|
41
|
+
|
|
42
|
+
const REAL_MSG_STUB_TYPES = new Set([
|
|
43
|
+
WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
|
|
44
|
+
WAMessageStubType.CALL_MISSED_GROUP_VOICE,
|
|
45
|
+
WAMessageStubType.CALL_MISSED_VIDEO,
|
|
46
|
+
WAMessageStubType.CALL_MISSED_VOICE
|
|
47
|
+
])
|
|
48
|
+
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD])
|
|
49
|
+
|
|
50
|
+
async function storeTcTokensFromHistorySync(chats, signalRepository, keyStore, logger) {
|
|
51
|
+
const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping)
|
|
52
|
+
const candidates = []
|
|
53
|
+
for (const chat of chats) {
|
|
54
|
+
const ts = chat.tcTokenTimestamp ? toNumber(chat.tcTokenTimestamp) : 0
|
|
55
|
+
if (chat.tcToken?.length && ts > 0) {
|
|
56
|
+
const jid = jidNormalizedUser(chat.id)
|
|
57
|
+
const storageJid = await resolveTcTokenJid(jid, getLIDForPN)
|
|
58
|
+
candidates.push({ storageJid, token: Buffer.from(chat.tcToken), ts, senderTs: chat.tcTokenSenderTimestamp ? toNumber(chat.tcTokenSenderTimestamp) : undefined })
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!candidates.length) return
|
|
62
|
+
const jids = candidates.map(c => c.storageJid)
|
|
63
|
+
const existing = await keyStore.get('tctoken', jids)
|
|
64
|
+
const entries = {}
|
|
65
|
+
for (const c of candidates) {
|
|
66
|
+
const existingEntry = existing[c.storageJid]
|
|
67
|
+
const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0
|
|
68
|
+
if (existingTs > 0 && existingTs >= c.ts) continue
|
|
69
|
+
entries[c.storageJid] = { ...existingEntry, token: c.token, timestamp: String(c.ts), ...(c.senderTs !== undefined ? { senderTimestamp: c.senderTs } : {}) }
|
|
70
|
+
}
|
|
71
|
+
if (Object.keys(entries).length) {
|
|
72
|
+
logger?.debug({ count: Object.keys(entries).length }, 'storing tctokens from history sync')
|
|
73
|
+
try {
|
|
74
|
+
const indexWrite = await buildMergedTcTokenIndexWrite(keyStore, Object.keys(entries))
|
|
75
|
+
await keyStore.set({ tctoken: { ...entries, ...indexWrite } })
|
|
76
|
+
} catch (err) {
|
|
77
|
+
logger?.warn({ err }, 'failed to store tctokens from history sync')
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Cleans a received message to further processing */
|
|
83
|
+
export const cleanMessage = (message, meId, meLid) => {
|
|
84
|
+
if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
|
|
85
|
+
message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid')
|
|
86
|
+
} else {
|
|
87
|
+
message.key.remoteJid = jidNormalizedUser(message.key.remoteJid)
|
|
88
|
+
}
|
|
89
|
+
if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
|
|
90
|
+
message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid')
|
|
91
|
+
} else {
|
|
92
|
+
message.key.participant = jidNormalizedUser(message.key.participant)
|
|
93
|
+
}
|
|
94
|
+
const content = normalizeMessageContent(message.message)
|
|
95
|
+
if (content?.reactionMessage) normaliseKey(content.reactionMessage.key)
|
|
96
|
+
if (content?.pollUpdateMessage) normaliseKey(content.pollUpdateMessage.pollCreationMessageKey)
|
|
97
|
+
|
|
98
|
+
function normaliseKey(msgKey) {
|
|
99
|
+
if (!message.key.fromMe) {
|
|
100
|
+
msgKey.fromMe = !msgKey.fromMe
|
|
101
|
+
? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) || areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
|
|
102
|
+
: false
|
|
103
|
+
msgKey.remoteJid = message.key.remoteJid
|
|
104
|
+
msgKey.participant = msgKey.participant || message.key.participant
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const isRealMessage = message => {
|
|
110
|
+
const normalizedContent = normalizeMessageContent(message.message)
|
|
111
|
+
const hasSomeContent = !!getContentType(normalizedContent)
|
|
112
|
+
return (
|
|
113
|
+
(!!normalizedContent || REAL_MSG_STUB_TYPES.has(message.messageStubType) || REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
|
|
114
|
+
hasSomeContent &&
|
|
115
|
+
!normalizedContent?.protocolMessage &&
|
|
116
|
+
!normalizedContent?.reactionMessage &&
|
|
117
|
+
!normalizedContent?.pollUpdateMessage
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const shouldIncrementChatUnread = message => !message.key.fromMe && !message.messageStubType
|
|
122
|
+
|
|
123
|
+
/** Get the ID of the chat from the given key. Typically the remoteJid, but for broadcasts, the participant. */
|
|
124
|
+
export const getChatId = ({ remoteJid, participant, fromMe }) => {
|
|
125
|
+
if (!remoteJid) throw new Boom('Cannot derive chat id: message key is missing remoteJid', { data: { remoteJid, participant, fromMe } })
|
|
126
|
+
if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
|
|
127
|
+
if (!participant) throw new Boom('Cannot derive chat id: broadcast message key is missing participant', { data: { remoteJid, fromMe } })
|
|
128
|
+
return participant
|
|
129
|
+
}
|
|
130
|
+
return remoteJid
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/* ------------------------------------------------------------------ */
|
|
134
|
+
/* Encrypted-payload decryption (poll votes, event responses, edits) */
|
|
135
|
+
/* ------------------------------------------------------------------ */
|
|
136
|
+
|
|
137
|
+
export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
|
|
138
|
+
const toBinary = txt => Buffer.from(txt)
|
|
139
|
+
const sign = Buffer.concat([toBinary(pollMsgId), toBinary(pollCreatorJid), toBinary(voterJid), toBinary('Poll Vote'), new Uint8Array([1])])
|
|
140
|
+
const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256')
|
|
141
|
+
const decKey = hmacSign(sign, key0, 'sha256')
|
|
142
|
+
const aad = toBinary(`${pollMsgId}\u0000${voterJid}`)
|
|
143
|
+
const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
|
|
144
|
+
return proto.Message.PollVoteMessage.decode(decrypted)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
|
|
148
|
+
const toBinary = txt => Buffer.from(txt)
|
|
149
|
+
const sign = Buffer.concat([toBinary(eventMsgId), toBinary(eventCreatorJid), toBinary(responderJid), toBinary('Event Response'), new Uint8Array([1])])
|
|
150
|
+
const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256')
|
|
151
|
+
const decKey = hmacSign(sign, key0, 'sha256')
|
|
152
|
+
const aad = toBinary(`${eventMsgId}\u0000${responderJid}`)
|
|
153
|
+
const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
|
|
154
|
+
return proto.Message.EventResponseMessage.decode(decrypted)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Decrypt a `secretEncryptedMessage` carrying a `MESSAGE_EDIT` payload.
|
|
159
|
+
* info = msgId || origSenderJid || editorJid || "Message Edit"; aad = (empty);
|
|
160
|
+
* key = HKDF-SHA256(salt=zeros, ikm=messageSecret, info, L=32).
|
|
161
|
+
*/
|
|
162
|
+
export function decryptMessageEdit({ encPayload, encIv }, { originalSenderJid, originalMsgId, editEncKey, editorJid }) {
|
|
163
|
+
const toBinary = txt => Buffer.from(txt)
|
|
164
|
+
const sign = Buffer.concat([toBinary(originalMsgId), toBinary(originalSenderJid), toBinary(editorJid), toBinary('Message Edit'), new Uint8Array([1])])
|
|
165
|
+
const key0 = hmacSign(editEncKey, new Uint8Array(32), 'sha256')
|
|
166
|
+
const decKey = hmacSign(sign, key0, 'sha256')
|
|
167
|
+
const aad = Buffer.alloc(0) // intentionally empty, unlike Poll Vote / Event Response
|
|
168
|
+
const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad)
|
|
169
|
+
return proto.Message.decode(decrypted)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const buildEditUpdate = args => {
|
|
173
|
+
const editedInner = decryptMessageEdit(
|
|
174
|
+
{ encPayload: args.encPayload, encIv: args.encIv },
|
|
175
|
+
{ editEncKey: args.editEncKey, originalSenderJid: args.originalSenderJid, originalMsgId: args.originalMsgId, editorJid: args.editorJid }
|
|
176
|
+
)
|
|
177
|
+
const editProtocol = editedInner.protocolMessage
|
|
178
|
+
const innerEdited = editProtocol?.editedMessage
|
|
179
|
+
if (!innerEdited) {
|
|
180
|
+
args.logger?.warn({ targetKey: args.targetKey }, 'decrypted MESSAGE_EDIT plaintext had no protocolMessage.editedMessage — skipping update')
|
|
181
|
+
return null
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
key: { ...args.messageKey, id: args.targetKeyId },
|
|
185
|
+
update: {
|
|
186
|
+
message: { editedMessage: { message: innerEdited } },
|
|
187
|
+
messageTimestamp: editProtocol?.timestampMs ? Math.floor(toNumber(editProtocol.timestampMs) / 1000) : args.fallbackTimestamp
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/* ------------------------------------------------------------------ */
|
|
193
|
+
/* Main incoming-message processor */
|
|
194
|
+
/* ------------------------------------------------------------------ */
|
|
195
|
+
|
|
196
|
+
const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage }) => {
|
|
197
|
+
const meId = creds.me.id
|
|
198
|
+
const { accountSettings } = creds
|
|
199
|
+
const chat = { id: jidNormalizedUser(getChatId(message.key)) }
|
|
200
|
+
const isRealMsg = isRealMessage(message)
|
|
201
|
+
if (isRealMsg) {
|
|
202
|
+
chat.messages = [{ message }]
|
|
203
|
+
chat.conversationTimestamp = toNumber(message.messageTimestamp)
|
|
204
|
+
if (shouldIncrementChatUnread(message)) chat.unreadCount = (chat.unreadCount || 0) + 1
|
|
205
|
+
}
|
|
206
|
+
const content = normalizeMessageContent(message.message)
|
|
207
|
+
if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
|
|
208
|
+
chat.archived = false
|
|
209
|
+
chat.readOnly = false
|
|
210
|
+
}
|
|
211
|
+
const protocolMsg = content?.protocolMessage
|
|
212
|
+
if (protocolMsg) {
|
|
213
|
+
// Self-only protocol message types must be dropped if not fromMe (spoofing guard) — mirrors
|
|
214
|
+
// whatsmeow's handleProtocolMessage. Cross-user types (REVOKE, MESSAGE_EDIT, EPHEMERAL_SETTING,
|
|
215
|
+
// GROUP_MEMBER_LABEL_CHANGE) legitimately arrive from others and are NOT in this set.
|
|
216
|
+
const SELF_ONLY_TYPES = new Set([
|
|
217
|
+
proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
|
|
218
|
+
proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
|
|
219
|
+
proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
|
|
220
|
+
proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
|
|
221
|
+
])
|
|
222
|
+
if (protocolMsg.type !== null && protocolMsg.type !== undefined && SELF_ONLY_TYPES.has(protocolMsg.type) && !message.key.fromMe) {
|
|
223
|
+
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')
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
switch (protocolMsg.type) {
|
|
227
|
+
case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION: {
|
|
228
|
+
const histNotification = protocolMsg.historySyncNotification
|
|
229
|
+
const process = shouldProcessHistoryMsg
|
|
230
|
+
const isLatest = !creds.processedHistoryMessages?.length
|
|
231
|
+
logger?.info({ histNotification, process, id: message.key.id, isLatest }, 'got history notification')
|
|
232
|
+
if (process) {
|
|
233
|
+
if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
|
234
|
+
ev.emit('creds.update', {
|
|
235
|
+
processedHistoryMessages: [...(creds.processedHistoryMessages || []), { key: message.key, messageTimestamp: message.messageTimestamp }]
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger)
|
|
239
|
+
if (data.lidPnMappings?.length) {
|
|
240
|
+
logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync')
|
|
241
|
+
await signalRepository.lidMapping.storeLIDPNMappings(data.lidPnMappings).catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'))
|
|
242
|
+
}
|
|
243
|
+
await storeTcTokensFromHistorySync(data.chats, signalRepository, keyStore, logger)
|
|
244
|
+
ev.emit('messaging-history.set', {
|
|
245
|
+
...data,
|
|
246
|
+
isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
|
|
247
|
+
chunkOrder: histNotification.chunkOrder,
|
|
248
|
+
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
|
|
249
|
+
})
|
|
250
|
+
}
|
|
251
|
+
break
|
|
252
|
+
}
|
|
253
|
+
case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE: {
|
|
254
|
+
const keys = protocolMsg.appStateSyncKeyShare.keys
|
|
255
|
+
if (keys?.length) {
|
|
256
|
+
let newAppStateSyncKeyId = ''
|
|
257
|
+
await keyStore.transaction(async () => {
|
|
258
|
+
const newKeys = []
|
|
259
|
+
for (const { keyData, keyId } of keys) {
|
|
260
|
+
const strKeyId = Buffer.from(keyId.keyId).toString('base64')
|
|
261
|
+
newKeys.push(strKeyId)
|
|
262
|
+
await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } })
|
|
263
|
+
newAppStateSyncKeyId = strKeyId
|
|
264
|
+
}
|
|
265
|
+
logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys')
|
|
266
|
+
}, meId)
|
|
267
|
+
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId })
|
|
268
|
+
} else {
|
|
269
|
+
logger?.info({ protocolMsg }, 'recv app state sync with 0 keys')
|
|
270
|
+
}
|
|
271
|
+
break
|
|
272
|
+
}
|
|
273
|
+
case proto.Message.ProtocolMessage.Type.REVOKE:
|
|
274
|
+
ev.emit('messages.update', [
|
|
275
|
+
{ key: { ...message.key, id: protocolMsg.key.id }, update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key } }
|
|
276
|
+
])
|
|
277
|
+
break
|
|
278
|
+
case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
|
|
279
|
+
Object.assign(chat, { ephemeralSettingTimestamp: toNumber(message.messageTimestamp), ephemeralExpiration: protocolMsg.ephemeralExpiration || null })
|
|
280
|
+
break
|
|
281
|
+
case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE: {
|
|
282
|
+
const response = protocolMsg.peerDataOperationRequestResponseMessage
|
|
283
|
+
if (response) {
|
|
284
|
+
const peerDataOperationResult = response.peerDataOperationResult || []
|
|
285
|
+
for (const result of peerDataOperationResult) {
|
|
286
|
+
const retryResponse = result?.placeholderMessageResendResponse
|
|
287
|
+
if (!retryResponse?.webMessageInfoBytes) continue
|
|
288
|
+
try {
|
|
289
|
+
const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes)
|
|
290
|
+
const msgId = webMessageInfo.key?.id
|
|
291
|
+
const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined
|
|
292
|
+
if (msgId) await placeholderResendCache?.del(msgId)
|
|
293
|
+
let finalMsg
|
|
294
|
+
if (cachedData && typeof cachedData === 'object') {
|
|
295
|
+
cachedData.message = webMessageInfo.message
|
|
296
|
+
if (webMessageInfo.messageTimestamp) cachedData.messageTimestamp = webMessageInfo.messageTimestamp
|
|
297
|
+
finalMsg = cachedData
|
|
298
|
+
} else {
|
|
299
|
+
finalMsg = webMessageInfo
|
|
300
|
+
}
|
|
301
|
+
logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend')
|
|
302
|
+
ev.emit('messages.upsert', { messages: [finalMsg], type: 'notify', requestId: response.stanzaId })
|
|
303
|
+
} catch (err) {
|
|
304
|
+
logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response')
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
break
|
|
309
|
+
}
|
|
310
|
+
case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
|
|
311
|
+
ev.emit('messages.update', [
|
|
312
|
+
{
|
|
313
|
+
key: { ...message.key, id: protocolMsg.key?.id },
|
|
314
|
+
update: {
|
|
315
|
+
message: { editedMessage: { message: protocolMsg.editedMessage } },
|
|
316
|
+
messageTimestamp: protocolMsg.timestampMs ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000) : message.messageTimestamp
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
])
|
|
320
|
+
break
|
|
321
|
+
case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE: {
|
|
322
|
+
const labelAssociationMsg = protocolMsg.memberLabel
|
|
323
|
+
if (labelAssociationMsg?.label) {
|
|
324
|
+
ev.emit('group.member-tag.update', {
|
|
325
|
+
groupId: chat.id,
|
|
326
|
+
label: labelAssociationMsg.label,
|
|
327
|
+
participant: message.key.participant,
|
|
328
|
+
participantAlt: message.key.participantAlt,
|
|
329
|
+
messageTimestamp: Number(message.messageTimestamp)
|
|
330
|
+
})
|
|
331
|
+
}
|
|
332
|
+
break
|
|
333
|
+
}
|
|
334
|
+
case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC: {
|
|
335
|
+
const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload
|
|
336
|
+
const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload)
|
|
337
|
+
logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp')
|
|
338
|
+
const pairs = []
|
|
339
|
+
for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
|
|
340
|
+
const lid = latestLid || assignedLid
|
|
341
|
+
pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` })
|
|
342
|
+
}
|
|
343
|
+
await signalRepository.lidMapping.storeLIDPNMappings(pairs)
|
|
344
|
+
if (pairs.length) for (const { pn, lid } of pairs) await signalRepository.migrateSession(pn, lid)
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
} else if (content?.reactionMessage) {
|
|
348
|
+
const reaction = { ...content.reactionMessage, key: message.key }
|
|
349
|
+
ev.emit('messages.reaction', [{ reaction, key: content.reactionMessage?.key }])
|
|
350
|
+
} else if (content?.encEventResponseMessage) {
|
|
351
|
+
const encEventResponse = content.encEventResponseMessage
|
|
352
|
+
const creationMsgKey = encEventResponse.eventCreationMessageKey
|
|
353
|
+
const eventMsg = await getMessage(creationMsgKey)
|
|
354
|
+
if (eventMsg) {
|
|
355
|
+
try {
|
|
356
|
+
const meIdNormalised = jidNormalizedUser(meId)
|
|
357
|
+
const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid
|
|
358
|
+
const eventCreatorPn = isLidUser(eventCreatorKey) ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey) : eventCreatorKey
|
|
359
|
+
const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised)
|
|
360
|
+
const responderJid = getKeyAuthor(message.key, meIdNormalised)
|
|
361
|
+
const eventEncKey = eventMsg?.messageContextInfo?.messageSecret
|
|
362
|
+
if (!eventEncKey) {
|
|
363
|
+
logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption')
|
|
364
|
+
} else {
|
|
365
|
+
const responseMsg = decryptEventResponse(encEventResponse, { eventEncKey, eventCreatorJid, eventMsgId: creationMsgKey.id, responderJid })
|
|
366
|
+
const eventResponse = { eventResponseMessageKey: message.key, senderTimestampMs: responseMsg.timestampMs, response: responseMsg }
|
|
367
|
+
ev.emit('messages.update', [{ key: creationMsgKey, update: { eventResponses: [eventResponse] } }])
|
|
368
|
+
}
|
|
369
|
+
} catch (err) {
|
|
370
|
+
logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response')
|
|
371
|
+
}
|
|
372
|
+
} else {
|
|
373
|
+
logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response')
|
|
374
|
+
}
|
|
375
|
+
} else if (content?.secretEncryptedMessage && content.secretEncryptedMessage.secretEncType === proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT) {
|
|
376
|
+
const secEnc = content.secretEncryptedMessage
|
|
377
|
+
const targetKey = secEnc.targetMessageKey
|
|
378
|
+
const targetMsg = await getMessage(targetKey)
|
|
379
|
+
if (targetMsg) {
|
|
380
|
+
try {
|
|
381
|
+
const meIdNormalised = jidNormalizedUser(meId)
|
|
382
|
+
const origSenderRaw = targetKey.participant || targetKey.remoteJid
|
|
383
|
+
const origSenderPn = isLidUser(origSenderRaw) ? await signalRepository.lidMapping.getPNForLID(origSenderRaw) : origSenderRaw
|
|
384
|
+
const originalSenderJid = getKeyAuthor({ remoteJid: jidNormalizedUser(origSenderPn), fromMe: meIdNormalised === origSenderPn }, meIdNormalised)
|
|
385
|
+
const editorJid = getKeyAuthor(message.key, meIdNormalised)
|
|
386
|
+
const editEncKey = targetMsg?.messageContextInfo?.messageSecret
|
|
387
|
+
if (!editEncKey) {
|
|
388
|
+
logger?.warn({ targetKey }, 'message edit: missing messageSecret on original message — cannot decrypt')
|
|
389
|
+
return
|
|
390
|
+
}
|
|
391
|
+
const update = buildEditUpdate({
|
|
392
|
+
editEncKey,
|
|
393
|
+
encPayload: secEnc.encPayload,
|
|
394
|
+
encIv: secEnc.encIv,
|
|
395
|
+
originalSenderJid,
|
|
396
|
+
originalMsgId: targetKey.id,
|
|
397
|
+
editorJid,
|
|
398
|
+
messageKey: message.key,
|
|
399
|
+
targetKeyId: targetKey.id,
|
|
400
|
+
fallbackTimestamp: toNumber(message.messageTimestamp),
|
|
401
|
+
logger,
|
|
402
|
+
targetKey
|
|
403
|
+
})
|
|
404
|
+
if (update) ev.emit('messages.update', [update])
|
|
405
|
+
} catch (err) {
|
|
406
|
+
logger?.warn({ err, targetKey }, 'failed to decrypt secretEncryptedMessage MESSAGE_EDIT')
|
|
407
|
+
}
|
|
408
|
+
} else {
|
|
409
|
+
logger?.warn({ targetKey }, 'original message not found in store, cannot decrypt secretEncryptedMessage edit')
|
|
410
|
+
}
|
|
411
|
+
} else if (message.messageStubType) {
|
|
412
|
+
const jid = message.key?.remoteJid
|
|
413
|
+
let participants
|
|
414
|
+
const emitParticipantsUpdate = action =>
|
|
415
|
+
ev.emit('group-participants.update', { id: jid, author: message.key.participant, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername, participants, action })
|
|
416
|
+
const emitGroupUpdate = update =>
|
|
417
|
+
ev.emit('groups.update', [{ id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt, authorUsername: message.key.participantUsername }])
|
|
418
|
+
const emitGroupRequestJoin = (participant, action, method) =>
|
|
419
|
+
ev.emit('group.join-request', {
|
|
420
|
+
id: jid,
|
|
421
|
+
author: message.key.participant,
|
|
422
|
+
authorPn: message.key.participantAlt,
|
|
423
|
+
authorUsername: message.key.participantUsername,
|
|
424
|
+
participant: participant.lid,
|
|
425
|
+
participantPn: participant.pn,
|
|
426
|
+
action,
|
|
427
|
+
method
|
|
428
|
+
})
|
|
429
|
+
const participantsIncludesMe = () => participants.find(jid_ => areJidsSameUser(meId, jid_.phoneNumber))
|
|
430
|
+
|
|
431
|
+
switch (message.messageStubType) {
|
|
432
|
+
case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
|
433
|
+
participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
|
|
434
|
+
emitParticipantsUpdate('modify')
|
|
435
|
+
break
|
|
436
|
+
case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
|
|
437
|
+
case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
|
|
438
|
+
participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
|
|
439
|
+
emitParticipantsUpdate('remove')
|
|
440
|
+
if (participantsIncludesMe()) chat.readOnly = true
|
|
441
|
+
break
|
|
442
|
+
case WAMessageStubType.GROUP_PARTICIPANT_ADD:
|
|
443
|
+
case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
|
|
444
|
+
case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
|
|
445
|
+
participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
|
|
446
|
+
if (participantsIncludesMe()) chat.readOnly = false
|
|
447
|
+
emitParticipantsUpdate('add')
|
|
448
|
+
break
|
|
449
|
+
case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
|
|
450
|
+
participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
|
|
451
|
+
emitParticipantsUpdate('demote')
|
|
452
|
+
break
|
|
453
|
+
case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
|
|
454
|
+
participants = message.messageStubParameters.map(a => JSON.parse(a)) || []
|
|
455
|
+
emitParticipantsUpdate('promote')
|
|
456
|
+
break
|
|
457
|
+
case WAMessageStubType.GROUP_CHANGE_ANNOUNCE: {
|
|
458
|
+
const announceValue = message.messageStubParameters?.[0]
|
|
459
|
+
emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' })
|
|
460
|
+
break
|
|
461
|
+
}
|
|
462
|
+
case WAMessageStubType.GROUP_CHANGE_RESTRICT: {
|
|
463
|
+
const restrictValue = message.messageStubParameters?.[0]
|
|
464
|
+
emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' })
|
|
465
|
+
break
|
|
466
|
+
}
|
|
467
|
+
case WAMessageStubType.GROUP_CHANGE_SUBJECT: {
|
|
468
|
+
const name = message.messageStubParameters?.[0]
|
|
469
|
+
chat.name = name
|
|
470
|
+
emitGroupUpdate({ subject: name })
|
|
471
|
+
break
|
|
472
|
+
}
|
|
473
|
+
case WAMessageStubType.GROUP_CHANGE_DESCRIPTION: {
|
|
474
|
+
const description = message.messageStubParameters?.[0]
|
|
475
|
+
chat.description = description
|
|
476
|
+
emitGroupUpdate({ desc: description })
|
|
477
|
+
break
|
|
478
|
+
}
|
|
479
|
+
case WAMessageStubType.GROUP_CHANGE_INVITE_LINK: {
|
|
480
|
+
const code = message.messageStubParameters?.[0]
|
|
481
|
+
emitGroupUpdate({ inviteCode: code })
|
|
482
|
+
break
|
|
483
|
+
}
|
|
484
|
+
case WAMessageStubType.GROUP_MEMBER_ADD_MODE: {
|
|
485
|
+
const memberAddValue = message.messageStubParameters?.[0]
|
|
486
|
+
emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' })
|
|
487
|
+
break
|
|
488
|
+
}
|
|
489
|
+
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE: {
|
|
490
|
+
const approvalMode = message.messageStubParameters?.[0]
|
|
491
|
+
emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' })
|
|
492
|
+
break
|
|
493
|
+
}
|
|
494
|
+
case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: {
|
|
495
|
+
const participant = JSON.parse(message.messageStubParameters?.[0])
|
|
496
|
+
const action = message.messageStubParameters?.[1]
|
|
497
|
+
const method = message.messageStubParameters?.[2]
|
|
498
|
+
emitGroupRequestJoin(participant, action, method)
|
|
499
|
+
break
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (Object.keys(chat).length > 1) ev.emit('chats.update', [chat])
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
export default processMessage
|
|
507
|
+
|
|
508
|
+
/* ------------------------------------------------------------------ */
|
|
509
|
+
/* Message retry manager */
|
|
510
|
+
/* ------------------------------------------------------------------ */
|
|
511
|
+
|
|
512
|
+
const RECENT_MESSAGES_SIZE = 1024
|
|
513
|
+
const MESSAGE_KEY_SEPARATOR = '\u0000'
|
|
514
|
+
const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
|
|
515
|
+
const PHONE_REQUEST_DELAY = 3000
|
|
516
|
+
|
|
517
|
+
/** Retry reason codes matching WhatsApp Web's Signal error codes. */
|
|
518
|
+
export const RetryReason = {
|
|
519
|
+
UnknownError: 0,
|
|
520
|
+
SignalErrorNoSession: 1,
|
|
521
|
+
SignalErrorInvalidKey: 2,
|
|
522
|
+
SignalErrorInvalidKeyId: 3,
|
|
523
|
+
SignalErrorInvalidMessage: 4, // MAC verification failed - most common cause of decryption failures
|
|
524
|
+
SignalErrorInvalidSignature: 5,
|
|
525
|
+
SignalErrorFutureMessage: 6,
|
|
526
|
+
SignalErrorBadMac: 7, // Explicit MAC failure - session is definitely out of sync
|
|
527
|
+
SignalErrorInvalidSession: 8,
|
|
528
|
+
SignalErrorInvalidMsgKey: 9,
|
|
529
|
+
BadBroadcastEphemeralSetting: 10,
|
|
530
|
+
UnknownCompanionNoPrekey: 11,
|
|
531
|
+
AdvFailure: 12,
|
|
532
|
+
StatusRevokeDelay: 13
|
|
533
|
+
}
|
|
534
|
+
// reverse lookup for logging, mirrors the old TS enum's string access
|
|
535
|
+
for (const [name, value] of Object.entries({ ...RetryReason })) RetryReason[value] = name
|
|
536
|
+
|
|
537
|
+
const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac])
|
|
538
|
+
|
|
539
|
+
export class MessageRetryManager {
|
|
540
|
+
constructor(logger, maxMsgRetryCount) {
|
|
541
|
+
this.logger = logger
|
|
542
|
+
this.recentMessagesMap = new Cache({
|
|
543
|
+
max: RECENT_MESSAGES_SIZE,
|
|
544
|
+
ttl: 5 * 60 * 1000,
|
|
545
|
+
dispose: (_value, key) => {
|
|
546
|
+
const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
|
|
547
|
+
if (separatorIndex > -1) this.messageKeyIndex.delete(key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length))
|
|
548
|
+
}
|
|
549
|
+
})
|
|
550
|
+
this.messageKeyIndex = new Map()
|
|
551
|
+
this.sessionRecreateHistory = new Cache({ ttl: RECREATE_SESSION_TIMEOUT * 2 })
|
|
552
|
+
this.retryCounters = new Cache({ ttl: 15 * 60 * 1000, updateAgeOnGet: true })
|
|
553
|
+
this.baseKeys = new Cache({ max: 1024, ttl: 15 * 60 * 1000 })
|
|
554
|
+
this.pendingPhoneRequests = {}
|
|
555
|
+
this.maxMsgRetryCount = maxMsgRetryCount
|
|
556
|
+
this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
|
|
557
|
+
// Tracks messages that were locally edited or revoked, so a late-arriving retry
|
|
558
|
+
// receipt for the pre-edit/pre-revoke version doesn't resend stale content (e.g.
|
|
559
|
+
// a deleted message reappearing, or an edit getting overwritten by its own
|
|
560
|
+
// pre-edit body). Bounded TTL: only need to cover the window a stale retry could
|
|
561
|
+
// realistically still be in flight.
|
|
562
|
+
this.invalidatedMessages = new Cache({ max: 512, ttl: 5 * 60 * 1000 })
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
invalidatedKey(to, id) {
|
|
566
|
+
return this.keyToString({ to, id })
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Mark (to, id) as edited/revoked so a subsequent resend request for it is dropped. */
|
|
570
|
+
invalidateMessage(to, id) {
|
|
571
|
+
if (!to || !id) return
|
|
572
|
+
this.invalidatedMessages.set(this.invalidatedKey(to, id), true)
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
isMessageInvalidated(to, id) {
|
|
576
|
+
if (!to || !id) return false
|
|
577
|
+
return this.invalidatedMessages.get(this.invalidatedKey(to, id)) === true
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
addRecentMessage(to, id, message) {
|
|
581
|
+
const keyStr = this.keyToString({ to, id })
|
|
582
|
+
this.recentMessagesMap.set(keyStr, { message, timestamp: Date.now() })
|
|
583
|
+
this.messageKeyIndex.set(id, keyStr)
|
|
584
|
+
this.logger.debug(`Added message to retry cache: ${to}/${id}`)
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
getRecentMessage(to, id) {
|
|
588
|
+
return this.recentMessagesMap.get(this.keyToString({ to, id }))
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout. */
|
|
592
|
+
shouldRecreateSession(jid, hasSession, errorCode) {
|
|
593
|
+
if (!hasSession) {
|
|
594
|
+
this.sessionRecreateHistory.set(jid, Date.now())
|
|
595
|
+
this.statistics.sessionRecreations++
|
|
596
|
+
return { reason: "we don't have a Signal session with them", recreate: true }
|
|
597
|
+
}
|
|
598
|
+
if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
|
|
599
|
+
this.sessionRecreateHistory.set(jid, Date.now())
|
|
600
|
+
this.statistics.sessionRecreations++
|
|
601
|
+
this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation')
|
|
602
|
+
return { reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`, recreate: true }
|
|
603
|
+
}
|
|
604
|
+
const now = Date.now()
|
|
605
|
+
const prevTime = this.sessionRecreateHistory.get(jid)
|
|
606
|
+
if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
|
|
607
|
+
this.sessionRecreateHistory.set(jid, now)
|
|
608
|
+
this.statistics.sessionRecreations++
|
|
609
|
+
return { reason: 'retry count > 1 and over an hour since last recreation', recreate: true }
|
|
610
|
+
}
|
|
611
|
+
return { reason: '', recreate: false }
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
parseRetryErrorCode(errorAttr) {
|
|
615
|
+
if (errorAttr === undefined || errorAttr === '') return undefined
|
|
616
|
+
const code = parseInt(errorAttr, 10)
|
|
617
|
+
if (Number.isNaN(code)) return undefined
|
|
618
|
+
if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) return code
|
|
619
|
+
return RetryReason.UnknownError
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
isMacError(errorCode) {
|
|
623
|
+
return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
incrementRetryCount(messageId) {
|
|
627
|
+
this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1)
|
|
628
|
+
this.statistics.totalRetries++
|
|
629
|
+
return this.retryCounters.get(messageId)
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
getRetryCount(messageId) {
|
|
633
|
+
return this.retryCounters.get(messageId) || 0
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
hasExceededMaxRetries(messageId) {
|
|
637
|
+
return this.getRetryCount(messageId) >= this.maxMsgRetryCount
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
markRetrySuccess(messageId) {
|
|
641
|
+
this.statistics.successfulRetries++
|
|
642
|
+
this.retryCounters.delete(messageId)
|
|
643
|
+
this.cancelPendingPhoneRequest(messageId)
|
|
644
|
+
this.removeRecentMessage(messageId)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
markRetryFailed(messageId) {
|
|
648
|
+
this.statistics.failedRetries++
|
|
649
|
+
this.retryCounters.delete(messageId)
|
|
650
|
+
this.cancelPendingPhoneRequest(messageId)
|
|
651
|
+
this.removeRecentMessage(messageId)
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
|
|
655
|
+
this.cancelPendingPhoneRequest(messageId)
|
|
656
|
+
this.pendingPhoneRequests[messageId] = setTimeout(() => {
|
|
657
|
+
delete this.pendingPhoneRequests[messageId]
|
|
658
|
+
this.statistics.phoneRequests++
|
|
659
|
+
callback()
|
|
660
|
+
}, delay)
|
|
661
|
+
this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`)
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
cancelPendingPhoneRequest(messageId) {
|
|
665
|
+
const timeout = this.pendingPhoneRequests[messageId]
|
|
666
|
+
if (timeout) {
|
|
667
|
+
clearTimeout(timeout)
|
|
668
|
+
delete this.pendingPhoneRequests[messageId]
|
|
669
|
+
this.logger.debug(`Cancelled pending phone request for message ${messageId}`)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
clear() {
|
|
674
|
+
this.recentMessagesMap.clear()
|
|
675
|
+
this.messageKeyIndex.clear()
|
|
676
|
+
this.sessionRecreateHistory.clear()
|
|
677
|
+
this.retryCounters.clear()
|
|
678
|
+
this.baseKeys.clear()
|
|
679
|
+
this.invalidatedMessages.clear()
|
|
680
|
+
for (const messageId of Object.keys(this.pendingPhoneRequests)) this.cancelPendingPhoneRequest(messageId)
|
|
681
|
+
this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
saveBaseKey(addr, msgId, baseKey) {
|
|
685
|
+
this.baseKeys.set(`${addr}:${msgId}`, baseKey)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
hasSameBaseKey(addr, msgId, baseKey) {
|
|
689
|
+
const stored = this.baseKeys.get(`${addr}:${msgId}`)
|
|
690
|
+
if (!stored || stored.length !== baseKey.length) return false
|
|
691
|
+
for (let i = 0; i < stored.length; i++) if (stored[i] !== baseKey[i]) return false
|
|
692
|
+
return true
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
deleteBaseKey(addr, msgId) {
|
|
696
|
+
this.baseKeys.delete(`${addr}:${msgId}`)
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
keyToString(key) {
|
|
700
|
+
return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
removeRecentMessage(messageId) {
|
|
704
|
+
const keyStr = this.messageKeyIndex.get(messageId)
|
|
705
|
+
if (!keyStr) return
|
|
706
|
+
this.recentMessagesMap.delete(keyStr)
|
|
707
|
+
this.messageKeyIndex.delete(messageId)
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/* ------------------------------------------------------------------ */
|
|
712
|
+
/* Offline node processor */
|
|
713
|
+
/* ------------------------------------------------------------------ */
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Creates a processor for offline stanza nodes that:
|
|
717
|
+
* - Queues nodes for sequential processing
|
|
718
|
+
* - Yields to the event loop periodically to avoid blocking
|
|
719
|
+
* - Catches handler errors to prevent the processing loop from crashing
|
|
720
|
+
*/
|
|
721
|
+
export function makeOfflineNodeProcessor(nodeProcessorMap, deps, batchSize = 10) {
|
|
722
|
+
const nodes = []
|
|
723
|
+
let isProcessing = false
|
|
724
|
+
const enqueue = (type, node) => {
|
|
725
|
+
nodes.push({ type, node })
|
|
726
|
+
if (isProcessing) return
|
|
727
|
+
isProcessing = true
|
|
728
|
+
const run = async () => {
|
|
729
|
+
let processedInBatch = 0
|
|
730
|
+
while (nodes.length && deps.isWsOpen()) {
|
|
731
|
+
const { type, node } = nodes.shift()
|
|
732
|
+
const nodeProcessor = nodeProcessorMap.get(type)
|
|
733
|
+
if (!nodeProcessor) {
|
|
734
|
+
deps.onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node')
|
|
735
|
+
continue
|
|
736
|
+
}
|
|
737
|
+
await nodeProcessor(node).catch(err => deps.onUnexpectedError(err, `processing offline ${type}`))
|
|
738
|
+
processedInBatch++
|
|
739
|
+
if (processedInBatch >= batchSize) {
|
|
740
|
+
processedInBatch = 0
|
|
741
|
+
await deps.yieldToEventLoop()
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
isProcessing = false
|
|
745
|
+
}
|
|
746
|
+
run().catch(error => deps.onUnexpectedError(error, 'processing offline nodes'))
|
|
747
|
+
}
|
|
748
|
+
return { enqueue }
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/* ------------------------------------------------------------------ */
|
|
752
|
+
/* History sync */
|
|
753
|
+
/* ------------------------------------------------------------------ */
|
|
754
|
+
|
|
755
|
+
const extractPnFromMessages = messages => {
|
|
756
|
+
for (const msgItem of messages) {
|
|
757
|
+
const message = msgItem.message
|
|
758
|
+
if (!message?.key?.fromMe || !message.userReceipt?.length) continue
|
|
759
|
+
const userJid = message.userReceipt[0]?.userJid
|
|
760
|
+
if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) return userJid
|
|
761
|
+
}
|
|
762
|
+
return undefined
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
export const downloadHistory = async (msg, options) => {
|
|
766
|
+
const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
|
|
767
|
+
const inflater = createInflate()
|
|
768
|
+
const chunks = []
|
|
769
|
+
inflater.on('data', chunk => chunks.push(chunk))
|
|
770
|
+
await pipeline(stream, inflater)
|
|
771
|
+
return proto.HistorySync.decode(Buffer.concat(chunks))
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
export const processHistoryMessage = (item, logger) => {
|
|
775
|
+
const messages = []
|
|
776
|
+
const contacts = []
|
|
777
|
+
const chats = []
|
|
778
|
+
const lidPnMappings = []
|
|
779
|
+
logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString())
|
|
780
|
+
for (const m of item.phoneNumberToLidMappings || []) {
|
|
781
|
+
if (m.lidJid && m.pnJid) lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid })
|
|
782
|
+
}
|
|
783
|
+
switch (item.syncType) {
|
|
784
|
+
case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
|
|
785
|
+
case proto.HistorySync.HistorySyncType.RECENT:
|
|
786
|
+
case proto.HistorySync.HistorySyncType.FULL:
|
|
787
|
+
case proto.HistorySync.HistorySyncType.ON_DEMAND:
|
|
788
|
+
for (const chat of item.conversations) {
|
|
789
|
+
contacts.push({ id: chat.id, name: chat.displayName || chat.name || chat.username || undefined, username: chat.username || undefined, lid: chat.lidJid || chat.accountLid || undefined, phoneNumber: chat.pnJid || undefined })
|
|
790
|
+
const chatId = chat.id
|
|
791
|
+
const isLid = isLidUser(chatId) || isHostedLidUser(chatId)
|
|
792
|
+
const isPn = isPnUser(chatId) || isHostedPnUser(chatId)
|
|
793
|
+
if (isLid && chat.pnJid) lidPnMappings.push({ lid: chatId, pn: chat.pnJid })
|
|
794
|
+
else if (isPn && chat.lidJid) lidPnMappings.push({ lid: chat.lidJid, pn: chatId })
|
|
795
|
+
else if (isLid && !chat.pnJid) {
|
|
796
|
+
const pnFromReceipt = extractPnFromMessages(chat.messages || [])
|
|
797
|
+
if (pnFromReceipt) lidPnMappings.push({ lid: chatId, pn: pnFromReceipt })
|
|
798
|
+
}
|
|
799
|
+
const msgs = chat.messages || []
|
|
800
|
+
delete chat.messages
|
|
801
|
+
for (const item_ of msgs) {
|
|
802
|
+
const message = item_.message
|
|
803
|
+
messages.push(message)
|
|
804
|
+
if (!chat.messages?.length) chat.messages = [{ message }] // keep only the most recent message in the chat array
|
|
805
|
+
if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
|
|
806
|
+
if (
|
|
807
|
+
(message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
|
|
808
|
+
message.messageStubParameters?.[0]
|
|
809
|
+
) {
|
|
810
|
+
contacts.push({ id: message.key.participant || message.key.remoteJid, verifiedName: message.messageStubParameters?.[0] })
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
chats.push(chat)
|
|
814
|
+
}
|
|
815
|
+
break
|
|
816
|
+
case proto.HistorySync.HistorySyncType.PUSH_NAME:
|
|
817
|
+
for (const c of item.pushnames) contacts.push({ id: c.id, notify: c.pushname })
|
|
818
|
+
break
|
|
819
|
+
}
|
|
820
|
+
return { chats, contacts, messages, lidPnMappings, pastParticipants: item.pastParticipants, syncType: item.syncType, progress: item.progress }
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
|
|
824
|
+
const historyMsg = msg.initialHistBootstrapInlinePayload
|
|
825
|
+
? proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload))
|
|
826
|
+
: await downloadHistory(msg, options)
|
|
827
|
+
return processHistoryMessage(historyMsg, logger)
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
export const getHistoryMsg = message => {
|
|
831
|
+
const normalizedContent = message ? normalizeMessageContent(message) : undefined
|
|
832
|
+
return normalizedContent?.protocolMessage?.historySyncNotification
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/* ------------------------------------------------------------------ */
|
|
836
|
+
/* Business / catalog */
|
|
837
|
+
/* ------------------------------------------------------------------ */
|
|
838
|
+
|
|
839
|
+
export const parseCatalogNode = node => {
|
|
840
|
+
const catalogNode = getBinaryNodeChild(node, 'product_catalog')
|
|
841
|
+
const products = getBinaryNodeChildren(catalogNode, 'product').map(parseProductNode)
|
|
842
|
+
const paging = getBinaryNodeChild(catalogNode, 'paging')
|
|
843
|
+
return { products, nextPageCursor: paging ? getBinaryNodeChildString(paging, 'after') : undefined }
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
export const parseCollectionsNode = node => {
|
|
847
|
+
const collectionsNode = getBinaryNodeChild(node, 'collections')
|
|
848
|
+
const collections = getBinaryNodeChildren(collectionsNode, 'collection').map(collectionNode => ({
|
|
849
|
+
id: getBinaryNodeChildString(collectionNode, 'id'),
|
|
850
|
+
name: getBinaryNodeChildString(collectionNode, 'name'),
|
|
851
|
+
products: getBinaryNodeChildren(collectionNode, 'product').map(parseProductNode),
|
|
852
|
+
status: parseStatusInfo(collectionNode)
|
|
853
|
+
}))
|
|
854
|
+
return { collections }
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
export const parseOrderDetailsNode = node => {
|
|
858
|
+
const orderNode = getBinaryNodeChild(node, 'order')
|
|
859
|
+
const products = getBinaryNodeChildren(orderNode, 'product').map(productNode => {
|
|
860
|
+
const imageNode = getBinaryNodeChild(productNode, 'image')
|
|
861
|
+
return {
|
|
862
|
+
id: getBinaryNodeChildString(productNode, 'id'),
|
|
863
|
+
name: getBinaryNodeChildString(productNode, 'name'),
|
|
864
|
+
imageUrl: getBinaryNodeChildString(imageNode, 'url'),
|
|
865
|
+
price: +getBinaryNodeChildString(productNode, 'price'),
|
|
866
|
+
currency: getBinaryNodeChildString(productNode, 'currency'),
|
|
867
|
+
quantity: +getBinaryNodeChildString(productNode, 'quantity')
|
|
868
|
+
}
|
|
869
|
+
})
|
|
870
|
+
const priceNode = getBinaryNodeChild(orderNode, 'price')
|
|
871
|
+
return { price: { total: +getBinaryNodeChildString(priceNode, 'total'), currency: getBinaryNodeChildString(priceNode, 'currency') }, products }
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
export const toProductNode = (productId, product) => {
|
|
875
|
+
const attrs = {}
|
|
876
|
+
const content = []
|
|
877
|
+
if (typeof productId !== 'undefined') content.push({ tag: 'id', attrs: {}, content: Buffer.from(productId) })
|
|
878
|
+
if (typeof product.name !== 'undefined') content.push({ tag: 'name', attrs: {}, content: Buffer.from(product.name) })
|
|
879
|
+
if (typeof product.description !== 'undefined') content.push({ tag: 'description', attrs: {}, content: Buffer.from(product.description) })
|
|
880
|
+
if (typeof product.retailerId !== 'undefined') content.push({ tag: 'retailer_id', attrs: {}, content: Buffer.from(product.retailerId) })
|
|
881
|
+
if (product.images.length) {
|
|
882
|
+
content.push({
|
|
883
|
+
tag: 'media',
|
|
884
|
+
attrs: {},
|
|
885
|
+
content: product.images.map(img => {
|
|
886
|
+
if (!('url' in img)) throw new Boom('Expected img for product to already be uploaded', { statusCode: 400 })
|
|
887
|
+
return { tag: 'image', attrs: {}, content: [{ tag: 'url', attrs: {}, content: Buffer.from(img.url.toString()) }] }
|
|
888
|
+
})
|
|
889
|
+
})
|
|
890
|
+
}
|
|
891
|
+
if (typeof product.price !== 'undefined') content.push({ tag: 'price', attrs: {}, content: Buffer.from(product.price.toString()) })
|
|
892
|
+
if (typeof product.currency !== 'undefined') content.push({ tag: 'currency', attrs: {}, content: Buffer.from(product.currency) })
|
|
893
|
+
if ('originCountryCode' in product) {
|
|
894
|
+
if (typeof product.originCountryCode === 'undefined') attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT'
|
|
895
|
+
else content.push({ tag: 'compliance_info', attrs: {}, content: [{ tag: 'country_code_origin', attrs: {}, content: Buffer.from(product.originCountryCode) }] })
|
|
896
|
+
}
|
|
897
|
+
if (typeof product.isHidden !== 'undefined') attrs['is_hidden'] = product.isHidden.toString()
|
|
898
|
+
return { tag: 'product', attrs, content }
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
export const parseProductNode = productNode => {
|
|
902
|
+
const isHidden = productNode.attrs.is_hidden === 'true'
|
|
903
|
+
const id = getBinaryNodeChildString(productNode, 'id')
|
|
904
|
+
const mediaNode = getBinaryNodeChild(productNode, 'media')
|
|
905
|
+
const statusInfoNode = getBinaryNodeChild(productNode, 'status_info')
|
|
906
|
+
return {
|
|
907
|
+
id,
|
|
908
|
+
imageUrls: parseImageUrls(mediaNode),
|
|
909
|
+
reviewStatus: { whatsapp: getBinaryNodeChildString(statusInfoNode, 'status') },
|
|
910
|
+
availability: 'in stock',
|
|
911
|
+
name: getBinaryNodeChildString(productNode, 'name'),
|
|
912
|
+
retailerId: getBinaryNodeChildString(productNode, 'retailer_id'),
|
|
913
|
+
url: getBinaryNodeChildString(productNode, 'url'),
|
|
914
|
+
description: getBinaryNodeChildString(productNode, 'description'),
|
|
915
|
+
price: +getBinaryNodeChildString(productNode, 'price'),
|
|
916
|
+
currency: getBinaryNodeChildString(productNode, 'currency'),
|
|
917
|
+
isHidden
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** Uploads images not already uploaded to WA's servers */
|
|
922
|
+
export async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
|
|
923
|
+
return { ...product, images: product.images ? await uploadingNecessaryImages(product.images, waUploadToServer, timeoutMs) : product.images }
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** Uploads images not already uploaded to WA's servers */
|
|
927
|
+
export const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
|
|
928
|
+
return Promise.all(
|
|
929
|
+
images.map(async img => {
|
|
930
|
+
if ('url' in img) {
|
|
931
|
+
const url = img.url.toString()
|
|
932
|
+
if (url.includes('.whatsapp.net')) return { url }
|
|
933
|
+
}
|
|
934
|
+
const { stream } = await getStream(img)
|
|
935
|
+
const hasher = createHash('sha256')
|
|
936
|
+
const filePath = join(tmpdir(), 'img' + generateMessageIDV2())
|
|
937
|
+
const encFileWriteStream = createWriteStream(filePath)
|
|
938
|
+
for await (const block of stream) {
|
|
939
|
+
hasher.update(block)
|
|
940
|
+
encFileWriteStream.write(block)
|
|
941
|
+
}
|
|
942
|
+
const sha = hasher.digest('base64')
|
|
943
|
+
const { directPath } = await waUploadToServer(filePath, { mediaType: 'product-catalog-image', fileEncSha256B64: sha, timeoutMs })
|
|
944
|
+
await fs.unlink(filePath).catch(err => console.log('Error deleting temp file ', err))
|
|
945
|
+
return { url: getUrlFromDirectPath(directPath) }
|
|
946
|
+
})
|
|
947
|
+
)
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const parseImageUrls = mediaNode => {
|
|
951
|
+
const imgNode = getBinaryNodeChild(mediaNode, 'image')
|
|
952
|
+
return { requested: getBinaryNodeChildString(imgNode, 'request_image_url'), original: getBinaryNodeChildString(imgNode, 'original_image_url') }
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
const parseStatusInfo = mediaNode => {
|
|
956
|
+
const node = getBinaryNodeChild(mediaNode, 'status_info')
|
|
957
|
+
return { status: getBinaryNodeChildString(node, 'status'), canAppeal: getBinaryNodeChildString(node, 'can_appeal') === 'true' }
|
|
958
|
+
}
|