Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): look each history sender up once
Yudhi Armyndharis62ebcdd9a968
diff --git a/.env.example b/.env.exampleindex 533824562..615e3ad7d 100644--- a/.env.example+++ b/.env.example@@ -427,7 +427,7 @@ WEBHOOK_SSRF_PROTECT=true# WEBHOOK_SSRF_REDIRECTS=false# Expose the FULL sender `contact` field set (id, number, shortName, business flags, isBlocked,-# labels, …) on the message.received webhook + websocket payload. OFF by default — the payload keeps+# labels, …) on message.received (webhook + websocket) and on chat history. OFF by default — the payload keeps# the minimal { name, pushName }. Opt in only if your consumer needs the richer data; all fields are# read from the already-cached contact (no extra WhatsApp API calls). whatsapp-web.js only — the# Baileys path never reads this flag, so setting it there changes nothing.diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 9fc444705..cf1d330dd 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -325,8 +325,8 @@ export interface EngineHistoryMessage {isLidSender?: boolean;senderPhone?: string | null;/**- * Sender contact info, best-effort from the engine's cache. History carries `pushName` only;- * the richer fields arrive on `message.received` when `WEBHOOK_CONTACT_DETAILS=true`.+ * Sender contact info, best-effort from the engine's cache. History carries `name` and `pushName`;+ * the richer fields are added when `WEBHOOK_CONTACT_DETAILS=true`, as on `message.received`.*/contact?: {id?: string;diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 1265707f0..85088d206 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -327,8 +327,9 @@ type MessageCall struct {Missed bool `json:"missed"`}-// MessageContact is the sender contact block on a live history message. History carries PushName-// only; the richer fields arrive on message.received when WEBHOOK_CONTACT_DETAILS is enabled.+// MessageContact is the sender contact block on a live history message. History carries Name and+// PushName; the richer fields are added when WEBHOOK_CONTACT_DETAILS is enabled, as on+// message.received.type MessageContact struct {ID string `json:"id,omitempty"`Number string `json:"number,omitempty"`diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.javaindex 9af781364..596adb382 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java@@ -58,8 +58,8 @@ public record ChatHistoryMessage(public record Product(String productId, String title, String description, String businessOwnerJid) {}/**- * Sender contact info. History carries {@code pushName} only; the richer fields arrive on- * {@code message.received} when {@code WEBHOOK_CONTACT_DETAILS} is enabled.+ * Sender contact info. History carries {@code name} and {@code pushName}; the richer fields+ * are added when {@code WEBHOOK_CONTACT_DETAILS} is enabled, as on {@code message.received}.*/public record Contact(String id,diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex d03bab9ac..7421b2ea3 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -573,8 +573,8 @@ export interface ChatHistoryMessage {isLidSender?: boolean;senderPhone?: string | null;/**- * Sender contact info, best-effort from the engine's cache. History carries `pushName` only;- * the richer fields arrive on `message.received` when `WEBHOOK_CONTACT_DETAILS=true`.+ * Sender contact info, best-effort from the engine's cache. History carries `name` and `pushName`;+ * the richer fields are added when `WEBHOOK_CONTACT_DETAILS=true`, as on `message.received`.*/contact?: {id?: Jid;diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex eef9a4b1e..ed25bd9c6 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -560,8 +560,8 @@ class MessageProduct(TypedDict):class MessageContact(TypedDict, total=False):- """Sender contact block. History carries ``pushName`` only; the richer fields arrive on- ``message.received`` when ``WEBHOOK_CONTACT_DETAILS`` is enabled."""+ """Sender contact block. History carries ``name`` and ``pushName``; the richer fields are+ added when ``WEBHOOK_CONTACT_DETAILS`` is enabled, as on ``message.received``."""id: Jidnumber: strdiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex d10ed32fb..608080da2 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -757,10 +757,39 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live pconst out = await readyAdapter(client).getChatHistory('[email protected]', 50, false);+ expect(groupMsg.getContact).toHaveBeenCalled();expect(out[0].contact).toBeUndefined();expect(out[0].body).toBe('hi all');});+ it('looks each history sender up once, not once per message', async () => {+ const msg = (id: string, author: string, getContact: jest.Mock) => ({+ id: { _serialized: id },+ from: '[email protected]',+ to: 'me',+ author,+ body: 'hi',+ type: 'chat',+ timestamp: 700,+ fromMe: false,+ hasMedia: false,+ hasQuotedMsg: false,+ getContact,+ });+ const alice1 = msg('M8', '111@lid', jest.fn().mockResolvedValue({ pushname: 'Alice' }));+ const alice2 = msg('M9', '111@lid', jest.fn().mockResolvedValue({ pushname: 'Alice' }));+ const bob = msg('M10', '222@lid', jest.fn().mockResolvedValue({ pushname: 'Bob' }));+ const chat = { fetchMessages: jest.fn().mockResolvedValue([alice1, alice2, bob]) };+ const client = { getChatById: jest.fn().mockResolvedValue(chat) };++ const out = await readyAdapter(client).getChatHistory('[email protected]', 50, false);++ expect(alice1.getContact).toHaveBeenCalledTimes(1);+ expect(alice2.getContact).not.toHaveBeenCalled();+ expect(bob.getContact).toHaveBeenCalledTimes(1);+ expect(out.map(m => m.contact)).toEqual([{ pushName: 'Alice' }, { pushName: 'Alice' }, { pushName: 'Bob' }]);+ });+it('skips the media download when the declared size exceeds a caller-tightened mediaMaxBytes', async () => {// 12 MB passes the global 50 MiB default but not the seed's 10 MB store cap — proving the// override (not the default) did the gating, and the blob is never downloaded.diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex af9aaa513..b3d68f68a 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -6,6 +6,7 @@ import {ContactCard,DeliveryStatus,MediaInput,+ MessageContact,MessageReaction,MessageResult,PollInput,@@ -707,6 +708,10 @@ export class WwebjsMessaging {: mediaMaxBytes === undefined? chatHistoryMediaBudgetBytes(): ingestMediaBudgetBytes(mediaMaxBytes);+ // Sender contacts resolved so far, keyed like Message.getContact() (`author || from`). Each lookup+ // is a page round trip and a history page repeats the same few senders, so resolve each once; a+ // failed lookup is remembered as undefined rather than retried for every later message.+ const senderContacts = new Map<string, MessageContact | undefined>();for (const msg of messages) {if (signal?.aborted) {break;@@ -727,17 +732,22 @@ export class WwebjsMessaging {// contacts (author-only, no saved name) shows no sender label at all in the chat view,// even though the live `message` event handler resolves one via getContact() for the// exact same message. Mirror that here so history and live rendering agree.- try {- const contact = await msg.getContact();- if (contact) {- const full = process.env.WEBHOOK_CONTACT_DETAILS === 'true';- const merged = { ...out.contact, ...mapContactFields(contact, full) };- if (Object.keys(merged).length > 0) {- out.contact = merged;- }+ const senderId = msg.author || msg.from;+ if (!senderContacts.has(senderId)) {+ let resolved: MessageContact | undefined;+ try {+ const contact = await msg.getContact();+ if (contact) resolved = mapContactFields(contact, process.env.WEBHOOK_CONTACT_DETAILS === 'true');+ } catch (error) {+ this.host.logger.warn(+ `Failed to resolve contact for history message ${msg.id._serialized}: ${String(error)}`,+ );}- } catch (error) {- this.host.logger.warn(`Failed to resolve contact for history message ${msg.id._serialized}: ${String(error)}`);+ senderContacts.set(senderId, resolved);+ }+ const merged = { ...out.contact, ...senderContacts.get(senderId) };+ if (Object.keys(merged).length > 0) {+ out.contact = merged;}const call = extractWwebjsCall(msg);if (call) out.call = call;diff --git a/src/modules/session/session-engine-leaf-events.ts b/src/modules/session/session-engine-leaf-events.tsindex f6b43a0de..fd756f3d3 100644--- a/src/modules/session/session-engine-leaf-events.ts+++ b/src/modules/session/session-engine-leaf-events.ts@@ -73,8 +73,8 @@ export class SessionEngineLeafEvents {const mediaMaxBytes =this.configService?.get<number>('status.mediaMaxBytes', DEFAULT_MEDIA_MAX_BYTES) ?? DEFAULT_MEDIA_MAX_BYTES;const messages = await engine.getChatHistory('status@broadcast', STATUS_SEED_LIMIT, true, mediaMaxBytes);- // getChatHistory maps a message's contact from the sync cache only, so status posters (usually- // @lid ids) come back nameless. Resolve each unique poster once via getContactById — the same+ // getChatHistory resolves each poster's contact, but a lookup that failed or found no name leaves+ // the status nameless (usually an @lid poster). Resolve each once via getContactById — the same// lookup the contacts API uses, which maps the @lid to the real contact — so a seeded status// carries the poster's name like a live one does. Cached per JID: one lookup per contact, not// one per status.