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:
11
.puppeteerrc.cjs
Normal file
11
.puppeteerrc.cjs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* Puppeteer comes in through whatsapp-web.js (ADR-0005). Installing
|
||||||
|
* dependencies must not download a browser: the WhatsApp channel uses an
|
||||||
|
* installed Chrome, Edge or Chromium and downloads one on demand only when
|
||||||
|
* none is found (packages/server/src/local/channels/whatsapp-browser.ts).
|
||||||
|
*
|
||||||
|
* @type {import('puppeteer').Configuration}
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
skipDownload: true,
|
||||||
|
};
|
||||||
@@ -16,13 +16,44 @@ of `server` and `launcher`.
|
|||||||
|
|
||||||
## Consequences
|
## Consequences
|
||||||
|
|
||||||
- `whatsapp-web.js` drives a Chrome browser through Puppeteer. The installer does not bundle a
|
Implemented in P1.7 with `whatsapp-web.js` 1.34.7 (Puppeteer 24).
|
||||||
browser, and installing dependencies does not download one.
|
|
||||||
- Open item, proposed and awaiting the owner: use an installed Edge or Chrome, and download a
|
- The adapter keeps its public shape: start, stop, status with the pairing QR, send and
|
||||||
browser (about 170 MB) only if none is found when the user enables WhatsApp.
|
inbound text. `LocalAuth` keeps the session as a browser profile in
|
||||||
- Voice and video messages go through ffmpeg, which is not bundled because ffmpeg builds carry
|
`<dataDir>/channels/whatsapp/session`, next to the WhatsApp Web page cache.
|
||||||
their own LGPL or GPL terms. Use an installed ffmpeg or download it on demand.
|
- The session is no longer encrypted at rest. Baileys state lived in the encrypted vault; the
|
||||||
- The client is unofficial. The UI warns that WhatsApp may block the account.
|
browser profile is protected only by file permissions.
|
||||||
|
- Baileys pairings are not migrated: whatsapp-web.js cannot use them. The old vault entry and
|
||||||
|
`<dataDir>/channels/whatsapp-auth` are left untouched because the data directory may still
|
||||||
|
be shared with the commercial edition. Users scan the QR once more.
|
||||||
|
- Installing dependencies does not download a browser: the root `.puppeteerrc.cjs` sets
|
||||||
|
`skipDownload`. This covers `npm install` and `npm ci` in this repository (development,
|
||||||
|
`install.sh`, Tauri staging). It does not cover `npx @waggle-ai/waggle`: there npm runs
|
||||||
|
Puppeteer's install script with no config in reach, and it downloads Chrome unless
|
||||||
|
`PUPPETEER_SKIP_DOWNLOAD=1` is set.
|
||||||
|
- Open item, implemented as proposed and still awaiting the owner: the browser source. The
|
||||||
|
order is `CHROME_PATH` or `PUPPETEER_EXECUTABLE_PATH`, an installed Chrome, Edge or Chromium
|
||||||
|
in the standard Windows, macOS and Linux locations, then a browser downloaded earlier.
|
||||||
|
Only when none is found does starting WhatsApp download the current stable Chrome for
|
||||||
|
Testing (about 170 MB) into `<dataDir>/browsers` with `@puppeteer/browsers`. Settings
|
||||||
|
shows the progress, or an error that asks the user to install Chrome or set `CHROME_PATH`.
|
||||||
|
Linux on ARM has no Chrome for Testing build, so users there install Chromium.
|
||||||
|
- The Tauri sidecar build keeps `whatsapp-web.js` and `@puppeteer/browsers` external.
|
||||||
|
Bundled into the ESM sidecar, whatsapp-web.js fails at runtime (`__dirname` is not defined).
|
||||||
|
- The channel handles text only. whatsapp-web.js needs ffmpeg only to turn videos into
|
||||||
|
stickers, which Waggle never sends, so ffmpeg is not bundled, downloaded or looked up.
|
||||||
|
Voice, video and other media messages are ignored and logged.
|
||||||
|
- New licenses: Apache-2.0 (`whatsapp-web.js`, `puppeteer`, `puppeteer-core`,
|
||||||
|
`@puppeteer/browsers`, `chromium-bidi`, `webdriver-bidi-protocol`), BSD (`devtools-protocol`,
|
||||||
|
`extract-zip`), MIT and ISC for the rest, and LGPL-3.0-or-later for `node-webpmux`, a
|
||||||
|
required dependency of whatsapp-web.js that it loads on startup for sticker metadata. It
|
||||||
|
ships as a separate, unmodified package. The licensing review has to accept it.
|
||||||
|
- The client is unofficial. Settings warns that WhatsApp may block the account and
|
||||||
|
recommends a secondary number.
|
||||||
|
- Risk: whatsapp-web.js awaits page work inside browser event listeners (for example
|
||||||
|
`inject()` after a navigation, which throws "auth timeout" when WhatsApp Web loads slowly).
|
||||||
|
Such a failure is an unhandled promise rejection, and the sidecar has no handler for those,
|
||||||
|
so Node stops the process.
|
||||||
|
|
||||||
## Alternatives considered
|
## Alternatives considered
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ Baseline: commit `b20b138` of `git.os-dev.tech/oleg.m/waggle-os`.
|
|||||||
| UF-017 | Startup text is invisible in the light theme | Open | Web UI |
|
| UF-017 | Startup text is invisible in the light theme | Open | Web UI |
|
||||||
| UF-018 | Default model shown in the top bar disagrees with Model Pilot | Open | Web UI, models |
|
| UF-018 | Default model shown in the top bar disagrees with Model Pilot | Open | Web UI, models |
|
||||||
| UF-019 | Memory count pluralization: "1 Memories" | Open | Web UI |
|
| UF-019 | Memory count pluralization: "1 Memories" | Open | Web UI |
|
||||||
| UF-020 | WhatsApp connector bundles GPL-3.0 code into the sidecar | Open | Licensing |
|
| UF-020 | WhatsApp connector bundles GPL-3.0 code into the sidecar | Fixed | Licensing |
|
||||||
| UF-021 | Settings visual-regression baseline is ignored by git | Fixed | Tests, git |
|
| UF-021 | Settings visual-regression baseline is ignored by git | Fixed | Tests, git |
|
||||||
| UF-022 | Unit tests write into the developer's real `~/.waggle` | Fixed | Tests |
|
| UF-022 | Unit tests write into the developer's real `~/.waggle` | Fixed | Tests |
|
||||||
| UF-023 | Four unit-test files fail on macOS | Open | Tests, macOS |
|
| UF-023 | Four unit-test files fail on macOS | Open | Tests, macOS |
|
||||||
@@ -206,12 +206,12 @@ Entries UF-010 to UF-019 come from the UI audit `anti-slop/audit-001-2026-10-14.
|
|||||||
- Recommendation: pluralize by count.
|
- Recommendation: pluralize by count.
|
||||||
|
|
||||||
### UF-020. WhatsApp connector bundles GPL-3.0 code into the sidecar
|
### UF-020. WhatsApp connector bundles GPL-3.0 code into the sidecar
|
||||||
- Status: Open
|
- Status: Fixed
|
||||||
- Found: 2026-10-15
|
- Found: 2026-10-15
|
||||||
- Where: `packages/server/package.json:30` and `packages/launcher/package.json:42` (`@whiskeysockets/baileys` ^7.0.0-rc13); `packages/server/src/local/channels/whatsapp-adapter.ts:118,260`; `scripts/build-sidecar.mjs` (`EXTERNAL` list)
|
- Where: `packages/server/package.json:30` and `packages/launcher/package.json:42` (`@whiskeysockets/baileys` ^7.0.0-rc13); `packages/server/src/local/channels/whatsapp-adapter.ts:118,260`; `scripts/build-sidecar.mjs` (`EXTERNAL` list)
|
||||||
- Symptom: Baileys itself is MIT, but it depends on `libsignal` 6.0.0 (`WhiskeySockets/libsignal-node`), which is GPL-3.0. Baileys is not in the esbuild `EXTERNAL` list, so the sidecar build bundles Baileys together with `libsignal` into `service.js`, which ships inside the desktop installer. This follows from the build configuration; we have not inspected a built installer.
|
- Symptom: Baileys itself is MIT, but it depends on `libsignal` 6.0.0 (`WhiskeySockets/libsignal-node`), which is GPL-3.0. Baileys is not in the esbuild `EXTERNAL` list, so the sidecar build bundles Baileys together with `libsignal` into `service.js`, which ships inside the desktop installer. This follows from the build configuration; we have not inspected a built installer.
|
||||||
- Cause: the licenses of transitive dependencies are not checked.
|
- Cause: the licenses of transitive dependencies are not checked.
|
||||||
- What we did: nothing in the main project code. The OSS edition replaces Baileys with `whatsapp-web.js` (Apache-2.0), per Egzakta decision Q5.
|
- What we did: the OSS edition replaces Baileys with `whatsapp-web.js` (Apache-2.0), per Egzakta decision Q5 (P1.7, ADR-0005). `libsignal` and Baileys are gone from the lockfile, and `whatsapp-web.js` stays outside the esbuild bundle. Its own dependency `node-webpmux` is LGPL-3.0-or-later and ships as a separate package; that is for the license review.
|
||||||
- Recommendation: include this in the license review (Q6). Shipping GPL-3.0 code inside a binary distributed under other terms is a compliance risk that needs a legal opinion. Options: replace Baileys in the main product as well, or move the WhatsApp connector into a separately installed component. Add a license check for transitive dependencies to CI.
|
- Recommendation: include this in the license review (Q6). Shipping GPL-3.0 code inside a binary distributed under other terms is a compliance risk that needs a legal opinion. Options: replace Baileys in the main product as well, or move the WhatsApp connector into a separately installed component. Add a license check for transitive dependencies to CI.
|
||||||
|
|
||||||
### UF-021. Settings visual-regression baseline is ignored by git
|
### UF-021. Settings visual-regression baseline is ignored by git
|
||||||
|
|||||||
1231
package-lock.json
generated
1231
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -39,7 +39,7 @@
|
|||||||
"@fastify/static": "^10.1.2",
|
"@fastify/static": "^10.1.2",
|
||||||
"@fastify/websocket": "^11.0.0",
|
"@fastify/websocket": "^11.0.0",
|
||||||
"@huggingface/transformers": "3.8.1",
|
"@huggingface/transformers": "3.8.1",
|
||||||
"@whiskeysockets/baileys": "^7.0.0-rc13",
|
"@puppeteer/browsers": "2.13.0",
|
||||||
"adm-zip": "^0.6.0",
|
"adm-zip": "^0.6.0",
|
||||||
"archiver": "^7.0.1",
|
"archiver": "^7.0.1",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
@@ -57,6 +57,7 @@
|
|||||||
"postgres": "^3.4.0",
|
"postgres": "^3.4.0",
|
||||||
"sqlite-vec": "^0.1.7-alpha.2",
|
"sqlite-vec": "^0.1.7-alpha.2",
|
||||||
"undici": "^6.27.0",
|
"undici": "^6.27.0",
|
||||||
|
"whatsapp-web.js": "1.34.7",
|
||||||
"ws": "^8.21.0",
|
"ws": "^8.21.0",
|
||||||
"zod": "^3.24.0"
|
"zod": "^3.24.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"@fastify/cors": "^10.0.0",
|
"@fastify/cors": "^10.0.0",
|
||||||
"@fastify/static": "^10.1.2",
|
"@fastify/static": "^10.1.2",
|
||||||
"@fastify/websocket": "^11.0.0",
|
"@fastify/websocket": "^11.0.0",
|
||||||
|
"@puppeteer/browsers": "2.13.0",
|
||||||
"@waggle/agent": "*",
|
"@waggle/agent": "*",
|
||||||
"@waggle/core": "*",
|
"@waggle/core": "*",
|
||||||
"@waggle/marketplace": "*",
|
"@waggle/marketplace": "*",
|
||||||
@@ -32,7 +33,6 @@
|
|||||||
"@waggle/waggle-dance": "*",
|
"@waggle/waggle-dance": "*",
|
||||||
"@waggle/weaver": "*",
|
"@waggle/weaver": "*",
|
||||||
"@waggle/wiki-compiler": "*",
|
"@waggle/wiki-compiler": "*",
|
||||||
"@whiskeysockets/baileys": "^7.0.0-rc13",
|
|
||||||
"adm-zip": "^0.6.0",
|
"adm-zip": "^0.6.0",
|
||||||
"archiver": "^7.0.1",
|
"archiver": "^7.0.1",
|
||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
@@ -46,6 +46,7 @@
|
|||||||
"mammoth": "^1.11.0",
|
"mammoth": "^1.11.0",
|
||||||
"pdf-parse": "^2.4.5",
|
"pdf-parse": "^2.4.5",
|
||||||
"postgres": "^3.4.0",
|
"postgres": "^3.4.0",
|
||||||
|
"whatsapp-web.js": "1.34.7",
|
||||||
"zod": "^3.24.0"
|
"zod": "^3.24.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ export const CHANNEL_VAULT_KEYS: Record<ChannelPlatform, string[]> = {
|
|||||||
telegram: ['telegram_bot_token'],
|
telegram: ['telegram_bot_token'],
|
||||||
discord: ['discord_bot_token'],
|
discord: ['discord_bot_token'],
|
||||||
slack: ['slack_app_token', 'slack_bot_token'],
|
slack: ['slack_app_token', 'slack_bot_token'],
|
||||||
whatsapp: [], // No user-entered token; Baileys state uses an encrypted Vault entry.
|
whatsapp: [], // No user-entered token; the WhatsApp Web session is a local browser profile.
|
||||||
};
|
};
|
||||||
|
|
||||||
interface ChannelVault {
|
interface ChannelVault {
|
||||||
@@ -169,11 +169,10 @@ export class ChannelManager {
|
|||||||
return new SlackAdapter({ appToken, botToken, onMessage, log: this.opts.log });
|
return new SlackAdapter({ appToken, botToken, onMessage, log: this.opts.log });
|
||||||
}
|
}
|
||||||
if (platform === 'whatsapp') {
|
if (platform === 'whatsapp') {
|
||||||
// No user-entered credential: Baileys pairs via QR and persists all
|
// No user-entered credential: whatsapp-web.js pairs via QR and keeps
|
||||||
// resulting session state through the encrypted Vault adapter.
|
// the session under <dataDir>/channels/whatsapp.
|
||||||
return new WhatsAppAdapter({
|
return new WhatsAppAdapter({
|
||||||
dataDir: this.opts.dataDir,
|
dataDir: this.opts.dataDir,
|
||||||
vault: this.opts.vault,
|
|
||||||
onMessage,
|
onMessage,
|
||||||
log: this.opts.log,
|
log: this.opts.log,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
* IM channel adapter contracts — Slack / Telegram / WhatsApp / Discord.
|
* IM channel adapter contracts — Slack / Telegram / WhatsApp / Discord.
|
||||||
*
|
*
|
||||||
* A ChannelAdapter owns exactly one platform transport (long-poll, gateway
|
* A ChannelAdapter owns exactly one platform transport (long-poll, gateway
|
||||||
* WebSocket, Socket Mode, Baileys). It normalizes inbound platform payloads
|
* WebSocket, Socket Mode, WhatsApp Web). It normalizes inbound platform payloads
|
||||||
* into ChannelMessage and hands them to the ChannelManager's inbound
|
* into ChannelMessage and hands them to the ChannelManager's inbound
|
||||||
* pipeline; it knows nothing about pairing, workspaces, or the agent loop.
|
* pipeline; it knows nothing about pairing, workspaces, or the agent loop.
|
||||||
* See docs/plans/CHANNELS-ARC-2026-07-09.md for the arc spec.
|
* See docs/plans/CHANNELS-ARC-2026-07-09.md for the arc spec.
|
||||||
|
|||||||
@@ -1,309 +1,119 @@
|
|||||||
/**
|
/**
|
||||||
* WhatsApp channel adapter — Baileys (unofficial multi-device WebSocket).
|
* WhatsApp channel adapter: whatsapp-web.js, which runs WhatsApp Web in a
|
||||||
|
* headless Chrome, Edge or Chromium through Puppeteer (ADR-0005).
|
||||||
*
|
*
|
||||||
* FOUNDER-ACCEPTED RISK (2026-07-09, docs/plans/CHANNELS-ARC-2026-07-09.md):
|
* The client is unofficial and WhatsApp may block the linked account. The
|
||||||
* Baileys is an UNOFFICIAL client that violates WhatsApp's ToS; accounts can
|
* Settings UI shows that warning and recommends a secondary number; keep it.
|
||||||
* be banned. The Settings UI must show a prominent ban-risk disclosure and
|
|
||||||
* recommend a secondary number. Do not soften or remove that copy.
|
|
||||||
*
|
*
|
||||||
* NAT-friendly: Baileys dials OUT to WhatsApp's multi-device WS. Pairing is
|
* Pairing is QR-scan like WhatsApp Web: the latest QR string is held in memory
|
||||||
* QR-scan (like WhatsApp Web): the latest QR string is held in memory and
|
* and surfaced through getStatus().qr → /api/channels for the UI to render.
|
||||||
* surfaced through getStatus().qr → /api/channels for the UI to render.
|
* LocalAuth keeps the session as a browser profile in
|
||||||
* Credentials persist as one encrypted Vault entry so pairing survives
|
* <dataDir>/channels/whatsapp/session, so pairing survives restarts. When the
|
||||||
* restarts without leaving Baileys session keys as plaintext JSON. Existing
|
* phone unlinks the device, whatsapp-web.js deletes that profile and shows a
|
||||||
* <dataDir>/channels/whatsapp-auth data is migrated once and then removed.
|
* fresh QR.
|
||||||
* DisconnectReason.loggedOut wipes the Vault entry (re-pair needed).
|
|
||||||
*
|
*
|
||||||
* Baileys is loaded via dynamic import so the sidecar boots without paying
|
* The browser comes from whatsapp-browser.ts (installed first, a one-time
|
||||||
* its (heavy: libsignal/protobuf) module cost until WhatsApp is enabled.
|
* 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 fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import type {
|
|
||||||
AuthenticationState, SignalDataSet, SignalDataTypeMap,
|
|
||||||
} from '@whiskeysockets/baileys';
|
|
||||||
import type {
|
import type {
|
||||||
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler,
|
ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler,
|
||||||
} from './types.js';
|
} from './types.js';
|
||||||
import { chunkText } from './types.js';
|
import { chunkText } from './types.js';
|
||||||
|
import { resolveWhatsAppBrowser, WhatsAppBrowserError } from './whatsapp-browser.js';
|
||||||
|
|
||||||
/** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */
|
/** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */
|
||||||
export const WHATSAPP_MAX_TEXT = 4000;
|
export const WHATSAPP_MAX_TEXT = 4000;
|
||||||
export const WHATSAPP_AUTH_VAULT_KEY = 'channel:whatsapp:auth-state';
|
|
||||||
const BACKOFF_START_MS = 2_000;
|
const BACKOFF_START_MS = 2_000;
|
||||||
const BACKOFF_CAP_MS = 60_000;
|
const BACKOFF_CAP_MS = 60_000;
|
||||||
|
/** Disconnect reasons that mean WhatsApp blocked the account: do not reconnect. */
|
||||||
export interface WhatsAppAuthVault {
|
const BLOCKED_STATES = new Set(['TOS_BLOCK', 'SMB_TOS_BLOCK']);
|
||||||
get(key: string): { value: string } | null | undefined;
|
const LINKED_MARKER = 'linked';
|
||||||
has(key: string): boolean;
|
|
||||||
set(key: string, value: string, metadata?: Record<string, unknown>): void;
|
|
||||||
delete(key: string): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface StoredWhatsAppAuth {
|
|
||||||
version: 1;
|
|
||||||
creds: AuthenticationState['creds'];
|
|
||||||
keys: Array<[string, unknown]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
type BaileysModule = typeof import('@whiskeysockets/baileys');
|
|
||||||
|
|
||||||
const SIGNAL_KEY_TYPES: Array<keyof SignalDataTypeMap> = [
|
|
||||||
'app-state-sync-version',
|
|
||||||
'app-state-sync-key',
|
|
||||||
'sender-key-memory',
|
|
||||||
'sender-key',
|
|
||||||
'identity-key',
|
|
||||||
'lid-mapping',
|
|
||||||
'device-list',
|
|
||||||
'pre-key',
|
|
||||||
'session',
|
|
||||||
'tctoken',
|
|
||||||
];
|
|
||||||
|
|
||||||
function fixLegacyFileName(value: string): string {
|
|
||||||
return value.replace(/\//g, '__').replace(/:/g, '-');
|
|
||||||
}
|
|
||||||
|
|
||||||
function signalStoreKey(type: keyof SignalDataTypeMap, id: string): string {
|
|
||||||
return `${type}:${fixLegacyFileName(id)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseStoredAuth(raw: string, baileys: BaileysModule): StoredWhatsAppAuth | null {
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(raw, baileys.BufferJSON.reviver) as Partial<StoredWhatsAppAuth>;
|
|
||||||
if (parsed.version !== 1 || !parsed.creds || !Array.isArray(parsed.keys)) return null;
|
|
||||||
const keys = parsed.keys.filter((entry): entry is [string, unknown] => (
|
|
||||||
Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'
|
|
||||||
));
|
|
||||||
return { version: 1, creds: parsed.creds, keys };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function readLegacyAuth(authDir: string, baileys: BaileysModule): StoredWhatsAppAuth | null {
|
|
||||||
const credsPath = path.join(authDir, 'creds.json');
|
|
||||||
if (!fs.existsSync(credsPath)) return null;
|
|
||||||
try {
|
|
||||||
const creds = JSON.parse(
|
|
||||||
fs.readFileSync(credsPath, 'utf8'),
|
|
||||||
baileys.BufferJSON.reviver,
|
|
||||||
) as AuthenticationState['creds'];
|
|
||||||
const keys: Array<[string, unknown]> = [];
|
|
||||||
for (const file of fs.readdirSync(authDir)) {
|
|
||||||
if (file === 'creds.json' || !file.endsWith('.json')) continue;
|
|
||||||
const base = file.slice(0, -'.json'.length);
|
|
||||||
const type = SIGNAL_KEY_TYPES.find(candidate => base.startsWith(`${candidate}-`));
|
|
||||||
if (!type) continue;
|
|
||||||
const id = base.slice(type.length + 1);
|
|
||||||
const value = JSON.parse(
|
|
||||||
fs.readFileSync(path.join(authDir, file), 'utf8'),
|
|
||||||
baileys.BufferJSON.reviver,
|
|
||||||
) as unknown;
|
|
||||||
keys.push([`${type}:${id}`, value]);
|
|
||||||
}
|
|
||||||
return { version: 1, creds, keys };
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Baileys AuthenticationState backed entirely by Waggle's encrypted Vault. */
|
|
||||||
export async function useVaultWhatsAppAuthState(
|
|
||||||
vault: WhatsAppAuthVault,
|
|
||||||
legacyAuthDir: string,
|
|
||||||
): Promise<{ state: AuthenticationState; saveCreds: () => void }> {
|
|
||||||
const baileys = await import('@whiskeysockets/baileys');
|
|
||||||
const storedExists = vault.has(WHATSAPP_AUTH_VAULT_KEY);
|
|
||||||
const storedEntry = vault.get(WHATSAPP_AUTH_VAULT_KEY);
|
|
||||||
const stored = storedEntry ? parseStoredAuth(storedEntry.value, baileys) : null;
|
|
||||||
if (storedExists && !stored) {
|
|
||||||
throw new Error('Encrypted WhatsApp auth state is unreadable; pairing state was left untouched');
|
|
||||||
}
|
|
||||||
const legacyExists = fs.existsSync(path.join(legacyAuthDir, 'creds.json'));
|
|
||||||
const legacy = stored ? null : readLegacyAuth(legacyAuthDir, baileys);
|
|
||||||
if (!stored && legacyExists && !legacy) {
|
|
||||||
throw new Error('Legacy WhatsApp auth state could not be migrated; plaintext state was left untouched');
|
|
||||||
}
|
|
||||||
const creds = stored?.creds ?? legacy?.creds ?? baileys.initAuthCreds();
|
|
||||||
const keyStore = new Map<string, unknown>(stored?.keys ?? legacy?.keys ?? []);
|
|
||||||
|
|
||||||
const persist = (): void => {
|
|
||||||
const payload: StoredWhatsAppAuth = {
|
|
||||||
version: 1,
|
|
||||||
creds,
|
|
||||||
keys: [...keyStore.entries()],
|
|
||||||
};
|
|
||||||
vault.set(
|
|
||||||
WHATSAPP_AUTH_VAULT_KEY,
|
|
||||||
JSON.stringify(payload, baileys.BufferJSON.replacer),
|
|
||||||
{ kind: 'whatsapp-auth-state', encryptedAtRest: true },
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (legacy) {
|
|
||||||
// Delete plaintext only after the encrypted write succeeds.
|
|
||||||
persist();
|
|
||||||
fs.rmSync(legacyAuthDir, { recursive: true, force: true });
|
|
||||||
} else if (stored && fs.existsSync(legacyAuthDir)) {
|
|
||||||
// Vault is authoritative; remove any stale plaintext residue.
|
|
||||||
fs.rmSync(legacyAuthDir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
const state: AuthenticationState = {
|
|
||||||
creds,
|
|
||||||
keys: {
|
|
||||||
get: async <T extends keyof SignalDataTypeMap>(type: T, ids: string[]) => {
|
|
||||||
const result = {} as Record<string, SignalDataTypeMap[T]>;
|
|
||||||
for (const id of ids) {
|
|
||||||
let value = keyStore.get(signalStoreKey(type, id));
|
|
||||||
if (type === 'app-state-sync-key' && value) {
|
|
||||||
value = baileys.proto.Message.AppStateSyncKeyData.fromObject(value as object);
|
|
||||||
}
|
|
||||||
result[id] = value as SignalDataTypeMap[T];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
},
|
|
||||||
set: async (data: SignalDataSet) => {
|
|
||||||
const categories = data as Record<string, Record<string, unknown | null> | undefined>;
|
|
||||||
for (const [category, values] of Object.entries(categories)) {
|
|
||||||
if (!values) continue;
|
|
||||||
for (const [id, value] of Object.entries(values)) {
|
|
||||||
const key = signalStoreKey(category as keyof SignalDataTypeMap, id);
|
|
||||||
if (value === null) keyStore.delete(key);
|
|
||||||
else keyStore.set(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
persist();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
return { state, saveCreds: persist };
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is a server-side state loader, not a React Hook. Use a non-hook alias
|
|
||||||
// internally so the repo-wide React lint rule can distinguish the call site.
|
|
||||||
const loadVaultWhatsAppAuthState = useVaultWhatsAppAuthState;
|
|
||||||
|
|
||||||
/** Status payload extended with the pairing QR (rendered by Settings UI). */
|
/** Status payload extended with the pairing QR (rendered by Settings UI). */
|
||||||
export interface WhatsAppStatus extends ChannelAdapterStatus {
|
export interface WhatsAppStatus extends ChannelAdapterStatus {
|
||||||
qr?: string;
|
qr?: string;
|
||||||
/** True when registered auth credentials exist in the encrypted Vault. */
|
/** True when a linked session is stored on disk. */
|
||||||
paired?: boolean;
|
paired?: boolean;
|
||||||
|
/** What the adapter is doing before the QR appears (browser lookup or download). */
|
||||||
|
detail?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Minimal structural contracts over Baileys (test seam) ──────────────
|
// ── Minimal structural contracts over whatsapp-web.js (test seam) ──────
|
||||||
|
|
||||||
interface BaileysEventMap {
|
export interface WaMessageLike {
|
||||||
'connection.update': {
|
from: string;
|
||||||
connection?: 'close' | 'connecting' | 'open';
|
/** Group messages: the participant who wrote it. */
|
||||||
qr?: string;
|
author?: string;
|
||||||
lastDisconnect?: { error?: unknown };
|
fromMe: boolean;
|
||||||
};
|
body: string;
|
||||||
'messages.upsert': {
|
/** 'chat' for text; 'image', 'video', 'ptt' (voice), 'audio', … for media. */
|
||||||
type: string;
|
type: string;
|
||||||
messages: Array<{
|
isStatus?: boolean;
|
||||||
key: { remoteJid?: string | null; fromMe?: boolean | null; id?: string | null; participant?: string | null };
|
broadcast?: boolean;
|
||||||
pushName?: string | null;
|
id?: { _serialized?: string };
|
||||||
message?: {
|
_data?: { notifyName?: string };
|
||||||
conversation?: string | null;
|
|
||||||
extendedTextMessage?: { text?: string | null } | null;
|
|
||||||
} | null;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
'creds.update': unknown;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WaSocketLike {
|
export interface WaClientLike {
|
||||||
ev: {
|
on(event: 'qr', listener: (qr: string) => void): unknown;
|
||||||
on<E extends keyof BaileysEventMap>(event: E, cb: (arg: BaileysEventMap[E]) => void): void;
|
on(event: 'authenticated' | 'ready', listener: () => void): unknown;
|
||||||
};
|
on(event: 'auth_failure' | 'disconnected', listener: (reason: string) => void): unknown;
|
||||||
sendMessage(jid: string, content: { text: string }): Promise<unknown>;
|
on(event: 'message', listener: (message: WaMessageLike) => void): unknown;
|
||||||
end?(err?: Error): void;
|
initialize(): Promise<void>;
|
||||||
|
sendMessage(chatId: string, content: string): Promise<unknown>;
|
||||||
|
destroy(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type WaSocketFactory = (
|
export type WaClientFactory = (opts: { authDir: string; executablePath: string }) => Promise<WaClientLike>;
|
||||||
vault: WhatsAppAuthVault,
|
|
||||||
legacyAuthDir: string,
|
|
||||||
onAuthError: (error: unknown) => void,
|
|
||||||
) => Promise<WaSocketLike>;
|
|
||||||
|
|
||||||
interface BaileysLogger {
|
export type WaBrowserResolver = (onProgress: (percent: number) => void) => Promise<string>;
|
||||||
level: string;
|
|
||||||
child(fields: Record<string, unknown>): BaileysLogger;
|
|
||||||
trace(value: unknown, message?: string): void;
|
|
||||||
debug(value: unknown, message?: string): void;
|
|
||||||
info(value: unknown, message?: string): void;
|
|
||||||
warn(value: unknown, message?: string): void;
|
|
||||||
error(value: unknown, message?: string): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const silentBaileysLogger: BaileysLogger = {
|
/** Production factory: real whatsapp-web.js, dynamically imported. */
|
||||||
level: 'silent',
|
async function defaultClientFactory(opts: { authDir: string; executablePath: string }): Promise<WaClientLike> {
|
||||||
child: () => silentBaileysLogger,
|
const { Client, LocalAuth } = (await import('whatsapp-web.js')).default;
|
||||||
trace: () => undefined,
|
return new Client({
|
||||||
debug: () => undefined,
|
authStrategy: new LocalAuth({ dataPath: opts.authDir }),
|
||||||
info: () => undefined,
|
// The default cache path is relative to the process cwd.
|
||||||
warn: () => undefined,
|
webVersionCache: { type: 'local', path: path.join(opts.authDir, 'web-cache') },
|
||||||
error: () => undefined,
|
puppeteer: {
|
||||||
};
|
executablePath: opts.executablePath,
|
||||||
|
headless: true,
|
||||||
/** Production factory — real Baileys, dynamically imported. */
|
// Puppeteer's own handlers would exit the process on Ctrl-C. The sidecar
|
||||||
async function defaultWaSocketFactory(
|
// shuts down itself and closes the browser through stop().
|
||||||
vault: WhatsAppAuthVault,
|
handleSIGINT: false,
|
||||||
legacyAuthDir: string,
|
handleSIGTERM: false,
|
||||||
onAuthError: (error: unknown) => void,
|
handleSIGHUP: false,
|
||||||
): Promise<WaSocketLike> {
|
},
|
||||||
const baileys = await import('@whiskeysockets/baileys');
|
|
||||||
const { state, saveCreds } = await loadVaultWhatsAppAuthState(vault, legacyAuthDir);
|
|
||||||
const sock = baileys.makeWASocket({
|
|
||||||
auth: state,
|
|
||||||
logger: silentBaileysLogger,
|
|
||||||
// No terminal QR — the Settings UI renders it from getStatus().qr.
|
|
||||||
printQRInTerminal: false,
|
|
||||||
syncFullHistory: false,
|
|
||||||
});
|
});
|
||||||
sock.ev.on('creds.update', () => {
|
|
||||||
try {
|
|
||||||
saveCreds();
|
|
||||||
} catch (error) {
|
|
||||||
onAuthError(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return sock as unknown as WaSocketLike;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Extract the Baileys disconnect status code (boom-style error). */
|
|
||||||
export function disconnectStatusCode(lastDisconnect?: { error?: unknown }): number | undefined {
|
|
||||||
const err = lastDisconnect?.error as { output?: { statusCode?: number } } | undefined;
|
|
||||||
return err?.output?.statusCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
const LOGGED_OUT = 401; // DisconnectReason.loggedOut
|
|
||||||
|
|
||||||
export interface WhatsAppAdapterOptions {
|
export interface WhatsAppAdapterOptions {
|
||||||
/** Channels data dir, used only to migrate/remove legacy plaintext state. */
|
/** Waggle data dir; the session lives in <dataDir>/channels/whatsapp. */
|
||||||
dataDir: string;
|
dataDir: string;
|
||||||
/** Encrypted store for all Baileys credentials and signal keys. */
|
|
||||||
vault: WhatsAppAuthVault;
|
|
||||||
onMessage: InboundHandler;
|
onMessage: InboundHandler;
|
||||||
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
log: { info: (msg: string) => void; warn: (msg: string) => void };
|
||||||
|
/** Test seam: finds or downloads the browser. */
|
||||||
|
browserResolver?: WaBrowserResolver;
|
||||||
/** Test seam. */
|
/** Test seam. */
|
||||||
socketFactory?: WaSocketFactory;
|
clientFactory?: WaClientFactory;
|
||||||
backoffCapMs?: number;
|
backoffCapMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class WhatsAppAdapter implements ChannelAdapter {
|
export class WhatsAppAdapter implements ChannelAdapter {
|
||||||
readonly platform = 'whatsapp' as const;
|
readonly platform = 'whatsapp' as const;
|
||||||
|
|
||||||
private readonly legacyAuthDir: string;
|
private readonly authDir: string;
|
||||||
private readonly vault: WhatsAppAuthVault;
|
|
||||||
private readonly onMessage: InboundHandler;
|
private readonly onMessage: InboundHandler;
|
||||||
private readonly log: WhatsAppAdapterOptions['log'];
|
private readonly log: WhatsAppAdapterOptions['log'];
|
||||||
private readonly socketFactory: WaSocketFactory;
|
private readonly browserResolver: WaBrowserResolver;
|
||||||
|
private readonly clientFactory: WaClientFactory;
|
||||||
private readonly backoffCap: number;
|
private readonly backoffCap: number;
|
||||||
|
|
||||||
private running = false;
|
private running = false;
|
||||||
@@ -311,33 +121,46 @@ export class WhatsAppAdapter implements ChannelAdapter {
|
|||||||
private lastError: string | undefined;
|
private lastError: string | undefined;
|
||||||
private lastActivityAt: number | undefined;
|
private lastActivityAt: number | undefined;
|
||||||
private qr: string | undefined;
|
private qr: string | undefined;
|
||||||
private sock: WaSocketLike | null = null;
|
private detail: string | undefined;
|
||||||
|
private client: WaClientLike | null = null;
|
||||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||||
private backoff: number;
|
private backoff: number;
|
||||||
|
/** Bumped by stop() so a connect still awaiting the browser can bail out. */
|
||||||
|
private generation = 0;
|
||||||
|
|
||||||
constructor(opts: WhatsAppAdapterOptions) {
|
constructor(opts: WhatsAppAdapterOptions) {
|
||||||
this.legacyAuthDir = path.join(opts.dataDir, 'channels', 'whatsapp-auth');
|
this.authDir = path.join(opts.dataDir, 'channels', 'whatsapp');
|
||||||
this.vault = opts.vault;
|
|
||||||
this.onMessage = opts.onMessage;
|
this.onMessage = opts.onMessage;
|
||||||
this.log = opts.log;
|
this.log = opts.log;
|
||||||
this.socketFactory = opts.socketFactory ?? defaultWaSocketFactory;
|
this.browserResolver = opts.browserResolver ?? (async onProgress => (
|
||||||
|
await resolveWhatsAppBrowser({ dataDir: opts.dataDir, onProgress })
|
||||||
|
).executablePath);
|
||||||
|
this.clientFactory = opts.clientFactory ?? defaultClientFactory;
|
||||||
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
|
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
|
||||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
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<void> {
|
async start(): Promise<void> {
|
||||||
if (this.running) return;
|
if (this.running) return;
|
||||||
this.running = true;
|
this.running = true;
|
||||||
this.lastError = undefined;
|
this.lastError = undefined;
|
||||||
await this.connect();
|
void this.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
async stop(): Promise<void> {
|
async stop(): Promise<void> {
|
||||||
this.running = false;
|
this.running = false;
|
||||||
|
this.generation += 1;
|
||||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||||
this.teardownSocket();
|
this.reconnectTimer = null;
|
||||||
this.connected = false;
|
this.connected = false;
|
||||||
this.qr = undefined;
|
this.qr = undefined;
|
||||||
|
this.detail = undefined;
|
||||||
|
await this.teardownClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
getStatus(): WhatsAppStatus {
|
getStatus(): WhatsAppStatus {
|
||||||
@@ -348,98 +171,160 @@ export class WhatsAppAdapter implements ChannelAdapter {
|
|||||||
lastError: this.lastError,
|
lastError: this.lastError,
|
||||||
lastActivityAt: this.lastActivityAt,
|
lastActivityAt: this.lastActivityAt,
|
||||||
qr: this.qr,
|
qr: this.qr,
|
||||||
paired: this.hasPersistedAuth(),
|
paired: this.hasLinkedSession(),
|
||||||
|
detail: this.detail,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async send(chatId: string, text: string): Promise<void> {
|
async send(chatId: string, text: string): Promise<void> {
|
||||||
if (!this.sock) throw new Error('WhatsApp is not connected');
|
const client = this.client;
|
||||||
|
if (!client || !this.connected) throw new Error('WhatsApp is not connected');
|
||||||
for (const chunk of chunkText(text, WHATSAPP_MAX_TEXT)) {
|
for (const chunk of chunkText(text, WHATSAPP_MAX_TEXT)) {
|
||||||
await this.sock.sendMessage(chatId, { text: chunk });
|
await client.sendMessage(chatId, chunk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Connection lifecycle ─────────────────────────────────────────────
|
// ── Connection lifecycle ─────────────────────────────────────────────
|
||||||
|
|
||||||
private async connect(): Promise<void> {
|
private async connect(): Promise<void> {
|
||||||
|
const generation = this.generation;
|
||||||
|
const current = () => this.running && generation === this.generation;
|
||||||
|
|
||||||
|
let executablePath: string;
|
||||||
try {
|
try {
|
||||||
const sock = await this.socketFactory(this.vault, this.legacyAuthDir, error => {
|
this.detail = 'Looking for Chrome, Edge or Chromium';
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
executablePath = await this.browserResolver(percent => {
|
||||||
this.lastError = `Could not save encrypted WhatsApp session: ${message}`;
|
if (current()) this.detail = `Downloading a browser for WhatsApp (about 170 MB): ${percent}%`;
|
||||||
this.log.warn(`[whatsapp] ${this.lastError}`);
|
|
||||||
});
|
|
||||||
this.sock = sock;
|
|
||||||
|
|
||||||
sock.ev.on('connection.update', update => {
|
|
||||||
if (update.qr) {
|
|
||||||
this.qr = update.qr;
|
|
||||||
this.log.info('[whatsapp] pairing QR refreshed — scan it from Settings → Channels');
|
|
||||||
}
|
|
||||||
if (update.connection === 'open') {
|
|
||||||
this.connected = true;
|
|
||||||
this.qr = undefined;
|
|
||||||
this.lastError = undefined;
|
|
||||||
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
|
|
||||||
this.lastActivityAt = Date.now();
|
|
||||||
this.log.info('[whatsapp] connected');
|
|
||||||
}
|
|
||||||
if (update.connection === 'close') {
|
|
||||||
const code = disconnectStatusCode(update.lastDisconnect);
|
|
||||||
if (code === LOGGED_OUT) {
|
|
||||||
// Device unlinked from the phone — credentials are dead. Wipe so
|
|
||||||
// the next start shows a fresh QR instead of a reconnect loop.
|
|
||||||
this.wipeAuthState();
|
|
||||||
this.handleDrop('logged out — re-pair via QR', false);
|
|
||||||
} else {
|
|
||||||
this.handleDrop(`connection closed (code ${code ?? 'unknown'})`, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
sock.ev.on('messages.upsert', upsert => {
|
|
||||||
if (upsert.type !== 'notify') return;
|
|
||||||
for (const raw of upsert.messages) {
|
|
||||||
const msg = this.normalize(raw);
|
|
||||||
if (!msg) continue;
|
|
||||||
this.lastActivityAt = Date.now();
|
|
||||||
void this.onMessage(msg).catch(e => {
|
|
||||||
this.log.warn(`[whatsapp] inbound handler failed: ${e instanceof Error ? e.message : e}`);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
this.handleDrop(e instanceof Error ? e.message : String(e), true);
|
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';
|
||||||
|
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 normalize(raw: BaileysEventMap['messages.upsert']['messages'][number]): ChannelMessage | null {
|
private attach(client: WaClientLike): void {
|
||||||
const jid = raw.key.remoteJid;
|
const live = () => this.client === client;
|
||||||
if (!jid || raw.key.fromMe) return null;
|
|
||||||
if (jid === 'status@broadcast') return null;
|
client.on('qr', qr => {
|
||||||
const text = raw.message?.conversation ?? raw.message?.extendedTextMessage?.text;
|
if (!live()) return;
|
||||||
if (!text) return null;
|
this.qr = qr;
|
||||||
// In groups the author is key.participant; in DMs it's the chat jid.
|
this.detail = undefined;
|
||||||
const senderId = raw.key.participant ?? jid;
|
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 {
|
return {
|
||||||
platform: 'whatsapp',
|
platform: 'whatsapp',
|
||||||
chatId: jid,
|
chatId,
|
||||||
senderId,
|
// In groups the author is the participant; in DMs it is the chat id.
|
||||||
senderName: raw.pushName ?? undefined,
|
senderId: raw.author ?? chatId,
|
||||||
text,
|
senderName: raw._data?.notifyName ?? undefined,
|
||||||
messageId: raw.key.id ?? undefined,
|
text: raw.body,
|
||||||
|
messageId: raw.id?._serialized ?? undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleDrop(reason: string, reconnect: boolean): void {
|
private handleDrop(reason: string, reconnect: boolean): void {
|
||||||
this.teardownSocket();
|
void this.teardownClient();
|
||||||
this.connected = false;
|
this.connected = false;
|
||||||
|
this.qr = undefined;
|
||||||
|
this.detail = undefined;
|
||||||
if (!this.running) return;
|
if (!this.running) return;
|
||||||
this.lastError = reason;
|
this.lastError = reason;
|
||||||
if (!reconnect) {
|
if (!reconnect) {
|
||||||
this.log.warn(`[whatsapp] ${reason}`);
|
this.log.warn(`[whatsapp] ${reason}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.log.warn(`[whatsapp] dropped (${reason}) — reconnecting in ${this.backoff}ms`);
|
this.log.warn(`[whatsapp] dropped (${reason}); reconnecting in ${this.backoff}ms`);
|
||||||
this.reconnectTimer = setTimeout(() => {
|
this.reconnectTimer = setTimeout(() => {
|
||||||
void this.connect();
|
void this.connect();
|
||||||
}, this.backoff);
|
}, this.backoff);
|
||||||
@@ -447,33 +332,39 @@ export class WhatsAppAdapter implements ChannelAdapter {
|
|||||||
this.backoff = Math.min(this.backoff * 2, this.backoffCap);
|
this.backoff = Math.min(this.backoff * 2, this.backoffCap);
|
||||||
}
|
}
|
||||||
|
|
||||||
private wipeAuthState(): void {
|
private markLinked(linked: boolean): void {
|
||||||
|
const marker = path.join(this.authDir, LINKED_MARKER);
|
||||||
try {
|
try {
|
||||||
this.vault.delete(WHATSAPP_AUTH_VAULT_KEY);
|
if (linked) {
|
||||||
fs.rmSync(this.legacyAuthDir, { recursive: true, force: true });
|
fs.mkdirSync(this.authDir, { recursive: true });
|
||||||
} catch (e: unknown) {
|
fs.writeFileSync(marker, new Date().toISOString(), 'utf8');
|
||||||
this.log.warn(`[whatsapp] failed to clear auth state: ${e instanceof Error ? e.message : e}`);
|
} else {
|
||||||
}
|
fs.rmSync(marker, { force: true });
|
||||||
}
|
|
||||||
|
|
||||||
private hasPersistedAuth(): boolean {
|
|
||||||
const entry = this.vault.get(WHATSAPP_AUTH_VAULT_KEY);
|
|
||||||
if (entry) {
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(entry.value) as { creds?: { registered?: boolean } };
|
|
||||||
return parsed.creds?.registered === true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
} catch (e: unknown) {
|
||||||
|
this.log.warn(`[whatsapp] failed to update the linked-session marker: ${e instanceof Error ? e.message : e}`);
|
||||||
}
|
}
|
||||||
// Compatibility during the one-time migration window.
|
|
||||||
return fs.existsSync(path.join(this.legacyAuthDir, 'creds.json'));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private teardownSocket(): void {
|
private wipeSession(): void {
|
||||||
|
this.markLinked(false);
|
||||||
try {
|
try {
|
||||||
this.sock?.end?.(undefined);
|
fs.rmSync(path.join(this.authDir, 'session'), { recursive: true, force: true, maxRetries: 4 });
|
||||||
} catch { /* already closed */ }
|
} catch (e: unknown) {
|
||||||
this.sock = null;
|
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<void> {
|
||||||
|
const client = this.client;
|
||||||
|
this.client = null;
|
||||||
|
try {
|
||||||
|
await client?.destroy();
|
||||||
|
} catch { /* browser already closed */ }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
198
packages/server/src/local/channels/whatsapp-browser.ts
Normal file
198
packages/server/src/local/channels/whatsapp-browser.ts
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
/**
|
||||||
|
* Browser for the WhatsApp channel (ADR-0005).
|
||||||
|
*
|
||||||
|
* whatsapp-web.js drives WhatsApp Web in a Chromium-based browser through
|
||||||
|
* Puppeteer. Waggle does not bundle a browser and installing dependencies does
|
||||||
|
* not download one (see the root .puppeteerrc.cjs). Instead, in this order:
|
||||||
|
* 1. CHROME_PATH or PUPPETEER_EXECUTABLE_PATH, when it points to a file;
|
||||||
|
* 2. an installed Chrome, Edge or Chromium in the standard locations;
|
||||||
|
* 3. a Chrome for Testing build downloaded earlier into <dataDir>/browsers;
|
||||||
|
* 4. a fresh download into <dataDir>/browsers (about 170 MB), only now that
|
||||||
|
* the user has started WhatsApp.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export const BROWSER_OVERRIDE_ENV_VARS = ['CHROME_PATH', 'PUPPETEER_EXECUTABLE_PATH'] as const;
|
||||||
|
|
||||||
|
export class WhatsAppBrowserError extends Error {
|
||||||
|
override name = 'WhatsAppBrowserError';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BrowserLookupOptions {
|
||||||
|
platform?: NodeJS.Platform;
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
/** Test seam: whether an executable exists at the path. */
|
||||||
|
exists?: (filePath: string) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const WINDOWS_BROWSERS = [
|
||||||
|
['Google', 'Chrome', 'Application', 'chrome.exe'],
|
||||||
|
['Microsoft', 'Edge', 'Application', 'msedge.exe'],
|
||||||
|
['Chromium', 'Application', 'chrome.exe'],
|
||||||
|
];
|
||||||
|
|
||||||
|
const MAC_BROWSERS = [
|
||||||
|
'Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||||
|
'Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
||||||
|
'Chromium.app/Contents/MacOS/Chromium',
|
||||||
|
];
|
||||||
|
|
||||||
|
const LINUX_BROWSERS = [
|
||||||
|
{ commands: ['google-chrome-stable', 'google-chrome'], paths: ['/opt/google/chrome/chrome'] },
|
||||||
|
{ commands: ['microsoft-edge-stable', 'microsoft-edge'], paths: ['/opt/microsoft/msedge/msedge'] },
|
||||||
|
{ commands: ['chromium', 'chromium-browser'], paths: [] },
|
||||||
|
];
|
||||||
|
|
||||||
|
function unique(values: string[]): string[] {
|
||||||
|
return [...new Set(values)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Standard install locations of Chrome, Edge and Chromium, in preference order. */
|
||||||
|
export function browserCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const roots = unique([
|
||||||
|
env['ProgramFiles'] ?? 'C:\\Program Files',
|
||||||
|
env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)',
|
||||||
|
...(env['LOCALAPPDATA'] ? [env['LOCALAPPDATA']] : []),
|
||||||
|
]);
|
||||||
|
return WINDOWS_BROWSERS.flatMap(parts => roots.map(root => path.win32.join(root, ...parts)));
|
||||||
|
}
|
||||||
|
if (platform === 'darwin') {
|
||||||
|
const roots = ['/Applications', ...(env['HOME'] ? [path.posix.join(env['HOME'], 'Applications')] : [])];
|
||||||
|
return MAC_BROWSERS.flatMap(app => roots.map(root => path.posix.join(root, app)));
|
||||||
|
}
|
||||||
|
const dirs = unique([
|
||||||
|
...(env['PATH'] ?? '').split(':').filter(dir => dir.startsWith('/')),
|
||||||
|
'/usr/bin',
|
||||||
|
'/usr/local/bin',
|
||||||
|
'/snap/bin',
|
||||||
|
]);
|
||||||
|
return unique(LINUX_BROWSERS.flatMap(browser => [
|
||||||
|
...browser.commands.flatMap(command => dirs.map(dir => path.posix.join(dir, command))),
|
||||||
|
...browser.paths,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExecutable(filePath: string): boolean {
|
||||||
|
try {
|
||||||
|
fs.accessSync(filePath, fs.constants.X_OK);
|
||||||
|
return fs.statSync(filePath).isFile();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first override or installed browser that exists, or null. */
|
||||||
|
export function findInstalledBrowser(opts: BrowserLookupOptions = {}): string | null {
|
||||||
|
const platform = opts.platform ?? process.platform;
|
||||||
|
const env = opts.env ?? process.env;
|
||||||
|
const exists = opts.exists ?? isExecutable;
|
||||||
|
const overrides = BROWSER_OVERRIDE_ENV_VARS
|
||||||
|
.map(name => env[name]?.trim())
|
||||||
|
.filter((value): value is string => Boolean(value));
|
||||||
|
return [...overrides, ...browserCandidates(platform, env)].find(candidate => exists(candidate)) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolveBrowserOptions extends BrowserLookupOptions {
|
||||||
|
/** Waggle data dir; downloads go to <dataDir>/browsers. */
|
||||||
|
dataDir: string;
|
||||||
|
/** Download progress in whole percent. */
|
||||||
|
onProgress?: (percent: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedBrowser {
|
||||||
|
executablePath: string;
|
||||||
|
source: 'installed' | 'downloaded';
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PendingDownload {
|
||||||
|
result: Promise<string>;
|
||||||
|
listeners: Set<(percent: number) => void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One lookup or download per cache dir, even if WhatsApp is restarted meanwhile. */
|
||||||
|
const pendingDownloads = new Map<string, PendingDownload>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a browser for whatsapp-web.js, downloading Chrome for Testing into
|
||||||
|
* <dataDir>/browsers only when nothing usable is installed.
|
||||||
|
*/
|
||||||
|
export async function resolveWhatsAppBrowser(opts: ResolveBrowserOptions): Promise<ResolvedBrowser> {
|
||||||
|
const installed = findInstalledBrowser(opts);
|
||||||
|
if (installed) return { executablePath: installed, source: 'installed' };
|
||||||
|
|
||||||
|
const cacheDir = path.join(opts.dataDir, 'browsers');
|
||||||
|
let pending = pendingDownloads.get(cacheDir);
|
||||||
|
if (!pending) {
|
||||||
|
const listeners = new Set<(percent: number) => void>();
|
||||||
|
const result = downloadedChrome(cacheDir, opts.exists ?? isExecutable, percent => {
|
||||||
|
for (const listener of listeners) listener(percent);
|
||||||
|
}).finally(() => pendingDownloads.delete(cacheDir));
|
||||||
|
pending = { result, listeners };
|
||||||
|
pendingDownloads.set(cacheDir, pending);
|
||||||
|
}
|
||||||
|
const onProgress = opts.onProgress;
|
||||||
|
if (onProgress) pending.listeners.add(onProgress);
|
||||||
|
try {
|
||||||
|
return { executablePath: await pending.result, source: 'downloaded' };
|
||||||
|
} finally {
|
||||||
|
if (onProgress) pending.listeners.delete(onProgress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chrome for Testing from <cacheDir>, downloaded first if it is not there yet. */
|
||||||
|
async function downloadedChrome(
|
||||||
|
cacheDir: string,
|
||||||
|
exists: (filePath: string) => boolean,
|
||||||
|
onProgress: (percent: number) => void,
|
||||||
|
): Promise<string> {
|
||||||
|
const browsers = await import('@puppeteer/browsers');
|
||||||
|
const platform = browsers.detectBrowserPlatform();
|
||||||
|
if (!platform) {
|
||||||
|
throw new WhatsAppBrowserError(
|
||||||
|
'No Chrome, Edge or Chromium found, and there is no Chrome download for this system. '
|
||||||
|
+ 'Install Chromium or Google Chrome, or set CHROME_PATH, then start WhatsApp again.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cached = (await browsers.getInstalledBrowsers({ cacheDir }))
|
||||||
|
.filter(browser => browser.browser === browsers.Browser.CHROME && browser.platform === platform);
|
||||||
|
const previous = cached.find(browser => exists(browser.executablePath));
|
||||||
|
if (previous) return previous.executablePath;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// A folder without an executable is left over from an interrupted download;
|
||||||
|
// install() refuses to overwrite it.
|
||||||
|
for (const partial of cached) {
|
||||||
|
await browsers.uninstall({ browser: partial.browser, buildId: partial.buildId, platform, cacheDir });
|
||||||
|
}
|
||||||
|
const buildId = await browsers.resolveBuildId(
|
||||||
|
browsers.Browser.CHROME,
|
||||||
|
platform,
|
||||||
|
browsers.ChromeReleaseChannel.STABLE,
|
||||||
|
);
|
||||||
|
let lastPercent = -1;
|
||||||
|
const downloaded = await browsers.install({
|
||||||
|
browser: browsers.Browser.CHROME,
|
||||||
|
buildId,
|
||||||
|
cacheDir,
|
||||||
|
platform,
|
||||||
|
downloadProgressCallback: (done, total) => {
|
||||||
|
const percent = total > 0 ? Math.floor((done / total) * 100) : 0;
|
||||||
|
if (percent !== lastPercent) {
|
||||||
|
lastPercent = percent;
|
||||||
|
onProgress(percent);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return downloaded.executablePath;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const reason = error instanceof Error ? error.message : String(error);
|
||||||
|
throw new WhatsAppBrowserError(
|
||||||
|
`No Chrome, Edge or Chromium found, and downloading one failed (${reason}). `
|
||||||
|
+ 'Install Google Chrome or set CHROME_PATH, then start WhatsApp again.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,89 +1,113 @@
|
|||||||
/**
|
/**
|
||||||
* WhatsAppAdapter — QR surfacing, message normalization (DM + group,
|
* WhatsAppAdapter on whatsapp-web.js — QR surfacing, message normalization
|
||||||
* fromMe/status filtering), logged-out auth wipe vs transient reconnect,
|
* (DM + group, own/status/media filtering), logout vs transient disconnects,
|
||||||
* chunked send (CHANNELS-ARC P3). Fake Baileys socket; no network, no
|
* chunked send, and the browser lookup that feeds Puppeteer (ADR-0005).
|
||||||
* real Baileys import.
|
* whatsapp-web.js and @puppeteer/browsers are mocked: no network, no browser.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { BufferJSON, initAuthCreds } from '@whiskeysockets/baileys';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { afterEach, beforeEach, describe, expect, it } 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 {
|
import {
|
||||||
WhatsAppAdapter,
|
WhatsAppAdapter,
|
||||||
WHATSAPP_AUTH_VAULT_KEY,
|
|
||||||
WHATSAPP_MAX_TEXT,
|
WHATSAPP_MAX_TEXT,
|
||||||
disconnectStatusCode,
|
type WaBrowserResolver,
|
||||||
useVaultWhatsAppAuthState,
|
type WaMessageLike,
|
||||||
} from '../src/local/channels/whatsapp-adapter.js';
|
} 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';
|
import type { ChannelMessage } from '../src/local/channels/types.js';
|
||||||
|
|
||||||
const noopLog = { info: () => undefined, warn: () => undefined };
|
const noopLog = { info: () => undefined, warn: () => undefined };
|
||||||
|
const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||||
|
|
||||||
class FakeAuthVault {
|
interface FakeClient extends EventEmitter {
|
||||||
readonly entries = new Map<string, string>();
|
options: Record<string, unknown>;
|
||||||
get(key: string) {
|
sends: Array<{ chatId: string; text: string }>;
|
||||||
const value = this.entries.get(key);
|
initialized: number;
|
||||||
return value === undefined ? null : { value };
|
destroyed: number;
|
||||||
}
|
|
||||||
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 } } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let dir: string;
|
let dir: string;
|
||||||
let adapter: WhatsAppAdapter | null = null;
|
let adapter: WhatsAppAdapter | null = null;
|
||||||
|
|
||||||
function makeAdapter() {
|
function clientAt(index: number): FakeClient {
|
||||||
const sockets: FakeWaSocket[] = [];
|
return wweb.clients[index] as unknown as FakeClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startAdapter(opts: { browserResolver?: WaBrowserResolver } = {}) {
|
||||||
const received: ChannelMessage[] = [];
|
const received: ChannelMessage[] = [];
|
||||||
const vault = new FakeAuthVault();
|
|
||||||
const a = new WhatsAppAdapter({
|
const a = new WhatsAppAdapter({
|
||||||
dataDir: dir,
|
dataDir: dir,
|
||||||
vault,
|
|
||||||
onMessage: async m => { received.push(m); },
|
onMessage: async m => { received.push(m); },
|
||||||
log: noopLog,
|
log: noopLog,
|
||||||
socketFactory: async () => {
|
browserResolver: opts.browserResolver ?? (async () => CHROME),
|
||||||
const s = new FakeWaSocket();
|
|
||||||
sockets.push(s);
|
|
||||||
return s;
|
|
||||||
},
|
|
||||||
backoffCapMs: 10,
|
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> {
|
async function tick(ms = 30): Promise<void> {
|
||||||
@@ -92,260 +116,333 @@ async function tick(ms = 30): Promise<void> {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-wa-'));
|
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-wa-'));
|
||||||
|
wweb.clients.length = 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
await adapter?.stop();
|
await adapter?.stop();
|
||||||
adapter = null;
|
adapter = null;
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
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', () => {
|
describe('WhatsAppAdapter pairing + status', () => {
|
||||||
it('surfaces the QR through status and clears it once connected', async () => {
|
it('surfaces the QR through status and clears it once connected', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('qr', 'QR-DATA-1');
|
||||||
await adapter.start();
|
expect(a.getStatus().qr).toBe('QR-DATA-1');
|
||||||
ctx.sockets[0].emit('connection.update', { qr: 'QR-DATA-1' });
|
expect(a.getStatus().connected).toBe(false);
|
||||||
expect(adapter.getStatus().qr).toBe('QR-DATA-1');
|
|
||||||
expect(adapter.getStatus().connected).toBe(false);
|
|
||||||
|
|
||||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
clientAt(0).emit('authenticated');
|
||||||
expect(adapter.getStatus().connected).toBe(true);
|
clientAt(0).emit('ready');
|
||||||
expect(adapter.getStatus().qr).toBeUndefined();
|
expect(a.getStatus().connected).toBe(true);
|
||||||
|
expect(a.getStatus().qr).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('reports paired=true when creds.json exists on disk', async () => {
|
it('reports paired=true once a linked session is stored on disk', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
expect(a.getStatus().paired).toBe(false);
|
||||||
await adapter.start();
|
// LocalAuth creates the profile directory before the browser starts.
|
||||||
expect(adapter.getStatus().paired).toBe(false);
|
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true });
|
||||||
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp-auth'), { recursive: true });
|
clientAt(0).emit('ready');
|
||||||
fs.writeFileSync(path.join(dir, 'channels', 'whatsapp-auth', 'creds.json'), '{}', 'utf8');
|
expect(a.getStatus().paired).toBe(true);
|
||||||
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);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('WhatsAppAdapter inbound', () => {
|
describe('WhatsAppAdapter inbound', () => {
|
||||||
it('normalizes a DM: sender = chat jid', async () => {
|
it('normalizes a DM: sender = chat id', async () => {
|
||||||
const ctx = makeAdapter();
|
const { received } = await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('message', textMessage());
|
||||||
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' },
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
await tick(5);
|
await tick(5);
|
||||||
expect(ctx.received[0]).toEqual({
|
expect(received[0]).toEqual({
|
||||||
platform: 'whatsapp',
|
platform: 'whatsapp',
|
||||||
chatId: '3816x@s.whatsapp.net',
|
chatId: '3816x@c.us',
|
||||||
senderId: '3816x@s.whatsapp.net',
|
senderId: '3816x@c.us',
|
||||||
senderName: 'Marko',
|
senderName: 'Marko',
|
||||||
text: 'zdravo',
|
text: 'zdravo',
|
||||||
messageId: 'm1',
|
messageId: 'false_3816x@c.us_m1',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('normalizes a group message: sender = participant', async () => {
|
it('normalizes a group message: sender = author', async () => {
|
||||||
const ctx = makeAdapter();
|
const { received } = await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('message', textMessage({
|
||||||
await adapter.start();
|
from: 'grp@g.us',
|
||||||
ctx.sockets[0].emit('messages.upsert', {
|
author: 'u9@c.us',
|
||||||
type: 'notify',
|
body: 'group hi',
|
||||||
messages: [{
|
id: { _serialized: 'false_grp@g.us_m2' },
|
||||||
key: { remoteJid: 'grp@g.us', fromMe: false, id: 'm2', participant: 'u9@s.whatsapp.net' },
|
}));
|
||||||
message: { extendedTextMessage: { text: 'group hi' } },
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
await tick(5);
|
await tick(5);
|
||||||
expect(ctx.received[0]?.senderId).toBe('u9@s.whatsapp.net');
|
expect(received[0]?.senderId).toBe('u9@c.us');
|
||||||
expect(ctx.received[0]?.chatId).toBe('grp@g.us');
|
expect(received[0]?.chatId).toBe('grp@g.us');
|
||||||
expect(ctx.received[0]?.text).toBe('group hi');
|
expect(received[0]?.text).toBe('group hi');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('filters own messages, status broadcasts, non-notify batches, and non-text', async () => {
|
it('filters own messages, status updates, broadcasts, media and empty text', async () => {
|
||||||
const ctx = makeAdapter();
|
const { received } = await startAdapter();
|
||||||
adapter = ctx.a;
|
const client = clientAt(0);
|
||||||
await adapter.start();
|
client.emit('message', textMessage({ fromMe: true }));
|
||||||
const s = ctx.sockets[0];
|
client.emit('message', textMessage({ from: 'status@broadcast' }));
|
||||||
s.emit('messages.upsert', {
|
client.emit('message', textMessage({ isStatus: true }));
|
||||||
type: 'notify',
|
client.emit('message', textMessage({ broadcast: true }));
|
||||||
messages: [
|
client.emit('message', textMessage({ type: 'ptt', body: '' }));
|
||||||
{ key: { remoteJid: 'a@s.whatsapp.net', fromMe: true, id: '1' }, message: { conversation: 'me' } },
|
client.emit('message', textMessage({ type: 'image', body: 'a caption' }));
|
||||||
{ key: { remoteJid: 'status@broadcast', fromMe: false, id: '2' }, message: { conversation: 's' } },
|
client.emit('message', textMessage({ body: '' }));
|
||||||
{ 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' } }],
|
|
||||||
});
|
|
||||||
await tick(5);
|
await tick(5);
|
||||||
expect(ctx.received).toEqual([]);
|
expect(received).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('WhatsAppAdapter disconnects', () => {
|
describe('WhatsAppAdapter disconnects', () => {
|
||||||
it('reconnects on transient close codes', async () => {
|
it('reconnects with a new client on transient disconnects', async () => {
|
||||||
const ctx = makeAdapter();
|
await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('ready');
|
||||||
await adapter.start();
|
clientAt(0).emit('disconnected', 'CONFLICT');
|
||||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
await vi.waitFor(() => expect(wweb.clients.length).toBeGreaterThanOrEqual(2));
|
||||||
ctx.sockets[0].emit('connection.update', {
|
expect(clientAt(0).destroyed).toBeGreaterThanOrEqual(1);
|
||||||
connection: 'close',
|
|
||||||
lastDisconnect: loggedOutError(408), // timeout — transient
|
|
||||||
});
|
|
||||||
await tick(50);
|
|
||||||
expect(ctx.sockets.length).toBeGreaterThanOrEqual(2);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('wipes auth state and does NOT reconnect on loggedOut (401)', async () => {
|
it('keeps the client on logout so whatsapp-web.js can show a fresh QR', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true });
|
||||||
await adapter.start();
|
clientAt(0).emit('ready');
|
||||||
const authDir = path.join(dir, 'channels', 'whatsapp-auth');
|
expect(a.getStatus().paired).toBe(true);
|
||||||
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: [],
|
|
||||||
}));
|
|
||||||
|
|
||||||
ctx.sockets[0].emit('connection.update', { connection: 'open' });
|
clientAt(0).emit('disconnected', 'LOGOUT');
|
||||||
ctx.sockets[0].emit('connection.update', {
|
expect(a.getStatus().connected).toBe(false);
|
||||||
connection: 'close',
|
expect(a.getStatus().paired).toBe(false);
|
||||||
lastDisconnect: loggedOutError(401),
|
expect(a.getStatus().lastError).toMatch(/new QR/i);
|
||||||
});
|
|
||||||
await tick(50);
|
clientAt(0).emit('qr', 'QR-AFTER-LOGOUT');
|
||||||
expect(ctx.sockets.length).toBe(1); // no reconnect
|
expect(a.getStatus().qr).toBe('QR-AFTER-LOGOUT');
|
||||||
expect(fs.existsSync(path.join(authDir, 'creds.json'))).toBe(false);
|
await tick(30);
|
||||||
expect(ctx.vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(false);
|
expect(wweb.clients).toHaveLength(1);
|
||||||
expect(adapter.getStatus().lastError).toMatch(/re-pair/i);
|
expect(clientAt(0).destroyed).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('stop() ends the socket and halts reconnection', async () => {
|
it('does not reconnect when WhatsApp blocked the account', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('ready');
|
||||||
await adapter.start();
|
clientAt(0).emit('disconnected', 'TOS_BLOCK');
|
||||||
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) });
|
|
||||||
await tick(50);
|
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;
|
adapter = null;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('WhatsAppAdapter send', () => {
|
describe('WhatsAppAdapter send', () => {
|
||||||
it('chunks long text and targets the jid', async () => {
|
it('chunks long text and targets the chat id', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
clientAt(0).emit('ready');
|
||||||
await adapter.start();
|
await a.send('x@c.us', 'w'.repeat(WHATSAPP_MAX_TEXT + 50));
|
||||||
await adapter.send('x@s.whatsapp.net', 'w'.repeat(WHATSAPP_MAX_TEXT + 50));
|
expect(clientAt(0).sends).toHaveLength(2);
|
||||||
expect(ctx.sockets[0].sends.length).toBe(2);
|
expect(clientAt(0).sends[0].chatId).toBe('x@c.us');
|
||||||
expect(ctx.sockets[0].sends[0].jid).toBe('x@s.whatsapp.net');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws when not connected', async () => {
|
it('throws when not connected', async () => {
|
||||||
const ctx = makeAdapter();
|
const { a } = await startAdapter();
|
||||||
adapter = ctx.a;
|
await expect(a.send('x@c.us', 'hi')).rejects.toThrow(/not connected/);
|
||||||
await expect(adapter.send('x@s.whatsapp.net', 'hi')).rejects.toThrow(/not connected/);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('disconnectStatusCode', () => {
|
describe('WhatsApp browser lookup', () => {
|
||||||
it('extracts boom-style status codes and tolerates garbage', () => {
|
const onlyExisting = (...paths: string[]) => (candidate: string) => paths.includes(candidate);
|
||||||
expect(disconnectStatusCode(loggedOutError(401))).toBe(401);
|
|
||||||
expect(disconnectStatusCode({ error: new Error('plain') })).toBeUndefined();
|
it('finds Chrome, then Edge, on Windows in Program Files and LOCALAPPDATA', () => {
|
||||||
expect(disconnectStatusCode(undefined)).toBeUndefined();
|
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();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -132,6 +132,12 @@ const EXTERNAL = [
|
|||||||
'@playwright/*',
|
'@playwright/*',
|
||||||
'chromium-bidi',
|
'chromium-bidi',
|
||||||
'chromium-bidi/*',
|
'chromium-bidi/*',
|
||||||
|
// WhatsApp channel (ADR-0005). whatsapp-web.js is CommonJS that relies on
|
||||||
|
// __dirname and fails inside the ESM bundle; bundling it would also inline
|
||||||
|
// its LGPL-3.0 dependency node-webpmux and unused optional code (TypeScript,
|
||||||
|
// the AWS S3 client). Staged as separate packages instead.
|
||||||
|
'whatsapp-web.js',
|
||||||
|
'@puppeteer/browsers',
|
||||||
];
|
];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
Reference in New Issue
Block a user