/** * WhatsApp channel adapter: whatsapp-web.js, which runs WhatsApp Web in a * headless Chrome, Edge or Chromium through Puppeteer (ADR-0005). * * The client is unofficial and WhatsApp may block the linked account. The * Settings UI shows that warning and recommends a secondary number; keep it. * * Pairing is QR-scan like WhatsApp Web: the latest QR string is held in memory * and surfaced through getStatus().qr → /api/channels for the UI to render. * LocalAuth keeps the session as a browser profile in * /channels/whatsapp/session, so pairing survives restarts. When the * phone unlinks the device, whatsapp-web.js deletes that profile and shows a * fresh QR. * * The browser comes from whatsapp-browser.ts (installed first, a one-time * download otherwise). whatsapp-web.js is loaded with a dynamic import so the * sidecar does not load Puppeteer until WhatsApp is started. * * Text only: media, voice and video messages are ignored, so the ffmpeg that * whatsapp-web.js uses for video stickers is never needed. */ import fs from 'node:fs'; import path from 'node:path'; import type { ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler, } from './types.js'; import { chunkText } from './types.js'; import { resolveWhatsAppBrowser, WhatsAppBrowserError } from './whatsapp-browser.js'; import { releaseOrphanedBrowser, type ProfileLockState } from './whatsapp-profile-lock.js'; /** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */ export const WHATSAPP_MAX_TEXT = 4000; const BACKOFF_START_MS = 2_000; const BACKOFF_CAP_MS = 60_000; /** Disconnect reasons that mean WhatsApp blocked the account: do not reconnect. */ const BLOCKED_STATES = new Set(['TOS_BLOCK', 'SMB_TOS_BLOCK']); const LINKED_MARKER = 'linked'; /** Status payload extended with the pairing QR (rendered by Settings UI). */ export interface WhatsAppStatus extends ChannelAdapterStatus { qr?: string; /** True when a linked session is stored on disk. */ paired?: boolean; /** What the adapter is doing before the QR appears (browser lookup or download). */ detail?: string; } // ── Minimal structural contracts over whatsapp-web.js (test seam) ────── export interface WaMessageLike { from: string; /** Group messages: the participant who wrote it. */ author?: string; fromMe: boolean; body: string; /** 'chat' for text; 'image', 'video', 'ptt' (voice), 'audio', … for media. */ type: string; isStatus?: boolean; broadcast?: boolean; id?: { _serialized?: string }; _data?: { notifyName?: string }; } export interface WaClientLike { on(event: 'qr', listener: (qr: string) => void): unknown; on(event: 'authenticated' | 'ready', listener: () => void): unknown; on(event: 'auth_failure' | 'disconnected', listener: (reason: string) => void): unknown; on(event: 'message', listener: (message: WaMessageLike) => void): unknown; initialize(): Promise; sendMessage(chatId: string, content: string): Promise; destroy(): Promise; } export type WaClientFactory = (opts: { authDir: string; executablePath: string }) => Promise; export type WaBrowserResolver = (onProgress: (percent: number) => void) => Promise; /** Production factory: real whatsapp-web.js, dynamically imported. */ async function defaultClientFactory(opts: { authDir: string; executablePath: string }): Promise { const { Client, LocalAuth } = (await import('whatsapp-web.js')).default; return new Client({ authStrategy: new LocalAuth({ dataPath: opts.authDir }), // The default cache path is relative to the process cwd. webVersionCache: { type: 'local', path: path.join(opts.authDir, 'web-cache') }, puppeteer: { executablePath: opts.executablePath, headless: true, // Puppeteer's own handlers would exit the process on Ctrl-C. The sidecar // shuts down itself and closes the browser through stop(). handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false, }, }); } export interface WhatsAppAdapterOptions { /** Waggle data dir; the session lives in /channels/whatsapp. */ dataDir: string; onMessage: InboundHandler; log: { info: (msg: string) => void; warn: (msg: string) => void }; /** Test seam: finds or downloads the browser. */ browserResolver?: WaBrowserResolver; /** Test seam. */ clientFactory?: WaClientFactory; /** Test seam: frees the session profile from a browser left by an earlier run. */ releaseStaleBrowser?: (profileDir: string) => Promise; backoffCapMs?: number; } export class WhatsAppAdapter implements ChannelAdapter { readonly platform = 'whatsapp' as const; private readonly authDir: string; private readonly onMessage: InboundHandler; private readonly log: WhatsAppAdapterOptions['log']; private readonly browserResolver: WaBrowserResolver; private readonly clientFactory: WaClientFactory; private readonly releaseStaleBrowser: (profileDir: string) => Promise; private readonly backoffCap: number; private running = false; private connected = false; private lastError: string | undefined; private lastActivityAt: number | undefined; private qr: string | undefined; private detail: string | undefined; private client: WaClientLike | null = null; private reconnectTimer: NodeJS.Timeout | null = null; private backoff: number; /** Bumped by stop() so a connect still awaiting the browser can bail out. */ private generation = 0; constructor(opts: WhatsAppAdapterOptions) { this.authDir = path.join(opts.dataDir, 'channels', 'whatsapp'); this.onMessage = opts.onMessage; this.log = opts.log; this.browserResolver = opts.browserResolver ?? (async onProgress => ( await resolveWhatsAppBrowser({ dataDir: opts.dataDir, onProgress }) ).executablePath); this.clientFactory = opts.clientFactory ?? defaultClientFactory; this.releaseStaleBrowser = opts.releaseStaleBrowser ?? (profileDir => releaseOrphanedBrowser(profileDir)); this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS; this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap); } /** * Returns once the connection attempt is under way. Finding or downloading * the browser and loading WhatsApp Web continue in the background and show * up in getStatus(). */ async start(): Promise { if (this.running) return; this.running = true; this.lastError = undefined; void this.connect(); } async stop(): Promise { this.running = false; this.generation += 1; if (this.reconnectTimer) clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.connected = false; this.qr = undefined; this.detail = undefined; await this.teardownClient(); } getStatus(): WhatsAppStatus { return { platform: this.platform, running: this.running, connected: this.connected, lastError: this.lastError, lastActivityAt: this.lastActivityAt, qr: this.qr, paired: this.hasLinkedSession(), detail: this.detail, }; } async send(chatId: string, text: string): Promise { const client = this.client; if (!client || !this.connected) throw new Error('WhatsApp is not connected'); for (const chunk of chunkText(text, WHATSAPP_MAX_TEXT)) { await client.sendMessage(chatId, chunk); } } // ── Connection lifecycle ───────────────────────────────────────────── private async connect(): Promise { const generation = this.generation; const current = () => this.running && generation === this.generation; let executablePath: string; try { this.detail = 'Looking for Chrome, Edge or Chromium'; executablePath = await this.browserResolver(percent => { if (current()) this.detail = `Downloading a browser for WhatsApp (about 170 MB): ${percent}%`; }); } catch (e: unknown) { if (!current()) return; const message = e instanceof Error ? e.message : String(e); // A missing browser needs the user to act, so do not retry on a timer. this.handleDrop(message, !(e instanceof WhatsAppBrowserError)); return; } if (!current()) return; let client: WaClientLike; try { this.detail = 'Starting the browser'; // LocalAuth keeps the profile in /session. const lock = await this.releaseStaleBrowser(path.join(this.authDir, 'session')); if (!current()) return; if (lock.kind === 'in-use') { // Another server's live session: taking it over would only make the two // stop each other's WhatsApp, so wait for the user instead. this.handleDrop( `another Waggle server on this computer is running WhatsApp with this session (browser pid ${lock.pid}); stop WhatsApp there, then start it here`, false, ); return; } if (lock.kind === 'released') { this.log.warn(`[whatsapp] stopped a browser left over from an earlier run (pid ${lock.pid})`); } client = await this.clientFactory({ authDir: this.authDir, executablePath }); } catch (e: unknown) { if (current()) this.handleDrop(e instanceof Error ? e.message : String(e), true); return; } if (!current()) { void client.destroy().catch(() => undefined); return; } this.client = client; this.attach(client); try { await client.initialize(); } catch (e: unknown) { if (this.client !== client) return; this.handleDrop(`browser session failed: ${e instanceof Error ? e.message : String(e)}`, true); } } private attach(client: WaClientLike): void { const live = () => this.client === client; client.on('qr', qr => { if (!live()) return; this.qr = qr; this.detail = undefined; this.log.info('[whatsapp] pairing QR refreshed; scan it from Settings > Channels'); }); client.on('authenticated', () => { if (!live()) return; this.qr = undefined; this.detail = 'Linked. Loading WhatsApp'; }); client.on('ready', () => { if (!live()) return; this.connected = true; this.qr = undefined; this.detail = undefined; this.lastError = undefined; this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap); this.lastActivityAt = Date.now(); this.markLinked(true); this.log.info('[whatsapp] connected'); }); client.on('auth_failure', reason => { if (!live()) return; this.handleDrop(`stored session rejected (${reason}); start WhatsApp again to re-pair via QR`, false); // The stored session cannot be restored. Delete the profile once the // browser has closed so the next start shows a fresh QR. void client.destroy().catch(() => undefined).then(() => this.wipeSession()); }); client.on('disconnected', reason => { if (!live()) return; if (reason === 'LOGOUT') { // Unlinked from the phone. whatsapp-web.js has already deleted the // profile and reloads WhatsApp Web, which emits a fresh QR. this.connected = false; this.markLinked(false); this.lastError = 'logged out from the phone; scan the new QR to link again'; this.log.warn(`[whatsapp] ${this.lastError}`); return; } if (BLOCKED_STATES.has(reason)) { this.handleDrop(`WhatsApp blocked this account (${reason})`, false); return; } this.handleDrop(`disconnected (${reason})`, true); }); client.on('message', raw => { if (!live()) return; const msg = this.normalize(raw); if (!msg) return; this.lastActivityAt = Date.now(); void this.onMessage(msg).catch(e => { this.log.warn(`[whatsapp] inbound handler failed: ${e instanceof Error ? e.message : e}`); }); }); } private normalize(raw: WaMessageLike): ChannelMessage | null { const chatId = raw.from; if (!chatId || raw.fromMe || raw.isStatus || raw.broadcast) return null; if (chatId === 'status@broadcast') return null; if (raw.type !== 'chat') { this.log.info(`[whatsapp] ignored a ${raw.type} message: the WhatsApp channel handles text only`); return null; } if (!raw.body) return null; return { platform: 'whatsapp', chatId, // In groups the author is the participant; in DMs it is the chat id. senderId: raw.author ?? chatId, senderName: raw._data?.notifyName ?? undefined, text: raw.body, messageId: raw.id?._serialized ?? undefined, }; } private handleDrop(reason: string, reconnect: boolean): void { void this.teardownClient(); this.connected = false; this.qr = undefined; this.detail = undefined; if (!this.running) return; this.lastError = reason; if (!reconnect) { this.log.warn(`[whatsapp] ${reason}`); return; } this.log.warn(`[whatsapp] dropped (${reason}); reconnecting in ${this.backoff}ms`); this.reconnectTimer = setTimeout(() => { void this.connect(); }, this.backoff); this.reconnectTimer.unref?.(); this.backoff = Math.min(this.backoff * 2, this.backoffCap); } private markLinked(linked: boolean): void { const marker = path.join(this.authDir, LINKED_MARKER); try { if (linked) { fs.mkdirSync(this.authDir, { recursive: true }); fs.writeFileSync(marker, new Date().toISOString(), 'utf8'); } else { fs.rmSync(marker, { force: true }); } } catch (e: unknown) { this.log.warn(`[whatsapp] failed to update the linked-session marker: ${e instanceof Error ? e.message : e}`); } } private wipeSession(): void { this.markLinked(false); try { fs.rmSync(path.join(this.authDir, 'session'), { recursive: true, force: true, maxRetries: 4 }); } catch (e: unknown) { this.log.warn(`[whatsapp] failed to clear the session: ${e instanceof Error ? e.message : e}`); } } private hasLinkedSession(): boolean { return fs.existsSync(path.join(this.authDir, LINKED_MARKER)) && fs.existsSync(path.join(this.authDir, 'session')); } private async teardownClient(): Promise { const client = this.client; this.client = null; try { await client?.destroy(); } catch { /* browser already closed */ } } }