Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): answer 409 for a wwebjs message write after a stop

Yudhi Armyndharisd05eb948f2db
diff --git a/src/engine/adapters/wwebjs-group-picture-lifetime.spec.ts b/src/engine/adapters/wwebjs-group-picture-lifetime.spec.ts
new file mode 100644
index 000000000..cdb6dfae0
--- /dev/null
+++ b/src/engine/adapters/wwebjs-group-picture-lifetime.spec.ts
@@ -0,0 +1,95 @@
+import { type Client } from 'whatsapp-web.js';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { WwebjsGroups } from './wwebjs-groups';
+import { type WwebjsEngineHost } from './wwebjs-host';
+import { toMessageMedia } from './wwebjs-messaging';
+
+jest.mock('./wwebjs-messaging', () => ({ toMessageMedia: jest.fn() }));
+jest.mock('./wwebjs-chats', () => ({ listChats: jest.fn() }));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+const GROUP = '[email protected]';
+const INPUT = { mimetype: 'image/png', data: 'QUJD' };
+const PICTURE = { mimetype: 'image/png', data: 'QUJD', filename: 'dummy.png' };
+
+function harness() {
+ const media = deferred<unknown>();
+ const mediaEntered = deferred<void>();
+ const commands: unknown[] = [];
+ const state = { ready: true };
+ const client = {
+ getChatById: () =>
+ Promise.resolve({
+ id: { _serialized: GROUP },
+ isGroup: true,
+ setPicture(picture: unknown) {
+ commands.push(picture);
+ return Promise.resolve(true);
+ },
+ }),
+ } as unknown as Client;
+ jest.mocked(toMessageMedia).mockImplementation(() => {
+ mediaEntered.resolve();
+ return media.promise as ReturnType<typeof toMessageMedia>;
+ });
+ const host = {
+ ensureReady() {
+ if (!state.ready) throw new EngineNotReadyError();
+ },
+ getClient() {
+ host.ensureReady();
+ return client;
+ },
+ isPageTransportError: () => false,
+ reportIfPageTransportError: jest.fn(),
+ config: { sessionId: 'picture-session' },
+ logger: { debug: jest.fn() },
+ } as unknown as WwebjsEngineHost;
+ return { groups: new WwebjsGroups(host), state, commands, media, mediaEntered };
+}
+
+describe('group picture write when the session stops during media preparation', () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it('writes the picture when the session stays ready', async () => {
+ const fixture = harness();
+ const pending = fixture.groups.setGroupPicture(GROUP, INPUT);
+ await fixture.mediaEntered.promise;
+ fixture.media.resolve(PICTURE);
+ await pending;
+
+ expect(fixture.commands).toEqual([PICTURE]);
+ });
+
+ it('answers not-ready without writing when the session stopped meanwhile', async () => {
+ const fixture = harness();
+ const pending = fixture.groups.setGroupPicture(GROUP, INPUT).catch(error => error as unknown);
+ await fixture.mediaEntered.promise;
+ fixture.state.ready = false;
+ fixture.media.resolve(PICTURE);
+ const result = await pending;
+
+ expect(result).toBeInstanceOf(EngineNotReadyError);
+ expect(fixture.commands).toEqual([]);
+ });
+
+ it('keeps a media preparation error and writes nothing', async () => {
+ const fixture = harness();
+ const failure = new Error('Dummy media preparation failed');
+ const pending = fixture.groups.setGroupPicture(GROUP, INPUT).catch(error => error as unknown);
+ await fixture.mediaEntered.promise;
+ fixture.media.reject(failure);
+
+ expect(await pending).toBe(failure);
+ expect(fixture.commands).toEqual([]);
+ });
+});
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index c572b8136..857cf0dab 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -539,6 +539,8 @@ export class WwebjsGroups {
const groupChat = await this.requireGroupChat(groupId, 'setGroupPicture');
// Loaded outside the page guard: a media fetch failing with "connection closed" is not a dead page.
const picture = await toMessageMedia(media, this.host.config.proxy?.url);
+ // The fetch can outlast the session, and the chat writes through the client that read it.
+ this.host.ensureReady();
// GroupChat.setPicture, NOT Client.setProfilePicture — the latter targets the own account.
const ok = await withPage(this.host, 'setGroupPicture', () => groupChat.setPicture(picture));
if (!ok) {
diff --git a/src/engine/adapters/wwebjs-message-mutation-lifetime.spec.ts b/src/engine/adapters/wwebjs-message-mutation-lifetime.spec.ts
new file mode 100644
index 000000000..350c2a515
--- /dev/null
+++ b/src/engine/adapters/wwebjs-message-mutation-lifetime.spec.ts
@@ -0,0 +1,128 @@
+import type { Client } from 'whatsapp-web.js';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { WwebjsMessaging } from './wwebjs-messaging';
+import type { WwebjsEngineHost } from './wwebjs-host';
+
+const CHAT = '[email protected]';
+const MESSAGE = '[email protected]_dummy';
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+};
+
+type Operation = 'react' | 'delete' | 'edit' | 'vote' | 'pin' | 'star' | 'unstar' | 'unpin';
+type Stage = 'chat' | 'messages';
+const operations: Operation[] = ['react', 'delete', 'edit', 'vote', 'pin', 'star', 'unstar', 'unpin'];
+const stages: Stage[] = ['chat', 'messages'];
+
+const invoke = (messaging: WwebjsMessaging, operation: Operation): Promise<unknown> => {
+ switch (operation) {
+ case 'react':
+ return messaging.reactToMessage(CHAT, MESSAGE, 'x');
+ case 'delete':
+ return messaging.deleteMessage(CHAT, MESSAGE, true);
+ case 'edit':
+ return messaging.editMessage(CHAT, MESSAGE, 'edited body');
+ case 'vote':
+ return messaging.votePoll(CHAT, MESSAGE, ['a']);
+ case 'pin':
+ return messaging.pinMessage(CHAT, MESSAGE, 86400);
+ case 'star':
+ return messaging.starMessage(CHAT, MESSAGE, true);
+ case 'unstar':
+ return messaging.starMessage(CHAT, MESSAGE, false);
+ case 'unpin':
+ return messaging.unpinMessage(CHAT, MESSAGE);
+ }
+};
+
+/** A READY client whose chat lookup or message fetch is held at `stage` until the test releases it. */
+function fixture(operation: Operation, stage?: Stage) {
+ const entered = deferred<void>();
+ const gate = deferred<void>();
+ const result = { id: { _serialized: MESSAGE, id: 'dummy' }, timestamp: 1 };
+ const mutation = jest
+ .fn()
+ .mockResolvedValue(operation === 'edit' ? result : operation === 'pin' || operation === 'unpin' ? true : undefined);
+ const message = {
+ ...result,
+ pollOptions: [{ name: 'a' }, { name: 'b' }],
+ react: mutation,
+ delete: mutation,
+ edit: mutation,
+ vote: mutation,
+ pin: mutation,
+ star: mutation,
+ unstar: mutation,
+ unpin: mutation,
+ };
+ const wait = async <T>(name: Stage, value: T): Promise<T> => {
+ if (stage === name) {
+ entered.resolve();
+ await gate.promise;
+ }
+ return value;
+ };
+ const chat = { fetchMessages: jest.fn(() => wait('messages', [message])) };
+ const client = { getChatById: jest.fn(() => wait('chat', chat)) };
+ let ready = true;
+ const host = {
+ ensureReady() {
+ if (!ready) throw new EngineNotReadyError();
+ },
+ getClient() {
+ host.ensureReady();
+ return client as unknown as Client;
+ },
+ isPageTransportError: () => false,
+ reportIfPageTransportError: jest.fn(),
+ logger: { debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
+ config: {},
+ } as unknown as WwebjsEngineHost;
+ return {
+ messaging: new WwebjsMessaging(host),
+ mutation,
+ entered,
+ gate,
+ stopSession: () => {
+ ready = false;
+ },
+ };
+}
+
+describe('message mutations when the session stops during their lookup', () => {
+ it.each(operations)('runs %s on a session that stays ready', async operation => {
+ const test = fixture(operation);
+ await invoke(test.messaging, operation);
+ expect(test.mutation).toHaveBeenCalledTimes(1);
+ });
+
+ const stopped = operations.flatMap(operation => stages.map(stage => ({ operation, stage })));
+ it.each(stopped)(
+ 'refuses $operation after the session stopped during the $stage lookup',
+ async ({ operation, stage }) => {
+ const test = fixture(operation, stage);
+ const done = invoke(test.messaging, operation).catch((error: unknown) => error);
+ await test.entered.promise;
+ test.stopSession();
+ test.gate.resolve();
+ expect(await done).toBeInstanceOf(EngineNotReadyError);
+ expect(test.mutation).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(stopped)('keeps the $stage lookup failure of $operation', async ({ operation, stage }) => {
+ const test = fixture(operation, stage);
+ const failure = new Error('dummy lookup unavailable');
+ const done = invoke(test.messaging, operation).catch((error: unknown) => error);
+ await test.entered.promise;
+ test.gate.reject(failure);
+ expect(await done).toBe(failure);
+ expect(test.mutation).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 89b8bb318..a35bb1a9c 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -888,6 +888,9 @@ export class WwebjsMessaging {
if (!message) {
throw new MessageNotFoundError(messageId, chatId);
}
+ // The message acts through the client that read it, which the host's check on getClient never sees
+ // again: a teardown that landed in the lookup is the retryable 409, not a write on a closing page.
+ this.host.ensureReady();
await (message as MessageWithReactions).react(emoji);
});
this.host.logger.debug('Reacted to message', { messageId, emoji: emoji || '(removed)' });
@@ -1067,6 +1070,7 @@ export class WwebjsMessaging {
if (!message) {
throw new MessageNotFoundError(messageId, chatId);
}
+ this.host.ensureReady();
await message.delete(forEveryone);
});
this.host.logger.debug('Deleted message', { chatId, messageId, forEveryone });
@@ -1090,6 +1094,7 @@ export class WwebjsMessaging {
if (!message) {
throw new MessageNotFoundError(messageId, chatId);
}
+ this.host.ensureReady();
// An edit REPLACES the content, so tags are re-applied rather than preserved: omitting mentions
// drops whatever the original carried. Options omitted entirely when none were asked for.
return mentions?.length ? message.edit(body, { mentions }) : message.edit(body);
@@ -1112,6 +1117,9 @@ export class WwebjsMessaging {
*
* As with those sites, chatId is NOT lid-resolved: the pin acts on the found message's own key,
* so resolving would only risk missing a message stored under the pre-migration @c.us chat.
+ *
+ * Readiness is checked again before the message is returned: it acts through the client that read it, so
+ * a teardown that landed in the lookup would otherwise reach a closing page.
*/
private async findInFetchWindow(chatId: string, messageId: string): Promise<Message> {
const chat = await this.client().getChatById(chatId);
@@ -1121,6 +1129,7 @@ export class WwebjsMessaging {
const messages = await chat.fetchMessages({ limit: 100 });
const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);
if (!message) throw new MessageNotFoundError(messageId, chatId);
+ this.host.ensureReady();
return message;
}