Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): keep transient lid lookup failures from clobbering stored mappings
Yudhi Armyndharis8718bc78fa3d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 14d3dc8c6..d8142a5c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A transient whatsapp-web.js lid-to-phone lookup failure (dead page, rate limit) no longer overwrites a valid stored mapping with a definitive null; the engine method rejects on failure and the HTTP boundary keeps its null-on-failure contract.- Nine whatsapp-web.js group routes answer `404` (`GroupNotFoundError`) when the id is not a group or is unknown, like the guarded settings writes; they previously threw a bare error that surfaced as an opaque `500`.- The cold-reachout budget is charged only after the group engine call resolves; a createGroup that 501s (whatsapp-web.js, always) or an add the engine refuses no longer burns the day's allowance for participants never contacted.- block/unblock refuse ids that do not name a person (400, both engines): whatsapp-web.js silently returned false for a group id (answered 200 "blocked" with nothing blocked) and Baileys surfaced an opaque 500 for an unresolvable jid.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 13002d0ca..7d14fb481 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -2520,9 +2520,12 @@ describe('WhatsAppWebJsAdapter.resolveContactPhone (@lid -> phone, #263)', () =>).resolves.toBeNull();});- it('is best-effort: a thrown engine error resolves to null, not a rejection', async () => {+ it('propagates a lookup failure instead of nulling it: a transient error must not read as "no mapping"', async () => {+ // The engine method rejects on failure (dead page, evaluation error, rate limit) so the lid+ // resolver never mistakes one for a definitive negative; the HTTP boundary+ // (ContactService.resolveContactPhone) is where null-on-failure is produced.const adapter = readyAdapter(jest.fn().mockRejectedValue(new Error('Evaluation failed')));- await expect(adapter.resolveContactPhone('123@lid')).resolves.toBeNull();+ await expect(adapter.resolveContactPhone('123@lid')).rejects.toThrow('Evaluation failed');});});diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 43b2ef0c5..eeaf80c74 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -83,19 +83,16 @@ export class WwebjsContacts {async resolveContactPhone(contactId: string): Promise<string | null> {this.host.ensureReady();- try {- // Queried one id at a time: the batch form is prone to "Evaluation failed" and rate-limiting- // (whatsapp-web.js #3857/#3969). `pn` is the phone JID (`<digits>@c.us`) when the account knows- // the mapping; best-effort, so a missing mapping or any failure resolves to null.- const [result] = await this.client().getContactLidAndPhone([contactId]);- const pn = result?.pn;- return pn ? pn.replace(/@c\.us$/i, '').replace(/\D/g, '') || null : null;- } catch (error) {- this.host.logger.debug(`resolveContactPhone failed for ${contactId}`, {- error: error instanceof Error ? error.message : String(error),- });- return null;- }+ // Queried one id at a time: the batch form is prone to "Evaluation failed" and rate-limiting+ // (whatsapp-web.js #3857/#3969). `pn` is the phone JID (`<digits>@c.us`) when the account knows+ // the mapping. An empty/absent pn RESOLVES to null (a definitive "no mapping" answer); a thrown+ // error PROPAGATES - the lid resolver must not mistake a transient failure (dead page,+ // evaluation error, rate limit) for "this contact has no phone" and clobber a valid stored+ // mapping with it. The HTTP route that promises null-on-failure swallows at its boundary+ // (contact.service.resolveContactPhone).+ const [result] = await this.client().getContactLidAndPhone([contactId]);+ const pn = result?.pn;+ return pn ? pn.replace(/@c\.us$/i, '').replace(/\D/g, '') || null : null;}async upsertContact(contactId: string, firstName: string, lastName = ''): Promise<void> {diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 4d3b55828..6424ec5a3 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -207,4 +207,18 @@ describe('ContactService', () => {expect(upsertContact).toHaveBeenCalled();});});++ describe('resolveContactPhone null-on-failure boundary', () => {+ it('returns null (200 contract) when the engine lookup throws', async () => {+ const svc = makeService({+ resolveContactPhone: jest.fn().mockRejectedValue(new Error('Protocol error: Target closed')),+ });+ await expect(svc.resolveContactPhone('s1', '123@lid')).resolves.toBeNull();+ });++ it('returns the engine answer verbatim on success', async () => {+ const svc = makeService({ resolveContactPhone: jest.fn().mockResolvedValue('628123') });+ await expect(svc.resolveContactPhone('s1', '123@lid')).resolves.toBe('628123');+ });+ });});diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex 5ba04bb59..7014af064 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -46,8 +46,18 @@ export class ContactService {return this.getEngine(sessionId).getNumberId(number);}- resolveContactPhone(sessionId: string, contactId: string) {- return this.getEngine(sessionId).resolveContactPhone(contactId);+ /**+ * The HTTP route promises null when the engine cannot map the id (docs/06 and the ApiResponse+ * text), and that includes "the lookup itself failed": a dead page, an evaluation error or a+ * rate limit answers 200 null, not a 5xx. The ENGINE method rejects on those (the lid resolver+ * needs the distinction), so swallow here at the boundary.+ */+ async resolveContactPhone(sessionId: string, contactId: string): Promise<string | null> {+ try {+ return await this.getEngine(sessionId).resolveContactPhone(contactId);+ } catch {+ return null;+ }}getProfilePicture(sessionId: string, contactId: string) {diff --git a/src/modules/session/session-lid-resolver.service.spec.ts b/src/modules/session/session-lid-resolver.service.spec.tsindex c59a82111..432f01c25 100644--- a/src/modules/session/session-lid-resolver.service.spec.ts+++ b/src/modules/session/session-lid-resolver.service.spec.ts@@ -79,6 +79,19 @@ describe('SessionLidResolver', () => {expect(remember).not.toHaveBeenCalled();});+ // The wwjs adapter used to swallow every lookup failure into null, so this guard was dead on+ // that engine: a dead page or rate-limit read as "no mapping" and clobbered a valid stored+ // row. The adapter now rejects on failure (the HTTP boundary nulls instead), which is what+ // makes the guard above real; this case pins that the persisted-negative path still fires for+ // a DEFINITIVE null (the engine answered: no mapping).+ it('persists a definitive null (the engine answered no-mapping) even on wwjs', async () => {+ resolveContactPhone.mockResolvedValue(null);++ await resolver.resolveSenderPhone('s1', '222@lid');++ expect(remember).toHaveBeenCalledWith('222', null, 's1');+ });+it('does not persist when there is no live engine (transient, not definitive)', async () => {await resolver.resolveSenderPhone('not-started', '111@lid');