Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): scope the pairing refusal to whatsapp-web.js

Yudhi Armyndharise6904c7ec254
diff --git a/src/modules/session/session-pairing-code.spec.ts b/src/modules/session/session-pairing-code.spec.ts
index 4173dbc73..92efaa348 100644
--- a/src/modules/session/session-pairing-code.spec.ts
+++ b/src/modules/session/session-pairing-code.spec.ts
@@ -1,22 +1,28 @@
import { ConflictException } from '@nestjs/common';
-import { Not } from 'typeorm';
+import { IsNull, Not } from 'typeorm';
import { SessionService } from './session.service';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { Session, SessionStatus } from './entities/session.entity';
const ID = '11111111-1111-4111-8111-111111111111';
-const OTHER_PHONE = '628111000111';
-function fixture(holderExists: boolean, ownPhone: string | null = null) {
- const row = { id: ID, name: 'pairing', status: SessionStatus.QR_READY, phone: ownPhone, config: {} } as Session;
+function fixture(options: { others: Array<string | null>; own?: string | null; engine?: string }) {
+ const row = {
+ id: ID,
+ name: 'pairing',
+ status: SessionStatus.QR_READY,
+ phone: options.own ?? null,
+ config: {},
+ } as Session;
const repository = {
findOne: jest.fn().mockResolvedValue(row),
- exists: jest.fn().mockResolvedValue(holderExists),
+ find: jest.fn().mockResolvedValue(options.others.filter(phone => phone !== null).map(phone => ({ phone }))),
};
const state = { attachTo: <T>(value: T): T => value };
const engine = { requestPairingCode: jest.fn().mockResolvedValue('ABCD1234') };
const registry = new EngineRegistry();
registry.set(ID, engine as never);
+ const config = { get: jest.fn((key: string) => (key === 'engine.type' ? options.engine : undefined)) };
const service = new SessionService(
repository as never,
{} as never,
@@ -29,28 +35,76 @@ function fixture(holderExists: boolean, ownPhone: string | null = null) {
{} as never,
{} as never,
{} as never,
+ config as never,
);
return { service, repository, engine };
}
describe('SessionService.requestPairingCode', () => {
- it('refuses a number another session of the gateway is linked with, without asking WhatsApp', async () => {
- const { service, repository, engine } = fixture(true);
+ it('refuses a number another session stores as its phone on whatsapp-web.js, without asking WhatsApp', async () => {
+ const { service, repository, engine } = fixture({ others: ['628111000111'], engine: 'whatsapp-web.js' });
- await expect(service.requestPairingCode(ID, OTHER_PHONE)).rejects.toBeInstanceOf(ConflictException);
+ await expect(service.requestPairingCode(ID, '628111000111')).rejects.toBeInstanceOf(ConflictException);
+
+ expect(repository.find).toHaveBeenCalledWith({
+ where: { id: Not(ID), phone: Not(IsNull()) },
+ select: { phone: true },
+ });
+ expect(engine.requestPairingCode).not.toHaveBeenCalled();
+ });
+
+ it('defaults to whatsapp-web.js when the engine type is not configured', async () => {
+ const { service, engine } = fixture({ others: ['628111000111'] });
+
+ await expect(service.requestPairingCode(ID, '628111000111')).rejects.toBeInstanceOf(ConflictException);
+
+ expect(engine.requestPairingCode).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['Brazil, typed without the ninth digit', '5511987654321', '551187654321'],
+ ['Brazil, typed with the ninth digit', '551187654321', '5511987654321'],
+ ['Mexico, typed without the 1', '5215512345678', '525512345678'],
+ ['Mexico, typed with the 1', '525512345678', '5215512345678'],
+ ['Argentina, typed without the 9', '5491123456789', '541123456789'],
+ ['Argentina, typed with the 9', '541123456789', '5491123456789'],
+ ])('refuses another spelling of the same number: %s', async (_family, stored, typed) => {
+ const { service, engine } = fixture({ others: [stored], engine: 'whatsapp-web.js' });
+
+ await expect(service.requestPairingCode(ID, typed)).rejects.toBeInstanceOf(ConflictException);
- expect(repository.exists).toHaveBeenCalledWith({ where: { phone: OTHER_PHONE, id: Not(ID) } });
expect(engine.requestPairingCode).not.toHaveBeenCalled();
});
- it('asks for a code for a number no other session holds, including the session own number', async () => {
- const { service, engine } = fixture(false, OTHER_PHONE);
+ it('asks for a code for a number no other session stores, including the session own number', async () => {
+ const { service, engine } = fixture({
+ others: ['628222000222', null],
+ own: '628111000111',
+ engine: 'whatsapp-web.js',
+ });
- await expect(service.requestPairingCode(ID, OTHER_PHONE)).resolves.toEqual({
+ await expect(service.requestPairingCode(ID, '628111000111')).resolves.toEqual({
pairingCode: 'ABCD1234',
status: SessionStatus.QR_READY,
});
- expect(engine.requestPairingCode).toHaveBeenCalledWith(OTHER_PHONE);
+ expect(engine.requestPairingCode).toHaveBeenCalledWith('628111000111');
+ });
+
+ it('does not treat a different number with a similar prefix as the same', async () => {
+ const { service, engine } = fixture({ others: ['5511987654321'], engine: 'whatsapp-web.js' });
+
+ await service.requestPairingCode(ID, '5511987654322');
+
+ expect(engine.requestPairingCode).toHaveBeenCalledWith('5511987654322');
+ });
+
+ it('leaves Baileys alone: its sessions are companion devices and may share a number', async () => {
+ const { service, repository, engine } = fixture({ others: ['628111000111'], engine: 'baileys' });
+
+ await expect(service.requestPairingCode(ID, '628111000111')).resolves.toMatchObject({ pairingCode: 'ABCD1234' });
+
+ expect(repository.find).not.toHaveBeenCalled();
+ expect(engine.requestPairingCode).toHaveBeenCalledWith('628111000111');
});
});
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index e78dc8c9e..66c3f6c75 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -516,10 +516,11 @@ export class SessionController {
'On the whatsapp-web.js engine, only request a code for a number you are prepared to re-link. A request ' +
'for a number that already has a linked session has been observed to end with WhatsApp revoking that ' +
'device: the linked session logs out, its credentials are deleted and it falls back to `qr_ready`. ' +
- 'A number that is the stored phone of another session of this gateway, compared digit for digit, is refused ' +
- 'with `409` and WhatsApp is not asked; the gateway cannot see a link made on another gateway or only on ' +
- 'the phone, nor another spelling of the same number. ' +
- 'Baileys was not affected in the same tests. Link by QR when a session of that number must stay up.',
+ 'On that engine a number that is the stored phone of another session of this gateway (the Brazilian, ' +
+ 'Mexican and Argentine mobile spellings of one number count as the same) is refused with `409` and WhatsApp ' +
+ 'is not asked; the gateway cannot see a link made on another gateway or only on the phone. ' +
+ 'Baileys was not affected in the same tests and accepts the request: its sessions are companion devices ' +
+ 'and may share a number. Link by QR when a session of that number must stay up.',
})
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiResponse({ status: 201, description: 'Pairing code generated', type: PairingCodeResponseDto })
@@ -529,8 +530,8 @@ export class SessionController {
status: 409,
description:
PAIRING_NOT_READY_409 +
- ' Also answered, with nothing sent to WhatsApp, when the requested number is the stored phone of another ' +
- 'session of this gateway: log that session out or delete it first.',
+ ' On whatsapp-web.js also answered, with nothing sent to WhatsApp, when the requested number is the stored ' +
+ 'phone of another session of this gateway: log that session out or delete it first.',
})
@ApiResponse({ status: 503, description: PAIRING_TRANSPORT_503 })
async requestPairingCode(
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 379179ffb..e769a94da 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -63,6 +63,7 @@ import { resolveJidCandidates } from '../../engine/identity/jid-candidates';
import { chatKind } from '../../engine/identity/wa-id';
import { Message, MessageDirection } from '../message/entities/message.entity';
import { ServerShuttingDownException, SessionStoppedException } from './session-engine-controls';
+import { phoneKey } from './message-mutation-guard';
// Type-only: the module binds this class to PLUGIN_SESSION_PORT with a `useExisting` alias, which
// TypeScript does not check, so `implements` is what keeps the two in step.
import type { PluginSessionPort } from '../../core/plugins/plugin-host-ports';
@@ -1342,7 +1343,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// On whatsapp-web.js a code requested for a number that is already linked can make WhatsApp revoke that
// device. The number is the caller's to choose, so a session this key may not touch could be logged out
// through this one; a number another session holds is refused. The session's own number is its to re-link.
- if (await this.sessionRepository.exists({ where: { phone: phoneNumber, id: Not(id) } })) {
+ // Baileys adds a companion device and showed no such effect, so two of its sessions may share a number.
+ if (this.pairingMayRevoke() && (await this.otherSessionHoldsNumber(id, phoneNumber))) {
throw new ConflictException(
'That number is linked to another session. Log that session out or delete it before pairing this one.',
);
@@ -1352,6 +1354,24 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return { pairingCode, status: session.status };
}
+ /** Whether the engine in use is whatsapp-web.js, where a pairing request can revoke a linked device. */
+ private pairingMayRevoke(): boolean {
+ return (this.configService?.get<string>('engine.type') ?? 'whatsapp-web.js') === 'whatsapp-web.js';
+ }
+
+ /**
+ * Whether another session stores this number as its phone, whichever way the country writes its mobile
+ * marker digit (the spellings the stored phone and the typed number can differ by).
+ */
+ private async otherSessionHoldsNumber(id: string, phoneNumber: string): Promise<boolean> {
+ const key = phoneKey(phoneNumber);
+ const others = await this.sessionRepository.find({
+ where: { id: Not(id), phone: Not(IsNull()) },
+ select: { phone: true },
+ });
+ return others.some(other => other.phone !== null && phoneKey(other.phone) === key);
+ }
+
getEngine(id: string): IWhatsAppEngine | undefined {
return this.engines.get(id);
}