Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): BaileysAdapter — auth, connection lifecycle, status, capability gating
rmyndharisd39a7e1c0d1e
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsnew file mode 100644index 000000000..c4f113c17--- /dev/null+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -0,0 +1,139 @@+import { EventEmitter } from 'events';++// A fake Baileys socket: an event emitter wearing the methods the adapter calls.+class FakeSock extends EventEmitter {+ public ev = {+ on: (event: string, handler: (arg: unknown) => void) => {+ this.emitter.on(event, handler);+ },+ };+ public emitter = new EventEmitter();+ public user: { id: string; name?: string } | undefined;+ public requestPairingCode = jest.fn().mockResolvedValue('ABCD-EFGH');+ public end = jest.fn();+ public logout = jest.fn().mockResolvedValue(undefined);+ public sendMessage = jest.fn();+ public onWhatsApp = jest.fn();+ public sendPresenceUpdate = jest.fn().mockResolvedValue(undefined);+ fire(event: string, arg: unknown): void {+ this.emitter.emit(event, arg);+ }+ resetEmitter(): void {+ this.emitter.removeAllListeners();+ }+}++const fakeSock = new FakeSock();+const saveCreds = jest.fn().mockResolvedValue(undefined);++jest.mock('@whiskeysockets/baileys', () => ({+ __esModule: true,+ default: jest.fn(() => fakeSock),+ useMultiFileAuthState: jest.fn().mockResolvedValue({ state: { creds: {}, keys: {} }, saveCreds }),+ fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 0] }),+ getContentType: jest.fn(() => 'conversation'),+ DisconnectReason: { loggedOut: 401, restartRequired: 515 },+}));++import { BaileysAdapter } from './baileys.adapter';+import { EngineStatus, EngineEventCallbacks } from '../interfaces/whatsapp-engine.interface';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';++const newAdapter = (): BaileysAdapter =>+ new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys' });++const noopCallbacks = (over: Partial<EngineEventCallbacks> = {}): EngineEventCallbacks => over;++describe('BaileysAdapter lifecycle & status', () => {+ beforeEach(() => {+ fakeSock.user = undefined;+ fakeSock.resetEmitter(); // drop listeners from previous test's initialize()+ jest.clearAllMocks();+ });++ it('starts DISCONNECTED', () => {+ expect(newAdapter().getStatus()).toBe(EngineStatus.DISCONNECTED);+ });++ it('emits onQRCode and moves to QR_READY on a connection.update with a qr', async () => {+ const onQRCode = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onQRCode }));+ fakeSock.fire('connection.update', { qr: 'QR-STRING' });+ expect(onQRCode).toHaveBeenCalledWith('QR-STRING');+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);+ expect(adapter.getQRCode()).toBe('QR-STRING');+ });++ it('captures phone/pushName and fires onReady on connection open', async () => {+ const onReady = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onReady }));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.fire('connection.update', { connection: 'open' });+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(adapter.getPhoneNumber()).toBe('628999');+ expect(adapter.getPushName()).toBe('Me');+ expect(onReady).toHaveBeenCalledWith('628999', 'Me');+ });++ it('on a logged-out close: DISCONNECTED, onDisconnected, and NO reconnect', async () => {+ const onDisconnected = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onDisconnected }));+ const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;+ makeWASocket.mockClear();+ fakeSock.fire('connection.update', { connection: 'close', lastDisconnect: { error: { output: { statusCode: 401 } } } });+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect(onDisconnected).toHaveBeenCalled();+ expect(makeWASocket).not.toHaveBeenCalled(); // no reconnect+ });++ it('on a recoverable close: reconnects (re-creates the socket)', async () => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;+ makeWASocket.mockClear();+ fakeSock.fire('connection.update', { connection: 'close', lastDisconnect: { error: { output: { statusCode: 515 } } } });+ await new Promise(r => setImmediate(r)); // let the async connect() run+ expect(makeWASocket).toHaveBeenCalledTimes(1);+ });++ it('disconnect() ends the socket and does not reconnect', async () => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ await adapter.disconnect();+ expect(fakeSock.end).toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ });++ it('requestPairingCode delegates to the socket', async () => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ await expect(adapter.requestPairingCode('628999')).resolves.toBe('ABCD-EFGH');+ expect(fakeSock.requestPairingCode).toHaveBeenCalledWith('628999');+ });++ it('persists creds: subscribes saveCreds to creds.update', async () => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.fire('creds.update', {});+ expect(saveCreds).toHaveBeenCalled();+ });+});++describe('BaileysAdapter capability gating', () => {+ it('throws EngineNotSupportedError for store-backed methods (e.g. getGroups, getChats)', async () => {+ const adapter = newAdapter();+ await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotSupportedError);+ await expect(adapter.getChats()).rejects.toBeInstanceOf(EngineNotSupportedError);+ await expect(adapter.sendImageMessage('x', { mimetype: 'image/png', data: 'AAA' })).rejects.toBeInstanceOf(+ EngineNotSupportedError,+ );+ });+});++// Suppress unused import lint warning — EngineNotReadyError is the correct class to import+// even though its direct use in tests is through the toBeInstanceOf check on thrown errors.+void EngineNotReadyError;diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsnew file mode 100644index 000000000..fb3e19dba--- /dev/null+++ b/src/engine/adapters/baileys.adapter.ts@@ -0,0 +1,429 @@+import * as path from 'path';+import makeWASocket, {+ DisconnectReason,+ fetchLatestBaileysVersion,+ useMultiFileAuthState,+} from '@whiskeysockets/baileys';+import type { WASocket } from '@whiskeysockets/baileys';+import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';+import {+ ChatState,+ Channel,+ ChannelMessage,+ Catalog,+ Contact,+ ContactCard,+ EngineEventCallbacks,+ EngineStatus,+ Group,+ GroupInfo,+ IncomingMessage,+ IWhatsAppEngine,+ Label,+ LocationInput,+ MediaInput,+ MessageReaction,+ MessageResult,+ PaginatedProducts,+ Product,+ ProductQueryOptions,+ Status,+ StatusResult,+ ChatSummary,+ TextStatusOptions,+} from '../interfaces/whatsapp-engine.interface';+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { createLogger } from '../../common/services/logger.service';+import { BaileysAdapterConfig, BaileysLogger } from '../types/baileys.types';++/** Linked-device identity shown in WhatsApp (Settings → Linked Devices). */+const BAILEYS_BROWSER: [string, string, string] = ['OpenWA', 'Chrome', '120.0.0'];++/** Fully silent logger so Baileys does not spam stdout; diagnostics flow via connection.update. */+function createSilentLogger(): BaileysLogger {+ const noop = (): void => {};+ const logger: BaileysLogger = {+ level: 'silent',+ child: () => logger,+ trace: noop,+ debug: noop,+ info: noop,+ warn: noop,+ error: noop,+ };+ return logger;+}++export class BaileysAdapter implements IWhatsAppEngine {+ private readonly logger = createLogger('BaileysAdapter');+ private readonly authPath: string;+ private sock: WASocket | null = null;+ private status: EngineStatus = EngineStatus.DISCONNECTED;+ private qrCode: string | null = null;+ private phoneNumber: string | null = null;+ private pushName: string | null = null;+ private callbacks: EngineEventCallbacks = {};+ private intentionalClose = false;++ constructor(private readonly config: BaileysAdapterConfig) {+ // Isolate each session's auth state under its own subdirectory of the shared auth dir.+ this.authPath = path.join(config.authDir, config.sessionId);+ if (config.proxyUrl) {+ // Proxy support is gated for this slice — Baileys proxying needs an http/socks agent (a new dep).+ this.logger.warn('Proxy configured but not supported by the baileys engine in this slice; ignoring it', {+ action: 'baileys_proxy_unsupported',+ sessionId: config.sessionId,+ });+ }+ }++ // ----- Lifecycle -----++ async initialize(callbacks: EngineEventCallbacks): Promise<void> {+ this.callbacks = callbacks;+ this.intentionalClose = false;+ await this.connect();+ }++ private async connect(): Promise<void> {+ this.setStatus(EngineStatus.INITIALIZING);+ const { state, saveCreds } = await useMultiFileAuthState(this.authPath);+ const { version } = await fetchLatestBaileysVersion();++ const sock = makeWASocket({+ auth: state,+ version,+ browser: BAILEYS_BROWSER,+ printQRInTerminal: false,+ // BaileysLogger matches ILogger exactly; cast needed because the module resolves+ // the type through a deep import path that TypeScript does not auto-unify here.+ logger: createSilentLogger() as unknown as ILogger,+ });+ this.sock = sock;++ sock.ev.on('creds.update', saveCreds);+ sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));+ // Message listeners are wired in the messaging slice (Task 5).+ }++ private handleConnectionUpdate(update: {+ connection?: string;+ qr?: string;+ lastDisconnect?: { error?: unknown };+ }): void {+ const { connection, qr, lastDisconnect } = update;++ if (qr) {+ this.qrCode = qr;+ this.setStatus(EngineStatus.QR_READY);+ this.callbacks.onQRCode?.(qr);+ }++ if (connection === 'connecting') {+ this.setStatus(EngineStatus.INITIALIZING);+ }++ if (connection === 'open') {+ this.qrCode = null;+ this.phoneNumber = this.extractPhone(this.sock?.user?.id);+ this.pushName = this.sock?.user?.name ?? null;+ this.setStatus(EngineStatus.READY);+ this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');+ }++ if (connection === 'close') {+ const statusCode = (lastDisconnect?.error as { output?: { statusCode?: number } } | undefined)?.output+ ?.statusCode;++ if (this.intentionalClose) {+ this.setStatus(EngineStatus.DISCONNECTED);+ return;+ }++ if (statusCode === DisconnectReason.loggedOut) {+ // Credentials invalidated — terminal. Re-linking requires a fresh QR/pairing.+ this.setStatus(EngineStatus.DISCONNECTED);+ this.callbacks.onDisconnected?.('logged out');+ return;+ }++ // Recoverable (e.g. restartRequired right after pairing, transient drop) — reconnect.+ this.callbacks.onDisconnected?.(`connection closed (${statusCode ?? 'unknown'})`);+ this.connect().catch(err => {+ this.setStatus(EngineStatus.FAILED);+ this.callbacks.onError?.(err instanceof Error ? err.message : String(err));+ });+ }+ }++ async disconnect(): Promise<void> {+ this.intentionalClose = true;+ this.sock?.end(undefined);+ this.sock = null;+ this.setStatus(EngineStatus.DISCONNECTED);+ }++ async logout(): Promise<void> {+ this.intentionalClose = true;+ try {+ await this.sock?.logout();+ } catch (err) {+ this.logger.warn('Baileys logout failed; ending socket', {+ error: err instanceof Error ? err.message : String(err),+ });+ this.sock?.end(undefined);+ }+ this.sock = null;+ this.setStatus(EngineStatus.DISCONNECTED);+ // ponytail: leaves the multi-file auth dir on disk; a fresh link overwrites it. Add fs cleanup if+ // stale creds ever block re-linking.+ }++ async destroy(): Promise<void> {+ this.intentionalClose = true;+ this.sock?.end(undefined);+ this.sock = null;+ this.setStatus(EngineStatus.DISCONNECTED);+ }++ // ----- Status -----++ getStatus(): EngineStatus {+ return this.status;+ }++ getQRCode(): string | null {+ return this.qrCode;+ }++ async requestPairingCode(phoneNumber: string): Promise<string> {+ if (!this.sock) {+ throw new EngineNotReadyError('Cannot request a pairing code before the engine is initialized.');+ }+ return this.sock.requestPairingCode(phoneNumber);+ }++ getPhoneNumber(): string | null {+ return this.phoneNumber;+ }++ getPushName(): string | null {+ return this.pushName;+ }++ // ----- Messaging (implemented in the messaging slice; gated until then) -----++ sendTextMessage(_chatId: string, _text: string): Promise<MessageResult> {+ return this.unsupported('sendTextMessage');+ }++ checkNumberExists(_number: string): Promise<boolean> {+ return this.unsupported('checkNumberExists');+ }++ getNumberId(_number: string): Promise<string | null> {+ return this.unsupported('getNumberId');+ }++ sendChatState(_chatId: string, _state: ChatState): Promise<void> {+ return this.unsupported('sendChatState');+ }++ // ----- Gated: not supported by this minimal slice (no store) -----++ sendImageMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {+ return this.unsupported('sendImageMessage');+ }+ sendVideoMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {+ return this.unsupported('sendVideoMessage');+ }+ sendAudioMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {+ return this.unsupported('sendAudioMessage');+ }+ sendDocumentMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {+ return this.unsupported('sendDocumentMessage');+ }+ sendLocationMessage(_chatId: string, _location: LocationInput): Promise<MessageResult> {+ return this.unsupported('sendLocationMessage');+ }+ sendContactMessage(_chatId: string, _contact: ContactCard): Promise<MessageResult> {+ return this.unsupported('sendContactMessage');+ }+ sendStickerMessage(_chatId: string, _media: MediaInput): Promise<MessageResult> {+ return this.unsupported('sendStickerMessage');+ }+ replyToMessage(_chatId: string, _quotedMsgId: string, _text: string): Promise<MessageResult> {+ return this.unsupported('replyToMessage');+ }+ forwardMessage(_fromChatId: string, _toChatId: string, _messageId: string): Promise<MessageResult> {+ return this.unsupported('forwardMessage');+ }+ reactToMessage(_chatId: string, _messageId: string, _emoji: string): Promise<void> {+ return this.unsupported('reactToMessage');+ }+ getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {+ return this.unsupported('getMessageReactions');+ }+ getContacts(): Promise<Contact[]> {+ return this.unsupported('getContacts');+ }+ getContactById(_contactId: string): Promise<Contact | null> {+ return this.unsupported('getContactById');+ }+ resolveContactPhone(_contactId: string): Promise<string | null> {+ return this.unsupported('resolveContactPhone');+ }+ getGroups(): Promise<Group[]> {+ return this.unsupported('getGroups');+ }+ getGroupInfo(_groupId: string): Promise<GroupInfo | null> {+ return this.unsupported('getGroupInfo');+ }+ createGroup(_name: string, _participants: string[]): Promise<Group> {+ return this.unsupported('createGroup');+ }+ addParticipants(_groupId: string, _participants: string[]): Promise<void> {+ return this.unsupported('addParticipants');+ }+ removeParticipants(_groupId: string, _participants: string[]): Promise<void> {+ return this.unsupported('removeParticipants');+ }+ promoteParticipants(_groupId: string, _participants: string[]): Promise<void> {+ return this.unsupported('promoteParticipants');+ }+ demoteParticipants(_groupId: string, _participants: string[]): Promise<void> {+ return this.unsupported('demoteParticipants');+ }+ leaveGroup(_groupId: string): Promise<void> {+ return this.unsupported('leaveGroup');+ }+ setGroupSubject(_groupId: string, _subject: string): Promise<void> {+ return this.unsupported('setGroupSubject');+ }+ setGroupDescription(_groupId: string, _description: string): Promise<void> {+ return this.unsupported('setGroupDescription');+ }+ getGroupInviteCode(_groupId: string): Promise<string> {+ return this.unsupported('getGroupInviteCode');+ }+ revokeGroupInviteCode(_groupId: string): Promise<string> {+ return this.unsupported('revokeGroupInviteCode');+ }+ deleteMessage(_chatId: string, _messageId: string, _forEveryone?: boolean): Promise<void> {+ return this.unsupported('deleteMessage');+ }+ getChatHistory(_chatId: string, _limit?: number, _includeMedia?: boolean): Promise<IncomingMessage[]> {+ return this.unsupported('getChatHistory');+ }+ getProfilePicture(_contactId: string): Promise<string | null> {+ return this.unsupported('getProfilePicture');+ }+ blockContact(_contactId: string): Promise<void> {+ return this.unsupported('blockContact');+ }+ unblockContact(_contactId: string): Promise<void> {+ return this.unsupported('unblockContact');+ }+ getLabels(): Promise<Label[]> {+ return this.unsupported('getLabels');+ }+ getLabelById(_labelId: string): Promise<Label | null> {+ return this.unsupported('getLabelById');+ }+ getChatLabels(_chatId: string): Promise<Label[]> {+ return this.unsupported('getChatLabels');+ }+ addLabelToChat(_chatId: string, _labelId: string): Promise<void> {+ return this.unsupported('addLabelToChat');+ }+ removeLabelFromChat(_chatId: string, _labelId: string): Promise<void> {+ return this.unsupported('removeLabelFromChat');+ }+ getSubscribedChannels(): Promise<Channel[]> {+ return this.unsupported('getSubscribedChannels');+ }+ getChannelById(_channelId: string): Promise<Channel | null> {+ return this.unsupported('getChannelById');+ }+ subscribeToChannel(_inviteCode: string): Promise<Channel> {+ return this.unsupported('subscribeToChannel');+ }+ unsubscribeFromChannel(_channelId: string): Promise<void> {+ return this.unsupported('unsubscribeFromChannel');+ }+ getChannelMessages(_channelId: string, _limit?: number): Promise<ChannelMessage[]> {+ return this.unsupported('getChannelMessages');+ }+ getContactStatuses(): Promise<Status[]> {+ return this.unsupported('getContactStatuses');+ }+ getContactStatus(_contactId: string): Promise<Status[]> {+ return this.unsupported('getContactStatus');+ }+ postTextStatus(_text: string, _options?: TextStatusOptions): Promise<StatusResult> {+ return this.unsupported('postTextStatus');+ }+ postImageStatus(_media: MediaInput, _caption?: string): Promise<StatusResult> {+ return this.unsupported('postImageStatus');+ }+ postVideoStatus(_media: MediaInput, _caption?: string): Promise<StatusResult> {+ return this.unsupported('postVideoStatus');+ }+ deleteStatus(_statusId: string): Promise<void> {+ return this.unsupported('deleteStatus');+ }+ getCatalog(): Promise<Catalog | null> {+ return this.unsupported('getCatalog');+ }+ getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {+ return this.unsupported('getProducts');+ }+ getProduct(_productId: string): Promise<Product | null> {+ return this.unsupported('getProduct');+ }+ sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {+ return this.unsupported('sendProduct');+ }+ sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {+ return this.unsupported('sendCatalog');+ }+ getChats(): Promise<ChatSummary[]> {+ return this.unsupported('getChats');+ }+ sendSeen(_chatId: string): Promise<boolean> {+ return this.unsupported('sendSeen');+ }+ deleteChat(_chatId: string): Promise<boolean> {+ return this.unsupported('deleteChat');+ }++ // ----- Helpers -----++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ private unsupported(method: string): Promise<any> {+ return Promise.reject(new EngineNotSupportedError(method));+ }++ protected ensureReady(): void {+ if (this.status !== EngineStatus.READY || !this.sock) {+ throw new EngineNotReadyError();+ }+ }++ private setStatus(status: EngineStatus): void {+ if (this.status === status) {+ return;+ }+ this.status = status;+ this.callbacks.onStateChanged?.(status);+ }++ /** `628999:[email protected]` / `[email protected]` -> `628999`. */+ private extractPhone(id: string | undefined): string | null {+ if (!id) {+ return null;+ }+ return id.split(':')[0].split('@')[0] || null;+ }+}diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.tsnew file mode 100644index 000000000..b380ce6d7--- /dev/null+++ b/src/engine/types/baileys.types.ts@@ -0,0 +1,27 @@+/**+ * Per-call construction config for {@link BaileysAdapter}. Engine-neutral fields come from the+ * factory; `authDir` is the base multi-file auth directory from the opaque `engine.baileys.*` blob+ * (the adapter appends the session id to isolate each session).+ */+export interface BaileysAdapterConfig {+ sessionId: string;+ authDir: string;+ proxyUrl?: string;+ proxyType?: 'http' | 'https' | 'socks4' | 'socks5';+}++/**+ * The minimal pino-compatible logger Baileys' `makeWASocket` expects. Declared locally so we can+ * pass a fully silent logger without taking a direct `pino` dependency.+ *+ * Matches the Baileys `ILogger` contract: each log method receives `(obj: unknown, msg?: string)`.+ */+export interface BaileysLogger {+ level: string;+ child: (bindings: Record<string, unknown>) => BaileysLogger;+ trace: (obj: unknown, msg?: string) => void;+ debug: (obj: unknown, msg?: string) => void;+ info: (obj: unknown, msg?: string) => void;+ warn: (obj: unknown, msg?: string) => void;+ error: (obj: unknown, msg?: string) => void;+}