Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

19.3 KB
Raw Blame
import { generateIdempotencyKey, generateDeliveryId } from './idempotency.util';

describe('Idempotency Utils', () => {
  describe('generateIdempotencyKey', () => {
    it('should generate a session-scoped key for message.received', () => {
      const key = generateIdempotencyKey('message.received', { messageId: 'ABC123', sessionId: 'A' });
      expect(key).toBe('msg_A_ABC123');
    });

    it('keys message.receipt by recipient and status, so two members reading the same message stay distinct', () => {
      const read = (participant: string): string =>
        generateIdempotencyKey('message.receipt', { id: 'ABC123', participant, status: 'read', sessionId: 'A' });
      expect(read('[email protected]')).toBe('[email protected]_read');
      expect(read('[email protected]')).not.toBe(read('[email protected]'));
      expect(
        generateIdempotencyKey('message.receipt', {
          id: 'ABC123',
          participant: '[email protected]',
          status: 'delivered',
          sessionId: 'A',
        }),
      ).not.toBe(read('[email protected]'));
    });

    it('falls back to the legacy `ack` integer for message.ack when no `status` is present', () => {
      const key = generateIdempotencyKey('message.ack', { messageId: 'ABC123', ack: 3, sessionId: 'A' });
      expect(key).toBe('ack_A_ABC123_3');
    });

    it('should use the IncomingMessage `id` field for message.received (the real dispatch shape)', () => {
      // session.service dispatches the IncomingMessage object, which carries `id`, not `messageId`.
      const key = generateIdempotencyKey('message.received', { id: 'ABC123', sessionId: 'A' });
      expect(key).toBe('msg_A_ABC123');
    });

    it('should prefer `id` over a legacy `messageId` when both are present for message.received', () => {
      const key = generateIdempotencyKey('message.received', { id: 'REAL', messageId: 'LEGACY', sessionId: 'A' });
      expect(key).toBe('msg_A_REAL');
    });

    it('keys message.ack on the neutral `status` (the real dispatch shape), preferring it over `ack`', () => {
      const key = generateIdempotencyKey('message.ack', { id: 'ABC123', status: 'read', ack: 3, sessionId: 'A' });
      expect(key).toBe('ack_A_ABC123_read');
    });

    it('should use the `id` field for message.revoked (the real dispatch shape)', () => {
      const key = generateIdempotencyKey('message.revoked', { id: 'ABC123', sessionId: 'A' });
      expect(key).toBe('rev_A_ABC123');
    });

    it('gives the same waMessageId in different sessions DISTINCT keys', () => {
      const a = generateIdempotencyKey('message.ack', { id: 'X', status: 'delivered', sessionId: 'A' });
      const b = generateIdempotencyKey('message.ack', { id: 'X', status: 'delivered', sessionId: 'B' });
      expect(a).not.toBe(b);
    });

    it('should generate key for session.status', () => {
      const key = generateIdempotencyKey('session.status', {
        sessionId: 'sess_1',
        status: 'CONNECTED',
      });
      expect(key).toBe('sess_sess_1_CONNECTED');
    });

    it('salts session.status keys with the occurrence time so repeated transitions to the same status stay distinct', () => {
      const a = generateIdempotencyKey(
        'session.status',
        { sessionId: 'A', status: 'DISCONNECTED' },
        '2026-06-19T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'session.status',
        { sessionId: 'A', status: 'DISCONNECTED' },
        '2026-06-19T02:00:00.000Z',
      );
      expect(a).not.toBe(b);
    });

    it('salts session.authenticated keys so re-authentication (same phone, later time) is a distinct event', () => {
      const a = generateIdempotencyKey(
        'session.authenticated',
        { sessionId: 'A', phone: '628', pushName: 'Me' },
        '2026-06-19T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'session.authenticated',
        { sessionId: 'A', phone: '628', pushName: 'Me' },
        '2026-06-19T01:00:00.000Z',
      );
      expect(a).not.toBe(b);
    });

    it('salts session.disconnected keys so repeat disconnects with the same reason stay distinct', () => {
      const a = generateIdempotencyKey(
        'session.disconnected',
        { sessionId: 'A', reason: 'logged out' },
        '2026-06-19T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'session.disconnected',
        { sessionId: 'A', reason: 'logged out' },
        '2026-06-19T03:00:00.000Z',
      );
      expect(a).not.toBe(b);
    });

    // An account restricted, freed and restricted again for the same cause produces byte-identical
    // payloads. Without the salt the second restriction would be deduped away as a replay of the
    // first — and that second one is exactly the event an operator needs.
    it('salts session.restriction keys so a recurring restriction is not deduped away', () => {
      const payload = { sessionId: 'A', active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' };
      const a = generateIdempotencyKey('session.restriction', payload, '2026-08-03T00:00:00.000Z');
      const b = generateIdempotencyKey('session.restriction', payload, '2026-08-04T00:00:00.000Z');
      expect(a).not.toBe(b);
    });

    // The onset and the lift are two different events about one restriction; they must never collide
    // even when they land inside the same occurrence timestamp.
    it('distinguishes a restriction from its lift', () => {
      const at = '2026-08-03T00:00:00.000Z';
      const applied = generateIdempotencyKey(
        'session.restriction',
        { sessionId: 'A', active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' },
        at,
      );
      const lifted = generateIdempotencyKey(
        'session.restriction',
        { sessionId: 'A', active: false, kind: 'reachout_timelock', code: 'BIZ_QUALITY' },
        at,
      );
      expect(applied).not.toBe(lifted);
    });

    it('scopes session.restriction keys per session so two accounts do not dedupe each other', () => {
      const at = '2026-08-03T00:00:00.000Z';
      const payload = { active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' };
      const a = generateIdempotencyKey('session.restriction', { ...payload, sessionId: 'A' }, at);
      const b = generateIdempotencyKey('session.restriction', { ...payload, sessionId: 'B' }, at);
      expect(a).not.toBe(b);
    });

    it('is retry-stable: the same lifecycle occurrence regenerates the same key', () => {
      const at = '2026-06-19T00:00:00.000Z';
      const a = generateIdempotencyKey('session.disconnected', { sessionId: 'A', reason: 'logged out' }, at);
      const b = generateIdempotencyKey('session.disconnected', { sessionId: 'A', reason: 'logged out' }, at);
      expect(a).toBe(b);
    });

    // Once the backoff reaches its cap, a later outage that loops to the same attempt count dispatches
    // a byte-identical payload; the second alert is news and must not dedupe onto the first.
    it('salts session.reconnect_loop keys per occurrence and keeps them retry-stable', () => {
      const payload = { sessionId: 'A', attempts: 10, nextDelayMs: 300_000 };
      const first = generateIdempotencyKey('session.reconnect_loop', payload, '2026-09-01T00:00:00.000Z');
      const later = generateIdempotencyKey('session.reconnect_loop', payload, '2026-09-01T06:00:00.000Z');
      expect(first).not.toBe(later);
      expect(generateIdempotencyKey('session.reconnect_loop', { ...payload }, '2026-09-01T00:00:00.000Z')).toBe(first);
    });

    it('does not salt message-event keys with the occurrence time (content-based dedup preserved)', () => {
      const a = generateIdempotencyKey(
        'message.ack',
        { id: 'X', status: 'read', sessionId: 'A' },
        '2026-06-19T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'message.ack',
        { id: 'X', status: 'read', sessionId: 'A' },
        '2026-06-19T09:00:00.000Z',
      );
      expect(a).toBe(b);
      expect(a).toBe('ack_A_X_read');
    });

    it('salts message.reaction keys so a re-reaction (same sender/emoji, later time) is a distinct event', () => {
      // A reaction has no unique id and is a read-modify-write: the same sender can go 👍 → remove → 👍.
      // Keying on (sender, message, emoji) alone would collapse the re-reaction onto the earlier one.
      const a = generateIdempotencyKey(
        'message.reaction',
        { sessionId: 'A', messageId: 'MSG1', senderId: '[email protected]', reaction: '👍' },
        '2026-06-20T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'message.reaction',
        { sessionId: 'A', messageId: 'MSG1', senderId: '[email protected]', reaction: '👍' },
        '2026-06-20T00:05:00.000Z',
      );
      expect(a).not.toBe(b);
    });

    it('is retry-stable for message.reaction: the same occurrence regenerates the same key', () => {
      const at = '2026-06-20T00:00:00.000Z';
      const data = { sessionId: 'A', messageId: 'MSG1', senderId: '[email protected]', reaction: '👍' };
      expect(generateIdempotencyKey('message.reaction', data, at)).toBe(
        generateIdempotencyKey('message.reaction', data, at),
      );
    });

    it('gives two senders reacting to the same message DISTINCT message.reaction keys', () => {
      const at = '2026-06-20T00:00:00.000Z';
      const a = generateIdempotencyKey('message.reaction', { sessionId: 'A', messageId: 'M', senderId: 'S1' }, at);
      const b = generateIdempotencyKey('message.reaction', { sessionId: 'A', messageId: 'M', senderId: 'S2' }, at);
      expect(a).not.toBe(b);
    });

    it('salts message.edited keys so an edit (same message, later time) is a distinct event', () => {
      const a = generateIdempotencyKey(
        'message.edited',
        { sessionId: 'A', messageId: 'MSG1' },
        '2026-06-20T00:00:00.000Z',
      );
      const b = generateIdempotencyKey(
        'message.edited',
        { sessionId: 'A', messageId: 'MSG1' },
        '2026-06-20T00:05:00.000Z',
      );
      expect(a).not.toBe(b);
    });

    it('is retry-stable for message.edited: the same occurrence regenerates the same key', () => {
      const at = '2026-06-20T00:00:00.000Z';
      const data = { sessionId: 'A', messageId: 'MSG1' };
      expect(generateIdempotencyKey('message.edited', data, at)).toBe(
        generateIdempotencyKey('message.edited', data, at),
      );
    });

    it('keys group.join on the group + affected participants (the real participantIds payload)', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const key = generateIdempotencyKey(
        'group.join',
        { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 },
        at,
      );
      expect(key).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_join_2026-07-20T00:00:00\.000Z$/);
    });

    it('keys group.join_request like group.join — a reject-then-re-request must stay a distinct event', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };

      const key = generateIdempotencyKey('group.join_request', data, at);

      expect(key).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_join_request_2026-07-20T00:00:00\.000Z$/);
      // Occurrence salt: the same user asking again later is a new event, not a duplicate.
      expect(generateIdempotencyKey('group.join_request', data, '2026-07-20T01:00:00.000Z')).not.toBe(key);
      // Retry-stable: the same dispatch regenerates the same key.
      expect(generateIdempotencyKey('group.join_request', data, at)).toBe(key);
    });

    it('is retry-stable for group.join: the same occurrence regenerates the same key', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };
      expect(generateIdempotencyKey('group.join', data, at)).toBe(generateIdempotencyKey('group.join', data, at));
    });

    it('salts group.join keys so a leave-then-rejoin of the same user stays a distinct event', () => {
      const data = { groupId: '[email protected]', participantIds: ['[email protected]'], timestamp: 1782000000 };
      const a = generateIdempotencyKey('group.join', data, '2026-07-20T00:00:00.000Z');
      const b = generateIdempotencyKey('group.join', data, '2026-07-20T01:00:00.000Z');
      expect(a).not.toBe(b);
    });

    it('gives different participants distinct group.join keys for the same occurrence', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const a = generateIdempotencyKey('group.join', { groupId: '[email protected]', participantIds: ['[email protected]'] }, at);
      const b = generateIdempotencyKey('group.join', { groupId: '[email protected]', participantIds: ['[email protected]'] }, at);
      expect(a).not.toBe(b);
    });

    it('keys group.leave symmetrically to group.join (and distinct from it)', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { groupId: '[email protected]', participantIds: ['[email protected]'] };
      const join = generateIdempotencyKey('group.join', data, at);
      const leave = generateIdempotencyKey('group.leave', data, at);
      expect(leave).toMatch(/^grp_123@g\.us_[a-f0-9]{12}_leave_/);
      expect(leave).not.toBe(join);
    });

    it('keys group.update on WHAT changed, salted per occurrence', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { groupId: '[email protected]', changes: { subject: 'New name' }, timestamp: 1782000000 };
      const a = generateIdempotencyKey('group.update', data, at);
      expect(a).toMatch(/^grp_123@g\.us_update_[a-f0-9]{12}_2026-07-20T00:00:00\.000Z$/);
      // Retry of the same delivery stays stable...
      expect(generateIdempotencyKey('group.update', data, at)).toBe(a);
      // ...a later identical update is a distinct occurrence...
      expect(generateIdempotencyKey('group.update', data, '2026-07-20T00:05:00.000Z')).not.toBe(a);
      // ...and a different change differs even inside the same dispatch window.
      expect(generateIdempotencyKey('group.update', { groupId: '[email protected]', changes: { announce: true } }, at)).not.toBe(
        a,
      );
    });

    it('keys presence.update on WHAT changed, salted per occurrence', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { sessionId: 'A', chatId: '[email protected]', participants: [{ id: 'u1@lid', state: 'composing' }] };
      const a = generateIdempotencyKey('presence.update', data, at);
      expect(a).toMatch(/^pres_A_123@g\.us_[a-f0-9]{12}_2026-07-20T00:00:00\.000Z$/);
      expect(generateIdempotencyKey('presence.update', data, at)).toBe(a);
      expect(generateIdempotencyKey('presence.update', data, '2026-07-20T00:05:00.000Z')).not.toBe(a);
      // Two participants changing in the same millisecond are two events, not one.
      const other = { ...data, participants: [{ id: 'u2@lid', state: 'available' }] };
      expect(generateIdempotencyKey('presence.update', other, at)).not.toBe(a);
    });

    it('keys event.response on the session + RSVP id (unique per answer, no occurrence salt needed)', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { sessionId: 'A', eventMessageId: 'EVT1', responseMessageId: 'RSVP1', response: 'going' };
      const key = generateIdempotencyKey('event.response', data, at);
      expect(key).toBe('rsvp_A_RSVP1');
      expect(generateIdempotencyKey('event.response', data, '2026-07-20T01:00:00.000Z')).toBe(key);
      // A changed answer is a new RSVP with a new id, so it is never deduped against the first.
      const changed = { ...data, responseMessageId: 'RSVP2', response: 'not_going' };
      expect(generateIdempotencyKey('event.response', changed, at)).not.toBe(key);
      expect(generateIdempotencyKey('event.response', { ...data, sessionId: 'B' }, at)).not.toBe(key);
    });

    it('keys poll.vote on the session + poll + voter + vote time (distinct per change, stable across retries)', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { sessionId: 'A', pollMessageId: 'POLL1', voterId: 'V1', selectedOptions: ['Yes'], timestamp: 100 };
      const key = generateIdempotencyKey('poll.vote', data, at);
      // Without the millisecond stamp the whole second stands in for it.
      expect(key).toMatch(/^vote_A_POLL1_V1_100_[0-9a-f]{12}$/);
      expect(generateIdempotencyKey('poll.vote', data, '2026-07-20T01:00:00.000Z')).toBe(key);
      // An identical redelivery dedupes, a different selection in the same second does not.
      expect(generateIdempotencyKey('poll.vote', { ...data }, at)).toBe(key);
      expect(generateIdempotencyKey('poll.vote', { ...data, selectedOptions: ['Yes', 'No'] }, at)).not.toBe(key);
      expect(generateIdempotencyKey('poll.vote', { ...data, selectedOptions: [] }, at)).not.toBe(key);
      // Going back to an earlier selection later is a new change, never deduped against the first.
      expect(generateIdempotencyKey('poll.vote', { ...data, timestamp: 200 }, at)).not.toBe(key);
      // Two voters on the same poll in the same second are two events.
      expect(generateIdempotencyKey('poll.vote', { ...data, voterId: 'V2' }, at)).not.toBe(key);
    });

    // A voter flipping A, B, A within one second: the third change shares the whole second, the selection and so
    // the hash with the first. Under the key of the first it would be dropped by a receiver that dedupes on it,
    // which would then end on B while the voter's choice is A.
    it('keeps a vote that returns to an earlier selection within the same second apart from the first', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const first = {
        sessionId: 'A',
        pollMessageId: 'POLL1',
        voterId: 'V1',
        selectedOptions: ['A'],
        timestamp: 100,
        timestampMs: 100100,
      };
      const third = { ...first, timestampMs: 100900 };
      expect(generateIdempotencyKey('poll.vote', third, at)).not.toBe(generateIdempotencyKey('poll.vote', first, at));
      // A redelivery of the same change still carries the same stamp and the same key.
      expect(generateIdempotencyKey('poll.vote', { ...first }, '2026-07-20T01:00:00.000Z')).toBe(
        generateIdempotencyKey('poll.vote', first, at),
      );
    });

    it('keys call.received on the session + call id (unique per call, no occurrence salt needed)', () => {
      const at = '2026-07-20T00:00:00.000Z';
      const data = { sessionId: 'A', callId: 'CALL1', from: '[email protected]', timestamp: 1782000000 };
      const key = generateIdempotencyKey('call.received', data, at);
      expect(key).toBe('call_A_CALL1');
      // Retry of the same dispatch regenerates the same key — occurredAt is ignored by design...
      expect(generateIdempotencyKey('call.received', data, '2026-07-20T01:00:00.000Z')).toBe(key);
      // ...while a distinct call (a new occurrence, always a new call id) gets a distinct key.
      expect(generateIdempotencyKey('call.received', { ...data, callId: 'CALL2' }, at)).not.toBe(key);
      // Scoped by session like the message keys: the same call id on another session must not dedupe.
      expect(generateIdempotencyKey('call.received', { ...data, sessionId: 'B' }, at)).not.toBe(key);
    });

    it('should generate fallback key for unknown events', () => {
      const key = generateIdempotencyKey('custom.event', {});
      expect(key).toMatch(/^evt_custom_event_[a-f0-9]{12}$/);
    });
  });

  describe('generateDeliveryId', () => {
    it('should generate unique delivery IDs', () => {
      const id1 = generateDeliveryId();
      const id2 = generateDeliveryId();

      expect(id1).toMatch(/^dlv_[a-f0-9-]{36}$/);
      expect(id2).toMatch(/^dlv_[a-f0-9-]{36}$/);
      expect(id1).not.toBe(id2);
    });
  });
});