Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
import type { WASocket } from '@whiskeysockets/baileys';
import { BaileysGroups, BaileysGroupsHost } from './baileys-groups';
import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
/**
* Every group and profile WRITE goes through a Baileys method that awaits `groupQuery`/`query` and
* then discards the result, so the call resolves the same way whether WhatsApp confirmed the change
* or never answered — and `query()` catches its own timeout and resolves rather than throwing.
*
* There is no value left to inspect, so these pin the only thing that can separate the two: a
* deadline OpenWA owns. One case per call site, because a missed wrapper is invisible otherwise.
*/
const never = (): Promise<never> => new Promise<never>(() => undefined);
const stub = () => jest.fn(never);
function groups(sock: Record<string, jest.Mock>, budgetMs: number): BaileysGroups {
const host = {
ensureReady: () => undefined,
sessionProxyUrl: () => undefined,
getSocket: () => sock as unknown as WASocket,
logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },
toNeutralJid: (j: string) => j,
toEngineJid: (j: string) => j,
normalizedSelfJid: () => '[email protected]',
} as unknown as BaileysGroupsHost;
return new BaileysGroups(host, budgetMs);
}
function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysContacts {
const host = {
ensureReady: () => undefined,
sessionProxyUrl: () => 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;
return new BaileysContacts(host, budgetMs);
}
// A real 1x1 PNG: a picture write reads the header of its bytes before it reaches the socket.
const PNG = {
mimetype: 'image/png',
data: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
),
};
describe('group writes report an unconfirmed write rather than success', () => {
it.each([
['leaveGroup', 'groupLeave', (g: BaileysGroups) => g.leaveGroup('[email protected]')],
['setGroupSubject', 'groupUpdateSubject', (g: BaileysGroups) => g.setGroupSubject('[email protected]', 'X')],
['setGroupDescription', 'groupUpdateDescription', (g: BaileysGroups) => g.setGroupDescription('[email protected]', 'X')],
[
'setGroupMessagesAdminsOnly',
'groupSettingUpdate',
(g: BaileysGroups) => g.setGroupMessagesAdminsOnly('[email protected]', true),
],
['setGroupInfoAdminsOnly', 'groupSettingUpdate', (g: BaileysGroups) => g.setGroupInfoAdminsOnly('[email protected]', true)],
['setGroupPicture', 'updateProfilePicture', (g: BaileysGroups) => g.setGroupPicture('[email protected]', PNG)],
['deleteGroupPicture', 'removeProfilePicture', (g: BaileysGroups) => g.deleteGroupPicture('[email protected]')],
[
'setGroupMemberAddMode',
'groupMemberAddMode',
(g: BaileysGroups) => g.setGroupMemberAddMode('[email protected]', 'admins'),
],
['setGroupEphemeral', 'groupToggleEphemeral', (g: BaileysGroups) => g.setGroupEphemeral('[email protected]', 604800)],
// A relayed message rather than an IQ, but the group lookup and device fetch before the relay can stall.
['setGroupMemberLabel', 'updateMemberLabel', (g: BaileysGroups) => g.setGroupMemberLabel('[email protected]', 'Site A')],
])('%s', async (_name, sockMethod, call) => {
await expect(call(groups({ [sockMethod]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);
});
it('still resolves when WhatsApp answers inside the budget', async () => {
const groupLeave = jest.fn().mockResolvedValue(undefined);
await expect(groups({ groupLeave }, 500).leaveGroup('[email protected]')).resolves.toBeUndefined();
expect(groupLeave).toHaveBeenCalledWith('[email protected]');
});
it('names the operation that was not confirmed', async () => {
await expect(groups({ groupLeave: stub() }, 15).leaveGroup('[email protected]')).rejects.toThrow(
'WhatsApp did not confirm leaving the group in time',
);
});
});
describe('profile writes report an unconfirmed write rather than success', () => {
it.each([
['setProfileName', 'updateProfileName', (c: BaileysContacts) => c.setProfileName('Ada')],
['setProfileStatus', 'updateProfileStatus', (c: BaileysContacts) => c.setProfileStatus('busy')],
['setProfilePicture', 'updateProfilePicture', (c: BaileysContacts) => c.setProfilePicture(PNG)],
])('%s', async (_name, sockMethod, call) => {
await expect(call(contacts({ [sockMethod]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);
});
it('still resolves when WhatsApp answers inside the budget', async () => {
const updateProfileName = jest.fn().mockResolvedValue(undefined);
await expect(contacts({ updateProfileName }, 500).setProfileName('Ada')).resolves.toBeUndefined();
expect(updateProfileName).toHaveBeenCalledWith('Ada');
});
});