Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): list a wwebjs contact once, with its phone as number
Yudhi Armyndharisdbb7e1e007c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1fe4619a7..5be1fc2e7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -80,6 +80,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Create the built-in PostgreSQL container with the saved `DATABASE_PASSWORD`, so a custom password saved with the built-in database no longer fails the next boot.- Serialize a plugin upload with an uninstall or update of the same plugin id.- Show hours for a session active within the last day on the Sessions page, as the Dashboard does.+- List a whatsapp-web.js contact held under both its LID and its phone once, with the phone as `number`, instead of twice with the LID's digits.## [0.25.0] - 2026-10-15diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 5d9356a6e..322accce3 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2499,7 +2499,7 @@ The `Contact` object returned by the list and get-by-id routes has this shape:List all contacts for a session, returned as an in-memory paginated window.-On Baileys the list is the saved address book: contacts with a name saved on the phone (`isMyContact: true`), rebuilt from WhatsApp's app-state contact collection on connect, including after a process restart. A peer known only by its pushname is not listed but still resolves through the get-by-id route below with `isMyContact: false`. whatsapp-web.js lists what the WhatsApp Web page holds, which also includes unsaved chat partners (`isMyContact: false`). An entry the page cannot read (for example a device-scoped id), or one without a readable id, is left out of the list; the gateway logs a warning with the count, and the response does not signal it.+On Baileys the list is the saved address book: contacts with a name saved on the phone (`isMyContact: true`), rebuilt from WhatsApp's app-state contact collection on connect, including after a process restart. A peer known only by its pushname is not listed but still resolves through the get-by-id route below with `isMyContact: false`. whatsapp-web.js lists what the WhatsApp Web page holds, which also includes unsaved chat partners (`isMyContact: false`). A contact the page holds under both its LID and its phone is listed once, under its phone id with the phone as `number`. An entry the page cannot read (for example a device-scoped id), or one without a readable id, is left out of the list; the gateway logs a warning with the count, and the response does not signal it.**Auth:** API keydiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex bec83a973..c19e3d327 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -7098,6 +7098,79 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(evaluate).toHaveBeenCalledTimes(1);});+ // A contact migrated to privacy-id addressing is two WhatsApp Web records, its LID and its phone.+ // whatsapp-web.js answers the LID record under the phone id (a plain string, the model's `phoneNumber`)+ // but leaves `number` at the LID's digits, so the phone id came back twice, once with the wrong number.+ const lidRecord = {+ id: '[email protected]',+ pushname: 'Ally',+ number: '262813461250071',+ isMyContact: false,+ isBlocked: false,+ };+ const phoneRecord = {+ id: { _serialized: '[email protected]' },+ name: 'Alice',+ number: '628111',+ isMyContact: true,+ isBlocked: false,+ };++ it.each([+ ['the LID record first', [lidRecord, phoneRecord]],+ ['the phone record first', [phoneRecord, lidRecord]],+ ])('lists a contact held as a LID and a phone record once, with its phone as number (%s)', async (_order, rows) => {+ const evaluate = jest.fn().mockResolvedValue({ rows, failed: 0 });+ const { adapter } = readyAdapter({ pupPage: { evaluate } });++ await expect(adapter.getContacts()).resolves.toEqual([+ { id: '[email protected]', name: 'Alice', pushName: 'Ally', number: '628111', isMyContact: true, isBlocked: false },+ ]);+ });++ it('keeps a folded contact where its first copy was, and a block on either copy survives', async () => {+ const other = { id: { _serialized: '[email protected]' }, name: 'Zed', number: '999', isMyContact: true, isBlocked: false };+ const evaluate = jest.fn().mockResolvedValue({+ rows: [lidRecord, other, { ...phoneRecord, isBlocked: true }],+ failed: 0,+ });+ const { adapter } = readyAdapter({ pupPage: { evaluate } });++ const contacts = await adapter.getContacts();++ expect(contacts.map(c => c.id)).toEqual(['[email protected]', '[email protected]']);+ expect(contacts[0].isBlocked).toBe(true);+ });++ it('leaves a LID with no known phone under its @lid id and the number WhatsApp Web gave', async () => {+ const unresolved = {+ id: { _serialized: '262813461250071@lid' },+ number: '262813461250071',+ isMyContact: false,+ isBlocked: false,+ };+ const evaluate = jest.fn().mockResolvedValue({ rows: [unresolved], failed: 0 });+ const { adapter } = readyAdapter({ pupPage: { evaluate } });++ await expect(adapter.getContacts()).resolves.toEqual([+ { id: '262813461250071@lid', number: '262813461250071', isMyContact: false, isBlocked: false },+ ]);+ });++ it('getContactById gives a contact answered under its phone id that phone as number', async () => {+ const getContactById = jest.fn().mockResolvedValue({ ...lidRecord, name: 'Alice', isMyContact: true });+ const { adapter } = readyAdapter({ getContactById });++ await expect(adapter.getContactById('262813461250071@lid')).resolves.toEqual({+ id: '[email protected]',+ name: 'Alice',+ pushName: 'Ally',+ number: '628111',+ isMyContact: true,+ isBlocked: false,+ });+ });+// #1476: an entry with no readable wid under either name (a shape wwebjs itself sometimes returns)// must not reject the whole address book — it is dropped and counted instead.it('skips a contact with no readable id and counts it in the warn log, keeping the rest', async () => {diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 1f9a6909b..7d631b4ff 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -2,7 +2,7 @@ import { type Client } from 'whatsapp-web.js';import { InternalServerErrorException } from '@nestjs/common';import { Contact } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';-import { userPart } from '../identity/wa-id';+import { parseWaId, userPart } from '../identity/wa-id';import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';import { type WwebjsEngineHost, withPage } from './wwebjs-host';import { isProtocolTimeout } from './wwebjs-lifecycle';@@ -114,12 +114,41 @@ export class WwebjsContacts {id,name: c.name || undefined,pushName: c.pushname || undefined,- number: c.number,+ // whatsapp-web.js answers a contact migrated to privacy-id addressing under its phone id (the+ // model's `phoneNumber`) but leaves `number` at the LID's digits, so a user id's number is read+ // from the id. A LID with no known phone keeps the engine's number.+ number: parseWaId(id).kind === 'user' ? userPart(id) : c.number,isMyContact: c.isMyContact,isBlocked: c.isBlocked,};}+ /**+ * WhatsApp Web holds a contact migrated to privacy-id addressing twice, as its LID record and its+ * phone record, and {@link toContact} reads the first under the phone id, so one id comes back twice.+ * The copies are folded into the first one's place, which keeps the paging order stable, and a name or+ * a flag only the other copy holds survives (a block is never dropped).+ */+ private static mergeById(contacts: Contact[]): Contact[] {+ const byId = new Map<string, Contact>();+ for (const c of contacts) {+ const first = byId.get(c.id);+ byId.set(+ c.id,+ first+ ? {+ ...first,+ name: first.name ?? c.name,+ pushName: first.pushName ?? c.pushName,+ isMyContact: first.isMyContact || c.isMyContact,+ isBlocked: first.isBlocked || c.isBlocked,+ }+ : c,+ );+ }+ return [...byId.values()];+ }+async getContacts(): Promise<Contact[]> {this.host.ensureReady();@@ -184,7 +213,7 @@ export class WwebjsContacts {if (unreadable > 0) {this.host.logger.warn(`Skipped ${unreadable} contact(s) WhatsApp Web could not read`, { error: firstError });}- return contacts;+ return WwebjsContacts.mergeById(contacts);}async getContactById(contactId: string): Promise<Contact | null> {