diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 22839fd451..367c2f4773 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -85,6 +85,11 @@ import { createId as cuid } from '@paralleldrive/cuid2'; import { Instance, Message } from '@prisma/client'; import { createJid } from '@utils/createJid'; import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion'; +import { + decryptGroupHistoryBundle, + GROUP_HISTORY_DOWNLOAD_TIMEOUT_MS, + GROUP_HISTORY_MAX_DOWNLOAD_BYTES, +} from '@utils/groupHistoryBundle'; import { makeProxyAgent, makeProxyAgentUndici } from '@utils/makeProxyAgent'; import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache'; import { status } from '@utils/renderStatus'; @@ -92,7 +97,7 @@ import { sendTelemetry } from '@utils/sendTelemetry'; import useMultiFileAuthStatePrisma from '@utils/use-multi-file-auth-state-prisma'; import { AuthStateProvider } from '@utils/use-multi-file-auth-state-provider-files'; import { useMultiFileAuthStateRedisDb } from '@utils/use-multi-file-auth-state-redis-db'; -import axios from 'axios'; +import axios, { AxiosRequestConfig } from 'axios'; import makeWASocket, { AnyMessageContent, BinaryNode, @@ -114,6 +119,7 @@ import makeWASocket, { GetCatalogOptions, getContentType, getDevice, + getUrlFromDirectPath, GroupMetadata, isJidBroadcast, isJidGroup, @@ -263,6 +269,7 @@ export class BaileysStartupService extends ChannelStartupService { private isDeleting = false; // Flag to prevent reconnection during deletion private logBaileys = this.configService.get('LOG').BAILEYS; private eventProcessingQueue: Promise = Promise.resolve(); + private historyQueue: Promise = Promise.resolve(); private _lastStream515At = 0; // Cumulative history sync counters (reset on new sync or completion) @@ -1039,232 +1046,381 @@ export class BaileysStartupService extends ChannelStartupService { }, }; - private readonly messageHandle = { - 'messaging-history.set': async ({ - messages, - chats, - contacts, - isLatest, - progress, - syncType, - }: { - chats: Chat[]; - contacts: Contact[]; - messages: WAMessage[]; - isLatest?: boolean; - progress?: number; - syncType?: proto.HistorySync.HistorySyncType; - }) => { - try { - const normalizedProgress = progress ?? -1; + private enqueueHistory(task: () => Promise): Promise { + const next = this.historyQueue.then(task).catch((error) => { + this.logger.error(`History queue task failed: ${(error as Error)?.message ?? error}`); + }); + this.historyQueue = next; + return next; + } - if (normalizedProgress <= this.historySyncLastProgress) { - this.historySyncMessageCount = 0; - this.historySyncChatCount = 0; - this.historySyncContactCount = 0; - } + private async processGroupHistoryBundle(received: WAMessage): Promise { + return this.enqueueHistory(async () => { + const groupJid = received.key?.remoteJid; + const bundleId = received.key?.id ?? 'unknown'; - this.historySyncLastProgress = normalizedProgress; + try { + const bundle = received.message?.messageHistoryBundle; + if (!groupJid || !isJidGroup(groupJid)) { + return; + } - if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) { - console.log('received on-demand history sync, messages=', messages); + if (!bundle?.mediaKey || bundle.mediaKey.length !== 32) { + this.logger.warn(`GroupHistory bundle ${bundleId} for ${groupJid} missing valid 32-byte mediaKey`); + return; } - console.log( - `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, - ); - const instance: InstanceDto = { instanceName: this.instance.name }; + if ( + typeof bundle.directPath !== 'string' || + !bundle.directPath.startsWith('/') || + bundle.directPath.startsWith('//') + ) { + this.logger.warn(`GroupHistory bundle ${bundleId} for ${groupJid} has invalid directPath`); + return; + } - let timestampLimitToImport = null; + const url = getUrlFromDirectPath(bundle.directPath); + const config: AxiosRequestConfig = { + responseType: 'arraybuffer', + timeout: GROUP_HISTORY_DOWNLOAD_TIMEOUT_MS, + maxContentLength: GROUP_HISTORY_MAX_DOWNLOAD_BYTES, + maxBodyLength: GROUP_HISTORY_MAX_DOWNLOAD_BYTES, + }; - if (this.configService.get('CHATWOOT').ENABLED) { - const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; + if (this.localProxy?.enabled) { + config.httpsAgent = makeProxyAgent({ + host: this.localProxy.host, + port: this.localProxy.port, + protocol: this.localProxy.protocol, + username: this.localProxy.username, + password: this.localProxy.password, + }); + } - const date = new Date(); - timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000; + const response = await axios.get(url, config); + const file = Buffer.isBuffer(response.data) ? response.data : Buffer.from(response.data); - const maxBatchTimestamp = Math.max(...messages.map((message) => message.messageTimestamp as number)); + if (file.length > GROUP_HISTORY_MAX_DOWNLOAD_BYTES) { + throw new Error(`Downloaded bundle exceeds ${GROUP_HISTORY_MAX_DOWNLOAD_BYTES} bytes (${file.length})`); + } - const processBatch = maxBatchTimestamp >= timestampLimitToImport; + const decoded = decryptGroupHistoryBundle(file, bundle.mediaKey, bundle.fileEncSha256); - if (!processBatch) { - return; - } + if (this.endSession || this.isDeleting) { + this.logger.info(`Skipping GroupHistory bundle ${bundleId} for ${groupJid}: session ended or deleting`); + return; } - const contactsMap = new Map(); - const contactsMapLidJid = new Map(); + const expectedCount = bundle.messageHistoryMetadata?.messageCount; + if (typeof expectedCount === 'number' && decoded.length !== expectedCount) { + this.logger.warn( + `GroupHistory bundle ${bundleId} for ${groupJid} decoded ${decoded.length} entries, expected ${expectedCount}`, + ); + } - for (const contact of contacts) { - let jid = null; + const messages: WAMessage[] = []; + for (const entry of decoded) { + if (!entry?.key?.id || !entry.message) { + continue; + } - if (contact?.id?.search('@lid') !== -1) { - if (contact.phoneNumber) { - jid = contact.phoneNumber; - } + if (entry.key.remoteJid && entry.key.remoteJid !== groupJid) { + this.logger.warn( + `GroupHistory bundle ${bundleId} skipped entry ${entry.key.id} with mismatched remoteJid for ${groupJid}`, + ); + continue; } - if (!jid) { - jid = contact?.id; + if (received.key?.fromMe !== true && entry.key.fromMe === true) { + this.logger.warn( + `GroupHistory bundle ${bundleId} skipped entry ${entry.key.id} with fromMe=true for ${groupJid}`, + ); + continue; } - if (contact.id && (contact.notify || contact.name)) { - contactsMap.set(contact.id, { name: contact.name ?? contact.notify, jid }); + const ts = Long.isLong(entry.messageTimestamp) + ? entry.messageTimestamp.toNumber() + : Number(entry.messageTimestamp); + if (!Number.isFinite(ts) || ts <= 0) { + continue; } - contactsMapLidJid.set(contact.id, { jid }); + entry.key.remoteJid = groupJid; + entry.messageTimestamp = ts; + messages.push(entry as WAMessage); } - const chatsRaw: { remoteJid: string; remoteLid: string; instanceId: string; name?: string }[] = []; - const chatsRepository = new Set( - (await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } })).map( - (chat) => chat.remoteJid, - ), + if (messages.length === 0) { + return; + } + + await this.handleHistorySet({ + messages, + chats: [], + contacts: [], + }); + } catch (error) { + this.logger.error( + `Failed to process GroupHistory bundle ${bundleId} for ${groupJid ?? 'unknown'}: ${(error as Error)?.message ?? error}`, ); + } + }); + } - for (const chat of chats) { - if (chatsRepository?.has(chat.id)) { - continue; - } + private async handleHistorySet({ + messages, + chats, + contacts, + isLatest, + progress, + syncType, + }: { + chats: Chat[]; + contacts: Contact[]; + messages: WAMessage[]; + isLatest?: boolean; + progress?: number; + syncType?: proto.HistorySync.HistorySyncType; + }) { + try { + const hasProgress = typeof progress === 'number'; - let remoteJid = null; - let remoteLid = null; + if (hasProgress) { + if (progress <= this.historySyncLastProgress) { + this.historySyncMessageCount = 0; + this.historySyncChatCount = 0; + this.historySyncContactCount = 0; + } - if (chat.id.search('@lid') !== -1) { - const contact = contactsMapLidJid.get(chat.id); + this.historySyncLastProgress = progress; + } - remoteLid = chat.id; + if (syncType === proto.HistorySync.HistorySyncType.ON_DEMAND) { + console.log('received on-demand history sync, messages=', messages); + } + console.log( + `recv ${chats.length} chats, ${contacts.length} contacts, ${messages.length} msgs (is latest: ${isLatest}, progress: ${progress}%), type: ${syncType}`, + ); - if (contact && contact.jid) { - remoteJid = contact.jid; - } - } + const instance: InstanceDto = { instanceName: this.instance.name }; - if (!remoteLid && chat.accountLid && chat.accountLid.search('@lid') !== -1) { - remoteLid = chat.accountLid; - } + let timestampLimitToImport = null; + + if (this.configService.get('CHATWOOT').ENABLED) { + const daysLimitToImport = this.localChatwoot?.enabled ? this.localChatwoot.daysLimitImportMessages : 1000; + + const date = new Date(); + timestampLimitToImport = new Date(date.setDate(date.getDate() - daysLimitToImport)).getTime() / 1000; + + const maxBatchTimestamp = Math.max(...messages.map((message) => message.messageTimestamp as number)); + + const processBatch = maxBatchTimestamp >= timestampLimitToImport; + + if (!processBatch) { + return; + } + } + + const contactsMap = new Map(); + const contactsMapLidJid = new Map(); + + for (const contact of contacts) { + let jid = null; - if (!remoteJid) { - remoteJid = chat.id; + if (contact?.id?.search('@lid') !== -1) { + if (contact.phoneNumber) { + jid = contact.phoneNumber; } + } - chatsRaw.push({ remoteJid, remoteLid, instanceId: this.instanceId, name: chat.name }); + if (!jid) { + jid = contact?.id; } - if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - const chatsToCreateMany = JSON.parse(JSON.stringify(chatsRaw)).map((chat) => { - delete chat.remoteLid; - return chat; - }); + if (contact.id && (contact.notify || contact.name)) { + contactsMap.set(contact.id, { name: contact.name ?? contact.notify, jid }); + } + + contactsMapLidJid.set(contact.id, { jid }); + } + + const chatsRaw: { remoteJid: string; remoteLid: string; instanceId: string; name?: string }[] = []; + const chatsRepository = new Set( + (await this.prismaRepository.chat.findMany({ where: { instanceId: this.instanceId } })).map( + (chat) => chat.remoteJid, + ), + ); - await this.prismaRepository.chat.createMany({ data: chatsToCreateMany, skipDuplicates: true }); + for (const chat of chats) { + if (chatsRepository?.has(chat.id)) { + continue; } - this.historySyncChatCount += chatsRaw.length; + let remoteJid = null; + let remoteLid = null; - this.sendDataWebhook(Events.CHATS_SET, chatsRaw); + if (chat.id.search('@lid') !== -1) { + const contact = contactsMapLidJid.get(chat.id); - const messagesRaw: any[] = []; + remoteLid = chat.id; - const messagesRepository: Set = new Set( - chatwootImport.getRepositoryMessagesCache(instance) ?? - ( - await this.prismaRepository.message.findMany({ - select: { key: true }, - where: { instanceId: this.instanceId }, - }) - ).map((message) => { - const key = message.key as { id: string }; + if (contact && contact.jid) { + remoteJid = contact.jid; + } + } - return key.id; - }), - ); + if (!remoteLid && chat.accountLid && chat.accountLid.search('@lid') !== -1) { + remoteLid = chat.accountLid; + } - if (chatwootImport.getRepositoryMessagesCache(instance) === null) { - chatwootImport.setRepositoryMessagesCache(instance, messagesRepository); + if (!remoteJid) { + remoteJid = chat.id; } - for (const m of messages) { - if (!m.message || !m.key || !m.messageTimestamp) { - continue; - } + chatsRaw.push({ remoteJid, remoteLid, instanceId: this.instanceId, name: chat.name }); + } - if (Long.isLong(m?.messageTimestamp)) { - m.messageTimestamp = m.messageTimestamp?.toNumber(); - } + if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { + const chatsToCreateMany = JSON.parse(JSON.stringify(chatsRaw)).map((chat) => { + delete chat.remoteLid; + return chat; + }); - if (this.configService.get('CHATWOOT').ENABLED) { - if (m.messageTimestamp <= timestampLimitToImport) { - continue; - } - } + await this.prismaRepository.chat.createMany({ data: chatsToCreateMany, skipDuplicates: true }); + } - if (messagesRepository?.has(m.key.id)) { - continue; - } + if (hasProgress) { + this.historySyncChatCount += chatsRaw.length; + } - if (!m.pushName && !m.key.fromMe) { - const participantJid = m.participant || m.key.participant || m.key.remoteJid; - if (participantJid && contactsMap.has(participantJid)) { - m.pushName = contactsMap.get(participantJid).name; - } else if (participantJid) { - m.pushName = participantJid.split('@')[0]; - } - } + this.sendDataWebhook(Events.CHATS_SET, chatsRaw); + + const messagesRaw: any[] = []; + + const cachedRepositoryMessages = chatwootImport.getRepositoryMessagesCache(instance); + const messagesRepository: Set = new Set( + cachedRepositoryMessages ?? + ( + await this.prismaRepository.message.findMany({ + select: { key: true }, + where: { instanceId: this.instanceId }, + }) + ).map((message) => { + const key = message.key as { id: string }; + + return key.id; + }), + ); + + if (cachedRepositoryMessages === null) { + chatwootImport.setRepositoryMessagesCache(instance, messagesRepository); + } + + const batchIds = new Set(); - messagesRaw.push(this.prepareMessage(m)); + for (const m of messages) { + if (!m.message || !m.key || !m.messageTimestamp) { + continue; } - this.historySyncMessageCount += messagesRaw.length; + if (Long.isLong(m?.messageTimestamp)) { + m.messageTimestamp = m.messageTimestamp?.toNumber(); + } - if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { - await this.prismaRepository.message.createMany({ data: messagesRaw, skipDuplicates: true }); + if (this.configService.get('CHATWOOT').ENABLED) { + if (m.messageTimestamp <= timestampLimitToImport) { + continue; + } } - this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw], true, undefined, { - isLatest, - progress, - }); + if (messagesRepository?.has(m.key.id) || batchIds.has(m.key.id)) { + continue; + } - if ( - this.configService.get('CHATWOOT').ENABLED && - this.localChatwoot?.enabled && - this.localChatwoot.importMessages && - messagesRaw.length > 0 - ) { - this.chatwootService.addHistoryMessages( - instance, - messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), - ); + if (!m.pushName && !m.key.fromMe) { + const participantJid = m.participant || m.key.participant || m.key.remoteJid; + if (participantJid && contactsMap.has(participantJid)) { + m.pushName = contactsMap.get(participantJid).name; + } else if (participantJid) { + m.pushName = participantJid.split('@')[0]; + } } - const filteredContacts = contacts.filter((c) => !!c.notify || !!c.name); - this.historySyncContactCount += filteredContacts.length; + messagesRaw.push(this.prepareMessage(m)); + batchIds.add(m.key.id); + } - if (normalizedProgress === 100) { - this.sendDataWebhook(Events.MESSAGING_HISTORY_SET, { - messageCount: this.historySyncMessageCount, - chatCount: this.historySyncChatCount, - contactCount: this.historySyncContactCount, - progress: normalizedProgress, - }); + if (hasProgress) { + this.historySyncMessageCount += messagesRaw.length; + } - this.historySyncMessageCount = 0; - this.historySyncChatCount = 0; - this.historySyncContactCount = 0; - this.historySyncLastProgress = -1; - } + if (this.configService.get('DATABASE').SAVE_DATA.HISTORIC) { + await this.prismaRepository.message.createMany({ data: messagesRaw, skipDuplicates: true }); + } + + for (const id of batchIds) { + messagesRepository.add(id); + cachedRepositoryMessages?.add(id); + } + + this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw], true, undefined, { + isLatest, + progress, + }); - await this.contactHandle['contacts.upsert']( - filteredContacts.map((c) => ({ id: c.id, name: c.name ?? c.notify })), + if ( + this.configService.get('CHATWOOT').ENABLED && + this.localChatwoot?.enabled && + this.localChatwoot.importMessages && + messagesRaw.length > 0 + ) { + this.chatwootService.addHistoryMessages( + instance, + messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), ); + } - contacts = undefined; - messages = undefined; - chats = undefined; - } catch (error) { - this.logger.error(error); + const filteredContacts = contacts.filter((c) => !!c.notify || !!c.name); + if (hasProgress) { + this.historySyncContactCount += filteredContacts.length; } + + if (hasProgress && progress === 100) { + this.sendDataWebhook(Events.MESSAGING_HISTORY_SET, { + messageCount: this.historySyncMessageCount, + chatCount: this.historySyncChatCount, + contactCount: this.historySyncContactCount, + progress, + }); + + this.historySyncMessageCount = 0; + this.historySyncChatCount = 0; + this.historySyncContactCount = 0; + this.historySyncLastProgress = -1; + } + + await this.contactHandle['contacts.upsert']( + filteredContacts.map((c) => ({ id: c.id, name: c.name ?? c.notify })), + ); + + contacts = undefined; + messages = undefined; + chats = undefined; + } catch (error) { + this.logger.error(error); + } + } + + private readonly messageHandle = { + 'messaging-history.set': (payload: { + chats: Chat[]; + contacts: Contact[]; + messages: WAMessage[]; + isLatest?: boolean; + progress?: number; + syncType?: proto.HistorySync.HistorySyncType; + }) => { + return this.enqueueHistory(() => this.handleHistorySet(payload)); }, 'messages.upsert': async ( @@ -1363,6 +1519,10 @@ export class BaileysStartupService extends ChannelStartupService { continue; } + if (received.message?.messageHistoryBundle && isJidGroup(received.key?.remoteJid)) { + void this.processGroupHistoryBundle(received); + } + const existingChat = await this.prismaRepository.chat.findFirst({ where: { instanceId: this.instanceId, remoteJid: received.key.remoteJid }, select: { id: true, name: true }, diff --git a/src/utils/groupHistoryBundle.ts b/src/utils/groupHistoryBundle.ts new file mode 100644 index 0000000000..3a19e48aff --- /dev/null +++ b/src/utils/groupHistoryBundle.ts @@ -0,0 +1,215 @@ +import { createDecipheriv, createHash, createHmac, hkdfSync, timingSafeEqual } from 'node:crypto'; +import { inflateSync } from 'node:zlib'; + +import { proto } from 'baileys'; + +export const GROUP_HISTORY_DOWNLOAD_TIMEOUT_MS = 30_000; +export const GROUP_HISTORY_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024; +export const GROUP_HISTORY_MAX_INFLATE_BYTES = 20 * 1024 * 1024; +export const GROUP_HISTORY_MAX_ENTRIES = 50_000; + +const GROUP_HISTORY_HKDF_INFO = Buffer.from('Group History'); +const HKDF_OUTPUT_LENGTH = 112; +const MAC_LENGTH = 10; +const AES_BLOCK_SIZE = 16; +const TOP_LEVEL_MESSAGE_FIELDS = new Set([1, 3, 4, 5]); +const ASSOCIATED_MESSAGE_LISTS_FIELD = 2; +const NESTED_MESSAGE_FIELDS = new Set([1]); + +function readVarint(buf: Buffer, offset: number): { value: number; nextOffset: number } { + let result = 0; + let multiplier = 1; + + for (let i = 0; i < 10; i++) { + if (offset + i >= buf.length) { + throw new Error('Malformed GroupHistory protobuf: truncated varint'); + } + + const byte = buf[offset + i]; + if (i === 9 && byte > 1) { + throw new Error('Malformed GroupHistory protobuf: varint overflow'); + } + + result += (byte & 0x7f) * multiplier; + if (!Number.isSafeInteger(result)) { + throw new Error('Malformed GroupHistory protobuf: varint exceeds safe integer'); + } + + if ((byte & 0x80) === 0) { + return { value: result, nextOffset: offset + i + 1 }; + } + + multiplier *= 128; + } + + throw new Error('Malformed GroupHistory protobuf: varint too long'); +} + +function skipVarint(buf: Buffer, offset: number): number { + for (let i = 0; i < 10; i++) { + if (offset + i >= buf.length) { + throw new Error('Malformed GroupHistory protobuf: truncated varint'); + } + if ((buf[offset + i] & 0x80) === 0) { + return offset + i + 1; + } + } + + throw new Error('Malformed GroupHistory protobuf: varint too long'); +} + +function parseFields( + buf: Buffer, + entries: proto.IWebMessageInfo[], + messageFields: ReadonlySet, + nestedField?: number, +): void { + let offset = 0; + + while (offset < buf.length) { + const tagRes = readVarint(buf, offset); + const tag = tagRes.value; + offset = tagRes.nextOffset; + + if (tag === 0 || tag > 0xffffffff) { + throw new Error(`Malformed GroupHistory protobuf: invalid tag ${tag}`); + } + + const fieldNumber = tag >>> 3; + const wireType = tag & 0x7; + + if (fieldNumber === 0) { + throw new Error('Malformed GroupHistory protobuf: field number 0'); + } + + if (messageFields.has(fieldNumber)) { + if (wireType !== 2) { + const scope = nestedField === undefined ? ' (nested)' : ''; + throw new Error( + `Malformed GroupHistory protobuf: unexpected wire type ${wireType} for field ${fieldNumber}${scope}`, + ); + } + + if (entries.length >= GROUP_HISTORY_MAX_ENTRIES) { + throw new Error('Malformed GroupHistory protobuf: too many entries'); + } + + const lenRes = readVarint(buf, offset); + const len = lenRes.value; + offset = lenRes.nextOffset; + + if (len > buf.length - offset) { + throw new Error(`Malformed GroupHistory protobuf: truncated field ${fieldNumber} payload`); + } + + const slice = buf.subarray(offset, offset + len); + offset += len; + entries.push(proto.WebMessageInfo.decode(slice)); + continue; + } + + if (nestedField !== undefined && fieldNumber === nestedField) { + if (wireType !== 2) { + throw new Error(`Malformed GroupHistory protobuf: unexpected wire type ${wireType} for field ${fieldNumber}`); + } + + const lenRes = readVarint(buf, offset); + const len = lenRes.value; + offset = lenRes.nextOffset; + + if (len > buf.length - offset) { + throw new Error(`Malformed GroupHistory protobuf: truncated field ${fieldNumber} payload`); + } + + const slice = buf.subarray(offset, offset + len); + offset += len; + parseFields(slice, entries, NESTED_MESSAGE_FIELDS); + continue; + } + + switch (wireType) { + case 0: + offset = skipVarint(buf, offset); + break; + case 1: + if (offset + 8 > buf.length) { + throw new Error('Malformed GroupHistory protobuf: truncated 64-bit field'); + } + offset += 8; + break; + case 2: { + const lenRes = readVarint(buf, offset); + const len = lenRes.value; + offset = lenRes.nextOffset; + if (len > buf.length - offset) { + throw new Error('Malformed GroupHistory protobuf: truncated length-delimited field'); + } + offset += len; + break; + } + case 5: + if (offset + 4 > buf.length) { + throw new Error('Malformed GroupHistory protobuf: truncated 32-bit field'); + } + offset += 4; + break; + default: + throw new Error(`Malformed GroupHistory protobuf: unsupported wire type ${wireType}`); + } + } +} + +function parseGroupHistory(buf: Buffer): proto.IWebMessageInfo[] { + const entries: proto.IWebMessageInfo[] = []; + parseFields(buf, entries, TOP_LEVEL_MESSAGE_FIELDS, ASSOCIATED_MESSAGE_LISTS_FIELD); + return entries; +} + +export function decryptGroupHistoryBundle( + file: Buffer, + mediaKey: Uint8Array, + fileEncSha256?: Uint8Array | null, +): proto.IWebMessageInfo[] { + if (!mediaKey || mediaKey.length !== 32) { + throw new Error(`Invalid GroupHistory mediaKey length: expected 32, got ${mediaKey?.length ?? 0}`); + } + + if ( + !Buffer.isBuffer(file) || + file.length < AES_BLOCK_SIZE + MAC_LENGTH || + (file.length - MAC_LENGTH) % AES_BLOCK_SIZE !== 0 + ) { + throw new Error(`Invalid GroupHistory encrypted file length: ${file?.length ?? 0}`); + } + + if (fileEncSha256 != null) { + if (fileEncSha256.length !== 32) { + throw new Error(`Invalid GroupHistory fileEncSha256 length: expected 32, got ${fileEncSha256.length}`); + } + const actualSha256 = createHash('sha256').update(file).digest(); + if (!timingSafeEqual(actualSha256, fileEncSha256)) { + throw new Error('GroupHistory bundle fileEncSha256 mismatch'); + } + } + + const expandedKey = Buffer.from( + hkdfSync('sha256', mediaKey, Buffer.alloc(0), GROUP_HISTORY_HKDF_INFO, HKDF_OUTPUT_LENGTH), + ); + const iv = expandedKey.subarray(0, 16); + const cipherKey = expandedKey.subarray(16, 48); + const macKey = expandedKey.subarray(48, 80); + + const ciphertext = file.subarray(0, file.length - MAC_LENGTH); + const mac10 = file.subarray(file.length - MAC_LENGTH); + const expectedMac10 = createHmac('sha256', macKey).update(iv).update(ciphertext).digest().subarray(0, MAC_LENGTH); + + if (!timingSafeEqual(expectedMac10, mac10)) { + throw new Error('GroupHistory bundle MAC mismatch'); + } + + const decipher = createDecipheriv('aes-256-cbc', cipherKey, iv); + const compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); + const plaintext = inflateSync(compressed, { maxOutputLength: GROUP_HISTORY_MAX_INFLATE_BYTES }); + + return parseGroupHistory(plaintext); +} diff --git a/test/group-history-bundle.test.ts b/test/group-history-bundle.test.ts new file mode 100644 index 0000000000..98cfd57767 --- /dev/null +++ b/test/group-history-bundle.test.ts @@ -0,0 +1,250 @@ +import assert from 'node:assert/strict'; +import { createCipheriv, createHash, createHmac, hkdfSync, randomBytes } from 'node:crypto'; +import { describe, it } from 'node:test'; +import { deflateSync } from 'node:zlib'; + +import { decryptGroupHistoryBundle, GROUP_HISTORY_MAX_ENTRIES } from '@utils/groupHistoryBundle'; +import { proto } from 'baileys'; + +function encodeVarint(value: number): Buffer { + const bytes: number[] = []; + let v = value >>> 0; + while (v >= 0x80) { + bytes.push((v & 0x7f) | 0x80); + v >>>= 7; + } + bytes.push(v); + return Buffer.from(bytes); +} + +function encodeLengthDelimitedField(fieldNumber: number, payload: Uint8Array): Buffer { + const tag = encodeVarint((fieldNumber << 3) | 2); + const len = encodeVarint(payload.length); + return Buffer.concat([tag, len, Buffer.from(payload)]); +} + +function encryptBundle(plaintext: Buffer, mediaKey: Uint8Array): { file: Buffer; fileEncSha256: Buffer } { + const compressed = deflateSync(plaintext); + const expanded = Buffer.from(hkdfSync('sha256', mediaKey, Buffer.alloc(0), Buffer.from('Group History'), 112)); + const iv = expanded.subarray(0, 16); + const cipherKey = expanded.subarray(16, 48); + const macKey = expanded.subarray(48, 80); + + const cipher = createCipheriv('aes-256-cbc', cipherKey, iv); + const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); + const mac10 = createHmac('sha256', macKey).update(iv).update(ciphertext).digest().subarray(0, 10); + + const file = Buffer.concat([ciphertext, mac10]); + const fileEncSha256 = createHash('sha256').update(file).digest(); + return { file, fileEncSha256 }; +} + +function buildSampleMessages(): proto.IWebMessageInfo[] { + return [ + { + key: { + id: 'MSG_1', + participant: '1234567890@lid', + fromMe: false, + }, + messageTimestamp: 1700000001, + message: { conversation: 'Hello from group history 1' }, + }, + { + key: { + id: 'MSG_2', + participant: '9876543210@lid', + fromMe: false, + }, + messageTimestamp: 1700000002, + message: { extendedTextMessage: { text: 'Hello from group history 2' } }, + }, + { + key: { + id: 'MSG_3', + participant: '5555555555@lid', + fromMe: true, + }, + messageTimestamp: 1700000003, + message: { conversation: 'Third message' }, + }, + ]; +} + +function buildValidPlaintextWithUnknownFields(messages: proto.IWebMessageInfo[]): Buffer { + const chunks: Buffer[] = []; + // Field 6, wire type 0 (varint) + chunks.push(encodeVarint((6 << 3) | 0), encodeVarint(42)); + // Field 7, wire type 1 (64-bit) + chunks.push(encodeVarint((7 << 3) | 1), Buffer.alloc(8, 0xaa)); + + for (const msg of messages) { + const encoded = proto.WebMessageInfo.encode(msg).finish(); + chunks.push(encodeLengthDelimitedField(1, encoded)); + } + + // Field 8, wire type 2 (length-delimited) + const extra = Buffer.from('extra-meta'); + chunks.push(encodeVarint((8 << 3) | 2), encodeVarint(extra.length), extra); + // Field 9, wire type 5 (32-bit) + chunks.push(encodeVarint((9 << 3) | 5), Buffer.alloc(4, 0x55)); + + return Buffer.concat(chunks); +} + +describe('decryptGroupHistoryBundle', () => { + it('1. round-trip decodes entries and skips unknown wire types 0/1/2/5', () => { + const mediaKey = randomBytes(32); + const sampleMessages = buildSampleMessages(); + const plaintext = buildValidPlaintextWithUnknownFields(sampleMessages); + const { file, fileEncSha256 } = encryptBundle(plaintext, mediaKey); + + const decoded = decryptGroupHistoryBundle(file, mediaKey, fileEncSha256); + + assert.equal(decoded.length, 3); + assert.equal(decoded[0].key?.id, 'MSG_1'); + assert.equal(decoded[0].key?.participant, '1234567890@lid'); + assert.equal(Number(decoded[0].messageTimestamp), 1700000001); + assert.equal(decoded[0].message?.conversation, 'Hello from group history 1'); + + assert.equal(decoded[1].key?.id, 'MSG_2'); + assert.equal(decoded[1].message?.extendedTextMessage?.text, 'Hello from group history 2'); + + assert.equal(decoded[2].key?.id, 'MSG_3'); + assert.equal(decoded[2].key?.fromMe, true); + }); + + it('2. throws on MAC mismatch', () => { + const mediaKey = randomBytes(32); + const plaintext = buildValidPlaintextWithUnknownFields(buildSampleMessages()); + const { file } = encryptBundle(plaintext, mediaKey); + + const tampered = Buffer.from(file); + tampered[tampered.length - 1] ^= 0x01; + + assert.throws(() => decryptGroupHistoryBundle(tampered, mediaKey), /MAC mismatch/i); + }); + + it('3. throws on fileEncSha256 mismatch and succeeds when omitted', () => { + const mediaKey = randomBytes(32); + const plaintext = buildValidPlaintextWithUnknownFields(buildSampleMessages()); + const { file, fileEncSha256 } = encryptBundle(plaintext, mediaKey); + + const badSha = Buffer.from(fileEncSha256); + badSha[0] ^= 0xff; + + assert.throws(() => decryptGroupHistoryBundle(file, mediaKey, badSha), /fileEncSha256 mismatch/i); + + const decodedWithoutSha = decryptGroupHistoryBundle(file, mediaKey, null); + assert.equal(decodedWithoutSha.length, 3); + }); + + it('4. throws on invalid mediaKey length', () => { + const mediaKey = randomBytes(16); + assert.throws(() => decryptGroupHistoryBundle(Buffer.alloc(32), mediaKey), /mediaKey length/i); + }); + + it('5. throws on malformed protobuf (truncation, bad field-1 wire type, unsupported wire types)', () => { + const mediaKey = randomBytes(32); + + // 5a: truncated field 1 payload + const truncated = Buffer.concat([encodeVarint((1 << 3) | 2), encodeVarint(100), Buffer.from([1, 2, 3])]); + const encTruncated = encryptBundle(truncated, mediaKey); + assert.throws( + () => decryptGroupHistoryBundle(encTruncated.file, mediaKey, encTruncated.fileEncSha256), + /truncated/i, + ); + + // 5b: wrong wire type (0) for field 1 + const badWire1 = Buffer.concat([encodeVarint((1 << 3) | 0), encodeVarint(1)]); + const encBadWire1 = encryptBundle(badWire1, mediaKey); + assert.throws( + () => decryptGroupHistoryBundle(encBadWire1.file, mediaKey, encBadWire1.fileEncSha256), + /unexpected wire type/i, + ); + + // 5b-2: wrong wire type (0) for top-level field 3 + const badWire3 = Buffer.concat([encodeVarint((3 << 3) | 0), encodeVarint(1)]); + const encBadWire3 = encryptBundle(badWire3, mediaKey); + assert.throws( + () => decryptGroupHistoryBundle(encBadWire3.file, mediaKey, encBadWire3.fileEncSha256), + /unexpected wire type/i, + ); + + // 5b-3: wrong wire type (0) for nested field 1 inside field 2 + const badWireNested1 = encodeLengthDelimitedField(2, Buffer.concat([encodeVarint((1 << 3) | 0), encodeVarint(1)])); + const encBadWireNested1 = encryptBundle(badWireNested1, mediaKey); + assert.throws( + () => decryptGroupHistoryBundle(encBadWireNested1.file, mediaKey, encBadWireNested1.fileEncSha256), + /unexpected wire type/i, + ); + + // 5c: unsupported wire type 3 (start group) and wire type 6 + for (const wt of [3, 6, 7]) { + const unsupported = encodeVarint((6 << 3) | wt); + const encUnsupported = encryptBundle(unsupported, mediaKey); + assert.throws( + () => decryptGroupHistoryBundle(encUnsupported.file, mediaKey, encUnsupported.fileEncSha256), + /unsupported wire type/i, + ); + } + }); + + it('6. throws when entry count exceeds GROUP_HISTORY_MAX_ENTRIES', () => { + const mediaKey = randomBytes(32); + const plaintext = Buffer.alloc((GROUP_HISTORY_MAX_ENTRIES + 1) * 2, Buffer.from([0x0a, 0x00])); + const { file, fileEncSha256 } = encryptBundle(plaintext, mediaKey); + + assert.throws( + () => decryptGroupHistoryBundle(file, mediaKey, fileEncSha256), + /Malformed GroupHistory protobuf: too many entries/, + ); + }); + + it('7. decodes all five GroupHistory message fields in wire order and skips nested unknown fields', () => { + const mediaKey = randomBytes(32); + const encodeMsg = (id: string) => + proto.WebMessageInfo.encode({ + key: { id, participant: '1234567890@lid', fromMe: false }, + messageTimestamp: 1700000010, + message: { conversation: id }, + }).finish(); + + const associatedList = Buffer.concat([ + encodeLengthDelimitedField(1, encodeMsg('MSG_F2_A')), + // Skipped submessage field 2 (varint) and field 3 (length-delimited) + encodeVarint((2 << 3) | 0), + encodeVarint(99), + encodeLengthDelimitedField(3, Buffer.from('nested-skip')), + encodeLengthDelimitedField(1, encodeMsg('MSG_F2_B')), + ]); + + const plaintext = Buffer.concat([ + encodeLengthDelimitedField(1, encodeMsg('MSG_F1')), + encodeLengthDelimitedField(2, associatedList), + encodeLengthDelimitedField(3, encodeMsg('MSG_F3')), + encodeLengthDelimitedField(4, encodeMsg('MSG_F4')), + encodeLengthDelimitedField(5, encodeMsg('MSG_F5')), + ]); + + const { file, fileEncSha256 } = encryptBundle(plaintext, mediaKey); + const decoded = decryptGroupHistoryBundle(file, mediaKey, fileEncSha256); + + assert.deepEqual( + decoded.map((m) => m.key?.id), + ['MSG_F1', 'MSG_F2_A', 'MSG_F2_B', 'MSG_F3', 'MSG_F4', 'MSG_F5'], + ); + }); + + it('8. enforces GROUP_HISTORY_MAX_ENTRIES across nested field-2 messages', () => { + const mediaKey = randomBytes(32); + const nestedEntries = Buffer.alloc((GROUP_HISTORY_MAX_ENTRIES + 1) * 2, Buffer.from([0x0a, 0x00])); + const plaintext = encodeLengthDelimitedField(2, nestedEntries); + const { file, fileEncSha256 } = encryptBundle(plaintext, mediaKey); + + assert.throws( + () => decryptGroupHistoryBundle(file, mediaKey, fileEncSha256), + /Malformed GroupHistory protobuf: too many entries/, + ); + }); +});