Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): source disappearing-messages timer from inbound messages (#473) (#513)
Ulises Cuñe54aaaa667d84
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 664b8c7c6..c59fbe7bb 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -96,6 +96,82 @@ describe('BaileysSessionStore', () => {expect(store.getEphemeralExpiration('[email protected]')).toBeUndefined();expect(store.getEphemeralExpiration('[email protected]')).toBeUndefined();});++ it('learns the timer from an inbound message ephemeralDuration without any chats.* upsert', () => {+ // The real-world case: Chat.ephemeralExpiration is never populated, but every inbound message in+ // a disappearing chat carries the live timer. A neutral @c.us send target must resolve it too.+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' },+ message: { conversation: 'hi' },+ messageTimestamp: 100,+ ephemeralDuration: 7776000,+ });+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ });++ it('resolves a timer learned under @lid when the send targets the phone jid (#473 LID migration)', () => {+ store.addLidMappings([{ lid: '41562515988583@lid', pn: '[email protected]' }]);+ store.recordMessage({+ key: { remoteJid: '41562515988583@lid', fromMe: false, id: 'M2' },+ message: { conversation: 'hola' },+ messageTimestamp: 100,+ ephemeralDuration: 7776000,+ });+ // matchwa replies to the neutral phone jid OpenWA delivered on the webhook — the prior no-op case.+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ expect(store.getEphemeralExpiration('41562515988583@lid')).toBe(7776000);+ });++ it('ignores a non-positive ephemeralDuration and never clears a known timer', () => {+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' },+ message: { conversation: 'hi' },+ messageTimestamp: 100,+ ephemeralDuration: 86400,+ });+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M2' },+ message: { conversation: 'later' },+ messageTimestamp: 200,+ ephemeralDuration: 0,+ });+ expect(store.getEphemeralExpiration('[email protected]')).toBe(86400);+ });++ it('prefers the message-learned timer over a stale Chat.ephemeralExpiration', () => {+ store.upsertChats([{ id: '[email protected]', ephemeralExpiration: 604800 }]);+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' },+ message: { conversation: 'hi' },+ messageTimestamp: 100,+ ephemeralDuration: 7776000,+ });+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ });++ it('learns the timer from contextInfo.expiration when ephemeralDuration is absent (live 1:1)', () => {+ // WebMessageInfo.ephemeralDuration is empty on a live 1:1 upsert; the per-message expiration on the+ // content's contextInfo is the reliable source.+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' },+ message: { extendedTextMessage: { text: 'hi', contextInfo: { expiration: 7776000 } } },+ messageTimestamp: 100,+ });+ expect(store.getEphemeralExpiration('[email protected]')).toBe(7776000);+ });++ it('unwraps an ephemeralMessage envelope to read contextInfo.expiration', () => {+ store.recordMessage({+ key: { remoteJid: '[email protected]', fromMe: false, id: 'M2' },+ message: {+ ephemeralMessage: { message: { extendedTextMessage: { text: 'hi', contextInfo: { expiration: 86400 } } } },+ },+ messageTimestamp: 100,+ });+ expect(store.getEphemeralExpiration('[email protected]')).toBe(86400);+ });});it('resolves a phone jid to its user-part, a lid via lidPnMappings, and a contact phoneNumber', () => {diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 116e7aae2..375acfd86 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -26,6 +26,15 @@ export class BaileysSessionStore {private readonly chats = new Map<string, Chat>();private readonly lastMessages = new Map<string, LastMessage>();private readonly lidToPn = new Map<string, string>();+ /**+ * Per-chat disappearing-messages timer (seconds) learned from inbound messages (#473), the reliable+ * source for it: `Chat.ephemeralExpiration` (from `chats.*`/history sync) is empirically absent for a+ * long-standing timer after a reconnect (observed live: 0 of 159 cached chats carried it). Keyed by+ * both the raw and neutral JID so an outbound send addressed in either dialect (phone `@c.us` /+ * `@s.whatsapp.net` or `@lid`) resolves to the same entry. See {@link extractEphemeralDuration} for+ * which message field is read.+ */+ private readonly ephemeralByChat = new Map<string, number>();/*** @param lidStore optional persisted, cross-session lid->phone table that backs resolution beyond@@ -100,6 +109,10 @@ export class BaileysSessionStore {if (!chatId || !msg.key) {return;}+ // Learn the chat's disappearing-messages timer from the message itself (#473). This runs before the+ // newest-message guard so every inbound refreshes it; the timer is cached under both the raw and+ // neutral JID so an outbound send addressed in either dialect (phone or @lid) finds it.+ this.recordEphemeralFromMessage(chatId, msg);const timestamp = this.toUnixSeconds(msg.messageTimestamp);const existing = this.lastMessages.get(chatId);if (existing && existing.timestamp >= timestamp) {@@ -109,6 +122,60 @@ export class BaileysSessionStore {this.lastMessages.set(chatId, { key: msg.key, timestamp, text });}+ /**+ * Cache a positive disappearing-messages timer learned from an inbound message under both the raw chat+ * JID and its neutral form, so {@link getEphemeralExpiration} hits regardless of which dialect the caller+ * sends to. A non-positive/absent value means "no live timer on this message" and is left untouched (a+ * single non-ephemeral message must not clear a known timer; WhatsApp keeps stamping it while on).+ */+ private recordEphemeralFromMessage(chatId: string, msg: WAMessage): void {+ const duration = this.extractEphemeralDuration(msg);+ if (duration === undefined) {+ return;+ }+ this.ephemeralByChat.set(chatId, duration);+ this.ephemeralByChat.set(this.toNeutralJid(chatId), duration);+ }++ /**+ * Best-effort read of a message's disappearing timer (seconds). `WebMessageInfo.ephemeralDuration` is+ * populated on history-synced messages but is typically ABSENT on a live 1:1 `messages.upsert`, so fall+ * back to the per-message `contextInfo.expiration` WhatsApp stamps on every message in a disappearing+ * chat — read after unwrapping the ephemeral / view-once / document-with-caption envelope.+ */+ private extractEphemeralDuration(msg: WAMessage): number | undefined {+ const fromInfo = msg.ephemeralDuration;+ if (typeof fromInfo === 'number' && fromInfo > 0) {+ return fromInfo;+ }+ const fromContext = this.contextExpiration(msg.message);+ return typeof fromContext === 'number' && fromContext > 0 ? fromContext : undefined;+ }++ /** Walk a message's content (unwrapping known envelopes) and return the first positive `contextInfo.expiration`. */+ private contextExpiration(content: WAMessage['message'], depth = 0): number | undefined {+ if (!content || typeof content !== 'object' || depth > 4) {+ return undefined;+ }+ const nodes = content as Record<+ string,+ { contextInfo?: { expiration?: number | null }; message?: WAMessage['message'] } | undefined+ >;+ for (const node of Object.values(nodes)) {+ const exp = node?.contextInfo?.expiration;+ if (typeof exp === 'number' && exp > 0) {+ return exp;+ }+ if (node?.message) {+ const nested = this.contextExpiration(node.message, depth + 1);+ if (nested !== undefined) {+ return nested;+ }+ }+ }+ return undefined;+ }+listContacts(): Contact[] {return [...this.contacts.values()].map(c => this.toNeutralContact(c));}@@ -135,7 +202,18 @@ export class BaileysSessionStore {* disappear. Folds a neutral `@c.us` id to the engine dialect first, like the other chat lookups.*/getEphemeralExpiration(chatId: string): number | undefined {- const chat = this.chats.get(chatId) ?? this.chats.get(this.toEngineJid(chatId));+ // Prefer the timer learned from inbound messages (reliably present); try the raw, engine, and+ // neutral keys so an @lid-keyed entry and a phone-dialect send target resolve to the same value.+ const fromMessage =+ this.ephemeralByChat.get(chatId) ??+ this.ephemeralByChat.get(this.toEngineJid(chatId)) ??+ this.ephemeralByChat.get(this.toNeutralJid(chatId));+ if (typeof fromMessage === 'number' && fromMessage > 0) {+ return fromMessage;+ }+ // Fallback to the chat object's own timer for sessions/engines that do surface it on `chats.*`.+ const chat =+ this.chats.get(chatId) ?? this.chats.get(this.toEngineJid(chatId)) ?? this.chats.get(this.toNeutralJid(chatId));const exp = chat?.ephemeralExpiration;return typeof exp === 'number' && exp > 0 ? exp : undefined;}