Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): finish applying #762's honesty rule to status posts and acks (#773)

Yudhi Armyndharis0536840a549f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37bfae4fb..147686192 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -81,6 +81,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
untouched, since failing `npm install` outright is the trade the flag exists to avoid. Both fixes are
regression-tested, including the `--best-effort` path.
+- **A status post no longer claims success it cannot prove, and no longer throws away a readable id.**
+ #762 established that `whatsapp-web.js` can *resolve* `undefined` instead of throwing, and that reporting
+ that as success is unrecoverable — so a send with no message back now fails loudly. Status posts were
+ left on the old behavior: they returned **201** with an empty `statusId` and a `new Date()` invented on
+ the spot, for a status that may never have been published. Their case is in fact simpler than a send's —
+ the engine returns the status model before reaching the lookup that makes a send's empty result
+ ambiguous, so no message back means nothing was posted, full stop — and it now surfaces as a `500`
+ carrying that reason rather than a fabricated success. Separately, the id was read only as `_serialized`,
+ so on a build that renamed the field to `$1` (#747) a status that posted perfectly well came back with
+ `statusId: ""` — and since `deleteStatus` takes that id as its revoke handle, the status could never be
+ taken down. The rename fallback the send path has since #762 is now applied here too. The same fallback
+ is added to the ack listener, where an unreadable id previously stranded a message at `sent` forever —
+ including the `failed` ack that is the only signal a send was rejected. Baileys is unaffected: its send
+ and status paths already agree with each other.
+
- **The Message Tester no longer invents HTTP status codes.** Its result banner rendered one of two
hardcoded strings — `200 OK - Success` or `400 - Failed` — for every outcome, in all eleven locales.
Neither number was ever read from the response. Send routes return **201**, not 200, so the success
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index b14daad94..210ec4b39 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -15,7 +15,7 @@ import {
import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';
import * as fs from 'fs';
import * as qrcode from 'qrcode';
-import { UnprocessableEntityException } from '@nestjs/common';
+import { InternalServerErrorException, UnprocessableEntityException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';
@@ -1121,6 +1121,38 @@ describe('WhatsAppWebJsAdapter status methods', () => {
},
);
+ it('postTextStatus reads a renamed `$1` id when the dependency has not normalized it', async () => {
+ // The id is right there — spending the "posted, id unknown" sentinel on it would hand the caller a
+ // statusId that deleteStatus can never revoke, for a status that really is live.
+ const sendMessage = jest.fn().mockResolvedValue({ id: { $1: 'STATUS_RENAMED' }, timestamp: 1700000012 });
+ const result = await readyAdapter({ sendMessage }).postTextStatus('hello', options);
+ expect(result.statusId).toBe('STATUS_RENAMED');
+ });
+
+ it('postTextStatus reports an unreadable id as posted-id-unknown rather than inventing one', async () => {
+ const sendMessage = jest.fn().mockResolvedValue({ id: { someFutureName: 'X' }, timestamp: 1700000013 });
+ const result = await readyAdapter({ sendMessage }).postTextStatus('hello', options);
+ // A Message came back, so the post itself is proven — only the id is unreadable.
+ expect(result.statusId).toBe('');
+ });
+
+ it.each([['postTextStatus'], ['postImageStatus'], ['postVideoStatus']] as const)(
+ '%s fails rather than claim a status that may never have been published',
+ async method => {
+ // whatsapp-web.js resolves undefined when the chat could not be resolved — nothing was posted.
+ // Returning a 201 with a fabricated timestamp here is unrecoverable; a visible failure is not.
+ const sendMessage = jest.fn().mockResolvedValue(undefined);
+ const adapter = readyAdapter({ sendMessage });
+ const call =
+ method === 'postTextStatus' ? adapter.postTextStatus('hello', options) : adapter[method](media, options);
+ // Assert the TYPE, not just the text: a bare Error is a 500 whose body says only "Internal server
+ // error" (no global filter — see message-not-found.error.spec.ts), which would silently discard
+ // the reason this throw exists to deliver.
+ await expect(call).rejects.toBeInstanceOf(InternalServerErrorException);
+ await expect(call).rejects.toThrow(/may not have been published/);
+ },
+ );
+
it('deleteStatus revokes via client.revokeStatusMessage(statusId)', async () => {
const revokeStatusMessage = jest.fn().mockResolvedValue(undefined);
await readyAdapter({ sendMessage: jest.fn(), revokeStatusMessage }).deleteStatus('STATUS1');
@@ -2088,6 +2120,16 @@ describe('WhatsAppWebJsAdapter message_ack (unreadable id)', () => {
expect(onMessageAck).toHaveBeenCalledWith('ACKED_MSG', expect.any(String));
});
+ it('reads a renamed `$1` id when the dependency has not normalized it', () => {
+ // The send path recovers from the rename; the ack path must too, or a message sent on an unpatched
+ // build can never leave SENT — including via `ack < 0`, the one signal that it failed outright.
+ const { onMessageAck, client } = wireAckHandler();
+
+ client.emit('message_ack', { id: { $1: 'ACKED_RENAMED' } }, 3);
+
+ expect(onMessageAck).toHaveBeenCalledWith('ACKED_RENAMED', expect.any(String));
+ });
+
it('drops an ack whose id cannot be read instead of passing undefined on', () => {
// An undefined id reaches the ack UPDATE as `waMessageId = NULL`, which matches nothing (`x = NULL`
// is never true in SQL). The ack would advance no row and still burn its one-shot retry, leaving the
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 2a54d6f79..6cd06f9b6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1,4 +1,5 @@
import { EventEmitter } from 'events';
+import { InternalServerErrorException } from '@nestjs/common';
import { Client, LocalAuth, MessageMedia, MessageTypes, WAState, type Message } from 'whatsapp-web.js';
import * as qrcode from 'qrcode';
import * as path from 'path';
@@ -602,7 +603,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// so the message stays at SENT with only a misleading "no status row advanced" in the log. Drop
// it here, where the reason is still visible. (Note this differs from the reaction path below,
// where `findOne` DROPS an undefined key instead of nulling it and matches an arbitrary row.)
- const ackId = (msg.id as unknown as SerializedWid | undefined)?._serialized;
+ // Read `$1` before giving up, as the send path does (#747): a build that renamed the field still
+ // has a perfectly good id here, and dropping it strands the message at SENT — including the
+ // `ack < 0` that is the only signal a send failed.
+ const rawId = msg.id as unknown as SerializedWid | undefined;
+ const ackId = rawId?._serialized ?? rawId?.$1;
if (!ackId) {
this.logger.warn('Dropping an ack whose message id could not be read', { ack });
return;
@@ -1864,10 +1869,35 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return { id: id?._serialized ?? id?.$1 ?? '', timestamp: msg.timestamp };
}
+ /**
+ * The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a
+ * send's. `Injected/Utils.js` builds the status model and returns it from the `isStatus` branch before
+ * ever reaching the `Msg.get` miss that makes an ordinary send ambiguous — so the only way back with no
+ * message is `Client.js`'s `if (!chat) return null`, i.e. nothing was posted at all. Not an ambiguity:
+ * a plain failure, which was previously dressed up as a `201` carrying a `new Date()` invented for a
+ * status that never existed.
+ *
+ * Thrown as an `InternalServerErrorException` rather than a bare `Error` because there is no global
+ * exception filter (see `message-not-found.error.spec.ts`), so a bare `Error` reaches the caller as
+ * `{"statusCode":500,"message":"Internal server error"}` — and unlike a send, which routes its message
+ * into the `message:failed` hook, HTTP is the only consumer a status post has. The same 500, with the
+ * reason surviving.
+ *
+ * A present `Message` proves the post happened, so an id it cannot read there carries the same empty
+ * sentinel `toMessageResult` uses. Read `$1` before falling back to it (#747): the sentinel means
+ * "posted, id unknown", and `deleteStatus` takes this id as the revoke handle — spending it on an id
+ * that was readable all along leaves a status nothing can revoke.
+ */
private toStatusResult(msg: Message | undefined): StatusResult {
- const ts = msg?.timestamp ? new Date(msg.timestamp * 1000) : new Date();
+ if (!msg) {
+ throw new InternalServerErrorException(
+ 'the engine returned no message for this status post, so it may not have been published — check your status before retrying',
+ );
+ }
+ const id = msg.id as unknown as SerializedWid | undefined;
+ const ts = msg.timestamp ? new Date(msg.timestamp * 1000) : new Date();
return {
- statusId: msg?.id?._serialized ?? '',
+ statusId: id?._serialized ?? id?.$1 ?? '',
timestamp: ts,
expiresAt: new Date(ts.getTime() + 24 * 3_600_000),
};