diff --git a/.puppeteerrc.cjs b/.puppeteerrc.cjs new file mode 100644 index 0000000..d90ffd8 --- /dev/null +++ b/.puppeteerrc.cjs @@ -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, +}; diff --git a/docs/oss/adr/0005-whatsapp-web-js.md b/docs/oss/adr/0005-whatsapp-web-js.md index 728282b..635a489 100644 --- a/docs/oss/adr/0005-whatsapp-web-js.md +++ b/docs/oss/adr/0005-whatsapp-web-js.md @@ -16,13 +16,44 @@ of `server` and `launcher`. ## Consequences -- `whatsapp-web.js` drives a Chrome browser through Puppeteer. The installer does not bundle a - browser, and installing dependencies does not download one. -- Open item, proposed and awaiting the owner: use an installed Edge or Chrome, and download a - browser (about 170 MB) only if none is found when the user enables WhatsApp. -- Voice and video messages go through ffmpeg, which is not bundled because ffmpeg builds carry - their own LGPL or GPL terms. Use an installed ffmpeg or download it on demand. -- The client is unofficial. The UI warns that WhatsApp may block the account. +Implemented in P1.7 with `whatsapp-web.js` 1.34.7 (Puppeteer 24). + +- The adapter keeps its public shape: start, stop, status with the pairing QR, send and + inbound text. `LocalAuth` keeps the session as a browser profile in + `/channels/whatsapp/session`, next to the WhatsApp Web page cache. +- The session is no longer encrypted at rest. Baileys state lived in the encrypted vault; the + browser profile is protected only by file permissions. +- Baileys pairings are not migrated: whatsapp-web.js cannot use them. The old vault entry and + `/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 `/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 diff --git a/docs/oss/upstream-fixes.md b/docs/oss/upstream-fixes.md index 5d9f61f..eefa2b7 100644 --- a/docs/oss/upstream-fixes.md +++ b/docs/oss/upstream-fixes.md @@ -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-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-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-022 | Unit tests write into the developer's real `~/.waggle` | Fixed | Tests | | 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. ### UF-020. WhatsApp connector bundles GPL-3.0 code into the sidecar -- Status: Open +- Status: Fixed - 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) - 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. -- 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. ### UF-021. Settings visual-regression baseline is ignored by git diff --git a/package-lock.json b/package-lock.json index aac99af..fb182e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1513,95 +1513,6 @@ "node": ">=18" } }, - "node_modules/@borewit/text-codec": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz", - "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==", - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, - "node_modules/@cacheable/memory": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", - "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", - "license": "MIT", - "dependencies": { - "@cacheable/utils": "^2.5.0", - "@keyv/bigmap": "^1.3.1", - "hookified": "^1.15.1", - "keyv": "^5.6.0" - } - }, - "node_modules/@cacheable/memory/node_modules/@keyv/bigmap": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", - "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", - "license": "MIT", - "dependencies": { - "hashery": "^1.4.0", - "hookified": "^1.15.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "keyv": "^5.6.0" - } - }, - "node_modules/@cacheable/memory/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "license": "MIT", - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, - "node_modules/@cacheable/node-cache": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@cacheable/node-cache/-/node-cache-1.7.6.tgz", - "integrity": "sha512-6Omk2SgNnjtxB5f/E6bTIWIt5xhdpx39fGNRQgU9lojvRxU68v+qY+SXXLsp3ZGukqoPjsK21wZ6XABFr/Ge3A==", - "license": "MIT", - "dependencies": { - "cacheable": "^2.3.1", - "hookified": "^1.14.0", - "keyv": "^5.5.5" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@cacheable/node-cache/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "license": "MIT", - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, - "node_modules/@cacheable/utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", - "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", - "license": "MIT", - "dependencies": { - "hashery": "^1.5.1", - "keyv": "^5.6.0" - } - }, - "node_modules/@cacheable/utils/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "license": "MIT", - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/@clerk/backend": { "version": "3.4.14", "resolved": "https://registry.npmjs.org/@clerk/backend/-/backend-3.4.14.tgz", @@ -3246,21 +3157,6 @@ "integrity": "sha512-j8cUmOJzVgkHuS0QiQ6ga76UIoLOFSAMWhs7aZJztH3aAdCOAE6vpC8KVvFB4cU10ON0y2/5oOVmPJ43s2lTwA==", "license": "MIT" }, - "node_modules/@hapi/boom": { - "version": "9.1.4", - "resolved": "https://registry.npmjs.org/@hapi/boom/-/boom-9.1.4.tgz", - "integrity": "sha512-Ls1oH8jaN1vNsqcaHVYJrKmgMcKsC1wcp8bujvXrHaAqD2iDYq3HoOwsxwo09Cuda5R5nC0o0IxlrlTuvPuzSw==", - "license": "BSD-3-Clause", - "dependencies": { - "@hapi/hoek": "9.x.x" - } - }, - "node_modules/@hapi/hoek": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", - "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==", - "license": "BSD-3-Clause" - }, "node_modules/@hono/node-server": { "version": "1.19.14", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz", @@ -3986,12 +3882,6 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@keyv/serialize": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", - "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", - "license": "MIT" - }, "node_modules/@lukeed/ms": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", @@ -5183,6 +5073,140 @@ "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", "license": "BSD-3-Clause" }, + "node_modules/@puppeteer/browsers": { + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.0.tgz", + "integrity": "sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA==", + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.4.3", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.5.0", + "semver": "^7.7.4", + "tar-fs": "^3.1.1", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@puppeteer/browsers/node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@puppeteer/browsers/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/@puppeteer/browsers/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@puppeteer/browsers/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@puppeteer/browsers/node_modules/tar-fs": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz", + "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0", + "tar-stream": "^3.1.5" + }, + "optionalDependencies": { + "bare-fs": "^4.0.1", + "bare-path": "^3.0.0" + } + }, + "node_modules/@puppeteer/browsers/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@puppeteer/browsers/node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/@puppeteer/browsers/node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@puppeteer/browsers/node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/@radix-ui/number": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz", @@ -7729,29 +7753,6 @@ } } }, - "node_modules/@tokenizer/inflate": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", - "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "token-types": "^6.1.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, - "node_modules/@tokenizer/token": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", - "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", - "license": "MIT" - }, "node_modules/@tootallnate/once": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.1.tgz", @@ -7762,6 +7763,12 @@ "node": ">= 10" } }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", + "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", + "license": "MIT" + }, "node_modules/@tybys/wasm-util": { "version": "0.10.2", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", @@ -8091,6 +8098,16 @@ "@types/node": "*" } }, + "node_modules/@types/yauzl": { + "version": "2.10.3", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", + "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.60.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.60.0.tgz", @@ -8960,86 +8977,6 @@ "resolved": "packages/worker", "link": true }, - "node_modules/@whiskeysockets/baileys": { - "version": "7.0.0-rc13", - "resolved": "https://registry.npmjs.org/@whiskeysockets/baileys/-/baileys-7.0.0-rc13.tgz", - "integrity": "sha512-8JPc8gaaCRykkjW2jxLGQ7/RZGrc7awO7WU+QJocf58eSUI9jAdcuYLynzhAbyU4UWvJJsHImZ+5E/JaZj5ypA==", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "@cacheable/node-cache": "^1.4.0", - "@hapi/boom": "^9.1.3", - "async-mutex": "^0.5.0", - "libsignal": "^6.0.0", - "lru-cache": "^11.1.0", - "music-metadata": "^11.12.3", - "p-queue": "^9.0.0", - "pino": "^9.6", - "protobufjs": "^7.5.6", - "whatsapp-rust-bridge": "0.5.4", - "ws": "^8.13.0" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "audio-decode": "^2.1.3", - "jimp": "^1.6.1", - "link-preview-js": "^3.0.0", - "sharp": "*" - }, - "peerDependenciesMeta": { - "audio-decode": { - "optional": true - }, - "jimp": { - "optional": true - }, - "link-preview-js": { - "optional": true - } - } - }, - "node_modules/@whiskeysockets/baileys/node_modules/pino": { - "version": "9.14.0", - "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", - "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==", - "license": "MIT", - "dependencies": { - "@pinojs/redact": "^0.4.0", - "atomic-sleep": "^1.0.0", - "on-exit-leak-free": "^2.1.0", - "pino-abstract-transport": "^2.0.0", - "pino-std-serializers": "^7.0.0", - "process-warning": "^5.0.0", - "quick-format-unescaped": "^4.0.3", - "real-require": "^0.2.0", - "safe-stable-stringify": "^2.3.1", - "sonic-boom": "^4.0.1", - "thread-stream": "^3.0.0" - }, - "bin": { - "pino": "bin.js" - } - }, - "node_modules/@whiskeysockets/baileys/node_modules/pino-abstract-transport": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", - "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", - "license": "MIT", - "dependencies": { - "split2": "^4.0.0" - } - }, - "node_modules/@whiskeysockets/baileys/node_modules/thread-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", - "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", - "license": "MIT", - "dependencies": { - "real-require": "^0.2.0" - } - }, "node_modules/@xmldom/xmldom": { "version": "0.8.13", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", @@ -9417,7 +9354,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, "license": "Python-2.0" }, "node_modules/aria-hidden": { @@ -9612,6 +9548,18 @@ "node": ">=12" } }, + "node_modules/ast-types": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", + "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/ast-types-flow": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", @@ -9654,15 +9602,6 @@ "node": ">= 0.4" } }, - "node_modules/async-mutex": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", - "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==", - "license": "MIT", - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -9936,6 +9875,15 @@ "node": ">=6.0.0" } }, + "node_modules/basic-ftp": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz", + "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/better-sqlite3": { "version": "12.6.2", "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.2.tgz", @@ -10345,28 +10293,6 @@ "node": ">=8" } }, - "node_modules/cacheable": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", - "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", - "license": "MIT", - "dependencies": { - "@cacheable/memory": "^2.2.0", - "@cacheable/utils": "^2.5.0", - "hookified": "^1.15.0", - "keyv": "^5.6.0", - "qified": "^0.10.1" - } - }, - "node_modules/cacheable/node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "license": "MIT", - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/call-bind": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", @@ -10419,7 +10345,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -10614,6 +10539,19 @@ "node": ">=18" } }, + "node_modules/chromium-bidi": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz", + "integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==", + "license": "Apache-2.0", + "dependencies": { + "mitt": "^3.0.1", + "zod": "^3.24.1" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, "node_modules/class-variance-authority": { "version": "0.7.1", "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", @@ -10944,6 +10882,32 @@ "url": "https://opencollective.com/express" } }, + "node_modules/cosmiconfig": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz", + "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==", + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/crc-32": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", @@ -11047,12 +11011,6 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, - "node_modules/curve25519-js": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/curve25519-js/-/curve25519-js-0.0.4.tgz", - "integrity": "sha512-axn2UMEnkhyDUPWOwVKBMVIzSQy2ejH2xRGy1wq81dqRwApXfIzfbE3hIX0ZRFBIihf/KDqK158DLwESu4AK1w==", - "license": "MIT" - }, "node_modules/d3-array": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", @@ -11213,6 +11171,15 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/data-urls": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", @@ -11425,6 +11392,20 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/degenerator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", + "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "license": "MIT", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -11495,6 +11476,12 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/devtools-protocol": { + "version": "0.0.1581282", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1581282.tgz", + "integrity": "sha512-nv7iKtNZQshSW2hKzYNr46nM/Cfh5SEvE2oV0/SEGgc9XupIY5ggf84Cz8eJIkBce7S3bmTAauFD6aysMpnqsQ==", + "license": "BSD-3-Clause" + }, "node_modules/dfa": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", @@ -12062,6 +12049,24 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, "node_modules/es-abstract": { "version": "1.24.2", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", @@ -12688,7 +12693,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", - "dev": true, "license": "BSD-2-Clause", "dependencies": { "esprima": "^4.0.1", @@ -13063,7 +13067,6 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", @@ -13103,7 +13106,6 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=4.0" @@ -13133,7 +13135,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=0.10.0" @@ -13543,6 +13544,26 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, + "node_modules/extract-zip": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", + "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", + "license": "BSD-2-Clause", + "dependencies": { + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + }, + "bin": { + "extract-zip": "cli.js" + }, + "engines": { + "node": ">= 10.17.0" + }, + "optionalDependencies": { + "@types/yauzl": "^2.9.1" + } + }, "node_modules/fast-csv": { "version": "4.3.6", "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz", @@ -13801,6 +13822,15 @@ "reusify": "^1.0.4" } }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -13837,24 +13867,6 @@ "node": ">=16.0.0" } }, - "node_modules/file-type": { - "version": "21.3.4", - "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.4.tgz", - "integrity": "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==", - "license": "MIT", - "dependencies": { - "@tokenizer/inflate": "^0.4.1", - "strtok3": "^10.3.4", - "token-types": "^6.1.1", - "uint8array-extras": "^1.4.0" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sindresorhus/file-type?sponsor=1" - } - }, "node_modules/file-uri-to-path": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", @@ -13964,6 +13976,37 @@ "dev": true, "license": "ISC" }, + "node_modules/fluent-ffmpeg": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/fluent-ffmpeg/-/fluent-ffmpeg-2.1.3.tgz", + "integrity": "sha512-Be3narBNt2s6bsaqP6Jzq91heDgOEaDCJAXcE3qcma/EJBSy5FB4cvO31XBInuAuKBx8Kptf8dkhjK0IOru39Q==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT", + "dependencies": { + "async": "^0.2.9", + "which": "^1.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/fluent-ffmpeg/node_modules/async": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==" + }, + "node_modules/fluent-ffmpeg/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, "node_modules/follow-redirects": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", @@ -14133,6 +14176,31 @@ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", "license": "MIT" }, + "node_modules/fs-extra": { + "version": "11.3.4", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.4.tgz", + "integrity": "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==", + "license": "MIT", + "optional": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs-extra/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -14296,6 +14364,21 @@ "node": ">= 0.4" } }, + "node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-symbol-description": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", @@ -14327,6 +14410,20 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/get-uri": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", + "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==", + "license": "MIT", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/github-from-package": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", @@ -14551,18 +14648,6 @@ "minimalistic-assert": "^1.0.1" } }, - "node_modules/hashery": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", - "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", - "license": "MIT", - "dependencies": { - "hookified": "^1.15.0" - }, - "engines": { - "node": ">=20" - } - }, "node_modules/hasown": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", @@ -14641,12 +14726,6 @@ "node": ">=16.9.0" } }, - "node_modules/hookified": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", - "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", - "license": "MIT" - }, "node_modules/html-encoding-sniffer": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", @@ -14802,7 +14881,6 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, "license": "MIT", "dependencies": { "parent-module": "^1.0.0", @@ -14980,6 +15058,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT" + }, "node_modules/is-async-function": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", @@ -15614,7 +15698,6 @@ "version": "4.3.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", - "dev": true, "funding": [ { "type": "github", @@ -15698,6 +15781,12 @@ "dev": true, "license": "MIT" }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT" + }, "node_modules/json-schema-ref-resolver": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz", @@ -15769,6 +15858,29 @@ "json5": "lib/cli.js" } }, + "node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonfile/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -15925,16 +16037,6 @@ "node": ">= 0.8.0" } }, - "node_modules/libsignal": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/libsignal/-/libsignal-6.0.0.tgz", - "integrity": "sha512-d/5V3YFtDljbFMufz4ncyUYGYhJl+vzAe+c2EFFBQ6bz1h8Q3IOMEGXYMzlibU60I+e8GagMMpji18iez3P1hA==", - "license": "GPL-3.0", - "dependencies": { - "curve25519-js": "^0.0.4", - "protobufjs": "^7.5.5" - } - }, "node_modules/lie": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", @@ -17794,6 +17896,12 @@ "node": ">= 18" } }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "license": "MIT" + }, "node_modules/mkdirp": { "version": "0.5.6", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", @@ -17886,63 +17994,6 @@ "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" } }, - "node_modules/music-metadata": { - "version": "11.13.0", - "resolved": "https://registry.npmjs.org/music-metadata/-/music-metadata-11.13.0.tgz", - "integrity": "sha512-uXRaov9dfjSpQufXIU7sMxVZnh+FilCQv2mXn+K5EJ/decP3dTWrgvPYa5r6MtRbieNSCE708Da4J0u1UGfQIw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - }, - { - "type": "buymeacoffee", - "url": "https://buymeacoffee.com/borewit" - } - ], - "license": "MIT", - "dependencies": { - "@borewit/text-codec": "^0.2.2", - "@tokenizer/token": "^0.3.0", - "content-type": "^2.0.0", - "debug": "^4.4.3", - "file-type": "^21.3.4", - "media-typer": "^2.0.0", - "strtok3": "^10.3.5", - "token-types": "^6.1.2", - "uint8array-extras": "^1.5.0", - "win-guid": "^0.2.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/music-metadata/node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/music-metadata/node_modules/media-typer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-2.0.0.tgz", - "integrity": "sha512-kOy3OxT2HH39N70UnKgu4NWDZjLOz8W/mfyvniHjRH/DrL3f2pOfvWQ4p60offbbtDAnXWp0v9LfMIqMec269Q==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/mz": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", @@ -18010,6 +18061,15 @@ "node": ">= 0.6" } }, + "node_modules/netmask": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz", + "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/next": { "version": "16.3.0", "resolved": "https://registry.npmjs.org/next/-/next-16.3.0.tgz", @@ -18246,6 +18306,13 @@ "node-gyp-build-optional-packages-test": "build-test.js" } }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", + "license": "MIT", + "optional": true + }, "node_modules/node-releases": { "version": "2.0.46", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.46.tgz", @@ -18255,6 +18322,12 @@ "node": ">=18" } }, + "node_modules/node-webpmux": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/node-webpmux/-/node-webpmux-3.2.1.tgz", + "integrity": "sha512-MKgpq9nFgo44pIVNx/umD3nkqb2E8oqQTfmstVsfNdx9uV4cX7a4LqA+d8AZd3v5tgJXwENKUFsXNP3bRLP8nQ==", + "license": "LGPL-3.0-or-later" + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -18662,40 +18735,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-queue": { - "version": "9.3.1", - "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.1.tgz", - "integrity": "sha512-POWdiIPmsUPGwb4FeQ4OBg46aqmcInSWe45CKDsGHiOBiVQM9chqfQTuqhuTzcg2Vz9faTI65at0KkVyVEiCHw==", - "license": "MIT", - "dependencies": { - "eventemitter3": "^5.0.4", - "p-timeout": "^7.0.0" - }, - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-queue/node_modules/eventemitter3": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", - "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", - "license": "MIT" - }, - "node_modules/p-timeout": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.1.tgz", - "integrity": "sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==", - "license": "MIT", - "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", @@ -18705,6 +18744,73 @@ "node": ">=6" } }, + "node_modules/pac-proxy-agent": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", + "license": "MIT", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.6", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", + "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "license": "MIT", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/package-json-from-dist": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", @@ -18721,7 +18827,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, "license": "MIT", "dependencies": { "callsites": "^3.0.0" @@ -18755,6 +18860,24 @@ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", "license": "MIT" }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/parse5": { "version": "7.3.0", "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", @@ -18929,6 +19052,12 @@ "node": ">=20" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -19425,6 +19554,15 @@ ], "license": "MIT" }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -19497,6 +19635,75 @@ "node": ">= 0.10" } }, + "node_modules/proxy-agent": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", + "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.6", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.1.0", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/proxy-agent/node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -19539,23 +19746,44 @@ "node": ">=6" } }, - "node_modules/qified": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", - "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", - "license": "MIT", + "node_modules/puppeteer": { + "version": "24.38.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.38.0.tgz", + "integrity": "sha512-abnJOBVoL9PQTLKSbYGm9mjNFyIPaTVj77J/6cS370dIQtcZMpx8wyZoAuBzR71Aoon6yvI71NEVFUsl3JU82g==", + "hasInstallScript": true, + "license": "Apache-2.0", "dependencies": { - "hookified": "^2.1.1" + "@puppeteer/browsers": "2.13.0", + "chromium-bidi": "14.0.0", + "cosmiconfig": "^9.0.0", + "devtools-protocol": "0.0.1581282", + "puppeteer-core": "24.38.0", + "typed-query-selector": "^2.12.1" + }, + "bin": { + "puppeteer": "lib/cjs/puppeteer/node/cli.js" }, "engines": { - "node": ">=20" + "node": ">=18" } }, - "node_modules/qified/node_modules/hookified": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", - "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", - "license": "MIT" + "node_modules/puppeteer-core": { + "version": "24.38.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.38.0.tgz", + "integrity": "sha512-zB3S/tksIhgi2gZRndUe07AudBz5SXOB7hqG0kEa9/YXWrGwlVlYm3tZtwKgfRftBzbmLQl5iwHkQQl04n/mWw==", + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "2.13.0", + "chromium-bidi": "14.0.0", + "debug": "^4.4.3", + "devtools-protocol": "0.0.1581282", + "typed-query-selector": "^2.12.1", + "webdriver-bidi-protocol": "0.4.1", + "ws": "^8.19.0" + }, + "engines": { + "node": ">=18" + } }, "node_modules/qrcode": { "version": "1.5.4", @@ -20277,7 +20505,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, "license": "MIT", "engines": { "node": ">=4" @@ -21044,6 +21271,53 @@ "node": ">=0.12.18" } }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.10", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", + "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/sonic-boom": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", @@ -21067,7 +21341,7 @@ "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -21605,22 +21879,6 @@ ], "license": "MIT" }, - "node_modules/strtok3": { - "version": "10.3.5", - "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.5.tgz", - "integrity": "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA==", - "license": "MIT", - "dependencies": { - "@tokenizer/token": "^0.3.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, "node_modules/style-to-js": { "version": "1.1.21", "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz", @@ -22226,24 +22484,6 @@ "node": ">=0.6" } }, - "node_modules/token-types": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", - "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==", - "license": "MIT", - "dependencies": { - "@borewit/text-codec": "^0.2.1", - "@tokenizer/token": "^0.3.0", - "ieee754": "^1.2.1" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, "node_modules/tough-cookie": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", @@ -22650,11 +22890,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typed-query-selector": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz", + "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==", + "license": "MIT" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, + "devOptional": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", @@ -22695,18 +22941,6 @@ "dev": true, "license": "MIT" }, - "node_modules/uint8array-extras": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", - "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/unbox-primitive": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", @@ -23368,6 +23602,12 @@ "integrity": "sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==", "license": "Apache-2.0" }, + "node_modules/webdriver-bidi-protocol": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz", + "integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==", + "license": "Apache-2.0" + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", @@ -23378,11 +23618,47 @@ "node": ">=12" } }, - "node_modules/whatsapp-rust-bridge": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/whatsapp-rust-bridge/-/whatsapp-rust-bridge-0.5.4.tgz", - "integrity": "sha512-yYO1qSs0Fe7tGtnxOFHomocUD6IZtoAgmA4oDFyGIRZ67D3QZk3w7swA6XXFXNQngiyrg2k7tul6IrM3eUFh7A==", - "license": "MIT" + "node_modules/whatsapp-web.js": { + "version": "1.34.7", + "resolved": "https://registry.npmjs.org/whatsapp-web.js/-/whatsapp-web.js-1.34.7.tgz", + "integrity": "sha512-CscRtB32OnozLj+cuG9Q5f7IhnNV2EU4RGRJYeYF7wwhN6acQ0efabnFpetSEh5Y8OL4YqBj7nSQbUrTZYLDGA==", + "license": "Apache-2.0", + "dependencies": { + "fluent-ffmpeg": "2.1.3", + "mime": "3.0.0", + "node-fetch": "2.7.0", + "node-webpmux": "3.2.1", + "puppeteer": "24.38.0" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "archiver": "7.0.1", + "fs-extra": "11.3.4", + "unzipper": "0.12.3" + } + }, + "node_modules/whatsapp-web.js/node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "license": "MIT", + "optional": true + }, + "node_modules/whatsapp-web.js/node_modules/unzipper": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.3.tgz", + "integrity": "sha512-PZ8hTS+AqcGxsaQntl3IRBw65QrBI6lxzqDEL7IAo/XCEqRTKGfOX56Vea5TH9SZczRVxuzk1re04z/YjuYCJA==", + "license": "MIT", + "optional": true, + "dependencies": { + "bluebird": "~3.7.2", + "duplexer2": "~0.1.4", + "fs-extra": "^11.2.0", + "graceful-fs": "^4.2.2", + "node-int64": "^0.4.0" + } }, "node_modules/whatwg-encoding": { "version": "2.0.0", @@ -23549,12 +23825,6 @@ "node": ">=8" } }, - "node_modules/win-guid": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/win-guid/-/win-guid-0.2.1.tgz", - "integrity": "sha512-gEIQU4mkgl2OPeoNrWflcJFJ3Ae2BPd4eCsHHA/XikslkIVms/nHhvnvzIZV7VLmBvtFlDOzLt9rrZT+n6D67A==", - "license": "MIT" - }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -23908,6 +24178,25 @@ "node": ">=8" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "node_modules/yauzl/node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", @@ -24799,7 +25088,7 @@ "@fastify/static": "^10.1.2", "@fastify/websocket": "^11.0.0", "@huggingface/transformers": "3.8.1", - "@whiskeysockets/baileys": "^7.0.0-rc13", + "@puppeteer/browsers": "2.13.0", "adm-zip": "^0.6.0", "archiver": "^7.0.1", "better-sqlite3": "^12.6.2", @@ -24817,6 +25106,7 @@ "postgres": "^3.4.0", "sqlite-vec": "^0.1.7-alpha.2", "undici": "^6.27.0", + "whatsapp-web.js": "1.34.7", "ws": "^8.21.0", "zod": "^3.24.0" }, @@ -25386,6 +25676,7 @@ "@fastify/cors": "^10.0.0", "@fastify/static": "^10.1.2", "@fastify/websocket": "^11.0.0", + "@puppeteer/browsers": "2.13.0", "@waggle/agent": "*", "@waggle/core": "*", "@waggle/marketplace": "*", @@ -25396,7 +25687,6 @@ "@waggle/waggle-dance": "*", "@waggle/weaver": "*", "@waggle/wiki-compiler": "*", - "@whiskeysockets/baileys": "^7.0.0-rc13", "adm-zip": "^0.6.0", "archiver": "^7.0.1", "better-sqlite3": "^12.6.2", @@ -25410,6 +25700,7 @@ "mammoth": "^1.11.0", "pdf-parse": "^2.4.5", "postgres": "^3.4.0", + "whatsapp-web.js": "1.34.7", "zod": "^3.24.0" }, "devDependencies": { diff --git a/packages/launcher/package.json b/packages/launcher/package.json index 5d647de..972f068 100644 --- a/packages/launcher/package.json +++ b/packages/launcher/package.json @@ -39,7 +39,7 @@ "@fastify/static": "^10.1.2", "@fastify/websocket": "^11.0.0", "@huggingface/transformers": "3.8.1", - "@whiskeysockets/baileys": "^7.0.0-rc13", + "@puppeteer/browsers": "2.13.0", "adm-zip": "^0.6.0", "archiver": "^7.0.1", "better-sqlite3": "^12.6.2", @@ -57,6 +57,7 @@ "postgres": "^3.4.0", "sqlite-vec": "^0.1.7-alpha.2", "undici": "^6.27.0", + "whatsapp-web.js": "1.34.7", "ws": "^8.21.0", "zod": "^3.24.0" }, diff --git a/packages/server/package.json b/packages/server/package.json index aa5807e..cb6df24 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -22,6 +22,7 @@ "@fastify/cors": "^10.0.0", "@fastify/static": "^10.1.2", "@fastify/websocket": "^11.0.0", + "@puppeteer/browsers": "2.13.0", "@waggle/agent": "*", "@waggle/core": "*", "@waggle/marketplace": "*", @@ -32,7 +33,6 @@ "@waggle/waggle-dance": "*", "@waggle/weaver": "*", "@waggle/wiki-compiler": "*", - "@whiskeysockets/baileys": "^7.0.0-rc13", "adm-zip": "^0.6.0", "archiver": "^7.0.1", "better-sqlite3": "^12.6.2", @@ -46,6 +46,7 @@ "mammoth": "^1.11.0", "pdf-parse": "^2.4.5", "postgres": "^3.4.0", + "whatsapp-web.js": "1.34.7", "zod": "^3.24.0" }, "devDependencies": { diff --git a/packages/server/src/local/channels/manager.ts b/packages/server/src/local/channels/manager.ts index 191f9cb..2463c4c 100644 --- a/packages/server/src/local/channels/manager.ts +++ b/packages/server/src/local/channels/manager.ts @@ -37,7 +37,7 @@ export const CHANNEL_VAULT_KEYS: Record = { telegram: ['telegram_bot_token'], discord: ['discord_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 { @@ -169,11 +169,10 @@ export class ChannelManager { return new SlackAdapter({ appToken, botToken, onMessage, log: this.opts.log }); } if (platform === 'whatsapp') { - // No user-entered credential: Baileys pairs via QR and persists all - // resulting session state through the encrypted Vault adapter. + // No user-entered credential: whatsapp-web.js pairs via QR and keeps + // the session under /channels/whatsapp. return new WhatsAppAdapter({ dataDir: this.opts.dataDir, - vault: this.opts.vault, onMessage, log: this.opts.log, }); diff --git a/packages/server/src/local/channels/types.ts b/packages/server/src/local/channels/types.ts index 8542ab5..766232b 100644 --- a/packages/server/src/local/channels/types.ts +++ b/packages/server/src/local/channels/types.ts @@ -2,7 +2,7 @@ * IM channel adapter contracts — Slack / Telegram / WhatsApp / Discord. * * 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 * pipeline; it knows nothing about pairing, workspaces, or the agent loop. * See docs/plans/CHANNELS-ARC-2026-07-09.md for the arc spec. diff --git a/packages/server/src/local/channels/whatsapp-adapter.ts b/packages/server/src/local/channels/whatsapp-adapter.ts index 0f491db..196c4ce 100644 --- a/packages/server/src/local/channels/whatsapp-adapter.ts +++ b/packages/server/src/local/channels/whatsapp-adapter.ts @@ -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): - * Baileys is an UNOFFICIAL client that violates WhatsApp's ToS; accounts can - * be banned. The Settings UI must show a prominent ban-risk disclosure and - * recommend a secondary number. Do not soften or remove that copy. + * The client is unofficial and WhatsApp may block the linked account. The + * Settings UI shows that warning and recommends a secondary number; keep it. * - * NAT-friendly: Baileys dials OUT to WhatsApp's multi-device WS. Pairing is - * QR-scan (like WhatsApp Web): the latest QR string is held in memory and - * surfaced through getStatus().qr → /api/channels for the UI to render. - * Credentials persist as one encrypted Vault entry so pairing survives - * restarts without leaving Baileys session keys as plaintext JSON. Existing - * /channels/whatsapp-auth data is migrated once and then removed. - * DisconnectReason.loggedOut wipes the Vault entry (re-pair needed). + * Pairing is QR-scan like WhatsApp Web: the latest QR string is held in memory + * and surfaced through getStatus().qr → /api/channels for the UI to render. + * LocalAuth keeps the session as a browser profile in + * /channels/whatsapp/session, so pairing survives restarts. When the + * phone unlinks the device, whatsapp-web.js deletes that profile and shows a + * fresh QR. * - * Baileys is loaded via dynamic import so the sidecar boots without paying - * its (heavy: libsignal/protobuf) module cost until WhatsApp is enabled. + * The browser comes from whatsapp-browser.ts (installed first, a one-time + * download otherwise). whatsapp-web.js is loaded with a dynamic import so the + * sidecar does not load Puppeteer until WhatsApp is started. + * + * Text only: media, voice and video messages are ignored, so the ffmpeg that + * whatsapp-web.js uses for video stickers is never needed. */ import fs from 'node:fs'; import path from 'node:path'; -import type { - AuthenticationState, SignalDataSet, SignalDataTypeMap, -} from '@whiskeysockets/baileys'; import type { ChannelAdapter, ChannelAdapterStatus, ChannelMessage, InboundHandler, } from './types.js'; import { chunkText } from './types.js'; +import { resolveWhatsAppBrowser, WhatsAppBrowserError } from './whatsapp-browser.js'; /** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */ export const WHATSAPP_MAX_TEXT = 4000; -export const WHATSAPP_AUTH_VAULT_KEY = 'channel:whatsapp:auth-state'; const BACKOFF_START_MS = 2_000; const BACKOFF_CAP_MS = 60_000; - -export interface WhatsAppAuthVault { - get(key: string): { value: string } | null | undefined; - has(key: string): boolean; - set(key: string, value: string, metadata?: Record): 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 = [ - '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; - 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(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 (type: T, ids: string[]) => { - const result = {} as Record; - 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 | 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; +/** Disconnect reasons that mean WhatsApp blocked the account: do not reconnect. */ +const BLOCKED_STATES = new Set(['TOS_BLOCK', 'SMB_TOS_BLOCK']); +const LINKED_MARKER = 'linked'; /** Status payload extended with the pairing QR (rendered by Settings UI). */ export interface WhatsAppStatus extends ChannelAdapterStatus { qr?: string; - /** True when registered auth credentials exist in the encrypted Vault. */ + /** True when a linked session is stored on disk. */ paired?: boolean; + /** What the adapter is doing before the QR appears (browser lookup or download). */ + detail?: string; } -// ── Minimal structural contracts over Baileys (test seam) ────────────── +// ── Minimal structural contracts over whatsapp-web.js (test seam) ────── -interface BaileysEventMap { - 'connection.update': { - connection?: 'close' | 'connecting' | 'open'; - qr?: string; - lastDisconnect?: { error?: unknown }; - }; - 'messages.upsert': { - type: string; - messages: Array<{ - key: { remoteJid?: string | null; fromMe?: boolean | null; id?: string | null; participant?: string | null }; - pushName?: string | null; - message?: { - conversation?: string | null; - extendedTextMessage?: { text?: string | null } | null; - } | null; - }>; - }; - 'creds.update': unknown; +export interface WaMessageLike { + from: string; + /** Group messages: the participant who wrote it. */ + author?: string; + fromMe: boolean; + body: string; + /** 'chat' for text; 'image', 'video', 'ptt' (voice), 'audio', … for media. */ + type: string; + isStatus?: boolean; + broadcast?: boolean; + id?: { _serialized?: string }; + _data?: { notifyName?: string }; } -export interface WaSocketLike { - ev: { - on(event: E, cb: (arg: BaileysEventMap[E]) => void): void; - }; - sendMessage(jid: string, content: { text: string }): Promise; - end?(err?: Error): void; +export interface WaClientLike { + on(event: 'qr', listener: (qr: string) => void): unknown; + on(event: 'authenticated' | 'ready', listener: () => void): unknown; + on(event: 'auth_failure' | 'disconnected', listener: (reason: string) => void): unknown; + on(event: 'message', listener: (message: WaMessageLike) => void): unknown; + initialize(): Promise; + sendMessage(chatId: string, content: string): Promise; + destroy(): Promise; } -export type WaSocketFactory = ( - vault: WhatsAppAuthVault, - legacyAuthDir: string, - onAuthError: (error: unknown) => void, -) => Promise; +export type WaClientFactory = (opts: { authDir: string; executablePath: string }) => Promise; -interface BaileysLogger { - level: string; - child(fields: Record): 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; -} +export type WaBrowserResolver = (onProgress: (percent: number) => void) => Promise; -const silentBaileysLogger: BaileysLogger = { - level: 'silent', - child: () => silentBaileysLogger, - trace: () => undefined, - debug: () => undefined, - info: () => undefined, - warn: () => undefined, - error: () => undefined, -}; - -/** Production factory — real Baileys, dynamically imported. */ -async function defaultWaSocketFactory( - vault: WhatsAppAuthVault, - legacyAuthDir: string, - onAuthError: (error: unknown) => void, -): Promise { - 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, +/** Production factory: real whatsapp-web.js, dynamically imported. */ +async function defaultClientFactory(opts: { authDir: string; executablePath: string }): Promise { + const { Client, LocalAuth } = (await import('whatsapp-web.js')).default; + return new Client({ + authStrategy: new LocalAuth({ dataPath: opts.authDir }), + // The default cache path is relative to the process cwd. + webVersionCache: { type: 'local', path: path.join(opts.authDir, 'web-cache') }, + puppeteer: { + executablePath: opts.executablePath, + headless: true, + // Puppeteer's own handlers would exit the process on Ctrl-C. The sidecar + // shuts down itself and closes the browser through stop(). + handleSIGINT: false, + handleSIGTERM: false, + handleSIGHUP: false, + }, }); - 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 { - /** Channels data dir, used only to migrate/remove legacy plaintext state. */ + /** Waggle data dir; the session lives in /channels/whatsapp. */ dataDir: string; - /** Encrypted store for all Baileys credentials and signal keys. */ - vault: WhatsAppAuthVault; onMessage: InboundHandler; log: { info: (msg: string) => void; warn: (msg: string) => void }; + /** Test seam: finds or downloads the browser. */ + browserResolver?: WaBrowserResolver; /** Test seam. */ - socketFactory?: WaSocketFactory; + clientFactory?: WaClientFactory; backoffCapMs?: number; } export class WhatsAppAdapter implements ChannelAdapter { readonly platform = 'whatsapp' as const; - private readonly legacyAuthDir: string; - private readonly vault: WhatsAppAuthVault; + private readonly authDir: string; private readonly onMessage: InboundHandler; private readonly log: WhatsAppAdapterOptions['log']; - private readonly socketFactory: WaSocketFactory; + private readonly browserResolver: WaBrowserResolver; + private readonly clientFactory: WaClientFactory; private readonly backoffCap: number; private running = false; @@ -311,33 +121,46 @@ export class WhatsAppAdapter implements ChannelAdapter { private lastError: string | undefined; private lastActivityAt: number | 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 backoff: number; + /** Bumped by stop() so a connect still awaiting the browser can bail out. */ + private generation = 0; constructor(opts: WhatsAppAdapterOptions) { - this.legacyAuthDir = path.join(opts.dataDir, 'channels', 'whatsapp-auth'); - this.vault = opts.vault; + this.authDir = path.join(opts.dataDir, 'channels', 'whatsapp'); this.onMessage = opts.onMessage; 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.backoff = Math.min(BACKOFF_START_MS, this.backoffCap); } + /** + * Returns once the connection attempt is under way. Finding or downloading + * the browser and loading WhatsApp Web continue in the background and show + * up in getStatus(). + */ async start(): Promise { if (this.running) return; this.running = true; this.lastError = undefined; - await this.connect(); + void this.connect(); } async stop(): Promise { this.running = false; + this.generation += 1; if (this.reconnectTimer) clearTimeout(this.reconnectTimer); - this.teardownSocket(); + this.reconnectTimer = null; this.connected = false; this.qr = undefined; + this.detail = undefined; + await this.teardownClient(); } getStatus(): WhatsAppStatus { @@ -348,98 +171,160 @@ export class WhatsAppAdapter implements ChannelAdapter { lastError: this.lastError, lastActivityAt: this.lastActivityAt, qr: this.qr, - paired: this.hasPersistedAuth(), + paired: this.hasLinkedSession(), + detail: this.detail, }; } async send(chatId: string, text: string): Promise { - 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)) { - await this.sock.sendMessage(chatId, { text: chunk }); + await client.sendMessage(chatId, chunk); } } // ── Connection lifecycle ───────────────────────────────────────────── private async connect(): Promise { + const generation = this.generation; + const current = () => this.running && generation === this.generation; + + let executablePath: string; try { - const sock = await this.socketFactory(this.vault, this.legacyAuthDir, error => { - const message = error instanceof Error ? error.message : String(error); - this.lastError = `Could not save encrypted WhatsApp session: ${message}`; - 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}`); - }); - } + this.detail = 'Looking for Chrome, Edge or Chromium'; + executablePath = await this.browserResolver(percent => { + if (current()) this.detail = `Downloading a browser for WhatsApp (about 170 MB): ${percent}%`; }); } catch (e: unknown) { - 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 { - const jid = raw.key.remoteJid; - if (!jid || raw.key.fromMe) return null; - if (jid === 'status@broadcast') return null; - const text = raw.message?.conversation ?? raw.message?.extendedTextMessage?.text; - if (!text) return null; - // In groups the author is key.participant; in DMs it's the chat jid. - const senderId = raw.key.participant ?? jid; + private attach(client: WaClientLike): void { + const live = () => this.client === client; + + client.on('qr', qr => { + if (!live()) return; + this.qr = qr; + this.detail = undefined; + this.log.info('[whatsapp] pairing QR refreshed; scan it from Settings > Channels'); + }); + + client.on('authenticated', () => { + if (!live()) return; + this.qr = undefined; + this.detail = 'Linked. Loading WhatsApp'; + }); + + client.on('ready', () => { + if (!live()) return; + this.connected = true; + this.qr = undefined; + this.detail = undefined; + this.lastError = undefined; + this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap); + this.lastActivityAt = Date.now(); + this.markLinked(true); + this.log.info('[whatsapp] connected'); + }); + + client.on('auth_failure', reason => { + if (!live()) return; + this.handleDrop(`stored session rejected (${reason}); start WhatsApp again to re-pair via QR`, false); + // The stored session cannot be restored. Delete the profile once the + // browser has closed so the next start shows a fresh QR. + void client.destroy().catch(() => undefined).then(() => this.wipeSession()); + }); + + client.on('disconnected', reason => { + if (!live()) return; + if (reason === 'LOGOUT') { + // Unlinked from the phone. whatsapp-web.js has already deleted the + // profile and reloads WhatsApp Web, which emits a fresh QR. + this.connected = false; + this.markLinked(false); + this.lastError = 'logged out from the phone; scan the new QR to link again'; + this.log.warn(`[whatsapp] ${this.lastError}`); + return; + } + if (BLOCKED_STATES.has(reason)) { + this.handleDrop(`WhatsApp blocked this account (${reason})`, false); + return; + } + this.handleDrop(`disconnected (${reason})`, true); + }); + + client.on('message', raw => { + if (!live()) return; + const msg = this.normalize(raw); + if (!msg) return; + this.lastActivityAt = Date.now(); + void this.onMessage(msg).catch(e => { + this.log.warn(`[whatsapp] inbound handler failed: ${e instanceof Error ? e.message : e}`); + }); + }); + } + + private normalize(raw: WaMessageLike): ChannelMessage | null { + const chatId = raw.from; + if (!chatId || raw.fromMe || raw.isStatus || raw.broadcast) return null; + if (chatId === 'status@broadcast') return null; + if (raw.type !== 'chat') { + this.log.info(`[whatsapp] ignored a ${raw.type} message: the WhatsApp channel handles text only`); + return null; + } + if (!raw.body) return null; return { platform: 'whatsapp', - chatId: jid, - senderId, - senderName: raw.pushName ?? undefined, - text, - messageId: raw.key.id ?? undefined, + chatId, + // In groups the author is the participant; in DMs it is the chat id. + senderId: raw.author ?? chatId, + senderName: raw._data?.notifyName ?? undefined, + text: raw.body, + messageId: raw.id?._serialized ?? undefined, }; } private handleDrop(reason: string, reconnect: boolean): void { - this.teardownSocket(); + void this.teardownClient(); this.connected = false; + this.qr = undefined; + this.detail = undefined; if (!this.running) return; this.lastError = reason; if (!reconnect) { this.log.warn(`[whatsapp] ${reason}`); return; } - this.log.warn(`[whatsapp] dropped (${reason}) — reconnecting in ${this.backoff}ms`); + this.log.warn(`[whatsapp] dropped (${reason}); reconnecting in ${this.backoff}ms`); this.reconnectTimer = setTimeout(() => { void this.connect(); }, this.backoff); @@ -447,33 +332,39 @@ export class WhatsAppAdapter implements ChannelAdapter { 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 { - this.vault.delete(WHATSAPP_AUTH_VAULT_KEY); - fs.rmSync(this.legacyAuthDir, { recursive: true, force: true }); - } catch (e: unknown) { - this.log.warn(`[whatsapp] failed to clear auth state: ${e instanceof Error ? e.message : e}`); - } - } - - 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; + if (linked) { + fs.mkdirSync(this.authDir, { recursive: true }); + fs.writeFileSync(marker, new Date().toISOString(), 'utf8'); + } else { + fs.rmSync(marker, { force: true }); } + } catch (e: unknown) { + this.log.warn(`[whatsapp] failed to update the linked-session marker: ${e instanceof Error ? e.message : e}`); } - // 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 { - this.sock?.end?.(undefined); - } catch { /* already closed */ } - this.sock = null; + fs.rmSync(path.join(this.authDir, 'session'), { recursive: true, force: true, maxRetries: 4 }); + } catch (e: unknown) { + this.log.warn(`[whatsapp] failed to clear the session: ${e instanceof Error ? e.message : e}`); + } + } + + private hasLinkedSession(): boolean { + return fs.existsSync(path.join(this.authDir, LINKED_MARKER)) + && fs.existsSync(path.join(this.authDir, 'session')); + } + + private async teardownClient(): Promise { + const client = this.client; + this.client = null; + try { + await client?.destroy(); + } catch { /* browser already closed */ } } } diff --git a/packages/server/src/local/channels/whatsapp-browser.ts b/packages/server/src/local/channels/whatsapp-browser.ts new file mode 100644 index 0000000..8a3d6bb --- /dev/null +++ b/packages/server/src/local/channels/whatsapp-browser.ts @@ -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 /browsers; + * 4. a fresh download into /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 /browsers. */ + dataDir: string; + /** Download progress in whole percent. */ + onProgress?: (percent: number) => void; +} + +export interface ResolvedBrowser { + executablePath: string; + source: 'installed' | 'downloaded'; +} + +interface PendingDownload { + result: Promise; + listeners: Set<(percent: number) => void>; +} + +/** One lookup or download per cache dir, even if WhatsApp is restarted meanwhile. */ +const pendingDownloads = new Map(); + +/** + * Find a browser for whatsapp-web.js, downloading Chrome for Testing into + * /browsers only when nothing usable is installed. + */ +export async function resolveWhatsAppBrowser(opts: ResolveBrowserOptions): Promise { + 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 , downloaded first if it is not there yet. */ +async function downloadedChrome( + cacheDir: string, + exists: (filePath: string) => boolean, + onProgress: (percent: number) => void, +): Promise { + 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.', + ); + } +} diff --git a/packages/server/tests/channels-whatsapp.test.ts b/packages/server/tests/channels-whatsapp.test.ts index e8864fa..c047f3c 100644 --- a/packages/server/tests/channels-whatsapp.test.ts +++ b/packages/server/tests/channels-whatsapp.test.ts @@ -1,89 +1,113 @@ /** - * WhatsAppAdapter — QR surfacing, message normalization (DM + group, - * fromMe/status filtering), logged-out auth wipe vs transient reconnect, - * chunked send (CHANNELS-ARC P3). Fake Baileys socket; no network, no - * real Baileys import. + * WhatsAppAdapter on whatsapp-web.js — QR surfacing, message normalization + * (DM + group, own/status/media filtering), logout vs transient disconnects, + * chunked send, and the browser lookup that feeds Puppeteer (ADR-0005). + * whatsapp-web.js and @puppeteer/browsers are mocked: no network, no browser. */ +import { EventEmitter } from 'node:events'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { BufferJSON, initAuthCreds } from '@whiskeysockets/baileys'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const wweb = vi.hoisted(() => ({ + clients: [] as Array<{ options: Record }>, +})); + +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) { + super(); + wweb.clients.push(this); + } + async initialize(): Promise { this.initialized += 1; } + async sendMessage(chatId: string, text: string): Promise { + this.sends.push({ chatId, text }); + return {}; + } + async destroy(): Promise { this.destroyed += 1; } + } + return { default: { Client, LocalAuth } }; +}); + +const puppeteerBrowsers = vi.hoisted(() => ({ + detectBrowserPlatform: vi.fn<() => string | undefined>(() => 'mac_arm'), + getInstalledBrowsers: vi.fn(async (): Promise>> => []), + resolveBuildId: vi.fn(async () => '150.0.0.0'), + install: vi.fn(), + uninstall: vi.fn(async () => undefined), +})); + +vi.mock('@puppeteer/browsers', () => ({ + ...puppeteerBrowsers, + Browser: { CHROME: 'chrome' }, + ChromeReleaseChannel: { STABLE: 'stable' }, +})); + import { WhatsAppAdapter, - WHATSAPP_AUTH_VAULT_KEY, WHATSAPP_MAX_TEXT, - disconnectStatusCode, - useVaultWhatsAppAuthState, + type WaBrowserResolver, + type WaMessageLike, } from '../src/local/channels/whatsapp-adapter.js'; -import type { WaSocketLike } from '../src/local/channels/whatsapp-adapter.js'; +import { + browserCandidates, + findInstalledBrowser, + resolveWhatsAppBrowser, + WhatsAppBrowserError, +} from '../src/local/channels/whatsapp-browser.js'; import type { ChannelMessage } from '../src/local/channels/types.js'; const noopLog = { info: () => undefined, warn: () => undefined }; +const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; -class FakeAuthVault { - readonly entries = new Map(); - get(key: string) { - const value = this.entries.get(key); - return value === undefined ? null : { value }; - } - has(key: string): boolean { return this.entries.has(key); } - set(key: string, value: string): void { this.entries.set(key, value); } - delete(key: string): boolean { return this.entries.delete(key); } -} - -type Handler = (arg: unknown) => void; - -class FakeWaSocket implements WaSocketLike { - sends: Array<{ jid: string; text: string }> = []; - ended = false; - private handlers = new Map(); - - 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 { - this.sends.push({ jid, text: content.text }); - return {}; - } - - end(): void { - this.ended = true; - } - - emit(event: string, arg: unknown): void { - for (const cb of this.handlers.get(event) ?? []) cb(arg); - } -} - -function loggedOutError(code: number): { error: unknown } { - return { error: { output: { statusCode: code } } }; +interface FakeClient extends EventEmitter { + options: Record; + sends: Array<{ chatId: string; text: string }>; + initialized: number; + destroyed: number; } let dir: string; let adapter: WhatsAppAdapter | null = null; -function makeAdapter() { - const sockets: FakeWaSocket[] = []; +function clientAt(index: number): FakeClient { + return wweb.clients[index] as unknown as FakeClient; +} + +async function startAdapter(opts: { browserResolver?: WaBrowserResolver } = {}) { const received: ChannelMessage[] = []; - const vault = new FakeAuthVault(); const a = new WhatsAppAdapter({ dataDir: dir, - vault, onMessage: async m => { received.push(m); }, log: noopLog, - socketFactory: async () => { - const s = new FakeWaSocket(); - sockets.push(s); - return s; - }, + browserResolver: opts.browserResolver ?? (async () => CHROME), backoffCapMs: 10, }); - return { a, sockets, received, vault }; + adapter = a; + await a.start(); + if (!opts.browserResolver) await vi.waitFor(() => expect(wweb.clients.length).toBe(1)); + return { a, received }; +} + +function textMessage(overrides: Partial = {}): WaMessageLike { + 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 { @@ -92,260 +116,333 @@ async function tick(ms = 30): Promise { beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-wa-')); + wweb.clients.length = 0; }); afterEach(async () => { await adapter?.stop(); adapter = null; fs.rmSync(dir, { recursive: true, force: true }); + vi.clearAllMocks(); +}); + +describe('WhatsAppAdapter client setup', () => { + it('launches whatsapp-web.js with the found browser and keeps its state in the data dir', async () => { + await startAdapter(); + const client = clientAt(0); + const authDir = path.join(dir, 'channels', 'whatsapp'); + expect(client.initialized).toBe(1); + expect((client.options.authStrategy as { opts: { dataPath: string } }).opts.dataPath).toBe(authDir); + expect(client.options.webVersionCache).toEqual({ type: 'local', path: path.join(authDir, 'web-cache') }); + expect(client.options.puppeteer).toMatchObject({ + executablePath: CHROME, + headless: true, + handleSIGINT: false, + handleSIGTERM: false, + }); + }); + + it('reports the download progress while the browser is being fetched', async () => { + let finish: (value: string) => void = () => undefined; + let report: (percent: number) => void = () => undefined; + const { a } = await startAdapter({ + browserResolver: onProgress => { + report = onProgress; + return new Promise(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(resolve => { finish = resolve; }), + }); + await a.stop(); + finish(CHROME); + await tick(20); + expect(wweb.clients).toHaveLength(0); + adapter = null; + }); }); describe('WhatsAppAdapter pairing + status', () => { it('surfaces the QR through status and clears it once connected', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - ctx.sockets[0].emit('connection.update', { qr: 'QR-DATA-1' }); - expect(adapter.getStatus().qr).toBe('QR-DATA-1'); - expect(adapter.getStatus().connected).toBe(false); + const { a } = await startAdapter(); + clientAt(0).emit('qr', 'QR-DATA-1'); + expect(a.getStatus().qr).toBe('QR-DATA-1'); + expect(a.getStatus().connected).toBe(false); - ctx.sockets[0].emit('connection.update', { connection: 'open' }); - expect(adapter.getStatus().connected).toBe(true); - expect(adapter.getStatus().qr).toBeUndefined(); + clientAt(0).emit('authenticated'); + clientAt(0).emit('ready'); + expect(a.getStatus().connected).toBe(true); + expect(a.getStatus().qr).toBeUndefined(); }); - it('reports paired=true when creds.json exists on disk', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - expect(adapter.getStatus().paired).toBe(false); - fs.mkdirSync(path.join(dir, 'channels', 'whatsapp-auth'), { recursive: true }); - fs.writeFileSync(path.join(dir, 'channels', 'whatsapp-auth', 'creds.json'), '{}', 'utf8'); - expect(adapter.getStatus().paired).toBe(true); - }); - - it('reports paired=true from registered encrypted Vault credentials', async () => { - const ctx = makeAdapter(); - ctx.vault.set(WHATSAPP_AUTH_VAULT_KEY, JSON.stringify({ - version: 1, - creds: { registered: true }, - keys: [], - })); - adapter = ctx.a; - await adapter.start(); - expect(adapter.getStatus().paired).toBe(true); - }); -}); - -describe('WhatsApp encrypted auth state', () => { - it('persists and reloads credentials and signal keys without plaintext files', async () => { - const vault = new FakeAuthVault(); - const legacyDir = path.join(dir, 'channels', 'whatsapp-auth'); - const first = await useVaultWhatsAppAuthState(vault, legacyDir); - first.state.creds.registered = true; - await first.state.keys.set({ - 'pre-key': { - '7': { private: Buffer.from([1, 2]), public: Buffer.from([3, 4]) }, - }, - }); - first.saveCreds(); - - expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(true); - expect(fs.existsSync(legacyDir)).toBe(false); - - const reloaded = await useVaultWhatsAppAuthState(vault, legacyDir); - const keys = await reloaded.state.keys.get('pre-key', ['7']); - expect(reloaded.state.creds.registered).toBe(true); - expect(Buffer.from(keys['7'].private)).toEqual(Buffer.from([1, 2])); - expect(Buffer.from(keys['7'].public)).toEqual(Buffer.from([3, 4])); - }); - - it('migrates a legacy multi-file pairing before deleting plaintext', async () => { - const vault = new FakeAuthVault(); - const legacyDir = path.join(dir, 'channels', 'whatsapp-auth'); - fs.mkdirSync(legacyDir, { recursive: true }); - const creds = initAuthCreds(); - creds.registered = true; - fs.writeFileSync( - path.join(legacyDir, 'creds.json'), - JSON.stringify(creds, BufferJSON.replacer), - 'utf8', - ); - fs.writeFileSync( - path.join(legacyDir, 'pre-key-9.json'), - JSON.stringify({ private: Buffer.from([5]), public: Buffer.from([6]) }, BufferJSON.replacer), - 'utf8', - ); - - const migrated = await useVaultWhatsAppAuthState(vault, legacyDir); - const keys = await migrated.state.keys.get('pre-key', ['9']); - - expect(migrated.state.creds.registered).toBe(true); - expect(Buffer.from(keys['9'].private)).toEqual(Buffer.from([5])); - expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(true); - expect(fs.existsSync(legacyDir)).toBe(false); - }); - - it('fails closed and preserves unreadable encrypted state', async () => { - const vault = new FakeAuthVault(); - const legacyDir = path.join(dir, 'channels', 'whatsapp-auth'); - vault.set(WHATSAPP_AUTH_VAULT_KEY, '{broken'); - - await expect(useVaultWhatsAppAuthState(vault, legacyDir)).rejects.toThrow(/unreadable/i); - - expect(vault.entries.get(WHATSAPP_AUTH_VAULT_KEY)).toBe('{broken'); - }); - - it('fails closed and preserves legacy files when migration cannot parse them', async () => { - const vault = new FakeAuthVault(); - const legacyDir = path.join(dir, 'channels', 'whatsapp-auth'); - fs.mkdirSync(legacyDir, { recursive: true }); - fs.writeFileSync(path.join(legacyDir, 'creds.json'), '{broken', 'utf8'); - - await expect(useVaultWhatsAppAuthState(vault, legacyDir)).rejects.toThrow(/could not be migrated/i); - - expect(fs.existsSync(path.join(legacyDir, 'creds.json'))).toBe(true); - expect(vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(false); + it('reports paired=true once a linked session is stored on disk', async () => { + const { a } = await startAdapter(); + expect(a.getStatus().paired).toBe(false); + // LocalAuth creates the profile directory before the browser starts. + fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true }); + clientAt(0).emit('ready'); + expect(a.getStatus().paired).toBe(true); }); }); describe('WhatsAppAdapter inbound', () => { - it('normalizes a DM: sender = chat jid', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - ctx.sockets[0].emit('messages.upsert', { - type: 'notify', - messages: [{ - key: { remoteJid: '3816x@s.whatsapp.net', fromMe: false, id: 'm1' }, - pushName: 'Marko', - message: { conversation: 'zdravo' }, - }], - }); + it('normalizes a DM: sender = chat id', async () => { + const { received } = await startAdapter(); + clientAt(0).emit('message', textMessage()); await tick(5); - expect(ctx.received[0]).toEqual({ + expect(received[0]).toEqual({ platform: 'whatsapp', - chatId: '3816x@s.whatsapp.net', - senderId: '3816x@s.whatsapp.net', + chatId: '3816x@c.us', + senderId: '3816x@c.us', senderName: 'Marko', text: 'zdravo', - messageId: 'm1', + messageId: 'false_3816x@c.us_m1', }); }); - it('normalizes a group message: sender = participant', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - ctx.sockets[0].emit('messages.upsert', { - type: 'notify', - messages: [{ - key: { remoteJid: 'grp@g.us', fromMe: false, id: 'm2', participant: 'u9@s.whatsapp.net' }, - message: { extendedTextMessage: { text: 'group hi' } }, - }], - }); + it('normalizes a group message: sender = author', async () => { + const { received } = await startAdapter(); + clientAt(0).emit('message', textMessage({ + from: 'grp@g.us', + author: 'u9@c.us', + body: 'group hi', + id: { _serialized: 'false_grp@g.us_m2' }, + })); await tick(5); - expect(ctx.received[0]?.senderId).toBe('u9@s.whatsapp.net'); - expect(ctx.received[0]?.chatId).toBe('grp@g.us'); - expect(ctx.received[0]?.text).toBe('group hi'); + expect(received[0]?.senderId).toBe('u9@c.us'); + expect(received[0]?.chatId).toBe('grp@g.us'); + expect(received[0]?.text).toBe('group hi'); }); - it('filters own messages, status broadcasts, non-notify batches, and non-text', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - const s = ctx.sockets[0]; - s.emit('messages.upsert', { - type: 'notify', - messages: [ - { key: { remoteJid: 'a@s.whatsapp.net', fromMe: true, id: '1' }, message: { conversation: 'me' } }, - { key: { remoteJid: 'status@broadcast', fromMe: false, id: '2' }, message: { conversation: 's' } }, - { key: { remoteJid: 'b@s.whatsapp.net', fromMe: false, id: '3' }, message: {} }, - ], - }); - s.emit('messages.upsert', { - type: 'append', - messages: [{ key: { remoteJid: 'c@s.whatsapp.net', fromMe: false, id: '4' }, message: { conversation: 'history' } }], - }); + it('filters own messages, status updates, broadcasts, media and empty text', async () => { + const { received } = await startAdapter(); + const client = clientAt(0); + client.emit('message', textMessage({ fromMe: true })); + client.emit('message', textMessage({ from: 'status@broadcast' })); + client.emit('message', textMessage({ isStatus: true })); + client.emit('message', textMessage({ broadcast: true })); + client.emit('message', textMessage({ type: 'ptt', body: '' })); + client.emit('message', textMessage({ type: 'image', body: 'a caption' })); + client.emit('message', textMessage({ body: '' })); await tick(5); - expect(ctx.received).toEqual([]); + expect(received).toEqual([]); }); }); describe('WhatsAppAdapter disconnects', () => { - it('reconnects on transient close codes', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - ctx.sockets[0].emit('connection.update', { connection: 'open' }); - ctx.sockets[0].emit('connection.update', { - connection: 'close', - lastDisconnect: loggedOutError(408), // timeout — transient - }); - await tick(50); - expect(ctx.sockets.length).toBeGreaterThanOrEqual(2); + it('reconnects with a new client on transient disconnects', async () => { + await startAdapter(); + clientAt(0).emit('ready'); + clientAt(0).emit('disconnected', 'CONFLICT'); + await vi.waitFor(() => expect(wweb.clients.length).toBeGreaterThanOrEqual(2)); + expect(clientAt(0).destroyed).toBeGreaterThanOrEqual(1); }); - it('wipes auth state and does NOT reconnect on loggedOut (401)', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - const authDir = path.join(dir, 'channels', 'whatsapp-auth'); - fs.mkdirSync(authDir, { recursive: true }); - fs.writeFileSync(path.join(authDir, 'creds.json'), '{}', 'utf8'); - ctx.vault.set(WHATSAPP_AUTH_VAULT_KEY, JSON.stringify({ - version: 1, - creds: { registered: true }, - keys: [], - })); + it('keeps the client on logout so whatsapp-web.js can show a fresh QR', async () => { + const { a } = await startAdapter(); + fs.mkdirSync(path.join(dir, 'channels', 'whatsapp', 'session'), { recursive: true }); + clientAt(0).emit('ready'); + expect(a.getStatus().paired).toBe(true); - ctx.sockets[0].emit('connection.update', { connection: 'open' }); - ctx.sockets[0].emit('connection.update', { - connection: 'close', - lastDisconnect: loggedOutError(401), - }); - await tick(50); - expect(ctx.sockets.length).toBe(1); // no reconnect - expect(fs.existsSync(path.join(authDir, 'creds.json'))).toBe(false); - expect(ctx.vault.entries.has(WHATSAPP_AUTH_VAULT_KEY)).toBe(false); - expect(adapter.getStatus().lastError).toMatch(/re-pair/i); + clientAt(0).emit('disconnected', 'LOGOUT'); + expect(a.getStatus().connected).toBe(false); + expect(a.getStatus().paired).toBe(false); + expect(a.getStatus().lastError).toMatch(/new QR/i); + + clientAt(0).emit('qr', 'QR-AFTER-LOGOUT'); + expect(a.getStatus().qr).toBe('QR-AFTER-LOGOUT'); + await tick(30); + expect(wweb.clients).toHaveLength(1); + expect(clientAt(0).destroyed).toBe(0); }); - it('stop() ends the socket and halts reconnection', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - ctx.sockets[0].emit('connection.update', { connection: 'open' }); - await adapter.stop(); - expect(ctx.sockets[0].ended).toBe(true); - ctx.sockets[0].emit('connection.update', { connection: 'close', lastDisconnect: loggedOutError(408) }); + it('does not reconnect when WhatsApp blocked the account', async () => { + const { a } = await startAdapter(); + clientAt(0).emit('ready'); + clientAt(0).emit('disconnected', 'TOS_BLOCK'); await tick(50); - expect(ctx.sockets.length).toBe(1); + expect(wweb.clients).toHaveLength(1); + expect(a.getStatus().lastError).toMatch(/blocked/i); + }); + + it('drops a rejected stored session and waits for the user', async () => { + const { a } = await startAdapter(); + const sessionDir = path.join(dir, 'channels', 'whatsapp', 'session'); + fs.mkdirSync(sessionDir, { recursive: true }); + clientAt(0).emit('auth_failure', 'restore failed'); + await vi.waitFor(() => expect(fs.existsSync(sessionDir)).toBe(false)); + await tick(30); + expect(wweb.clients).toHaveLength(1); + expect(a.getStatus().lastError).toMatch(/re-pair/i); + }); + + it('stop() destroys the client and halts reconnection', async () => { + const { a } = await startAdapter(); + const client = clientAt(0); + client.emit('ready'); + await a.stop(); + expect(client.destroyed).toBe(1); + client.emit('disconnected', 'CONFLICT'); + await tick(50); + expect(wweb.clients).toHaveLength(1); adapter = null; }); }); describe('WhatsAppAdapter send', () => { - it('chunks long text and targets the jid', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await adapter.start(); - await adapter.send('x@s.whatsapp.net', 'w'.repeat(WHATSAPP_MAX_TEXT + 50)); - expect(ctx.sockets[0].sends.length).toBe(2); - expect(ctx.sockets[0].sends[0].jid).toBe('x@s.whatsapp.net'); + it('chunks long text and targets the chat id', async () => { + const { a } = await startAdapter(); + clientAt(0).emit('ready'); + await a.send('x@c.us', 'w'.repeat(WHATSAPP_MAX_TEXT + 50)); + expect(clientAt(0).sends).toHaveLength(2); + expect(clientAt(0).sends[0].chatId).toBe('x@c.us'); }); it('throws when not connected', async () => { - const ctx = makeAdapter(); - adapter = ctx.a; - await expect(adapter.send('x@s.whatsapp.net', 'hi')).rejects.toThrow(/not connected/); + const { a } = await startAdapter(); + await expect(a.send('x@c.us', 'hi')).rejects.toThrow(/not connected/); }); }); -describe('disconnectStatusCode', () => { - it('extracts boom-style status codes and tolerates garbage', () => { - expect(disconnectStatusCode(loggedOutError(401))).toBe(401); - expect(disconnectStatusCode({ error: new Error('plain') })).toBeUndefined(); - expect(disconnectStatusCode(undefined)).toBeUndefined(); +describe('WhatsApp browser lookup', () => { + const onlyExisting = (...paths: string[]) => (candidate: string) => paths.includes(candidate); + + it('finds Chrome, then Edge, on Windows in Program Files and LOCALAPPDATA', () => { + const env = { + ProgramFiles: 'C:\\Program Files', + 'ProgramFiles(x86)': 'C:\\Program Files (x86)', + LOCALAPPDATA: 'C:\\Users\\ana\\AppData\\Local', + }; + const edge = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'; + const userChrome = 'C:\\Users\\ana\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'; + expect(findInstalledBrowser({ platform: 'win32', env, exists: onlyExisting(edge) })).toBe(edge); + expect(findInstalledBrowser({ platform: 'win32', env, exists: onlyExisting(edge, userChrome) })) + .toBe(userChrome); + }); + + it('finds Chrome, Edge or Chromium app bundles on macOS, including ~/Applications', () => { + const env = { HOME: '/Users/ana' }; + const userChromium = '/Users/ana/Applications/Chromium.app/Contents/MacOS/Chromium'; + const edge = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'; + expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(userChromium) })) + .toBe(userChromium); + expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(userChromium, edge) })) + .toBe(edge); + expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(CHROME, edge) })) + .toBe(CHROME); + }); + + it('finds browsers on Linux through PATH and the standard locations', () => { + const env = { PATH: '/home/ana/bin:relative/bin:/usr/bin' }; + expect(findInstalledBrowser({ platform: 'linux', env, exists: onlyExisting('/home/ana/bin/chromium') })) + .toBe('/home/ana/bin/chromium'); + expect(findInstalledBrowser({ platform: 'linux', env, exists: onlyExisting('/snap/bin/chromium') })) + .toBe('/snap/bin/chromium'); + expect(findInstalledBrowser({ + platform: 'linux', + env, + exists: onlyExisting('/usr/bin/chromium', '/opt/google/chrome/chrome'), + })).toBe('/opt/google/chrome/chrome'); + expect(browserCandidates('linux', env).some(candidate => candidate.startsWith('relative/'))).toBe(false); + }); + + it('prefers CHROME_PATH and PUPPETEER_EXECUTABLE_PATH over detection and skips missing ones', () => { + const custom = '/opt/custom/chrome'; + const env = { CHROME_PATH: '/missing/chrome', PUPPETEER_EXECUTABLE_PATH: custom }; + expect(findInstalledBrowser({ platform: 'darwin', env, exists: onlyExisting(custom, CHROME) })).toBe(custom); + expect(findInstalledBrowser({ platform: 'darwin', env: {}, exists: onlyExisting(CHROME) })).toBe(CHROME); + }); + + it('returns null when nothing is installed', () => { + for (const platform of ['win32', 'darwin', 'linux'] as const) { + expect(findInstalledBrowser({ platform, env: {}, exists: () => false })).toBeNull(); + } + }); + + it('uses an installed browser without loading the downloader', async () => { + const resolved = await resolveWhatsAppBrowser({ + dataDir: dir, platform: 'darwin', env: {}, exists: onlyExisting(CHROME), + }); + expect(resolved).toEqual({ executablePath: CHROME, source: 'installed' }); + expect(puppeteerBrowsers.install).not.toHaveBeenCalled(); + }); + + it('reuses a browser downloaded earlier into /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 /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(); }); }); diff --git a/scripts/build-sidecar.mjs b/scripts/build-sidecar.mjs index 7a7c72d..a42c105 100644 --- a/scripts/build-sidecar.mjs +++ b/scripts/build-sidecar.mjs @@ -132,6 +132,12 @@ const EXTERNAL = [ '@playwright/*', '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 {