Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): Baileys v7 upgrade with message-retry and reconnect-drop fixes
محفوظ9e40b818188e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a7222c3e4..cc8875be7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **PostgreSQL upgrade crash-loop for deployments formerly run with `DATABASE_SYNCHRONIZE=true`.** On the PostgreSQL data connection, migrations always run at boot (`migrationsRun: true`), so a schema previously bootstrapped with `DATABASE_SYNCHRONIZE=true` — whose `@PrimaryGeneratedColumn('uuid')` columns TypeORM created as native `uuid` — collides with a migration chain that assumes `varchar` ids and crash-loops the container on boot. A new guard migration (`NormalizeSynchronizeUuidColumns`), ordered before the first colliding migration, now converts those `uuid` id and foreign-key columns to `varchar` (dropping and recreating the dependent cascade foreign keys, and re-applying the `gen_random_uuid()::varchar` defaults), so affected deployments self-heal on the next restart. It is a single-probe no-op on SQLite and on already-`varchar` (healthy) PostgreSQL. For very large `messages` tables the conversion holds an exclusive lock, so run `npm run migration:run` against the stopped app during a maintenance window if needed; `DATABASE_SYNCHRONIZE=true` on PostgreSQL remains unsupported for production. Fixes #690.+- **Baileys engine: messages no longer get stuck on "Waiting for this message. This may take a while." on iOS recipients.** Reported specifically on iOS WhatsApp: the recipient's chat shows the message as permanently pending, with no error and a stable connection. The Baileys `makeWASocket` config had no `getMessage` implementation, so WhatsApp's own retry-on-decrypt-failure protocol had nothing to resend, leaving the recipient stuck instead of recovering within seconds; it's now backed by the message store.++- **Baileys message-store lookups no longer fail their FK check.** The engine factory keyed `messageStore.put`/`getMessage`/`clearSession` by the session's on-disk auth-directory name, but `BaileysStoredMessage.sessionId` is a foreign key to `sessions.id` — every write violated the FK and was silently dropped by the orphan guard, leaving the store empty and defeating the `getMessage` fix above. The engine config now carries the auth-directory key (`sessionId`, the session name) and the DB-row key (`dbSessionId`, the session's UUID) as two separate fields, so the message store is keyed correctly without disturbing the existing on-disk auth-directory layout (and `purgeSessionData`, still keyed by name, keeps working on delete).++- **Closed a write-then-immediate-read race in the Baileys signal key store.** The raw signal key store is now wrapped in Baileys' own `makeCacheableSignalKeyStore`, which could previously make a freshly-established session appear "missing" and force an unnecessary fresh PreKey handshake.++- **Upgraded `@whiskeysockets/baileys` `6.7.23` → `7.0.0-rc13`.** Picks up an upstream concurrency rewrite (WhiskeySockets/Baileys#2571, #2587) that closes a "dual uncoordinated prekey queues" race in the same session-establishment path; no `6.x` release (up to `6.17.16`) carries this fix.++- **Fixed a first-message-after-reconnect drop on the Baileys engine.** `handleMessagesUpsert` no longer treats every `type: 'append'` upsert as history sync — Baileys can tag a genuinely new customer message `'append'` when it arrives in the same window as a reconnect's state-sync handshake, silently dropping it; it's now gated on the message's own timestamp against the connection's open time instead (with the account's own sent-message echoes still excluded, to avoid double-firing the existing `emitOwnSendEcho` webhook).+- **Dashboard Korean (ko) locale polish.** Refined several ko strings for consistency, fluency, and accuracy (follow-up to #679): "Create New Session" → `새 세션 생성` (aligns with `생성` used elsewhere in the create flow); the plugin "Configuration" tab → `설정` (matches the rest of the config UI); "Start messaging" → `대화 시작하기` (idiomatic — in Korean one starts a conversation, not a "message"); the WhatsApp Web build "current known-good" now reads `현재` instead of `최신` (latest), which had inverted the version-pinning intent; the "New" session status → `신규` (the conventional Korean status label); and the template placeholder example re-phrases the `{{orderId}}` clause so the interpolation reads naturally.- **Reliability and correctness hardening batch.** A set of fixes across the engine, session, auth, infra, dashboard, and SDK layers:diff --git a/package-lock.json b/package-lock.jsonindex b81eab23c..ac8815045 100644--- a/package-lock.json+++ b/package-lock.json@@ -27,7 +27,7 @@"@nestjs/throttler": "^6.5.0","@nestjs/typeorm": "^11.0.3","@nestjs/websockets": "^11.1.27",- "@whiskeysockets/baileys": "6.7.23",+ "@whiskeysockets/baileys": "7.0.0-rc13","adm-zip": "^0.5.18","archiver": "^8.0.0","bullmq": "^5.79.2",@@ -647,7 +647,6 @@"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",@@ -1153,7 +1152,6 @@"resolved": "https://registry.npmjs.org/@bull-board/api/-/api-8.1.0.tgz","integrity": "sha512-RLm7YOsLBAbKRCOQpH++Ec/FzllrGkNRGT0Bxj9sTwph5qKNlp1MikcBAK4zq3/IufluOnWAySdl8GVdxUcfrg==","license": "MIT",- "peer": true,"dependencies": {"redis-info": "^3.1.0"},@@ -1192,7 +1190,6 @@"resolved": "https://registry.npmjs.org/@bull-board/ui/-/ui-8.1.0.tgz","integrity": "sha512-BX7ATnvyAaFbcKwHcpsdMLpr1bawU9FZK9G5oeW4ebHSVXbAtNrmhQFWOrhMyN8Xfhx2Y88R/iC7rKR2LBekpg==","license": "MIT",- "peer": true,"dependencies": {"@bull-board/api": "8.1.0"}@@ -1230,7 +1227,6 @@"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz","integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==","license": "MIT",- "peer": true,"dependencies": {"@keyv/serialize": "^1.1.1"}@@ -1561,7 +1557,6 @@"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz","integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==","license": "Apache-2.0",- "peer": true,"dependencies": {"@grpc/proto-loader": "^0.8.0","@js-sdsl/ordered-map": "^4.4.2"@@ -1593,7 +1588,6 @@"resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz","integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==","license": "Apache-2.0",- "peer": true,"dependencies": {"lodash.camelcase": "^4.3.0","long": "^5.0.0",@@ -1705,6 +1699,7 @@"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz","integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18"}@@ -1721,6 +1716,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -1743,6 +1739,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -1762,6 +1759,7 @@"os": ["freebsd"],+ "peer": true,"dependencies": {"@img/sharp-wasm32": "0.35.1"},@@ -1784,6 +1782,7 @@"os": ["darwin"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1800,6 +1799,7 @@"os": ["darwin"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1816,6 +1816,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1832,6 +1833,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1848,6 +1850,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1864,6 +1867,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1880,6 +1884,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1896,6 +1901,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1912,6 +1918,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1928,6 +1935,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1944,6 +1952,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -1966,6 +1975,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -1988,6 +1998,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2010,6 +2021,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2032,6 +2044,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2054,6 +2067,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2076,6 +2090,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2098,6 +2113,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2114,6 +2130,7 @@"integrity": "sha512-PCQUoQdZyE8tp3HpbevuihfUmgSP4qWI0FGEPWoeXqaS+cUrFfemabHQiebUmUmlUhCuNnQMxGrQ+CPqK4hnxg==","license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,+ "peer": true,"dependencies": {"@emnapi/runtime": "^1.11.0"},@@ -2133,6 +2150,7 @@],"license": "Apache-2.0","optional": true,+ "peer": true,"dependencies": {"@img/sharp-wasm32": "0.35.1"},@@ -2155,6 +2173,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -2174,6 +2193,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": "^20.9.0"},@@ -2193,6 +2213,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">=20.9.0"},@@ -3456,7 +3477,6 @@"resolved": "https://registry.npmjs.org/@nestjs/bull-shared/-/bull-shared-11.0.4.tgz","integrity": "sha512-VBJcDHSAzxQnpcDfA0kt9MTGUD1XZzfByV70su0W0eDCQ9aqIEBlzWRW21tv9FG9dIut22ysgDidshdjlnczLw==","license": "MIT",- "peer": true,"dependencies": {"tslib": "2.8.1"},@@ -3611,7 +3631,6 @@"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.27.tgz","integrity": "sha512-kEGSzqM2lWr4whh4Ubflw+oPZSEzxvRMu9WL+LveZploJWTjec5bBlCiRVlVzTPg2kIwBiLwWSvCCW7Wnin1gg==","license": "MIT",- "peer": true,"dependencies": {"file-type": "21.3.4","iterare": "1.2.1",@@ -3658,7 +3677,6 @@"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.27.tgz","integrity": "sha512-K6DX7hcqmZdeXkv7tsPakKBRCgqL19a4mtbX4FluY0hWtFdtPKp6lbe+lb8gWPfvLdbOWr/CPScn7BSjBX+Ecg==","license": "MIT",- "peer": true,"dependencies": {"fast-safe-stringify": "2.1.1","iterare": "1.2.1",@@ -3718,7 +3736,6 @@"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.27.tgz","integrity": "sha512-0ZFhz6H6EdGh4xQVbUNwjoAwBuz73P7FvUAl67h9CTdMqQlJDaQYJApBv8pKfVZ1fGjMCbl0m9DcC6pXaZPWSQ==","license": "MIT",- "peer": true,"dependencies": {"cors": "2.8.6","express": "5.2.1",@@ -3740,7 +3757,6 @@"resolved": "https://registry.npmjs.org/@nestjs/platform-socket.io/-/platform-socket.io-11.1.27.tgz","integrity": "sha512-xgpLzaIDGOCC6xOAtHnRAz8sqieFgGxxu3MN5ID026Jt6oeL3efp29N5QHhPr7UlqBfy/Jd02uj0POkZq6Au3Q==","license": "MIT",- "peer": true,"dependencies": {"socket.io": "4.8.3","tslib": "2.8.1"@@ -3953,7 +3969,6 @@"resolved": "https://registry.npmjs.org/@nestjs/typeorm/-/typeorm-11.0.3.tgz","integrity": "sha512-zJ+E5l7auVVA7c0PsvcMdyvRPKTUqU5s2ToYmOA2QEsXQ42qbUGtK4+1HlRfpHqBkCSXP+phiH4luvf9DyJNog==","license": "MIT",- "peer": true,"peerDependencies": {"@nestjs/common": "^10.0.0 || ^11.0.0","@nestjs/core": "^10.0.0 || ^11.0.0",@@ -3967,7 +3982,6 @@"resolved": "https://registry.npmjs.org/@nestjs/websockets/-/websockets-11.1.27.tgz","integrity": "sha512-X3OgJt9KgYTvt9D7sNz9SOj3A1daAHy7DZrYhM1pky8Fh+erlKQH5IQ/tKm+GaJKA5M0srBUr1CMqjak/qNxOw==","license": "MIT",- "peer": true,"dependencies": {"iterare": "1.2.1","object-hash": "3.0.0",@@ -4493,7 +4507,6 @@"integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/estree": "*","@types/json-schema": "*"@@ -4623,7 +4636,6 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz","integrity": "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw==","license": "MIT",- "peer": true,"dependencies": {"undici-types": "~8.3.0"}@@ -4838,7 +4850,6 @@"integrity": "sha512-sPhE4iHuJDSvoAiec+Ro8JyXw8f0ql13HFR82P99nCm9GwTEKG0KYLvDe6REk8BCXuit6vJAv/Yxg5ABaNS2rA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.62.1","@typescript-eslint/types": "8.62.1",@@ -5501,20 +5512,22 @@}},"node_modules/@whiskeysockets/baileys": {- "version": "6.7.23",- "resolved": "https://registry.npmjs.org/@whiskeysockets/baileys/-/baileys-6.7.23.tgz",- "integrity": "sha512-UDbysXJpFKHC2S27qy4oABQc2uZekhUcCNi+Nvzev7wZkOhC72wqezzM2cfYB3PHJdy3Jadc2VkVv8eQeywIUw==",+ "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",- "axios": "^1.6.0",- "libsignal": "git+https://github.com/whiskeysockets/libsignal-node.git",- "music-metadata": "^11.7.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.2.4",+ "protobufjs": "^7.5.6",+ "whatsapp-rust-bridge": "0.5.4","ws": "^8.13.0"},"engines": {@@ -5522,7 +5535,7 @@},"peerDependencies": {"audio-decode": "^2.1.3",- "jimp": "^1.6.0",+ "jimp": "^1.6.1","link-preview-js": "^3.0.0","sharp": "*"},@@ -5538,6 +5551,15 @@}}},+ "node_modules/@whiskeysockets/baileys/node_modules/lru-cache": {+ "version": "11.5.2",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },"node_modules/@xtuc/ieee754": {"version": "1.2.0","resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",@@ -5590,7 +5612,6 @@"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==","devOptional": true,"license": "MIT",- "peer": true,"bin": {"acorn": "bin/acorn"},@@ -5648,6 +5669,7 @@"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz","integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==","license": "MIT",+ "optional": true,"dependencies": {"debug": "4"},@@ -5688,7 +5710,6 @@"integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"fast-deep-equal": "^3.1.1","fast-json-stable-stringify": "^2.0.0",@@ -6100,6 +6121,7 @@"version": "0.4.0","resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz","integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",+ "dev": true,"license": "MIT"},"node_modules/atomic-sleep": {@@ -6126,27 +6148,6 @@"url": "https://github.com/sponsors/ljharb"}},- "node_modules/axios": {- "version": "1.18.0",- "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz",- "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==",- "license": "MIT",- "dependencies": {- "follow-redirects": "^1.16.0",- "form-data": "^4.0.5",- "https-proxy-agent": "^5.0.1",- "proxy-from-env": "^2.1.0"- }- },- "node_modules/axios/node_modules/proxy-from-env": {- "version": "2.1.0",- "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",- "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",- "license": "MIT",- "engines": {- "node": ">=10"- }- },"node_modules/b4a": {"version": "1.8.0","resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.0.tgz",@@ -6271,7 +6272,6 @@"resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.8.2.tgz","integrity": "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==","license": "Apache-2.0",- "peer": true,"peerDependencies": {"bare-abort-controller": "*"},@@ -6561,7 +6561,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"baseline-browser-mapping": "^2.10.12","caniuse-lite": "^1.0.30001782",@@ -6652,7 +6651,6 @@"resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.79.2.tgz","integrity": "sha512-FebD+8XCZl/hnS1R4to24L4EAN70XSndKZO0776M36vGRk5MKVhKlNFM8/34zXLXKyYB4QaeIPFhVXSYYGTHpQ==","license": "MIT",- "peer": true,"dependencies": {"cron-parser": "4.9.0","ioredis": "5.10.1",@@ -6970,7 +6968,6 @@"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"readdirp": "^4.0.1"},@@ -7049,15 +7046,13 @@"version": "0.5.1","resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz","integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/class-validator": {"version": "0.15.1","resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.15.1.tgz","integrity": "sha512-LqoS80HBBSCVhz/3KloUly0ovokxpdOLR++Al3J3+dHXWt9sTKlKd4eYtoxhxyUjoe5+UcIM+5k9MIxyBWnRTw==","license": "MIT",- "peer": true,"dependencies": {"@types/validator": "^13.15.3","libphonenumber-js": "^1.11.1",@@ -7239,6 +7234,7 @@"version": "1.0.8","resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz","integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dev": true,"license": "MIT","dependencies": {"delayed-stream": "~1.0.0"@@ -7857,6 +7853,7 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz","integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "dev": true,"license": "MIT","engines": {"node": ">=0.4.0"@@ -7910,8 +7907,7 @@"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",- "peer": true+ "license": "BSD-3-Clause"},"node_modules/dezalgo": {"version": "1.0.4",@@ -8333,6 +8329,7 @@"version": "2.1.0","resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz","integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0",@@ -8409,7 +8406,6 @@"integrity": "sha512-6lVbcqSodALYo+4ELD0heG6lFiFxnLMuLkiMi2qV8LMp54N8tE8FT1GMH+ev4Ti00nFjNze2+Su6DsV5OQW3Dg==","dev": true,"license": "MIT",- "peer": true,"workspaces": ["packages/*"],@@ -8469,7 +8465,6 @@"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==","dev": true,"license": "MIT",- "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -8706,6 +8701,12 @@"node": ">=6"}},+ "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/events": {"version": "3.3.0","resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",@@ -8818,7 +8819,6 @@"resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==","license": "MIT",- "peer": true,"dependencies": {"accepts": "^2.0.0","body-parser": "^2.2.1",@@ -9129,26 +9129,6 @@"which": "bin/which"}},- "node_modules/follow-redirects": {- "version": "1.16.0",- "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",- "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",- "funding": [- {- "type": "individual",- "url": "https://github.com/sponsors/RubenVerborgh"- }- ],- "license": "MIT",- "engines": {- "node": ">=4.0"- },- "peerDependenciesMeta": {- "debug": {- "optional": true- }- }- },"node_modules/for-each": {"version": "0.3.5","resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",@@ -9212,6 +9192,7 @@"version": "4.0.5","resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz","integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",+ "dev": true,"license": "MIT","dependencies": {"asynckit": "^0.4.0",@@ -9228,6 +9209,7 @@"version": "1.52.0","resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz","integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -9237,6 +9219,7 @@"version": "2.1.35","resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz","integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dev": true,"license": "MIT","dependencies": {"mime-db": "1.52.0"@@ -9748,7 +9731,6 @@"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.27.tgz","integrity": "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q==","license": "MIT",- "peer": true,"engines": {"node": ">=16.9.0"}@@ -9813,6 +9795,7 @@"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz","integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==","license": "MIT",+ "optional": true,"dependencies": {"agent-base": "6","debug": "4"@@ -9979,7 +9962,6 @@"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.11.1.tgz","integrity": "sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==","license": "MIT",- "peer": true,"dependencies": {"@ioredis/commands": "1.10.0","cluster-key-slot": "1.1.1",@@ -10252,7 +10234,6 @@"integrity": "sha512-Yi1jqNC/Oq0N4hBgNH/YvBpP1P57QqundgytzYqy3yqAa7NZPNjSoi4SGbRAXDMdBzNE6xBCi5U7RgfrvMEUVQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@jest/core": "30.4.2","@jest/types": "30.4.1",@@ -12394,6 +12375,34 @@"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-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",@@ -12615,7 +12624,6 @@"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz","integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==","license": "MIT",- "peer": true,"dependencies": {"pg-connection-string": "^2.14.0","pg-pool": "^3.14.0",@@ -12954,7 +12962,6 @@"integrity": "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==","dev": true,"license": "MIT",- "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -13670,8 +13677,7 @@"version": "0.2.2","resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz","integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",- "license": "Apache-2.0",- "peer": true+ "license": "Apache-2.0"},"node_modules/require-directory": {"version": "2.1.1",@@ -13820,7 +13826,6 @@"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz","integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==","license": "Apache-2.0",- "peer": true,"dependencies": {"tslib": "^2.1.0"}@@ -14410,7 +14415,6 @@"integrity": "sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==","hasInstallScript": true,"license": "BSD-3-Clause",- "peer": true,"dependencies": {"bindings": "^1.5.0","node-addon-api": "^7.0.0",@@ -14921,7 +14925,6 @@"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"fast-deep-equal": "^3.1.3","fast-uri": "^3.0.1",@@ -15275,7 +15278,6 @@"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==","devOptional": true,"license": "MIT",- "peer": true,"dependencies": {"@cspotcode/source-map-support": "^0.8.0","@tsconfig/node10": "^1.0.7",@@ -15460,7 +15462,6 @@"resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.3.30.tgz","integrity": "sha512-8T35PzjefOdqc2ZR9mwLQj0pUGp6lQhMbK2EvVMwJVJWlaoHm0v/Q6dThNOZkFchD+0yMg8gwjKM28ePiLSXSQ==","license": "MIT",- "peer": true,"dependencies": {"@sqltools/formatter": "^1.2.5","ansis": "^4.2.0",@@ -15680,7 +15681,6 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","devOptional": true,"license": "Apache-2.0",- "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -16008,7 +16008,6 @@"integrity": "sha512-wGN3qcrBQIFmQ/c0AiOAQBvrZ5lmY8vbbMv4Mxfgzqd/B6+9pXtLo73WuS1dSGXM5QYY3hZnIbvx+K1xxe6FyA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/eslint-scope": "^3.7.7","@types/estree": "^1.0.8",@@ -16077,7 +16076,6 @@"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"fast-deep-equal": "^3.1.3","fast-uri": "^3.0.1",@@ -16171,6 +16169,12 @@"url": "https://opencollective.com/webpack"}},+ "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",@@ -16614,7 +16618,6 @@"resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz","integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==","license": "MIT",- "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/package.json b/package.jsonindex 6a0788dd2..a397ddb04 100644--- a/package.json+++ b/package.json@@ -71,7 +71,7 @@"@nestjs/throttler": "^6.5.0","@nestjs/typeorm": "^11.0.3","@nestjs/websockets": "^11.1.27",- "@whiskeysockets/baileys": "6.7.23",+ "@whiskeysockets/baileys": "7.0.0-rc13","adm-zip": "^0.5.18","archiver": "^8.0.0","bullmq": "^5.79.2",diff --git a/src/engine/adapters/baileys-group-mapper.spec.ts b/src/engine/adapters/baileys-group-mapper.spec.tsindex 74a6c97eb..11042b3f1 100644--- a/src/engine/adapters/baileys-group-mapper.spec.ts+++ b/src/engine/adapters/baileys-group-mapper.spec.ts@@ -1,21 +1,20 @@import type { GroupMetadata } from '@whiskeysockets/baileys';import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';-const meta = (over: Partial<GroupMetadata> = {}): GroupMetadata =>- ({- id: '[email protected]',- subject: 'My Group',- owner: '[email protected]',- desc: 'a description',- creation: 1700000000,- announce: false,- participants: [- { id: '[email protected]', admin: 'superadmin' },- { id: '[email protected]', admin: null },- { id: '[email protected]', admin: 'admin' },- ],- ...over,- }) as GroupMetadata;+const meta = (over: Partial<GroupMetadata> = {}): GroupMetadata => ({+ id: '[email protected]',+ subject: 'My Group',+ owner: '[email protected]',+ desc: 'a description',+ creation: 1700000000,+ announce: false,+ participants: [+ { id: '[email protected]', admin: 'superadmin' },+ { id: '[email protected]', admin: null },+ { id: '[email protected]', admin: 'admin' },+ ],+ ...over,+});describe('mapBaileysGroup', () => {it('maps the summary shape and flags self-admin', () => {diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex c59fbe7bb..36a08c124 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -228,25 +228,25 @@ describe('BaileysSessionStore', () => {});describe('recordKeyLidMappings (#362)', () => {- it('learns a lid->pn mapping from an inbound message key (senderLid/senderPn)', () => {- store.recordKeyLidMappings({ senderLid: '111@lid', senderPn: '[email protected]' });+ it('learns a lid->pn mapping from an inbound message key (remoteJid/remoteJidAlt)', () => {+ store.recordKeyLidMappings({ remoteJid: '111@lid', remoteJidAlt: '[email protected]' });expect(store.resolvePhone('111@lid')).toBe('628999');});- it('learns a group participant lid->pn mapping (participantLid/participantPn)', () => {- store.recordKeyLidMappings({ participantLid: '222@lid', participantPn: '[email protected]' });+ it('learns a group participant lid->pn mapping (participant/participantAlt)', () => {+ store.recordKeyLidMappings({ participant: '222@lid', participantAlt: '[email protected]' });expect(store.resolvePhone('222@lid')).toBe('628222');});it('canonicalizes a @lid to <phone>@c.us once the key mapping is learned', () => {expect(store.toNeutralJid('111@lid')).toBe('111@lid'); // unknown yet- store.recordKeyLidMappings({ senderLid: '111@lid', senderPn: '[email protected]' });+ store.recordKeyLidMappings({ remoteJid: '111@lid', remoteJidAlt: '[email protected]' });expect(store.toNeutralJid('111@lid')).toBe('[email protected]');});it('ignores a key with no lid/pn pair', () => {store.recordKeyLidMappings({});- store.recordKeyLidMappings({ senderLid: '333@lid' }); // lid without pn+ store.recordKeyLidMappings({ remoteJid: '333@lid' }); // lid without an Alt counterpartexpect(store.resolvePhone('333@lid')).toBeNull();});});@@ -315,8 +315,7 @@ describe('BaileysSessionStore', () => {const lidStore = makeFakeLidStore();const s = new BaileysSessionStore(lidStore, 'sess-1');s.addLidMappings([{ lid: '111@lid', pn: '[email protected]' }]);- // Baileys 6.7.23 carries the phone in `jid`; the WhatsApp Business shape uses `phoneNumber`.- s.upsertContacts([{ id: '222@lid', lid: '222@lid', jid: '[email protected]' }]);+ s.upsertContacts([{ id: '222@lid', lid: '222@lid', phoneNumber: '[email protected]' }]);s.upsertContacts([{ id: '333@lid', lid: '333@lid', phoneNumber: '[email protected]' }]);expect(lidStore.remember).toHaveBeenCalledWith('111', '628999', 'sess-1');expect(lidStore.remember).toHaveBeenCalledWith('222', '628222', 'sess-1');@@ -328,7 +327,7 @@ describe('BaileysSessionStore', () => {const s = new BaileysSessionStore(lidStore, 'sess-1');s.upsertContacts([{ id: 'c1', lid: '444@lid' }]); // lid first, no phone yetexpect(lidStore.remember).not.toHaveBeenCalled();- s.upsertContacts([{ id: 'c1', jid: '[email protected]' }]); // phone arrives later+ s.upsertContacts([{ id: 'c1', phoneNumber: '[email protected]' }]); // phone arrives laterexpect(lidStore.remember).toHaveBeenCalledWith('444', '628444', 'sess-1');});diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 57c5d769c..8fbf50f15 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -3,19 +3,6 @@ import { ChatSummary, Contact } from '../interfaces/whatsapp-engine.interface';import { parseWaId, toNeutralJid as canonicalizeWaId, userPart } from '../identity/wa-id';import type { LidMappingStore } from '../identity/lid-mapping-store.service';-/**- * Baileys `Contact` does not include a `phoneNumber` field, but WhatsApp Business events may supply- * the resolved phone JID alongside the lid-based id. We extend the input type locally so callers can- * pass `phoneNumber` when available (e.g. from `contacts.upsert` payloads that carry lid+pn pairs).- *- * `jid` is declared locally as well: it carries the contact's phone `@s.whatsapp.net` on- * `@whiskeysockets/baileys` 6.7.x, but the field was dropped from `Contact` in 6.17.x. Declaring it- * here (optional) keeps the `merged.jid` phone fallback type-safe across both engine versions — the- * value is read at runtime on 6.7.x and is simply `undefined` (harmlessly skipped) on newer Baileys,- * instead of becoming an `error`-typed access that trips the type-aware `no-unsafe-*` lint rules.- */-type BaileysContactWithPhone = BaileysContact & { phoneNumber?: string; jid?: string };-interface LastMessage {key: WAMessageKey;timestamp: number;@@ -28,7 +15,7 @@ interface LastMessage {* each connect) and is mapped to the neutral `Contact`/`ChatSummary` on read. Holds no socket — pure data.*/export class BaileysSessionStore {- private readonly contacts = new Map<string, BaileysContactWithPhone>();+ private readonly contacts = new Map<string, BaileysContact>();private readonly chats = new Map<string, Chat>();private readonly lastMessages = new Map<string, LastMessage>();private readonly lidToPn = new Map<string, string>();@@ -52,18 +39,18 @@ export class BaileysSessionStore {private readonly sessionId?: string,) {}- upsertContacts(records: Partial<BaileysContactWithPhone>[] = []): void {+ upsertContacts(records: Partial<BaileysContact>[] = []): void {for (const r of records) {if (!r.id) {continue;}const existing = this.contacts.get(r.id) ?? { id: r.id };- const merged: BaileysContactWithPhone = { ...existing, ...r };+ const merged: BaileysContact = { ...existing, ...r };this.contacts.set(r.id, merged);// Capture a lid->phone pair from the merged record (lid + phone can arrive in separate updates).- // The phone is `jid` on a Baileys Contact (`@s.whatsapp.net`); `phoneNumber` only appears on the- // WhatsApp Business event shape we extend in locally.- const phone = merged.phoneNumber ?? merged.jid;+ // `phoneNumber` is the authoritative PN field; fall back to `id` itself only when it's already+ // in the phone dialect (a lid-only contact's `id` is `<lid>@lid`, which is not a usable phone).+ const phone = merged.phoneNumber ?? (merged.id.endsWith('@s.whatsapp.net') ? merged.id : undefined);if (merged.lid && phone) {this.lidToPn.set(merged.lid, phone);this.persistLidMapping(merged.lid, phone);@@ -91,20 +78,34 @@ export class BaileysSessionStore {}/**- * Learn lid->pn mappings from an inbound message key (#362). Baileys attaches the sender's phone JID- * (`senderPn` / `participantPn`) next to its privacy id (`senderLid` / `participantLid`) on the message- * key — the only place a fresh `@lid` sender's number is revealed in @whiskeysockets/[email protected]- * (there is no `getPNForLID` lookup and `contacts.*` / `messaging-history.set` don't fire for it). This- * lets `resolvePhone` (senderPhone, `GET /contacts/:id/phone`) and lid canonicalization succeed. The+ * Learn lid->pn mappings from an inbound message key (#362). Baileys v7 replaced the 6.7.x+ * `senderLid`/`senderPn`/`participantLid`/`participantPn` fields with `remoteJidAlt` (DM) and+ * `participantAlt` (group) — the "Alt" is always the other dialect of the same field+ * (`remoteJid`/`participant`): if one side is `@lid`, the Alt is the phone JID, and vice versa. This+ * is still the only place a fresh `@lid` sender's number is revealed on the message key itself; the* pairs flow through addLidMappings, so they also write through to the persistent table.*/- recordKeyLidMappings(key: Pick<WAMessageKey, 'senderLid' | 'senderPn' | 'participantLid' | 'participantPn'>): void {+ recordKeyLidMappings(key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt'>): void {this.addLidMappings([- { lid: key.senderLid ?? undefined, pn: key.senderPn ?? undefined },- { lid: key.participantLid ?? undefined, pn: key.participantPn ?? undefined },+ this.lidPnPair(key.remoteJid, key.remoteJidAlt),+ this.lidPnPair(key.participant, key.participantAlt),]);}+ /** Sorts a JID and its WhatsApp-supplied "Alt" counterpart into { lid, pn } by @lid suffix. */+ private lidPnPair(jid?: string | null, alt?: string | null): { lid?: string; pn?: string } {+ if (!jid || !alt) {+ return {};+ }+ if (jid.endsWith('@lid')) {+ return { lid: jid, pn: alt };+ }+ if (alt.endsWith('@lid')) {+ return { lid: alt, pn: jid };+ }+ return {};+ }+/** Write a learned lid->phone pair through to the persistent table (bare digits, fire-and-forget). */private persistLidMapping(lidJid: string, pnJid: string): void {void this.lidStore?.remember(userPart(lidJid), userPart(pnJid), this.sessionId);@@ -272,7 +273,7 @@ export class BaileysSessionStore {return parsed.kind === 'user' ? `${parsed.userPart}@s.whatsapp.net` : jid;}- private toNeutralContact(c: BaileysContactWithPhone): Contact {+ private toNeutralContact(c: BaileysContact): Contact {const number = c.phoneNumber ? userPart(c.phoneNumber) : c.id.endsWith('@s.whatsapp.net') ? userPart(c.id) : '';return {id: this.toNeutralJid(c.id),@@ -286,11 +287,15 @@ export class BaileysSessionStore {}private toNeutralChat(c: Chat): ChatSummary {- const last = this.lastMessages.get(c.id);+ // Chat.id is nullable on Baileys' own type (it's the raw proto.IConversation field), but+ // upsertChats() only ever stores a record under a truthy r.id, so every value in `this.chats`+ // is provably keyed by a real id.+ const id = c.id!;+ const last = this.lastMessages.get(id);return {- id: this.toNeutralJid(c.id),- name: c.name ?? this.resolveContactName(c.id),- isGroup: c.id.endsWith('@g.us'),+ id: this.toNeutralJid(id),+ name: c.name ?? this.resolveContactName(id),+ isGroup: id.endsWith('@g.us'),unreadCount: c.unreadCount ?? 0,timestamp: last?.timestamp ?? this.toUnixSeconds(c.conversationTimestamp),lastMessage: last?.text,diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 6a0f3760a..0ada7359a 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -57,6 +57,9 @@ jest.mock('@whiskeysockets/baileys', () => ({}),useMultiFileAuthState: jest.fn().mockResolvedValue({ state: { creds: {}, keys: {} }, saveCreds }),fetchLatestBaileysVersion: jest.fn().mockResolvedValue({ version: [2, 3000, 0] }),+ // Identity passthrough — the adapter wraps state.keys with this for session-store caching; tests+ // don't exercise the caching behavior itself, just need the real store object to flow through.+ makeCacheableSignalKeyStore: jest.fn((store: unknown) => store),getContentType: jest.fn(() => 'conversation'),// The adapter now downloads via 'stream' mode, so resolve to an async-iterable of chunks (factory is// hoisted above imports, so this stays inline; tests override with the `streamOf` helper below).@@ -102,8 +105,15 @@ function streamOf(...chunks: Buffer[]): AsyncIterable<Buffer> & { destroy: () =>destroy: jest.fn(),};}+// sessionId (name) and dbSessionId (Session.id UUID) are deliberately distinct here so assertions+// below prove auth-dir/logging use the name while messageStore (FK-bound) uses the UUID.const newAdapter = (): BaileysAdapter =>- new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys', messageStore: fakeStore });+ new BaileysAdapter({+ sessionId: 'sess-1',+ dbSessionId: 'db-uuid-1',+ authDir: './data/baileys',+ messageStore: fakeStore,+ });const noopCallbacks = (over: Partial<EngineEventCallbacks> = {}): EngineEventCallbacks => over;@@ -866,8 +876,8 @@ describe('BaileysAdapter inbound fan-out', () => {const onMessage = jest.fn();const adapter = newAdapter();await adapter.initialize({ onMessage });- // No history-sync mapping this time; the inbound key itself carries senderLid + senderPn,- // which is the only place a fresh @lid sender's number is revealed in [email protected].+ // No history-sync mapping this time; the inbound key itself carries remoteJid + remoteJidAlt,+ // which is the only place a fresh @lid sender's number is revealed on the key in baileys v7.fakeSock.fire('messages.upsert', {type: 'notify',messages: [@@ -876,8 +886,7 @@ describe('BaileysAdapter inbound fan-out', () => {remoteJid: '111@lid',fromMe: false,id: 'IN_LID_KEY',- senderLid: '111@lid',- senderPn: '[email protected]',+ remoteJidAlt: '[email protected]',},message: { conversation: 'hi from lid' },messageTimestamp: 1700000005,@@ -887,7 +896,7 @@ describe('BaileysAdapter inbound fan-out', () => {await new Promise(r => setImmediate(r));// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accessconst msg = onMessage.mock.calls[0][0] as { from: string; isLidSender?: boolean };- expect(msg.from).toBe('[email protected]'); // resolved from the key's senderPn, neutral dialect+ expect(msg.from).toBe('[email protected]'); // resolved from the key's remoteJidAlt, neutral dialectexpect(msg.isLidSender).toBe(true);});@@ -933,17 +942,69 @@ describe('BaileysAdapter inbound fan-out', () => {expect(onMessage).not.toHaveBeenCalled();});- it('ignores append (history) upserts', async () => {+ it('ignores an append upsert with no/old timestamp (real history backfill)', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('connection.update', { connection: 'open' }); // sets connectedAt+ fakeSock.fire('messages.upsert', {+ type: 'append',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'OLD' },+ message: { conversation: 'old' },+ messageTimestamp: Math.floor(Date.now() / 1000) - 3600, // an hour before connectedAt+ },+ ],+ });+ expect(onMessage).not.toHaveBeenCalled();+ });++ it('still processes an append upsert timestamped after this connection opened (reconnect edge case, #703)', async () => {+ // Baileys can tag a genuinely new message 'append' when it arrives in the same window as a+ // reconnect's state-sync handshake; only the message's own timestamp vs. connectedAt should+ // decide history vs. live, not the batch's type tag.const onMessage = jest.fn();const adapter = newAdapter();await adapter.initialize({ onMessage });+ fakeSock.fire('connection.update', { connection: 'open' }); // sets connectedAt+ fakeSock.fire('messages.upsert', {+ type: 'append',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'FRESH' },+ message: { conversation: 'hi right after reconnect' },+ messageTimestamp: Math.floor(Date.now() / 1000),+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ expect(onMessage).toHaveBeenCalled();+ });++ it('does not double-fire onMessageCreate for a recent append echo of our own send', async () => {+ // Baileys echoes our own just-sent messages back through messages.upsert tagged 'append' too.+ // sendContent() already emits onMessageCreate for those via emitOwnSendEcho() (not exercised by+ // this fakeSock harness) — the recency override must stay scoped to fromMe !== true so this+ // path doesn't ALSO fire onMessageCreate a second time for the same send.+ const onMessage = jest.fn();+ const onMessageCreate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage, onMessageCreate });+ fakeSock.fire('connection.update', { connection: 'open' }); // sets connectedAtfakeSock.fire('messages.upsert', {type: 'append',messages: [- { key: { remoteJid: '[email protected]', fromMe: false, id: 'OLD' }, message: { conversation: 'old' } },+ {+ key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN_ECHO' },+ message: { conversation: 'sent by us' },+ messageTimestamp: Math.floor(Date.now() / 1000),+ },],});+ await new Promise(r => setImmediate(r));expect(onMessage).not.toHaveBeenCalled();+ expect(onMessageCreate).not.toHaveBeenCalled();});it('emits onMessageAck from messages.update with a neutral status', async () => {@@ -1595,7 +1656,7 @@ describe('BaileysAdapter store-backed ops', () => {fakeStore.getMessage.mockResolvedValue(stored);const adapter = await ready();await adapter.replyToMessage('[email protected]', 'TARGET', 'my reply');- expect(fakeStore.getMessage).toHaveBeenCalledWith('sess-1', 'TARGET');+ expect(fakeStore.getMessage).toHaveBeenCalledWith('db-uuid-1', 'TARGET');expect(fakeSock.sendMessage).toHaveBeenCalledWith({ text: 'my reply' },@@ -1684,7 +1745,7 @@ describe('BaileysAdapter store-backed ops', () => {await new Promise(r => setImmediate(r));// eslint-disable-next-line @typescript-eslint/no-unsafe-assignmentconst inboundMatcher = expect.objectContaining({ key: expect.objectContaining({ id: 'IN9' }) });- expect(fakeStore.put).toHaveBeenCalledWith('sess-1', inboundMatcher);+ expect(fakeStore.put).toHaveBeenCalledWith('db-uuid-1', inboundMatcher);});it('populates the store on an outgoing send', async () => {@@ -1692,13 +1753,13 @@ describe('BaileysAdapter store-backed ops', () => {await adapter.sendTextMessage('[email protected]', 'hello');// eslint-disable-next-line @typescript-eslint/no-unsafe-assignmentconst outboundMatcher = expect.objectContaining({ key: expect.objectContaining({ id: 'OUT' }) });- expect(fakeStore.put).toHaveBeenCalledWith('sess-1', outboundMatcher);+ expect(fakeStore.put).toHaveBeenCalledWith('db-uuid-1', outboundMatcher);});it('clears the store on logout', async () => {const adapter = await ready();await adapter.logout();- expect(fakeStore.clearSession).toHaveBeenCalledWith('sess-1');+ expect(fakeStore.clearSession).toHaveBeenCalledWith('db-uuid-1');});});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 64fa2d391..a90e25aae 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -133,6 +133,9 @@ export class BaileysAdapter implements IWhatsAppEngine {private callbacks: EngineEventCallbacks = {};private intentionalClose = false;private connecting = false;+ /** Unix-seconds timestamp of the last 'open' connection.update, used to distinguish a genuinely+ * live message misfiled as 'append' (see handleMessagesUpsert) from real history backfill. */+ private connectedAt = 0;private reconnectAttempts = 0;private reconnectTimer?: ReturnType<typeof setTimeout>;/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */@@ -187,6 +190,21 @@ export class BaileysAdapter implements IWhatsAppEngine {const b = await this.loadLib();const { state, saveCreds } = await b.useMultiFileAuthState(this.authPath);const { version } = await b.fetchLatestBaileysVersion();+ // BaileysLogger matches ILogger exactly; cast needed because the module resolves the type+ // through a deep import path that TypeScript does not auto-unify here. Shared by the key+ // store wrapper below and the socket itself, rather than constructing two instances.+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileysLogger = createBaileysLogger() as unknown as ILogger;++ // Wrap the raw file-backed signal key store with Baileys' own official caching layer.+ // Without it, every session read/write hits disk directly with no protection against a+ // write-then-immediate-read race — observed here as a freshly-established Signal session+ // appearing "missing" moments later, forcing Baileys to discard it and start a brand new+ // PreKey handshake on the very next send (visible as repeated "Closing session" log spam and+ // the recipient stuck on "waiting for this message" until a slow WhatsApp-side retry rescues+ // it). makeCacheableSignalKeyStore keeps the just-written state visible in memory immediately,+ // regardless of disk I/O timing.+ state.keys = b.makeCacheableSignalKeyStore(state.keys, baileysLogger);// C2: resurrect-after-stop guard — if disconnect/logout/destroy ran during the awaits above,// bail now so we don't create a live socket for a session that was intentionally stopped.@@ -212,7 +230,7 @@ export class BaileysAdapter implements IWhatsAppEngine {previous.ev.removeAllListeners('chats.upsert');previous.ev.removeAllListeners('chats.update');previous.ev.removeAllListeners('messaging-history.set');- previous.ev.removeAllListeners('chats.phoneNumberShare');+ previous.ev.removeAllListeners('lid-mapping.update');previous.end(undefined);} catch {// end() may already have run from Baileys' own close handler — a safe no-op.@@ -232,10 +250,19 @@ export class BaileysAdapter implements IWhatsAppEngine {// RECENT window + the full contact/app-state snapshot, not the entire message history.shouldSyncHistoryMessage: () => true,syncFullHistory: process.env.BAILEYS_SYNC_FULL_HISTORY === 'true',- // BaileysLogger matches ILogger exactly; cast needed because the module resolves- // the type through a deep import path that TypeScript does not auto-unify here.- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion- logger: createBaileysLogger() as unknown as ILogger,+ // Baileys defaults this to `async () => undefined` (Defaults/index.js). Without a real+ // implementation, WhatsApp's message-retry protocol — triggered whenever a recipient's client+ // fails to decrypt on the first attempt — has nothing to resend, so the recipient is stuck on+ // "waiting for this message" indefinitely instead of the retry resolving it within seconds.+ // Backed by the same messageStore used for reply/forward/react/delete-by-id.+ getMessage: async key => {+ if (!key.id) {+ return undefined;+ }+ const stored = await this.config.messageStore?.getMessage(this.config.dbSessionId, key.id);+ return stored?.message ?? undefined;+ },+ logger: baileysLogger,});this.sock = sock;@@ -266,16 +293,12 @@ export class BaileysAdapter implements IWhatsAppEngine {sock.ev.on('messaging-history.set', history => {this.sessionStore.upsertContacts(history.contacts);this.sessionStore.upsertChats(history.chats);- // lidPnMappings is not in the installed @whiskeysockets/[email protected] type definition but- // is present at runtime in later protocol versions; cast to access it safely.- const h = history as unknown as { lidPnMappings?: { lid: string; pn: string }[]; syncType?: unknown };- const lidPnMappings = h.lidPnMappings;- this.sessionStore.addLidMappings(lidPnMappings ?? []);+ this.sessionStore.addLidMappings(history.lidPnMappings ?? []);void this.captureHistoryMessages(history.messages ?? []);this.logger.debug('History sync received', {action: 'baileys_history_set',sessionId: this.config.sessionId,- syncType: h.syncType,+ syncType: history.syncType,isLatest: history.isLatest,progress: history.progress,chats: history.chats?.length ?? 0,@@ -283,11 +306,12 @@ export class BaileysAdapter implements IWhatsAppEngine {contacts: history.contacts?.length ?? 0,namedContacts: history.contacts?.filter(c => c.name || c.notify).length ?? 0,lidContacts: history.contacts?.filter(c => c.lid).length ?? 0,- lidPnMappings: lidPnMappings?.length ?? 0,+ lidPnMappings: history.lidPnMappings?.length ?? 0,});});- // WhatsApp pushes this when a lid contact shares its phone number - a direct lid->phone pair.- sock.ev.on('chats.phoneNumberShare', ({ lid, jid }) => this.sessionStore.addLidMappings([{ lid, pn: jid }]));+ // WhatsApp pushes this when a lid<->phone mapping is learned (renamed from the pre-v7+ // 'chats.phoneNumberShare' event, whose { lid, jid } payload this shape directly replaces).+ sock.ev.on('lid-mapping.update', ({ lid, pn }) => this.sessionStore.addLidMappings([{ lid, pn }]));}private handleConnectionUpdate(update: {@@ -313,6 +337,10 @@ export class BaileysAdapter implements IWhatsAppEngine {this.pushName = this.sock?.user?.name ?? null;// I4: reset the reconnect counter on a successful connection.this.reconnectAttempts = 0;+ // Small backward buffer for clock skew between this host and WhatsApp's server (messageTimestamp+ // is WA's clock, Date.now() is ours) — without it, a message sent right at reconnect time could+ // land a couple seconds "before" connectedAt and be misjudged as history.+ this.connectedAt = Math.floor(Date.now() / 1000) - 10;this.setStatus(EngineStatus.READY);this.callbacks.onReady?.(this.phoneNumber ?? '', this.pushName ?? '');// Backfill names the initial sync skipped (see hydrateNames).@@ -408,7 +436,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}this.sock = null;this.setStatus(EngineStatus.DISCONNECTED);- await this.config.messageStore?.clearSession(this.config.sessionId).catch(() => undefined);+ await this.config.messageStore?.clearSession(this.config.dbSessionId).catch(() => undefined);// Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be// reloaded on the next connect() and block re-linking (Baileys retries them, no QR emitted).await this.clearAuthState();@@ -483,7 +511,7 @@ export class BaileysAdapter implements IWhatsAppEngine {? await this.sock!.sendMessage(chatId, content, options): await this.sock!.sendMessage(chatId, content);if (sent) {- void this.config.messageStore?.put(this.config.sessionId, sent).catch(err =>+ void this.config.messageStore?.put(this.config.dbSessionId, sent).catch(err =>this.logger.warn('Failed to persist sent message to store', {error: err instanceof Error ? err.message : String(err),}),@@ -913,14 +941,29 @@ export class BaileysAdapter implements IWhatsAppEngine {// ----- Helpers -----private handleMessagesUpsert(event: { messages: WAMessage[]; type: string }): void {- // Only live messages ('notify'); 'append' is history sync, which this storeless slice skips.- if (event.type !== 'notify') {- return;- }for (const msg of event.messages) {if (!msg.message || !msg.key?.remoteJid) {continue; // protocol/empty messages carry no neutral content}+ if (event.type !== 'notify') {+ // Baileys echoes back OUR OWN just-sent messages through this same 'append' path too, and+ // sendContent() already emits onMessageCreate for those via emitOwnSendEcho() — always+ // exclude fromMe here (unconditionally, regardless of timestamp) so that echo doesn't fire+ // onMessageCreate a second time.+ if (msg.key.fromMe === true) {+ continue;+ }+ // For everyone else: gate on the message's own timestamp vs. this connection's open time,+ // not the upsert batch's `type` tag. `type: 'append'` usually means real history-sync+ // backfill, but Baileys can also tag a genuinely new CUSTOMER message 'append' when it+ // arrives in the same window as a reconnect's state-sync handshake — a strict+ // `type !== 'notify'` filter silently drops that message (observed as "the first message+ // after a reconnect gets ignored"). A message sent AFTER this connection opened is live+ // regardless of which tag the batch carries; true backfill always predates it.+ if (this.toUnixSeconds(msg.messageTimestamp) < this.connectedAt) {+ continue;+ }+ }// Throttle through the limiter so a burst of media messages can't run unbounded parallel// downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store// keeps the newest by timestamp. When the waiter queue is saturated we REJECT instead of parking@@ -1022,7 +1065,7 @@ export class BaileysAdapter implements IWhatsAppEngine {} else {this.callbacks.onMessage?.(incoming);}- void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>+ void this.config.messageStore?.put(this.config.dbSessionId, msg).catch(err =>this.logger.warn('Failed to persist message to store', {error: err instanceof Error ? err.message : String(err),}),@@ -1440,7 +1483,7 @@ export class BaileysAdapter implements IWhatsAppEngine {? await this.sock!.sendMessage(chatId, content, merged): await this.sock!.sendMessage(chatId, content);if (sent) {- void this.config.messageStore?.put(this.config.sessionId, sent).catch(err =>+ void this.config.messageStore?.put(this.config.dbSessionId, sent).catch(err =>this.logger.warn('Failed to persist sent message to store', {error: err instanceof Error ? err.message : String(err),}),@@ -1479,7 +1522,7 @@ export class BaileysAdapter implements IWhatsAppEngine {/** Resolve a previously-seen message from the store, or throw a clear not-found error. */private async requireStored(messageId: string): Promise<WAMessage> {- const found = await this.config.messageStore?.getMessage(this.config.sessionId, messageId);+ const found = await this.config.messageStore?.getMessage(this.config.dbSessionId, messageId);if (!found?.key) {throw new MessageNotFoundError(messageId);}diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex 6d2cd7026..b58f63357 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -43,8 +43,8 @@ describe('EngineFactory', () => {} as unknown as PluginLoaderService;const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());- expect(() => factory.create({ sessionId: '../../etc' })).toThrow(/unsafe session name/i);- expect(() => factory.create({ sessionId: 'a/b' })).toThrow(/unsafe session name/i);+ expect(() => factory.create({ sessionId: '../../etc', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);+ expect(() => factory.create({ sessionId: 'a/b', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);expect(createEngine).not.toHaveBeenCalled();});@@ -56,11 +56,16 @@ describe('EngineFactory', () => {} as unknown as PluginLoaderService;const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());- factory.create({ sessionId: 'sess-1', proxyUrl: 'http://p', proxyType: 'http' });+ factory.create({ sessionId: 'sess-1', dbSessionId: 'db-1', proxyUrl: 'http://p', proxyType: 'http' });// Plain-object (not objectContaining) assertion: any browser key (headless/puppeteerArgs/// executablePath/sessionDataPath) leaking into the per-call config would fail this exact match.- expect(createEngine).toHaveBeenCalledWith({ sessionId: 'sess-1', proxyUrl: 'http://p', proxyType: 'http' });+ expect(createEngine).toHaveBeenCalledWith({+ sessionId: 'sess-1',+ dbSessionId: 'db-1',+ proxyUrl: 'http://p',+ proxyType: 'http',+ });});it('registers the built-in engine with the opaque engine config blob (#219 guarantee moves to context.config)', async () => {@@ -103,7 +108,7 @@ describe('EngineFactory', () => {} as unknown as PluginLoaderService;const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());- expect(() => factory.create({ sessionId: 'sess-2' })).not.toThrow();+ expect(() => factory.create({ sessionId: 'sess-2', dbSessionId: 'db-2' })).not.toThrow();});it('throws instead of silently building whatsapp-web.js when a non-wwebjs engine has no plugin', () => {@@ -119,7 +124,7 @@ describe('EngineFactory', () => {buildMessageStore(),buildLidStore(),);- expect(() => factory.create({ sessionId: 'sess-b' })).toThrow(/baileys/i);+ expect(() => factory.create({ sessionId: 'sess-b', dbSessionId: 'db-b' })).toThrow(/baileys/i);});describe('purgeSessionData (delete fully removes on-disk auth, keyed by session name)', () => {diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex 8382f996b..1038c62b6 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -13,7 +13,10 @@ import { LidMappingStoreService } from './identity/lid-mapping-store.service';import { isSafeSessionName } from '../common/utils/path-safety';export interface EngineCreateOptions {+ /** Session NAME — the on-disk auth-directory key (matches purgeSessionData/sessionAuthDir). */sessionId: string;+ /** Session UUID (Session.id) — the DB-row key for FK-bound stores (e.g. baileys_stored_messages). */+ dbSessionId: string;proxyUrl?: string;proxyType?: 'http' | 'https' | 'socks4' | 'socks5';}@@ -109,6 +112,7 @@ export class EngineFactory implements OnModuleInit {// registration, so the factory never assembles browser-shaped fields.return enginePlugin.instance.createEngine({sessionId: options.sessionId,+ dbSessionId: options.dbSessionId,proxyUrl: options.proxyUrl,proxyType: options.proxyType,}) as IWhatsAppEngine;diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.tsindex 0ea0f7f5e..418aa697b 100644--- a/src/engine/types/baileys.types.ts+++ b/src/engine/types/baileys.types.ts@@ -20,7 +20,10 @@ export interface BaileysMessageStore {* (the adapter appends the session id to isolate each session).*/export interface BaileysAdapterConfig {+ /** Session NAME — keys the on-disk auth directory and LID-mapping provenance. */sessionId: string;+ /** Session UUID (Session.id) — keys the FK-bound baileys_stored_messages rows via messageStore. */+ dbSessionId: string;authDir: string;proxyUrl?: string;proxyType?: 'http' | 'https' | 'socks4' | 'socks5';diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex ed4bd2667..646356715 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -554,7 +554,9 @@ describe('SessionService', () => {await service.start('sess-uuid-1');- expect(engineFactory.create).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'test-session' }));+ expect(engineFactory.create).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 'test-session', dbSessionId: 'sess-uuid-1' }),+ );expect(mockEngine.initialize).toHaveBeenCalled();expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {status: SessionStatus.INITIALIZING,diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a1aa5944a..d6e0deec6 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -640,6 +640,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst engine = this.engineFactory.create({sessionId: session.name,+ dbSessionId: id,proxyUrl: session.proxyUrl || undefined,proxyType: session.proxyType || undefined,});diff --git a/src/plugins/engines/baileys/index.spec.ts b/src/plugins/engines/baileys/index.spec.tsindex 83ce98f2a..051aec840 100644--- a/src/plugins/engines/baileys/index.spec.ts+++ b/src/plugins/engines/baileys/index.spec.ts@@ -17,11 +17,12 @@ describe('BaileysPlugin.createEngine (opaque config)', () => {logger: { log: jest.fn() },} as unknown as PluginContext);- plugin.createEngine({ sessionId: 'sess-1', proxyUrl: 'http://p', proxyType: 'http' });+ plugin.createEngine({ sessionId: 'sess-1', dbSessionId: 'db-1', proxyUrl: 'http://p', proxyType: 'http' });expect(BaileysAdapter).toHaveBeenCalledWith(expect.objectContaining({sessionId: 'sess-1',+ dbSessionId: 'db-1',authDir: '/data/baileys',proxyUrl: 'http://p',proxyType: 'http',diff --git a/src/plugins/engines/baileys/index.ts b/src/plugins/engines/baileys/index.tsindex 873c05abf..42a87c668 100644--- a/src/plugins/engines/baileys/index.ts+++ b/src/plugins/engines/baileys/index.ts@@ -40,6 +40,7 @@ export class BaileysPlugin implements IEnginePlugin {createEngine(config: Record<string, unknown>): IWhatsAppEngine {const sessionId = config.sessionId as string;+ const dbSessionId = config.dbSessionId as string;const proxyUrl = config.proxyUrl as string | undefined;const proxyType = config.proxyType as 'http' | 'https' | 'socks4' | 'socks5' | undefined;@@ -51,6 +52,7 @@ export class BaileysPlugin implements IEnginePlugin {return new BaileysAdapter({sessionId,+ dbSessionId,authDir,proxyUrl,proxyType,