Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(contacts)!: require an OPERATOR key for the number check

Yudhi Armyndharis9850f11d339f
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 7895a9f67..7dc68a60e 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -182,7 +182,7 @@ Two consequences worth knowing:
1. **WhatsApp 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.
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 }`; see the Contacts reference).
+**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).
**For real delivery state**, track the stored message's `status`, which advances asynchronously as WhatsApp sends acks: `sent → delivered → read`, or `failed` when WhatsApp reports an error for the message — which also dispatches a `message.failed` webhook. See the message shape under the Messages reference.
@@ -2356,7 +2356,7 @@ Cancel a running (pending/processing) bulk batch. No request body.
### 6.4.3 Contacts
-Contact endpoints are scoped under a session: `/api/sessions/:sessionId/contacts`. All read routes require a valid API key; the block/unblock writes require an `OPERATOR` key. Every route returns `400 "Session is not started"` when the target session is missing entirely or is not in a started/ready state (the engine guard does not distinguish the two). Responses are the raw handler payload (no envelope).
+Contact endpoints are scoped under a session: `/api/sessions/:sessionId/contacts`. All read routes require a valid API key, except the number check (`GET .../check/:number`), which requires an `OPERATOR` key because each call queries WhatsApp about a third party and bulk checks put the linked account's standing at risk; the block/unblock writes require an `OPERATOR` key. Every route returns `400 "Session is not started"` when the target session is missing entirely or is not in a started/ready state (the engine guard does not distinguish the two). Responses are the raw handler payload (no envelope).
The `Contact` object returned by the list and get-by-id routes has this shape:
@@ -2434,7 +2434,7 @@ engines claim different things about the same account.
Check whether a phone number exists on WhatsApp and return its canonical WhatsApp id when it does.
-**Auth:** API key
+**Auth:** API key (`OPERATOR`)
**Path parameters**
@@ -2457,7 +2457,7 @@ Check whether a phone number exists on WhatsApp and return its canonical WhatsAp
> Route-order caveat: this route is two path segments (`check/:number`), so it never collides with the single-segment `GET /:contactId` — a contact id of literally `check` resolves to `GET /:contactId`.
-**Errors:** `400` session is not started · `401` missing/invalid API key · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)
+**Errors:** `400` session is not started · `401` missing/invalid API key · `403` API-key role below OPERATOR · `409` conflict or engine not ready (retryable) · `503` session not ready or dependency unavailable (retryable)
#### GET /api/sessions/:sessionId/contacts/:contactId
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 933e241e9..6e1203232 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -619,7 +619,7 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts?limit=100&offset=0" \
#### GET /api/sessions/:sessionId/contacts/check/:number
-Check whether a phone number is on WhatsApp.
+Check whether a phone number is on WhatsApp. Requires an `OPERATOR` key.
```bash
curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/check/628123456789" \
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 656ea3a7e..79b4d1454 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -185,7 +185,7 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
| ----------------- | -------------------------------------- | ------------------------------------------------------------------------------------ |
| `list` | `list(sessionId, query?)` | List contacts known to the session. |
| `get` | `get(sessionId, contactId)` | Get details for a single contact by JID. |
-| `check` | `check(sessionId, number)` | Check whether a phone number is registered on WhatsApp. |
+| `check` | `check(sessionId, number)` | Check whether a phone number is registered on WhatsApp. **OPERATOR** |
| `profilePicture` | `profilePicture(sessionId, contactId)` | Get the contact's profile picture URL (or null). |
| `profilePictures` | `profilePictures(sessionId, ids)` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |
| `phone` | `phone(sessionId, contactId)` | Resolve a contact id (e.g. a `@lid`) to a phone number. |
@@ -559,7 +559,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
| ------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `list` | `list(session_id, query=None) -> list[ContactRecord]` | List contacts (`query`: `limit`, `offset`). |
| `get` | `get(session_id, contact_id) -> ContactRecord` | Get one contact. |
-| `check` | `check(session_id, number) -> CheckNumberResponse` | Check whether a number is on WhatsApp. |
+| `check` | `check(session_id, number) -> CheckNumberResponse` | Check whether a number is on WhatsApp. **OPERATOR** |
| `profile_picture` | `profile_picture(session_id, contact_id) -> ProfilePictureResponse` | Get a contact's profile picture. |
| `profile_pictures` | `profile_pictures(session_id, ids) -> ProfilePicturesResponse` | Batch-resolve profile picture URLs for up to 50 contacts. |
| `phone` | `phone(session_id, contact_id) -> ContactPhoneResponse` | Resolve a contact's phone number. |
@@ -909,7 +909,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu
| ----------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| `list` | `list(string $sessionId, array $query = []): array` | List contacts. |
| `get` | `get(string $sessionId, string $contactId): array` | Get one contact. |
-| `check` | `check(string $sessionId, string $number): array` | Check whether a number is on WhatsApp. |
+| `check` | `check(string $sessionId, string $number): array` | Check whether a number is on WhatsApp. **OPERATOR** |
| `profilePicture` | `profilePicture(string $sessionId, string $contactId): array` | Get a contact's profile picture. |
| `profilePictures` | `profilePictures(string $sessionId, array $ids): array` | Batch-resolve profile picture URLs for up to 50 contacts in one request. |
| `phone` | `phone(string $sessionId, string $contactId): array` | Resolve a contact's phone number. |
diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.md
index 7d861dee4..5ad8ea184 100644
--- a/docs/24-mcp-integration.md
+++ b/docs/24-mcp-integration.md
@@ -127,18 +127,19 @@ The surface is an **allowlist by construction** — a capability is exposed only
declares a `tier` (`read` | `write`) and a `requiredRole` when the call warrants one: every
write carries its privilege level, and a read carries the role its REST twin requires. The
reads at OPERATOR are `WebhooksList`, `WebhookFindBySession` and `WebhookFindOne`,
-`AutomationRuleFindAll` and `AutomationRuleFindOne`, and `GroupGetInviteCode` (the invite
-code is a transferable join capability, so it sits at OPERATOR like the QR endpoint).
-
-| Domain | Read tools | Write tools |
-| -------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
-| **Session** | list, get, chats, stats, presence | mark read/unread, typing, subscribe presence |
-| **Message** | list, history, reactions | send text/image/video/audio/document/location/contact/sticker/template, reply, forward, react |
-| **Contact** | list, get, check-number, resolve-phone, profile-picture | block, unblock |
-| **Group** | list, get, invite-code (OPERATOR) | create, add participants, set subject, set description |
-| **Webhook** | list, get (OPERATOR) | — |
-| **Label** | list, get, chats for a label, labels on a chat | upsert, delete, add to chat, remove from chat |
-| **Automation** | rules list, get (OPERATOR) | — |
+`AutomationRuleFindAll` and `AutomationRuleFindOne`, `GroupGetInviteCode` (the invite
+code is a transferable join capability, so it sits at OPERATOR like the QR endpoint), and
+`ContactCheckNumber` (each call queries WhatsApp about a third party).
+
+| Domain | Read tools | Write tools |
+| -------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
+| **Session** | list, get, chats, stats, presence | mark read/unread, typing, subscribe presence |
+| **Message** | list, history, reactions | send text/image/video/audio/document/location/contact/sticker/template, reply, forward, react |
+| **Contact** | list, get, check-number (OPERATOR), resolve-phone, profile-picture | block, unblock |
+| **Group** | list, get, invite-code (OPERATOR) | create, add participants, set subject, set description |
+| **Webhook** | list, get (OPERATOR) | — |
+| **Label** | list, get, chats for a label, labels on a chat | upsert, delete, add to chat, remove from chat |
+| **Automation** | rules list, get (OPERATOR) | — |
> **Labels split across the engines**, and each tool's description says which way. Every label
> _read_ needs whatsapp-web.js — Baileys exposes no label query at all. Editing a label (upsert,
@@ -279,8 +280,8 @@ Guidelines:
`WebhookResponseDto.fromEntity`, `SessionResponseDto.fromEntity`). Returning a raw entity
can leak fields the REST API deliberately strips.
- Mark writes with `tier: 'write'` and the appropriate `requiredRole`. Give a read the same
- `requiredRole` as the REST route it mirrors: the webhook and automation-rule reads and
- `GroupGetInviteCode` sit at OPERATOR because their REST routes do.
+ `requiredRole` as the REST route it mirrors: the webhook and automation-rule reads,
+ `GroupGetInviteCode` and `ContactCheckNumber` sit at OPERATOR because their REST routes do.
- Use `sessionScoped: true` and a non-empty `sessionId` field for any per-session tool so
the scope check applies.
- A snapshot test (`tool-registry.spec.ts`) locks the public tool-name set; update it
diff --git a/src/core/agent-tools/tools/contact.tools.spec.ts b/src/core/agent-tools/tools/contact.tools.spec.ts
index 01a1c3810..6cc9a1ab5 100644
--- a/src/core/agent-tools/tools/contact.tools.spec.ts
+++ b/src/core/agent-tools/tools/contact.tools.spec.ts
@@ -1,8 +1,10 @@
+import { ForbiddenException } from '@nestjs/common';
import { invokeTool } from '../tool-invoker';
import { contactTools } from './contact.tools';
import type { AnyToolDescriptor } from '../tool-descriptor';
import type { ContactService } from '../../../modules/contact/contact.service';
import type { AuthService } from '../../../modules/auth/auth.service';
+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';
// Covers every contactTools execute() handler via the real invokeTool path (auth → zod → handler).
// agent-tools.module.ts is pure Nest wiring, stays at 0% coverage, and is intentionally not a target.
@@ -63,6 +65,23 @@ describe('contactTools', () => {
expect(out).toEqual({ number: '628123', exists: false, whatsappId: null });
});
+ it('ContactCheckNumber requires OPERATOR: a below-role key is refused before the lookup runs', async () => {
+ const getNumberId = jest.fn().mockResolvedValue('[email protected]');
+ const tool = makeTools({ getNumberId } as unknown as ContactService).get('ContactCheckNumber')!;
+ expect(tool.requiredRole).toBe(ApiKeyRole.OPERATOR);
+
+ const auth = makeAuth();
+ (auth.hasPermission as jest.Mock).mockReturnValue(false);
+ await expect(
+ invokeTool(tool, { sessionId: 's1', number: '628123' }, 'key', auth as unknown as AuthService),
+ ).rejects.toBeInstanceOf(ForbiddenException);
+ expect(getNumberId).not.toHaveBeenCalled();
+ });
+
+ it.each(['ContactResolvePhone', 'ContactGetProfilePicture'])('%s stays open to any valid key', name => {
+ expect(makeTools({} as ContactService).get(name)!.requiredRole).toBeUndefined();
+ });
+
it('ContactResolvePhone delegates to resolveContactPhone', async () => {
const resolveContactPhone = jest.fn().mockResolvedValue('628123');
const out = await run(makeTools({ resolveContactPhone } as unknown as ContactService).get('ContactResolvePhone')!, {
diff --git a/src/core/agent-tools/tools/contact.tools.ts b/src/core/agent-tools/tools/contact.tools.ts
index e06d64408..36ae4a334 100644
--- a/src/core/agent-tools/tools/contact.tools.ts
+++ b/src/core/agent-tools/tools/contact.tools.ts
@@ -33,8 +33,9 @@ export function contactTools(contact: ContactService): AnyToolDescriptor[] {
defineTool({
name: 'ContactCheckNumber',
description:
- 'Check whether a phone number is registered on WhatsApp. Returns exists flag and the WhatsApp JID if found.',
+ 'Check whether a phone number is registered on WhatsApp. Returns exists flag and the WhatsApp JID if found. Requires OPERATOR role.',
tier: 'read',
+ requiredRole: ApiKeyRole.OPERATOR,
sessionScoped: true,
inputSchema: z.object({
sessionId,
diff --git a/src/modules/auth/role-coverage.spec.ts b/src/modules/auth/role-coverage.spec.ts
index 5d0e96587..b8a360037 100644
--- a/src/modules/auth/role-coverage.spec.ts
+++ b/src/modules/auth/role-coverage.spec.ts
@@ -4,6 +4,7 @@ import { ApiKeyRole } from './entities/api-key.entity';
import { IntegrationInstanceController } from '../integration/integration-instance.controller';
import { RedriveController } from '../integration/redrive.controller';
import { GroupController } from '../group/group.controller';
+import { ContactController } from '../contact/contact.controller';
// The dashboard's client-side role (seeded from localStorage) is cosmetic UX only — the ACTUAL
// authorization boundary is the backend @RequireRole guard. These assertions lock that the sensitive
@@ -28,3 +29,22 @@ describe('group invite-code role coverage (the code is a capability, not read da
expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, GroupController.prototype[method])).toBe(ApiKeyRole.OPERATOR);
});
});
+
+// A number-existence check is an outbound WhatsApp query about a third party, and bulk checks put the
+// linked account's standing at risk, so it sits at OPERATOR (the MCP ContactCheckNumber tool too).
+// The profile-picture and phone-resolution reads stay open to any key: the dashboard loads avatars
+// with a VIEWER key.
+describe('contact lookup role coverage', () => {
+ it('ContactController.checkNumber requires the OPERATOR role', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, ContactController.prototype.checkNumber)).toBe(ApiKeyRole.OPERATOR);
+ });
+
+ it.each(['getProfilePictures', 'getProfilePicture', 'resolvePhone'] as const)(
+ 'ContactController.%s stays open to any valid key',
+ method => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata, not invoking
+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, ContactController.prototype[method])).toBeUndefined();
+ },
+ );
+});
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 34b9ab9d5..8b358aeb2 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -117,14 +117,17 @@ export class ContactController {
return this.contactService.getContactById(sessionId, contactId);
}
+ // OPERATOR, unlike the other reads here: each call is an outbound WhatsApp query about a third
+ // party, and bulk number checks put the linked account's standing at risk.
@Get('check/:number')
+ @RequireRole(ApiKeyRole.OPERATOR)
@ApiOperation({
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 send endpoints return 201 on accepting a message ' +
'even for numbers that are not on WhatsApp, so this is the only way to confirm a new number is ' +
- 'reachable before you send to it.',
+ 'reachable before you send to it. Requires an OPERATOR key.',
})
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiParam({ name: 'number', description: 'Phone number to check (e.g., 628123456789)' })
@@ -140,6 +143,7 @@ export class ContactController {
'would be a claim about the number rather than about the query, and this route exists to be ' +
'trusted before a send.',
})
+ @ApiResponse({ status: 403, description: 'API key role below OPERATOR' })
@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
async checkNumber(@Param('sessionId') sessionId: string, @Param('number') number: string) {
// The engine returns the canonical chat id in its native format; we don't build the JID here