Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): give three failure paths their documented status

Yudhi Armyndharisf18709c52a23
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b23861c4d..de1a4f32a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- whatsapp-web.js `deleteChannel` classifies a dead browser page as the documented `503` plus an early death signal, like every other channel call; it reached the client directly, so a crash there answered an opaque `500` while the session still reported READY.
+- Baileys block/unblock answer `400` when WhatsApp cannot map the id between the phone-number and privacy-id dialects (no mapping either way, or an id that is neither). The library refuses those with a Boom the gateway could not classify, so a well-formed request got an opaque `500`; whatsapp-web.js already answered `400` for the same cause.
+- docs/06 states that editing another account's message answers `403`, not `500`. Both engines raise the refusal as `EngineRefusedError`, and the published contract already declared `403` with no `500` on that route.
- Follow-ups from the accessibility review: the plugin ConfigField derives a per-field id (a hardcoded id collided on any schema with two booleans, making the second label toggle the first checkbox), the 10 codemod-touched files are Prettier-clean (9 failed the dashboard format gate), and six more multi-line labels in MessageTester are wired.
- Dashboard accessibility: 55 form labels are associated with their controls (`htmlFor`/`id`, no duplicates or orphans), the muted-text token meets AA on both themes (4.76:1 light, 5.71:1 dark), and the primary button uses dark text on the green (9.0:1, from 1.98:1).
- Follow-ups from the batch review: the chain-boot e2e sets MAIN_DATABASE_SYNCHRONIZE=false explicitly (the env's absence defaults to synchronize=true, so the main chain was never exercised), the drift gate classifies statements against the two known shape families (column-type rebuild, index-name drift) instead of blanket-filtering every index/DROP statement, the shared delivery recorder strips the raw error before the persistence spread, and the ignore-pattern list deduplicates.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 11030962b..d7430fc8d 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2062,7 +2062,7 @@ The edited message keeps its original id.
{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1760000000 }
```
-**Errors:** `400` session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` message not found · `500` engine error (e.g. editing another account's message, which WhatsApp forbids) · `409` conflict or engine not ready (retryable)
+**Errors:** `400` session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR, or the engine refused the edit (only the account's own messages are editable, which WhatsApp enforces) · `404` message not found · `409` conflict or engine not ready (retryable)
#### POST /api/sessions/:sessionId/messages/send-bulk
diff --git a/src/engine/adapters/baileys-block-unresolvable-id.spec.ts b/src/engine/adapters/baileys-block-unresolvable-id.spec.ts
new file mode 100644
index 000000000..d36538228
--- /dev/null
+++ b/src/engine/adapters/baileys-block-unresolvable-id.spec.ts
@@ -0,0 +1,81 @@
+import { Boom } from '@hapi/boom';
+import type { WASocket } from '@whiskeysockets/baileys';
+import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';
+import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+
+/**
+ * `updateBlockStatus` maps the id between the phone-number and privacy-id dialects before it sends
+ * anything, and refuses an id it cannot map with `Boom(..., { statusCode: 400 })` (chats.js has
+ * three such throws: no PN for a lid, no LID for a phone number, and an id that is neither). Boom is
+ * not an HttpException, so those escaped as an opaque `500 Internal server error` for a caller whose
+ * request was well-formed and whose id the API itself accepts.
+ *
+ * whatsapp-web.js already answers `400 RecipientUnreachableError` for the same cause on the send
+ * path ("No LID for user"), so this is the engine-parity mapping rather than a new contract.
+ */
+const host = (sock: Record<string, jest.Mock>): BaileysContactsHost =>
+ ({
+ 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;
+
+const contacts = (sock: Record<string, jest.Mock>): BaileysContacts => new BaileysContacts(host(sock), 500);
+
+describe('block/unblock on an id WhatsApp cannot map between dialects', () => {
+ it.each([
+ ['blockContact', (c: BaileysContacts) => c.blockContact('[email protected]')],
+ ['unblockContact', (c: BaileysContacts) => c.unblockContact('[email protected]')],
+ ])('%s answers 400, not an opaque 500', async (_name, call) => {
+ const updateBlockStatus = jest
+ .fn()
+ .mockRejectedValue(
+ new Boom('Unable to resolve LID for PN JID: [email protected]', { statusCode: 400 }),
+ );
+ await expect(call(contacts({ updateBlockStatus }))).rejects.toBeInstanceOf(RecipientUnreachableError);
+ });
+
+ it('blockContact answers 400 for a privacy id with no phone mapping', async () => {
+ // The @lid half of the same guard: block resolves a lid to its phone number first.
+ const updateBlockStatus = jest
+ .fn()
+ .mockRejectedValue(new Boom('Unable to resolve PN JID for LID: 159442138038327@lid', { statusCode: 400 }));
+ await expect(contacts({ updateBlockStatus }).blockContact('159442138038327@lid')).rejects.toBeInstanceOf(
+ RecipientUnreachableError,
+ );
+ });
+
+ it('names the contact id so the caller knows which one failed', async () => {
+ const updateBlockStatus = jest.fn().mockRejectedValue(new Boom('Unable to resolve LID', { statusCode: 400 }));
+ await expect(contacts({ updateBlockStatus }).blockContact('[email protected]')).rejects.toThrow(
+ /628123456789@s\.whatsapp\.net/,
+ );
+ });
+
+ /**
+ * The discriminating half. Only a 400 means "this id cannot be used"; a dropped connection carries
+ * DisconnectReason.connectionClosed (428) and must stay a transport failure, or a dead socket
+ * would be reported to the caller as a bad contact id.
+ */
+ it('leaves a non-400 Boom alone', async () => {
+ const updateBlockStatus = jest.fn().mockRejectedValue(new Boom('Connection Closed', { statusCode: 428 }));
+ const rejection = contacts({ updateBlockStatus }).blockContact('[email protected]');
+ await expect(rejection).rejects.not.toBeInstanceOf(RecipientUnreachableError);
+ await expect(rejection).rejects.toThrow(/Connection Closed/);
+ });
+
+ it('leaves the unconfirmed-write deadline alone', async () => {
+ const updateBlockStatus = jest.fn(() => new Promise<never>(() => undefined));
+ await expect(
+ new BaileysContacts(host({ updateBlockStatus }), 15).blockContact('[email protected]'),
+ ).rejects.toBeInstanceOf(EngineTransportError);
+ });
+});
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 058692191..19f48e6a0 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -4,6 +4,7 @@ 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';
+import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';
/**
* Contacts/profile/chats-domain operations extracted from BaileysAdapter. The adapter keeps the
@@ -101,15 +102,41 @@ export class BaileysContacts {
await this.confirmed(this.sock().removeContact(this.host.toEngineJid(contactId)), 'the contact removal');
}
+ /**
+ * `updateBlockStatus` maps the id between the phone-number and privacy-id dialects before it sends
+ * anything, and refuses one it cannot map with `Boom(..., { statusCode: 400 })`: no phone number
+ * for a lid, no lid for a phone number, or an id that is neither. Boom is not an HttpException, so
+ * those reached the caller as an opaque `500 Internal server error` even though the request was
+ * well-formed and the id is a shape this API accepts.
+ *
+ * Only a 400 is folded in. A dropped connection carries `DisconnectReason.connectionClosed` and the
+ * write deadline throws `EngineTransportError`, and reporting either as a bad contact id would send
+ * the caller after the wrong problem. whatsapp-web.js already answers `RecipientUnreachableError`
+ * (400) for the same cause on the send path, so this is the parity mapping, not a new contract.
+ */
+ private async mapUnresolvableId<T>(contactId: string, op: () => Promise<T>): Promise<T> {
+ try {
+ return await op();
+ } catch (error) {
+ const status = (error as { output?: { statusCode?: unknown } } | null)?.output?.statusCode;
+ if (status === 400) throw new RecipientUnreachableError(contactId);
+ throw error;
+ }
+ }
+
async blockContact(contactId: string): Promise<void> {
this.host.ensureReady();
- await this.confirmed(this.sock().updateBlockStatus(contactId, 'block'), 'the block');
+ await this.mapUnresolvableId(contactId, () =>
+ this.confirmed(this.sock().updateBlockStatus(contactId, 'block'), 'the block'),
+ );
this.invalidateBlocklist();
}
async unblockContact(contactId: string): Promise<void> {
this.host.ensureReady();
- await this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock');
+ await this.mapUnresolvableId(contactId, () =>
+ this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock'),
+ );
this.invalidateBlocklist();
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 7d14fb481..1a02084f2 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -6068,6 +6068,11 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
['postTextStatus', (a: WhatsAppWebJsAdapter) => a.postTextStatus('hello', {})],
['deleteStatus', (a: WhatsAppWebJsAdapter) => a.deleteStatus('status@broadcast')],
['getSubscribedChannels', (a: WhatsAppWebJsAdapter) => a.getSubscribedChannels()],
+ // The channel WRITES take the same path: deleteChannel reached the client directly, so a dead
+ // page there surfaced as an opaque 500 under a session still reporting READY, while the route
+ // documents 503. unsubscribeFromChannel is its structural twin and was already wrapped.
+ ['deleteChannel', (a: WhatsAppWebJsAdapter) => a.deleteChannel('1200@newsletter')],
+ ['unsubscribeFromChannel', (a: WhatsAppWebJsAdapter) => a.unsubscribeFromChannel('1200@newsletter')],
])('%s answers EngineTransportError (503) on a dead page', async (_name, call) => {
const adapter = readyAdapter({
setDisplayName: jest.fn().mockRejectedValue(transportError()),
@@ -6078,6 +6083,8 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
sendMessage: jest.fn().mockRejectedValue(transportError()),
revokeStatusMessage: jest.fn().mockRejectedValue(transportError()),
getChannels: jest.fn().mockRejectedValue(transportError()),
+ deleteChannel: jest.fn().mockRejectedValue(transportError()),
+ unsubscribeFromChannel: jest.fn().mockRejectedValue(transportError()),
});
await expect(call(adapter)).rejects.toBeInstanceOf(EngineTransportError);
});
diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.ts
index d9703ac59..75f1624de 100644
--- a/src/engine/adapters/wwebjs-channels.ts
+++ b/src/engine/adapters/wwebjs-channels.ts
@@ -152,7 +152,9 @@ export class WwebjsChannels {
/** Delete a channel. `false` means the channel was not found or the server refused. */
async deleteChannel(channelId: string): Promise<void> {
this.host.ensureReady();
- const ok = await (this.client() as unknown as BusinessClient).deleteChannel(channelId);
+ const ok = await this.withPage('deleteChannel', () =>
+ (this.client() as unknown as BusinessClient).deleteChannel(channelId),
+ );
if (!ok) {
throw new EngineRefusedError(`Failed to delete channel ${channelId}`);
}