Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): fail the contact list when no unblocked contact reads

Yudhi Armyndharised8083efaa8c
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 1989f0648..77aee3b7b 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2354,7 +2354,7 @@ The `Contact` object returned by the list and get-by-id routes has this shape:
List all contacts for a session, returned as an in-memory paginated window.
-On Baileys the list is the saved address book: contacts with a name saved on the phone (`isMyContact: true`), rebuilt from WhatsApp's app-state contact collection on connect, including after a process restart. A peer known only by its pushname is not listed but still resolves through the get-by-id route below with `isMyContact: false`. whatsapp-web.js lists what the WhatsApp Web page holds, which also includes unsaved chat partners (`isMyContact: false`).
+On Baileys the list is the saved address book: contacts with a name saved on the phone (`isMyContact: true`), rebuilt from WhatsApp's app-state contact collection on connect, including after a process restart. A peer known only by its pushname is not listed but still resolves through the get-by-id route below with `isMyContact: false`. whatsapp-web.js lists what the WhatsApp Web page holds, which also includes unsaved chat partners (`isMyContact: false`). An entry the page cannot read, or one without a readable id (for example a device-scoped id), is left out of the list; the gateway logs a warning with the count, and the response does not signal it.
**Auth:** API key
@@ -2387,7 +2387,7 @@ On Baileys the list is the saved address book: contacts with a name saved on the
]
```
-**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 or the command timed out (retry shortly)
+**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) · `500` engine error, including whatsapp-web.js when some entries could not be read and no unblocked contact was readable (a page-wide failure, not an empty address book) · `503` the WhatsApp page died while reading contacts or the command timed out (retry shortly)
#### GET /api/sessions/:sessionId/contacts/blocked
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 5addcdf40..a385a859a 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -6069,11 +6069,70 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-
const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });
await expect(adapter.getContacts()).rejects.toThrow(
- 'WhatsApp Web could not read any of 3 contact(s): x is not a function',
+ 'WhatsApp Web could not read any unblocked contact (3 failed, 0 without an id, 0 blocked read): x is not a function',
);
expect(onDisconnected).not.toHaveBeenCalled();
});
+ // Models that failed plus rows that came back without a readable id leave nothing to list: the
+ // same page-wide failure, not an empty address book.
+ it('fails the read when the only rows left after a partial failure have no readable id', async () => {
+ const evaluate = jest.fn().mockResolvedValue({ rows: [{ id: {}, number: '1' }], failed: 2, firstError: 'boom' });
+ const { adapter } = readyAdapter({ pupPage: { evaluate } });
+
+ await expect(adapter.getContacts()).rejects.toThrow(
+ 'WhatsApp Web could not read any unblocked contact (2 failed, 1 without an id, 0 blocked read): boom',
+ );
+ });
+
+ it('fails the read when no row at all has a readable id', async () => {
+ const evaluate = jest.fn().mockResolvedValue({ rows: [{ id: {} }, { id: {} }], failed: 0 });
+ const { adapter } = readyAdapter({ pupPage: { evaluate } });
+
+ await expect(adapter.getContacts()).rejects.toThrow(
+ 'WhatsApp Web could not read any unblocked contact (0 failed, 2 without an id, 0 blocked read)',
+ );
+ });
+
+ // getContactModel calls getAlternateUserWid only for an unblocked contact, so a build that breaks
+ // that call still reads every blocked row. Blocked survivors alone say nothing about the rest.
+ it('fails the read when only blocked contacts survive a failure', async () => {
+ const blocked = { id: { _serialized: '[email protected]' }, number: '9', isBlocked: true };
+ const evaluate = jest.fn().mockResolvedValue({
+ rows: [blocked],
+ failed: 499,
+ firstError: 'getAlternateUserWid - Invalid get call using deviceWid',
+ });
+ const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });
+
+ await expect(adapter.getContacts()).rejects.toThrow(
+ 'WhatsApp Web could not read any unblocked contact (499 failed, 0 without an id, 1 blocked read): ' +
+ 'getAlternateUserWid - Invalid get call using deviceWid',
+ );
+ expect(onDisconnected).not.toHaveBeenCalled();
+ });
+
+ it('keeps a blocked-only address book when nothing failed, and an empty one', async () => {
+ const blocked = { id: { _serialized: '[email protected]' }, number: '9', isBlocked: true };
+ const evaluate = jest
+ .fn()
+ .mockResolvedValueOnce({ rows: [blocked], failed: 0 })
+ .mockResolvedValueOnce({ rows: [], failed: 0 });
+ const { adapter } = readyAdapter({ pupPage: { evaluate } });
+
+ await expect(adapter.getContacts()).resolves.toEqual([expect.objectContaining({ id: '[email protected]', isBlocked: true })]);
+ await expect(adapter.getContacts()).resolves.toEqual([]);
+ });
+
+ // The #1720 shape at scale: a single device-scoped wid among ordinary contacts still answers.
+ it('keeps the readable unblocked contacts when one of many could not be read', async () => {
+ const rows = Array.from({ length: 499 }, (_, i) => ({ id: { _serialized: `${i}@c.us` }, number: String(i) }));
+ const evaluate = jest.fn().mockResolvedValue({ rows, failed: 1, firstError: 'x' });
+ const { adapter } = readyAdapter({ pupPage: { evaluate } });
+
+ await expect(adapter.getContacts()).resolves.toHaveLength(499);
+ });
+
// A walk over a large address book that outruns Puppeteer's per-command budget got no answer: a
// 503 the client retries, not a bare 500, and not a death.
it('answers a protocol timeout on the contact walk with a 503 and reports no death', async () => {
diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.ts
index 629960c76..e724c01c2 100644
--- a/src/engine/adapters/wwebjs-contacts.ts
+++ b/src/engine/adapters/wwebjs-contacts.ts
@@ -147,13 +147,6 @@ export class WwebjsContacts {
throw error;
}
- // Every model threw: a systemic page failure (a renamed WA Web module, WWebJS not injected), not
- // one unreadable entry. Answer an error, as before the per-entry catch, rather than an empty
- // address book that a syncing consumer would read as every contact deleted.
- if (raw.length === 0 && unreadable > 0) {
- throw new Error(`WhatsApp Web could not read any of ${unreadable} contact(s): ${firstError}`);
- }
-
// Read every id through readWid (so the `_serialized`->`$1` rename lands here too) and skip
// entries with no readable id, counted and logged like the chats path, rather than dropping
// the whole address book silently.
@@ -167,6 +160,18 @@ export class WwebjsContacts {
}
contacts.push(mapped);
}
+
+ // A systemic page failure (a renamed WA Web module, WWebJS not injected), not one unreadable
+ // entry: answer an error rather than a list a syncing consumer would read as every contact
+ // deleted. That covers models that exist but none mapped, and a failure that left only blocked
+ // contacts: getContactModel skips getAlternateUserWid for a blocked contact, so a blocked row
+ // still reads when that call is broken for everyone else.
+ if ((unreadable > 0 && !contacts.some(c => !c.isBlocked)) || (contacts.length === 0 && skipped > 0)) {
+ throw new Error(
+ `WhatsApp Web could not read any unblocked contact (${unreadable} failed, ${skipped} without an id, ` +
+ `${contacts.length} blocked read)${firstError ? `: ${firstError}` : ''}`,
+ );
+ }
if (skipped > 0) {
this.host.logger.warn(`Skipped ${skipped} contact(s) without a serialized id`);
}