Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): stop reporting a failed avatar lookup as "no picture"
Yudhi Armyndharisb4900fd0a4b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b151eb79..d8e3bcf25 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A profile-picture lookup that fails on the whatsapp-web.js engine now answers `503` instead of `{"url": null}`, which is what the route already documented. whatsapp-web.js resolves `undefined` for the only legitimate negative — no picture, or hidden by privacy — so every error reaching the adapter was a failure being reported as "this contact has no avatar". The batch route keeps its best-effort `null`, having no per-id error channel. A dead page during a single-contact lookup likewise stops reading as `404`.- The JavaScript, Python, Go and Java SDKs list `group.join_request`, an event the gateway has accepted and dispatched all along, so a typed client can subscribe to it without casting past its own type.- A webhook's `lastTriggeredAt` is published as a nullable date-time string instead of an object, so a client generated from the contract no longer rejects both of the values the field actually carries. The response itself is unchanged.- The group-list and status routes no longer appear twice in the OpenAPI contract under different path-parameter names, so a client generated from it gets one method per endpoint; the parameters are now `sessionId` and `id`. The URLs themselves are unchanged.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 207f43759..29d4a702f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2198,11 +2198,17 @@ Get the profile picture URL for a contact (best-effort).{ "url": "https://pps.whatsapp.net/v/..." }```-`url` is `null` when there is no picture, the contact's privacy hides it, or it cannot be resolved.+`url` is `null` when there is no picture or the contact's privacy hides it — both are answers. A+lookup that could not reach an answer is **not** reported this way; it answers `503`, so a caller can+tell "this contact has no avatar" from "we could not find out".> The path segment is `profile-picture` (hyphenated), not `profile-pic`.-**Errors:** `400` session is not started · `401` missing/invalid API key+**Errors:** `400` session is not started · `401` missing/invalid API key · `503` the engine could not+complete the lookup++Note the batch route below keeps its best-effort contract: it has no per-id error channel, so a+failed lookup there still appears as `null`.#### GET /api/sessions/:sessionId/contacts/profile-picturesdiff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 68ab0ec9e..760060dd1 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -59,6 +59,11 @@ export class BaileysContacts {} 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.+ //+ // NOTE the whatsapp-web.js adapter does the OPPOSITE on this same interface method, and+ // correctly: there the no-picture verdict is delivered as `undefined`, so every throw is a+ // failure and none of them may become null. Same neutral method, opposite error conventions+ // underneath — do not harmonise the two into a shared helper.if (err instanceof EngineTransportError) {throw err;}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 640769595..074cae6b7 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5913,13 +5913,24 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {await expect(adapter.getProfilePicture('[email protected]')).rejects.toBeInstanceOf(EngineTransportError);});- it('getProfilePicture still maps a genuine lookup failure to null (→ "no picture")', async () => {- // A wwebjs "this contact has no picture" rejects with a ServerError — it is NOT a transport- // signature. It must resolve to null so the API answers "no avatar" rather than a 503.+ it('getProfilePicture maps undefined — the library\'s only "no picture" channel — to null', async () => {+ // `Client.getProfilePicUrl` catches ServerStatusCodeError INSIDE the page and resolves+ // `undefined` (Client.js:2163-2164), then ends `return profilePic ? profilePic.eurl :+ // undefined`. So the no-picture verdict reaches us as a VALUE and never as a rejection.+ const adapter = readyAdapter({ getProfilePicUrl: jest.fn().mockResolvedValue(undefined) });+ await expect(adapter.getProfilePicture('[email protected]')).resolves.toBeNull();+ });++ it('getProfilePicture answers 503 for a page-side exception, which is what the route documents', async () => {+ // This case used to resolve null. The test that pinned it mocked a rejected ServerError —+ // a shape the library cannot deliver, since the page swallows exactly that one into+ // `undefined` above — so it pinned the opposite of the route's own 503 description:+ // "Deliberately not reported as `url: null` — that is the same answer a contact with no+ // picture gives, and a caller cannot tell them apart."const adapter = readyAdapter({getProfilePicUrl: jest.fn().mockRejectedValue(new Error("Server returned error: couldn't get profile picture")),});- await expect(adapter.getProfilePicture('[email protected]')).resolves.toBeNull();+ await expect(adapter.getProfilePicture('[email protected]')).rejects.toBeInstanceOf(EngineTransportError);});});diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex fec9a0600..43b2ef0c5 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -50,6 +50,15 @@ export class WwebjsContacts {isBlocked: contact.isBlocked,};} catch (error) {+ // Unlike the avatar lookup, a throw here can legitimately mean the contact is absent:+ // `window.WWebJS.getContact` has no try/catch and reads `contact.isBusiness` straight off+ // `Contact.find`, so an unknown id throws a TypeError on null. Null (→ 404) stays the answer+ // for that. A dead page is not a missing contact, though, and this was the one lookup that+ // never separated the two.+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'getContactById');+ throw new EngineTransportError(`Transport died while reading contact ${contactId}`);+ }this.host.logger.warn(`Failed to get contact: ${contactId}`, { error: String(error) });return null;}@@ -142,15 +151,21 @@ export class WwebjsContacts {const url = await this.client().getProfilePicUrl(contactId);return url || null;} catch (error) {- // Mirrors getGroupInfo: a dead page and a contact with no picture both land here, and only the- // second may become null (→ service: the contact simply has no avatar). A transport death- // surfaced as "no picture" sends operators debugging the wrong layer — report it and answer 503.- if (this.host.isPageTransportError(error)) {- this.host.reportIfPageTransportError(error, 'getProfilePicture');- throw new EngineTransportError(`Transport died while reading profile picture for ${contactId}`);- }+ // Nothing reaching here is a statement about the avatar, so nothing reaching here may become+ // null. Returning null would answer 200 with {"url": null} — byte-identical to the verdict+ // above — and a caller that caches "no avatar" would record absence for a lookup that never+ // produced one. The page throws for two distinct reasons and we cannot tell them apart from+ // the message: `getChat` failing to resolve the contact at all, or the profile-pic bridge+ // failing. 404 would assert the first; 503 says only that we could not reach an answer, which+ // is all we know.+ //+ // NOTE the Baileys adapter does the OPPOSITE on this same interface method, and correctly:+ // there a no-picture verdict *is* delivered as a throw, so it swallows to null and uses its+ // own deadline to separate a verdict from a non-answer. Do not harmonise the two into a shared+ // helper — the engines disagree about what a throw means.+ this.host.reportIfPageTransportError(error, 'getProfilePicture');this.host.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);- return null;+ throw new EngineTransportError(`Could not read the profile picture for ${contactId}: ${String(error)}`);}}}diff --git a/src/engine/adapters/wwebjs-lookup-failure.spec.ts b/src/engine/adapters/wwebjs-lookup-failure.spec.tsnew file mode 100644index 000000000..39828cbdc--- /dev/null+++ b/src/engine/adapters/wwebjs-lookup-failure.spec.ts@@ -0,0 +1,102 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsContacts } from './wwebjs-contacts';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * A failed lookup must not be reported as a negative result.+ *+ * `Client.getProfilePicUrl` (Client.js:2156-2170) runs in the page and catches+ * `ServerStatusCodeError` **itself**, resolving `undefined` — that is the entire "no picture, or+ * hidden by privacy" verdict. Every other error is rethrown. So on this engine the legitimate+ * negative never arrives as a throw, and a `catch → return null` can only ever turn a genuine+ * failure into "this contact has no avatar", answered `200` with `{"url": null}`.+ *+ * That is the inverse of Baileys, where a no-picture verdict *does* arrive as a throw and swallowing+ * it is correct — which is why the two adapters deliberately do not share a shape here.+ *+ * `getContactById` is a different case and is left alone: `window.WWebJS.getContact` has no+ * try/catch and reads `contact.isBusiness` straight off `Contact.find`, so an unknown contact throws+ * a TypeError on null. There a throw genuinely can mean not-found, and folding it to `null` (→ 404)+ * is defensible. What it lacks entirely, unlike its siblings, is the transport branch: a dead page+ * during a contact lookup currently reads as a clean 404.+ */++const logger = createLogger('wwebjs-lookup-failure.spec');++const PAGE_TRANSPORT_ERROR_PATTERN =+ /protocol error|target closed|targetclosederror|detached frame|session closed|connection closed/i;++function makeContacts(client: Partial<Record<string, jest.Mock>>): {+ contacts: WwebjsContacts;+ reported: string[];+} {+ const reported: string[] = [];+ const isPageTransportError = (error: unknown): boolean =>+ PAGE_TRANSPORT_ERROR_PATTERN.test(error instanceof Error ? error.message : String(error));+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ isPageTransportError,+ reportIfPageTransportError: (error: unknown, context: string) => {+ if (isPageTransportError(error)) reported.push(context);+ },+ } as unknown as WwebjsEngineHost;+ return { contacts: new WwebjsContacts(host), reported };+}++describe('WwebjsContacts.getProfilePicture', () => {+ it('reports no avatar only when the library resolves undefined, which is its ServerStatusCodeError verdict', async () => {+ const getProfilePicUrl = jest.fn().mockResolvedValue(undefined);+ await expect(makeContacts({ getProfilePicUrl }).contacts.getProfilePicture('[email protected]')).resolves.toBeNull();+ });++ it('returns the url when there is one', async () => {+ const getProfilePicUrl = jest.fn().mockResolvedValue('https://example.com/a.jpg');+ await expect(makeContacts({ getProfilePicUrl }).contacts.getProfilePicture('[email protected]')).resolves.toBe(+ 'https://example.com/a.jpg',+ );+ });++ // The defect: a page-side exception carries no transport signature, so it used to fall through to+ // `return null` and reach the caller as "this contact has no avatar" with a 200.+ it('surfaces a page-side exception as a failure instead of reporting "no avatar"', async () => {+ const getProfilePicUrl = jest.fn().mockRejectedValue(new Error('t: t'));+ await expect(makeContacts({ getProfilePicUrl }).contacts.getProfilePicture('[email protected]')).rejects.toBeInstanceOf(+ EngineTransportError,+ );+ });++ it('still surfaces a dead page, and still reports it as a death signal', async () => {+ const getProfilePicUrl = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));+ const { contacts, reported } = makeContacts({ getProfilePicUrl });+ await expect(contacts.getProfilePicture('[email protected]')).rejects.toBeInstanceOf(EngineTransportError);+ expect(reported).toContain('getProfilePicture');+ });++ it('names the contact in the failure, so an operator can tell which lookup died', async () => {+ const getProfilePicUrl = jest.fn().mockRejectedValue(new Error('t: t'));+ await expect(makeContacts({ getProfilePicUrl }).contacts.getProfilePicture('[email protected]')).rejects.toThrow(+ /628999/,+ );+ });+});++describe('WwebjsContacts.getContactById', () => {+ // Not-found semantics are preserved: on this path a throw genuinely can mean the contact is absent.+ it('still answers null for a non-transport error, since an unknown contact throws here', async () => {+ const getContactById = jest+ .fn()+ .mockRejectedValue(new TypeError("Cannot read properties of null (reading 'isBusiness')"));+ await expect(makeContacts({ getContactById }).contacts.getContactById('[email protected]')).resolves.toBeNull();+ });++ it('surfaces a dead page rather than reporting the contact as not found', async () => {+ const getContactById = jest.fn().mockRejectedValue(new Error('Session closed'));+ const { contacts, reported } = makeContacts({ getContactById });+ await expect(contacts.getContactById('[email protected]')).rejects.toBeInstanceOf(EngineTransportError);+ expect(reported).toContain('getContactById');+ });+});