Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

24.2 KB
Raw Blame
import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
import { ContactService } from './contact.service';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
import { WwebjsContacts } from '../../engine/adapters/wwebjs-contacts';
import type { WwebjsEngineHost } from '../../engine/adapters/wwebjs-host';

describe('ContactService', () => {
  const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
    const engines = new EngineRegistry();
    if (engine) engines.set('s1', engine as IWhatsAppEngine);
    return new ContactService(engines);
  };

  it('throws 400 when the session is not started', () => {
    expect(() => makeService(undefined).getContacts('s1')).toThrow(BadRequestException);
  });

  it('getBlockedContacts delegates to the engine and returns the bare id list', async () => {
    const getBlockedContacts = jest.fn().mockResolvedValue(['[email protected]']);
    await expect(makeService({ getBlockedContacts }).getBlockedContacts('s1')).resolves.toEqual(['[email protected]']);
    expect(getBlockedContacts).toHaveBeenCalledTimes(1);
  });

  it('getBlockedContacts throws 400 when the session is not started', () => {
    expect(() => makeService(undefined).getBlockedContacts('s1')).toThrow(BadRequestException);
  });

  it('listContacts returns the whole set, unwindowed', async () => {
    const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));
    const getContacts = jest.fn().mockResolvedValue(big);
    await expect(makeService({ getContacts }).listContacts('s1')).resolves.toHaveLength(1500);
    expect(() => makeService(undefined).listContacts('s1')).toThrow(BadRequestException);
  });

  it('caps an unbounded contacts list at the default limit (1000)', async () => {
    const big = Array.from({ length: 1500 }, (_, i) => ({ id: `${i}@c.us` }));
    const getContacts = jest.fn().mockResolvedValue(big);
    await expect(makeService({ getContacts }).getContacts('s1')).resolves.toHaveLength(1000);
  });

  it('applies limit/offset to the contacts list', async () => {
    const big = Array.from({ length: 50 }, (_, i) => ({ id: `${i}@c.us` }));
    const getContacts = jest.fn().mockResolvedValue(big);
    const page = (await makeService({ getContacts }).getContacts('s1', { limit: 5, offset: 10 })) as { id: string }[];
    expect(page).toHaveLength(5);
    expect(page[0].id).toBe('[email protected]');
  });

  it('maps a missing contact to 404', async () => {
    const svc = makeService({ getContactById: jest.fn().mockResolvedValue(null) });
    await expect(svc.getContactById('s1', 'c404')).rejects.toBeInstanceOf(NotFoundException);
  });

  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');
  });

  it('delegates resolveContactPhone to the engine', async () => {
    const resolveContactPhone = jest.fn().mockResolvedValue('628123456789');
    await expect(makeService({ resolveContactPhone }).resolveContactPhone('s1', '123@lid')).resolves.toBe(
      '628123456789',
    );
    expect(resolveContactPhone).toHaveBeenCalledWith('123@lid');
  });

  it('batch-resolves profile pictures, nulling per-id failures without aborting', async () => {
    const getProfilePicture = jest
      .fn()
      .mockResolvedValueOnce('https://pps/1.jpg')
      .mockRejectedValueOnce(new Error('no picture'))
      .mockResolvedValueOnce('https://pps/3.jpg');
    const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ['[email protected]', '[email protected]', '[email protected]']);
    expect(out).toEqual({ '[email protected]': 'https://pps/1.jpg', '[email protected]': null, '[email protected]': 'https://pps/3.jpg' });
  });

  // Not ready is a fact about the session, not about one avatar: a 200 with every picture null would
  // be cached by the dashboard as "nobody has a picture" for the whole stale window.
  it('fails the whole batch with 409 when the engine is not ready, without starting further chunks', async () => {
    const getProfilePicture = jest.fn().mockRejectedValue(new EngineNotReadyError());
    const ids = Array.from({ length: 12 }, (_, i) => `${i}@c.us`);
    const batch = makeService({ getProfilePicture }).getProfilePictures('s1', ids);
    await expect(batch).rejects.toBeInstanceOf(EngineNotReadyError);
    await expect(batch).rejects.toMatchObject({ status: 409 });
    expect(getProfilePicture).toHaveBeenCalledTimes(5);
  });

  it('still nulls a single id whose lookup fails with a transport error', async () => {
    const getProfilePicture = jest
      .fn()
      .mockRejectedValueOnce(new EngineTransportError('query stalled'))
      .mockResolvedValueOnce('https://pps/2.jpg');
    const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ['[email protected]', '[email protected]']);
    expect(out).toEqual({ '[email protected]': null, '[email protected]': 'https://pps/2.jpg' });
  });

  it('ignores ids beyond the 50-id batch cap', async () => {
    const getProfilePicture = jest.fn().mockResolvedValue(null);
    const ids = Array.from({ length: 60 }, (_, i) => `${i}@c.us`);
    const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ids);
    expect(Object.keys(out)).toHaveLength(50);
    expect(getProfilePicture).toHaveBeenCalledTimes(50);
  });

  it('runs batch lookups at most 5 concurrently', async () => {
    let active = 0;
    let maxActive = 0;
    const getProfilePicture = jest.fn().mockImplementation(async () => {
      active += 1;
      maxActive = Math.max(maxActive, active);
      await new Promise(r => setImmediate(r));
      active -= 1;
      return null;
    });
    const ids = Array.from({ length: 12 }, (_, i) => `${i}@c.us`);
    await makeService({ getProfilePicture }).getProfilePictures('s1', ids);
    expect(maxActive).toBeLessThanOrEqual(5);
  });

  it('yields null (not a stalled batch) when an engine lookup hangs past the per-id deadline', async () => {
    const getProfilePicture = jest
      .fn()
      .mockResolvedValueOnce('https://pps/1.jpg')
      .mockImplementationOnce(() => new Promise(() => undefined)); // never settles
    jest.useFakeTimers();
    try {
      const out = makeService({ getProfilePicture }).getProfilePictures('s1', ['[email protected]', '[email protected]']);
      await jest.advanceTimersByTimeAsync(8000);
      await expect(out).resolves.toEqual({ '[email protected]': 'https://pps/1.jpg', '[email protected]': null });
    } finally {
      jest.useRealTimers();
    }
  });

  it.each(['resolve', 'reject'] as const)(
    'stops later avatar chunks after a timeout and handles a late %s',
    async outcome => {
      jest.useFakeTimers();
      let active = 0;
      let peak = 0;
      let calls = 0;
      const getProfilePicture = jest.fn().mockImplementation(() => {
        active += 1;
        peak = Math.max(peak, active);
        const call = ++calls;
        if (call > 5) return Promise.resolve(null).finally(() => active--);
        return new Promise<string | null>((resolve, reject) => {
          setTimeout(() => {
            if (outcome === 'reject' && call === 1) reject(new Error('lookup failed'));
            else resolve('https://pps/picture.jpg');
          }, 9000);
        }).finally(() => active--);
      });
      const ids = Array.from({ length: 6 }, (_, i) => String(628100000000 + i) + '@c.us');
      try {
        const result = makeService({ getProfilePicture }).getProfilePictures('s1', ids);
        await jest.advanceTimersByTimeAsync(8000);
        await expect(result).resolves.toEqual(Object.fromEntries(ids.slice(0, 5).map(id => [id, null])));
        expect(active).toBe(5);
        await jest.advanceTimersByTimeAsync(1000);
        expect(active).toBe(0);
        expect(getProfilePicture).toHaveBeenCalledTimes(5);
        expect(peak).toBeLessThanOrEqual(5);
        expect(jest.getTimerCount()).toBe(0);
      } finally {
        await jest.advanceTimersByTimeAsync(30000);
        jest.clearAllTimers();
        jest.useRealTimers();
      }
    },
  );

  it('preserves not-ready when other lookups in the chunk time out', async () => {
    jest.useFakeTimers();
    const getProfilePicture = jest
      .fn()
      .mockRejectedValueOnce(new EngineNotReadyError())
      .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(null), 9000)));
    try {
      const result = makeService({ getProfilePicture })
        .getProfilePictures(
          's1',
          Array.from({ length: 6 }, (_, i) => String(628100000000 + i) + '@c.us'),
        )
        .catch((error: unknown) => error);
      await jest.advanceTimersByTimeAsync(8000);
      expect(await result).toBeInstanceOf(EngineNotReadyError);
      expect(getProfilePicture).toHaveBeenCalledTimes(5);
      await jest.advanceTimersByTimeAsync(1000);
      expect(jest.getTimerCount()).toBe(0);
    } finally {
      await jest.advanceTimersByTimeAsync(30000);
      jest.clearAllTimers();
      jest.useRealTimers();
    }
  });

  describe('block/unblock reject ids that do not name a person', () => {
    // whatsapp-web.js's Contact.block()/unblock() return false for a group id (nothing blocked,
    // answered 200 "blocked"). Both engines share this 400 guard.
    it.each([
      ['blockContact', (svc: ContactService) => svc.blockContact('s1', '[email protected]')],
      ['unblockContact', (svc: ContactService) => svc.unblockContact('s1', '[email protected]')],
      ['blockContact (newsletter)', (svc: ContactService) => svc.blockContact('s1', '1200000000@newsletter')],
      ['blockContact (broadcast)', (svc: ContactService) => svc.blockContact('s1', '1200000000@broadcast')],
      ['blockContact (status)', (svc: ContactService) => svc.blockContact('s1', 'status@broadcast')],
      ['blockContact (free text)', (svc: ContactService) => svc.blockContact('s1', '[email protected]')],
    ])('%s refuses the id with a 400 before the engine is called', (_name, call) => {
      const blockContact = jest.fn();
      const unblockContact = jest.fn();
      const svc = makeService({ blockContact, unblockContact });
      expect(() => call(svc)).toThrow(BadRequestException);
      expect(blockContact).not.toHaveBeenCalled();
      expect(unblockContact).not.toHaveBeenCalled();
    });

    /**
     * A Meta-hosted id names the same account as its plain twin, so the write must reach the engine
     * rather than be refused. It is neutralized on the way there: whatsapp-web.js knows no `@hosted`
     * domain, so forwarding the suffix verbatim would fail inside the page instead of blocking anyone.
     */
    it('accepts a Meta-hosted id and hands the engine the neutral dialect', async () => {
      const blockContact = jest.fn().mockResolvedValue(undefined);
      const unblockContact = jest.fn().mockResolvedValue(undefined);
      const svc = makeService({ blockContact, unblockContact });

      await svc.blockContact('s1', '628123456789@hosted');
      await svc.unblockContact('s1', '[email protected]');

      expect(blockContact).toHaveBeenCalledWith('[email protected]');
      expect(unblockContact).toHaveBeenCalledWith('12345678901234567890@lid');
    });

    /**
     * Neutralizing covers the raw-protocol dialect too, which used to reach the engine verbatim.
     * That is a round trip, not a loss: the Baileys adapter hands the jid to `updateBlockStatus`,
     * which starts with `jidNormalizedUser` and turns `@c.us` straight back into `@s.whatsapp.net`.
     * whatsapp-web.js, which has no such dialect, gets the form it actually understands.
     */
    it('hands the engine the neutral dialect for a raw-protocol id', async () => {
      const blockContact = jest.fn().mockResolvedValue(undefined);
      const svc = makeService({ blockContact });

      await svc.blockContact('s1', '[email protected]');

      expect(blockContact).toHaveBeenCalledWith('[email protected]');
    });

    /**
     * A privacy-id contact has no phone number at all, and the blocklist READ answers those ids
     * verbatim (Baileys maps each blocked jid through toNeutralJid, which leaves an unresolved lid
     * as `<lid>@lid`; whatsapp-web.js returns the wid as-is). Refusing them here made the ids the
     * API itself hands out unusable for the matching write, so a privacy-id contact could be listed
     * as blocked and never unblocked. Blocking acts on the identity, not on an addressbook row, so
     * neither engine needs a phone here: Baileys passes the jid straight to updateBlockStatus, and
     * whatsapp-web.js only short-circuits (`return false`) for a group.
     */
    it.each([
      ['blockContact', (svc: ContactService) => svc.blockContact('s1', '159442138038327@lid')],
      ['unblockContact', (svc: ContactService) => svc.unblockContact('s1', '159442138038327@lid')],
    ])('%s forwards a privacy id (@lid) to the engine unchanged', async (_name, call) => {
      const blockContact = jest.fn().mockResolvedValue(undefined);
      const unblockContact = jest.fn().mockResolvedValue(undefined);
      await call(makeService({ blockContact, unblockContact }));
      const called = blockContact.mock.calls.length ? blockContact : unblockContact;
      expect(called).toHaveBeenCalledWith('159442138038327@lid');
    });

    it('accepts every id shape the blocklist read can return', async () => {
      // The read half answers ids only, so whatever it lists must be feedable back to unblock.
      const getBlockedContacts = jest.fn().mockResolvedValue(['[email protected]', '159442138038327@lid']);
      const unblockContact = jest.fn().mockResolvedValue(undefined);
      const svc = makeService({ getBlockedContacts, unblockContact });
      for (const id of await svc.getBlockedContacts('s1')) {
        await svc.unblockContact('s1', id);
      }
      expect(unblockContact).toHaveBeenCalledWith('[email protected]');
      expect(unblockContact).toHaveBeenCalledWith('159442138038327@lid');
    });

    it('qualifies a bare number and forwards it to the engine as a @c.us id', async () => {
      const blockContact = jest.fn().mockResolvedValue(undefined);
      await makeService({ blockContact }).blockContact('s1', '628123');
      expect(blockContact).toHaveBeenCalledWith('[email protected]');
    });

    it('still allows a normal phone-based contact id through to the engine', async () => {
      const unblockContact = jest.fn().mockResolvedValue(undefined);
      await makeService({ unblockContact }).unblockContact('s1', '[email protected]');
      expect(unblockContact).toHaveBeenCalledWith('[email protected]');
    });
  });

  describe('addressbook writes reject a privacy id', () => {
    // The lid's digits are NOT a phone number (see the note on
    // MessageService.resolveJidCandidates). whatsapp-web.js takes a bare NUMBER for the
    // addressbook, so an unguarded @lid would be stored as if it were a real phone —
    // silently creating an entry for a number that does not exist.
    it.each([
      ['upsertContact', (svc: ContactService) => svc.upsertContact('s1', '159442138038327@lid', 'Ada')],
      ['deleteContact', (svc: ContactService) => svc.deleteContact('s1', '159442138038327@lid')],
    ])('%s refuses an @lid contact id with a 400', (_name, call) => {
      const upsertContact = jest.fn();
      const deleteContact = jest.fn();
      const svc = makeService({ upsertContact, deleteContact });
      expect(() => call(svc)).toThrow(BadRequestException);
      expect(upsertContact).not.toHaveBeenCalled();
      expect(deleteContact).not.toHaveBeenCalled();
    });

    it('still allows a normal phone-based contact id through to the engine', async () => {
      const upsertContact = jest.fn().mockResolvedValue(undefined);
      await makeService({ upsertContact }).upsertContact('s1', '[email protected]', 'Ada', 'Lovelace');
      expect(upsertContact).toHaveBeenCalledWith('[email protected]', 'Ada', 'Lovelace');
    });

    // UpsertContactDto lets a JSON null through (@IsOptional skips it). A default parameter ignores null, so
    // the whatsapp-web.js delegate's `lastName = ''` never applied and the page-side save received null.
    it.each([undefined, null])('hands the engine no last name for lastName %p', async lastName => {
      const upsertContact = jest.fn().mockResolvedValue(undefined);
      await makeService({ upsertContact }).upsertContact('s1', '[email protected]', 'Ada', lastName as string | undefined);
      expect(upsertContact).toHaveBeenCalledWith('[email protected]', 'Ada', undefined);
    });

    it('reaches the whatsapp-web.js save with an empty last name when the body sent null', async () => {
      const save = jest.fn().mockResolvedValue(undefined);
      const host = {
        ensureReady: jest.fn(),
        getClient: () => ({ saveOrEditAddressbookContact: save }),
        isPageTransportError: () => false,
        reportIfPageTransportError: jest.fn(),
        logger: { debug: jest.fn() },
      } as unknown as WwebjsEngineHost;
      const contacts = new WwebjsContacts(host);
      const svc = makeService({
        upsertContact: (id: string, first: string, last?: string) => contacts.upsertContact(id, first, last),
      });
      await svc.upsertContact('s1', '[email protected]', 'Ada', null as unknown as string);
      expect(save).toHaveBeenCalledWith('628123', 'Ada', '');
    });

    // Same hazard as the lid, different ids: a group/newsletter/broadcast id also carries digits
    // that would be stored as a phone number for a contact that does not exist.
    it.each(['[email protected]', '120363000000000000@newsletter', 'status@broadcast'])(
      'refuses the non-person id %s with a 400',
      id => {
        const upsertContact = jest.fn();
        const svc = makeService({ upsertContact });
        expect(() => svc.upsertContact('s1', id, 'Ada')).toThrow(BadRequestException);
        expect(upsertContact).not.toHaveBeenCalled();
      },
    );

    /**
     * The guard checked the JID DOMAIN only: `parseWaId(id).kind === 'user'` holds for anything
     * ending in `@c.us` / `@s.whatsapp.net` whatever its user-part. So free text reached the engine
     * and the caller was told the contact was saved — while the three sibling surfaces on the same
     * shapes (group participants, channel admin, message mentions) reject exactly these strings
     * through isAddressableParticipant, which also requires the user-part to be numeric.
     */
    it.each([
      ['free text', 'NOT A [email protected]'],
      ['letters', '[email protected]'],
      ['an empty user-part', '@c.us'],
      ['the engine dialect with free text', '[email protected]'],
    ])('refuses %s without reaching the engine', (_label, id) => {
      const upsertContact = jest.fn();
      const deleteContact = jest.fn();
      const svc = makeService({ upsertContact, deleteContact });

      expect(() => svc.upsertContact('s1', id, 'Ada')).toThrow(BadRequestException);
      expect(() => svc.deleteContact('s1', id)).toThrow(BadRequestException);
      expect(upsertContact).not.toHaveBeenCalled();
      expect(deleteContact).not.toHaveBeenCalled();
    });

    // Negative twin: the ids this route exists to serve must still pass.
    it.each([
      ['a phone jid', '[email protected]'],
      ['the engine dialect', '[email protected]'],
      ['a bare number', '628123456789'],
    ])('still accepts %s', async (_label, id) => {
      const upsertContact = jest.fn().mockResolvedValue(undefined);
      await makeService({ upsertContact }).upsertContact('s1', id, 'Ada');
      expect(upsertContact).toHaveBeenCalled();
    });
  });

  describe('one engine read per walk', () => {
    const contactsOf = (prefix: string, count: number) =>
      Array.from({ length: count }, (_, i) => ({ id: `${prefix}${i}@c.us` }));
    const walk = async (svc: ContactService, sessionId = 's1') => {
      const ids: string[] = [];
      for (let offset = 0; ; offset += 1000) {
        const page = (await svc.getContacts(sessionId, { limit: 1000, offset })) as { id: string }[];
        ids.push(...page.map(c => c.id));
        if (page.length < 1000) return ids;
      }
    };

    it('reads the engine once for every page of one walk, and afresh for the next walk', async () => {
      const getContacts = jest.fn().mockResolvedValue(contactsOf('62', 5000));
      const svc = makeService({ getContacts });
      expect(new Set(await walk(svc)).size).toBe(5000);
      expect(getContacts).toHaveBeenCalledTimes(1);
      await walk(svc);
      expect(getContacts).toHaveBeenCalledTimes(2);
    });

    it("never serves one session's listing to another session", async () => {
      const engines = new EngineRegistry();
      const first = { getContacts: jest.fn().mockResolvedValue(contactsOf('62', 5000)) };
      const second = { getContacts: jest.fn().mockResolvedValue(contactsOf('63', 1500)) };
      engines.set('s1', first as unknown as IWhatsAppEngine);
      engines.set('s2', second as unknown as IWhatsAppEngine);
      const svc = new ContactService(engines);
      await svc.getContacts('s1', { offset: 0 });
      const page = (await svc.getContacts('s2', { offset: 1000 })) as { id: string }[];
      expect(second.getContacts).toHaveBeenCalledTimes(1);
      expect(page).toHaveLength(500);
      expect(page.every(c => c.id.startsWith('63'))).toBe(true);
    });

    it('reads afresh once the engine it came from was retired, and answers 400 while none runs', async () => {
      const engines = new EngineRegistry();
      const getContacts = jest.fn().mockResolvedValue(contactsOf('62', 1500));
      const engine = { getContacts } as unknown as IWhatsAppEngine;
      engines.set('s1', engine);
      const svc = new ContactService(engines);
      await svc.getContacts('s1', { offset: 0 });
      engines.delete('s1');
      expect(() => svc.getContacts('s1', { offset: 1000 })).toThrow(BadRequestException);
      // The same engine object registered again: only the retire notification can drop the listing.
      engines.set('s1', engine);
      await svc.getContacts('s1', { offset: 1000 });
      expect(getContacts).toHaveBeenCalledTimes(2);
    });

    it.each([
      ['upsertContact', (svc: ContactService) => svc.upsertContact('s1', '[email protected]', 'Ada')],
      ['deleteContact', (svc: ContactService) => svc.deleteContact('s1', '[email protected]')],
      ['blockContact', (svc: ContactService) => svc.blockContact('s1', '[email protected]')],
      ['unblockContact', (svc: ContactService) => svc.unblockContact('s1', '[email protected]')],
    ])('a %s call makes the next page read afresh, even when it fails', async (method, write) => {
      const getContacts = jest.fn().mockResolvedValue(contactsOf('62', 5000));
      const engine: Partial<Record<string, jest.Mock>> = { getContacts, [method]: jest.fn().mockResolvedValue(true) };
      const svc = makeService(engine as Partial<IWhatsAppEngine>);
      await svc.getContacts('s1', { offset: 0 });
      await write(svc);
      await svc.getContacts('s1', { offset: 1000 });
      expect(getContacts).toHaveBeenCalledTimes(2);

      // A timed-out write may still have been applied, so a failure drops the listing too.
      engine[method] = jest.fn().mockRejectedValue(new Error('timed out'));
      await expect(write(svc)).rejects.toThrow('timed out');
      await svc.getContacts('s1', { offset: 2000 });
      expect(getContacts).toHaveBeenCalledTimes(3);
    });
  });

  describe('resolveContactPhone error contract', () => {
    it('propagates the 400 when the session is not started (getEngine is outside the swallow)', async () => {
      const svc = makeService(undefined);
      await expect(svc.resolveContactPhone('s1', '123@lid')).rejects.toThrow('Session is not started');
    });

    it('propagates an HttpException from the engine (409 not-ready keeps its retry guidance)', async () => {
      const svc = makeService({
        resolveContactPhone: jest.fn().mockRejectedValue(new ConflictException('Session is not connected')),
      });
      await expect(svc.resolveContactPhone('s1', '123@lid')).rejects.toBeInstanceOf(ConflictException);
    });

    it('returns null for a non-HTTP lookup failure (dead page), preserving the route contract', async () => {
      const svc = makeService({
        resolveContactPhone: jest.fn().mockRejectedValue(new Error('Protocol error: Target closed')),
      });
      await expect(svc.resolveContactPhone('s1', '123@lid')).resolves.toBeNull();
    });
  });
});