Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop reading an unanswered picture lookup as "no picture"
Yudhi Armyndharis4a48300fe5a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e7786e7b..d75dbc007 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A profile picture lookup that WhatsApp never answered no longer reads as "this contact has no picture"** — the route answered `200` with `url: null` after a silent minute, which is the same answer a contact without a picture gives, so a caller had no way to tell them apart; it now answers `503`. Passing the engine's own timeout would not have been enough on its own, because the resulting error landed in the catch that produces that same `null`. The batch lookup is unchanged: a per-id failure there is documented as `null` and stays that way.- **The last fifteen writes that reported success without confirmation now report it** — the addressbook saves, block and unblock, the archive/unread/clear/delete chat actions, delete-for-me and star, the four label writes and a call rejection all go through an engine call that discards its own result, so each answered `200` whether WhatsApp applied the change or never replied; a rejected call was the sharpest case, since the gateway also published a `rejected` outcome for a rejection nothing had acknowledged. All now share the request budget and answer `503` when no confirmation arrives.- **A dead connection is no longer reported as a bad invite code or a permissions refusal** — joining by invite and updating participants both fail without ever entering their `catch`, because the engine resolves an unanswered query rather than rejecting it: the join landed on the same "invite code may be invalid" `400` as a genuinely bad code, and a participant update on the same `403` as a missing admin right. Both now share the request budget and answer `503`; an answered-but-empty result still means what it meant.- **Marking a chat read no longer answers a bare `500` when WhatsApp stays silent** — the read receipt reaches a library helper that destructures the query result, so an unanswered one threw a raw `TypeError` that nothing could classify; it now shares the same 30-second budget and answers `503`. The media send path fails the same way and is deliberately left alone: a send is not repeatable, and `503` is a status the SDKs retry, so making it one would trade an opaque failure for duplicate messages.diff --git a/openapi.json b/openapi.jsonindex 516f15d96..04a51d734 100644--- a/openapi.json+++ b/openapi.json@@ -4028,6 +4028,9 @@}}}+ },+ "503": {+ "description": "WhatsApp did not answer the lookup. Deliberately not reported as `url: null` — that is the same answer a contact with no picture gives, and a caller cannot tell them apart."}},"summary": "Get profile picture URL for a contact",diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex d21611df9..9a3a570dc 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -3,6 +3,7 @@ import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.import { resolveMediaBuffer } from './baileys-messaging';import { type createLogger } from '../../common/services/logger.service';import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';+import { EngineTransportError } from '../../common/errors/engine-transport.error';/*** Contacts/profile/chats-domain operations extracted from BaileysAdapter. The adapter keeps the@@ -44,8 +45,21 @@ export class BaileysContacts {async getProfilePicture(contactId: string): Promise<string | null> {this.host.ensureReady();try {- return (await this.sock().profilePictureUrl(contactId, 'image')) ?? null;+ // The library also accepts a timeoutMs third argument, but passing it only converts the+ // stall into a throw — which this catch would swallow into the same null. The deadline has+ // to be ours, and the catch has to let it past.+ const url = await withQueryDeadline(+ this.sock().profilePictureUrl(contactId, 'image'),+ this.queryBudgetMs,+ 'WhatsApp did not answer the profile picture lookup in time',+ );+ return url ?? null;} catch (err) {+ // A no-picture verdict arrives as a thrown error, so this catch must keep swallowing — but a+ // query that never came back is not a verdict about the picture.+ if (err instanceof EngineTransportError) {+ throw err;+ }this.host.logger.debug('profilePictureUrl failed; no picture or hidden', {contactId,error: err instanceof Error ? err.message : String(err),diff --git a/src/engine/adapters/baileys-profile-picture.spec.ts b/src/engine/adapters/baileys-profile-picture.spec.tsnew file mode 100644index 000000000..d7de3b3ea--- /dev/null+++ b/src/engine/adapters/baileys-profile-picture.spec.ts@@ -0,0 +1,54 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * getProfilePicture answers `null` for a contact with no picture, for one whose privacy settings+ * hide it, and — until now — for a query that was never answered. That last one was confirmed live:+ * the route returned HTTP 200 {"url":null} after 60.03s.+ *+ * The catch here is load-bearing and must KEEP swallowing: a genuine "no picture" arrives as a+ * thrown error from the library. Only the deadline may pass through it.+ */+const never = (): Promise<never> => new Promise<never>(() => undefined);++function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysContacts {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },+ normalizedSelfJid: () => '[email protected]',+ listContacts: () => [],+ findContact: () => null,+ resolvePhone: () => null,+ listChats: () => [],+ lastMessage: () => null,+ toEngineJid: (j: string) => j,+ } as unknown as BaileysContactsHost;+ return new BaileysContacts(host, budgetMs);+}++describe('getProfilePicture', () => {+ it('reports an unanswered lookup instead of "no picture"', async () => {+ await expect(+ contacts({ profilePictureUrl: jest.fn(never) }, 15).getProfilePicture('[email protected]'),+ ).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still answers null when the library reports no picture', async () => {+ const profilePictureUrl = jest.fn().mockRejectedValue(new Error('item-not-found'));+ await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).resolves.toBeNull();+ });++ it('still answers null when the library resolves nothing', async () => {+ const profilePictureUrl = jest.fn().mockResolvedValue(undefined);+ await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).resolves.toBeNull();+ });++ it('still returns the url', async () => {+ const profilePictureUrl = jest.fn().mockResolvedValue('https://pps.whatsapp.net/x.jpg');+ await expect(contacts({ profilePictureUrl }, 500).getProfilePicture('[email protected]')).resolves.toBe(+ 'https://pps.whatsapp.net/x.jpg',+ );+ });+});diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 75719bc0c..b27989b57 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -120,6 +120,12 @@ export class ContactController {description: 'Profile picture URL',type: ProfilePictureResponseDto,})+ @ApiResponse({+ status: 503,+ description:+ 'WhatsApp did not answer the lookup. Deliberately not reported as `url: null` — that is the ' ++ 'same answer a contact with no picture gives, and a caller cannot tell them apart.',+ })async getProfilePicture(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {const url = await this.contactService.getProfilePicture(sessionId, contactId);return { url };