feat(server): run the WhatsApp channel on whatsapp-web.js (P1.7)
Baileys depends on libsignal (GPL-3.0), which the sidecar bundled. The WhatsApp adapter now drives WhatsApp Web through whatsapp-web.js and keeps its public shape: start, stop, status with the pairing QR, send and inbound text. LocalAuth stores the session as a browser profile in <dataDir>/channels/whatsapp; the old Baileys state is left untouched. The browser comes from whatsapp-browser.ts: CHROME_PATH or PUPPETEER_EXECUTABLE_PATH, then an installed Chrome, Edge or Chromium (Windows, macOS, Linux), then a Chrome for Testing build downloaded on the first start into <dataDir>/browsers, with progress in the status. The root .puppeteerrc.cjs stops npm install from downloading a browser. The sidecar build keeps whatsapp-web.js external: bundled, it fails on __dirname and would inline LGPL node-webpmux. Text only, so ffmpeg is never needed. New dependencies, pinned: whatsapp-web.js 1.34.7 (Apache-2.0) and @puppeteer/browsers 2.13.0 (Apache-2.0). Transitive: puppeteer, puppeteer-core, chromium-bidi, webdriver-bidi-protocol (Apache-2.0), devtools-protocol (BSD-3-Clause), extract-zip (BSD-2-Clause), fluent-ffmpeg and the rest (MIT or ISC), and node-webpmux (LGPL-3.0-or-later, shipped as a separate package; needs the license review). Removed: @whiskeysockets/baileys and libsignal. UF-020 is now Fixed; ADR-0005 records the consequences.
This commit is contained in:
@@ -1,89 +1,113 @@
|
||||
/**
|
||||
* WhatsAppAdapter — QR surfacing, message normalization (DM + group,
|
||||
* fromMe/status filtering), logged-out auth wipe vs transient reconnect,
|
||||
* chunked send (CHANNELS-ARC P3). Fake Baileys socket; no network, no
|
||||
* real Baileys import.
|
||||
* WhatsAppAdapter on whatsapp-web.js — QR surfacing, message normalization
|
||||
* (DM + group, own/status/media filtering), logout vs transient disconnects,
|
||||
* chunked send, and the browser lookup that feeds Puppeteer (ADR-0005).
|
||||
* whatsapp-web.js and @puppeteer/browsers are mocked: no network, no browser.
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { BufferJSON, initAuthCreds } from '@whiskeysockets/baileys';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const wweb = vi.hoisted(() => ({
|
||||
clients: [] as Array<{ options: Record<string, unknown> }>,
|
||||
}));
|
||||
|
||||
vi.mock('whatsapp-web.js', async () => {
|
||||
const { EventEmitter: Emitter } = await import('node:events');
|
||||
class LocalAuth {
|
||||
constructor(readonly opts: { dataPath: string }) {}
|
||||
}
|
||||
class Client extends Emitter {
|
||||
sends: Array<{ chatId: string; text: string }> = [];
|
||||
initialized = 0;
|
||||
destroyed = 0;
|
||||
constructor(readonly options: Record<string, unknown>) {
|
||||
super();
|
||||
wweb.clients.push(this);
|
||||
}
|
||||
async initialize(): Promise<void> { this.initialized += 1; }
|
||||
async sendMessage(chatId: string, text: string): Promise<unknown> {
|
||||
this.sends.push({ chatId, text });
|
||||
return {};
|
||||
}
|
||||
async destroy(): Promise<void> { this.destroyed += 1; }
|
||||
}
|
||||
return { default: { Client, LocalAuth } };
|
||||
});
|
||||
|
||||
const puppeteerBrowsers = vi.hoisted(() => ({
|
||||
detectBrowserPlatform: vi.fn<() => string | undefined>(() => 'mac_arm'),
|
||||
getInstalledBrowsers: vi.fn(async (): Promise<Array<Record<string, string>>> => []),
|
||||
resolveBuildId: vi.fn(async () => '150.0.0.0'),
|
||||
install: vi.fn(),
|
||||
uninstall: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
vi.mock('@puppeteer/browsers', () => ({
|
||||
...puppeteerBrowsers,
|
||||
Browser: { CHROME: 'chrome' },
|
||||
ChromeReleaseChannel: { STABLE: 'stable' },
|
||||
}));
|
||||
|
||||
import {
|
||||
WhatsAppAdapter,
|
||||
WHATSAPP_AUTH_VAULT_KEY,
|
||||
WHATSAPP_MAX_TEXT,
|
||||
disconnectStatusCode,
|
||||
useVaultWhatsAppAuthState,
|
||||
type WaBrowserResolver,
|
||||
type WaMessageLike,
|
||||
} from '../src/local/channels/whatsapp-adapter.js';
|
||||
import type { WaSocketLike } from '../src/local/channels/whatsapp-adapter.js';
|
||||
import {
|
||||
browserCandidates,
|
||||
findInstalledBrowser,
|
||||
resolveWhatsAppBrowser,
|
||||
WhatsAppBrowserError,
|
||||
} from '../src/local/channels/whatsapp-browser.js';
|
||||
import type { ChannelMessage } from '../src/local/channels/types.js';
|
||||
|
||||
const noopLog = { info: () => undefined, warn: () => undefined };
|
||||
const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
|
||||
class FakeAuthVault {
|
||||
readonly entries = new Map<string, string>();
|
||||
get(key: string) {
|
||||
const value = this.entries.get(key);
|
||||
return value === undefined ? null : { value };
|
||||
}
|
||||
has(key: string): boolean { return this.entries.has(key); }
|
||||
set(key: string, value: string): void { this.entries.set(key, value); }
|
||||
delete(key: string): boolean { return this.entries.delete(key); }
|
||||
}
|
||||
|
||||
type Handler = (arg: unknown) => void;
|
||||
|
||||
class FakeWaSocket implements WaSocketLike {
|
||||
sends: Array<{ jid: string; text: string }> = [];
|
||||
ended = false;
|
||||
private handlers = new Map<string, Handler[]>();
|
||||
|
||||
ev = {
|
||||
on: (event: string, cb: Handler): void => {
|
||||
this.handlers.set(event, [...(this.handlers.get(event) ?? []), cb]);
|
||||
},
|
||||
} as WaSocketLike['ev'];
|
||||
|
||||
async sendMessage(jid: string, content: { text: string }): Promise<unknown> {
|
||||
this.sends.push({ jid, text: content.text });
|
||||
return {};
|
||||
}
|
||||
|
||||
end(): void {
|
||||
this.ended = true;
|
||||
}
|
||||
|
||||
emit(event: string, arg: unknown): void {
|
||||
for (const cb of this.handlers.get(event) ?? []) cb(arg);
|
||||
}
|
||||
}
|
||||
|
||||
function loggedOutError(code: number): { error: unknown } {
|
||||
return { error: { output: { statusCode: code } } };
|
||||
interface FakeClient extends EventEmitter {
|
||||
options: Record<string, unknown>;
|
||||
sends: Array<{ chatId: string; text: string }>;
|
||||
initialized: number;
|
||||
destroyed: number;
|
||||
}
|
||||
|
||||
let dir: string;
|
||||
let adapter: WhatsAppAdapter | null = null;
|
||||
|
||||
function makeAdapter() {
|
||||
const sockets: FakeWaSocket[] = [];
|
||||
function clientAt(index: number): FakeClient {
|
||||
return wweb.clients[index] as unknown as FakeClient;
|
||||
}
|
||||
|
||||
async function startAdapter(opts: { browserResolver?: WaBrowserResolver } = {}) {
|
||||
const received: ChannelMessage[] = [];
|
||||
const vault = new FakeAuthVault();
|
||||
const a = new WhatsAppAdapter({
|
||||
dataDir: dir,
|
||||
vault,
|
||||
onMessage: async m => { received.push(m); },
|
||||
log: noopLog,
|
||||
socketFactory: async () => {
|
||||
const s = new FakeWaSocket();
|
||||
sockets.push(s);
|
||||
return s;
|
||||
},
|
||||
browserResolver: opts.browserResolver ?? (async () => CHROME),
|
||||
backoffCapMs: 10,
|
||||
});
|
||||
return { a, sockets, received, vault };
|
||||
adapter = a;
|
||||
await a.start();
|
||||
if (!opts.browserResolver) await vi.waitFor(() => expect(wweb.clients.length).toBe(1));
|
||||
return { a, received };
|
||||
}
|
||||
|
||||
function textMessage(overrides: Partial<WaMessageLike> = {}): WaMessageLike {
|
||||
return {
|
||||
from: '3816x@c.us',
|
||||
fromMe: false,
|
||||
body: 'zdravo',
|
||||
type: 'chat',
|
||||
id: { _serialized: 'false_3816x@c.us_m1' },
|
||||
_data: { notifyName: 'Marko' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function tick(ms = 30): Promise<void> {
|
||||
@@ -92,260 +116,333 @@ async function tick(ms = 30): Promise<void> {
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-wa-'));
|
||||
wweb.clients.length = 0;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await adapter?.stop();
|
||||
adapter = null;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('WhatsAppAdapter client setup', () => {
|
||||
it('launches whatsapp-web.js with the found browser and keeps its state in the data dir', async () => {
|
||||
await startAdapter();
|
||||
const client = clientAt(0);
|
||||
const authDir = path.join(dir, 'channels', 'whatsapp');
|
||||
expect(client.initialized).toBe(1);
|
||||
expect((client.options.authStrategy as { opts: { dataPath: string } }).opts.dataPath).toBe(authDir);
|
||||
expect(client.options.webVersionCache).toEqual({ type: 'local', path: path.join(authDir, 'web-cache') });
|
||||
expect(client.options.puppeteer).toMatchObject({
|
||||
executablePath: CHROME,
|
||||
headless: true,
|
||||
handleSIGINT: false,
|
||||
handleSIGTERM: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports the download progress while the browser is being fetched', async () => {
|
||||
let finish: (value: string) => void = () => undefined;
|
||||
let report: (percent: number) => void = () => undefined;
|
||||
const { a } = await startAdapter({
|
||||
browserResolver: onProgress => {
|
||||
report = onProgress;
|
||||
return new Promise<string>(resolve => { finish = resolve; });
|
||||
},
|
||||
});
|
||||
report(42);
|
||||
expect(a.getStatus().detail).toMatch(/Downloading a browser.*42%/);
|
||||
expect(wweb.clients).toHaveLength(0);
|
||||
|
||||
finish(CHROME);
|
||||
await vi.waitFor(() => expect(wweb.clients.length).toBe(1));
|
||||
clientAt(0).emit('qr', 'QR-DATA');
|
||||
expect(a.getStatus().detail).toBeUndefined();
|
||||
});
|
||||
|
||||
it('stays stopped with a clear error when no browser can be found or downloaded', async () => {
|
||||
const { a } = await startAdapter({
|
||||
browserResolver: async () => {
|
||||
throw new WhatsAppBrowserError('No Chrome, Edge or Chromium found, and downloading one failed (offline).');
|
||||
},
|
||||
});
|
||||
await vi.waitFor(() => expect(a.getStatus().lastError).toMatch(/No Chrome, Edge or Chromium/));
|
||||
await tick(50);
|
||||
expect(wweb.clients).toHaveLength(0);
|
||||
expect(a.getStatus().connected).toBe(false);
|
||||
});
|
||||
|
||||
it('does not create a client when stopped while the browser is still being resolved', async () => {
|
||||
let finish: (value: string) => void = () => undefined;
|
||||
const { a } = await startAdapter({
|
||||
browserResolver: () => new Promise<string>(resolve => { finish = resolve; }),
|
||||
});
|
||||
await a.stop();
|
||||
finish(CHROME);
|
||||
await tick(20);
|
||||
expect(wweb.clients).toHaveLength(0);
|
||||
adapter = null;
|
||||
});
|
||||
});
|
||||
|
||||
describe('WhatsAppAdapter pairing + status', () => {
|
||||
it('surfaces the QR through status and clears it once connected', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
ctx.sockets[0].emit('connection.update', { qr: 'QR-DATA-1' });
|
||||
expect(adapter.getStatus().qr).toBe('QR-DATA-1');
|
||||
expect(adapter.getStatus().connected).toBe(false);
|
||||
const { a } = await startAdapter();
|
||||
clientAt(0).emit('qr', 'QR-DATA-1');
|
||||
expect(a.getStatus().qr).toBe('QR-DATA-1');
|
||||
expect(a.getStatus().connected).toBe(false);
|
||||
|
||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
||||
expect(adapter.getStatus().connected).toBe(true);
|
||||
expect(adapter.getStatus().qr).toBeUndefined();
|
||||
clientAt(0).emit('authenticated');
|
||||
clientAt(0).emit('ready');
|
||||
expect(a.getStatus().connected).toBe(true);
|
||||
expect(a.getStatus().qr).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reports paired=true when creds.json exists on disk', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
expect(adapter.getStatus().paired).toBe(false);
|
||||
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp-auth'), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'channels', 'whatsapp-auth', 'creds.json'), '{}', 'utf8');
|
||||
expect(adapter.getStatus().paired).toBe(true);
|
||||
});
|
||||
|
||||
it('reports paired=true from registered encrypted Vault credentials', async () => {
|
||||
const ctx = makeAdapter();
|
||||
ctx.vault.set(WHATSAPP_AUTH_VAULT_KEY, JSON.stringify({
|
||||
version: 1,
|
||||
creds: { registered: true },
|
||||
keys: [],
|
||||
}));
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
expect(adapter.getStatus().paired).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WhatsApp encrypted auth state', () => {
|
||||
it('persists and reloads credentials and signal keys without plaintext files', async () => {
|
||||
const vault = new FakeAuthVault();
|
||||
const legacyDir = path.join(dir, 'channels', 'whatsapp-auth');
|
||||
const first = await useVaultWhatsAppAuthState(vault, legacyDir);
|
||||
first.state.creds.registered = true;
|
||||
await first.state.keys.set({
|
||||
'pre-key': {
|
||||
'7': { private: Buffer.from([1, 2]), public: Buffer.from([3, 4]) },
|
||||
},
|
||||
});
|
||||
first.saveCreds();
|
||||
|
||||
expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(true);
|
||||
expect(fs.existsSync(legacyDir)).toBe(false);
|
||||
|
||||
const reloaded = await useVaultWhatsAppAuthState(vault, legacyDir);
|
||||
const keys = await reloaded.state.keys.get('pre-key', ['7']);
|
||||
expect(reloaded.state.creds.registered).toBe(true);
|
||||
expect(Buffer.from(keys['7'].private)).toEqual(Buffer.from([1, 2]));
|
||||
expect(Buffer.from(keys['7'].public)).toEqual(Buffer.from([3, 4]));
|
||||
});
|
||||
|
||||
it('migrates a legacy multi-file pairing before deleting plaintext', async () => {
|
||||
const vault = new FakeAuthVault();
|
||||
const legacyDir = path.join(dir, 'channels', 'whatsapp-auth');
|
||||
fs.mkdirSync(legacyDir, { recursive: true });
|
||||
const creds = initAuthCreds();
|
||||
creds.registered = true;
|
||||
fs.writeFileSync(
|
||||
path.join(legacyDir, 'creds.json'),
|
||||
JSON.stringify(creds, BufferJSON.replacer),
|
||||
'utf8',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(legacyDir, 'pre-key-9.json'),
|
||||
JSON.stringify({ private: Buffer.from([5]), public: Buffer.from([6]) }, BufferJSON.replacer),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
const migrated = await useVaultWhatsAppAuthState(vault, legacyDir);
|
||||
const keys = await migrated.state.keys.get('pre-key', ['9']);
|
||||
|
||||
expect(migrated.state.creds.registered).toBe(true);
|
||||
expect(Buffer.from(keys['9'].private)).toEqual(Buffer.from([5]));
|
||||
expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(true);
|
||||
expect(fs.existsSync(legacyDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('fails closed and preserves unreadable encrypted state', async () => {
|
||||
const vault = new FakeAuthVault();
|
||||
const legacyDir = path.join(dir, 'channels', 'whatsapp-auth');
|
||||
vault.set(WHATSAPP_AUTH_VAULT_KEY, '{broken');
|
||||
|
||||
await expect(useVaultWhatsAppAuthState(vault, legacyDir)).rejects.toThrow(/unreadable/i);
|
||||
|
||||
expect(vault.entries.get(WHATSAPP_AUTH_VAULT_KEY)).toBe('{broken');
|
||||
});
|
||||
|
||||
it('fails closed and preserves legacy files when migration cannot parse them', async () => {
|
||||
const vault = new FakeAuthVault();
|
||||
const legacyDir = path.join(dir, 'channels', 'whatsapp-auth');
|
||||
fs.mkdirSync(legacyDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(legacyDir, 'creds.json'), '{broken', 'utf8');
|
||||
|
||||
await expect(useVaultWhatsAppAuthState(vault, legacyDir)).rejects.toThrow(/could not be migrated/i);
|
||||
|
||||
expect(fs.existsSync(path.join(legacyDir, 'creds.json'))).toBe(true);
|
||||
expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(false);
|
||||
it('reports paired=true once a linked session is stored on disk', async () => {
|
||||
const { a } = await startAdapter();
|
||||
expect(a.getStatus().paired).toBe(false);
|
||||
// LocalAuth creates the profile directory before the browser starts.
|
||||
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true });
|
||||
clientAt(0).emit('ready');
|
||||
expect(a.getStatus().paired).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WhatsAppAdapter inbound', () => {
|
||||
it('normalizes a DM: sender = chat jid', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
ctx.sockets[0].emit('messages.upsert', {
|
||||
type: 'notify',
|
||||
messages: [{
|
||||
key: { remoteJid: '3816x@s.whatsapp.net', fromMe: false, id: 'm1' },
|
||||
pushName: 'Marko',
|
||||
message: { conversation: 'zdravo' },
|
||||
}],
|
||||
});
|
||||
it('normalizes a DM: sender = chat id', async () => {
|
||||
const { received } = await startAdapter();
|
||||
clientAt(0).emit('message', textMessage());
|
||||
await tick(5);
|
||||
expect(ctx.received[0]).toEqual({
|
||||
expect(received[0]).toEqual({
|
||||
platform: 'whatsapp',
|
||||
chatId: '3816x@s.whatsapp.net',
|
||||
senderId: '3816x@s.whatsapp.net',
|
||||
chatId: '3816x@c.us',
|
||||
senderId: '3816x@c.us',
|
||||
senderName: 'Marko',
|
||||
text: 'zdravo',
|
||||
messageId: 'm1',
|
||||
messageId: 'false_3816x@c.us_m1',
|
||||
});
|
||||
});
|
||||
|
||||
it('normalizes a group message: sender = participant', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
ctx.sockets[0].emit('messages.upsert', {
|
||||
type: 'notify',
|
||||
messages: [{
|
||||
key: { remoteJid: 'grp@g.us', fromMe: false, id: 'm2', participant: 'u9@s.whatsapp.net' },
|
||||
message: { extendedTextMessage: { text: 'group hi' } },
|
||||
}],
|
||||
});
|
||||
it('normalizes a group message: sender = author', async () => {
|
||||
const { received } = await startAdapter();
|
||||
clientAt(0).emit('message', textMessage({
|
||||
from: 'grp@g.us',
|
||||
author: 'u9@c.us',
|
||||
body: 'group hi',
|
||||
id: { _serialized: 'false_grp@g.us_m2' },
|
||||
}));
|
||||
await tick(5);
|
||||
expect(ctx.received[0]?.senderId).toBe('u9@s.whatsapp.net');
|
||||
expect(ctx.received[0]?.chatId).toBe('grp@g.us');
|
||||
expect(ctx.received[0]?.text).toBe('group hi');
|
||||
expect(received[0]?.senderId).toBe('u9@c.us');
|
||||
expect(received[0]?.chatId).toBe('grp@g.us');
|
||||
expect(received[0]?.text).toBe('group hi');
|
||||
});
|
||||
|
||||
it('filters own messages, status broadcasts, non-notify batches, and non-text', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
const s = ctx.sockets[0];
|
||||
s.emit('messages.upsert', {
|
||||
type: 'notify',
|
||||
messages: [
|
||||
{ key: { remoteJid: 'a@s.whatsapp.net', fromMe: true, id: '1' }, message: { conversation: 'me' } },
|
||||
{ key: { remoteJid: 'status@broadcast', fromMe: false, id: '2' }, message: { conversation: 's' } },
|
||||
{ key: { remoteJid: 'b@s.whatsapp.net', fromMe: false, id: '3' }, message: {} },
|
||||
],
|
||||
});
|
||||
s.emit('messages.upsert', {
|
||||
type: 'append',
|
||||
messages: [{ key: { remoteJid: 'c@s.whatsapp.net', fromMe: false, id: '4' }, message: { conversation: 'history' } }],
|
||||
});
|
||||
it('filters own messages, status updates, broadcasts, media and empty text', async () => {
|
||||
const { received } = await startAdapter();
|
||||
const client = clientAt(0);
|
||||
client.emit('message', textMessage({ fromMe: true }));
|
||||
client.emit('message', textMessage({ from: 'status@broadcast' }));
|
||||
client.emit('message', textMessage({ isStatus: true }));
|
||||
client.emit('message', textMessage({ broadcast: true }));
|
||||
client.emit('message', textMessage({ type: 'ptt', body: '' }));
|
||||
client.emit('message', textMessage({ type: 'image', body: 'a caption' }));
|
||||
client.emit('message', textMessage({ body: '' }));
|
||||
await tick(5);
|
||||
expect(ctx.received).toEqual([]);
|
||||
expect(received).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WhatsAppAdapter disconnects', () => {
|
||||
it('reconnects on transient close codes', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
||||
ctx.sockets[0].emit('connection.update', {
|
||||
connection: 'close',
|
||||
lastDisconnect: loggedOutError(408), // timeout — transient
|
||||
});
|
||||
await tick(50);
|
||||
expect(ctx.sockets.length).toBeGreaterThanOrEqual(2);
|
||||
it('reconnects with a new client on transient disconnects', async () => {
|
||||
await startAdapter();
|
||||
clientAt(0).emit('ready');
|
||||
clientAt(0).emit('disconnected', 'CONFLICT');
|
||||
await vi.waitFor(() => expect(wweb.clients.length).toBeGreaterThanOrEqual(2));
|
||||
expect(clientAt(0).destroyed).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('wipes auth state and does NOT reconnect on loggedOut (401)', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
const authDir = path.join(dir, 'channels', 'whatsapp-auth');
|
||||
fs.mkdirSync(authDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(authDir, 'creds.json'), '{}', 'utf8');
|
||||
ctx.vault.set(WHATSAPP_AUTH_VAULT_KEY, JSON.stringify({
|
||||
version: 1,
|
||||
creds: { registered: true },
|
||||
keys: [],
|
||||
}));
|
||||
it('keeps the client on logout so whatsapp-web.js can show a fresh QR', async () => {
|
||||
const { a } = await startAdapter();
|
||||
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true });
|
||||
clientAt(0).emit('ready');
|
||||
expect(a.getStatus().paired).toBe(true);
|
||||
|
||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
||||
ctx.sockets[0].emit('connection.update', {
|
||||
connection: 'close',
|
||||
lastDisconnect: loggedOutError(401),
|
||||
});
|
||||
await tick(50);
|
||||
expect(ctx.sockets.length).toBe(1); // no reconnect
|
||||
expect(fs.existsSync(path.join(authDir, 'creds.json'))).toBe(false);
|
||||
expect(ctx.vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(false);
|
||||
expect(adapter.getStatus().lastError).toMatch(/re-pair/i);
|
||||
clientAt(0).emit('disconnected', 'LOGOUT');
|
||||
expect(a.getStatus().connected).toBe(false);
|
||||
expect(a.getStatus().paired).toBe(false);
|
||||
expect(a.getStatus().lastError).toMatch(/new QR/i);
|
||||
|
||||
clientAt(0).emit('qr', 'QR-AFTER-LOGOUT');
|
||||
expect(a.getStatus().qr).toBe('QR-AFTER-LOGOUT');
|
||||
await tick(30);
|
||||
expect(wweb.clients).toHaveLength(1);
|
||||
expect(clientAt(0).destroyed).toBe(0);
|
||||
});
|
||||
|
||||
it('stop() ends the socket and halts reconnection', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
||||
await adapter.stop();
|
||||
expect(ctx.sockets[0].ended).toBe(true);
|
||||
ctx.sockets[0].emit('connection.update', { connection: 'close', lastDisconnect: loggedOutError(408) });
|
||||
it('does not reconnect when WhatsApp blocked the account', async () => {
|
||||
const { a } = await startAdapter();
|
||||
clientAt(0).emit('ready');
|
||||
clientAt(0).emit('disconnected', 'TOS_BLOCK');
|
||||
await tick(50);
|
||||
expect(ctx.sockets.length).toBe(1);
|
||||
expect(wweb.clients).toHaveLength(1);
|
||||
expect(a.getStatus().lastError).toMatch(/blocked/i);
|
||||
});
|
||||
|
||||
it('drops a rejected stored session and waits for the user', async () => {
|
||||
const { a } = await startAdapter();
|
||||
const sessionDir = path.join(dir, 'channels', 'whatsapp', 'session');
|
||||
fs.mkdirSync(sessionDir, { recursive: true });
|
||||
clientAt(0).emit('auth_failure', 'restore failed');
|
||||
await vi.waitFor(() => expect(fs.existsSync(sessionDir)).toBe(false));
|
||||
await tick(30);
|
||||
expect(wweb.clients).toHaveLength(1);
|
||||
expect(a.getStatus().lastError).toMatch(/re-pair/i);
|
||||
});
|
||||
|
||||
it('stop() destroys the client and halts reconnection', async () => {
|
||||
const { a } = await startAdapter();
|
||||
const client = clientAt(0);
|
||||
client.emit('ready');
|
||||
await a.stop();
|
||||
expect(client.destroyed).toBe(1);
|
||||
client.emit('disconnected', 'CONFLICT');
|
||||
await tick(50);
|
||||
expect(wweb.clients).toHaveLength(1);
|
||||
adapter = null;
|
||||
});
|
||||
});
|
||||
|
||||
describe('WhatsAppAdapter send', () => {
|
||||
it('chunks long text and targets the jid', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await adapter.start();
|
||||
await adapter.send('x@s.whatsapp.net', 'w'.repeat(WHATSAPP_MAX_TEXT + 50));
|
||||
expect(ctx.sockets[0].sends.length).toBe(2);
|
||||
expect(ctx.sockets[0].sends[0].jid).toBe('x@s.whatsapp.net');
|
||||
it('chunks long text and targets the chat id', async () => {
|
||||
const { a } = await startAdapter();
|
||||
clientAt(0).emit('ready');
|
||||
await a.send('x@c.us', 'w'.repeat(WHATSAPP_MAX_TEXT + 50));
|
||||
expect(clientAt(0).sends).toHaveLength(2);
|
||||
expect(clientAt(0).sends[0].chatId).toBe('x@c.us');
|
||||
});
|
||||
|
||||
it('throws when not connected', async () => {
|
||||
const ctx = makeAdapter();
|
||||
adapter = ctx.a;
|
||||
await expect(adapter.send('x@s.whatsapp.net', 'hi')).rejects.toThrow(/not connected/);
|
||||
const { a } = await startAdapter();
|
||||
await expect(a.send('x@c.us', 'hi')).rejects.toThrow(/not connected/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('disconnectStatusCode', () => {
|
||||
it('extracts boom-style status codes and tolerates garbage', () => {
|
||||
expect(disconnectStatusCode(loggedOutError(401))).toBe(401);
|
||||
expect(disconnectStatusCode({ error: new Error('plain') })).toBeUndefined();
|
||||
expect(disconnectStatusCode(undefined)).toBeUndefined();
|
||||
describe('WhatsApp browser lookup', () => {
|
||||
const onlyExisting = (...paths: string[]) => (candidate: string) => paths.includes(candidate);
|
||||
|
||||
it('finds Chrome, then Edge, on Windows in Program Files and LOCALAPPDATA', () => {
|
||||
const env = {
|
||||
ProgramFiles: 'C:\\Program Files',
|
||||
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
|
||||
LOCALAPPDATA: 'C:\\Users\\ana\\AppData\\Local',
|
||||
};
|
||||
const edge = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
|
||||
const userChrome = 'C:\\Users\\ana\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe';
|
||||
expect(findInstalledBrowser({ platform: 'win32', env, exists: onlyExisting(edge) })).toBe(edge);
|
||||
expect(findInstalledBrowser({ platform: 'win32', env, exists: onlyExisting(edge, userChrome) }))
|
||||
.toBe(userChrome);
|
||||
});
|
||||
|
||||
it('finds Chrome, Edge or Chromium app bundles on macOS, including ~/Applications', () => {
|
||||
const env = { HOME: '/Users/ana' };
|
||||
const userChromium = '/Users/ana/Applications/Chromium.app/Contents/MacOS/Chromium';
|
||||
const edge = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge';
|
||||
expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(userChromium) }))
|
||||
.toBe(userChromium);
|
||||
expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(userChromium, edge) }))
|
||||
.toBe(edge);
|
||||
expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(CHROME, edge) }))
|
||||
.toBe(CHROME);
|
||||
});
|
||||
|
||||
it('finds browsers on Linux through PATH and the standard locations', () => {
|
||||
const env = { PATH: '/home/ana/bin:relative/bin:/usr/bin' };
|
||||
expect(findInstalledBrowser({ platform: 'linux', env, exists: onlyExisting('/home/ana/bin/chromium') }))
|
||||
.toBe('/home/ana/bin/chromium');
|
||||
expect(findInstalledBrowser({ platform: 'linux', env, exists: onlyExisting('/snap/bin/chromium') }))
|
||||
.toBe('/snap/bin/chromium');
|
||||
expect(findInstalledBrowser({
|
||||
platform: 'linux',
|
||||
env,
|
||||
exists: onlyExisting('/usr/bin/chromium', '/opt/google/chrome/chrome'),
|
||||
})).toBe('/opt/google/chrome/chrome');
|
||||
expect(browserCandidates('linux', env).some(candidate => candidate.startsWith('relative/'))).toBe(false);
|
||||
});
|
||||
|
||||
it('prefers CHROME_PATH and PUPPETEER_EXECUTABLE_PATH over detection and skips missing ones', () => {
|
||||
const custom = '/opt/custom/chrome';
|
||||
const env = { CHROME_PATH: '/missing/chrome', PUPPETEER_EXECUTABLE_PATH: custom };
|
||||
expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(custom, CHROME) })).toBe(custom);
|
||||
expect(findInstalledBrowser({ platform: 'darwin', env: {}, exists: onlyExisting(CHROME) })).toBe(CHROME);
|
||||
});
|
||||
|
||||
it('returns null when nothing is installed', () => {
|
||||
for (const platform of ['win32', 'darwin', 'linux'] as const) {
|
||||
expect(findInstalledBrowser({ platform, env: {}, exists: () => false })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('uses an installed browser without loading the downloader', async () => {
|
||||
const resolved = await resolveWhatsAppBrowser({
|
||||
dataDir: dir, platform: 'darwin', env: {}, exists: onlyExisting(CHROME),
|
||||
});
|
||||
expect(resolved).toEqual({ executablePath: CHROME, source: 'installed' });
|
||||
expect(puppeteerBrowsers.install).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reuses a browser downloaded earlier into <dataDir>/browsers', async () => {
|
||||
const earlier = path.join(dir, 'browsers', 'chrome', 'mac_arm-149', 'chrome');
|
||||
puppeteerBrowsers.getInstalledBrowsers.mockResolvedValueOnce([
|
||||
{ browser: 'chrome', platform: 'mac_arm', buildId: '149', executablePath: earlier },
|
||||
]);
|
||||
const resolved = await resolveWhatsAppBrowser({
|
||||
dataDir: dir, platform: 'darwin', env: {}, exists: onlyExisting(earlier),
|
||||
});
|
||||
expect(resolved).toEqual({ executablePath: earlier, source: 'downloaded' });
|
||||
expect(puppeteerBrowsers.getInstalledBrowsers).toHaveBeenCalledWith({ cacheDir: path.join(dir, 'browsers') });
|
||||
expect(puppeteerBrowsers.install).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('downloads Chrome into <dataDir>/browsers when nothing is installed, reporting progress', async () => {
|
||||
const downloaded = path.join(dir, 'browsers', 'chrome', 'mac_arm-150', 'chrome');
|
||||
const partial = { browser: 'chrome', platform: 'mac_arm', buildId: '148', executablePath: '/gone' };
|
||||
puppeteerBrowsers.getInstalledBrowsers.mockResolvedValueOnce([partial]);
|
||||
puppeteerBrowsers.install.mockImplementationOnce(async (opts: {
|
||||
downloadProgressCallback: (done: number, total: number) => void;
|
||||
}) => {
|
||||
opts.downloadProgressCallback(50, 200);
|
||||
opts.downloadProgressCallback(200, 200);
|
||||
return { executablePath: downloaded };
|
||||
});
|
||||
const progress: number[] = [];
|
||||
|
||||
const resolved = await resolveWhatsAppBrowser({
|
||||
dataDir: dir, platform: 'darwin', env: {}, exists: () => false, onProgress: p => progress.push(p),
|
||||
});
|
||||
|
||||
expect(resolved).toEqual({ executablePath: downloaded, source: 'downloaded' });
|
||||
expect(puppeteerBrowsers.uninstall).toHaveBeenCalledWith(expect.objectContaining({ buildId: '148' }));
|
||||
expect(puppeteerBrowsers.install).toHaveBeenCalledWith(expect.objectContaining({
|
||||
browser: 'chrome',
|
||||
buildId: '150.0.0.0',
|
||||
cacheDir: path.join(dir, 'browsers'),
|
||||
platform: 'mac_arm',
|
||||
}));
|
||||
expect(progress).toEqual([25, 100]);
|
||||
});
|
||||
|
||||
it('fails with a clear error when nothing is installed and the download fails', async () => {
|
||||
puppeteerBrowsers.install.mockRejectedValueOnce(new Error('getaddrinfo ENOTFOUND'));
|
||||
const lookup = resolveWhatsAppBrowser({ dataDir: dir, platform: 'linux', env: {}, exists: () => false });
|
||||
await expect(lookup).rejects.toBeInstanceOf(WhatsAppBrowserError);
|
||||
await expect(lookup).rejects.toThrow(/No Chrome, Edge or Chromium found.*ENOTFOUND.*CHROME_PATH/);
|
||||
});
|
||||
|
||||
it('fails with a clear error when there is no Chrome download for this system', async () => {
|
||||
puppeteerBrowsers.detectBrowserPlatform.mockReturnValueOnce(undefined);
|
||||
await expect(resolveWhatsAppBrowser({ dataDir: dir, platform: 'linux', env: {}, exists: () => false }))
|
||||
.rejects.toThrow(/no Chrome download for this system/);
|
||||
expect(puppeteerBrowsers.install).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user