Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): stop two unguarded id reads failing quietly (#765)

Yudhi Armyndharis37aa219baa85
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc79ac3b2..fd59f7818 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
whatsapp-web.js cannot resolve the original (it is no longer in its local store) `revokedId` is
absent and the lookup falls back to `id`, as before. Refs #755.
+- **A failed group creation now reports why it failed.** `whatsapp-web.js` signals a failed
+ `createGroup` by *resolving* with a plain string (`'CreateGroupError: …'`) instead of throwing, and
+ its typings say so (`Promise<CreateGroupResult | string>`) — but the adapter cast that union away and
+ read `.gid` off the string, so the reason upstream gave us was replaced by an opaque
+ `TypeError`. The union is handled, and an unreadable group id now fails loudly rather than being
+ coerced through `String()` into the literal id `"undefined"`. The status is unchanged (the group
+ genuinely wasn't created, so it was always a 500); the error text is now the real one.
+
+- **An ack whose message id can't be read is dropped instead of silently advancing nothing.** On a
+ WhatsApp Web build that renames the id field (#747), the id reached the status `UPDATE` as
+ `undefined`, which TypeORM sends as `waMessageId = NULL` — matching no row, since `x = NULL` is never
+ true. The ack advanced nothing, burned its one-shot retry, and left only a misleading "no status row
+ advanced" line behind. It is now dropped at the adapter boundary, where the reason is still visible.
+
- **A send whose message can't be read back no longer crashes, and never claims a delivery it can't
prove.** `whatsapp-web.js`'s `Client.sendMessage()` can *resolve* with `undefined` instead of
throwing, while its typings declare `Promise<Message>` — so the adapter's `msg.id._serialized` reads
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index c6d202eb6..b14daad94 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2060,3 +2060,82 @@ describe('WhatsAppWebJsAdapter send-result contract', () => {
expect(res).toEqual({ id: '[email protected]_XYZ', timestamp: 1700000002 });
});
});
+
+describe('WhatsAppWebJsAdapter message_ack (unreadable id)', () => {
+ const wireAckHandler = (): { onMessageAck: jest.Mock; client: EventEmitter } => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: 'sess-ack-test',
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ });
+ const client = Object.assign(new EventEmitter(), {
+ info: { wid: { _serialized: '[email protected]', user: '628123' }, pushname: 'Tester' },
+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),
+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },
+ });
+ (adapter as unknown as { client: unknown }).client = client;
+ const onMessageAck = jest.fn();
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onMessageAck };
+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();
+ return { onMessageAck, client };
+ };
+
+ it('forwards the ack on a healthy build', () => {
+ const { onMessageAck, client } = wireAckHandler();
+
+ client.emit('message_ack', { id: { _serialized: 'ACKED_MSG' } }, 3);
+
+ expect(onMessageAck).toHaveBeenCalledWith('ACKED_MSG', 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
+ // message at SENT with only a misleading "no status row advanced" in the log.
+ const { onMessageAck, client } = wireAckHandler();
+
+ client.emit('message_ack', { id: { someFutureName: 'x' } }, 3);
+
+ expect(onMessageAck).not.toHaveBeenCalled();
+ });
+});
+
+describe('WhatsAppWebJsAdapter createGroup (failure shapes)', () => {
+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+
+ it("surfaces the engine's reason when creation fails", async () => {
+ // whatsapp-web.js RESOLVES with a plain string on failure rather than throwing (Client.js:2376).
+ // Reading `.gid` off it produced an opaque TypeError and threw the actual reason away.
+ const createGroup = jest
+ .fn()
+ .mockResolvedValue('CreateGroupError: An unknown error occupied while creating a group');
+
+ await expect(readyAdapter({ createGroup }).createGroup('team', ['[email protected]'])).rejects.toThrow(
+ /CreateGroupError/,
+ );
+ });
+
+ it('never returns a placeholder when the group id cannot be read', async () => {
+ // The old `String(gid._serialized)` coerced an unreadable id into the literal string "undefined"
+ // and handed it back as a real, addressable group id.
+ const createGroup = jest.fn().mockResolvedValue({ gid: { someFutureName: 'x' } });
+
+ const call = readyAdapter({ createGroup }).createGroup('team', ['[email protected]']);
+
+ await expect(call).rejects.toThrow(/id could not be read/);
+ await expect(call).rejects.not.toThrow(/undefined/);
+ });
+
+ it('returns the group on success', async () => {
+ const createGroup = jest.fn().mockResolvedValue({ gid: { _serialized: '[email protected]' } });
+
+ const res = await readyAdapter({ createGroup }).createGroup('team', ['[email protected]', '[email protected]']);
+
+ expect(res).toEqual({ id: '[email protected]', name: 'team', participantsCount: 2 });
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 3bbd992d9..2a54d6f79 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -596,9 +596,20 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
this.client.on('message_ack', (msg, ack) => {
+ // An unreadable id (a WhatsApp Web build renaming the field, as in #747) would reach the ack
+ // UPDATE as undefined, which TypeORM sends as `waMessageId = NULL` — matching nothing, since
+ // `x = NULL` is never true. The ack then silently advances no row AND burns its one-shot retry,
+ // 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;
+ if (!ackId) {
+ this.logger.warn('Dropping an ack whose message id could not be read', { ack });
+ return;
+ }
// Map the whatsapp-web.js MessageAck integer to the neutral DeliveryStatus here, at the
// adapter boundary, so no downstream consumer ever sees engine-specific ack codes.
- this.callbacks.onMessageAck?.(msg.id._serialized, wwebjsAckToDeliveryStatus(ack));
+ this.callbacks.onMessageAck?.(ackId, wwebjsAckToDeliveryStatus(ack));
});
this.client.on('message_revoke_everyone', (after, before) => {
@@ -1316,7 +1327,20 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));
const result = await this.client!.createGroup(name, participantIds);
- const groupId = String((result as unknown as GroupCreateResult).gid._serialized);
+ // whatsapp-web.js reports a failed creation by RESOLVING with a plain string
+ // ('CreateGroupError: …', Client.js:2376) rather than throwing, and its own typings say so
+ // (`Promise<CreateGroupResult | string>`). Reading `.gid` straight off that string threw an opaque
+ // TypeError and discarded the reason upstream actually gave us; surface it instead.
+ if (typeof result === 'string') {
+ throw new Error(result);
+ }
+ const gid = (result as unknown as GroupCreateResult).gid as SerializedWid | undefined;
+ const groupId = gid?._serialized ?? gid?.$1;
+ // A group id is not ack-safe the way a message id is: there is no empty-sentinel equivalent, and any
+ // placeholder would be handed back as a real, addressable group. Fail instead of inventing one.
+ if (!groupId) {
+ throw new Error('the group was created but its id could not be read');
+ }
return {
id: groupId,
name: name,