Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat: add STORE_EPHEMERAL_MESSAGES to skip persisting disappearing messages (#506)

spidgrou6cf1df7f5543
diff --git a/.env.example b/.env.example
index 7fe692eb0..bded9a9c1 100644
--- a/.env.example
+++ b/.env.example
@@ -201,6 +201,9 @@ WEBHOOK_SSRF_PROTECT=true
# # (no decryption, no memory allocation, no storage).
# # NOTE: disabling also makes hasMedia report false and removes the
# # media field from webhooks and the dashboard.
+# STORE_EPHEMERAL_MESSAGES=true # Set to false to skip persisting and dispatching incoming
+# # WhatsApp disappearing messages (ephemeralDuration > 0).
+# # Default: true (backward compatible — store everything).
# MEDIA_DOWNLOAD_MAX_BYTES=52428800 # cap remote-URL sends, inbound media, AND outbound base64 sends (default 50 MiB; oversized inbound media is dropped, message kept; oversized base64 is rejected with 400)
# MEDIA_DOWNLOAD_TIMEOUT_MS=30000 # abort a slow media download (default 30s)
# Storage import/export limits (ADMIN /infra/storage/* endpoints):
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9179feacf..2643171e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Configurable webhook worker concurrency** (`WEBHOOK_WORKER_CONCURRENCY`, default 10): a single slow or unresponsive receiver no longer head-of-line-blocks delivery for every other webhook. (#511)
- Dropped a redundant single-column index on `messages(sessionId)` already covered by the existing composite indexes, reducing write-time overhead on a high-volume table. (#509)
+- **Selective skip for disappearing messages.** New `STORE_EPHEMERAL_MESSAGES` env var (default `true`). Set to `false` to skip persisting and dispatching incoming disappearing messages (those with `ephemeralDuration > 0`) — no DB insert, no webhook dispatch, no websocket event. Backward compatible; existing deployments are unaffected. The `ephemeralDuration` field is also surfaced on `IncomingMessage` for consumers that want to handle it themselves. Thanks @spidgrou. (#506)
+
## [0.7.10] - 2026-06-28
### Added
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 67b3fe98d..966990601 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4512,6 +4512,8 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `session.disconnected` | The session disconnects | `{ sessionId, reason }` |
| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `failed` |
+> **`STORE_EPHEMERAL_MESSAGES=false` affects `message.received`.** When `STORE_EPHEMERAL_MESSAGES` is set to `false`, incoming disappearing messages (those with `ephemeralDuration > 0`) are **not** persisted nor dispatched — no DB insert, no webhook delivery, and no websocket event. Downstream consumers and the dashboard both stop seeing them. Default is `true` (backward compatible — store and dispatch everything).
+
> **Reserved but not emitted.** `group.join`, `group.leave`, and `group.update` are accepted in a webhook's `events` list (and have reserved idempotency-key formats), but **no code path currently emits them** — registering for them is harmless but they will never be delivered. Likewise there is **no** `contact.update` or `presence.update` event.
### Delivery semantics — at-least-once
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index 7c007f4ab..578fff837 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -126,4 +126,18 @@ describe('buildIncomingMessageFromBaileys', () => {
const r = buildIncomingMessageFromBaileys({ ...base, pushName: 'Alice' });
expect(r.contact).toEqual({ pushName: 'Alice' });
});
+
+ it('maps ephemeralDuration when present on the fields', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, ephemeralDuration: 604800 });
+ expect(r.ephemeralDuration).toBe(604800);
+ });
+
+ it('omits ephemeralDuration when absent from the fields', () => {
+ expect(buildIncomingMessageFromBaileys(base).ephemeralDuration).toBeUndefined();
+ });
+
+ it('omits ephemeralDuration when ephemeralDuration is 0', () => {
+ const r = buildIncomingMessageFromBaileys({ ...base, ephemeralDuration: 0 });
+ expect(r.ephemeralDuration).toBeUndefined();
+ });
});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index 6468c8861..dd11d5472 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -83,6 +83,8 @@ export interface BaileysIncomingFields {
location?: IncomingMessage['location'];
/** Pre-extracted quoted message context. Populated by the adapter when `contextInfo` is present. */
quotedMessage?: IncomingMessage['quotedMessage'];
+ /** Ephemeral/disappearing-messages timer from `contextInfo.expiration` on the Baileys message. */
+ ephemeralDuration?: number;
}
/**
@@ -143,5 +145,10 @@ export function buildIncomingMessageFromBaileys(
incoming.quotedMessage = fields.quotedMessage;
}
+ // Ephemeral/disappearing-messages timer, when the chat has one set.
+ if (fields.ephemeralDuration && fields.ephemeralDuration > 0) {
+ incoming.ephemeralDuration = fields.ephemeralDuration;
+ }
+
return incoming;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 024f4010f..d30da83e4 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -606,13 +606,19 @@ describe('BaileysAdapter messaging', () => {
describe('BaileysAdapter inbound fan-out', () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
- const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {
+ getContentType: jest.Mock;
+ normalizeMessageContent: jest.Mock;
+ };
beforeEach(() => {
fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
fakeSock.resetEmitter();
jest.clearAllMocks();
baileys.getContentType.mockReturnValue('conversation');
+ // clearAllMocks() wipes call history but keeps implementations, so a prior test's
+ // normalizeMessageContent override would leak into the next; reset it to the identity default.
+ baileys.normalizeMessageContent.mockImplementation((c: unknown) => c);
});
it('routes an inbound (not fromMe) message to onMessage with a neutral shape', async () => {
@@ -973,6 +979,44 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(msg.media.data).toBe(docBuf.toString('base64'));
});
+ it('extracts ephemeralDuration from an ephemeralMessage-wrapped inbound message (disappearing chat)', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {
+ getContentType: jest.Mock;
+ normalizeMessageContent: jest.Mock;
+ };
+ baileys.getContentType.mockReturnValue('extendedTextMessage');
+ // A live disappearing message arrives wrapped in `ephemeralMessage`; normalizeMessageContent unwraps
+ // it to the inner content carrying the timer on `contextInfo.expiration`. Reading the raw (wrapped)
+ // content would miss it — the exact case this guards.
+ baileys.normalizeMessageContent.mockReturnValue({
+ extendedTextMessage: { text: 'vanishes', contextInfo: { expiration: 86400 } },
+ });
+
+ 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: 'EPH1' },
+ message: {
+ ephemeralMessage: {
+ message: { extendedTextMessage: { text: 'vanishes', contextInfo: { expiration: 86400 } } },
+ },
+ },
+ messageTimestamp: 1700000040,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { ephemeralDuration?: number };
+ expect(msg.ephemeralDuration).toBe(86400);
+ });
+
it('inbound location: populates the location field with coordinates', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 5a990b07c..f31b0e4d8 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1127,19 +1127,30 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
}
- // --- quoted message ---
+ // --- quoted message + disappearing-messages timer ---
let quotedMessage: IncomingMessage['quotedMessage'];
+ // Read context off the NORMALIZED content: a live disappearing message arrives wrapped in
+ // `ephemeralMessage` (also viewOnce / documentWithCaption), whose inner content carries the
+ // contextInfo. The raw wrapper exposes none at top level, so both the quote and the timer
+ // (`contextInfo.expiration`) would be missed if we read the raw content here.
+ const normalizedForContext = b.normalizeMessageContent(content) ?? content;
const subForContext =
- content.extendedTextMessage ??
- content.imageMessage ??
- content.videoMessage ??
- content.audioMessage ??
- content.documentMessage ??
- content.stickerMessage ??
- content.locationMessage;
+ normalizedForContext.extendedTextMessage ??
+ normalizedForContext.imageMessage ??
+ normalizedForContext.videoMessage ??
+ normalizedForContext.audioMessage ??
+ normalizedForContext.documentMessage ??
+ normalizedForContext.stickerMessage ??
+ normalizedForContext.locationMessage;
const contextInfo = (
subForContext as
- | { contextInfo?: { stanzaId?: string | null; quotedMessage?: Record<string, unknown> | null } }
+ | {
+ contextInfo?: {
+ stanzaId?: string | null;
+ quotedMessage?: Record<string, unknown> | null;
+ expiration?: number | null;
+ };
+ }
| undefined
)?.contextInfo;
if (contextInfo?.quotedMessage && contextInfo.stanzaId) {
@@ -1175,6 +1186,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
media,
location,
quotedMessage,
+ ephemeralDuration: contextInfo?.expiration ?? undefined,
},
jid => this.sessionStore.toNeutralJid(jid),
);
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index 88050e8c2..86e851d1e 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -67,6 +67,26 @@ describe('buildIncomingMessageBase', () => {
expect(r.contact).toBeUndefined();
});
+ it('maps ephemeralDuration when present on _data', () => {
+ const r = buildIncomingMessageBase({
+ ...base,
+ _data: { ephemeralDuration: 86400 },
+ });
+ expect(r.ephemeralDuration).toBe(86400);
+ });
+
+ it('omits ephemeralDuration when absent from _data', () => {
+ expect(buildIncomingMessageBase(base).ephemeralDuration).toBeUndefined();
+ });
+
+ it('omits ephemeralDuration when ephemeralDuration is 0', () => {
+ const r = buildIncomingMessageBase({
+ ...base,
+ _data: { ephemeralDuration: 0 },
+ });
+ expect(r.ephemeralDuration).toBeUndefined();
+ });
+
it('uses `to` as the chat for an outgoing (fromMe) message, not the account JID in `from`', () => {
const r = buildIncomingMessageBase({ ...base, fromMe: true, from: '[email protected]', to: '[email protected]' });
expect(r.chatId).toBe('[email protected]');
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index 1e6586f6d..b91b9abd8 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -52,7 +52,7 @@ export interface RawMessageFields {
/** WIDs @mentioned in the message; whatsapp-web.js attaches this to every Message. */
mentionedIds?: string[];
/** Raw wwebjs payload; `notifyName` carries the sender's push name without an extra lookup. */
- _data?: { notifyName?: string };
+ _data?: { notifyName?: string; ephemeralDuration?: number };
}
/**
@@ -102,6 +102,11 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
incoming.contact = { pushName };
}
+ // Ephemeral/disappearing-messages timer, when the chat has one set.
+ if (msg._data?.ephemeralDuration && msg._data.ephemeralDuration > 0) {
+ incoming.ephemeralDuration = msg._data.ephemeralDuration;
+ }
+
return incoming;
}
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index b74a70dc2..4f7d31b83 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -69,6 +69,10 @@ export interface IncomingMessage {
* code can skip these without matching an engine-specific pseudo-JID (e.g. `status@broadcast`).
*/
isStatusBroadcast?: boolean;
+ /** WhatsApp ephemeral/disappearing-messages timer in seconds. Set per-chat on each message
+ * in the raw payload. 0 or undefined = no disappearing timer.
+ * Known values: 86400 (24h), 604800 (7d), 7776000 (90d). */
+ ephemeralDuration?: number;
/** For group messages, the WID of the participant who actually sent it (`from` is the group JID there). */
author?: string;
/** WIDs @mentioned in the message (empty/absent when none). Surfaced for command targeting. */
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 68f1a75f8..b8b584f8e 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1188,6 +1188,31 @@ describe('SessionService', () => {
expect(dispatchedEvents('message.received')).toHaveLength(0);
});
+ it('skips persist and dispatch for ephemeral messages when STORE_EPHEMERAL_MESSAGES=false', async () => {
+ process.env.STORE_EPHEMERAL_MESSAGES = 'false';
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockClear();
+
+ callbacks.onMessage!(makeMessage({ id: 'wa-eph-1', ephemeralDuration: 86400 }));
+ await flush();
+
+ expect(messageRepository.insert).not.toHaveBeenCalled();
+ expect(dispatchedEvents('message.received')).toHaveLength(0);
+ delete process.env.STORE_EPHEMERAL_MESSAGES;
+ });
+
+ it('still persists ephemeral messages when STORE_EPHEMERAL_MESSAGES is unset (default)', async () => {
+ delete process.env.STORE_EPHEMERAL_MESSAGES;
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockClear();
+
+ callbacks.onMessage!(makeMessage({ id: 'wa-eph-2', ephemeralDuration: 86400 }));
+ await flush();
+
+ expect(messageRepository.insert).toHaveBeenCalled();
+ expect(dispatchedEvents('message.received')).toHaveLength(1);
+ });
+
it('does not process an own-send status echo (type=append) — no dispatch, no WS emit, no DB write', async () => {
// Regression guard for the WhatsApp Status feature: posting a status produces an own-send echo
// that Baileys delivers as `messages.upsert` with `type: 'append'` (NOT 'notify'). The adapter's
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index bca6770b9..a58e3bff3 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -631,6 +631,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (message.isStatusBroadcast) {
return;
}
+ // Ephemeral/disappearing messages: skip persist + dispatch when the operator opted out.
+ // A message is ephemeral when its chat has a disappearing-messages timer (ephemeralDuration > 0).
+ if (
+ process.env.STORE_EPHEMERAL_MESSAGES === 'false' &&
+ message.ephemeralDuration &&
+ message.ephemeralDuration > 0
+ ) {
+ this.logger.debug('Skipping ephemeral message', {
+ sessionId: id,
+ messageId: message.id,
+ chatId: message.chatId,
+ ephemeralDuration: message.ephemeralDuration,
+ });
+ return;
+ }
this.logger.debug(`Message received from ${message.from}`, {
sessionId: id,
messageId: message.id,