Repository navigation
feat(baileys): decrypt group history bundles - #2808
opropriokratos wants to merge 4 commits into
Conversation
When an admin adds the instance to a group with "share recent messages" on, WhatsApp delivers a messageHistoryBundle. Download and decrypt it (HKDF-SHA256 "Group History", AES-256-CBC, HMAC-SHA256 truncated MAC, zlib), parse the GroupHistory protobuf and deliver the contained messages through the existing messaging-history.set handler, so they follow the history rules (SAVE_DATA.HISTORIC, MESSAGES_SET) and never reach chatbots. History sync counters are only touched when a progress value is present, and accepted message ids are added to the dedupe set so re-delivered bundles are not duplicated.
Reviewer's GuideImplementationImplement bounded, integrity-checked decryption and parsing of GroupHistory bundles, including all supported message fields.
Integrate group bundle downloads and decoded messages with serialized history-sync processing, while preserving deduplication and progress-accounting behavior.
TestsExercise bundle decryption, integrity checks, protobuf parsing, and entry-count limits with encrypted test fixtures.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1126" />
<code_context>
+ continue;
+ }
+
+ entry.key.remoteJid = groupJid;
+ entry.messageTimestamp = ts;
+ messages.push(entry as WAMessage);
</code_context>
<issue_to_address>
**Bundle entries can impersonate group members**
When a group participant sends a crafted `messageHistoryBundle` with entries attributed to another participant or the instance, a group participant who can submit a crafted bundle can choose its media key and produce a matching MAC, then place arbitrary `participant` and `fromMe` values in decoded entries. `processGroupHistoryBundle` checks only the group JID and forwards those entries to persistence and `MESSAGES_SET`, so consumers see forged historical messages attributed to other senders or the instance.
Validate each entry's author and `fromMe` status against trusted bundle provenance, or reject bundle entries whose authorship cannot be authenticated independently of the sender-supplied media key.
</issue_to_address>
### Comment 2
<location path="src/utils/groupHistoryBundle.ts" line_range="92" />
<code_context>
+
+ const slice = buf.subarray(offset, offset + len);
+ offset += len;
+ entries.push(proto.WebMessageInfo.decode(slice));
+ continue;
+ }
</code_context>
<issue_to_address>
**Bundle parsing can exhaust memory**
When a received group bundle contains a very large number of small field-1 records, a valid bundle can contain millions of tiny field-1 entries within the 20 MB inflate limit; `parseGroupHistory` decodes and retains every entry before the caller filters them, allowing a group participant who can submit bundles to drive large heap growth and crash the instance.
Enforce a strict maximum decoded-entry count (and preferably a per-instance in-flight limit) before retaining or processing bundle entries.
Also at `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1483`.
</issue_to_address>
### Comment 3
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1483" />
<code_context>
}
+ if (received.message?.messageHistoryBundle && isJidGroup(received.key?.remoteJid)) {
+ void this.processGroupHistoryBundle(received);
+ }
+
</code_context>
<issue_to_address>
**Concurrent bundles exhaust memory**
When multiple group bundles are delivered before earlier downloads and decryptions finish, each detached task can hold a downloaded bundle, its inflated plaintext, and decoded message objects at once; the 20 MB limits apply per bundle, not across tasks. A burst of concurrent bundles can therefore exhaust the process heap and disconnect the instance service.
Limit concurrent bundle processing per instance or globally, and queue excess work.
</issue_to_address>
### Comment 4
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1327" />
<code_context>
messagesRaw.push(this.prepareMessage(m));
+ messagesRepository.add(m.key.id);
+ cachedRepositoryMessages?.add(m.key.id);
}
</code_context>
<issue_to_address>
**Failed history writes lose messages**
When `message.createMany` fails after IDs are added to the repository-message cache, the history handler leaves those IDs cached, so a later delivery skips messages that were never persisted or emitted.
Add IDs to the repository-message cache only after `message.createMany` succeeds, or remove them if the write fails.
</issue_to_address>
### Comment 5
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1483" />
<code_context>
}
+ if (received.message?.messageHistoryBundle && isJidGroup(received.key?.remoteJid)) {
+ void this.processGroupHistoryBundle(received);
+ }
+
</code_context>
<issue_to_address>
**Overlapping history processing duplicates messages**
When a bundle and another history handler overlap before their deduplication sets are shared or updated, concurrent `processGroupHistoryBundle` and history-sync handlers can build or read separate sets of stored IDs, then both accept the same messages in `messaging-history.set`; duplicate rows and `MESSAGES_SET` emissions reach users.
Serialize history processing or use an atomic shared deduplication mechanism so overlapping handlers cannot accept the same message IDs.
Also at `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1293`, `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1327`.
</issue_to_address>
### Comment 6
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1483" />
<code_context>
}
+ if (received.message?.messageHistoryBundle && isJidGroup(received.key?.remoteJid)) {
+ void this.processGroupHistoryBundle(received);
+ }
+
</code_context>
<issue_to_address>
**Failed bundle downloads are not retried**
When a bundle download or decryption fails temporarily and WhatsApp does not redeliver it, `processGroupHistoryBundle` catches the error, while the upsert caller launches it with `void`; the failure never reaches the message processor's retry path, leaving the bundle's history unprocessed.
Await `processGroupHistoryBundle` from the caller and let failures propagate to the retry mechanism.
Also at `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1141`.
</issue_to_address>
### Comment 7
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1483" />
<code_context>
}
+ if (received.message?.messageHistoryBundle && isJidGroup(received.key?.remoteJid)) {
+ void this.processGroupHistoryBundle(received);
+ }
+
</code_context>
<issue_to_address>
**Pending bundle writes after logout**
When the instance is logged out while the bundle download is still in flight, the detached bundle task continues after logout and calls `messaging-history.set` without checking `endSession`. It can therefore persist and emit historical messages after the instance has been logged out.
Track and cancel pending bundle tasks on logout, or check the instance lifecycle state before dispatching the decoded messages.
</issue_to_address>
### Comment 8
<location path="src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts" line_range="1073" />
<code_context>
+ }
+
+ const url = getUrlFromDirectPath(bundle.directPath);
+ const config: Record<string, any> = {
+ responseType: 'arraybuffer',
+ timeout: GROUP_HISTORY_DOWNLOAD_TIMEOUT_MS,
</code_context>
<issue_to_address>
**Download options lose type safety**
`config` uses `Record<string, any>`, so TypeScript cannot check the types of the Axios download options and invalid option values can reach the request at runtime.
Use Axios's request-config type for `config` instead of `any`.
</issue_to_address>
### Comment 9
<location path="src/utils/groupHistoryBundle.ts" line_range="131" />
<code_context>
+}
+
+export function decryptGroupHistoryBundle(
+ file: Buffer,
+ mediaKey: Uint8Array,
+ fileEncSha256?: Uint8Array | null,
</code_context>
<issue_to_address>
**Utility failures skip local logging**
`decryptGroupHistoryBundle` throws on validation, decryption, and parsing failures without logging them; callers that use the utility directly therefore receive no utility-level failure context.
Add the utility's standard logger and catch failures to log and rethrow them, or revise the utility guidance for intentionally pure helpers.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and a faulty decrypt or bundle parser could insert incorrect historical messages into the database; reverting stops future imports but leaves those rows behind. The affected imports are bounded to each downloaded bundle and can be removed or re-imported.
Blocking findings: src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1126, src/utils/groupHistoryBundle.ts:92, src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1483, src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1327, src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1483, and 2 more
| continue; | ||
| } | ||
|
|
||
| entry.key.remoteJid = groupJid; |
There was a problem hiding this comment.
🟡 Medium · Bundle entries can impersonate group members
When a group participant sends a crafted messageHistoryBundle with entries attributed to another participant or the instance, a group participant who can submit a crafted bundle can choose its media key and produce a matching MAC, then place arbitrary participant and fromMe values in decoded entries. processGroupHistoryBundle checks only the group JID and forwards those entries to persistence and MESSAGES_SET, so consumers see forged historical messages attributed to other senders or the instance.
Validate each entry's author and fromMe status against trusted bundle provenance, or reject bundle entries whose authorship cannot be authenticated independently of the sender-supplied media key.
Prompt for AI agents
In `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts` at line 1126:
**Bundle entries can impersonate group members**
When a group participant sends a crafted `messageHistoryBundle` with entries attributed to another participant or the instance, a group participant who can submit a crafted bundle can choose its media key and produce a matching MAC, then place arbitrary `participant` and `fromMe` values in decoded entries. `processGroupHistoryBundle` checks only the group JID and forwards those entries to persistence and `MESSAGES_SET`, so consumers see forged historical messages attributed to other senders or the instance.
Validate each entry's author and `fromMe` status against trusted bundle provenance, or reject bundle entries whose authorship cannot be authenticated independently of the sender-supplied media key.There was a problem hiding this comment.
Good catch, and partly addressed in ccbea44. Unlike regular group messages, bundle entries carry no per-sender signature: they are authenticated only by the bundle's media key, which the sending participant controls. So authorship of individual entries can't be verified on our side.
What we can block cheaply is the most harmful case: entries marked fromMe: true are now dropped unless the bundle itself was sent by this instance, so a participant can't forge messages "from" the instance. Attribution to other participants stays as delivered by the bundle sender.
- cap GroupHistory entries at GROUP_HISTORY_MAX_ENTRIES (50k) before decoding - serialize bundle processing and messaging-history.set per instance through a history queue - add message ids to the repository/chatwoot caches only after persistence - skip dispatch when the session ended or the instance is being deleted - type the download config as AxiosRequestConfig - drop bundle entries claiming fromMe when the bundle was not sent by this instance Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
📋 Description
When a group admin adds the instance's number with "share recent messages" enabled, WhatsApp delivers a
messageHistoryBundlemessage. Today Evolution stores/emits only that pointer, so the shared history is never readable by users.This PR downloads and decrypts the bundle and delivers the contained messages through the existing history-sync path (
messaging-history.set), so they follow exactly the same rules as regular history sync.Recipe (verified against a real bundle, Nov 2026):
messageHistoryBundle.mediaKey(32 bytes).Group History, 112 bytes →iv = [0:16],cipherKey = [16:48],macKey = [48:80].https://mmg.whatsapp.net+directPath;sha256(file) == fileEncSha256;file = ciphertext || mac10, wheremac10= first 10 bytes ofHMAC-SHA256(macKey, iv || ciphertext).GroupHistoryprotobuf whose field 1 isrepeated WebMessageInfo. WAProto has noGroupHistorytype, so field 1 is read with a small bounds-checked parser and each entry is decoded withproto.WebMessageInfo.decode.Changes:
src/utils/groupHistoryBundle.ts(new): puredecryptGroupHistoryBundle(file, mediaKey, fileEncSha256)using onlynode:crypto/node:zliband Baileys'proto. Verifies SHA-256 and MAC (constant time) before decrypting, caps inflate output (20 MB), rejects malformed protobuf. No new dependency, no Baileys patch.whatsapp.baileys.service.ts:messages.upsert, after the existinggroupsIgnorecheck, a groupmessageHistoryBundlestartsprocessGroupHistoryBundlein the background (not awaited); the bundle message itself keeps its current handling.processGroupHistoryBundlevalidatesmediaKey/directPath, downloads with timeout, size cap and the instance proxy (same pattern as other downloads), decrypts, keeps only entries that have an id, content and timestamp and belong to the same group (a bundle cannot inject messages into other chats), then callsmessaging-history.setwith them. All errors are caught and logged (ids/counts only, no content).messaging-history.set: progress counters andMESSAGING_HISTORY_SETare only updated when a numericprogressis present, so a bundle does not reset the counters of a concurrent history sync; accepted ids are added to the dedupe set so re-delivered bundles (e.g. offlineappend) are not duplicated.Delivery and gating: messages are emitted as
MESSAGES_SETand saved only whenDATABASE_SAVE_DATA_HISTORICis enabled, same as history sync. Chatbots/integrations are not triggered for these old messages (messaging-history.setnever calls the chatbot controller; Chatwoot history import already ignores groups). Instances withgroupsIgnoredo not process bundles. Media inside the historical messages keep their ownmediaKey/directPathand can be downloaded with the existing media endpoints.Complementary to WhiskeySockets/Baileys#2936 (native support in Baileys). This PR does not depend on it.
🔗 Related Issue
N/A
🧪 Type of Change
🧪 Testing
Manual testing completed
Functionality verified in development environment
No breaking changes introduced (see note on history-sync counters below)
Tested with different connection types (if applicable)
The decryption recipe was verified end to end on a real bundle (Nov 2026): SHA-256 and MAC matched, and the number of decoded entries matched
messageHistoryMetadata.messageCount.Synthetic self-check with
node:test(bundle encrypted with the same primitives, random key): round trip, MAC mismatch,fileEncSha256mismatch, invalid key length, malformed protobuf — 5/5 passing. The repo ignores/test/, so the file is not part of this PR; happy to add it wherever you prefer.npm run lint:checkandnpm run buildpass.Not yet exercised against a live instance: the download, the
messages.upsertintegration and persistence were not tested end to end; only the decryption (real and synthetic bundles).📸 Screenshots (if applicable)
N/A
✅ Checklist
📝 Additional Notes
patches/.messaging-history.set, chunks without a numericprogressno longer reset or advance the progress counters, so they are not counted inMESSAGING_HISTORY_SET. Happy to restrict this to bundle deliveries only if you prefer.Drafted with an AI assistant, reviewed and tested by me.
Summary by Sourcery
Enable secure ingestion of WhatsApp shared group history while preserving existing history-sync, persistence, deduplication, and delivery behavior.
New Features:
Bug Fixes:
Enhancements:
Tests: