Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(contacts): cover toContact mapping and declare the 503 on the contacts route

Deyvis17GY32e9f7bea51a
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index c6688878d..22bede2aa 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2278,7 +2278,7 @@ 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 · `409` conflict or engine not ready (retryable)
+**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `409` conflict or engine not ready (retryable) · `503` the WhatsApp page died while reading contacts (retry shortly)
#### GET /api/sessions/:sessionId/contacts/blocked
diff --git a/openapi.json b/openapi.json
index 9bd863eae..a1e5f1582 100644
--- a/openapi.json
+++ b/openapi.json
@@ -4398,6 +4398,9 @@
},
"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. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."
+ },
+ "503": {
+ "description": "The WhatsApp page died while reading contacts, retry shortly"
}
},
"summary": "Get all contacts for a session",
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 8a447afb3..8abf45b0b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5624,15 +5624,92 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-
},
);
- it('detects a transport error from a getter too (getContacts)', async () => {
+ it('converts a transport error from a getter into a 503 (getContacts)', async () => {
const getContacts = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));
const { adapter, onDisconnected } = readyAdapter({ getContacts });
- await expect(adapter.getContacts()).rejects.toThrow('Protocol error: Target closed');
-
- expect(onDisconnected).toHaveBeenCalledTimes(1);
+ await expect(adapter.getContacts()).rejects.toBeInstanceOf(EngineTransportError);
expect(onDisconnected).toHaveBeenCalledWith('Page transport error during getContacts');
- expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ // #1476: a raw wwebjs contact carries its wid under `_serialized` or, on a renamed WA Web build,
+ // under `$1` (see readWid). Both shapes must map to the same library-agnostic Contact.
+ it('maps both the `_serialized` and the renamed `$1` id shapes in getContacts', async () => {
+ const raw = [
+ {
+ id: { _serialized: '[email protected]' },
+ name: 'Alice',
+ pushname: 'Ally',
+ number: '111',
+ isMyContact: true,
+ isBlocked: false,
+ },
+ { id: { $1: '[email protected]' }, name: 'Bob', pushname: 'Bobby', number: '222', isMyContact: false, isBlocked: true },
+ ];
+ const getContacts = jest.fn().mockResolvedValue(raw);
+ const { adapter } = readyAdapter({ getContacts });
+
+ await expect(adapter.getContacts()).resolves.toEqual([
+ { id: '[email protected]', name: 'Alice', pushName: 'Ally', number: '111', isMyContact: true, isBlocked: false },
+ { id: '[email protected]', name: 'Bob', pushName: 'Bobby', number: '222', isMyContact: false, isBlocked: true },
+ ]);
+ });
+
+ // #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 () => {
+ const good1 = { id: { _serialized: '[email protected]' }, name: 'Alice', number: '111' };
+ const unreadable = { id: {}, name: 'Ghost', number: '000' };
+ const good2 = { id: { $1: '[email protected]' }, name: 'Bob', number: '222' };
+ const getContacts = jest.fn().mockResolvedValue([good1, unreadable, good2]);
+ const { adapter } = readyAdapter({ getContacts });
+ const logger = (adapter as unknown as { logger: { warn: (m: string) => void } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+
+ const contacts = await adapter.getContacts();
+
+ expect(contacts.map(c => c.id)).toEqual(['[email protected]', '[email protected]']);
+ expect(warnSpy).toHaveBeenCalledWith('Skipped 1 contact(s) without a serialized id');
+ });
+
+ // A rejection that carries no transport-death signature is an ordinary failure, not a dead page —
+ // it must reach the caller unchanged and leave the session READY, unlike the 503 case above.
+ it('propagates a non-transport rejection from getContacts untouched and leaves the session READY', async () => {
+ const getContacts = jest.fn().mockRejectedValue(new Error('Evaluation failed: TypeError: x is not a function'));
+ const { adapter, onDisconnected } = readyAdapter({ getContacts });
+
+ await expect(adapter.getContacts()).rejects.toThrow('Evaluation failed: TypeError: x is not a function');
+
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ });
+
+ it('getContactById maps the renamed `$1` id shape too', async () => {
+ const getContactById = jest.fn().mockResolvedValue({
+ id: { $1: '[email protected]' },
+ name: 'Cara',
+ pushname: 'C',
+ number: '333',
+ isMyContact: true,
+ isBlocked: false,
+ });
+ const { adapter } = readyAdapter({ getContactById });
+
+ await expect(adapter.getContactById('[email protected]')).resolves.toEqual({
+ name: 'Cara',
+ pushName: 'C',
+ number: '333',
+ isMyContact: true,
+ isBlocked: false,
+ });
+ });
+
+ it('getContactById returns null for an entry with no readable id', async () => {
+ const getContactById = jest.fn().mockResolvedValue({ id: {}, name: 'Ghost', number: '000' });
+ const { adapter } = readyAdapter({ getContactById });
+
+ await expect(adapter.getContactById('[email protected]')).resolves.toBeNull();
});
// joinGroupViaInviteCode answers 503 for a transport failure (a refused invite is no longer
diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.ts
index eeef5566b..bbeea6944 100644
--- a/src/engine/adapters/wwebjs-contacts.ts
+++ b/src/engine/adapters/wwebjs-contacts.ts
@@ -28,7 +28,7 @@ export class WwebjsContacts {
* unguarded (the shape that lets a single bad entry reject the whole request).
*/
private toContact(c: RawWwebjsContact): Contact | null {
- const id = readWid(c.id as unknown as SerializedWid);
+ const id = readWid(c.id);
if (!id) return null;
return {
id,
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index e37532b0b..0f93f230a 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -28,6 +28,7 @@ export class ContactController {
type: [ContactDto],
})
@ApiResponse({ status: 400, description: 'Session not ready' })
+ @ApiResponse({ status: 503, description: 'The WhatsApp page died while reading contacts, retry shortly' })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
@ApiQuery({ name: 'limit', required: false, description: 'Max contacts to return (1–1000, default 1000)' })
@ApiQuery({ name: 'offset', required: false, description: 'Number of contacts to skip (for paging)' })