Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): drop only known protocol noise on the live path

Yudhi Armyndharisa61fd29d17ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 039dae648..4d48c93ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,7 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- The Baileys live path drops contentless protocol traffic (sender-key distributions, message-history notices) instead of delivering it as a bodyless `unknown` `message.received`, matching what the history path already does ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
+- The Baileys live path drops a message made only of sender-key distributions or message-history notices instead of delivering it as a bodyless `unknown` `message.received`; other messages it cannot type still arrive as `unknown` ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
- A Baileys reconnect loop is observable: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics; a connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 39de30cb8..6913ecfe7 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -76,6 +76,18 @@ const PRESENCE_STATES: ReadonlySet<PresenceState> = new Set<PresenceState>([
'paused',
]);
+/**
+ * Top-level Message keys that carry no user content. A live message made only of these is dropped;
+ * messageContextInfo rides along on real content too, so on its own it is not enough to drop.
+ */
+const PROTOCOL_NOISE_KEYS: ReadonlySet<string> = new Set([
+ 'senderKeyDistributionMessage',
+ 'fastRatchetKeySenderKeyDistributionMessage',
+ 'messageContextInfo',
+ 'messageHistoryNotice',
+ 'messageHistoryBundle',
+]);
+
export interface BaileysEventsHost {
/** Live socket handle for media re-upload requests (inbound media download). */
getSocket(): WASocket;
@@ -304,14 +316,19 @@ export class BaileysEvents {
}
// --- contentless protocol traffic: don't emit onMessage ---
- // Baileys' getContentType only matches keys named `conversation` or containing `Message`, and
- // excludes senderKeyDistributionMessage BY NAME, so a sender-key distribution (Signal traffic
- // every group participant emits on first write or key rotation), a messageHistoryNotice or any
- // other suffix-less proto resolves here as contentType `undefined`, never as its own key.
- // These carry no user content yet reached consumers as bodyless `unknown` message.received
- // events (#1568). mapHistoryMessage drops exactly this set via its `!contentType` guard, and
- // emitOwnSendEcho has always skipped undefined the same way, so live inbound must agree.
- if (!contentType || contentType === 'senderKeyDistributionMessage') {
+ // A sender-key distribution (Signal traffic every group participant emits on first write or key
+ // rotation) or a history-sync notice carries no user content, yet reached consumers as a bodyless
+ // `unknown` message.received (#1568). Drop only a message made entirely of those keys. Anything
+ // else without a resolvable content type (a call log, a type newer than the bundled proto, which
+ // decodes to a lone messageContextInfo) still flows on as `unknown`, as it always has.
+ const keys = Object.keys(normalizedRoot ?? {});
+ if (keys.every(k => PROTOCOL_NOISE_KEYS.has(k)) && keys.some(k => k !== 'messageContextInfo')) {
+ this.host.logger.debug('Dropping contentless protocol message', {
+ action: 'baileys_drop_protocol_noise',
+ msgId: msg.key.id,
+ remoteJid,
+ keys,
+ });
return;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 6ba8257c5..fed98c772 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -175,6 +175,17 @@ function streamOf(...chunks: Buffer[]): AsyncIterable<Buffer> & { destroy: () =>
destroy: jest.fn(),
};
}
+/**
+ * Baileys 7.0.0-rc14 `getContentType` (lib/Utils/messages.js), copied because the library is
+ * ESM-only and mocked here: a key matches only when it is `conversation` or contains `Message`, and
+ * senderKeyDistributionMessage is excluded by name.
+ */
+function realGetContentType(content?: Record<string, unknown>): string | undefined {
+ return Object.keys(content ?? {}).find(
+ k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage',
+ );
+}
+
// sessionId (name) and dbSessionId (Session.id UUID) are deliberately distinct here so assertions
// below prove auth-dir/logging use the name while messageStore (FK-bound) uses the UUID.
const newAdapter = (): BaileysAdapter =>
@@ -2699,41 +2710,79 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(event.senderId).toBe('[email protected]'); // canonicalized to the neutral dialect
});
- it('senderKeyDistributionMessage: emits nothing and stores nothing (protocol noise the history path drops, #1568)', async () => {
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
- const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
- // Real baileys 7.x getContentType EXCLUDES senderKeyDistributionMessage by name and only matches
- // keys named `conversation` or containing `Message`, so an SKDM-only message resolves to
- // undefined, never to 'senderKeyDistributionMessage'. The mock must return the realistic value
- // or the test pins a code path production cannot reach.
- baileys.getContentType.mockReturnValue(undefined);
-
- const onMessage = jest.fn();
- const adapter = newAdapter();
- await adapter.initialize({ onMessage });
- fakeSock.fire('messages.upsert', {
- type: 'notify',
- messages: [
- {
- key: {
- remoteJid: '[email protected]',
- fromMe: false,
- id: 'SKDM1',
- participant: '[email protected]',
- },
- message: {
- senderKeyDistributionMessage: { axolotlSenderKeyDistributionMessage: 'R1NFMTIx...' },
+ describe('contentless protocol traffic on the live path (#1568)', () => {
+ /** Push one group message through the live upsert handler with Baileys' real content-type resolution. */
+ const fireLive = async (
+ id: string,
+ message: Record<string, unknown>,
+ ): Promise<{ onMessage: jest.Mock; debug: jest.SpyInstance }> => {
+ baileys.getContentType.mockImplementation(realGetContentType);
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { debug: (m: string, meta?: unknown) => void } }).logger;
+ const debug = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id, participant: '[email protected]' },
+ message,
+ messageTimestamp: 1700000025,
},
- messageTimestamp: 1700000025,
- },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ return { onMessage, debug };
+ };
+
+ // Signal and history-sync traffic with no user content: every top-level key is protocol noise.
+ it.each<[string, Record<string, unknown>]>([
+ ['a sender-key distribution', { senderKeyDistributionMessage: { groupId: '[email protected]' } }],
+ [
+ 'a sender-key distribution with its context info',
+ { senderKeyDistributionMessage: { groupId: '[email protected]' }, messageContextInfo: { messageSecret: 'cw==' } },
+ ],
+ [
+ 'a sender-key distribution with a message-history notice',
+ { senderKeyDistributionMessage: { groupId: '[email protected]' }, messageHistoryNotice: { contextInfo: {} } },
],
+ // The only noise key getContentType resolves to itself (it contains `Message` and is not excluded).
+ ['a fast-ratchet sender-key distribution', { fastRatchetKeySenderKeyDistributionMessage: { groupId: 'g' } }],
+ ['a message-history bundle', { messageHistoryBundle: { mimetype: 'application/octet-stream' } }],
+ ])('drops %s without emitting or storing it, and logs the drop', async (_label, message) => {
+ const { onMessage, debug } = await fireLive('NOISE1', message);
+ expect(onMessage).not.toHaveBeenCalled();
+ expect(fakeStore.put).not.toHaveBeenCalled();
+ expect(debug).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ msgId: 'NOISE1', remoteJid: '[email protected]', keys: Object.keys(message) }),
+ );
+ });
+
+ // No resolvable content type, yet not known noise: a call log (the proto's own `Messsage` spelling
+ // fails the `Message` match) or a lone messageContextInfo, which is what a content type newer than
+ // the bundled proto decodes to. These keep reaching consumers as `unknown`.
+ it.each<[string, Record<string, unknown>]>([
+ ['a call log', { callLogMesssage: { isVideo: false, callOutcome: 1, durationSecs: 12 } }],
+ ['a bare messageContextInfo', { messageContextInfo: { messageSecret: 'cw==' } }],
+ ])('emits and stores %s as unknown', async (_label, message) => {
+ const { onMessage } = await fireLive('UNK1', message);
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ expect((onMessage.mock.calls[0][0] as { type: string }).type).toBe('unknown');
+ expect(fakeStore.put).toHaveBeenCalledTimes(1);
+ });
+
+ it('emits a real message that arrives bundled with a sender-key distribution', async () => {
+ const { onMessage } = await fireLive('SKDM_TEXT', {
+ senderKeyDistributionMessage: { groupId: '[email protected]' },
+ conversation: 'hello group',
+ });
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ expect(onMessage.mock.calls[0][0]).toMatchObject({ type: 'text', body: 'hello group' });
});
- await new Promise(r => setImmediate(r));
- // A sender-key distribution is Signal protocol traffic every group participant emits on first
- // write or key rotation; it carries no user content. The history mapper already returns null
- // for it, so the live path must not deliver a bodyless `unknown` message.received either.
- expect(onMessage).not.toHaveBeenCalled();
- expect(fakeStore.put).not.toHaveBeenCalled();
});
it('learns the lid pair carried on a dropped sender-key distribution before dropping it (#1568)', async () => {