Skip to content

feat(baileys): decrypt group history bundles - #2808

Open
opropriokratos wants to merge 4 commits into
evolution-foundation:developfrom
opropriokratos:feat/group-history-bundle
Open

opropriokratos wants to merge 4 commits into
evolution-foundation:developfrom
opropriokratos:feat/group-history-bundle

Conversation

@opropriokratos

@opropriokratos opropriokratos commented Nov 27, 2026 •

Copy link
Copy Markdown

📋 Description

When a group admin adds the instance's number with "share recent messages" enabled, WhatsApp delivers a messageHistoryBundle message. 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):

  • Key material: messageHistoryBundle.mediaKey (32 bytes).
  • HKDF-SHA256, empty salt, info Group History, 112 bytes → iv = [0:16], cipherKey = [16:48], macKey = [48:80].
  • Download https://mmg.whatsapp.net + directPath; sha256(file) == fileEncSha256; file = ciphertext || mac10, where mac10 = first 10 bytes of HMAC-SHA256(macKey, iv || ciphertext).
  • AES-256-CBC (PKCS7) → zlib inflate → GroupHistory protobuf whose field 1 is repeated WebMessageInfo. WAProto has no GroupHistory type, so field 1 is read with a small bounds-checked parser and each entry is decoded with proto.WebMessageInfo.decode.

Changes:

  • src/utils/groupHistoryBundle.ts (new): pure decryptGroupHistoryBundle(file, mediaKey, fileEncSha256) using only node:crypto / node:zlib and 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:
    • In messages.upsert, after the existing groupsIgnore check, a group messageHistoryBundle starts processGroupHistoryBundle in the background (not awaited); the bundle message itself keeps its current handling.
    • processGroupHistoryBundle validates mediaKey/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 calls messaging-history.set with them. All errors are caught and logged (ids/counts only, no content).
    • messaging-history.set: progress counters and MESSAGING_HISTORY_SET are only updated when a numeric progress is 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. offline append) are not duplicated.

Delivery and gating: messages are emitted as MESSAGES_SET and saved only when DATABASE_SAVE_DATA_HISTORIC is enabled, same as history sync. Chatbots/integrations are not triggered for these old messages (messaging-history.set never calls the chatbot controller; Chatwoot history import already ignores groups). Instances with groupsIgnore do not process bundles. Media inside the historical messages keep their own mediaKey/directPath and 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

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧹 Code cleanup
  • 🔒 Security fix

🧪 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, fileEncSha256 mismatch, 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:check and npm run build pass.

  • Not yet exercised against a live instance: the download, the messages.upsert integration and persistence were not tested end to end; only the decryption (real and synthetic bundles).

📸 Screenshots (if applicable)

N/A

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

  • No new dependency and no change to patches/.
  • Behavior change: in messaging-history.set, chunks without a numeric progress no longer reset or advance the progress counters, so they are not counted in MESSAGING_HISTORY_SET. Happy to restrict this to bundle deliveries only if you prefer.
  • Limits: 30 s download timeout, 20 MB download cap, 20 MB inflate cap.

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:

  • Decrypt WhatsApp group history bundles and deliver their messages through the existing history-sync event path.

Bug Fixes:

  • Prevent group history bundle deliveries from corrupting concurrent history-sync progress and prevent duplicate historical messages from being reprocessed.

Enhancements:

  • Add validation, integrity checks, size limits, group scoping, and serialized processing for downloaded historical bundles.

Tests:

  • Add coverage for bundle decryption, integrity failures, malformed protobuf data, and entry limits.

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.
@sourcery-ai

sourcery-ai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Implement bounded, integrity-checked decryption and parsing of GroupHistory bundles, including all supported message fields.

  • src/utils/groupHistoryBundle.ts L1-215

Integrate group bundle downloads and decoded messages with serialized history-sync processing, while preserving deduplication and progress-accounting behavior.

  • src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts L88-92, L1049-1423, L1522-1525 (+3 small edits)

Tests

Exercise bundle decryption, integrity checks, protobuf parsing, and entry-count limits with encrypted test fixtures.

  • test/group-history-bundle.test.ts L1-250

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

continue;
}

entry.key.remoteJid = groupJid;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/utils/groupHistoryBundle.ts Resolved
Comment thread src/utils/groupHistoryBundle.ts Resolved
opropriokratos and others added 3 commits November 27, 2026 14:09
- 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>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant