Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): report real blocklist state on Baileys contact reads
Yudhi Armyndharis81000cfdad7a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b9b6d0f9..e372270fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- On the Baileys engine, `isBlocked` on a contact read is now the account's real blocklist state rather than a literal `false`. Nothing derived it, while the same session's `/contacts/blocked` endpoint returned the real ids — so automation that skips blocked contacts before sending messaged people the account had explicitly blocked. A blocklist query that fails leaves the field at its default and logs a warning rather than failing the contact read or selling a transport failure as "nobody is blocked". `isMyContact` is unchanged: Baileys has no addressbook signal to derive it from, and inventing one would repeat the mistake.+- Five whatsapp-web.js chat operations — mark-as-read, clear, archive, mark-unread and delete — no longer report a dead browser as a refusal. Each caught every error and resolved `false`, so the caller got `200 {"success": false}` ("WhatsApp declined a valid request") while the session's page was actually dead, and retried against it instead of receiving the documented 503. The early death signal was lost too, so the session kept reporting READY until the slower watchdog noticed. They now split transport failure out into `EngineTransportError` and report it, exactly as `getChats` and the other sibling reads in the same adapter already did. An ordinary page-side refusal still resolves `false`, unchanged.- The cross-node takeover sweep no longer adopts sessions while the process is shutting down. `onModuleDestroy` cleared the interval, which stops the next sweep but does nothing about one already running — it is neither aborted nor awaited, and nothing on the start path consulted a shutting-down signal. On a rolling restart a sweep mid-flight could construct and register an engine after the shutdown path had emptied the registry, and claim the ownership lease for a process about to exit, pinning that session to a dead node until the lease lapsed. The signal is re-checked per adoption, because each one costs a browser launch and the loop spans much of the sweep interval.diff --git a/src/engine/adapters/baileys-contact-blocked.spec.ts b/src/engine/adapters/baileys-contact-blocked.spec.tsnew file mode 100644index 000000000..fa949084d--- /dev/null+++ b/src/engine/adapters/baileys-contact-blocked.spec.ts@@ -0,0 +1,70 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysContacts, type BaileysContactsHost } from './baileys-contacts';+import { createLogger } from '../../common/services/logger.service';+import type { Contact } from '../interfaces/whatsapp-engine.interface';++/**+ * `toNeutralContact` returned the literal `isBlocked: false` for every contact — not derived from+ * anything — while the SAME session's `/contacts/blocked` endpoint returned the real ids. Automation+ * that skips blocked contacts before sending therefore messaged people the account had explicitly+ * blocked, on the strength of a field the gateway had simply made up.+ */+const logger = createLogger('baileys-contact-blocked.spec');++describe('Baileys contact reads report real blocklist state', () => {+ const contact = (id: string): Contact => ({+ id,+ number: id.split('@')[0],+ isMyContact: true,+ isBlocked: false,+ pushName: 'x',+ });++ function make(opts: { blocklist?: string[]; blocklistError?: Error }): {+ contacts: BaileysContacts;+ warn: jest.Mock;+ } {+ const warn = jest.fn();+ const fetchBlocklist = opts.blocklistError+ ? jest.fn().mockRejectedValue(opts.blocklistError)+ : jest.fn().mockResolvedValue(opts.blocklist ?? []);+ const host = {+ ensureReady: jest.fn(),+ getSocket: () => ({ fetchBlocklist }) as unknown as WASocket,+ logger: { ...logger, warn },+ listContacts: () => [contact('[email protected]'), contact('[email protected]')],+ findContact: (id: string) => contact(id),+ toNeutralJid: (jid: string) => jid,+ } as unknown as BaileysContactsHost;+ return { contacts: new BaileysContacts(host), warn };+ }++ it('marks a contact on the blocklist as blocked', async () => {+ const { contacts } = make({ blocklist: ['[email protected]'] });++ const all = await contacts.getContacts();++ expect(all.find(c => c.id === '[email protected]')?.isBlocked).toBe(true);+ expect(all.find(c => c.id === '[email protected]')?.isBlocked).toBe(false);+ });++ it('marks a single contact read the same way', async () => {+ const { contacts } = make({ blocklist: ['[email protected]'] });++ await expect(contacts.getContactById('[email protected]')).resolves.toMatchObject({ isBlocked: true });+ await expect(contacts.getContactById('[email protected]')).resolves.toMatchObject({ isBlocked: false });+ });++ // A blocklist query that fails is a transport fact, not a claim that nobody is blocked. The read+ // must not fail outright either — contacts are still useful — so it degrades loudly.+ it('does not fail the contact read when the blocklist query does, and says so', async () => {+ const { contacts, warn } = make({+ blocklistError: new Error('WhatsApp did not answer the blocklist query in time'),+ });++ const all = await contacts.getContacts();++ expect(all).toHaveLength(2);+ expect(warn).toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 760060dd1..e8b191bb4 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -165,13 +165,41 @@ export class BaileysContacts {// eslint-disable-next-line @typescript-eslint/require-awaitasync getContacts(): Promise<Contact[]> {this.host.ensureReady();- return this.host.listContacts();+ return this.withBlockedState(this.host.listContacts());}- // eslint-disable-next-line @typescript-eslint/require-awaitasync getContactById(contactId: string): Promise<Contact | null> {this.host.ensureReady();- return this.host.findContact(contactId);+ const contact = this.host.findContact(contactId);+ if (!contact) return null;+ return (await this.withBlockedState([contact]))[0];+ }++ /**+ * Stamp the real blocklist state onto contacts the store mapped.+ *+ * The store has no socket, so its mapper defaulted `isBlocked` to a literal `false` for everyone —+ * a claim about the account, not a reading of it, while THIS session's own blocklist query returns+ * the real ids. Automation that skips blocked contacts before sending therefore messaged people the+ * account had explicitly blocked.+ *+ * A failed blocklist query degrades rather than failing the read: contacts are still useful, and+ * getBlockedContacts deliberately throws instead of returning an empty list precisely so a+ * transport failure is not sold as "nobody is blocked". The default is kept and the gap is warned+ * about, so the degradation is visible instead of silent.+ */+ private async withBlockedState(contacts: Contact[]): Promise<Contact[]> {+ if (contacts.length === 0) return contacts;+ let blocked: Set<string>;+ try {+ blocked = new Set(await this.getBlockedContacts());+ } catch (error) {+ this.host.logger.warn('Blocklist unavailable; contact isBlocked left at its default', {+ error: error instanceof Error ? error.message : String(error),+ });+ return contacts;+ }+ return contacts.map(contact => ({ ...contact, isBlocked: blocked.has(contact.id) }));}// eslint-disable-next-line @typescript-eslint/require-await