Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(engine): move JID construction into the engine (#265) (#271)

Yudhi Armyndharisbad9288aec1f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01338a757..162168a0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
mode, including the zero-config SQLite default where data migrations don't), so historical chats render correctly
and message-type stats don't split the same kind across old/new tokens.
- Fixes a latent dashboard bug where incoming text (`chat`) was mis-styled as media and shown as `[chat]` in reply previews.
+- **JID construction moved into the engine** (engine-pluggability decoupling, #265). The check-number endpoint
+ (`GET /sessions/:id/contacts/check/:number`) now returns the engine's canonical chat id via a new
+ `IWhatsAppEngine.getNumberId(number)` instead of the controller hand-building a `…@c.us` JID. As a result the
+ returned `whatsappId` is the engine-resolved id and may be normalized — it can differ from the submitted number's
+ `…@c.us` form (e.g. a `@lid` identifier) rather than echoing the input. And status/story
+ broadcasts are flagged with a neutral `isStatusBroadcast` on the message payload, so engine-neutral code no longer
+ matches the engine-specific `status@broadcast` pseudo-JID. A non-whatsapp-web.js engine supplies its own JID scheme.
## [0.2.7] - 2026-06-16
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 1f34ae89a..2384df31a 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1073,11 +1073,17 @@ GET /api/sessions/:sessionId/contacts/check/:phone
**Response (200 OK):**
```json
{
+ "number": "628123456789",
"exists": true,
- "chatId": "[email protected]"
+ "whatsappId": "[email protected]"
}
```
+> `whatsappId` is the engine's canonical WhatsApp ID for the number (and `null`
+> when `exists` is `false`). It is resolved by the engine, so it may be
+> normalized and differ from the submitted number's `@c.us` form (e.g. a `@lid`
+> identifier) — use it verbatim as the chat target rather than rebuilding it.
+
---
#### Get Profile Picture
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 8394375ef..f9ee60776 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -588,26 +588,27 @@ curl -H "X-API-Key: $API_KEY" \
http://localhost:2785/api/sessions/default/contacts/628123456789
```
-### GET /api/sessions/:id/contacts/:phone/exists
+### GET /api/sessions/:id/contacts/check/:number
Check if number exists on WhatsApp.
```bash
curl -H "X-API-Key: $API_KEY" \
- http://localhost:2785/api/sessions/default/contacts/628123456789/exists
+ http://localhost:2785/api/sessions/default/contacts/check/628123456789
```
**Response:**
```json
{
- "success": true,
- "data": {
- "exists": true,
- }
+ "number": "628123456789",
+ "exists": true,
+ "whatsappId": "[email protected]"
}
```
+`whatsappId` is the engine's canonical WhatsApp ID (`null` when `exists` is
+`false`); it may be normalized and differ from the submitted number.
+
### POST /api/sessions/:id/contacts/:phone/block
Block contact.
diff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.ts
index fb3baaa1c..a597fed77 100644
--- a/src/engine/adapters/message-mapper.spec.ts
+++ b/src/engine/adapters/message-mapper.spec.ts
@@ -17,10 +17,16 @@ describe('buildIncomingMessageBase', () => {
expect(r.chatId).toBe('[email protected]');
expect(r.type).toBe('text'); // wwebjs 'chat' is neutralized to 'text'
expect(r.isGroup).toBe(false);
+ expect(r.isStatusBroadcast).toBe(false);
expect(r.author).toBeUndefined();
expect(r.contact).toBeUndefined();
});
+ it('flags a status/story broadcast via isStatusBroadcast (engine pseudo-JID stays in the adapter)', () => {
+ const r = buildIncomingMessageBase({ ...base, fromMe: true, from: '[email protected]', to: 'status@broadcast' });
+ expect(r.isStatusBroadcast).toBe(true);
+ });
+
it('includes author and pushName for a group message', () => {
const r = buildIncomingMessageBase({
...base,
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index 39ea0cd46..326144a20 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -72,6 +72,9 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
timestamp: msg.timestamp,
fromMe: msg.fromMe,
isGroup: chatId.endsWith('@g.us'),
+ // Flag status/story broadcasts here (the engine-specific `status@broadcast` pseudo-JID stays in
+ // the adapter) so engine-neutral code can skip them without matching the literal.
+ isStatusBroadcast: msg.to === 'status@broadcast' || chatId === 'status@broadcast',
};
// In a group, `from` is the group JID, so `author` is the only way to know the real sender.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index a037f20c0..0c403d31f 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -118,6 +118,7 @@ describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {
await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotReadyError);
await expect(adapter.checkNumberExists('628123')).rejects.toBeInstanceOf(EngineNotReadyError);
+ await expect(adapter.getNumberId('628123')).rejects.toBeInstanceOf(EngineNotReadyError);
});
it('carries HTTP 409 so NestJS returns "session not connected" (not 500) without a custom filter', () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 710f73e55..7f2415912 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -546,10 +546,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
}
- async checkNumberExists(number: string): Promise<boolean> {
+ async getNumberId(number: string): Promise<string | null> {
this.ensureReady();
const numberId = await this.client!.getNumberId(number);
- return numberId !== null;
+ return numberId?._serialized ?? null;
+ }
+
+ async checkNumberExists(number: string): Promise<boolean> {
+ return (await this.getNumberId(number)) !== null;
}
async getGroups(): Promise<Group[]> {
@@ -984,10 +988,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Reuse the shared mapper so history messages carry the same author/contact
// enrichment as live incoming messages (#223). The mapper defaults chatId to
// msg.from, which is wrong here (history includes fromMe messages whose `from`
- // is our own number), so override it to the requested chat and recompute isGroup.
+ // is our own number), so override it to the requested chat and recompute the
+ // chatId-derived flags (isGroup, isStatusBroadcast) from the real chat.
const out = buildIncomingMessageBase(msg);
out.chatId = chatId;
out.isGroup = chatId.endsWith('@g.us');
+ out.isStatusBroadcast = chatId === 'status@broadcast';
if (includeMedia && msg.hasMedia) {
try {
const media = await msg.downloadMedia();
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index d595cbeef..e7a5230b2 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -51,6 +51,11 @@ export interface IncomingMessage {
timestamp: number;
fromMe: boolean;
isGroup: boolean;
+ /**
+ * True for a status/story broadcast (not a real conversation). Set by the adapter so engine-neutral
+ * code can skip these without matching an engine-specific pseudo-JID (e.g. `status@broadcast`).
+ */
+ isStatusBroadcast?: boolean;
/** For group messages, the WID of the participant who actually sent it (`from` is the group JID there). */
author?: string;
/** Sender display info, best-effort from the WhatsApp Web contact cache. */
@@ -347,6 +352,11 @@ export interface IWhatsAppEngine {
getContacts(): Promise<Contact[]>;
getContactById(contactId: string): Promise<Contact | null>;
checkNumberExists(number: string): Promise<boolean>;
+ /**
+ * Resolve a phone number to its canonical chat id in the engine's native format, or null if the
+ * number is not registered. The engine owns the JID scheme, so callers never build it themselves.
+ */
+ getNumberId(number: string): Promise<string | null>;
// Groups - Basic
getGroups(): Promise<Group[]>;
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 129ba2668..9f1d994a8 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -42,11 +42,13 @@ export class ContactController {
description: 'Number existence check result',
})
async checkNumber(@Param('sessionId') sessionId: string, @Param('number') number: string) {
- const exists = await this.contactService.checkNumberExists(sessionId, number);
+ // The engine returns the canonical chat id in its native format; we don't build the JID here
+ // (decoupled from the whatsapp-web.js `@c.us` scheme).
+ const whatsappId = await this.contactService.getNumberId(sessionId, number);
return {
number,
- exists,
- whatsappId: exists ? `${number}@c.us` : null,
+ exists: whatsappId !== null,
+ whatsappId,
};
}
diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.ts
index 910e04f1c..7b5fffd57 100644
--- a/src/modules/contact/contact.service.spec.ts
+++ b/src/modules/contact/contact.service.spec.ts
@@ -23,4 +23,10 @@ describe('ContactService', () => {
await expect(makeService({ checkNumberExists }).checkNumberExists('s1', '628123')).resolves.toBe(true);
expect(checkNumberExists).toHaveBeenCalledWith('628123');
});
+
+ it('delegates getNumberId to the engine (canonical JID resolution)', async () => {
+ const getNumberId = jest.fn().mockResolvedValue('[email protected]');
+ await expect(makeService({ getNumberId }).getNumberId('s1', '628123')).resolves.toBe('[email protected]');
+ expect(getNumberId).toHaveBeenCalledWith('628123');
+ });
});
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index 6e35df53c..1c95022b4 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -34,6 +34,10 @@ export class ContactService {
return this.getEngine(sessionId).checkNumberExists(number);
}
+ getNumberId(sessionId: string, number: string) {
+ return this.getEngine(sessionId).getNumberId(number);
+ }
+
getProfilePicture(sessionId: string, contactId: string) {
return this.getEngine(sessionId).getProfilePicture(contactId);
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index d6b740f96..c1a817cbe 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -453,11 +453,19 @@ describe('SessionService', () => {
expect(dispatchedEvents('message.sent')).toHaveLength(0);
});
- it('does not dispatch message.sent for a status@broadcast (Story) post', async () => {
+ it('does not dispatch message.sent for a status/story broadcast (isStatusBroadcast flag)', async () => {
const callbacks = await startAndCaptureCallbacks();
+ // The adapter flags status broadcasts; session.service branches on the neutral flag, not the
+ // engine-specific `status@broadcast` pseudo-JID.
callbacks.onMessageCreate!(
- makeMessage({ id: 'wa-status', from: '[email protected]', to: 'status@broadcast', fromMe: true }),
+ makeMessage({
+ id: 'wa-status',
+ to: 'status@broadcast',
+ fromMe: true,
+ isStatusBroadcast: true,
+ }),
);
await flush();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index dcc229b62..27a56b1b3 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -434,9 +434,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return;
}
- // Status/Story posts (`status@broadcast`) are account-created but not real conversations;
- // don't emit `message.sent` for them.
- if (message.to === 'status@broadcast' || message.chatId === 'status@broadcast') {
+ // Status/Story posts are account-created but not real conversations; don't emit `message.sent`
+ // for them. The adapter flags these (the engine-specific pseudo-JID stays out of this layer).
+ if (message.isStatusBroadcast) {
return;
}