Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(contact): expose the blocklist read (GET /contacts/blocked)
Yudhi Armyndharisf85b0c6a798e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f47ff9eb5..a1223fd00 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- **Own global presence: `PUT /sessions/:id/presence`** — appear online or offline on both engines; an always-online headless bot suppresses the phone's own notifications, and `available: false` hands them back. Connection-scoped (re-issue after a reconnect). Refs #871.+- **Blocklist read: `GET /sessions/:sessionId/contacts/blocked`** — the missing read half of the block/unblock endpoints, as a bare array of neutral contact ids on both engines; on Baileys an unanswered query is a `503`, never an empty list.+- **The media download route now serves media sent by the account** — `GET /messages/:chatId/:messageId/media` falls back to the inline copy stored on the message row when no archived file exists, which covers outbound messages (never archived) and inbound messages whose archived file retention has purged.### Changeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 43cfd7e74..7fbafe04f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2002,6 +2002,23 @@ List all contacts for a session, returned as an in-memory paginated window.**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session+#### GET /api/sessions/:sessionId/contacts/blocked++The contacts this account has blocked — the read half of the block/unblock endpoints. A bare array+of neutral contact ids, and ids only: whatsapp-web.js resolves full contact models, but Baileys'+blocklist query answers bare jids, and inventing the other fields on one engine would make the two+engines claim different things about the same account.++**Auth:** API key++**Response** `200`++```json+["[email protected]", "[email protected]"]+```++**Errors:** `400` session not started · `401` missing/invalid `X-API-Key` · `409` engine not ready · `503` WhatsApp did not answer the blocklist query (on Baileys the gateway bounds the query with its own clock — an unanswered query is a `503`, never an empty list)+#### GET /api/sessions/:sessionId/contacts/check/:numberCheck whether a phone number exists on WhatsApp and return its canonical WhatsApp id when it does.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex d4cfe1e1e..ff63cfc99 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -22,7 +22,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins## Unwired-capability inventory-21 of the 104 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.+21 of the 105 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.### Channels / Newsletter@@ -174,8 +174,8 @@ These are hand-maintained and had drifted from the source before this pass; theyfrom `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way whenadding a method, instead of incrementing the previous figure.-- **104** interface methods, **208** adapter-cells (104 × 2 engines).-- **186** supported cells; **22** not-available cells across **21** methods.+- **105** interface methods, **210** adapter-cells (105 × 2 engines).+- **188** supported cells; **22** not-available cells across **21** methods.- Of the 22 not-available cells: **2 adapter-gaps** (fixable) + **20 library-limitations** + **0 uncertain**.- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.diff --git a/openapi.json b/openapi.jsonindex 46d0ec9c9..4aa5e5845 100644--- a/openapi.json+++ b/openapi.json@@ -4057,6 +4057,48 @@]}},+ "/api/sessions/{sessionId}/contacts/blocked": {+ "get": {+ "description": "The read half of the block/unblock endpoints. A bare array of neutral contact ids — ids only, because that is the honest common subset: whatsapp-web.js resolves full contact models but Baileys' blocklist query answers bare jids, and inventing the other fields on one engine would make the two engines claim different things about the same account.",+ "operationId": "ContactController_getBlockedContacts",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Blocked contact ids",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ }+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this."+ },+ "503": {+ "description": "WhatsApp did not answer the blocklist query — retry shortly"+ }+ },+ "summary": "List the contacts this account has blocked",+ "tags": [+ "contacts"+ ]+ }+ },"/api/sessions/{sessionId}/contacts/{contactId}": {"get": {"operationId": "ContactController_findOne",diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 9a3a570dc..2e5e44d2d 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -24,6 +24,8 @@ export interface BaileysContactsHost {lastMessage(chatId: string): { key: WAMessageKey; timestamp: number } | null;/** Fold a neutral @c.us id to the engine @s.whatsapp.net form used as the app-state index key. */toEngineJid(jid: string): string;+ /** Fold an engine jid back to the neutral dialect before it crosses the engine boundary. */+ toNeutralJid(jid: string): string;}export class BaileysContacts {@@ -104,6 +106,22 @@ export class BaileysContacts {await this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock');}+ /**+ * The read half of block/unblockContact. Bounded by our own clock: Baileys' `query()` swallows+ * its timeout, and an unanswered blocklist query would otherwise surface as an EMPTY blocklist —+ * a claim about the account sold in place of a transport failure. Wire items without a jid attr+ * are dropped rather than reported as "undefined".+ */+ async getBlockedContacts(): Promise<string[]> {+ this.host.ensureReady();+ const jids = await withQueryDeadline(+ this.sock().fetchBlocklist(),+ this.queryBudgetMs,+ 'WhatsApp did not answer the blocklist query in time',+ );+ return (jids ?? []).filter((jid): jid is string => Boolean(jid)).map(jid => this.host.toNeutralJid(jid));+ }+async setProfileName(name: string): Promise<void> {this.host.ensureReady();await this.confirmed(this.sock().updateProfileName(name), 'the profile name change');diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex ce873555a..f19d60f56 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -176,6 +176,7 @@ export class BaileysAdapter implements IWhatsAppEngine {listChats: () => this.sessionStore.listChats(),lastMessage: chatId => this.sessionStore.lastMessage(chatId),toEngineJid: jid => this.sessionStore.toEngineJid(jid),+ toNeutralJid: jid => this.sessionStore.toNeutralJid(jid),});this.statusOps = new BaileysStatus({ensureReady: () => this.ensureReady(),@@ -496,6 +497,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.contacts.unblockContact(contactId);}+ async getBlockedContacts(): Promise<string[]> {+ return this.contacts.getBlockedContacts();+ }+// ----- Profile (own account) -----async setProfileName(name: string): Promise<void> {diff --git a/src/engine/adapters/blocked-contacts.spec.ts b/src/engine/adapters/blocked-contacts.spec.tsnew file mode 100644index 000000000..69e7f2cb4--- /dev/null+++ b/src/engine/adapters/blocked-contacts.spec.ts@@ -0,0 +1,86 @@+import { WwebjsContacts } from './wwebjs-contacts';+import { BaileysContacts } from './baileys-contacts';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import type { Client } from 'whatsapp-web.js';+import type { WASocket } from '@whiskeysockets/baileys';++/**+ * The blocklist READ — the missing half of the exposed block/unblock writes. The neutral shape is+ * a bare array of ids: whatsapp-web.js resolves full Contact models but Baileys' blocklist query+ * answers only jids, and inventing the other fields on one engine would make the two engines claim+ * different things about the same account.+ */++const logger = createLogger('blocked-contacts.spec');++describe('WwebjsContacts.getBlockedContacts', () => {+ function makeContacts(): { contacts: WwebjsContacts; client: { getBlockedContacts: jest.Mock } } {+ const client = { getBlockedContacts: jest.fn() };+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ reportIfPageTransportError: jest.fn(),+ } as unknown as WwebjsEngineHost;+ return { contacts: new WwebjsContacts(host), client };+ }++ it('maps the blocked Contact models to their neutral ids', async () => {+ const { contacts, client } = makeContacts();+ client.getBlockedContacts.mockResolvedValue([+ { id: { _serialized: '[email protected]' } },+ { id: { _serialized: '[email protected]' } },+ ]);++ await expect(contacts.getBlockedContacts()).resolves.toEqual(['[email protected]', '[email protected]']);+ });++ it('drops an entry whose id is unreadable rather than reporting "undefined"', async () => {+ const { contacts, client } = makeContacts();+ client.getBlockedContacts.mockResolvedValue([{ id: {} }, { id: { _serialized: '[email protected]' } }]);++ await expect(contacts.getBlockedContacts()).resolves.toEqual(['[email protected]']);+ });++ it('resolves [] for an empty blocklist', async () => {+ const { contacts, client } = makeContacts();+ client.getBlockedContacts.mockResolvedValue([]);++ await expect(contacts.getBlockedContacts()).resolves.toEqual([]);+ });+});++describe('BaileysContacts.getBlockedContacts', () => {+ function makeContacts(): { contacts: BaileysContacts; sock: { fetchBlocklist: jest.Mock } } {+ const sock = { fetchBlocklist: jest.fn() };+ const host = {+ ensureReady: jest.fn(),+ getSocket: () => sock as unknown as WASocket,+ logger,+ toNeutralJid: (jid: string) => jid.replace('@s.whatsapp.net', '@c.us'),+ };+ return { contacts: new BaileysContacts(host as never), sock };+ }++ it('neutralises the blocklist jids', async () => {+ const { contacts, sock } = makeContacts();+ sock.fetchBlocklist.mockResolvedValue(['[email protected]', '[email protected]']);++ await expect(contacts.getBlockedContacts()).resolves.toEqual(['[email protected]', '[email protected]']);+ });++ it('drops undefined jid attrs (a wire item without a jid carries nothing addressable)', async () => {+ const { contacts, sock } = makeContacts();+ sock.fetchBlocklist.mockResolvedValue([undefined, '[email protected]']);++ await expect(contacts.getBlockedContacts()).resolves.toEqual(['[email protected]']);+ });++ it('resolves [] for an empty blocklist', async () => {+ const { contacts, sock } = makeContacts();+ sock.fetchBlocklist.mockResolvedValue([]);++ await expect(contacts.getBlockedContacts()).resolves.toEqual([]);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 63c7af69a..576eb9ec2 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1693,6 +1693,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.contacts.unblockContact(contactId);}+ getBlockedContacts(): Promise<string[]> {+ return this.contacts.getBlockedContacts();+ }+// ========== Profile (own account) ==========setProfileName(name: string): Promise<void> {diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex d13d9b137..fec9a0600 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 { Contact } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { userPart } from '../identity/wa-id';-import { readWid } from '../types/whatsapp-web-js.types';+import { readWid, type SerializedWid } from '../types/whatsapp-web-js.types';import { type WwebjsEngineHost } from './wwebjs-host';/**@@ -113,6 +113,22 @@ export class WwebjsContacts {this.host.logger.log(`Blocked contact ${contactId}`);}+ /**+ * The read half of block/unblockContact. Ids only — the neutral common subset with Baileys,+ * whose blocklist query answers bare jids. An entry whose wid is unreadable (#747 rename+ * hazard) is dropped rather than reported as the literal "undefined".+ */+ async getBlockedContacts(): Promise<string[]> {+ this.host.ensureReady();+ try {+ const contacts = await this.client().getBlockedContacts();+ return contacts.map(c => readWid(c.id as unknown as SerializedWid)).filter((id): id is string => Boolean(id));+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'getBlockedContacts');+ throw error;+ }+ }+async unblockContact(contactId: string): Promise<void> {this.host.ensureReady();const contact = await this.client().getContactById(contactId);diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex fdd3347ef..3ce7fb91c 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -93,6 +93,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {"wwjs Client.archiveChat(chatId)/unarchiveChat(chatId) → Promise<boolean> (index.d.ts:46,328) — the CLIENT methods, not Chat.archive(), which resolves void; baileys chatModify({archive,lastMessages}, jid) (Types/Chat.d.ts:63-66) needs the chat's last message, so a chat with no known history resolves false rather than throwing",},blockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getBlockedContacts: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.getBlockedContacts() → Contact[] models (index.d.ts:97) — mapped to neutral ids via readWid; baileys fetchBlocklist() → bare jid strings (Socket/chats.d.ts:41; chats.js:263-274) — an unanswered query would resolve [] (query() swallows its timeout), so the adapter bounds it with its own deadline',+ },checkNumberExists: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },clearChatMessages: {wwjs: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 1233a651b..73a75b097 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -993,6 +993,13 @@ export interface IWhatsAppEngine {getProfilePicture(contactId: string): Promise<string | null>;blockContact(contactId: string): Promise<void>;unblockContact(contactId: string): Promise<void>;+ /**+ * Neutral ids of the contacts this account has blocked — the read half of block/unblockContact.+ * Ids only: whatsapp-web.js resolves full Contact models, but Baileys' blocklist query answers+ * bare jids, and inventing the other fields on one engine would make the two engines claim+ * different things about the same account.+ */+ getBlockedContacts(): Promise<string[]>;/*** Save a contact to the account's addressbook, or edit an existing entry. `contactId` is adiff --git a/src/modules/contact/contact.controller.spec.ts b/src/modules/contact/contact.controller.spec.tsindex 1a01358bc..9af76b0ed 100644--- a/src/modules/contact/contact.controller.spec.ts+++ b/src/modules/contact/contact.controller.spec.ts@@ -13,6 +13,7 @@ describe('ContactController', () => {deleteContact: jest.fn(),blockContact: jest.fn(),unblockContact: jest.fn(),+ getBlockedContacts: jest.fn(),};const controller = new ContactController(service as unknown as ContactService);@@ -80,6 +81,12 @@ describe('ContactController', () => {});});+ it('getBlockedContacts returns the service list as a bare array', async () => {+ service.getBlockedContacts.mockResolvedValue(['[email protected]', '[email protected]']);+ await expect(controller.getBlockedContacts('s1')).resolves.toEqual(['[email protected]', '[email protected]']);+ expect(service.getBlockedContacts).toHaveBeenCalledWith('s1');+ });+it('upsertContact passes first/last name from the DTO', async () => {service.upsertContact.mockResolvedValue(undefined);await expect(controller.upsertContact('s1', 'c1', { firstName: 'A', lastName: 'B' })).resolves.toEqual({diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 9d8dd538f..520b91f4a 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -64,6 +64,24 @@ export class ContactController {return { pictures };}+ @Get('blocked')+ @ApiOperation({+ summary: 'List the contacts this account has blocked',+ description:+ 'The read half of the block/unblock endpoints. A bare array of neutral contact ids — ids ' ++ 'only, because that is the honest common subset: whatsapp-web.js resolves full contact ' ++ "models but Baileys' blocklist query answers bare jids, and inventing the other fields on " ++ 'one engine would make the two engines claim different things about the same account.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'Blocked contact ids', type: [String] })+ @ApiResponse({ status: 503, description: 'WhatsApp did not answer the blocklist query — retry shortly' })+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ // NOTE: declared BEFORE @Get(':contactId') so the literal segment wins over the param route.+ async getBlockedContacts(@Param('sessionId') sessionId: string) {+ return this.contactService.getBlockedContacts(sessionId);+ }+@Get(':contactId')@ApiOperation({ summary: 'Get a specific contact by ID' })@ApiParam({ name: 'sessionId', description: 'Session ID' })diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex aecc6affd..a7e0f0520 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -14,6 +14,16 @@ describe('ContactService', () => {expect(() => makeService(undefined).getContacts('s1')).toThrow(BadRequestException);});+ it('getBlockedContacts delegates to the engine and returns the bare id list', async () => {+ const getBlockedContacts = jest.fn().mockResolvedValue(['[email protected]']);+ await expect(makeService({ getBlockedContacts }).getBlockedContacts('s1')).resolves.toEqual(['[email protected]']);+ expect(getBlockedContacts).toHaveBeenCalledTimes(1);+ });++ it('getBlockedContacts throws 400 when the session is not started', () => {+ expect(() => makeService(undefined).getBlockedContacts('s1')).toThrow(BadRequestException);+ });+it('caps an unbounded contacts list at the default limit (1000)', async () => {const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));const getContacts = jest.fn().mockResolvedValue(big);diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex cc4b72417..95223d0be 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -33,6 +33,11 @@ export class ContactService {return contact;}+ /** The read half of block/unblock — neutral ids only (the honest common subset of both engines). */+ getBlockedContacts(sessionId: string) {+ return this.getEngine(sessionId).getBlockedContacts();+ }+checkNumberExists(sessionId: string, number: string) {return this.getEngine(sessionId).checkNumberExists(number);}