Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): normalize first-contact recipients

Yudhi Armyndharis8ad6eff4b3e7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index acdd34e1e..9900d10a2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Fix Baileys first-contact addresses and reject phone numbers reported as unregistered before sending.
- Preserve archived media and reactions during concurrent metadata updates.
- Keep sent media when merging onto an echo row fails.
- Keep inline media when its WhatsApp message ID is unavailable.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 8f34bd1d2..e86e65b27 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -196,7 +196,7 @@ Single-recipient send routes under `/messages` return **HTTP 201** with `{ "mess
Two consequences worth knowing:
-1. **Baileys does not reject an unregistered recipient synchronously.** A message to a number that is not on WhatsApp still returns `201` with a valid `messageId`. Whether it later delivers, stalls, or is reported as an error reaches you asynchronously, if at all. whatsapp-web.js refuses the same send with `400` when it cannot resolve the number, which can also mean this session has never had a chat with it.
+1. **A number reported as unregistered is refused before sending.** Baileys checks a phone destination when it has no LID mapping: a negative answer returns `400`, and an unanswered lookup returns `503`. Known LIDs skip that query. whatsapp-web.js also returns `400` when it cannot resolve the recipient, which can include its first-contact limitation. Neither result guarantees that a registered recipient will receive the message.
2. **There is no synchronous delivery confirmation on either engine** (whatsapp-web.js or Baileys), so the `201` cannot be made to mean "delivered."
**Before sending to a new number**, you can confirm it is a registered WhatsApp account with `GET /api/sessions/:sessionId/contacts/check/:number` (returns `{ exists, whatsappId }`; needs an `OPERATOR` key, like the send itself; see the Contacts reference).
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index d4ca6fa37..e259e4662 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -32,36 +32,36 @@ npm --prefix dashboard run test:unit
## 9.2 Test Commands
-| Command | Purpose |
-| ---------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| `npm test` | Run backend Jest unit tests from `src/` |
-| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |
-| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |
-| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |
-| `npm run test:docs` | Run the docs and manifest drift gates that `npm test` excludes |
-| `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test |
-| `npm run test:scripts` | Run the repo-level script tests on the Node test runner |
-| `npm run build && npm run test:engine-real` | Feed inbound messages through the real Baileys library and built adapter |
-| `OPENWA_SMOKE_IMAGE=<image> ./scripts/smoke-test-engine-libs.sh` | Import Baileys and launch the browser inside a built image |
-| `./scripts/smoke-test-backup-restore.sh` | Run the backup/restore smoke test used by the `scripts-smoke` job |
-| `npm run lint` | Run backend ESLint with type-aware rules |
-| `npm run format:check` | Check Prettier formatting for backend source and specs |
-| `npx tsc --noEmit -p tsconfig.json` | Type-check backend source, unit specs, and e2e specs |
-| `npm run openapi:check` | Verify the committed OpenAPI snapshot |
-| `npm run check:versions` | Verify documentation and package version consistency |
-| `npm run check:dockerignore` | Verify the Docker build context that `.dockerignore` defines |
-| `cd dashboard && npm run lint` | Run dashboard ESLint |
-| `cd dashboard && npm run typecheck` | Type-check dashboard test files |
-| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |
-| `cd dashboard && npm run test:cov` | Measure dashboard unit-test coverage (on demand, no enforced floor) |
-| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |
-| `cd dashboard && npm run build` | Type-check and build the dashboard |
-| `cd sdk/javascript && npm test && npm run typecheck` | Type-check and unit-test the JavaScript SDK |
-| `cd sdk/javascript && npm run build && npm run smoke` | Build and dual CJS/ESM package-smoke the JavaScript SDK |
-| `cd sdk/python && pytest` | Run the Python SDK tests |
-| `cd sdk/php && ./vendor/bin/phpunit` | Run the PHP SDK tests |
-| `cd sdk/java && mvn -B verify` | Run the Java SDK tests |
-| `cd sdk/go && gofmt -l . && go vet ./... && go test -race ./...` | List unformatted files, vet, and race-test the Go SDK |
+| Command | Purpose |
+| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| `npm test` | Run backend Jest unit tests from `src/` |
+| `npm test -- --runInBand` | Run backend tests serially; useful for local debugging and clean output |
+| `npm run test:cov` | Run backend tests with coverage and coverage thresholds |
+| `npm run test:e2e` | Run smoke-level e2e tests from `test/` |
+| `npm run test:docs` | Run the docs and manifest drift gates that `npm test` excludes |
+| `npm run test:pg-smoke` | Run the PostgreSQL migration and UUID-default smoke test |
+| `npm run test:scripts` | Run the repo-level script tests on the Node test runner |
+| `npm run build && npm run test:engine-real` | Exercise inbound messages and outbound recipient preparation with the real Baileys library and built adapter |
+| `OPENWA_SMOKE_IMAGE=<image> ./scripts/smoke-test-engine-libs.sh` | Import Baileys and launch the browser inside a built image |
+| `./scripts/smoke-test-backup-restore.sh` | Run the backup/restore smoke test used by the `scripts-smoke` job |
+| `npm run lint` | Run backend ESLint with type-aware rules |
+| `npm run format:check` | Check Prettier formatting for backend source and specs |
+| `npx tsc --noEmit -p tsconfig.json` | Type-check backend source, unit specs, and e2e specs |
+| `npm run openapi:check` | Verify the committed OpenAPI snapshot |
+| `npm run check:versions` | Verify documentation and package version consistency |
+| `npm run check:dockerignore` | Verify the Docker build context that `.dockerignore` defines |
+| `cd dashboard && npm run lint` | Run dashboard ESLint |
+| `cd dashboard && npm run typecheck` | Type-check dashboard test files |
+| `cd dashboard && npm run test:unit` | Run dashboard pure utility/unit tests |
+| `cd dashboard && npm run test:cov` | Measure dashboard unit-test coverage (on demand, no enforced floor) |
+| `cd dashboard && npm run i18n:check` | Verify dashboard locale key parity |
+| `cd dashboard && npm run build` | Type-check and build the dashboard |
+| `cd sdk/javascript && npm test && npm run typecheck` | Type-check and unit-test the JavaScript SDK |
+| `cd sdk/javascript && npm run build && npm run smoke` | Build and dual CJS/ESM package-smoke the JavaScript SDK |
+| `cd sdk/python && pytest` | Run the Python SDK tests |
+| `cd sdk/php && ./vendor/bin/phpunit` | Run the PHP SDK tests |
+| `cd sdk/java && mvn -B verify` | Run the Java SDK tests |
+| `cd sdk/go && gofmt -l . && go vet ./... && go test -race ./...` | List unformatted files, vet, and race-test the Go SDK |
## 9.3 Backend Unit Tests
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index fe4579c2e..aa205847c 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -703,13 +703,13 @@ curl -H "X-API-Key: $API_KEY" \
**Common Causes:**
-| Cause | Symptom | Solution |
-| -------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------- |
-| Invalid phone number | 400 error | Format: `[email protected]` |
-| Rate limited | 429 error | Reduce sending rate |
-| Session not started or not ready | 400 (`is not active`) or 409 | Start or reconnect the session |
-| Media too large | 413 error | Compress or reduce size |
-| Number not on WhatsApp | 400 on whatsapp-web.js; Baileys may accept it and never deliver | Verify the number first (`GET /api/sessions/{sessionId}/contacts/check/{number}`) |
+| Cause | Symptom | Solution |
+| -------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------------------------- |
+| Invalid phone number | 400 error | Format: `[email protected]` |
+| Rate limited | 429 error | Reduce sending rate |
+| Session not started or not ready | 400 (`is not active`) or 409 | Start or reconnect the session |
+| Media too large | 413 error | Compress or reduce size |
+| Number not on WhatsApp | 400 when the recipient lookup reports it as unregistered | Verify the number first (`GET /api/sessions/{sessionId}/contacts/check/{number}`) |
**Phone Number Validation:**
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 1d1e3e4c9..f74747958 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -590,16 +590,16 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
**Queries** (8)
-| Library method | OpenWA exposure |
-| ------------------------------ | ----------------------- |
-| `executeUSyncQuery` | ❌ **not exposed** |
-| `fetchAccountReachoutTimelock` | ⚙️ internal wiring |
-| `fetchBlocklist` | ✅ `getBlockedContacts` |
-| `fetchDisappearingDuration` | ❌ **not exposed** |
-| `fetchNewChatMessageCap` | ❌ **not exposed** |
-| `fetchStatus` | ❌ **not exposed** |
-| `getUSyncDevices` | ❌ **not exposed** |
-| `onWhatsApp` | ✅ `getNumberId` |
+| Library method | OpenWA exposure |
+| ------------------------------ | ----------------------------------- |
+| `executeUSyncQuery` | ❌ **not exposed** |
+| `fetchAccountReachoutTimelock` | ⚙️ internal wiring |
+| `fetchBlocklist` | ✅ `getBlockedContacts` |
+| `fetchDisappearingDuration` | ❌ **not exposed** |
+| `fetchNewChatMessageCap` | ❌ **not exposed** |
+| `fetchStatus` | ❌ **not exposed** |
+| `getUSyncDevices` | ❌ **not exposed** |
+| `onWhatsApp` | ✅ `getNumberId`, `sendTextMessage` |
**Profile, contacts & presence** (12)
diff --git a/openapi.json b/openapi.json
index f830ac2dc..cad2ecb14 100644
--- a/openapi.json
+++ b/openapi.json
@@ -8980,7 +8980,7 @@
},
"/api/sessions/{sessionId}/contacts/check/{number}": {
"get": {
- "description": "Returns whether the number is a registered WhatsApp account and its canonical id. Use this to pre-validate a recipient before sending: the Baileys send endpoints can return 201 for a number that is not on WhatsApp (whatsapp-web.js answers 400), so this is the way to confirm a new number is reachable before you send to it. Requires an OPERATOR key.",
+ "description": "Returns whether the number is a registered WhatsApp account and its canonical id. Use this to pre-validate a recipient before sending. Baileys also checks unmapped phone destinations before sending: a number reported as unregistered is rejected with 400. A successful check does not confirm message delivery. Requires an OPERATOR key.",
"operationId": "ContactController_checkNumber",
"parameters": [
{
@@ -19852,7 +19852,7 @@
"properties": {
"messageId": {
"type": "string",
- "description": "The message id, assigned when the gateway accepts the message for sending. A 201 here means the message was handed to the WhatsApp client — it does NOT confirm delivery. On Baileys a message to a number that is not on WhatsApp still returns 201 with a valid messageId (whatsapp-web.js answers 400); whether it later delivers, stalls, or is reported as an error reaches you asynchronously, if at all. To confirm a number is on WhatsApp before sending, use GET /api/sessions/{sessionId}/contacts/check/{number}; track real delivery via the message `status` field (sent → delivered → read, or failed if WhatsApp reports an error for it). A message resting at `sent` is not diagnostic on its own: a registered recipient whose device has not come online since the send stays at `sent` too.",
+ "description": "The message id, assigned when the gateway accepts the message for sending. A 201 here means the message was handed to the WhatsApp session; it does not confirm delivery. Baileys checks phone destinations without a LID mapping and rejects a number reported as unregistered with 400. An unanswered lookup returns 503 before sending. Known LIDs skip the number check. Track delivery through the message status (sent, delivered, read, or failed). A message resting at sent can also belong to a registered recipient whose device is offline.",
"example": "[email protected]_3EB0123456789"
},
"timestamp": {
diff --git a/package.json b/package.json
index 806ebb131..dcfafb874 100644
--- a/package.json
+++ b/package.json
@@ -48,7 +48,7 @@
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"test:pg-smoke": "node scripts/pg-uuid-smoke.js",
- "test:engine-real": "node --test test/engine-real/baileys-inbound.spec.mjs",
+ "test:engine-real": "node --test test/engine-real/baileys-inbound.spec.mjs test/engine-real/baileys-outbound.spec.mjs",
"typeorm": "typeorm-ts-node-commonjs",
"typeorm:prod": "typeorm",
"migration:create": "npm run typeorm -- migration:create src/database/migrations/$npm_config_name",
diff --git a/src/engine/adapters/baileys-click-button.spec.ts b/src/engine/adapters/baileys-click-button.spec.ts
index f5d32052a..54a4c300d 100644
--- a/src/engine/adapters/baileys-click-button.spec.ts
+++ b/src/engine/adapters/baileys-click-button.spec.ts
@@ -63,7 +63,7 @@ function makeMessaging(stored: unknown = PROMPT, opts: { ephemeralExpiration?: n
key: { id: 'CLICK-1', remoteJid: '[email protected]', fromMe: true },
messageTimestamp: 1700000000,
});
- const sock = { sendMessage };
+ const sock = { sendMessage, onWhatsApp: jest.fn((jid: string) => Promise.resolve([{ jid, exists: true }])) };
const getStoredMessage = jest.fn().mockResolvedValue(stored);
const putStoredMessage = jest.fn();
const getEphemeralExpiration = jest.fn().mockReturnValue(opts.ephemeralExpiration);
@@ -71,6 +71,7 @@ function makeMessaging(stored: unknown = PROMPT, opts: { ephemeralExpiration?: n
ensureReady: jest.fn(),
sessionProxyUrl: () => undefined,
getSocket: () => sock as unknown as WASocket,
+ getSocketOrNull: () => sock as unknown as WASocket,
logger,
toNeutralJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
toEngineJid: (j: string) => j,
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index f919ccab8..f13c2e4c6 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -40,6 +40,8 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { type createLogger } from '../../common/services/logger.service';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { EngineNotSentError } from '../../common/errors/engine-not-sent.error';
+import { parseWaId, userPart } from '../identity/wa-id';
import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';
/**
@@ -287,7 +289,11 @@ export class BaileysMessaging {
async getNumberId(number: string): Promise<string | null> {
this.host.ensureReady();
- const results = await this.sock().onWhatsApp(number);
+ const results = await withQueryDeadline(
+ this.sock().onWhatsApp(number),
+ this.queryBudgetMs,
+ 'WhatsApp did not answer the number-check query in time',
+ );
// onWhatsApp has no else branch after `if (results)`, so it resolves undefined when the usync
// query goes unanswered — and Baileys' query() swallows its own timeout rather than throwing.
// An empty ARRAY is a real answer; undefined is the absence of one, and coalescing the two
@@ -702,24 +708,32 @@ export class BaileysMessaging {
* Resolve a 1:1 phone-dialect chat id (`@c.us` / `@s.whatsapp.net`) to the contact's `@lid` when the
* mapping is known. WhatsApp rejects PN-addressed 1:1 sends to LID-migrated accounts with ack error
* 463 ("missing tctoken" — the privacy token is stored and honored under the LID), while the very
- * same send addressed to the LID delivers (verified live). Groups, broadcast, already-lid and
- * unmapped ids pass through unchanged, reproducing the previous behavior.
+ * same send addressed to the LID delivers (verified live). Unmapped phone ids still need the
+ * canonical Baileys domain; the library does not rewrite a neutral @c.us destination.
*/
private async toDeliverableJid(chatId: string): Promise<string> {
- if (!chatId.endsWith('@c.us') && !chatId.endsWith('@s.whatsapp.net')) {
- return chatId;
- }
+ const { kind, userPart: user } = parseWaId(chatId);
+ if (kind === 'lid') return `${user}@lid`;
+ if (kind !== 'user') return chatId;
+ const pn = this.host.toEngineJid(chatId);
+ const sock = this.sock();
try {
- const pn = this.host.toEngineJid(chatId);
- const lid = await this.sock().signalRepository?.lidMapping?.getLIDForPN(pn);
+ const lid = await withQueryDeadline(
+ Promise.resolve(sock.signalRepository?.lidMapping?.getLIDForPN(pn)),
+ this.queryBudgetMs,
+ 'WhatsApp did not answer the recipient LID lookup in time',
+ );
+ if (this.host.getSocketOrNull() !== sock) throw new EngineNotReadyError();
// Record what the socket just told us. This resolution is the one place a cold contact's lid
// becomes known before any message arrives, and without writing it back the session store
// still believes the two ids are unrelated — which makes an ownership check comparing the
// stored key's lid against a phone-dialect chatId reject a message that IS in that chat.
- if (lid) this.host.recordLidMapping(lid, pn);
- return lid ?? chatId;
- } catch {
- return chatId; // resolution is best-effort; an unmapped contact sends to the PN as before
+ if (lid) this.host.recordLidMapping(`${userPart(lid)}@lid`, pn);
+ return lid ? `${userPart(lid)}@lid` : pn;
+ } catch (error) {
+ if (this.host.getSocketOrNull() !== sock || error instanceof EngineNotReadyError) throw new EngineNotReadyError();
+ if (error instanceof EngineTransportError) throw new EngineNotSentError(error.message);
+ return pn; // LID resolution is best-effort; the phone destination must still be canonical.
}
}
@@ -831,6 +845,20 @@ export class BaileysMessaging {
options?: Parameters<WASocket['sendMessage']>[2],
): Promise<WAMessage | undefined> {
const sock = this.sock();
+ if (parseWaId(jid).kind === 'user') {
+ let numberId: string | null;
+ try {
+ numberId = await this.getNumberId(jid);
+ } catch (error) {
+ if (this.host.getSocketOrNull() !== sock) throw new EngineNotReadyError();
+ throw new EngineNotSentError(`WhatsApp could not check the recipient before send: ${String(error)}`);
+ }
+ if (this.host.getSocketOrNull() !== sock) throw new EngineNotReadyError();
+ if (!numberId) throw new BadRequestException(`WhatsApp reports recipient ${jid} is not registered`);
+ const canonical = this.host.toEngineJid(numberId);
+ if (canonical !== jid) jid = await this.toDeliverableJid(numberId);
+ }
+ if (this.host.getSocketOrNull() !== sock) throw new EngineNotReadyError();
let sent: WAMessage | undefined;
try {
sent = options ? await sock.sendMessage(jid, content, options) : await sock.sendMessage(jid, content);
diff --git a/src/engine/adapters/baileys-quote-on-receipt.spec.ts b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
index 5f3ec086c..dfe5c6d56 100644
--- a/src/engine/adapters/baileys-quote-on-receipt.spec.ts
+++ b/src/engine/adapters/baileys-quote-on-receipt.spec.ts
@@ -77,6 +77,7 @@ describe('quoting a Baileys message the moment it is announced', () => {
on: { edited?: () => void; revoked?: () => void } = {},
): { events: BaileysEvents; messaging: BaileysMessaging; sock: { sendMessage: jest.Mock } } => {
const sock = {
+ onWhatsApp: jest.fn((jid: string) => Promise.resolve([{ jid, exists: true }])),
sendMessage: jest
.fn()
.mockResolvedValue({ key: { id: 'R1', remoteJid: CHAT, fromMe: true }, messageTimestamp: 1 }),
diff --git a/src/engine/adapters/baileys-quoted-send.spec.ts b/src/engine/adapters/baileys-quoted-send.spec.ts
index f3fe5c1bd..c2abc2569 100644
--- a/src/engine/adapters/baileys-quoted-send.spec.ts
+++ b/src/engine/adapters/baileys-quoted-send.spec.ts
@@ -33,12 +33,16 @@ function makeMessaging(stored: unknown = STORED): {
sock: { sendMessage: jest.Mock };
getStoredMessage: jest.Mock;
} {
- const sock = { sendMessage: jest.fn().mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 }) };
+ const sock = {
+ onWhatsApp: jest.fn((jid: string) => Promise.resolve([{ jid, exists: true }])),
+ sendMessage: jest.fn().mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 }),
+ };
const getStoredMessage = jest.fn().mockResolvedValue(stored);
const host = {
ensureReady: jest.fn(),
sessionProxyUrl: () => undefined,
getSocket: () => sock as unknown as WASocket,
+ getSocketOrNull: () => sock as unknown as WASocket,
logger,
toNeutralJid: (j: string) => j,
toEngineJid: (j: string) => j,
diff --git a/src/engine/adapters/baileys-sticker-webp.spec.ts b/src/engine/adapters/baileys-sticker-webp.spec.ts
index bd49f1d0d..eeb3501e4 100644
--- a/src/engine/adapters/baileys-sticker-webp.spec.ts
+++ b/src/engine/adapters/baileys-sticker-webp.spec.ts
@@ -45,11 +45,15 @@ const isWebp = (b: unknown): boolean =>
b.subarray(8, 12).toString('ascii') === 'WEBP';
function makeMessaging(): { messaging: BaileysMessaging; sock: { sendMessage: jest.Mock } } {
- const sock = { sendMessage: jest.fn().mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 }) };
+ const sock = {
+ onWhatsApp: jest.fn((jid: string) => Promise.resolve([{ jid, exists: true }])),
+ sendMessage: jest.fn().mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 }),
+ };
const host = {
ensureReady: jest.fn(),
sessionProxyUrl: () => undefined,
getSocket: () => sock as unknown as WASocket,
+ getSocketOrNull: () => sock as unknown as WASocket,
logger,
toNeutralJid: (j: string) => j,
toEngineJid: (j: string) => j,
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 85d57b7e1..16a2fda89 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -195,6 +195,7 @@ const fakeStore = {
beforeEach(() => {
fakeStore.getMessage.mockReset();
fakeSock.signalRepository = undefined;
+ fakeSock.onWhatsApp.mockReset().mockImplementation((jid: string) => Promise.resolve([{ jid, exists: true }]));
fakeSock.groupFetchAllParticipating.mockReset();
const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
baileys.getContentType.mockReset().mockReturnValue('conversation');
@@ -1951,13 +1952,13 @@ describe('BaileysAdapter messaging', () => {
expect(spy).toHaveBeenCalledWith([{ lid: '484848@lid', pn: '[email protected]' }]);
});
- it('sendTextMessage keeps the phone jid when no LID mapping is known', async () => {
+ it('sendTextMessage uses the canonical phone jid when no LID mapping is known', async () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(null) } };
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hello');
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
{ text: 'hello', linkPreview: null },
safeSendOptions(),
);
@@ -4275,11 +4276,11 @@ describe('BaileysAdapter store-backed ops', () => {
await adapter.replyToMessage('[email protected]', 'LIST1', 'got it');
await adapter.reactToMessage('[email protected]', 'LIST1', '👍');
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
{ text: 'got it', linkPreview: null },
expect.objectContaining({ quoted: listMsg }),
);
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
react: { text: '👍', key: listMsg.key },
});
});
@@ -4655,7 +4656,7 @@ describe('BaileysAdapter store-backed ops', () => {
const adapter = await ready();
await expect(adapter.editMessage('[email protected]', 'TARGET', 'x')).resolves.toBeDefined();
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
{
text: 'x',
edit: ownStored.key,
diff --git a/src/engine/adapters/own-presence.spec.ts b/src/engine/adapters/own-presence.spec.ts
index e7991f220..a891c4b8a 100644
--- a/src/engine/adapters/own-presence.spec.ts
+++ b/src/engine/adapters/own-presence.spec.ts
@@ -89,6 +89,7 @@ describe('BaileysMessaging.setOnlinePresence', () => {
const host = {
ensureReady: jest.fn(),
getSocket: () => sock as unknown as WASocket,
+ getSocketOrNull: () => sock as unknown as WASocket,
toEngineJid: (jid: string) => jid,
recordLidMapping: jest.fn(),
logger,
diff --git a/src/engine/inventory-mapping-direction.spec.ts b/src/engine/inventory-mapping-direction.spec.ts
index ce22c8ff5..de39921f3 100644
--- a/src/engine/inventory-mapping-direction.spec.ts
+++ b/src/engine/inventory-mapping-direction.spec.ts
@@ -186,9 +186,10 @@ describe('docs/29 §29.5 inventory — the interface methods a row names can rea
it('does not credit one engine with a symbol only the other engine reaches', () => {
// Every interface method has the same name in both adapters. Baileys reaches `onWhatsApp` from
- // getNumberId alone; its send paths must not borrow the wwjs send helpers' call edges.
+ // getNumberId and the shared send path; unrelated reads must not borrow the wwjs call edges.
expect(reachers('onWhatsApp', 'baileys').has('getNumberId')).toBe(true);
- expect(reachers('onWhatsApp', 'baileys').has('sendTextMessage')).toBe(false);
+ expect(reachers('onWhatsApp', 'baileys').has('sendTextMessage')).toBe(true);
+ expect(reachers('onWhatsApp', 'baileys').has('getContacts')).toBe(false);
expect(reachers('getBlockedContacts', 'wwjs').has('getContacts')).toBe(false);
});
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 22e4c067e..5ae0df9e9 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -128,9 +128,9 @@ export class ContactController {
summary: 'Check if a phone number exists on WhatsApp',
description:
'Returns whether the number is a registered WhatsApp account and its canonical id. Use this to ' +
- 'pre-validate a recipient before sending: the Baileys send endpoints can return 201 for a number ' +
- 'that is not on WhatsApp (whatsapp-web.js answers 400), so this is the way to confirm a new number ' +
- 'is reachable before you send to it. Requires an OPERATOR key.',
+ 'pre-validate a recipient before sending. Baileys also checks unmapped phone destinations before ' +
+ 'sending: a number reported as unregistered is rejected with 400. A successful check does not ' +
+ 'confirm message delivery. Requires an OPERATOR key.',
})
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiParam({ name: 'number', description: 'Phone number to check (e.g., 628123456789)' })
diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.ts
index 322697053..02b5bfcac 100644
--- a/src/modules/message/dto/send-message.dto.ts
+++ b/src/modules/message/dto/send-message.dto.ts
@@ -343,14 +343,11 @@ export class MessageResponseDto {
@ApiProperty({
description:
'The message id, assigned when the gateway accepts the message for sending. A 201 here means the ' +
- 'message was handed to the WhatsApp client — it does NOT confirm delivery. On Baileys a message to a ' +
- 'number that is not on WhatsApp still returns 201 with a valid messageId (whatsapp-web.js answers ' +
- '400); whether it later delivers, stalls, or is reported as an error ' +
- 'reaches you asynchronously, if at all. To confirm a number is on WhatsApp before ' +
- 'sending, use GET /api/sessions/{sessionId}/contacts/check/{number}; track real delivery via the ' +
- 'message `status` field (sent → delivered → read, or failed if WhatsApp reports an error for it). ' +
- 'A message resting at `sent` is not diagnostic on its own: a registered recipient whose device has ' +
- 'not come online since the send stays at `sent` too.',
+ 'message was handed to the WhatsApp session; it does not confirm delivery. Baileys checks phone ' +
+ 'destinations without a LID mapping and rejects a number reported as unregistered with 400. An ' +
+ 'unanswered lookup returns 503 before sending. Known LIDs skip the number check. Track delivery ' +
+ 'through the message status (sent, delivered, read, or failed). A message resting at sent can ' +
+ 'also belong to a registered recipient whose device is offline.',
example: '[email protected]_3EB0123456789',
})
messageId!: string;
diff --git a/test/engine-real/baileys-outbound.spec.mjs b/test/engine-real/baileys-outbound.spec.mjs
new file mode 100644
index 000000000..9a3af9f4b
--- /dev/null
+++ b/test/engine-real/baileys-outbound.spec.mjs
@@ -0,0 +1,210 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import * as lib from '@whiskeysockets/baileys';
+import { LIDMappingStore } from '@whiskeysockets/baileys/lib/Signal/lid-mapping.js';
+
+const require = createRequire(import.meta.url);
+const { BaileysMessaging } = require('../../dist/engine/adapters/baileys-messaging.js');
+const { BaileysSessionStore } = require('../../dist/engine/adapters/baileys-session-store.js');
+const { EngineNotSentError } = require('../../dist/common/errors/engine-not-sent.error.js');
+const PN = '[email protected]';
+const LID = '123456789012345@lid';
+const noop = () => undefined;
+
+function build(t, { lid = null, budget = 1000 } = {}) {
+ const getLIDForPN = t.mock.fn(() => Promise.resolve(lid));
+ const sock = {
+ signalRepository: { lidMapping: { getLIDForPN, getPNForLID: () => Promise.resolve(PN) } },
+ onWhatsApp: t.mock.fn(jid => Promise.resolve([{ jid, exists: true }])),
+ sendMessage: t.mock.fn(jid => Promise.resolve({ key: { id: 'M1', remoteJid: jid }, messageTimestamp: 1 })),
+ sendPresenceUpdate: t.mock.fn(() => Promise.resolve()),
+ presenceSubscribe: t.mock.fn(() => Promise.resolve()),
+ };
+ let live = sock;
+ const recordLidMapping = t.mock.fn();
+ const messaging = new BaileysMessaging(
+ {
+ ensureReady: noop,
+ getSocket: () => live,
+ getSocketOrNull: () => live,
+ logger: { warn: noop },
+ toEngineJid: jid => BaileysSessionStore.prototype.toEngineJid(jid),
+ toNeutralJid: jid => jid.replace('@s.whatsapp.net', '@c.us'),
+ getEphemeralExpiration: noop,
+ getStoredMessage: () => Promise.resolve({ key: { id: 'Q1', remoteJid: PN }, message: { conversation: 'Q' } }),
+ wasDeletedForEveryone: () => false,
+ pendingEditOf: noop,
+ toUnixSeconds: ts => ts,
+ sessionProxyUrl: noop,
+ loadLib: () => Promise.resolve(lib),
+ putStoredMessage: noop,
+ recordMessage: noop,
+ rememberOwnSend: noop,
+ recordLidMapping,
+ getOnMessageCreate: noop,
+ },
+ budget,
+ );
+ return {
+ messaging,
+ sock,
+ recordLidMapping,
+ stop: () => {
+ live = null;
+ },
+ };
+}
+
+test('an unmapped neutral phone destination uses the Baileys domain', async t => {
+ const { messaging, sock } = build(t);
+ await messaging.sendTextMessage(PN.replace('@s.whatsapp.net', '@c.us'), 'hello');
+ assert.equal(sock.sendMessage.mock.calls[0].arguments[0], PN);
+ assert.equal(sock.onWhatsApp.mock.callCount(), 1);
+});
+
+test('cold sends resolve through the real Baileys LID store', async t => {
+ for (const pairs of [[], [{ pn: PN, lid: LID }]]) {
+ const data = {};
+ const lookup = t.mock.fn(() => Promise.resolve(pairs));
+ const mapping = new LIDMappingStore(
+ {
+ get: (_type, ids) => Promise.resolve(Object.fromEntries(ids.map(id => [id, data[id]]))),
+ set: update => {
+ Object.assign(data, update['lid-mapping']);
+ return Promise.resolve();
+ },
+ transaction: work => work(),
+ },
+ { trace: noop, debug: noop, warn: noop },
+ lookup,
+ );
+ t.after(() => mapping.close());
+ const { messaging, sock } = build(t);
+ sock.signalRepository.lidMapping = mapping;
+ await messaging.sendTextMessage(PN.replace('@s.whatsapp.net', '@c.us'), 'hello');
+ assert.deepEqual(lookup.mock.calls[0].arguments[0], [PN]);
+ assert.equal(sock.sendMessage.mock.calls[0].arguments[0], pairs.length ? LID : PN);
+ assert.equal(sock.onWhatsApp.mock.callCount(), pairs.length ? 0 : 1);
+ }
+});
+
+test('text, poll and reply sends share canonical recipient preparation', async t => {
+ for (const send of [
+ m => m.sendTextMessage(PN.replace('@s.whatsapp.net', '@c.us'), 'hello'),
+ m => m.sendPollMessage(PN.replace('@s.whatsapp.net', '@c.us'), { name: 'Q', options: ['A', 'B'] }),
+ m => m.replyToMessage(PN.replace('@s.whatsapp.net', '@c.us'), 'Q1', 'reply'),
+ ]) {
+ const { messaging, sock } = build(t);
+ await send(messaging);
+ assert.equal(sock.sendMessage.mock.calls[0].arguments[0], PN);
+ assert.equal(sock.onWhatsApp.mock.callCount(), 1);
+ }
+});
+
+test('hosted phone and LID destinations normalize to the account', async t => {
+ const { messaging, sock } = build(t);
+ await messaging.sendTextMessage(PN.replace('@s.whatsapp.net', ':3@hosted'), 'hello');
+ await messaging.sendTextMessage(LID.replace('@lid', ':[email protected]'), 'hello');
+ assert.deepEqual(
+ sock.sendMessage.mock.calls.map(call => call.arguments[0]),
+ [PN, LID],
+ );
+});
+
+test('known and explicit device LIDs address the account and skip phone checks', async t => {
+ const { messaging, sock, recordLidMapping } = build(t, { lid: LID.replace('@', ':3@') });
+ await messaging.sendTextMessage(PN, 'hello');
+ await messaging.sendTextMessage(LID.replace('@', ':7@'), 'hello');
+ assert.deepEqual(
+ sock.sendMessage.mock.calls.map(call => call.arguments[0]),
+ [LID, LID],
+ );
+ assert.equal(recordLidMapping.mock.calls[0].arguments[0], LID);
+ assert.equal(sock.onWhatsApp.mock.callCount(), 0);
+});
+
+test('presence normalizes a phone without querying its registration', async t => {
+ const { messaging, sock } = build(t);
+ await messaging.sendChatState(PN.replace('@s.whatsapp.net', '@c.us'), 'typing');
+ await messaging.subscribeToPresence(PN);
+ assert.equal(sock.sendPresenceUpdate.mock.calls[0].arguments[1], PN);
+ assert.equal(sock.onWhatsApp.mock.callCount(), 0);
+});
+
+test('groups, broadcasts and channels bypass phone checks', async t => {
+ const { messaging, sock } = build(t);
+ for (const jid of ['[email protected]', 'status@broadcast', '123@broadcast', '123@newsletter']) {
+ await messaging.sendTextMessage(jid, 'hello');
+ assert.equal(sock.sendMessage.mock.calls.at(-1).arguments[0], jid);
+ }
+ assert.equal(sock.onWhatsApp.mock.callCount(), 0);
+});
+
+test('an unregistered phone is refused before sending', async t => {
+ const { messaging, sock } = build(t);
+ sock.onWhatsApp.mock.mockImplementation(() => Promise.resolve([]));
+ await assert.rejects(messaging.sendTextMessage(PN, 'hello'), error => error.getStatus() === 400);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+});
+
+test('an unanswered or rejected phone query is a transport failure before sending', async t => {
+ for (const outcome of [() => Promise.resolve(undefined), () => Promise.reject(new Error('disconnected'))]) {
+ const { messaging, sock } = build(t);
+ sock.onWhatsApp.mock.mockImplementation(outcome);
+ await assert.rejects(messaging.sendTextMessage(PN, 'hello'), error => error instanceof EngineNotSentError);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+ }
+});
+
+test('a stalled phone query stops at the OpenWA deadline', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { messaging, sock } = build(t, { budget: 20 });
+ sock.onWhatsApp.mock.mockImplementation(() => new Promise(noop));
+ const sent = messaging.sendTextMessage(PN, 'hello');
+ await new Promise(setImmediate);
+ t.mock.timers.tick(21);
+ await assert.rejects(sent, error => error instanceof EngineNotSentError);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+});
+
+test('a stalled LID lookup cannot hold or send the request indefinitely', async t => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { messaging, sock } = build(t, { budget: 20 });
+ sock.signalRepository.lidMapping.getLIDForPN.mock.mockImplementation(() => new Promise(noop));
+ const sent = messaging.sendTextMessage(PN, 'hello');
+ await new Promise(setImmediate);
+ t.mock.timers.tick(21);
+ await assert.rejects(sent, error => error instanceof EngineNotSentError);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+});
+
+test('a socket stopped during phone lookup cannot send', async t => {
+ const { messaging, sock, stop } = build(t);
+ sock.onWhatsApp.mock.mockImplementation(jid => {
+ stop();
+ return Promise.resolve([{ jid, exists: true }]);
+ });
+ await assert.rejects(messaging.sendTextMessage(PN, 'hello'), error => error.getStatus() === 409);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+});
+
+test('a socket stopped during LID resolution cannot send or record its mapping', async t => {
+ for (const outcome of [() => Promise.resolve(LID), () => Promise.reject(new Error('disconnected'))]) {
+ const { messaging, sock, recordLidMapping, stop } = build(t);
+ sock.signalRepository.lidMapping.getLIDForPN.mock.mockImplementation(() => {
+ stop();
+ return outcome();
+ });
+ await assert.rejects(messaging.sendTextMessage(PN, 'hello'), error => error.getStatus() === 409);
+ assert.equal(sock.sendMessage.mock.callCount(), 0);
+ assert.equal(recordLidMapping.mock.callCount(), 0);
+ }
+});
+
+test('a failed LID query still uses a canonical phone destination', async t => {
+ const { messaging, sock } = build(t);
+ sock.signalRepository.lidMapping.getLIDForPN.mock.mockImplementation(() => Promise.reject(new Error('no mapping')));
+ await messaging.sendTextMessage(PN.replace('@s.whatsapp.net', '@c.us'), 'hello');
+ assert.equal(sock.sendMessage.mock.calls[0].arguments[0], PN);
+});