Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(identity): preserve reported chat identities

Yudhi Armyndharis01e1874a90a6
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index d33ed31db..b266ed8c8 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -729,6 +729,8 @@ The data connection also owns:
- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).
- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. `chatId` is the person's phone JID (`<phone>@s.whatsapp.net`) whenever their lid resolves, so a state WhatsApp syncs under the lid and one set through the phone number land on the same row; it stays `<lid>@lid` while the lid is unresolved, and a row found under the lid later is folded onto the phone JID on the chat's next change (reads and the fold take each field from the newest row that observed it: `observed` lists the fields a row has seen, and null, on a row not written since the column was added, means the fields it holds a set value for; the next write that can read the row records the list). WhatsApp does not re-deliver that state, so it is kept in backups. A chat deleted on the phone or through the API loses its row, so a later message starts it clean.
+`lid_mappings.isReported` distinguishes engine mapping reports from cache-only display data. Phone/LID alias authorization, candidate expansion and list filters use only reported mappings. A conflicting cached phone revokes alias trust without replacing the stored phone, and a later actual report restores it. The migration conservatively marks older mixed-origin rows as display data; backups carry the flag, and older backups restore with alias access disabled until a new report arrives.
+
Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint.
> [!NOTE]
@@ -933,7 +935,8 @@ src/database/migrations/ # data connection (pluggable)
├── 1790812800000-AddMessageWindowIndexes.ts # compound timestamp indexes for message-time pagination
├── 1791100000000-AddIntegrationDeliveryFailureDeliveryIndex.ts # (pluginId, instanceId, deliveryId) index for the dead-letter guards
├── 1791200000000-AddWebhookOutboxSessionIndex.ts # (sessionId) index for the per-session outbox delete
-└── 1791300000000-BackfillLegacyMessageTypes.ts # converts raw wwebjs message types to the neutral vocabulary, once
+├── 1791300000000-BackfillLegacyMessageTypes.ts # converts raw wwebjs message types to the neutral vocabulary, once
+└── 1791400000000-AddLidMappingReportSource.ts # distinguishes mapping reports from cached display data
```
> [!NOTE]
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 3abd730ff..4667f1dfc 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -7292,6 +7292,12 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
> **`senderPhone` on `message.received` is opt-in (`RESOLVE_LID_TO_PHONE`).** When a sender is identified by a WhatsApp privacy id (`…@lid`) rather than a phone number, setting `RESOLVE_LID_TO_PHONE=true` attaches a best-effort `senderPhone` — MSISDN digits, or `null` when the engine cannot map the id — before dispatch, so the webhook and the websocket event both carry it in the same pass. Default is **off**, and while it is off the field is absent from every payload: resolving costs a per-sender lookup (cached). Only inbound privacy-id senders are resolved — a sender that already is a phone number needs no lookup, and own-sends are skipped. The on-demand `GET /api/sessions/:sessionId/contacts/:contactId/phone` works regardless of this flag.
+Cached answers are checked again on the first message at least five minutes later and are discarded when the session engine stops or is replaced. Both engines can answer from local cache, so rechecking does not guarantee a fresh network identity check. Cache-only mappings remain available for display but cannot authorize phone/LID aliases or expand chat filters. A conflicting cached lookup disables alias matching until an engine mapping report confirms the phone. Baileys learns those reports from message identity fields and contact updates carrying a phone; its signal-key and send-time cache lookups remain display data. A cached Baileys answer can revoke a contradictory reported alias but cannot grant either phone. whatsapp-web.js can also confirm a mapping through its send-time number query. After a failed mapping write, another actual report retries it; a message without a new mapping does not re-report a cached Baileys answer.
+
+Baileys preserves raw LIDs in message, contact and chat identities, with phone numbers kept separately for display. Older phone-keyed message rows keep their original ids. Cross-form edits and deletes require a reported pairing; explicit API actions that need such a pairing can confirm it through the public WhatsApp LID query before acting. A cached phone alone cannot redirect an operation to an older row or attach another chat's preview. A successful shared-table lookup with no mapping does not reuse a resident alias, including after a data import removes that row.
+
+Existing stored mappings from older releases have mixed origins, so an upgrade retains their display data but requires a new mapping report before phone/LID alias matching resumes. Exact phone or LID grants still match the chat id explicitly named. Upgrade every process sharing the database together: older readers do not enforce this distinction. Backups preserve mapping origin; older backups without it restore conservatively as display data.
+
> **`contact` on `message.received` is minimal unless you opt in (`WEBHOOK_CONTACT_DETAILS`).** By default the payload carries only `contact { name?, pushName? }`. Setting `WEBHOOK_CONTACT_DETAILS=true` adds `id`, `number`, `shortName`, `type`, `isMyContact`, `isWAContact`, `isBusiness`, `isEnterprise`, `verifiedName`, `verifiedLevel`, `isBlocked` and `labels`, each present only when the engine has a value for it. Every field is copied from the contact record the engine has already loaded for the message, so opting in costs no extra WhatsApp lookup and cannot add rate-limiting pressure. The same enrichment reaches the websocket event, since both are dispatched from one payload. `contact` itself is omitted entirely when the engine has no value for any of its fields, so treat the whole object as optional rather than just its members. **whatsapp-web.js only** — the Baileys path emits `contact { pushName }` when a push name is available, and never reads this flag.
> **`edited` on `message.received` and `message.sent`.** When an edit reached a message before the gateway stored it, the message is announced with the edited `body` and `edited: true`, as its stored row carries `metadata.edited`. This holds when a later edit restored the text it arrived with too, and the `body` is then that text; edit events that each repeat the text set neither. Its `message.edited` can arrive before the message itself, so a client that holds no copy of it yet reads the mark from here. An own message the engine delivers again after an edit marked its stored row is announced in `message.sent` with `edited: true` too, after the `message.edited` of an edit that reached the gateway first (it remembers up to 500 marked messages per session, the oldest forgotten first, while the session has an engine). A message announced deleted (`type: 'revoked'`) carries an empty `body` and never the field. The field is absent otherwise.
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index da79b02d5..97ede18ff 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -890,6 +890,7 @@ skips: check `pg_index.indisvalid` and drop the invalid index before building it
| Release | Change | Action |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `next` | Existing and older-backup LID mappings become display data; phone/LID aliases stay disabled until an actual engine mapping report. Cache-only lookup results cannot authorize an alias. Baileys preserves LIDs in message and listing identities instead of deriving them from cached phone numbers | Upgrade every reader together: older versions do not enforce the origin flag. Exact-ID grants remain available. Back up before downgrade; reversing this migration clears unreported display phone mappings so an older reader cannot authorize them |
| `next` | The first boot rewrites every legacy `messages.type` value in one `UPDATE`, inside the transaction of the other pending migrations: on PostgreSQL about a minute per million legacy rows, with the port closed. Only a database whose conversion kept being cancelled on `0.25.0` still holds a large backlog | Count them with `SELECT count(*) FROM messages WHERE type IN ('chat', 'buttons_response', 'list_response', 'template_button_reply', 'ptt', 'vcard', 'multi_vcard')`; above a few million, run the migrations first (section 14.5), or raise `startupProbe.failureThreshold` to cover about a minute per million legacy rows (measured with twelve indexes on the table) on top of the index builds |
| `next` | A production boot refuses a `METRICS_TOKEN` that is the `.env.example` placeholder or a weak value the other secrets are checked against (`test`, `change-me`, `changeme`, `password`, `secret`, `admin`, `demo` and a few more), trimmed and case-insensitive | Set a long random token, or unset `METRICS_TOKEN` to keep `/api/metrics` disabled (it answers `404`); there is no length floor, so a short value that is not on the list still boots |
| `next` | A session delete removes its messages, outbox rows and delivery failures in batches (about 150 ms, at most 2000 rows, on SQLite; 500 rows on PostgreSQL), so a large session takes longer than the one statement of `0.25.0`: on SQLite 3 to 4.5 times as long for 300,000 to 1.2 million messages (`0.25.0` froze the process meanwhile); on PostgreSQL 17 to 67 s for a million messages against about 1 s, 13 to 50 times as long (on a test host under load, the longer times under heavier load, whether the table was analyzed or not), and about 8 to 10 s for 300,000 outbox rows with as many delivery failures, growing faster than linearly beyond that. A few thousand messages still take a fraction of a second. A failure part-way leaves the session stopped, with fewer rows | Give the delete a client or proxy timeout that covers a large session, and repeat it after a failure: the repeat finishes the job (`POST /start` keeps the session instead) |
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.ts
index 5382118d9..40fe120b7 100644
--- a/src/core/plugins/plugin-capability-context.ts
+++ b/src/core/plugins/plugin-capability-context.ts
@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from 'async_hooks';
import type { HookManager, HookEvent } from '../hooks';
import type { LidMappingStore } from '../../engine/identity/lid-mapping-store.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
-import { toNeutralJid } from '../../engine/identity/wa-id';
+import { parseWaId, toNeutralJid } from '../../engine/identity/wa-id';
import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';
import { createLogger, UNPRINTABLE } from '../../common/services/logger.service';
import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';
@@ -321,12 +321,12 @@ export class PluginCapabilityContext {
Math.min(Math.max(typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : 50, 1), 100),
includeMedia ?? false,
),
- canonicalChatId: (sessionId, chatId) => {
- // resolveEngineRead is the gate only (engine:read permission + live session); the resolution
- // itself is a synchronous host lid->phone lookup, not an engine call, mirroring the webhook
- // from-filter. Not `async` (nothing to await) — a resolved promise satisfies the signature.
+ canonicalChatId: async (sessionId, chatId) => {
this.resolveEngineRead(plugin, sessionId);
- return Promise.resolve(toNeutralJid(chatId, jid => this.lidMappingStore?.resolveLid(jid) ?? null));
+ const parsed = parseWaId(chatId);
+ const phone =
+ parsed.kind === 'lid' ? await this.lidMappingStore?.findPhoneForLid?.(chatId).catch(() => null) : null;
+ return toNeutralJid(chatId, () => phone ?? null);
},
} satisfies PluginEngineReadCapability;
}
diff --git a/src/database/migrations/1791400000000-AddLidMappingReportSource.ts b/src/database/migrations/1791400000000-AddLidMappingReportSource.ts
new file mode 100644
index 000000000..584331884
--- /dev/null
+++ b/src/database/migrations/1791400000000-AddLidMappingReportSource.ts
@@ -0,0 +1,24 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Distinguish engine mapping reports from cache-only phone lookups. Existing rows have mixed origins,
+ * so they keep their display data but require a new mapping report before authorizing phone/LID aliases.
+ */
+export class AddLidMappingReportSource1791400000000 implements MigrationInterface {
+ name = 'AddLidMappingReportSource1791400000000';
+
+ async up(runner: QueryRunner): Promise<void> {
+ if (!(await runner.hasTable('lid_mappings')) || (await runner.hasColumn('lid_mappings', 'isReported'))) return;
+ const initial = runner.dataSource.options.type === 'postgres' ? 'false' : '0';
+ await runner.query(`ALTER TABLE "lid_mappings" ADD COLUMN "isReported" boolean NOT NULL DEFAULT ${initial}`);
+ }
+
+ async down(runner: QueryRunner): Promise<void> {
+ if (!(await runner.hasTable('lid_mappings')) || !(await runner.hasColumn('lid_mappings', 'isReported'))) return;
+ // Older readers ignore origin, so an unreported positive must not become an indefinitely trusted row.
+ await runner.query(
+ `UPDATE "lid_mappings" SET "phone" = NULL, "sessionId" = NULL WHERE "isReported" = false AND "phone" IS NOT NULL`,
+ );
+ await runner.dropColumn('lid_mappings', 'isReported');
+ }
+}
diff --git a/src/database/migrations/__tests__/1791400000000-AddLidMappingReportSource.spec.ts b/src/database/migrations/__tests__/1791400000000-AddLidMappingReportSource.spec.ts
new file mode 100644
index 000000000..5317461e4
--- /dev/null
+++ b/src/database/migrations/__tests__/1791400000000-AddLidMappingReportSource.spec.ts
@@ -0,0 +1,91 @@
+import { randomUUID } from 'crypto';
+import { DataSource } from 'typeorm';
+import { LidMapping } from '../../../engine/identity/lid-mapping.entity';
+import { LidMappingStoreService } from '../../../engine/identity/lid-mapping-store.service';
+import { AddLidMappings1781200000000 } from '../1781200000000-AddLidMappings';
+import { AddLidMappingReportSource1791400000000 } from '../1791400000000-AddLidMappingReportSource';
+
+describe('AddLidMappingReportSource migration', () => {
+ const pg = process.env.DATABASE_TYPE === 'postgres';
+ const server = {
+ type: 'postgres' as const,
+ host: process.env.DATABASE_HOST || '127.0.0.1',
+ port: Number(process.env.DATABASE_PORT || 5432),
+ username: process.env.DATABASE_USERNAME || 'openwa',
+ password: process.env.DATABASE_PASSWORD || 'openwa',
+ database: process.env.DATABASE_NAME || 'openwa',
+ };
+ const migration = new AddLidMappingReportSource1791400000000();
+ let ds: DataSource;
+ let admin: DataSource | undefined;
+ let schema: string;
+
+ beforeEach(async () => {
+ schema = `lid_report_${randomUUID().replace(/-/g, '')}`;
+ admin = pg ? await new DataSource(server).initialize() : undefined;
+ if (admin) await admin.query(`CREATE SCHEMA "${schema}"`);
+ ds = await new DataSource(
+ pg
+ ? { ...server, schema, extra: { options: `-c search_path=${schema},public` }, entities: [LidMapping] }
+ : { type: 'better-sqlite3', database: ':memory:', entities: [LidMapping] },
+ ).initialize();
+ const runner = ds.createQueryRunner();
+ await new AddLidMappings1781200000000().up(runner);
+ await runner.release();
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ if (admin) {
+ await admin.query(`DROP SCHEMA "${schema}" CASCADE`);
+ await admin.destroy();
+ }
+ });
+
+ it('preserves legacy data conservatively, upgrades an actual report, and does not renew trust on retry', async () => {
+ await ds.query(
+ `INSERT INTO "lid_mappings" ("lid", "phone", "sessionId") VALUES ('111', '628111', 's1'), ('222', NULL, 's2')`,
+ );
+ const runner = ds.createQueryRunner();
+ await migration.up(runner);
+ expect(await ds.getRepository(LidMapping).find({ order: { lid: 'ASC' } })).toMatchObject([
+ { lid: '111', phone: '628111', sessionId: 's1', isReported: false },
+ { lid: '222', phone: null, sessionId: 's2', isReported: false },
+ ]);
+ const store = new LidMappingStoreService(ds.getRepository(LidMapping));
+ await store.onModuleInit();
+ expect(store.getCached('111')).toBe('628111');
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ await store.remember('111', '628111', 's1');
+ await migration.up(runner);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ await runner.release();
+ });
+
+ it('clears only unreported positive aliases before dropping origin on downgrade', async () => {
+ const runner = ds.createQueryRunner();
+ await migration.up(runner);
+ await ds.getRepository(LidMapping).insert([
+ { lid: '111', phone: '628111', sessionId: 's1', isReported: false },
+ { lid: '222', phone: '628222', sessionId: 's2', isReported: true },
+ { lid: '333', phone: null, sessionId: 's3', isReported: false },
+ ]);
+ await migration.down(runner);
+ await migration.down(runner);
+ expect(await runner.hasColumn('lid_mappings', 'isReported')).toBe(false);
+ expect(await ds.query(`SELECT "lid", "phone", "sessionId" FROM "lid_mappings" ORDER BY "lid"`)).toEqual([
+ { lid: '111', phone: null, sessionId: null },
+ { lid: '222', phone: '628222', sessionId: 's2' },
+ { lid: '333', phone: null, sessionId: 's3' },
+ ]);
+ await runner.release();
+ });
+
+ it('skips a database without the mapping table', async () => {
+ const runner = ds.createQueryRunner();
+ await runner.dropTable('lid_mappings');
+ await expect(migration.up(runner)).resolves.toBeUndefined();
+ await expect(migration.down(runner)).resolves.toBeUndefined();
+ await runner.release();
+ });
+});
diff --git a/src/engine/adapters/baileys-contacts-identity.spec.ts b/src/engine/adapters/baileys-contacts-identity.spec.ts
new file mode 100644
index 000000000..5b2a46692
--- /dev/null
+++ b/src/engine/adapters/baileys-contacts-identity.spec.ts
@@ -0,0 +1,254 @@
+import type { WASocket } from '@whiskeysockets/baileys';
+import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';
+import { BaileysMessaging, BaileysMessagingHost } from './baileys-messaging';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { createLogger } from '../../common/services/logger.service';
+import { toNeutralJid } from '../identity/wa-id';
+
+const operations: Array<[string, (contacts: BaileysContacts) => Promise<unknown>]> = [
+ ['mute', contacts => contacts.muteChat('[email protected]', null)],
+ ['pin', contacts => contacts.pinChat('[email protected]', true)],
+ ['unread', contacts => contacts.markUnread('[email protected]')],
+ ['clear', contacts => contacts.clearChatMessages('[email protected]')],
+ ['archive', contacts => contacts.archiveChat('[email protected]', true)],
+ ['delete', contacts => contacts.deleteChat('[email protected]')],
+ ['receipt', contacts => contacts.sendSeen('[email protected]')],
+ ['contact', contacts => contacts.getContactById('[email protected]')],
+];
+
+class Query {
+ withLIDProtocol(): this {
+ return this;
+ }
+ withContext(): this {
+ return this;
+ }
+ withUser(): this {
+ return this;
+ }
+}
+class User {
+ withId(): this {
+ return this;
+ }
+}
+
+describe.each(['persisted', 'fresh', 'library'] as const)('Chat identity prepared through %s mapping', source => {
+ it.each(operations)('does not carry %s across a socket replacement', async (_name, act) => {
+ let release!: () => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const makeSocket = () => ({
+ chatModify: jest.fn().mockResolvedValue(undefined),
+ readMessages: jest.fn().mockResolvedValue(undefined),
+ fetchBlocklist: jest.fn().mockResolvedValue([]),
+ executeUSyncQuery: jest.fn(async () => {
+ entered();
+ await gate;
+ return { list: [{ id: '[email protected]', lid: '111@lid' }] };
+ }),
+ });
+ const first = makeSocket();
+ const replacement = makeSocket();
+ let current = first;
+ const recordLidMapping = jest.fn();
+ const key = { remoteJid: '111@lid', id: 'M1', fromMe: false };
+ const host = {
+ ensureReady: () => undefined,
+ getSocket: () => current as unknown as WASocket,
+ loadLib: async () => {
+ if (source === 'library') {
+ entered();
+ await gate;
+ }
+ return { USyncQuery: Query, USyncUser: User };
+ },
+ logger: createLogger('ChatIdentity'),
+ findPersistedLidPhone: async () => {
+ if (source !== 'persisted') return null;
+ entered();
+ await gate;
+ return '628111';
+ },
+ recordLidMapping,
+ chatJid: () => '111@lid',
+ toNeutralJid,
+ toEngineJid: (jid: string) => jid,
+ lastMessage: () => ({ key, jid: '111@lid', timestamp: 1 }),
+ lastInboundMessage: () => ({ key, timestamp: 1 }),
+ findContact: () => ({ id: '111@lid', number: '628111', isWAContact: true }),
+ } as unknown as BaileysContactsHost;
+ const contacts = new BaileysContacts(host);
+ const pending = act(contacts).catch((error: unknown) => error);
+ await started;
+ current = replacement;
+ release();
+ expect(await pending).toBeInstanceOf(EngineNotReadyError);
+ for (const socket of [first, replacement]) {
+ expect(socket.chatModify).not.toHaveBeenCalled();
+ expect(socket.readMessages).not.toHaveBeenCalled();
+ expect(socket.fetchBlocklist).not.toHaveBeenCalled();
+ }
+ expect(recordLidMapping).not.toHaveBeenCalled();
+ if (source === 'library') expect(first.executeUSyncQuery).not.toHaveBeenCalled();
+ });
+});
+
+it('does not query a retired message socket after the library finishes loading', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const first = {
+ executeUSyncQuery: jest.fn().mockResolvedValue({ list: [{ id: '[email protected]', lid: '111@lid' }] }),
+ chatModify: jest.fn(),
+ };
+ let current = first;
+ const recordLidMapping = jest.fn();
+ const host = {
+ ensureReady: () => undefined,
+ getSocket: () => current,
+ getSocketOrNull: () => current,
+ loadLib: async () => {
+ entered();
+ await gate;
+ return { USyncQuery: Query, USyncUser: User };
+ },
+ getStoredMessage: () =>
+ Promise.resolve({
+ key: { id: 'M1', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'mine' },
+ }),
+ wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
+ findPersistedLidPhone: () => Promise.resolve(null),
+ recordLidMapping,
+ toEngineJid: (jid: string) => jid,
+ logger: createLogger('MessageIdentity'),
+ } as unknown as BaileysMessagingHost;
+ const pending = new BaileysMessaging(host).starMessage('[email protected]', 'M1', true).catch((error: unknown) => error);
+ await started;
+ current = { ...first, chatModify: jest.fn(), executeUSyncQuery: jest.fn() };
+ release();
+ expect(await pending).toBeInstanceOf(EngineNotReadyError);
+ expect(first.executeUSyncQuery).not.toHaveBeenCalled();
+ expect(first.chatModify).not.toHaveBeenCalled();
+ expect(current.chatModify).not.toHaveBeenCalled();
+ expect(recordLidMapping).not.toHaveBeenCalled();
+});
+
+const messageActions: Array<[string, (messaging: BaileysMessaging) => Promise<unknown>, boolean, boolean]> = [
+ ['reply', m => m.replyToMessage('[email protected]', 'M1', 'reply'), true, true],
+ ['forward', m => m.forwardMessage('[email protected]', '[email protected]', 'M1'), true, true],
+ ['reaction', m => m.reactToMessage('[email protected]', 'M1', 'yes'), false, true],
+ ['edit', m => m.editMessage('[email protected]', 'M1', 'edited'), true, true],
+ ['delete for everyone', m => m.deleteMessage('[email protected]', 'M1', true), false, true],
+ ['delete for me', m => m.deleteMessage('[email protected]', 'M1', false), false, false],
+ ['star', m => m.starMessage('[email protected]', 'M1', true), false, false],
+ ['pin', m => m.pinMessage('[email protected]', 'M1', 86400), true, true],
+ ['unpin', m => m.unpinMessage('[email protected]', 'M1'), true, true],
+ ['button', m => m.clickButton('[email protected]', 'M1', 'yes'), true, true],
+];
+
+describe.each(['stored', 'persisted', 'library', 'recipient'] as const)(
+ 'Message actions prepared through %s',
+ phase => {
+ it.each(
+ messageActions.filter(
+ ([, , library, recipient]) => (phase !== 'library' || library) && (phase !== 'recipient' || recipient),
+ ),
+ )('does not move %s to a replacement socket', async (_name, act) => {
+ let entered!: () => void;
+ let release!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const pause = async (stage: string): Promise<void> => {
+ if (stage === phase) {
+ entered();
+ await gate;
+ }
+ };
+ const makeSocket = () => ({
+ executeUSyncQuery: jest.fn(),
+ chatModify: jest.fn().mockResolvedValue(undefined),
+ sendMessage: jest.fn().mockResolvedValue(undefined),
+ signalRepository: {
+ lidMapping: {
+ getLIDForPN: async () => {
+ await pause('recipient');
+ return '111@lid';
+ },
+ },
+ },
+ });
+ const first = makeSocket(),
+ replacement = makeSocket();
+ let current = first;
+ const recordLidMapping = jest.fn();
+ const library = {
+ USyncQuery: Query,
+ USyncUser: User,
+ normalizeMessageContent: (value: unknown) => value,
+ getContentType: () => 'buttonsMessage',
+ proto: { PinInChat: { Type: { PIN_FOR_ALL: 1, UNPIN_FOR_ALL: 2 } } },
+ };
+ const host = {
+ ensureReady: () => undefined,
+ getSocket: () => current,
+ getSocketOrNull: () => current,
+ getStoredMessage: async () => {
+ await pause('stored');
+ return {
+ key: { id: 'M1', remoteJid: '111@lid', fromMe: true },
+ message: {
+ buttonsMessage: {
+ contentText: 'Choose',
+ buttons: [{ buttonId: 'yes', buttonText: { displayText: 'Yes' } }],
+ },
+ },
+ messageTimestamp: 1,
+ };
+ },
+ wasDeletedForEveryone: () => false,
+ pendingEditOf: () => undefined,
+ findPersistedLidPhone: async () => {
+ await pause('persisted');
+ return '628111';
+ },
+ loadLib: async () => {
+ await pause('library');
+ return library;
+ },
+ toEngineJid: (jid: string) => jid,
+ getEphemeralExpiration: () => undefined,
+ toUnixSeconds: () => 1,
+ recordLidMapping,
+ logger: createLogger('MessageEpoch'),
+ } as unknown as BaileysMessagingHost;
+ const pending = act(new BaileysMessaging(host)).catch((error: unknown) => error);
+ await started;
+ const reportsBeforeRetire = recordLidMapping.mock.calls.length;
+ current = replacement;
+ release();
+ expect(await pending).toBeInstanceOf(EngineNotReadyError);
+ for (const socket of [first, replacement]) {
+ expect(socket.chatModify).not.toHaveBeenCalled();
+ expect(socket.sendMessage).not.toHaveBeenCalled();
+ }
+ expect(recordLidMapping).toHaveBeenCalledTimes(reportsBeforeRetire);
+ });
+ },
+);
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index b13a25ebb..3c2ce314a 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -1,3 +1,6 @@
+import type * as BaileysLib from '@whiskeysockets/baileys';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+import { queryLidPhone } from './baileys-identity-query';
import type { WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';
import { assertReadableImage, resolveMediaBuffer } from './baileys-messaging';
@@ -6,8 +9,8 @@ import { BAILEYS_QUERY_BUDGET_MS, confirmedWrite, withQueryDeadline } from './ba
import { EngineTransportError } from '../../common/errors/engine-transport.error';
import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';
import { LidNotMappedError } from '../../common/errors/lid-not-mapped.error';
-import { chatKind, parseWaId, userPart } from '../identity/wa-id';
-import { storedKeyInChat } from './baileys-message-mapper';
+import { chatKind, parseWaId, toNeutralJid, userPart } from '../identity/wa-id';
+import { storedKeyInChat, storedKeyInChatPersisted } from './baileys-message-mapper';
import { refusedStatusCode } from './baileys-groups';
/**
@@ -21,6 +24,7 @@ export interface BaileysContactsHost {
ensureReady(): void;
/** Post-ensureReady socket handle — call host.ensureReady() first. */
getSocket(): WASocket;
+ loadLib?(): Promise<typeof BaileysLib>;
readonly logger: ReturnType<typeof createLogger>;
normalizedSelfJid(): string;
listContacts(): Contact[];
@@ -29,7 +33,7 @@ export interface BaileysContactsHost {
/** The phone the persisted lid->phone table holds for a lid, or null; read when the caches miss. */
findPersistedLidPhone(lid: string): Promise<string | null>;
/** Learn a lid->phone pair (written through to the persisted table). */
- recordLidMapping(lid: string, pn: string): void;
+ recordLidMapping(lid: string, pn: string, isReported?: boolean): void;
listChats(): ChatSummary[];
/**
* The chat's last known message (the handle chatModify needs), or null when none.
@@ -65,8 +69,10 @@ export class BaileysContacts {
}
/** Post-ensureReady socket handle. */
- private sock(): WASocket {
- return this.host.getSocket();
+ private sock(expected?: WASocket): WASocket {
+ const socket = this.host.getSocket();
+ if (expected && socket !== expected) throw new EngineNotReadyError();
+ return socket;
}
async getProfilePicture(contactId: string): Promise<string | null> {
@@ -237,6 +243,11 @@ export class BaileysContacts {
this.host.ensureReady();
const contact = this.host.findContact(contactId);
if (!contact) return null;
+ if (
+ !storedKeyInChat({ remoteJid: contact.id }, contactId, toNeutralJid) &&
+ !(await this.matchesChat({ remoteJid: contact.id }, contactId))
+ )
+ return null;
return (await this.withBlockedState([contact]))[0];
}
@@ -360,7 +371,7 @@ export class BaileysContacts {
.signalRepository?.lidMapping?.getPNForLID(contactId)
.catch(() => null);
if (pn) {
- this.host.recordLidMapping(contactId, pn);
+ this.host.recordLidMapping(contactId, pn, false);
return userPart(pn);
}
throw new LidNotMappedError(contactId);
@@ -374,6 +385,7 @@ export class BaileysContacts {
async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
const keys = await this.receiptKeys(chatId, messageIds, authors);
if (keys.length === 0) {
return false; // nothing known to mark read
@@ -381,7 +393,7 @@ export class BaileysContacts {
// readMessages reaches fetchPrivacySettings, which destructures the query result and throws a
// raw TypeError on an unanswered one — no Boom, so nothing downstream can classify it. Marking
// a chat read is idempotent, so bounding it is safe: a repeat costs nothing.
- await this.confirmed(this.sock().readMessages(keys), 'the read receipt');
+ await this.confirmed(this.sock(socket).readMessages(keys), 'the read receipt');
return true;
}
@@ -416,7 +428,7 @@ export class BaileysContacts {
// The newest RECEIVED message, not the preview: after an API reply the preview is an own key,
// which Baileys drops from the receipt, so the call would answer true having sent nothing.
const last = this.host.lastInboundMessage(chatId);
- return last ? [last.key] : [];
+ return last && (await this.matchesChat(last.key, chatId)) ? [last.key] : [];
}
if (messageIds.length === 0) {
return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest
@@ -432,13 +444,12 @@ export class BaileysContacts {
// lid to its phone user-part through the session's lid mapping, so both spellings of one chat
// still meet. Anything that still differs falls back to the synthesised key for the ADDRESSED
// chat, which is exactly what every id ran on before stored keys existed.
- const keyById = new Map(
- stored
- .filter(
- msg => msg.key?.id && msg.key.remoteJid && storedKeyInChat(msg.key, chatId, j => this.host.toNeutralJid(j)),
- )
- .map(msg => [msg.key.id as string, msg.key]),
- );
+ const keyById = new Map<string, WAMessageKey>();
+ for (const msg of stored) {
+ if (msg.key?.id && msg.key.remoteJid && (await this.matchesChat(msg.key, chatId))) {
+ keyById.set(msg.key.id, msg.key);
+ }
+ }
const inGroup = chatKind(remoteJid) === 'group';
return messageIds.flatMap((id): WAMessageKey[] => {
const key = keyById.get(id);
@@ -449,14 +460,41 @@ export class BaileysContacts {
});
}
+ private async matchesChat(key: WAMessageKey, chatId: string): Promise<boolean> {
+ const socket = this.sock();
+ const persisted = await storedKeyInChatPersisted(key, chatId, jid => this.host.findPersistedLidPhone(jid));
+ this.sock(socket);
+ if (persisted) return true;
+ const requested = parseWaId(chatId);
+ const stored = parseWaId(key.remoteJid ?? '');
+ if (!((requested.kind === 'user' && stored.kind === 'lid') || (requested.kind === 'lid' && stored.kind === 'user')))
+ return false;
+ const phone = requested.kind === 'user' ? requested.userPart : stored.userPart;
+ const lid = requested.kind === 'lid' ? requested.userPart : stored.userPart;
+ if (typeof socket.executeUSyncQuery !== 'function' || !this.host.loadLib) return false;
+ const library = await this.host.loadLib();
+ this.sock(socket);
+ const confirmed = await queryLidPhone(socket, library, phone, lid, this.queryBudgetMs);
+ this.sock(socket);
+ if (confirmed) this.host.recordLidMapping(`${lid}@lid`, `${phone}@s.whatsapp.net`);
+ return confirmed;
+ }
+
+ async confirmedChatJid(chatId: string): Promise<string> {
+ const jid = this.host.chatJid(chatId);
+ if (!(await this.matchesChat({ remoteJid: jid }, chatId))) throw new RecipientUnreachableError(chatId);
+ return jid;
+ }
+
async markUnread(chatId: string): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
const last = this.host.lastMessage(chatId);
- if (!last) {
+ if (!last || !(await this.matchesChat(last.key, chatId))) {
return false; // Baileys' unread toggle needs the last message; can't synthesize it
}
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{ markRead: false, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
last.jid,
),
@@ -467,12 +505,13 @@ export class BaileysContacts {
async clearChatMessages(chatId: string): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
const last = this.host.lastMessage(chatId);
- if (!last) {
+ if (!last || !(await this.matchesChat(last.key, chatId))) {
return false; // Baileys' clear needs the last message; can't synthesize it
}
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{ clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
last.jid,
),
@@ -483,12 +522,13 @@ export class BaileysContacts {
async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
const last = this.host.lastMessage(chatId);
- if (!last) {
+ if (!last || !(await this.matchesChat(last.key, chatId))) {
return false; // Baileys' archive toggle needs the last message; can't synthesize it
}
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{ archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
last.jid,
),
@@ -499,29 +539,34 @@ export class BaileysContacts {
async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
// Deliberately no lastMessage lookup: the `mute` member of ChatModification carries no
// `lastMessages`, unlike archive/clear/delete, so a chat with no known history mutes fine.
- await this.confirmed(this.sock().chatModify({ mute: muteUntil }, this.host.chatJid(chatId)), 'the mute change');
+ const jid = await this.confirmedChatJid(chatId);
+ await this.confirmed(this.sock(socket).chatModify({ mute: muteUntil }, jid), 'the mute change');
}
async pinChat(chatId: string, pin: boolean): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
// No lastMessage lookup: the `pin` member of ChatModification carries no `lastMessages`, unlike
// archive/clear/delete, so a chat with no known history pins fine. Always true — Baileys writes
// the app-state patch and reports nothing back, so it has no equivalent of the whatsapp-web.js
// three-pin refusal to surface.
- await this.confirmed(this.sock().chatModify({ pin }, this.host.chatJid(chatId)), 'the pin change');
+ const jid = await this.confirmedChatJid(chatId);
+ await this.confirmed(this.sock(socket).chatModify({ pin }, jid), 'the pin change');
return true;
}
async deleteChat(chatId: string): Promise<boolean> {
this.host.ensureReady();
+ const socket = this.sock();
const last = this.host.lastMessage(chatId);
- if (!last) {
+ if (!last || !(await this.matchesChat(last.key, chatId))) {
return false; // Baileys' delete needs the last message; can't synthesize it
}
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{ delete: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
last.jid,
),
diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.ts
index a85d20691..e771e93f0 100644
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@ -591,14 +591,25 @@ describe('BaileysEvents store writes across an unlink', () => {
let release!: () => void;
const gate = new Promise<void>(resolve => (release = resolve));
const putStoredMessage = jest.fn(() => Promise.resolve());
+ const recordKeyLidMappings = jest.fn();
const events = new BaileysEvents(
- makeHost({ loadLib: () => gate.then(() => libStub), putStoredMessage, getOnMessage: () => jest.fn() }),
+ makeHost({
+ loadLib: () => gate.then(() => libStub),
+ putStoredMessage,
+ recordKeyLidMappings,
+ getOnMessage: () => jest.fn(),
+ }),
);
events.handleMessagesUpsert({
type: 'notify',
messages: [
{
- key: { id: 'wamid.unlink', remoteJid: '[email protected]', fromMe: false },
+ key: {
+ id: 'wamid.unlink',
+ remoteJid: '123456789@lid',
+ remoteJidAlt: '[email protected]',
+ fromMe: false,
+ },
messageTimestamp: 1_700_000_000,
message: { conversation: 'hi' },
},
@@ -608,20 +619,22 @@ describe('BaileysEvents store writes across an unlink', () => {
release();
for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve));
};
- return { events, putStoredMessage, settle };
+ return { events, putStoredMessage, recordKeyLidMappings, settle };
};
it('stores a message whose processing finishes with the account still linked', async () => {
- const { putStoredMessage, settle } = held();
+ const { putStoredMessage, recordKeyLidMappings, settle } = held();
await settle();
expect(putStoredMessage).toHaveBeenCalledTimes(1);
+ expect(recordKeyLidMappings).toHaveBeenCalledTimes(1);
});
it('does not store a message still being processed when the account was unlinked', async () => {
- const { events, putStoredMessage, settle } = held();
+ const { events, putStoredMessage, recordKeyLidMappings, settle } = held();
events.fenceStoredWrites();
await settle();
expect(putStoredMessage).not.toHaveBeenCalled();
+ expect(recordKeyLidMappings).not.toHaveBeenCalled();
});
});
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index de8592224..b2c3fcf30 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -1,3 +1,4 @@
+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WACallEvent, WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
import {
@@ -216,11 +217,14 @@ export interface BaileysEventsHost {
/** The adapter's inbound media download gate (shared so the bound holds across all inbound paths). */
readonly inboundLimiter: ConcurrencyLimiter;
/** Learn any lid->pn pair a message key carries (also writes through to the persistent table). */
- recordKeyLidMappings(key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt'>): void;
+ recordKeyLidMappings(
+ key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt' | 'fromMe'>,
+ ): void;
/** Seed the chat's last-message preview + sort time from an inbound message. */
recordMessage(msg: WAMessage, type?: MessageType): void;
/** Apply a message edit to the stored body. */
recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void;
+ findPersistedLidPhone?(jid: string): Promise<string | null>;
/** Persist an inbound message to the store; undefined when no store is configured. */
putStoredMessage(msg: WAMessage): Promise<void> | undefined;
/** Rewrite a stored message in place (see BaileysMessageStore.update); undefined without a store. */
@@ -377,6 +381,15 @@ export class BaileysEvents {
*/
private changesAwaiting = 0;
+ /** Up to 64 preparations keep per-message order across directory reads; later arrivals wait for room. */
+ private readonly messageChanges = new KeyedMutationQueue();
+ private changesPreparing = 0;
+ private preparationRoom?: { ready: Promise<void>; release: () => void };
+ private retirePreparations!: () => void;
+ private preparationsRetired = new Promise<void>(resolve => {
+ this.retirePreparations = resolve;
+ });
+
private static readonly CHANGES_PARKED_LIMIT = 64;
/**
@@ -400,9 +413,18 @@ export class BaileysEvents {
constructor(private readonly host: BaileysEventsHost) {}
+ getStoredWriteGeneration(): number {
+ return this.storeGeneration;
+ }
+
/** Drop the store writes of every message that arrived before now; call before wiping the store. */
fenceStoredWrites(): void {
this.storeGeneration++;
+ const retire = this.retirePreparations;
+ this.preparationsRetired = new Promise<void>(resolve => {
+ this.retirePreparations = resolve;
+ });
+ retire();
}
/** Whether a delete for everyone of this message was accepted (see deletedForEveryone). */
@@ -436,10 +458,12 @@ export class BaileysEvents {
const found = await this.readTarget(target.id, 'checking what a history revoke targets');
if (generation !== this.storeGeneration) return undefined;
const original = found?.key ?? target;
- if (!this.mayChange(original, envelope, true)) return undefined;
+ const resolve = await this.reportedPhones(original, envelope);
+ if (generation !== this.storeGeneration) return undefined;
+ if (!this.mayChange(original, envelope, true, resolve)) return undefined;
if (found) this.markDeletedForEveryone(target.id);
this.changeStoredMessage(target.id, copy =>
- this.mayChange(copy.key, envelope, true) ? { ...copy, message: null } : null,
+ this.mayChange(copy.key, envelope, true, resolve) ? { ...copy, message: null } : null,
);
return original;
}
@@ -651,6 +675,26 @@ export class BaileysEvents {
});
}
+ private async recordPreviewChange(
+ chatId: string,
+ messageId: string,
+ body: string,
+ type?: MessageType,
+ generation = this.storeGeneration,
+ ): Promise<void> {
+ if (generation !== this.storeGeneration) return;
+ if (type === undefined) this.host.recordMessageEdit(chatId, messageId, body);
+ else this.host.recordMessageEdit(chatId, messageId, body, type);
+ if (parseWaId(chatId).kind === 'lid') {
+ const phone = await this.host.findPersistedLidPhone?.(chatId).catch(() => null);
+ if (generation !== this.storeGeneration) return;
+ if (phone) {
+ if (type === undefined) this.host.recordMessageEdit(`${phone}@s.whatsapp.net`, messageId, body);
+ else this.host.recordMessageEdit(`${phone}@s.whatsapp.net`, messageId, body, type);
+ }
+ }
+ }
+
private async processInboundMessage(
msg: WAMessage,
opts: {
@@ -662,6 +706,7 @@ export class BaileysEvents {
): Promise<void> {
try {
const b = await this.host.loadLib();
+ if (opts.generation !== this.storeGeneration) return;
const remoteJid = msg.key.remoteJid!;
// The chat the events below report: a received broadcast-list message belongs to its sender's
// chat. Store lookups and the foreign-message checks keep the raw key, which is what is stored.
@@ -689,132 +734,11 @@ export class BaileysEvents {
}
}
- // --- protocolMessage REVOKE: don't emit onMessage ---
- if (contentType === 'protocolMessage') {
- const pm = normalizedRoot?.protocolMessage;
- if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {
- // A group admin may revoke anyone's message, so only the chat is checked there.
- if (await this.targetsForeignMessage(pm.key?.id, msg.key, !remoteJid.endsWith('@g.us'), undefined, opts)) {
- return;
- }
- const from = msg.key.fromMe === true ? this.host.normalizedSelfJid() : chatJid;
- const to = msg.key.fromMe === true ? chatJid : this.host.normalizedSelfJid();
- const revoked: RevokedMessage = {
- id: pm.key?.id ?? '',
- // The REVOKE protocolMessage's key points at the ORIGINAL deleted message,
- // so `id` already IS the original here. Mirror it into `revokedId` so that
- // field is the reliable cross-engine handle (wwebjs sets it separately).
- revokedId: pm.key?.id ?? undefined,
- chatId: this.host.toNeutralJid(chatJid),
- from: this.host.toNeutralJid(from),
- to: this.host.toNeutralJid(to),
- type: 'revoked',
- body: '',
- timestamp: toUnixSeconds(msg.messageTimestamp),
- };
- this.host.recordMessageEdit(chatJid, revoked.id, '', 'revoked');
- // While the target is still being processed, the store change waits for it and lands after
- // this delete is announced, and a repeat delivery may already hold the content in the store:
- // record the delete now, checked against the target's own key.
- const target = this.inboundInFlight.get(revoked.id);
- if (target && this.mayChange(target.key, msg.key, true)) {
- this.markDeletedForEveryone(revoked.id);
- }
- // The stored copy keeps its key, so a late re-delivery is still recognised and a delete
- // for me can still address it, but loses its content, so nothing can quote or resend it.
- this.changeStoredMessage(pm.key?.id, stored =>
- this.mayChange(stored.key, msg.key, true) ? { ...stored, message: null } : null,
- );
- // Behind the reactions and edits of the message that wait for its emit, never for the message itself:
- // the delete keeps it from being emitted, and they were made before it.
- this.announceWhenHandedOn(
- revoked.id,
- opts.ticket,
- () => this.host.getOnMessageRevoked()?.(revoked, { fromMe: msg.key.fromMe === true }),
- true,
- );
- return;
- }
- if (pm?.type === b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT) {
- if (await this.targetsForeignMessage(pm.key?.id, msg.key, true, undefined, opts)) return;
- // MESSAGE_EDIT wraps the message's latest content. Normalize that INNER content separately
- // so captions, type, PTT, media presence and mentions describe the edited value rather than
- // the outer protocol envelope.
- const normalizedEdited = b.normalizeMessageContent(pm.editedMessage ?? undefined) ?? pm.editedMessage ?? {};
- const editedContentType = b.getContentType(normalizedEdited);
- const editedSubMessage =
- normalizedEdited.extendedTextMessage ??
- normalizedEdited.imageMessage ??
- normalizedEdited.videoMessage ??
- normalizedEdited.audioMessage ??
- normalizedEdited.documentMessage ??
- normalizedEdited.stickerMessage ??
- normalizedEdited.locationMessage;
- const contextInfo = editedSubMessage?.contextInfo;
- const base = buildIncomingMessageFromBaileys(
- {
- id: pm.key?.id ?? '',
- remoteJid,
- fromMe: msg.key.fromMe === true,
- participant: keyParticipant(msg.key),
- body: extractBaileysBody(normalizedEdited),
- contentType: editedContentType,
- isPtt: normalizedEdited.audioMessage?.ptt === true,
- timestamp: this.toEditUnixSeconds(pm.timestampMs, msg.messageTimestamp),
- selfJid: this.host.normalizedSelfJid(),
- mentionedJids: contextInfo?.mentionedJid ?? undefined,
- },
- jid => this.host.toNeutralJid(jid),
- );
- const hasMedia =
- editedContentType === 'imageMessage' ||
- editedContentType === 'videoMessage' ||
- editedContentType === 'audioMessage' ||
- editedContentType === 'documentMessage' ||
- editedContentType === 'documentWithCaptionMessage' ||
- editedContentType === 'stickerMessage';
- const edited: EditedMessage = buildEditedMessage(base, hasMedia);
- this.host.recordMessageEdit(chatJid, edited.messageId, edited.body);
- const target = this.inboundInFlight.get(edited.messageId);
- if (target && this.mayChange(target.key, msg.key, false)) {
- const earlier = this.editedWhileInFlight.get(edited.messageId);
- const afterOtherText = !!earlier && (earlier.afterOtherText || earlier.body !== edited.body);
- this.editedWhileInFlight.delete(edited.messageId); // re-inserted as the newest
- this.editedWhileInFlight.set(edited.messageId, { envelope: msg.key, body: edited.body, afterOtherText });
- if (this.editedWhileInFlight.size > BaileysEvents.DELETED_FOR_EVERYONE_LIMIT) {
- const [oldest] = this.editedWhileInFlight.keys();
- this.editedWhileInFlight.delete(oldest);
- }
- }
- this.changeStoredMessage(edited.messageId, stored => {
- const content = this.mayChange(stored.key, msg.key, false)
- ? b.normalizeMessageContent(stored.message ?? undefined)
- : undefined;
- return content && setBaileysText(content, edited.body) ? stored : null;
- });
- this.announceWhenHandedOn(edited.messageId, opts.ticket, () => this.host.getOnMessageEdited()?.(edited));
- return;
- }
- // Other protocol messages (ephemeral, history sync, etc.) — skip silently.
- return;
- }
-
- // --- reactionMessage: don't emit onMessage ---
- if (contentType === 'reactionMessage') {
- const rm = normalizedRoot?.reactionMessage;
- if (await this.targetsForeignMessage(rm?.key?.id, msg.key, false, 'reaction', opts)) return;
- const event: ReactionEvent = {
- messageId: rm?.key?.id ?? '',
- chatId: this.host.toNeutralJid(chatJid),
- reaction: rm?.text ?? '',
- // A 1:1 key names the chat partner, not the author: for a reaction the account made from
- // its phone (fromMe) the reactor is the account itself. Group and status keys carry the
- // author as `participant`, own reactions included, which the edit branch reads the same way.
- senderId: this.host.toNeutralJid(
- keyParticipant(msg.key) ?? (msg.key.fromMe === true ? this.host.normalizedSelfJid() : remoteJid),
- ),
- };
- this.announceWhenHandedOn(rm?.key?.id, opts.ticket, () => this.host.getOnMessageReaction()?.(event));
+ if (contentType === 'protocolMessage' || contentType === 'reactionMessage') {
+ const targetId = normalizedRoot?.protocolMessage?.key?.id ?? normalizedRoot?.reactionMessage?.key?.id;
+ await this.prepareMessageChange(targetId, opts, releasePreparation =>
+ this.processMessageChange(b, msg, normalizedRoot, contentType, { ...opts, releasePreparation }),
+ );
return;
}
@@ -937,6 +861,249 @@ export class BaileysEvents {
}
}
+ /** Preparation runs without a media permit; full-queue waiters provide backpressure without blocking its head. */
+ private async prepareMessageChange(
+ messageId: string | null | undefined,
+ opts: { generation: number; ticket?: InboundTicket; yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R> },
+ work: (releasePreparation: () => void) => Promise<void>,
+ ): Promise<void> {
+ if (opts.generation !== this.storeGeneration) return;
+ const retired = this.preparationsRetired;
+ if (!messageId) {
+ if (opts.generation === this.storeGeneration) await work(() => undefined);
+ return;
+ }
+ opts.ticket?.drop();
+ while (this.changesPreparing >= BaileysEvents.CHANGES_PARKED_LIMIT) {
+ if (!this.preparationRoom) {
+ let release!: () => void;
+ const ready = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ this.preparationRoom = { ready, release };
+ }
+ await Promise.race([this.preparationRoom.ready, retired]);
+ if (opts.generation !== this.storeGeneration) return;
+ }
+ this.changesPreparing++;
+ let finish!: () => void;
+ let fail!: (error: unknown) => void;
+ const done = new Promise<void>((resolve, reject) => {
+ finish = resolve;
+ fail = reject;
+ });
+ let releasePreparation!: () => void;
+ const released = new Promise<void>(resolve => {
+ releasePreparation = resolve;
+ });
+ this.messageChanges.enqueue(messageId, async () => {
+ const preparing = (async () => {
+ if (opts.generation === this.storeGeneration) await work(releasePreparation);
+ })().then(finish, fail);
+ try {
+ await Promise.race([preparing, released, retired]);
+ } finally {
+ this.changesPreparing--;
+ const room = this.preparationRoom;
+ this.preparationRoom = undefined;
+ room?.release();
+ }
+ });
+ const settled = Promise.race([done, retired]);
+ await (opts.yieldSlot ? opts.yieldSlot(() => settled) : settled);
+ }
+
+ private async processMessageChange(
+ b: typeof BaileysLib,
+ msg: WAMessage,
+ normalizedRoot: WAMessage['message'],
+ contentType: string,
+ opts: {
+ generation: number;
+ ticket?: InboundTicket;
+ yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R>;
+ releasePreparation: () => void;
+ },
+ ): Promise<void> {
+ const remoteJid = msg.key.remoteJid!;
+ const protocolType = normalizedRoot?.protocolMessage?.type;
+ const reaction = contentType === 'reactionMessage';
+ const revoke = !reaction && protocolType === b.proto.Message.ProtocolMessage.Type.REVOKE;
+ const edit = !reaction && protocolType === b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT;
+ const targetId = normalizedRoot?.protocolMessage?.key?.id ?? normalizedRoot?.reactionMessage?.key?.id;
+ let parked = false;
+ const inbound = {
+ ...opts,
+ releasePreparation: () => {
+ parked = true;
+ opts.releasePreparation();
+ },
+ };
+ if (
+ (reaction || revoke || edit) &&
+ (await this.targetsForeignMessage(
+ targetId,
+ msg.key,
+ edit || (revoke && !remoteJid.endsWith('@g.us')),
+ reaction ? 'reaction' : undefined,
+ inbound,
+ ))
+ )
+ return;
+ if (opts.generation !== this.storeGeneration) return;
+ const apply = () => this.applyMessageChange(b, msg, normalizedRoot, contentType, opts);
+ // Waiting for an original must not occupy the preparation queue. Once it answers, take a new
+ // turn before the remaining directory reads, so mixed change kinds still reach callbacks in order.
+ if (parked) await this.prepareMessageChange(targetId, { ...opts, ticket: undefined }, apply);
+ else await apply();
+ }
+
+ private async applyMessageChange(
+ b: typeof BaileysLib,
+ msg: WAMessage,
+ normalizedRoot: WAMessage['message'],
+ contentType: string,
+ opts: { generation: number; ticket?: InboundTicket; yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R> },
+ ): Promise<void> {
+ const remoteJid = msg.key.remoteJid!;
+ const chatJid = baileysChatJid(remoteJid, msg.key.participant, msg.key.fromMe === true);
+ // --- protocolMessage REVOKE: don't emit onMessage ---
+ if (contentType === 'protocolMessage') {
+ const pm = normalizedRoot?.protocolMessage;
+ if (pm?.type === b.proto.Message.ProtocolMessage.Type.REVOKE) {
+ const from = msg.key.fromMe === true ? this.host.normalizedSelfJid() : chatJid;
+ const to = msg.key.fromMe === true ? chatJid : this.host.normalizedSelfJid();
+ const revoked: RevokedMessage = {
+ id: pm.key?.id ?? '',
+ // The REVOKE protocolMessage's key points at the ORIGINAL deleted message,
+ // so `id` already IS the original here. Mirror it into `revokedId` so that
+ // field is the reliable cross-engine handle (wwebjs sets it separately).
+ revokedId: pm.key?.id ?? undefined,
+ chatId: this.host.toNeutralJid(chatJid),
+ from: this.host.toNeutralJid(from),
+ to: this.host.toNeutralJid(to),
+ type: 'revoked',
+ body: '',
+ timestamp: toUnixSeconds(msg.messageTimestamp),
+ };
+ await this.recordPreviewChange(chatJid, revoked.id, '', 'revoked', opts.generation);
+ if (opts.generation !== this.storeGeneration) return;
+ // While the target is still being processed, the store change waits for it and lands after
+ // this delete is announced, and a repeat delivery may already hold the content in the store:
+ // record the delete now, checked against the target's own key.
+ const target = this.inboundInFlight.get(revoked.id);
+ if (target && this.mayChange(target.key, msg.key, true)) {
+ this.markDeletedForEveryone(revoked.id);
+ }
+ // The stored copy keeps its key, so a late re-delivery is still recognised and a delete
+ // for me can still address it, but loses its content, so nothing can quote or resend it.
+ const resolveStored = await this.reportedPhones(
+ (await this.readTarget(revoked.id, 'reading a delete target'))?.key,
+ msg.key,
+ );
+ if (opts.generation !== this.storeGeneration) return;
+ this.changeStoredMessage(pm.key?.id, stored =>
+ this.mayChange(stored.key, msg.key, true, resolveStored) ? { ...stored, message: null } : null,
+ );
+ // Behind the reactions and edits of the message that wait for its emit, never for the message itself:
+ // the delete keeps it from being emitted, and they were made before it.
+ this.announceWhenHandedOn(
+ revoked.id,
+ opts.ticket,
+ () => this.host.getOnMessageRevoked()?.(revoked, { fromMe: msg.key.fromMe === true }),
+ true,
+ );
+ return;
+ }
+ if (pm?.type === b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT) {
+ // MESSAGE_EDIT wraps the message's latest content. Normalize that INNER content separately
+ // so captions, type, PTT, media presence and mentions describe the edited value rather than
+ // the outer protocol envelope.
+ const normalizedEdited = b.normalizeMessageContent(pm.editedMessage ?? undefined) ?? pm.editedMessage ?? {};
+ const editedContentType = b.getContentType(normalizedEdited);
+ const editedSubMessage =
+ normalizedEdited.extendedTextMessage ??
+ normalizedEdited.imageMessage ??
+ normalizedEdited.videoMessage ??
+ normalizedEdited.audioMessage ??
+ normalizedEdited.documentMessage ??
+ normalizedEdited.stickerMessage ??
+ normalizedEdited.locationMessage;
+ const contextInfo = editedSubMessage?.contextInfo;
+ const base = buildIncomingMessageFromBaileys(
+ {
+ id: pm.key?.id ?? '',
+ remoteJid,
+ fromMe: msg.key.fromMe === true,
+ participant: keyParticipant(msg.key),
+ body: extractBaileysBody(normalizedEdited),
+ contentType: editedContentType,
+ isPtt: normalizedEdited.audioMessage?.ptt === true,
+ timestamp: this.toEditUnixSeconds(pm.timestampMs, msg.messageTimestamp),
+ selfJid: this.host.normalizedSelfJid(),
+ mentionedJids: contextInfo?.mentionedJid ?? undefined,
+ },
+ jid => this.host.toNeutralJid(jid),
+ );
+ const hasMedia =
+ editedContentType === 'imageMessage' ||
+ editedContentType === 'videoMessage' ||
+ editedContentType === 'audioMessage' ||
+ editedContentType === 'documentMessage' ||
+ editedContentType === 'documentWithCaptionMessage' ||
+ editedContentType === 'stickerMessage';
+ const edited: EditedMessage = buildEditedMessage(base, hasMedia);
+ await this.recordPreviewChange(chatJid, edited.messageId, edited.body, undefined, opts.generation);
+ if (opts.generation !== this.storeGeneration) return;
+ const target = this.inboundInFlight.get(edited.messageId);
+ if (target && this.mayChange(target.key, msg.key, false)) {
+ const earlier = this.editedWhileInFlight.get(edited.messageId);
+ const afterOtherText = !!earlier && (earlier.afterOtherText || earlier.body !== edited.body);
+ this.editedWhileInFlight.delete(edited.messageId); // re-inserted as the newest
+ this.editedWhileInFlight.set(edited.messageId, { envelope: msg.key, body: edited.body, afterOtherText });
+ if (this.editedWhileInFlight.size > BaileysEvents.DELETED_FOR_EVERYONE_LIMIT) {
+ const [oldest] = this.editedWhileInFlight.keys();
+ this.editedWhileInFlight.delete(oldest);
+ }
+ }
+ const resolveStored = await this.reportedPhones(
+ (await this.readTarget(edited.messageId, 'reading an edit target'))?.key,
+ msg.key,
+ );
+ if (opts.generation !== this.storeGeneration) return;
+ this.changeStoredMessage(edited.messageId, stored => {
+ const content = this.mayChange(stored.key, msg.key, false, resolveStored)
+ ? b.normalizeMessageContent(stored.message ?? undefined)
+ : undefined;
+ return content && setBaileysText(content, edited.body) ? stored : null;
+ });
+ this.announceWhenHandedOn(edited.messageId, opts.ticket, () => this.host.getOnMessageEdited()?.(edited));
+ return;
+ }
+ // Other protocol messages (ephemeral, history sync, etc.) — skip silently.
+ return;
+ }
+
+ // --- reactionMessage: don't emit onMessage ---
+ if (contentType === 'reactionMessage') {
+ const rm = normalizedRoot?.reactionMessage;
+ if (opts.generation !== this.storeGeneration) return;
+ const event: ReactionEvent = {
+ messageId: rm?.key?.id ?? '',
+ chatId: this.host.toNeutralJid(chatJid),
+ reaction: rm?.text ?? '',
+ // A 1:1 key names the chat partner, not the author: for a reaction the account made from
+ // its phone (fromMe) the reactor is the account itself. Group and status keys carry the
+ // author as `participant`, own reactions included, which the edit branch reads the same way.
+ senderId: this.host.toNeutralJid(
+ keyParticipant(msg.key) ?? (msg.key.fromMe === true ? this.host.normalizedSelfJid() : remoteJid),
+ ),
+ };
+ this.announceWhenHandedOn(rm?.key?.id, opts.ticket, () => this.host.getOnMessageReaction()?.(event));
+ return;
+ }
+ }
+
/**
* Announce a reaction, an edit or a delete of message `id`. With a ticket the session holds the message from
* its arrival and keeps the change for its row, so it is announced at once. Without one the session knows
@@ -1247,7 +1414,11 @@ export class BaileysEvents {
key: WAMessageKey,
checkAuthor: boolean,
kind?: 'reaction',
- inbound?: { ticket?: InboundTicket; yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R> },
+ inbound?: {
+ ticket?: InboundTicket;
+ yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R>;
+ releasePreparation?: () => void;
+ },
): Promise<boolean> {
if (!targetId) return false;
// The key a wait was for (the delivery in flight, or the copy the change read as foreign to), and the
@@ -1318,12 +1489,17 @@ export class BaileysEvents {
private async parkUntil(
until: Promise<void>,
limitMs: number,
- inbound?: { ticket?: InboundTicket; yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R> },
+ inbound?: {
+ ticket?: InboundTicket;
+ yieldSlot?: <R>(fn: () => Promise<R>) => Promise<R>;
+ releasePreparation?: () => void;
+ },
): Promise<boolean> {
if (this.changesParked >= BaileysEvents.CHANGES_PARKED_LIMIT) return false;
this.changesParked++;
try {
- inbound?.ticket?.drop();
+ inbound?.releasePreparation?.();
+ if (!inbound?.releasePreparation) inbound?.ticket?.drop();
const wait = (): Promise<void> =>
new Promise<void>(resolve => {
let wake: (() => void) | null = resolve;
@@ -1380,7 +1556,13 @@ export class BaileysEvents {
change: (stored: WAMessage) => WAMessage | null,
): void {
if (!messageId) return;
- const apply = async (): Promise<void> => this.host.updateStoredMessage(messageId, change);
+ const generation = this.storeGeneration;
+ const apply = async (): Promise<void> => {
+ if (generation !== this.storeGeneration) return;
+ await this.host.updateStoredMessage(messageId, stored =>
+ generation === this.storeGeneration ? change(stored) : null,
+ );
+ };
const inFlight = this.inboundInFlight.get(messageId)?.done;
void (inFlight ? inFlight.then(apply) : apply()).catch(err =>
this.host.logger.warn('Failed to apply an edit or delete to the message store', {
@@ -1395,16 +1577,50 @@ export class BaileysEvents {
* checks neither the chat nor the sender of either (Utils/process-message.js), so the stored copy
* changes only for one from the same chat and from the message's author. A group admin may delete
* anyone's message, which nothing here can verify, so a group delete skips the author check.
- * Compared in the neutral dialect, and through each key's alt twin as targetsForeignMessage does, so
- * a chat or sender seen by lid once and by phone once matches even when the pair is not yet known.
+ * Compare raw identities and incoming alt pairs. A stored LID/phone pair matches only through a
+ * reported directory lookup; own-message senderAlt is not proof of the recipient's phone.
*/
- private mayChange(target: WAMessageKey, envelope: WAMessageKey, isDelete: boolean): boolean {
+ private async reportedPhones(...keys: Array<WAMessageKey | undefined>): Promise<(jid: string) => string | null> {
+ const lids = new Set(
+ keys
+ .flatMap(key => [key?.remoteJid, key?.participant])
+ .filter((jid): jid is string => !!jid && parseWaId(jid).kind === 'lid'),
+ );
+ const pairs = new Map<string, string>();
+ await Promise.all(
+ [...lids].map(async lid => {
+ const phone = await this.host.findPersistedLidPhone?.(lid).catch(() => null);
+ if (phone) pairs.set(userPart(lid), phone);
+ }),
+ );
+ return jid => pairs.get(userPart(jid)) ?? null;
+ }
+
+ private mayChange(
+ target: WAMessageKey,
+ envelope: WAMessageKey,
+ isDelete: boolean,
+ resolve?: (jid: string) => string | null,
+ ): boolean {
const neutral = (jids: Array<string | null | undefined>): string[] =>
jids.filter((jid): jid is string => !!jid).map(jid => this.host.toNeutralJid(jid));
- const chat = (key: WAMessageKey): string[] => neutral([key.remoteJid, key.remoteJidAlt]);
+ const chat = (key: WAMessageKey): string[] => neutral([key.remoteJid, key.fromMe ? undefined : key.remoteJidAlt]);
const author = (key: WAMessageKey): string[] =>
key.fromMe === true ? ['fromMe'] : key.participant ? neutral([key.participant, key.participantAlt]) : chat(key);
- const overlap = (a: string[], b: string[]): boolean => a.some(jid => b.includes(jid));
+ const overlap = (a: string[], b: string[]): boolean => {
+ if (parseWaId(a[0] ?? '').kind === 'lid' && parseWaId(b[0] ?? '').kind === 'lid' && a[0] !== b[0]) return false;
+ return a.some(left =>
+ b.some(right => {
+ if (left === right) return true;
+ const l = parseWaId(left).kind;
+ const r = parseWaId(right).kind;
+ return (
+ (l === 'lid' && r === 'user' && resolve?.(left) === userPart(right)) ||
+ (r === 'lid' && l === 'user' && resolve?.(right) === userPart(left))
+ );
+ }),
+ );
+ };
if (!overlap(chat(target), chat(envelope))) return false;
const inGroup = chat(target).some(jid => parseWaId(jid).kind === 'group');
return (isDelete && inGroup) || overlap(author(target), author(envelope));
diff --git a/src/engine/adapters/baileys-history-revokes.spec.ts b/src/engine/adapters/baileys-history-revokes.spec.ts
index 986dad010..f016cfc13 100644
--- a/src/engine/adapters/baileys-history-revokes.spec.ts
+++ b/src/engine/adapters/baileys-history-revokes.spec.ts
@@ -84,7 +84,7 @@ describe('Baileys history revokes', () => {
normalizeMessageContent: (m: unknown) => m,
getContentType: (m: object) => Object.keys(m)[0],
extractMessageContent: (m: unknown) => m,
- proto: { Message: { ProtocolMessage: { Type: { REVOKE: 0 } } } },
+ proto: { Message: { ProtocolMessage: { Type: { REVOKE: 0, MESSAGE_EDIT: 14 } } } },
downloadMediaMessage: () =>
new Promise(resolve => {
releaseMedia = () =>
@@ -318,6 +318,128 @@ describe('Baileys history revokes', () => {
expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(target().message);
});
+ it('keeps distinct raw LIDs separate even when both keys carry the same phone', async () => {
+ const original = target({ key: { id: 'M1', remoteJid: '111@lid', remoteJidAlt: CHAT, fromMe: false } });
+ await raw.put('s1', original);
+ const applying = events.applyHistoryRevoke(original.key, {
+ remoteJid: '222@lid',
+ remoteJidAlt: CHAT,
+ fromMe: false,
+ });
+ expect(await applying).toBeUndefined();
+ expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(original.message);
+ });
+
+ it('does not apply a history revoke whose directory lookup outlives unlinking', async () => {
+ await raw.put('s1', target());
+ let release!: (phone: string) => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ (events as unknown as { host: BaileysEventsHost }).host.findPersistedLidPhone = () => {
+ entered();
+ return new Promise(resolve => {
+ release = resolve;
+ });
+ };
+ const applying = events.applyHistoryRevoke(target().key, { remoteJid: '111@lid', fromMe: false });
+ await started;
+ events.fenceStoredWrites();
+ release('628111');
+ expect(await applying).toBeUndefined();
+ expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(target().message);
+ });
+
+ it.each([
+ ['edit', 'preview'],
+ ['edit', 'stored'],
+ ['revoke', 'preview'],
+ ['revoke', 'stored'],
+ ] as const)('does not resume a live %s after its %s lookup outlives reset', async (kind, phase) => {
+ await raw.put('s1', target());
+ previews.upsertChats([{ id: CHAT }]);
+ previews.recordMessage(target());
+ let release!: (phone: string) => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const host = (events as unknown as { host: BaileysEventsHost }).host;
+ const phone = new Promise<string>(resolve => {
+ release = resolve;
+ });
+ let reads = 0;
+ host.findPersistedLidPhone = () => {
+ reads++;
+ if (reads !== (phase === 'preview' ? 1 : 2)) return Promise.resolve('628111');
+ entered();
+ return phone;
+ };
+ host.getOnMessageEdited = () => liveFanout;
+ const change =
+ kind === 'revoke'
+ ? revoke(target().key, { remoteJid: '111@lid' })
+ : {
+ key: { id: 'EDIT', remoteJid: '111@lid', fromMe: false },
+ message: {
+ protocolMessage: { type: 14, key: { id: 'M1' }, editedMessage: { conversation: 'old connection edit' } },
+ },
+ messageTimestamp: 1700000100,
+ };
+ events.handleMessagesUpsert({ type: 'notify', messages: [change] });
+ await started;
+ const jobs = [
+ ...(events as unknown as { inboundInFlight: Map<string, { done: Promise<void> }> }).inboundInFlight.values(),
+ ].map(job => job.done);
+ events.fenceStoredWrites();
+ await raw.clearSession('s1');
+ const current = target({ message: { conversation: 'current connection body' } });
+ await raw.put('s1', current);
+ previews = new BaileysSessionStore(undefined, 's1');
+ previews.upsertChats([{ id: CHAT }]);
+ previews.recordMessage(current);
+ release('628111');
+ await Promise.all(jobs);
+ for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
+ expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(current.message);
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')?.lastMessage).toBe('current connection body');
+ expect(liveFanout).not.toHaveBeenCalled();
+ });
+
+ it('does not bridge a history preview after its directory lookup outlives reset', async () => {
+ let generation = 0;
+ let release!: (phone: string) => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const host = (history as unknown as { host: BaileysHistoryHost & { getStoredWriteGeneration?: () => number } })
+ .host;
+ host.getStoredWriteGeneration = () => generation;
+ const phone = new Promise<string>(resolve => {
+ release = resolve;
+ });
+ host.findPersistedLidPhone = () => {
+ entered();
+ return phone;
+ };
+ onHistory.mockImplementationOnce((messages: IncomingMessage[]) =>
+ Promise.resolve(messages.map(message => ({ ...message, type: 'revoked', body: '' }))),
+ );
+ const capturing = history.captureHistoryMessages([
+ target({ key: { id: 'M1', remoteJid: '111@lid', fromMe: false } }),
+ ]);
+ await started;
+ generation++;
+ previews = new BaileysSessionStore(undefined, 's1');
+ previews.upsertChats([{ id: CHAT }]);
+ previews.recordMessage(target({ message: { conversation: 'current connection body' } }));
+ release('628111');
+ await capturing;
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')?.lastMessage).toBe('current connection body');
+ });
+
it('clears old content with retention enabled without inserting old content again', async () => {
await capture([target()]);
const previous = process.env.MESSAGE_RETENTION_DAYS;
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index 633b7f0eb..23d3975e5 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -1,3 +1,4 @@
+import { parseWaId } from '../identity/wa-id';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
import { EngineEventCallbacks, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
@@ -26,6 +27,7 @@ export interface BaileysHistoryHost {
getSocket(): WASocket;
readonly logger: ReturnType<typeof createLogger>;
toNeutralJid(jid: string): string;
+ findPersistedLidPhone?(jid: string): Promise<string | null>;
normalizedSelfJid(): string;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
loadLib(): Promise<typeof BaileysLib>;
@@ -45,6 +47,7 @@ export interface BaileysHistoryHost {
extractEphemeralDuration(msg: WAMessage): number | undefined;
/** The currently-registered onHistoryMessages callback, if any (assigned at initialize()). */
getOnHistoryMessages(): EngineEventCallbacks['onHistoryMessages'];
+ getStoredWriteGeneration?(): number;
}
/**
@@ -105,7 +108,10 @@ export class BaileysHistory {
if (!messages.length) {
return;
}
+ const generation = this.host.getStoredWriteGeneration?.();
+ const current = (): boolean => generation === this.host.getStoredWriteGeneration?.();
const b = await this.host.loadLib();
+ if (!current()) return;
const nameUpdates: { id: string; notify: string }[] = [];
const mapped: IncomingMessage[] = [];
const revokes: { message: WAMessage; target: WAMessageKey }[] = [];
@@ -135,6 +141,7 @@ export class BaileysHistory {
original?.key ?? { ...target, remoteJid: target.remoteJid ?? message.key.remoteJid },
message.key,
);
+ if (!current()) return;
if (!key?.remoteJid) continue;
const cleared = this.revokedMessage(key, toUnixSeconds(original?.messageTimestamp ?? message.messageTimestamp));
mapped.push(cleared);
@@ -144,6 +151,7 @@ export class BaileysHistory {
}
if (mapped.length) {
const storedRevokes = await this.host.getOnHistoryMessages()?.(mapped);
+ if (!current()) return;
const revoked = (storedRevokes ?? mapped).filter(m => m.type === 'revoked');
const revokedKeys = new Set(revoked.map(m => JSON.stringify([m.id, m.chatId, m.fromMe])));
for (const incoming of mapped) {
@@ -152,7 +160,14 @@ export class BaileysHistory {
const deleted = revokedKeys.has(JSON.stringify([incoming.id, incoming.chatId, incoming.fromMe]));
this.host.recordMessage(original, deleted ? 'revoked' : incoming.type);
}
- for (const m of revoked) this.host.recordMessageEdit(m.chatId, m.id, '', 'revoked');
+ for (const m of revoked) {
+ this.host.recordMessageEdit(m.chatId, m.id, '', 'revoked');
+ if (parseWaId(m.chatId).kind === 'lid') {
+ const phone = await this.host.findPersistedLidPhone?.(m.chatId).catch(() => null);
+ if (!current()) return;
+ if (phone) this.host.recordMessageEdit(`${phone}@s.whatsapp.net`, m.id, '', 'revoked');
+ }
+ }
}
}
diff --git a/src/engine/adapters/baileys-identity-query.ts b/src/engine/adapters/baileys-identity-query.ts
new file mode 100644
index 000000000..16a8f5c2a
--- /dev/null
+++ b/src/engine/adapters/baileys-identity-query.ts
@@ -0,0 +1,30 @@
+import type * as BaileysLib from '@whiskeysockets/baileys';
+import type { WASocket } from '@whiskeysockets/baileys';
+import { parseWaId, userPart } from '../identity/wa-id';
+import { withQueryDeadline } from './baileys-query-deadline';
+
+/** Confirm a phone/LID pair with the public server query, without reading Baileys' signal cache. */
+export async function queryLidPhone(
+ socket: WASocket,
+ library: typeof BaileysLib,
+ phone: string,
+ lid: string,
+ budgetMs: number,
+): Promise<boolean> {
+ const query = new library.USyncQuery()
+ .withLIDProtocol()
+ .withContext('background')
+ .withUser(new library.USyncUser().withId(`${phone}@s.whatsapp.net`));
+ const result = await withQueryDeadline(
+ socket.executeUSyncQuery(query),
+ budgetMs,
+ 'WhatsApp did not answer the LID identity query in time',
+ );
+ const matches = result?.list.filter(row => parseWaId(row.id).kind === 'user' && userPart(row.id) === phone);
+ return (
+ matches?.length === 1 &&
+ typeof matches[0].lid === 'string' &&
+ parseWaId(matches[0].lid).kind === 'lid' &&
+ userPart(matches[0].lid) === lid
+ );
+}
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index b843f2674..2913a7195 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -20,6 +20,7 @@ import {
mapBaileysMessageType,
mapBaileysStatus,
setBaileysText,
+ storedKeyInChatPersisted,
} from './baileys-message-mapper';
describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)', () => {
@@ -1310,3 +1311,29 @@ describe('native poll choice metadata', () => {
});
});
});
+
+describe('storedKeyInChatPersisted', () => {
+ it('accepts an exact identity without requiring a directory', async () => {
+ expect(await storedKeyInChatPersisted({ remoteJid: '111@lid' }, '111@lid')).toBe(true);
+ expect(await storedKeyInChatPersisted({ remoteJid: '[email protected]' }, '[email protected]')).toBe(true);
+ });
+
+ it('refuses cross-form identity when no directory is available', async () => {
+ expect(await storedKeyInChatPersisted({ remoteJid: '111@lid' }, '[email protected]')).toBe(false);
+ expect(await storedKeyInChatPersisted({ remoteJid: '[email protected]' }, '111@lid')).toBe(false);
+ });
+
+ it.each([null, '628222', '628111'])('uses only the reported pairing %s in either direction', async phone => {
+ const resolve = () => Promise.resolve(phone);
+ expect(await storedKeyInChatPersisted({ remoteJid: '111@lid' }, '[email protected]', resolve)).toBe(phone === '628111');
+ expect(await storedKeyInChatPersisted({ remoteJid: '[email protected]' }, '111@lid', resolve)).toBe(
+ phone === '628111',
+ );
+ });
+
+ it('keeps distinct raw LIDs separate even if a directory maps both to one phone', async () => {
+ expect(await storedKeyInChatPersisted({ remoteJid: '111@lid' }, '222@lid', () => Promise.resolve('628111'))).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index ebd47af6d..51c164199 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -5,7 +5,7 @@ import {
IncomingMessage,
MessageType,
} from '../interfaces/whatsapp-engine.interface';
-import { chatKind } from '../identity/wa-id';
+import { chatKind, parseWaId, toNeutralJid } from '../identity/wa-id';
import { boundPollOptions, boundPollText } from './message-mapper';
/**
@@ -1064,6 +1064,25 @@ export function storedKeyInChat(
return neutral(raw) === want || neutral(baileysChatJid(raw, key.participant, key.fromMe === true)) === want;
}
+/** Match a stored LID/phone alias only through a reported persisted pairing. */
+export async function storedKeyInChatPersisted(
+ key: { remoteJid?: string | null; participant?: string | null; fromMe?: boolean | null },
+ chatId: string,
+ resolveLid?: (jid: string) => Promise<string | null>,
+): Promise<boolean> {
+ if (storedKeyInChat(key, chatId, toNeutralJid)) return true;
+ if (!resolveLid) return false;
+ const want = parseWaId(chatId);
+ for (const raw of [key.remoteJid ?? '', baileysChatJid(key.remoteJid ?? '', key.participant, key.fromMe === true)]) {
+ const stored = parseWaId(raw);
+ if (!((stored.kind === 'lid' && want.kind === 'user') || (stored.kind === 'user' && want.kind === 'lid'))) continue;
+ const lid = stored.kind === 'lid' ? raw : chatId;
+ const phone = stored.kind === 'user' ? stored.userPart : want.userPart;
+ if ((await resolveLid(lid).catch(() => null)) === phone) return true;
+ }
+ return false;
+}
+
/**
* The participant a live key names, or undefined when it names none. Baileys passes every live key
* through cleanMessage, which writes jidNormalizedUser(participant) back, and that is '' for the absent
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index e0d677f4d..ac77e161d 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -1,3 +1,4 @@
+import { queryLidPhone } from './baileys-identity-query';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type {
AnyMessageContent,
@@ -31,7 +32,7 @@ import {
mapBaileysMessageType,
resolveBaileysButtonClick,
setBaileysText,
- storedKeyInChat,
+ storedKeyInChatPersisted,
} from './baileys-message-mapper';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
import { BadRequestException, InternalServerErrorException } from '@nestjs/common';
@@ -63,6 +64,7 @@ export interface BaileysMessagingHost {
readonly logger: ReturnType<typeof createLogger>;
toNeutralJid(jid: string): string;
toEngineJid(jid: string): string;
+ findPersistedLidPhone?(jid: string): Promise<string | null>;
normalizedSelfJid(): string;
/** The chat's cached disappearing-messages timer (#473), or undefined when none is known. */
getEphemeralExpiration(chatId: string): number | undefined;
@@ -89,7 +91,7 @@ export interface BaileysMessagingHost {
/** The text of an edit of this message the stored copy with key `target` does not show yet, if any. */
pendingEditOf(messageId: string, target: WAMessageKey): string | undefined;
/** Remember a lid<->phone pair the socket resolved, so later reads do not have to ask again. */
- recordLidMapping(lid: string, pn: string): void;
+ recordLidMapping(lid: string, pn: string, isReported?: boolean): void;
/** The currently-registered onMessageCreate callback, if any (assigned at initialize()). */
getOnMessageCreate(): EngineEventCallbacks['onMessageCreate'];
/** Map a WAMessage to its neutral shape (the adapter's inbound mapper). */
@@ -297,8 +299,10 @@ export class BaileysMessaging {
}
/** Post-ensureReady socket handle. */
- private sock(): WASocket {
- return this.host.getSocket();
+ private sock(expected?: WASocket): WASocket {
+ const socket = this.host.getSocket();
+ if (expected && socket !== expected) throw new EngineNotReadyError();
+ return socket;
}
async sendTextMessage(
@@ -613,6 +617,7 @@ export class BaileysMessaging {
async replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {
this.host.ensureReady();
+ const socket = this.sock();
const quoted = await this.requireStored(quotedMsgId);
// The one requireStored path that had no chat check. whatsapp-web.js resolves the quote by
// fetching from the named chat and 404s when the id is not in it, so the same request replied
@@ -620,8 +625,8 @@ export class BaileysMessaging {
// contextInfo rather than rejecting it (Utils/messages.js), so the adapter is the only guard.
// NOT applied to quoteOption: cross-chat quoting on the send-* routes is deliberate and
// published in docs/06.
- this.assertStoredInChat(quoted, chatId, quotedMsgId);
- return this.sendContent(chatId, { text, ...this.withMentions(mentions) }, { quoted });
+ await this.assertStoredInChat(quoted, chatId, quotedMsgId, socket);
+ return this.sendContent(chatId, { text, ...this.withMentions(mentions) }, { quoted }, socket);
}
/**
@@ -635,8 +640,9 @@ export class BaileysMessaging {
*/
async clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult> {
this.host.ensureReady();
+ const socket = this.sock();
const quoted = await this.requireStored(messageId);
- this.assertStoredInChat(quoted, chatId, messageId);
+ await this.assertStoredInChat(quoted, chatId, messageId, socket);
const b = await this.host.loadLib();
const normalized = b.normalizeMessageContent(quoted.message ?? undefined) ?? quoted.message ?? {};
@@ -653,33 +659,41 @@ export class BaileysMessaging {
);
}
- const result = await this.sendContent(chatId, resolved.payload.content as AnyMessageContent, { quoted });
+ const result = await this.sendContent(chatId, resolved.payload.content as AnyMessageContent, { quoted }, socket);
return { ...result, body: resolved.payload.text };
}
async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {
this.host.ensureReady();
+ const socket = this.sock();
const forward = await this.requireStored(messageId);
// fromChatId was accepted and then ignored, so a message id from ANY chat forwarded successfully
// while whatsapp-web.js answered 404 for the same request (it fetches from the named chat and
// fails when the id is not in it). Same check the star and react paths already apply.
- this.assertStoredInChat(forward, fromChatId, messageId);
- return this.sendContent(toChatId, { forward });
+ await this.assertStoredInChat(forward, fromChatId, messageId, socket);
+ return this.sendContent(toChatId, { forward }, undefined, socket);
}
async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
const target = await this.requireStored(messageId);
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
// Resolved like any other send: a lid-migrated contact rejects PN-addressed sends (ack 463).
- await this.send(await this.toDeliverableJid(chatId), { react: { text: emoji, key: target.key } });
+ await this.send(
+ await this.toDeliverableJid(chatId, socket),
+ { react: { text: emoji, key: target.key } },
+ undefined,
+ socket,
+ );
}
async deleteMessage(chatId: string, messageId: string, forEveryone = true): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
// A message already deleted for everyone can still be deleted for me: that clears its placeholder.
const target = await this.requireStored(messageId, true);
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
// Only the sender, or a group admin, can delete a message for everyone. WhatsApp ignores any other
// revoke, yet the send resolves, so it would report a deletion that never happened. WhatsApp Web
// deletes such a message for the account alone instead, and so does this. A group whose member
@@ -688,8 +702,11 @@ export class BaileysMessaging {
const chatJid = target.key.remoteJid ?? chatId;
// The preview of a received broadcast-list message is kept in its sender's chat.
const previewJid = baileysChatJid(chatJid, target.key.participant, target.key.fromMe === true);
- if (forEveryone && (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid)) !== false)) {
- await this.send(await this.toDeliverableJid(chatId), { delete: target.key });
+ if (
+ forEveryone &&
+ (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid, socket)) !== false)
+ ) {
+ await this.send(await this.toDeliverableJid(chatId, socket), { delete: target.key }, undefined, socket);
this.host.recordMessageEdit(previewJid, messageId, '', 'revoked');
// Clear the stored copy before the buffered echo arrives. Record the deletion first so it
// survives a failed store write or a repeat delivery of the original.
@@ -700,7 +717,7 @@ export class BaileysMessaging {
// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a
// sendMessage. The stored message timestamp (epoch seconds) is part of the payload.
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{
deleteForMe: {
deleteMedia: true,
@@ -721,23 +738,25 @@ export class BaileysMessaging {
* Whether the account is an admin of this chat: false for anything that is not a group, and
* undefined when no participant row can be identified as the account.
*/
- private async selfIsGroupAdmin(jid: string | null | undefined): Promise<boolean | undefined> {
+ private async selfIsGroupAdmin(jid: string | null | undefined, socket?: WASocket): Promise<boolean | undefined> {
if (!jid?.endsWith('@g.us')) return false;
const metadata = await withQueryDeadline(
- this.sock().groupMetadata(jid),
+ this.sock(socket).groupMetadata(jid),
this.queryBudgetMs,
'WhatsApp did not answer the group metadata query in time',
);
+ if (socket) this.sock(socket);
const self = findSelfParticipant(metadata, this.host.normalizedSelfJid(), id => this.host.toNeutralJid(id));
return self === undefined ? undefined : self.admin === 'admin' || self.admin === 'superadmin';
}
async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {
this.host.ensureReady();
+ const socket = this.sock();
const target = await this.requireStored(messageId);
// The chat check comes first so a message from another chat answers not-found whichever side
// sent it; checking fromMe first would tell an inbound message there from an own one.
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
// Only the account's own messages are editable: WhatsApp refuses the edit of an inbound message
// but the send would still resolve, dressing the refusal up as success (and the service layer
// would then "update" the stored body). Refuse first — mirrors the wwjs null-edit guard.
@@ -749,7 +768,7 @@ export class BaileysMessaging {
// An edit keeps the original message id, so it is neither re-persisted nor echoed as a new send.
// The destination is resolved like any other send: a lid-migrated contact rejects PN-addressed
// sends with ack error 463 (see toDeliverableJid).
- const jid = await this.toDeliverableJid(chatId);
+ const jid = await this.toDeliverableJid(chatId, socket);
// Same guard as sendContent: an edit carries text, so without it the library would fetch
// every URL in the new body through its own vulnerable generator.
// Tags are applied to the inner message's contextInfo BEFORE the library wraps it in the
@@ -757,7 +776,7 @@ export class BaileysMessaging {
// content, so omitting mentions drops whatever tags the original carried.
const editContent = { text: body, ...this.withMentions(mentions), edit: target.key };
const b = await this.host.loadLib();
- await this.send(jid, this.previewSafe(editContent), this.previewSafeOptions(editContent));
+ await this.send(jid, this.previewSafe(editContent), this.previewSafeOptions(editContent), socket);
// Update the preview and raw copy immediately, ahead of the buffered echo.
this.host.recordMessageEdit(target.key.remoteJid ?? chatId, messageId, body);
// A later quote must carry the updated text even before the edit's echo arrives.
@@ -790,7 +809,8 @@ export class BaileysMessaging {
* same send addressed to the LID delivers (verified live). Unmapped phone ids still need the
* canonical Baileys domain; the library does not rewrite a neutral @c.us destination.
*/
- private async toDeliverableJid(chatId: string): Promise<string> {
+ private async toDeliverableJid(chatId: string, expected?: WASocket): Promise<string> {
+ if (expected) this.sock(expected);
const { kind, userPart: user } = parseWaId(chatId);
if (kind === 'lid') return `${user}@lid`;
if (kind !== 'user') return chatId;
@@ -807,7 +827,7 @@ export class BaileysMessaging {
// becomes known before any message arrives, and without writing it back the session store
// still believes the two ids are unrelated — which makes an ownership check comparing the
// stored key's lid against a phone-dialect chatId reject a message that IS in that chat.
- if (lid) this.host.recordLidMapping(`${userPart(lid)}@lid`, pn);
+ if (lid) this.host.recordLidMapping(`${userPart(lid)}@lid`, pn, false);
return lid ? `${userPart(lid)}@lid` : pn;
} catch (error) {
if (this.host.getSocketOrNull() !== sock || error instanceof EngineNotReadyError) throw new EngineNotReadyError();
@@ -870,12 +890,15 @@ export class BaileysMessaging {
chatId: string,
content: AnyMessageContent,
options?: MiscMessageGenerationOptions,
+ expected?: WASocket,
): Promise<MessageResult> {
+ if (expected) this.sock(expected);
const b = await this.host.loadLib();
- const jid = await this.toDeliverableJid(chatId);
+ if (expected) this.sock(expected);
+ const jid = await this.toDeliverableJid(chatId, expected);
const safe = this.previewSafe(content);
const merged = this.previewSafeOptions(safe, this.withEphemeral(jid, options));
- const sent = await this.send(jid, safe, merged);
+ const sent = await this.send(jid, safe, merged, expected);
if (sent) {
void this.host.putStoredMessage(sent)?.catch(err =>
this.host.logger.warn('Failed to persist sent message to store', {
@@ -922,8 +945,9 @@ export class BaileysMessaging {
jid: string,
content: Parameters<WASocket['sendMessage']>[1],
options?: Parameters<WASocket['sendMessage']>[2],
+ expected?: WASocket,
): Promise<WAMessage | undefined> {
- const sock = this.sock();
+ const sock = this.sock(expected);
if (parseWaId(jid).kind === 'user') {
let numberId: string | null;
try {
@@ -1030,16 +1054,46 @@ export class BaileysMessaging {
* so @c.us/@s.whatsapp.net (and a known lid<->pn twin) compare equal, and a received broadcast-list
* message is found under the sender chat it is reported in.
*/
- private assertStoredInChat(target: WAMessage, chatId: string, messageId: string): void {
- if (!storedKeyInChat(target.key, chatId, jid => this.host.toNeutralJid(jid))) {
- throw new MessageNotFoundError(messageId, chatId);
+ private async assertStoredInChat(
+ target: WAMessage,
+ chatId: string,
+ messageId: string,
+ socket: WASocket,
+ ): Promise<void> {
+ this.sock(socket);
+ const persisted = await storedKeyInChatPersisted(
+ target.key,
+ chatId,
+ this.host.findPersistedLidPhone?.bind(this.host),
+ );
+ this.sock(socket);
+ if (persisted) return;
+ const requested = parseWaId(chatId);
+ const stored = parseWaId(
+ baileysChatJid(target.key.remoteJid ?? '', target.key.participant, target.key.fromMe === true),
+ );
+ if ((requested.kind === 'user' && stored.kind === 'lid') || (requested.kind === 'lid' && stored.kind === 'user')) {
+ const phone = requested.kind === 'user' ? requested.userPart : stored.userPart;
+ const lid = requested.kind === 'lid' ? requested.userPart : stored.userPart;
+ if (typeof socket.executeUSyncQuery === 'function') {
+ const library = await this.host.loadLib();
+ if (this.host.getSocketOrNull() !== socket) throw new EngineNotReadyError();
+ const confirmed = await queryLidPhone(socket, library, phone, lid, this.queryBudgetMs);
+ if (this.host.getSocketOrNull() !== socket) throw new EngineNotReadyError();
+ if (confirmed) {
+ this.host.recordLidMapping(`${lid}@lid`, `${phone}@s.whatsapp.net`);
+ return;
+ }
+ }
}
+ throw new MessageNotFoundError(messageId, chatId);
}
async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
const target = await this.requireStored(messageId);
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
// fromMe is load-bearing: the same message id addresses a different message depending on
// direction, so omitting it would star the wrong side of the conversation.
// chatModify keys the star app-state index by the raw jid (no jidNormalizedUser, unlike the send
@@ -1047,7 +1101,7 @@ export class BaileysMessaging {
// or the phone jid of a chat keyed by the contact's lid, would index a phantom chat and the star
// would silently apply to nothing.
await this.confirmed(
- this.sock().chatModify(
+ this.sock(socket).chatModify(
{ star: { messages: [{ id: target.key.id!, fromMe: target.key.fromMe ?? false }], star } },
this.host.toEngineJid(target.key.remoteJid ?? chatId),
),
@@ -1061,30 +1115,42 @@ export class BaileysMessaging {
*/
async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
const target = await this.requireStored(messageId);
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
// Read the enum through the LAZY loader rather than a static import. @whiskeysockets/baileys is
// pure ESM and every other site in this codebase defers it to first connect; a module-scope
// require would drag ~590 modules into boot even for whatsapp-web.js-only processes.
const { proto } = await this.host.loadLib();
- await this.send(await this.toDeliverableJid(chatId), {
- pin: target.key,
- type: proto.PinInChat.Type.PIN_FOR_ALL,
- // WhatsApp recognises only these three windows; the DTO rejects anything else before we
- // get here, so the cast documents the contract rather than widening it.
- time: durationSeconds as 86400 | 604800 | 2592000,
- });
+ await this.send(
+ await this.toDeliverableJid(chatId, socket),
+ {
+ pin: target.key,
+ type: proto.PinInChat.Type.PIN_FOR_ALL,
+ // WhatsApp recognises only these three windows; the DTO rejects anything else before we
+ // get here, so the cast documents the contract rather than widening it.
+ time: durationSeconds as 86400 | 604800 | 2592000,
+ },
+ undefined,
+ socket,
+ );
}
async unpinMessage(chatId: string, messageId: string): Promise<void> {
this.host.ensureReady();
+ const socket = this.sock();
const target = await this.requireStored(messageId);
- this.assertStoredInChat(target, chatId, messageId);
+ await this.assertStoredInChat(target, chatId, messageId, socket);
const { proto } = await this.host.loadLib();
// `time` is meaningless for an unpin and is omitted rather than sent as a dummy value.
- await this.send(await this.toDeliverableJid(chatId), {
- pin: target.key,
- type: proto.PinInChat.Type.UNPIN_FOR_ALL,
- });
+ await this.send(
+ await this.toDeliverableJid(chatId, socket),
+ {
+ pin: target.key,
+ type: proto.PinInChat.Type.UNPIN_FOR_ALL,
+ },
+ undefined,
+ socket,
+ );
}
}
diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.ts
index 83f0bbf3b..1ada2c18d 100644
--- a/src/engine/adapters/baileys-send-seen.spec.ts
+++ b/src/engine/adapters/baileys-send-seen.spec.ts
@@ -31,12 +31,15 @@ function makeHost(overrides: Partial<Record<keyof BaileysContactsHost, unknown>>
listContacts: () => [],
findContact: () => null,
resolvePhone: () => null,
+ findPersistedLidPhone: () => Promise.resolve(null),
listChats: () => [],
lastInboundMessage: () => ({ key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 }),
getStoredMessages: () => Promise.resolve([]),
toEngineJid,
...overrides,
} as unknown as BaileysContactsHost;
+ const socket = host.getSocket();
+ host.getSocket = () => socket;
// Wired the way the adapter wires it: the real fold, reading the session's lid mapping through
// this host's own resolvePhone, so a test can hand it a mapping and exercise the lid dialect.
host.toNeutralJid = (jid: string): string => toNeutralJid(jid, id => host.resolvePhone(id));
@@ -100,6 +103,7 @@ describe('sendSeen', () => {
const host = makeHost({
getSocket: () => ({ readMessages }) as unknown as WASocket,
resolvePhone: (jid: string) => (jid === '9988@lid' ? '628123' : null),
+ findPersistedLidPhone: (jid: string) => Promise.resolve(jid === '9988@lid' ? '628123' : null),
getStoredMessages: () =>
Promise.resolve([stored({ id: 'L1', remoteJid: '9988@lid', fromMe: true, participant: '9988@lid' })]),
});
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index 9bec3129f..53c2d14b0 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -124,16 +124,17 @@ describe('BaileysSessionStore', () => {
store.upsertContacts([{ id: '111@lid', name: 'Alice' }]);
store.upsertContacts([{ id: '[email protected]', lid: '111@lid', name: 'Alice' }]);
- expect(store.findContact('111@lid')).toMatchObject({ id: '[email protected]', name: 'Alice', number: '628111' });
+ expect(store.findContact('111@lid')).toMatchObject({ id: '111@lid', name: 'Alice', number: '628111' });
});
- it('lists a person once when both of their entries carry a saved name', () => {
+ it('keeps phone and LID contact identities distinct when both carry a saved name', () => {
// Both project to the same neutral id once the lid resolves, so listing both puts two rows
// sharing one id into GET /contacts.
store.upsertContacts([{ id: '111@lid', name: 'Alice' }]);
store.upsertContacts([{ id: '[email protected]', lid: '111@lid', name: 'Alice' }]);
expect(store.listContacts()).toEqual([
+ expect.objectContaining({ id: '111@lid', name: 'Alice', number: '628111' }),
expect.objectContaining({ id: '[email protected]', name: 'Alice', number: '628111' }),
]);
});
@@ -150,7 +151,7 @@ describe('BaileysSessionStore', () => {
]);
});
- it('folds two twins by content, not by which one was touched last', () => {
+ it('keeps each raw contact record stable when a lookup touches its LID', () => {
// The store is LRU-ordered, so iteration order tracks traffic: an inbound message touches the
// lid twin on every message. Letting order decide meant the list answered with whichever twin
// had been quiet, dropping a pushname the other had just learned and flipping back later.
@@ -159,27 +160,21 @@ describe('BaileysSessionStore', () => {
const first = store.listContacts();
expect(first).toEqual([
- {
- name: 'Alice',
- pushName: 'Ali', // filled from the lid twin, which is the only side that has one
- number: '628111', // and the number from the phone twin, which is the only side with that
- isMyContact: true,
- isBlocked: false,
- profilePicUrl: 'http://p/a.jpg',
- },
+ expect.objectContaining({ id: '111@lid', name: 'Alice', pushName: 'Ali', profilePicUrl: 'http://p/a.jpg' }),
+ expect.objectContaining({ id: '[email protected]', name: 'Alice', number: '628111', pushName: undefined }),
]);
// Touch the lid twin the way an inbound message does, moving it to the recent end, and read again.
expect(store.findContact('111@lid')).toBeTruthy();
- expect(store.listContacts()).toEqual(first);
+ expect(store.listContacts()).toHaveLength(first.length);
+ expect(store.listContacts()).toEqual(expect.arrayContaining(first));
});
it('accepts a contact keyed only by lid (id omitted) and finds it by phone', () => {
store.upsertContacts([{ lid: '111@lid', phoneNumber: '[email protected]', name: 'Ada' }]);
expect(store.findContact('111@lid')?.name).toBe('Ada');
expect(store.findContact('[email protected]')?.name).toBe('Ada');
- expect(store.listContacts()[0]).toMatchObject({ id: '[email protected]', name: 'Ada', number: '628111' });
+ expect(store.listContacts()[0]).toMatchObject({ id: '111@lid', name: 'Ada', number: '628111' });
});
it('drops groups/newsletters/status from the contact map (they are not address-book entries)', () => {
@@ -421,7 +416,7 @@ describe('BaileysSessionStore', () => {
});
});
- it('keeps the latest type across older messages, edits, and revokes addressed through a twin', () => {
+ it('keeps the latest type across older messages and edits of independent raw chats', () => {
store.addLidMappings([{ lid: '999@lid', pn: '[email protected]' }]);
store.upsertChats([{ id: '999@lid' }]);
store.recordMessage(
@@ -436,7 +431,7 @@ describe('BaileysSessionStore', () => {
},
'text',
);
- store.recordMessageEdit('[email protected]', 'LATEST', 'new caption');
+ store.recordMessageEdit('999@lid', 'LATEST', 'new caption');
expect(store.listChats()[0]).toMatchObject({
lastMessage: 'new caption',
lastMessageType: 'image',
@@ -444,7 +439,7 @@ describe('BaileysSessionStore', () => {
});
store.recordMessageEdit('[email protected]', 'OLD', '', 'revoked');
expect(store.listChats()[0].lastMessageType).toBe('image');
- store.recordMessageEdit('[email protected]', 'LATEST', '', 'revoked');
+ store.recordMessageEdit('999@lid', 'LATEST', '', 'revoked');
expect(store.listChats()[0]).toMatchObject({ lastMessage: '', lastMessageType: 'revoked', timestamp: 200 });
});
@@ -489,7 +484,8 @@ describe('BaileysSessionStore', () => {
});
store.upsertChats(chats.map(id => ({ id })));
store.recordMessageEdit(editedVia, 'M1', '');
- expect(store.listChats().map(c => c.lastMessage)).toEqual(['']);
+ expect(store.listChats().find(c => c.id === '999@lid')?.lastMessage).toBe(editedVia === '999@lid' ? '' : 'secret');
+ expect(store.listChats().find(c => c.id === '[email protected]')?.lastMessage).toBeUndefined();
});
it('flags a group chat by jid', () => {
@@ -742,6 +738,11 @@ describe('BaileysSessionStore', () => {
});
describe('recordKeyLidMappings (#362)', () => {
+ it('does not pair an own-message recipient with the sender phone carried as remoteJidAlt', () => {
+ store.recordKeyLidMappings({ remoteJid: '111@lid', remoteJidAlt: '[email protected]', fromMe: true });
+ expect(store.resolvePhone('111@lid')).toBeNull();
+ });
+
it('learns a lid->pn mapping from an inbound message key (remoteJid/remoteJidAlt)', () => {
store.recordKeyLidMappings({ remoteJid: '111@lid', remoteJidAlt: '[email protected]' });
expect(store.resolvePhone('111@lid')).toBe('628999');
@@ -752,10 +753,11 @@ describe('BaileysSessionStore', () => {
expect(store.resolvePhone('222@lid')).toBe('628222');
});
- it('canonicalizes a @lid to <phone>@c.us once the key mapping is learned', () => {
+ it('retains the LID identity after learning its phone for display', () => {
expect(store.toNeutralJid('111@lid')).toBe('111@lid'); // unknown yet
store.recordKeyLidMappings({ remoteJid: '111@lid', remoteJidAlt: '[email protected]' });
- expect(store.toNeutralJid('111@lid')).toBe('[email protected]');
+ expect(store.toNeutralJid('111@lid')).toBe('111@lid');
+ expect(store.resolvePhone('111@lid')).toBe('628111');
});
it('pairs the sender of a broadcast-list or status message with its alt, never the list id', () => {
@@ -810,10 +812,11 @@ describe('BaileysSessionStore', () => {
expect(store.toNeutralJid('')).toBe('');
});
- it('resolves a @lid to <phone>@c.us when known, else keeps the raw lid', () => {
+ it('retains the raw LID while its display phone is known', () => {
expect(store.toNeutralJid('111@lid')).toBe('111@lid'); // no mapping yet
store.addLidMappings([{ lid: '111@lid', pn: '[email protected]' }]);
- expect(store.toNeutralJid('111@lid')).toBe('[email protected]');
+ expect(store.toNeutralJid('111@lid')).toBe('111@lid');
+ expect(store.resolvePhone('111@lid')).toBe('628999');
});
it('is idempotent on an already-neutral @c.us id', () => {
@@ -866,20 +869,25 @@ describe('BaileysSessionStore', () => {
store.upsertChats([{ id: PHONE }]);
store.addLidMappings([{ lid: LID, pn: PHONE }]);
store.recordMessage(msg(LID, 'OUT', 100, true));
- expect(store.listChats()).toEqual([expect.objectContaining({ timestamp: 100, lastMessage: 'OUT' })]);
+ expect(store.listChats()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: LID, timestamp: 100, lastMessage: 'OUT' }),
+ expect.objectContaining({ id: '[email protected]', lastMessage: undefined }),
+ ]),
+ );
});
it('finds a lid-keyed chat from the @c.us id the listing publishes', () => {
store.upsertChats([{ id: LID }]);
store.recordKeyLidMappings({ remoteJid: LID, remoteJidAlt: PHONE });
store.recordMessage(msg(LID, 'IN', 100));
- expect(store.listChats()[0].id).toBe('[email protected]');
+ expect(store.listChats()[0].id).toBe(LID);
expect(store.lastMessage('[email protected]')).toEqual({
key: { remoteJid: LID, fromMe: false, id: 'IN' },
timestamp: 100,
jid: LID,
});
- store.recordMessageEdit('[email protected]', 'IN', 'edited');
+ store.recordMessageEdit(LID, 'IN', 'edited');
expect(store.listChats()[0].lastMessage).toBe('edited');
});
@@ -898,7 +906,7 @@ describe('BaileysSessionStore', () => {
expect(fake.rows.size).toBe(0);
// A later message re-creates the chat without the pin the deleted one carried.
s.upsertChats([{ id: LID }]);
- expect(s.listChats().find(c => c.id === '[email protected]')).toEqual(expect.objectContaining({ pinned: false }));
+ expect(s.listChats().find(c => c.id === LID)).toEqual(expect.objectContaining({ pinned: false }));
});
it('finds the lid twin through the persisted table as well', () => {
@@ -987,7 +995,7 @@ describe('BaileysSessionStore', () => {
{ id: LID, muteEndTime: -1 },
]);
const expected = { id: '[email protected]', name: 'Alice', pinned: true, archived: true, muted: true };
- expect(s.listChats()).toEqual([expect.objectContaining(expected)]);
+ expect(s.listChats()).toEqual(expect.arrayContaining([expect.objectContaining(expected)]));
expect([...fake.rows.keys()]).toEqual([K(PHONE)]);
const restarted = newStore();
@@ -1002,7 +1010,9 @@ describe('BaileysSessionStore', () => {
expect([...fake.rows.keys()]).toEqual([K(LID)]);
s.upsertChats([{ id: PHONE, name: 'Alice' }]);
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', name: 'Alice', pinned: true })]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: '[email protected]', name: 'Alice', pinned: true })]),
+ );
await flush();
expect([...fake.rows.keys()]).toEqual([K(LID)]); // a listing writes nothing
// A later mute through either spelling folds the lid row onto the phone row.
@@ -1082,7 +1092,9 @@ describe('BaileysSessionStore', () => {
s.upsertChats([{ id: PHONE, pinned: 2 }]);
s.upsertChats([{ id: LID, pinned: 0 }]);
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', pinned: false })]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: '[email protected]', pinned: false })]),
+ );
s.upsertChats([{ id: PHONE, muteEndTime: -1 }]);
expect([...fake.rows.keys()]).toEqual([K(PHONE)]);
expect(s.listChats()[0]).toMatchObject({ pinned: false, muted: true });
@@ -1115,7 +1127,9 @@ describe('BaileysSessionStore', () => {
const s = newStore();
s.upsertContacts([{ id: LID, phoneNumber: PHONE }]);
s.upsertChats([{ id: LID }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true, pinned: true })]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: LID, archived: true, pinned: true })]),
+ );
s.upsertChats([{ id: LID, muteEndTime: -1 }]);
expect([...fake.rows.keys()]).toEqual([K(PHONE)]);
expect(s.listChats()[0]).toMatchObject({ archived: true, pinned: true, muted: true });
@@ -1129,7 +1143,9 @@ describe('BaileysSessionStore', () => {
const s = newStore();
s.upsertContacts([{ id: LID, phoneNumber: PHONE }]);
s.upsertChats(ids.map(id => ({ id })));
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true, pinned: true })]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ id: '[email protected]', archived: true, pinned: true })]),
+ );
s.upsertChats([{ id: PHONE, muteEndTime: -1 }]);
expect([...fake.rows.keys()]).toEqual([K(PHONE)]);
expect(s.listChats()[0]).toMatchObject({ archived: true, pinned: true, muted: true });
@@ -1151,7 +1167,7 @@ describe('BaileysSessionStore', () => {
{ lid: '2@lid', pn: '[email protected]' },
]);
s.upsertChats([{ id: PHONE }, { id: LID }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', pinned: true })]);
+ expect(s.listChats()).toEqual(expect.arrayContaining([expect.objectContaining({ id: LID, pinned: true })]));
} finally {
if (cap === undefined) delete process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES;
else process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES = cap;
@@ -1205,15 +1221,18 @@ describe('BaileysSessionStore', () => {
it.each([
['phone first', [PHONE, LID]],
['lid first', [LID, PHONE]],
- ])('merges the two records into one row, whichever arrived first (%s)', (_order, ids) => {
+ ])('keeps both raw chat records, whichever arrived first (%s)', (_order, ids) => {
const s = new BaileysSessionStore();
for (const id of ids) {
s.upsertChats([id === LID ? { id, name: 'Alice', unreadCount: 2, conversationTimestamp: 50 } : { id }]);
}
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([
- expect.objectContaining({ id: '[email protected]', name: 'Alice', unreadCount: 2, timestamp: 50 }),
- ]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: LID, name: 'Alice', unreadCount: 2, timestamp: 50 }),
+ expect.objectContaining({ id: '[email protected]', unreadCount: 0, timestamp: 0 }),
+ ]),
+ );
});
it('takes the unread count from the more recently active of the two records', () => {
@@ -1223,7 +1242,12 @@ describe('BaileysSessionStore', () => {
{ id: LID, unreadCount: 2, conversationTimestamp: 50 },
]);
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', unreadCount: 2, timestamp: 50 })]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: LID, unreadCount: 2, timestamp: 50 }),
+ expect.objectContaining({ id: '[email protected]', unreadCount: 0, timestamp: 10 }),
+ ]),
+ );
});
it('shows a preview filed under the lid before the mapping on the merged row, newest first', () => {
@@ -1236,11 +1260,18 @@ describe('BaileysSessionStore', () => {
s.upsertChats([{ id: PHONE }]);
s.recordMessage(msg(LID, 'VIA_LID', 100));
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([
- expect.objectContaining({ id: '[email protected]', timestamp: 100, lastMessage: 'VIA_LID' }),
- ]);
+ expect(s.listChats()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: LID, timestamp: 100, lastMessage: 'VIA_LID' }),
+ expect.objectContaining({ id: '[email protected]', lastMessage: undefined }),
+ ]),
+ );
s.recordMessage(msg(PHONE, 'VIA_PHONE', 50));
- expect(s.listChats()[0]).toMatchObject({ timestamp: 100, lastMessage: 'VIA_LID' });
+ expect(s.listChats().find(c => c.id === LID)).toMatchObject({ timestamp: 100, lastMessage: 'VIA_LID' });
+ expect(s.listChats().find(c => c.id === '[email protected]')).toMatchObject({
+ timestamp: 50,
+ lastMessage: 'VIA_PHONE',
+ });
});
it('keeps distinct chats apart', () => {
@@ -1277,7 +1308,7 @@ describe('BaileysSessionStore', () => {
fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: false });
const s = newStore();
s.addLidMappings([{ lid: LID, pn: PHONE }]);
- expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true })]);
+ expect(s.listChats()).toEqual([expect.objectContaining({ id: LID, archived: true })]);
});
it('finds the disappearing timer a lid-keyed chat record carries from the @c.us id', () => {
@@ -1302,6 +1333,10 @@ describe('BaileysSessionStore', () => {
map.set(lid, phone);
return Promise.resolve(true);
}),
+ rememberIfUnknown: jest.fn((lid: string, phone: string) => {
+ if (!map.has(lid)) map.set(lid, phone);
+ return Promise.resolve(true);
+ }),
};
};
@@ -1325,12 +1360,24 @@ describe('BaileysSessionStore', () => {
expect(lidStore.remember).toHaveBeenCalledWith('444', '628444', 'sess-1');
});
+ it('keeps a reconstructed contact phone as display data until an incoming phone field confirms it', () => {
+ const lidStore = makeFakeLidStore();
+ const s = new BaileysSessionStore(lidStore, 'sess-1');
+ s.upsertContacts([{ id: 'c1', phoneNumber: '[email protected]' }]);
+ s.upsertContacts([{ id: 'c1', lid: '444@lid' }]);
+ expect(s.resolvePhone('444@lid')).toBe('628444');
+ expect(lidStore.rememberIfUnknown).toHaveBeenCalledWith('444', '628444', 'sess-1');
+ expect(lidStore.remember).not.toHaveBeenCalled();
+ s.upsertContacts([{ id: 'c1', phoneNumber: '[email protected]' }]);
+ expect(lidStore.remember).toHaveBeenCalledWith('444', '628444', 'sess-1');
+ });
+
it('resolves a lid via the persistent cache when the in-session map misses', () => {
const lidStore = makeFakeLidStore();
lidStore.map.set('444', '628777'); // known only to the cross-session table
const s = new BaileysSessionStore(lidStore, 'sess-1');
expect(s.resolvePhone('444@lid')).toBe('628777');
- expect(s.toNeutralJid('444@lid')).toBe('[email protected]');
+ expect(s.toNeutralJid('444@lid')).toBe('444@lid');
});
it('returns null for a cached-negative or unseen lid', () => {
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 271a95b8e..8cbd3fc27 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -263,11 +263,12 @@ export class BaileysSessionStore {
// `phoneNumber` is the authoritative PN field; fall back to `id` itself only when it's already
// in the phone dialect (a lid-only contact's `id` is `<lid>@lid`, which is not a usable phone).
// A record keyed by its lid carries the lid side in `id` and usually has no `lid` field.
+ // A name-only update carries no new pair and must not write an older merged phone over the shared table.
const phone = merged.phoneNumber ?? (merged.id.endsWith('@s.whatsapp.net') ? merged.id : undefined);
const lid = merged.lid ?? (parseWaId(merged.id).kind === 'lid' ? merged.id : undefined);
- if (lid && phone) {
+ if (lid && phone && (r.lid !== undefined || r.phoneNumber !== undefined)) {
this.lidToPn.set(lid, phone);
- this.persistLidMapping(lid, phone);
+ this.persistLidMapping(lid, phone, r.phoneNumber !== undefined || kind === 'user');
}
}
}
@@ -374,11 +375,11 @@ export class BaileysSessionStore {
if (missed.length) await store.forget(sessionId, missed);
}
- addLidMappings(mappings: { lid?: string; pn?: string }[] = []): void {
+ addLidMappings(mappings: { lid?: string; pn?: string }[] = [], isReported = true): void {
for (const m of mappings) {
if (m.lid && m.pn) {
this.lidToPn.set(m.lid, m.pn);
- this.persistLidMapping(m.lid, m.pn);
+ this.persistLidMapping(m.lid, m.pn, isReported);
}
}
}
@@ -391,12 +392,15 @@ export class BaileysSessionStore {
* is still the only place a fresh `@lid` sender's number is revealed on the message key itself; the
* pairs flow through addLidMappings, so they also write through to the persistent table.
*/
- recordKeyLidMappings(key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt'>): void {
+ recordKeyLidMappings(
+ key: Pick<WAMessageKey, 'remoteJid' | 'remoteJidAlt' | 'participant' | 'participantAlt' | 'fromMe'>,
+ ): void {
// On a status or broadcast-list message `remoteJidAlt` is the SENDER's other dialect (Baileys fills
// it for every non-group chat), so it pairs with `participant`, not with the `@broadcast` id.
const broadcast = key.remoteJid?.endsWith('@broadcast');
this.addLidMappings([
- this.lidPnPair(broadcast ? key.participant : key.remoteJid, key.remoteJidAlt),
+ // Own-message remoteJid can name the recipient while senderAlt still names this account.
+ key.fromMe === true ? {} : this.lidPnPair(broadcast ? key.participant : key.remoteJid, key.remoteJidAlt),
this.lidPnPair(key.participant, key.participantAlt),
]);
}
@@ -414,8 +418,9 @@ export class BaileysSessionStore {
}
/** Write a learned lid->phone pair through to the persistent table (bare digits, fire-and-forget). */
- private persistLidMapping(lidJid: string, pnJid: string): void {
- void this.lidStore?.remember(userPart(lidJid), userPart(pnJid), this.sessionId);
+ private persistLidMapping(lidJid: string, pnJid: string, isReported: boolean): void {
+ if (isReported) void this.lidStore?.remember(userPart(lidJid), userPart(pnJid), this.sessionId);
+ else void this.lidStore?.rememberIfUnknown?.(userPart(lidJid), userPart(pnJid), this.sessionId);
}
recordMessage(msg: WAMessage, type?: MessageType): void {
@@ -428,7 +433,7 @@ export class BaileysSessionStore {
// neutral JID so an outbound send addressed in either dialect (phone or @lid) finds it.
this.recordEphemeralFromMessage(chatId, msg);
// A received broadcast-list message previews in its sender's chat, where Baileys lists it.
- const key = this.chatKey(baileysChatJid(chatId, msg.key.participant, msg.key.fromMe === true));
+ const key = this.toEngineJid(baileysChatJid(chatId, msg.key.participant, msg.key.fromMe === true));
const timestamp = this.toUnixSeconds(msg.messageTimestamp);
if (!msg.key.fromMe) {
const inbound = this.lastInbound.get(key);
@@ -449,7 +454,7 @@ export class BaileysSessionStore {
*/
recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void {
if (!messageId) return;
- for (const key of new Set([this.chatKey(chatId), ...this.chatTwins(chatId)])) {
+ for (const key of new Set([chatId, this.toEngineJid(chatId)])) {
const existing = this.lastMessages.get(key);
if (existing?.key.id === messageId)
this.lastMessages.set(key, { ...existing, text, type: type ?? existing.type });
@@ -641,6 +646,11 @@ export class BaileysSessionStore {
const id = this.toNeutralJid(c.id!);
byId.set(id, [...(byId.get(id) ?? []), c]);
}
+ // A message proves the raw conversation exists even before its chat record reaches this process.
+ for (const [key] of [...this.lastMessages.entries()]) {
+ const id = this.toNeutralJid(key);
+ if (!byId.has(id)) byId.set(id, [{ id: key }]);
+ }
// A new engine starts with no chats (see the class comment), but a chat with a persisted state is
// known to exist: a deleted chat loses its row. So it is listed before its next message arrives.
if (this.chatStateStore && this.sessionId) {
@@ -697,10 +707,9 @@ export class BaileysSessionStore {
getEphemeralExpiration(chatId: string): number | undefined {
// Prefer the timer learned from inbound messages (reliably present); try the raw, engine, and
// neutral keys so an @lid-keyed entry and a phone-dialect send target resolve to the same value.
- const fromMessage =
- this.ephemeralByChat.get(chatId) ??
- this.ephemeralByChat.get(this.toEngineJid(chatId)) ??
- this.ephemeralByChat.get(this.toNeutralJid(chatId));
+ const fromMessage = [chatId, this.toEngineJid(chatId), ...this.chatTwins(chatId)]
+ .map(key => this.ephemeralByChat.get(key))
+ .find(value => typeof value === 'number' && value > 0);
if (typeof fromMessage === 'number' && fromMessage > 0) {
return fromMessage;
}
@@ -740,11 +749,11 @@ export class BaileysSessionStore {
}
/**
- * Canonicalize a Baileys JID to the neutral dialect (see {@link canonicalizeWaId} / wa-id.ts),
- * resolving a lid to its phone via this session's lid->pn map when the mapping is known.
+ * Normalize identity without deriving it from a display cache. A LID stays a LID; persisted,
+ * reported mappings bridge it to phone grants and filters at the application boundary.
*/
toNeutralJid(jid: string): string {
- return canonicalizeWaId(jid, id => this.resolvePhone(id));
+ return canonicalizeWaId(jid);
}
/**
@@ -766,7 +775,7 @@ export class BaileysSessionStore {
// the raw `@lid` key answered an empty string for somebody the account has saved. An unresolved
// lid still answers '', which is the honest answer there.
const id = this.toNeutralJid(c.id);
- const number = c.phoneNumber ? userPart(c.phoneNumber) : id.endsWith('@c.us') ? userPart(id) : '';
+ const number = c.phoneNumber ? userPart(c.phoneNumber) : (this.resolvePhone(c.id) ?? '');
return {
id,
name: c.name ?? c.verifiedName,
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 19af540e7..570bb88a8 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -3,6 +3,16 @@ import * as fs from 'fs';
import * as path from 'path';
import * as qrcode from 'qrcode';
import * as messagingModule from './baileys-messaging';
+import { randomUUID } from 'crypto';
+import { DataSource } from 'typeorm';
+import { EngineRegistry } from '../engine-registry.service';
+import { LidMapping } from '../identity/lid-mapping.entity';
+import { LidMappingStoreService } from '../identity/lid-mapping-store.service';
+import { Session } from '../../modules/session/entities/session.entity';
+import { Message, MessageDirection } from '../../modules/message/entities/message.entity';
+import { MessageProjector } from '../../modules/session/message-projector.service';
+import { SessionLidResolver } from '../../modules/session/session-lid-resolver.service';
+import { ChatScopeService } from '../../modules/auth/chat-scope.service';
jest.mock('../../common/media/load-remote-media', () => ({
loadRemoteMediaBuffer: jest.fn(),
@@ -66,6 +76,7 @@ class FakeSock extends EventEmitter {
public removeContact = jest.fn().mockResolvedValue(undefined);
public readMessages = jest.fn().mockResolvedValue(undefined);
public chatModify = jest.fn().mockResolvedValue(undefined);
+ public executeUSyncQuery = jest.fn().mockResolvedValue(undefined);
public addChatLabel = jest.fn().mockResolvedValue(undefined);
public addLabel = jest.fn().mockResolvedValue(undefined);
public removeChatLabel = jest.fn().mockResolvedValue(undefined);
@@ -128,6 +139,30 @@ jest.mock('@whiskeysockets/baileys', () => ({
// Identity passthrough — the adapter wraps state.keys with this for session-store caching; tests
// don't exercise the caching behavior itself, just need the real store object to flow through.
makeCacheableSignalKeyStore: jest.fn((store: unknown) => store),
+ USyncQuery: class {
+ users: unknown[] = [];
+ protocols: string[] = [];
+ context = 'interactive';
+ withLIDProtocol() {
+ this.protocols.push('lid');
+ return this;
+ }
+ withContext(context: string) {
+ this.context = context;
+ return this;
+ }
+ withUser(user: unknown) {
+ this.users.push(user);
+ return this;
+ }
+ },
+ USyncUser: class {
+ id?: string;
+ withId(id: string) {
+ this.id = id;
+ return this;
+ }
+ },
getContentType: jest.fn(() => 'conversation'),
// The adapter now downloads via 'stream' mode, so resolve to an async-iterable of chunks (factory is
// hoisted above imports, so this stays inline; tests override with the `streamOf` helper below).
@@ -165,6 +200,7 @@ import { BaileysAdapter, createProxyAgent } from './baileys.adapter';
import { BaileysEvents } from './baileys-events';
import {
EditedMessage,
+ DeliveryStatus,
EngineStatus,
EngineEventCallbacks,
GroupEvent,
@@ -206,6 +242,7 @@ const fakeStore = {
beforeEach(() => {
fakeStore.getMessage.mockReset();
fakeSock.signalRepository = undefined;
+ fakeSock.executeUSyncQuery.mockReset().mockResolvedValue(undefined);
fakeSock.onWhatsApp.mockReset().mockImplementation((jid: string) => Promise.resolve([{ jid, exists: true }]));
fakeSock.groupFetchAllParticipating.mockReset();
const baileys = jest.requireMock<Record<string, jest.Mock>>('@whiskeysockets/baileys');
@@ -2062,7 +2099,7 @@ describe('BaileysAdapter messaging', () => {
await adapter.sendTextMessage('[email protected]', 'hello');
// The device suffix (:3) is stripped — that is the key the lid->phone lookup reads.
- expect(spy).toHaveBeenCalledWith([{ lid: '484848@lid', pn: '[email protected]' }]);
+ expect(spy).toHaveBeenCalledWith([{ lid: '484848@lid', pn: '[email protected]' }], false);
});
it('sendTextMessage uses the canonical phone jid when no LID mapping is known', async () => {
@@ -2562,7 +2599,7 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(msg.chatId).toBe('[email protected]');
});
- it('resolves an @lid sender to <phone>@c.us using a history-sync lid->pn mapping', async () => {
+ it('retains the raw LID sender after a history phone mapping', async () => {
const onMessage = jest.fn();
const adapter = newAdapter();
await adapter.initialize({ onMessage });
@@ -2581,11 +2618,11 @@ describe('BaileysAdapter inbound fan-out', () => {
await new Promise(r => setImmediate(r));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const msg = onMessage.mock.calls[0][0] as { from: string; isLidSender?: boolean };
- expect(msg.from).toBe('[email protected]'); // lid resolved to phone, neutral dialect
+ expect(msg.from).toBe('111@lid'); // display resolution does not change chat identity
expect(msg.isLidSender).toBe(true); // still flagged: the raw sender was a lid
});
- it('resolves an @lid sender via the lid/pn pair carried on the inbound message key (#362)', async () => {
+ it('retains a sender LID while recording its explicit key phone pairing', async () => {
const onMessage = jest.fn();
const adapter = newAdapter();
await adapter.initialize({ onMessage });
@@ -2609,7 +2646,7 @@ describe('BaileysAdapter inbound fan-out', () => {
await new Promise(r => setImmediate(r));
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const msg = onMessage.mock.calls[0][0] as { from: string; isLidSender?: boolean };
- expect(msg.from).toBe('[email protected]'); // resolved from the key's remoteJidAlt, neutral dialect
+ expect(msg.from).toBe('111@lid'); // the reported pair bridges the phone through the shared directory
expect(msg.isLidSender).toBe(true);
});
@@ -4179,7 +4216,7 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(onMessage).toHaveBeenCalledTimes(1);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const msg = onMessage.mock.calls[0][0] as { author?: string; body: string };
- expect(msg.author).toBe('[email protected]');
+ expect(msg.author).toBe('111@lid');
expect(msg.body).toBe('first real message');
});
@@ -4523,6 +4560,110 @@ describe('BaileysAdapter store-backed ops', () => {
messageTimestamp: '1700000000',
};
+ it('confirms a phone-addressed stored LID through a fresh LID query before mutating it', async () => {
+ const adapter = await ready();
+ fakeStore.getMessage.mockResolvedValue({
+ key: { id: 'TARGET', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'mine' },
+ });
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce({ list: [{ id: '[email protected]', lid: '111@lid' }] });
+ await expect(adapter.starMessage('[email protected]', 'TARGET', true)).resolves.toBeUndefined();
+ expect(fakeSock.executeUSyncQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: 'background',
+ protocols: ['lid'],
+ users: [expect.objectContaining({ id: '[email protected]' })],
+ }),
+ );
+ });
+
+ it('confirms a LID request against an older phone-keyed message through the same fresh query', async () => {
+ const adapter = await ready();
+ fakeStore.getMessage.mockResolvedValue({
+ key: { id: 'TARGET', remoteJid: '[email protected]', fromMe: true },
+ message: { conversation: 'mine' },
+ });
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce({ list: [{ id: '[email protected]', lid: '111@lid' }] });
+ await expect(adapter.starMessage('111@lid', 'TARGET', true)).resolves.toBeUndefined();
+ });
+
+ it.each([
+ { list: [{ id: '[email protected]', lid: '111@lid' }] },
+ { list: [{ id: '[email protected]', lid: '222@lid' }] },
+ { list: [{ id: '[email protected]', lid: '[email protected]' }] },
+ { list: [{ id: '628111@lid', lid: '111@lid' }] },
+ { list: [{ id: '[email protected]' }] },
+ {
+ list: [
+ { id: '[email protected]', lid: '111@lid' },
+ { id: '[email protected]', lid: '222@lid' },
+ ],
+ },
+ { list: [] },
+ undefined,
+ ])('refuses a stored LID whose query result does not uniquely confirm the addressed phone (%j)', async result => {
+ const adapter = await ready();
+ fakeStore.getMessage.mockResolvedValue({
+ key: { id: 'TARGET', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'mine' },
+ });
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce(result);
+ await expect(adapter.starMessage('[email protected]', 'TARGET', true)).rejects.toBeInstanceOf(MessageNotFoundError);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ });
+
+ it('bounds a stored LID identity query that never answers', async () => {
+ const adapter = await ready();
+ fakeStore.getMessage.mockResolvedValue({
+ key: { id: 'TARGET', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'mine' },
+ });
+ fakeSock.executeUSyncQuery.mockImplementationOnce(() => new Promise(() => undefined));
+ jest.useFakeTimers();
+ try {
+ let failure: unknown;
+ void adapter.starMessage('[email protected]', 'TARGET', true).catch(error => {
+ failure = error;
+ });
+ await jest.advanceTimersByTimeAsync(30_000);
+ expect(failure).toBeInstanceOf(EngineTransportError);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('drops a matching identity answer from a retired socket', async () => {
+ const adapter = await ready();
+ const mappings = jest.spyOn(
+ (adapter as unknown as { sessionStore: { addLidMappings: () => void } }).sessionStore,
+ 'addLidMappings',
+ );
+ fakeStore.getMessage.mockResolvedValue({
+ key: { id: 'TARGET', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'mine' },
+ });
+ let reply!: (value: unknown) => void;
+ let started!: () => void;
+ const entered = new Promise<void>(resolve => {
+ started = resolve;
+ });
+ fakeSock.executeUSyncQuery.mockImplementationOnce(() => {
+ started();
+ return new Promise(resolve => {
+ reply = resolve;
+ });
+ });
+ const pending = adapter.starMessage('[email protected]', 'TARGET', true);
+ const rejected = expect(pending).rejects.toBeInstanceOf(EngineNotReadyError);
+ await entered;
+ await adapter.disconnect();
+ reply({ list: [{ id: '[email protected]', lid: '111@lid' }] });
+ await rejected;
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ expect(mappings).not.toHaveBeenCalled();
+ });
+
it('replyToMessage quotes the stored message', async () => {
fakeStore.getMessage.mockResolvedValue(stored);
const adapter = await ready();
@@ -5226,21 +5367,26 @@ describe('BaileysAdapter store-backed ops', () => {
);
afterEach(() => {
fakeSock.signalRepository = undefined;
+ fakeSock.executeUSyncQuery.mockResolvedValue(undefined);
});
it.each([
['an unmapped @c.us id to a phone-keyed chat', '[email protected]', '[email protected]', null],
['a phone id to a phone-keyed chat whose lid is known', '[email protected]', '[email protected]', '484848@lid'],
['a phone id to a lid-keyed chat', '[email protected]', '484848@lid', '484848@lid'],
- ])('%s still becomes the chat preview and sort time', async (_label, sendTo, chatKey, lid) => {
+ ])('%s keeps the wire identity for its preview and operations', async (_label, sendTo, chatKey, lid) => {
fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(lid) } };
echoSend();
+ if (lid) fakeSock.executeUSyncQuery.mockResolvedValue({ list: [{ id: '[email protected]', lid }] });
const adapter = await ready();
fakeSock.fire('chats.upsert', [{ id: chatKey, conversationTimestamp: 1700000000 }]);
await adapter.sendTextMessage(sendTo, 'on its way');
- expect(await adapter.getChats()).toEqual([
- expect.objectContaining({ id: '[email protected]', timestamp: 1700000100, lastMessage: 'on its way' }),
- ]);
+ const identity = lid ?? '[email protected]';
+ expect(await adapter.getChats()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: identity, timestamp: 1700000100, lastMessage: 'on its way' }),
+ ]),
+ );
fakeStore.getMessage.mockResolvedValue({
key: { id: 'OUT', remoteJid: lid ?? sendTo, fromMe: true },
@@ -5248,9 +5394,9 @@ describe('BaileysAdapter store-backed ops', () => {
messageTimestamp: 1700000100,
});
await adapter.editMessage('[email protected]', 'OUT', 'arriving tomorrow');
- expect((await adapter.getChats())[0]?.lastMessage).toBe('arriving tomorrow');
+ expect((await adapter.getChats()).find(chat => chat.id === identity)?.lastMessage).toBe('arriving tomorrow');
await adapter.deleteMessage('[email protected]', 'OUT', true);
- expect((await adapter.getChats())[0]?.lastMessage).toBe('');
+ expect((await adapter.getChats()).find(chat => chat.id === identity)?.lastMessage).toBe('');
});
});
@@ -5480,7 +5626,7 @@ describe('BaileysAdapter group management', () => {
await expect(adapter.getGroupInfo('[email protected]')).rejects.toThrow('unexpected');
});
- it('getGroupInfo canonicalizes participant + owner ids through the session store (lid -> phone)', async () => {
+ it('getGroupInfo keeps LID participant and owner identities separate from cached phones', async () => {
const adapter = await ready();
// History sync supplies the lid -> phone mapping; the adapter passes the store's canonicalizer in.
fakeSock.fire('messaging-history.set', { lidPnMappings: [{ lid: '111@lid', pn: '[email protected]' }] });
@@ -5495,8 +5641,8 @@ describe('BaileysAdapter group management', () => {
});
const info = await adapter.getGroupInfo('[email protected]');
// Owner + the known admin fold to <phone>@c.us, so they share the dialect of canonicalized authors.
- expect(info?.owner).toBe('[email protected]');
- expect(info?.participants[0]).toMatchObject({ id: '[email protected]', number: '628111', isSuperAdmin: true });
+ expect(info?.owner).toBe('111@lid');
+ expect(info?.participants[0]).toMatchObject({ id: '111@lid', number: '111', isSuperAdmin: true });
expect(info?.participants[1]).toMatchObject({ id: '222@lid', number: '222' }); // unresolved kept raw
});
@@ -6077,7 +6223,7 @@ describe('BaileysAdapter group events (group-participants.update / groups.update
expect(firstEvent(onGroupEvent).participantIds).toEqual(['[email protected]']);
});
- it('resolves a lid-only participant through the learned lid->pn mapping, else keeps the lid', async () => {
+ it('retains a lid-only participant identity after learning a display phone', async () => {
const { onGroupEvent } = await readyWithGroupEvents();
fakeSock.fire('group-participants.update', {
@@ -6095,7 +6241,7 @@ describe('BaileysAdapter group events (group-participants.update / groups.update
participants: [{ id: '111@lid' }],
});
const calls = onGroupEvent.mock.calls as Array<[GroupEvent]>;
- expect(calls[1][0].participantIds).toEqual(['[email protected]']);
+ expect(calls[1][0].participantIds).toEqual(['111@lid']);
});
it('prefers authorPn over a lid author for the neutral actorId', async () => {
@@ -6292,7 +6438,7 @@ describe('BaileysAdapter group events (group-participants.update / groups.update
expect(firstEvent(onGroupEvent).groupId).toBe('[email protected]');
});
- it('skips a self-created group addressed by lid when the creds carry no own lid', async () => {
+ it('retains a lid actor when the credentials cannot identify it as this account', async () => {
// Without `user.lid` every lid comparison answered false, so the group this session had just
// created was reported as a join of itself. The store's own lid mapping settles it instead.
fakeSock.user = { id: '628999:[email protected]', name: 'Me' }; // no lid on the creds
@@ -6302,7 +6448,7 @@ describe('BaileysAdapter group events (group-participants.update / groups.update
fakeSock.fire('groups.upsert', [createdGroup({ author: '999000@lid', owner: '999000@lid', authorPn: undefined })]);
- expect(onGroupEvent).not.toHaveBeenCalled();
+ expect(onGroupEvent).toHaveBeenCalledWith(expect.objectContaining({ actorId: '999000@lid' }));
});
it('reports a groups.upsert entry the session authored for a group another account owns', async () => {
@@ -6831,12 +6977,64 @@ describe('BaileysAdapter contact + chat reads', () => {
});
});
+ it.each(['add', 'remove'])('does not %s a label if the connection changes after address preparation', async mode => {
+ const adapter = await ready();
+ const original = fakeSock;
+ const replacement = { addChatLabel: jest.fn(), removeChatLabel: jest.fn() };
+ const contacts = (adapter as unknown as { contacts: { confirmedChatJid: (chatId: string) => Promise<string> } })
+ .contacts;
+ const prepare = contacts.confirmedChatJid.bind(contacts);
+ const lookup = jest.spyOn(contacts, 'confirmedChatJid').mockImplementation(async chatId => {
+ const jid = await prepare(chatId);
+ (adapter as unknown as { sock: unknown }).sock = replacement;
+ return jid;
+ });
+ try {
+ const pending =
+ mode === 'add'
+ ? adapter.addLabelToChat('[email protected]', 'label')
+ : adapter.removeLabelFromChat('[email protected]', 'label');
+ await expect(pending).rejects.toBeInstanceOf(EngineNotReadyError);
+ for (const socket of [original, replacement]) {
+ expect(socket.addChatLabel).not.toHaveBeenCalled();
+ expect(socket.removeChatLabel).not.toHaveBeenCalled();
+ }
+ } finally {
+ lookup.mockRestore();
+ (adapter as unknown as { sock: unknown }).sock = original;
+ await adapter.destroy();
+ }
+ });
+
+ it('drops a contact identity answer from a retired socket', async () => {
+ const adapter = await ready();
+ fakeSock.fire('contacts.upsert', [{ id: '111@lid', phoneNumber: '[email protected]' }]);
+ let reply!: (value: unknown) => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ fakeSock.executeUSyncQuery.mockImplementationOnce(() => {
+ entered();
+ return new Promise(resolve => {
+ reply = resolve;
+ });
+ });
+ const pending = adapter.getContactById('[email protected]');
+ const rejected = expect(pending).rejects.toBeInstanceOf(EngineNotReadyError);
+ await started;
+ await adapter.disconnect();
+ reply({ list: [{ id: '[email protected]', lid: '111@lid' }] });
+ await rejected;
+ });
+
describe('resolveContactPhone for a lid this session does not hold in memory', () => {
const makeLidStore = () => ({
getCached: jest.fn((): string | null | undefined => undefined),
resolveLid: jest.fn(() => null),
lidsForPhone: jest.fn((): string[] => []),
remember: jest.fn(() => Promise.resolve(true)),
+ rememberIfUnknown: jest.fn(() => Promise.resolve(true)),
findPhoneForLid: jest.fn((): Promise<string | null> => Promise.resolve(null)),
});
const readyWith = async (lidMappingStore: ReturnType<typeof makeLidStore>): Promise<BaileysAdapter> => {
@@ -6855,6 +7053,52 @@ describe('BaileysAdapter contact + chat reads', () => {
fakeSock.signalRepository = undefined;
});
+ it.each(['persisted-add', 'persisted-remove', 'fresh-add', 'fresh-remove'])(
+ 'does not send a label action across replacement during %s preparation',
+ async mode => {
+ const lidStore = makeLidStore();
+ let release!: () => void;
+ let entered!: () => void;
+ const started = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ if (mode.startsWith('persisted'))
+ lidStore.findPhoneForLid.mockImplementation(async () => {
+ entered();
+ await gate;
+ return '628111';
+ });
+ const adapter = await readyWith(lidStore);
+ const original = fakeSock;
+ original.executeUSyncQuery.mockReset().mockImplementation(async () => {
+ entered();
+ await gate;
+ return { list: [{ id: '[email protected]', lid: '111@lid' }] };
+ });
+ fakeSock.fire('contacts.upsert', [{ id: '111@lid', phoneNumber: '[email protected]' }]);
+ fakeSock.fire('chats.upsert', [{ id: '111@lid' }]);
+ const replacement = { addChatLabel: jest.fn(), removeChatLabel: jest.fn() };
+ const pending = (
+ mode.endsWith('add')
+ ? adapter.addLabelToChat('[email protected]', 'label')
+ : adapter.removeLabelFromChat('[email protected]', 'label')
+ ).catch((error: unknown) => error);
+ await started;
+ (adapter as unknown as { sock: unknown }).sock = replacement;
+ release();
+ expect(await pending).toBeInstanceOf(EngineNotReadyError);
+ for (const socket of [original, replacement]) {
+ expect(socket.addChatLabel).not.toHaveBeenCalled();
+ expect(socket.removeChatLabel).not.toHaveBeenCalled();
+ }
+ (adapter as unknown as { sock: unknown }).sock = original;
+ await adapter.destroy();
+ },
+ );
+
it('answers from the persisted table when the cache no longer holds the mapping', async () => {
const lidStore = makeLidStore();
lidStore.findPhoneForLid.mockResolvedValue('628111');
@@ -6871,7 +7115,8 @@ describe('BaileysAdapter contact + chat reads', () => {
const adapter = await readyWith(lidStore);
expect(await adapter.resolveContactPhone('111@lid')).toBe('628222');
expect(getPNForLID).toHaveBeenCalledWith('111@lid');
- expect(lidStore.remember).toHaveBeenCalledWith('111', '628222', 'sess-1');
+ expect(lidStore.rememberIfUnknown).toHaveBeenCalledWith('111', '628222', 'sess-1');
+ expect(lidStore.remember).not.toHaveBeenCalled();
});
it('rejects instead of answering null when nothing maps the lid, so no null is stored', async () => {
@@ -6891,6 +7136,436 @@ describe('BaileysAdapter contact + chat reads', () => {
expect(await adapter.resolveContactPhone('[email protected]')).toBeNull();
expect(lidStore.findPhoneForLid).not.toHaveBeenCalled();
});
+
+ it.each(['history', 'contact', 'signal'])(
+ 'keeps a newer shared phone when a sender lookup reads an earlier %s mapping',
+ async source => {
+ const pg = process.env.DATABASE_TYPE === 'postgres';
+ const server = {
+ type: 'postgres' as const,
+ host: process.env.DATABASE_HOST || '127.0.0.1',
+ port: Number(process.env.DATABASE_PORT || 5432),
+ username: process.env.DATABASE_USERNAME || 'openwa',
+ password: process.env.DATABASE_PASSWORD || 'openwa',
+ database: process.env.DATABASE_NAME || 'openwa',
+ };
+ const schema = `lid_sender_${randomUUID().replace(/-/g, '')}`;
+ const admin = pg ? await new DataSource(server).initialize() : undefined;
+ if (admin) await admin.query(`CREATE SCHEMA "${schema}"`);
+ const entities = [LidMapping, Session, Message];
+ const ds = await new DataSource(
+ pg
+ ? { ...server, schema, extra: { options: `-c search_path=${schema},public` }, entities, synchronize: true }
+ : { type: 'better-sqlite3', database: ':memory:', entities, synchronize: true },
+ ).initialize();
+ const [s1, s2] = ['00000001-0000-4000-8000-000000000000', '00000002-0000-4000-8000-000000000000'];
+ await ds.getRepository(Session).insert([s1, s2].map(id => ({ id, name: id, phone: '6290000000' })));
+ const repo = ds.getRepository(LidMapping);
+ const store = new LidMappingStoreService(repo);
+ const peer = new LidMappingStoreService(repo);
+ await store.onModuleInit();
+ await peer.onModuleInit();
+ jest.spyOn((store as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => {});
+ const pending = new Set<Promise<boolean>>();
+ for (const method of ['remember', 'rememberIfUnknown'] as const) {
+ const real = store[method].bind(store);
+ jest.spyOn(store, method).mockImplementation((...args: Parameters<typeof store.remember>) => {
+ const promise = real(...(args as [string, string, string]));
+ pending.add(promise);
+ void promise.finally(() => pending.delete(promise));
+ return promise;
+ });
+ }
+ const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await new Promise(resolve => setImmediate(resolve));
+ await Promise.allSettled([...pending]);
+ }
+ };
+ const adapter = new BaileysAdapter({
+ sessionId: s1,
+ dbSessionId: s1,
+ authDir: './data/baileys',
+ messageStore: fakeStore,
+ lidMappingStore: store,
+ });
+ try {
+ const projected = new Set<Promise<unknown>>();
+ const onMessage = jest.fn((message: IncomingMessage) => {
+ const receipt = projector?.handleInboundMessage(s1, adapter, message);
+ if (receipt) {
+ projected.add(receipt.settled);
+ void receipt.settled.finally(() => projected.delete(receipt.settled));
+ }
+ return receipt;
+ });
+ const library = jest.requireMock<{ getContentType: jest.Mock }>('@whiskeysockets/baileys');
+ library.getContentType.mockImplementation((message: Record<string, unknown> = {}) => Object.keys(message)[0]);
+ const edits = jest.fn((message: EditedMessage) => projector.applyMessageEditQueued(s1, message));
+ const acks = jest.fn((id: string, status: DeliveryStatus, chatId?: string) =>
+ projector.handleMessageAck(s1, adapter, id, status, chatId),
+ );
+ await adapter.initialize({
+ onMessage,
+ onMessageCreate: message => projector.handleOwnSendEcho(s1, adapter, message),
+ onHistoryMessages: messages => projector.persistHistoryMessages(s1, adapter, messages),
+ onMessageAck: acks,
+ onMessageEdited: edits,
+ onMessageRevoked: (message, actor) => projector.handleMessageRevoked(s1, adapter, message, actor),
+ onMessageReaction: event => projector.applyReactionQueued(s1, event),
+ });
+ fakeSock.fire('connection.update', { connection: 'open' });
+ const engines = new EngineRegistry();
+ engines.set(s1, adapter);
+ const resolver = new SessionLidResolver(engines, store);
+ const projector = new MessageProjector(
+ ds.getRepository(Message),
+ ds.getRepository(Session),
+ engines,
+ {
+ emitNewMessage: jest.fn(),
+ emitMessage: jest.fn(),
+ emitMessageEdited: jest.fn(),
+ emitMessageRevoked: jest.fn(),
+ emitMessageReaction: jest.fn(),
+ emitMessageSent: jest.fn(),
+ emitMessageAck: jest.fn(),
+ } as never,
+ { dispatch: jest.fn().mockResolvedValue(undefined) } as never,
+ {
+ execute: jest.fn((_event: string, data: Record<string, unknown>) =>
+ Promise.resolve({ continue: true, data }),
+ ),
+ } as never,
+ {} as never,
+ resolver,
+ undefined,
+ undefined,
+ undefined,
+ store,
+ );
+ const drainProjection = async () => {
+ await settle();
+ await Promise.allSettled([...projected]);
+ for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve));
+ };
+ const rowEventually = async (
+ waMessageId: string,
+ check: (row: Message) => boolean = () => true,
+ ): Promise<Message> => {
+ const deadline = performance.now() + 5000;
+ for (;;) {
+ const row = await ds.getRepository(Message).findOneBy({ waMessageId });
+ if (row && check(row)) return row;
+ if (performance.now() >= deadline)
+ throw new Error(`Message ${waMessageId} did not reach its expected state`);
+ await new Promise(resolve => setTimeout(resolve, 1));
+ }
+ };
+ let clock = 0;
+ (resolver as unknown as { now: () => number }).now = () => clock;
+ const failed = jest.spyOn(repo, 'upsert').mockRejectedValue(new Error('connection lost'));
+ const builder = repo.createQueryBuilder().insert().values({});
+ const execute = jest.spyOn(builder, 'execute').mockRejectedValue(new Error('connection lost'));
+ const failedSeed = jest.spyOn(repo, 'createQueryBuilder').mockReturnValue(builder as never);
+ if (source === 'history') {
+ fakeSock.fire('messaging-history.set', {
+ contacts: [],
+ chats: [],
+ messages: [],
+ lidPnMappings: [{ lid: '111@lid', pn: '[email protected]' }],
+ });
+ } else if (source === 'contact') {
+ fakeSock.fire('contacts.upsert', [{ id: '111@lid', phoneNumber: '[email protected]' }]);
+ } else {
+ fakeSock.signalRepository = {
+ lidMapping: { getLIDForPN: jest.fn(), getPNForLID: jest.fn().mockResolvedValue('[email protected]') },
+ };
+ }
+ await expect(resolver.resolveSenderPhone(s1, '111@lid')).resolves.toBe('628111');
+ await settle();
+ expect(await repo.findOne({ where: { lid: '111' } })).toBeNull();
+ failed.mockRestore();
+ failedSeed.mockRestore();
+ execute.mockRestore();
+ await peer.remember('111', '628222', s2);
+ fakeSock.fire('contacts.update', [{ id: '111@lid', notify: 'New name' }]);
+ await settle();
+ expect(await repo.findOneByOrFail({ lid: '111' })).toMatchObject({ phone: '628222', isReported: true });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'CACHE_ONLY', remoteJid: '111@lid', fromMe: false },
+ message: { conversation: 'private message' },
+ messageTimestamp: 1700000029,
+ },
+ ],
+ });
+ await settle();
+ fakeSock.fire('chats.upsert', [{ id: '111@lid' }, { id: '[email protected]' }]);
+ const chats = await adapter.getChats();
+ const fence = new ChatScopeService(store);
+ expect(await fence.filter({ allowedChats: ['[email protected]'] }, chats, chat => chat.id)).toEqual([
+ expect.objectContaining({ id: '[email protected]', lastMessage: undefined }),
+ ]);
+ expect(await fence.filter({ allowedChats: ['111@lid'] }, chats, chat => chat.id)).toContainEqual(
+ expect.objectContaining({ id: '111@lid', lastMessage: 'private message' }),
+ );
+ const incoming = onMessage.mock.calls.find(([message]) => message.id === 'CACHE_ONLY')![0];
+ expect(incoming.chatId).toBe('111@lid');
+ expect(await new ChatScopeService(store).allows({ allowedChats: ['[email protected]'] }, incoming.chatId)).toBe(
+ false,
+ );
+ await drainProjection();
+ const persisted = await ds.getRepository(Message).findOneByOrFail({ waMessageId: 'CACHE_ONLY' });
+ expect(persisted.chatId).toBe('111@lid');
+ expect(await fence.filter({ allowedChats: ['[email protected]'] }, [persisted], message => message.chatId)).toEqual(
+ [],
+ );
+ expect(
+ await fence.filter({ allowedChats: ['111@lid'] }, [persisted], message => message.chatId),
+ ).toHaveLength(1);
+ fakeSock.fire('messages.update', [
+ { key: { id: 'CACHE_ONLY', remoteJid: '111@lid' }, update: { status: 3 } },
+ ]);
+ expect(acks).toHaveBeenCalledWith('CACHE_ONLY', 'delivered', '111@lid');
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'RAW_OWN', remoteJid: '111@lid', remoteJidAlt: '[email protected]', fromMe: true },
+ message: { conversation: 'own content' },
+ messageTimestamp: 1700000029,
+ },
+ ],
+ });
+ fakeSock.fire('messaging-history.set', {
+ contacts: [],
+ chats: [],
+ messages: [
+ {
+ key: { id: 'RAW_HISTORY', remoteJid: '111@lid', fromMe: false },
+ message: { conversation: 'history content' },
+ messageTimestamp: 1700000029,
+ },
+ ],
+ });
+ await drainProjection();
+ for (const waMessageId of ['RAW_OWN', 'RAW_HISTORY']) {
+ const raw = await rowEventually(waMessageId);
+ expect(raw.chatId).toBe('111@lid');
+ expect(await fence.allows({ allowedChats: ['[email protected]'] }, raw.chatId)).toBe(false);
+ expect(await fence.allows({ allowedChats: ['111@lid'] }, raw.chatId)).toBe(true);
+ }
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'RAW_REACTION', remoteJid: '111@lid', fromMe: false },
+ message: { reactionMessage: { key: { id: 'CACHE_ONLY' }, text: 'yes' } },
+ messageTimestamp: 1700000029,
+ },
+ ],
+ });
+ await drainProjection();
+ expect((await rowEventually('CACHE_ONLY', row => !!row.metadata?.reactions)).metadata?.reactions).toEqual({
+ '111@lid': 'yes',
+ });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'RAW_REVOKE', remoteJid: '111@lid', fromMe: false },
+ message: { protocolMessage: { type: 0, key: { id: 'CACHE_ONLY' } } },
+ messageTimestamp: 1700000029,
+ },
+ ],
+ });
+ await drainProjection();
+ expect(await rowEventually('CACHE_ONLY', row => row.type === 'revoked')).toMatchObject({
+ chatId: '111@lid',
+ body: '',
+ type: 'revoked',
+ });
+ await ds.getRepository(Message).save({
+ sessionId: s1,
+ waMessageId: 'LEGACY',
+ chatId: '[email protected]',
+ to: 'me',
+ body: 'old body',
+ type: 'text',
+ direction: MessageDirection.INCOMING,
+ metadata: {},
+ });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'LEGACY', remoteJid: '[email protected]', fromMe: false },
+ message: { conversation: 'old body' },
+ messageTimestamp: 1700000028,
+ },
+ ],
+ });
+ await drainProjection();
+ const editLegacy = (id: string) =>
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id, remoteJid: '111@lid', fromMe: false },
+ messageTimestamp: 1700000029,
+ message: {
+ protocolMessage: { type: 14, key: { id: 'LEGACY' }, editedMessage: { conversation: 'new body' } },
+ },
+ },
+ ],
+ });
+ editLegacy('EDIT_FOREIGN');
+ await drainProjection();
+ expect((await ds.getRepository(Message).findOneByOrFail({ waMessageId: 'LEGACY' })).body).toBe('old body');
+ expect((await adapter.getChats()).find(chat => chat.id === '[email protected]')?.lastMessage).toBe('old body');
+ if (source === 'contact') {
+ expect(await adapter.getContactById('[email protected]')).toBeNull();
+ fakeSock.fire('contacts.update', [{ id: '111@lid', name: 'Private name' }]);
+ const contacts = await adapter.getContacts();
+ expect(await fence.filter({ allowedChats: ['[email protected]'] }, contacts, contact => contact.id)).toEqual([]);
+ expect(await fence.filter({ allowedChats: ['111@lid'] }, contacts, contact => contact.id)).toContainEqual(
+ expect.objectContaining({ id: '111@lid', name: 'Private name' }),
+ );
+ }
+ clock += 300_000;
+
+ await expect(resolver.resolveSenderPhone(s1, '111@lid')).resolves.toBe('628111');
+ await settle();
+
+ expect(await repo.findOne({ where: { lid: '111' } })).toMatchObject({
+ phone: '628222',
+ sessionId: s2,
+ isReported: false,
+ });
+ for (const node of [store, peer]) {
+ const fence = new ChatScopeService(node);
+ const key = { allowedChats: ['[email protected]'] };
+ expect(await fence.allows(key, '111@lid')).toBe(false);
+ expect((await fence.scopeForFilter(key))!.allowed.has('111@lid')).toBe(false);
+ }
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'CURRENT', remoteJid: '111@lid', remoteJidAlt: '[email protected]', fromMe: false },
+ message: { conversation: 'hello' },
+ messageTimestamp: 1700000030,
+ },
+ ],
+ });
+ await settle();
+ expect(await repo.findOne({ where: { lid: '111' } })).toMatchObject({ phone: '628222', sessionId: s1 });
+ expect(await new ChatScopeService(store).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(true);
+ const failedChange = jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ const changed = {
+ key: { id: 'CHANGED', remoteJid: '111@lid', remoteJidAlt: '[email protected]', fromMe: false },
+ message: { conversation: 'new number' },
+ messageTimestamp: 1700000031,
+ };
+ fakeSock.fire('messages.upsert', { type: 'notify', messages: [changed] });
+ await settle();
+ expect(await repo.findOne({ where: { lid: '111' } })).toMatchObject({ phone: '628222' });
+ failedChange.mockRestore();
+ const recovered = jest.spyOn(repo, 'upsert');
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'NO_ALT', remoteJid: '111@lid', fromMe: false },
+ message: { conversation: 'hello' },
+ messageTimestamp: 1700000032,
+ },
+ ],
+ });
+ clock += 300_000;
+ await expect(resolver.resolveSenderPhone(s1, '111@lid')).resolves.toBe('628333');
+ await settle();
+ expect(recovered).not.toHaveBeenCalled();
+ expect(await repo.findOne({ where: { lid: '111' } })).toMatchObject({ phone: '628222' });
+ const restoredReader = new LidMappingStoreService(repo);
+ await restoredReader.reload();
+ expect(await repo.findOneByOrFail({ lid: '111' })).toMatchObject({ phone: '628222', isReported: false });
+ for (const reader of [peer, restoredReader]) {
+ expect(await new ChatScopeService(reader).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(false);
+ expect(await new ChatScopeService(reader).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(false);
+ }
+
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [{ ...changed, key: { ...changed.key, id: 'RETRY' } }],
+ });
+ await settle();
+ expect(await repo.findOne({ where: { lid: '111' } })).toMatchObject({ phone: '628333', sessionId: s1 });
+ expect(await new ChatScopeService(store).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(true);
+ await peer.remember('111', '628111', s2);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ editLegacy('EDIT_MATCHING');
+ await drainProjection();
+ expect((await rowEventually('LEGACY', row => row.body === 'new body')).body).toBe('new body');
+ expect(edits).toHaveBeenCalledTimes(2);
+ expect((await adapter.getChats()).find(chat => chat.id === '[email protected]')?.lastMessage).toBe('new body');
+ const updates = fakeStore.update.mock.calls as Array<
+ [string, string, (message: unknown) => { message: { conversation: string } | null } | null]
+ >;
+ const update = updates.filter(([, id]) => id === 'LEGACY').at(-1)?.[2];
+ expect(
+ update?.({
+ key: { id: 'LEGACY', remoteJid: '[email protected]', fromMe: false },
+ message: { conversation: 'old body' },
+ })?.message?.conversation,
+ ).toBe('new body');
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { id: 'LEGACY_REVOKE', remoteJid: '111@lid', fromMe: false },
+ message: { protocolMessage: { type: 0, key: { id: 'LEGACY' } } },
+ messageTimestamp: 1700000033,
+ },
+ ],
+ });
+ expect(await rowEventually('LEGACY', row => row.type === 'revoked')).toMatchObject({
+ chatId: '[email protected]',
+ body: '',
+ type: 'revoked',
+ });
+ const removeBody = updates.filter(([, id]) => id === 'LEGACY').at(-1)?.[2];
+ expect(
+ removeBody?.({
+ key: { id: 'LEGACY', remoteJid: '[email protected]', fromMe: false },
+ message: { conversation: 'new body' },
+ })?.message,
+ ).toBeNull();
+ await peer.rememberIfUnknown('111', '628222', s2);
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ fakeStore.getMessage.mockResolvedValueOnce({
+ key: { id: 'CONFIRMED', remoteJid: '111@lid', fromMe: true },
+ message: { conversation: 'own' },
+ });
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce({ list: [{ id: '[email protected]', lid: '111@lid' }] });
+ await adapter.starMessage('[email protected]', 'CONFIRMED', true);
+ await settle();
+ expect(await repo.findOneByOrFail({ lid: '111' })).toMatchObject({ phone: '628111', isReported: true });
+ expect(await fence.allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(true);
+ } finally {
+ await adapter.destroy();
+ await ds.destroy();
+ if (admin) {
+ await admin.query(`DROP SCHEMA "${schema}" CASCADE`);
+ await admin.destroy();
+ }
+ }
+ },
+ );
});
describe('address book on a first link', () => {
@@ -7133,36 +7808,40 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
['clearChatMessages', (a: BaileysAdapter) => a.clearChatMessages('[email protected]')],
['archiveChat', (a: BaileysAdapter) => a.archiveChat('[email protected]', true)],
['deleteChat', (a: BaileysAdapter) => a.deleteChat('[email protected]')],
- ])('%s addresses a lid-keyed chat by its lid when called with the listed @c.us id', async (_n, act) => {
- const adapter = newAdapter();
- await adapter.initialize({});
- fakeSock.fire('connection.update', { connection: 'open' });
- fakeSock.fire('chats.upsert', [{ id: '484848@lid' }]);
- fakeSock.fire('messages.upsert', {
- type: 'notify',
- messages: [
- {
- key: { remoteJid: '484848@lid', remoteJidAlt: '[email protected]', fromMe: false, id: 'M1' },
- message: { conversation: 'hi' },
- messageTimestamp: 1700000020,
- },
- ],
- });
- await new Promise(r => setImmediate(r));
- expect((await adapter.getChats())[0]?.id).toBe('[email protected]');
- await expect(act(adapter)).resolves.toBe(true);
- expect(fakeSock.chatModify).toHaveBeenCalledWith(
- expect.objectContaining({
- lastMessages: [{ key: expect.objectContaining({ id: 'M1' }) as unknown, messageTimestamp: 1700000020 }],
- }),
- '484848@lid',
- );
- });
+ ])(
+ '%s addresses a lid-keyed chat by its lid when called with the phone alias confirmed by a fresh query',
+ async (_n, act) => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ fakeSock.fire('chats.upsert', [{ id: '484848@lid' }]);
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '484848@lid', remoteJidAlt: '[email protected]', fromMe: false, id: 'M1' },
+ message: { conversation: 'hi' },
+ messageTimestamp: 1700000020,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect((await adapter.getChats())[0]?.id).toBe('484848@lid');
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce({ list: [{ id: '[email protected]', lid: '484848@lid' }] });
+ await expect(act(adapter)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lastMessages: [{ key: expect.objectContaining({ id: 'M1' }) as unknown, messageTimestamp: 1700000020 }],
+ }),
+ '484848@lid',
+ );
+ },
+ );
// The writes that need no last message resolve the chat the same way. Keyed by the phone jid, the
// patch named a chat the phone does not hold, and its local echo added a second row to GET /chats
// under the same @c.us id, carrying the mute or pin the listed row never showed.
- describe('writes without a last message on a lid-keyed chat called with the listed @c.us id', () => {
+ describe('writes without a last message on a lid-keyed chat called with the phone alias confirmed by a fresh query', () => {
const lidKeyedChat = async (): Promise<BaileysAdapter> => {
const adapter = newAdapter();
await adapter.initialize({});
@@ -7179,7 +7858,8 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
],
});
await new Promise(r => setImmediate(r));
- expect((await adapter.getChats()).map(c => c.id)).toEqual(['[email protected]']);
+ expect((await adapter.getChats()).map(c => c.id)).toEqual(['484848@lid']);
+ fakeSock.executeUSyncQuery.mockResolvedValueOnce({ list: [{ id: '[email protected]', lid: '484848@lid' }] });
return adapter;
};
@@ -7199,7 +7879,7 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
// Baileys replays its own patch as chats.update under the jid the patch was indexed by.
fakeSock.fire('chats.update', [{ id: jid, ...echo }]);
expect(await adapter.getChats()).toEqual([
- expect.objectContaining({ id: '[email protected]', name: 'Alice', ...state }),
+ expect.objectContaining({ id: '484848@lid', name: 'Alice', ...state }),
]);
});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 4add37110..7c349504b 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1,6 +1,6 @@
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
-import { isChannelJid } from '../identity/wa-id';
+import { isChannelJid, parseWaId, toNeutralJid } from '../identity/wa-id';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WASocket } from '@whiskeysockets/baileys';
import { BaileysChannels } from './baileys-channels';
@@ -66,6 +66,8 @@ import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-dead
export { createProxyAgent } from './baileys-lifecycle';
export class BaileysAdapter implements IWhatsAppEngine {
+ readonly contactPhoneLookupPersistence = 'seed' as const;
+
private readonly logger = createLogger('BaileysAdapter');
// Bound concurrent inbound media downloads: each materialises a full decrypted buffer in heap, so an
// unbounded fire-and-forget loop lets a sender flood the gateway with N parallel multi-MB allocations.
@@ -132,7 +134,13 @@ export class BaileysAdapter implements IWhatsAppEngine {
},
getSocketOrNull: () => this.sock,
logger: this.logger,
- toNeutralJid: jid => this.sessionStore.toNeutralJid(jid),
+ toNeutralJid: jid => {
+ const ownLid = this.sock?.user?.lid;
+ if (ownLid && parseWaId(jid).kind === 'lid' && parseWaId(jid).userPart === parseWaId(ownLid).userPart) {
+ return toNeutralJid(this.normalizedSelfJid());
+ }
+ return this.sessionStore.toNeutralJid(jid);
+ },
normalizedSelfJid: () => this.normalizedSelfJid(),
loadLib: () => this.loadLib(),
getFetchDispatcher: () => this.lifecycle.fetchDispatcher(),
@@ -175,8 +183,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
getEphemeralExpiration: chatId => this.sessionStore.getEphemeralExpiration(chatId),
getStoredMessage: messageId => this.config.messageStore?.getMessage(this.config.dbSessionId, messageId),
getStoredMessages: messageIds => this.config.messageStore?.getMessages(this.config.dbSessionId, messageIds),
- recordLidMapping: (lid, pn) =>
- this.sessionStore.addLidMappings([{ lid: `${lid.split('@')[0].split(':')[0]}@lid`, pn }]),
+ recordLidMapping: (lid, pn, isReported = true) =>
+ this.sessionStore.addLidMappings([{ lid: `${lid.split('@')[0].split(':')[0]}@lid`, pn }], isReported),
mapMessage: (msg, contentType, opts) => this.events.mapMessage(msg, contentType, opts),
listContacts: () => this.sessionStore.listContacts(),
contactCount: () => this.sessionStore.listContacts().length,
@@ -191,6 +199,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
removeChats: ids => this.sessionStore.removeChats(ids),
extractEphemeralDuration: msg => this.sessionStore.extractEphemeralDuration(msg),
getOnHistoryMessages: () => this.callbacks.onHistoryMessages,
+ getStoredWriteGeneration: () => this.events.getStoredWriteGeneration(),
authPath: this.authPath,
config: this.config,
// A getter so the events delegate exists by first read: the literal is built before the
@@ -633,8 +642,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
async addLabelToChat(chatId: string, labelId: string): Promise<void> {
this.ensureReady();
this.assertLabelable(chatId);
+ const socket = this.sock!;
+ const jid = await this.contacts.confirmedChatJid(chatId);
+ this.ensureReady();
+ if (this.sock !== socket) throw new EngineNotReadyError();
await withQueryDeadline(
- this.sock!.addChatLabel(this.sessionStore.chatJid(chatId), labelId),
+ socket.addChatLabel(jid, labelId),
BAILEYS_QUERY_BUDGET_MS,
'WhatsApp did not confirm the chat label add in time',
);
@@ -642,8 +655,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {
this.ensureReady();
this.assertLabelable(chatId);
+ const socket = this.sock!;
+ const jid = await this.contacts.confirmedChatJid(chatId);
+ this.ensureReady();
+ if (this.sock !== socket) throw new EngineNotReadyError();
await withQueryDeadline(
- this.sock!.removeChatLabel(this.sessionStore.chatJid(chatId), labelId),
+ socket.removeChatLabel(jid, labelId),
BAILEYS_QUERY_BUDGET_MS,
'WhatsApp did not confirm the chat label removal in time',
);
diff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.ts
index ccd98f9d5..1c88fed8d 100644
--- a/src/engine/adapters/inbound-hold.spec.ts
+++ b/src/engine/adapters/inbound-hold.spec.ts
@@ -232,7 +232,7 @@ describe('Baileys inbound messages held for storage', () => {
getOnCallOutcome: () => undefined,
...store,
} as unknown as BaileysEventsHost;
- return { events: new BaileysEvents(host), emitted, recordKeyLidMappings };
+ return { events: new BaileysEvents(host), emitted, recordKeyLidMappings, limiter: host.inboundLimiter };
};
const media = (id: string, chat: string, over: Row = {}): WAMessage => ({
@@ -1457,6 +1457,336 @@ describe('Baileys inbound messages held for storage', () => {
},
);
+ it.each([1, 4])('orders mixed changes after their outcome wait and directory read (limiter %i)', async k => {
+ const store = memoryStore();
+ const outcome = deferred<{ conflict: boolean }>();
+ const directory = deferred<string | null>();
+ const findPersistedLidPhone = jest.fn(() => directory.promise);
+ const log: string[] = [];
+ const { events, limiter } = build(
+ k,
+ {
+ onMessage: () => ({ settled: outcome.promise }),
+ onMessageEdited: () => {
+ log.push('edit');
+ },
+ onMessageReaction: () => {
+ log.push('reaction');
+ },
+ },
+ Object.assign(store, { findPersistedLidPhone }),
+ );
+ upsert(events, text('M', '[email protected]'));
+ await flush();
+ const e = edit('E', 'M', 'fixed');
+ const r = reaction('R', 'M', 'ok');
+ e.key.remoteJid = r.key.remoteJid = '777@lid';
+ upsert(events, e, r);
+ await flush();
+ expect(log).toEqual([]);
+ outcome.resolve({ conflict: true });
+ await flush();
+ expect(findPersistedLidPhone).toHaveBeenCalledTimes(1);
+ expect(log).toEqual([]);
+ directory.resolve('628111');
+ await flush();
+ expect(log).toEqual(['edit', 'reaction']);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ });
+
+ it.each(['active', 'retired', 'throwing'] as const)(
+ 'prepares another target while one waits and releases its queue when %s',
+ async ending => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ store.copies.set('N', text('N', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const log: string[] = [];
+ const { events, limiter } = build(
+ 4,
+ {
+ onMessageEdited: e => {
+ if (ending === 'throwing') throw new Error('consumer failed');
+ log.push(`edit ${e.messageId}`);
+ },
+ onMessageReaction: r => {
+ log.push(`reaction ${r.messageId}`);
+ },
+ },
+ store,
+ );
+ upsert(events, edit('E', 'M', 'fixed'), reaction('R', 'M', 'a'), reaction('N1', 'N', 'b'));
+ await flush();
+ expect(log).toEqual(['reaction N']);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ if (ending === 'retired') events.fenceStoredWrites();
+ gate.resolve();
+ await flush();
+ expect(log).toEqual(
+ ending === 'retired'
+ ? ['reaction N']
+ : ending === 'throwing'
+ ? ['reaction N', 'reaction M']
+ : ['reaction N', 'edit M', 'reaction M'],
+ );
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(0);
+ upsert(events, reaction('CURRENT', 'M', 'current'));
+ await flush();
+ expect(log.at(-1)).toBe('reaction M');
+ },
+ );
+
+ it.each([
+ ['reaction', false],
+ ['reaction', true],
+ ['edit', false],
+ ['edit', true],
+ ['revoke', false],
+ ['revoke', true],
+ ] as const)('finishes a prepared %s only in its original generation (retired: %s)', async (kind, retired) => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const announced = jest.fn();
+ const { events, limiter } = build(
+ 4,
+ {
+ onMessageEdited: announced,
+ onMessageRevoked: announced,
+ onMessageReaction: announced,
+ },
+ store,
+ );
+ const message = kind === 'reaction' ? reaction('CHANGE', 'M', 'a') : edit('CHANGE', 'M', 'fixed');
+ if (kind === 'revoke') message.message = { protocolMessage: { type: 0, key: target('M') } };
+ upsert(events, message);
+ await flush();
+ if (retired) events.fenceStoredWrites();
+ gate.resolve();
+ await flush();
+ expect(announced).toHaveBeenCalledTimes(retired ? 0 : 1);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ announced.mockClear();
+ upsert(events, reaction('CURRENT', 'M', 'current'));
+ await flush();
+ expect(announced).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([1, 4])(
+ 'keeps all 64 prepared edits in arrival order without media slots (limiter %i)',
+ async concurrency => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const log: string[] = [];
+ const { events, limiter } = build(
+ concurrency,
+ {
+ onMessageEdited: e => {
+ log.push(e.body);
+ },
+ },
+ store,
+ );
+ upsert(events, ...Array.from({ length: 64 }, (_, i) => edit(`E${i}`, 'M', `v${i + 1}`)));
+ await flush();
+ expect(log).toEqual([]);
+ expect(limiter.activeCount).toBe(0);
+ gate.resolve();
+ await flush();
+ expect(log).toEqual(Array.from({ length: 64 }, (_, i) => `v${i + 1}`));
+ expect(store.copies.get('M')?.message?.conversation).toBe('v64');
+ expect(limiter.activeCount).toBe(0);
+ },
+ );
+
+ it.each([1, 4])(
+ 'backpressures preparations above 64 without changing edit order (limiter %i)',
+ async concurrency => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const log: string[] = [];
+ const { events, limiter } = build(
+ concurrency,
+ {
+ onMessageEdited: e => {
+ log.push(e.body);
+ },
+ },
+ store,
+ );
+ upsert(events, edit('E0', 'M', 'v1'));
+ await flush();
+ upsert(events, ...Array.from({ length: 69 }, (_, i) => edit(`E${i + 1}`, 'M', `v${i + 2}`)));
+ await flush();
+ expect(log).toEqual([]);
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(64);
+ gate.resolve();
+ await flush();
+ expect(log).toEqual(Array.from({ length: 70 }, (_, i) => `v${i + 1}`));
+ expect(store.copies.get('M')?.message?.conversation).toBe('v70');
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(0);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ },
+ );
+
+ it.each([1, 4])(
+ 'lets a queued original run while 70 foreign changes wait for it (limiter %i)',
+ async concurrency => {
+ const store = memoryStore();
+ const arrived = deferred<string>();
+ const edits: string[] = [];
+ const { events, limiter, emitted } = build(
+ concurrency,
+ {
+ onMessage: m => {
+ arrived.resolve(m.id);
+ },
+ onMessageEdited: e => {
+ edits.push(e.body);
+ },
+ },
+ store,
+ );
+ upsert(
+ events,
+ ...Array.from({ length: 70 }, (_, i) => edit(`E${i}`, 'M', `v${i + 1}`)),
+ text('M', '[email protected]'),
+ );
+ expect(await Promise.race([arrived.promise, sleep(400).then(() => null)])).toBe('M');
+ await flush();
+ expect(emitted).toEqual(['M']);
+ expect(edits).toEqual([]);
+ expect(store.copies.get('M')?.key.remoteJid).toBe('[email protected]');
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(0);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ },
+ );
+
+ it.each([false, true])(
+ 'does not replay prepared callbacks when the limiter closes (retired: %s)',
+ async retired => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const log: string[] = [];
+ const { events, limiter } = build(
+ 4,
+ {
+ onMessageEdited: e => {
+ log.push(e.body);
+ },
+ },
+ store,
+ );
+ upsert(events, edit('E0', 'M', 'v1'));
+ await flush();
+ upsert(events, ...Array.from({ length: 69 }, (_, i) => edit(`E${i + 1}`, 'M', `v${i + 2}`)));
+ await flush();
+ if (retired) events.fenceStoredWrites();
+ limiter.close();
+ gate.resolve();
+ await flush();
+ expect(log).toEqual(retired ? [] : Array.from({ length: 70 }, (_, i) => `v${i + 1}`));
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(0);
+ expect(limiter.activeCount).toBe(0);
+ expect(limiter.queuedCount).toBe(0);
+ },
+ );
+
+ it('starts the current generation without waiting for an old preparation read', async () => {
+ const store = memoryStore();
+ store.copies.set('M', text('M', CHAT));
+ const read = store.getStoredMessage;
+ const gate = deferred<void>();
+ let first = true;
+ store.getStoredMessage = id => {
+ if (id === 'M' && first) {
+ first = false;
+ return gate.promise.then(() => read(id));
+ }
+ return read(id);
+ };
+ const current = deferred<string>();
+ const edited = jest.fn();
+ const { events, limiter } = build(
+ 4,
+ {
+ onMessageEdited: edited,
+ onMessageReaction: r => {
+ current.resolve(r.reaction);
+ },
+ },
+ store,
+ );
+ upsert(events, ...Array.from({ length: 64 }, (_, i) => edit(`E${i}`, 'M', 'old')));
+ await flush();
+ events.fenceStoredWrites();
+ upsert(events, reaction('CURRENT', 'M', 'current'));
+ try {
+ expect(await Promise.race([current.promise, sleep(400).then(() => null)])).toBe('current');
+ } finally {
+ gate.resolve();
+ }
+ await flush();
+ expect(edited).not.toHaveBeenCalled();
+ expect((events as unknown as { changesPreparing: number }).changesPreparing).toBe(0);
+ expect(limiter.activeCount).toBe(0);
+ });
+
// In the turn of the emit, so they reach the message before the session has written its row: an edit that
// meets the row with the text it already has is no edit to the session, and takes no marker.
it('announces what waited in the turn of the emit', async () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 7e30aef41..dab1d734d 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -28,7 +28,14 @@ import { type WwebjsCalls } from './wwebjs-calls';
import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';
import { resolveAuthTimeoutMs, resolveEngineInitTimeoutMs } from '../engine-init-timeout';
import * as fs from 'fs';
-import { createHash } from 'crypto';
+import { createHash, randomUUID } from 'crypto';
+import { DataSource } from 'typeorm';
+import { EngineRegistry } from '../engine-registry.service';
+import { LidMapping } from '../identity/lid-mapping.entity';
+import { LidMappingStoreService } from '../identity/lid-mapping-store.service';
+import { Session } from '../../modules/session/entities/session.entity';
+import { SessionLidResolver } from '../../modules/session/session-lid-resolver.service';
+import { ChatScopeService } from '../../modules/auth/chat-scope.service';
import * as path from 'path';
import * as ts from 'typescript';
import * as vm from 'vm';
@@ -9546,12 +9553,13 @@ describe('WhatsAppWebJsAdapter number check through the library page code', () =
});
/** The typed number exists under LID; `knownLocally` is whether the page already holds that lid's phone. */
- function checkOn(page: { knownLocally: boolean; secondQuery?: 'fills' | 'throws' }) {
+ function checkOn(page: { knownLocally: boolean; secondQuery?: 'fills' | 'throws' | 'absent' }) {
const wid = (id: string) => ({ _serialized: id, server: id.split('@')[1], user: id.split('@')[0] });
let mapped = page.knownLocally;
const queryWidExists = jest.fn((queried: { server: string }) => {
if (queried.server === 'lid') {
if (page.secondQuery === 'throws') return Promise.reject(new Error('query failed'));
+ if (page.secondQuery === 'absent') return Promise.resolve({});
mapped = true;
}
return Promise.resolve({ wid: wid(LID) });
@@ -9579,6 +9587,99 @@ describe('WhatsAppWebJsAdapter number check through the library page code', () =
expect(queryWidExists).toHaveBeenCalledTimes(1);
});
+ it('seeds an unknown lid from the page cache without replacing a newer shared phone or negative', async () => {
+ const pg = process.env.DATABASE_TYPE === 'postgres';
+ const server = {
+ type: 'postgres' as const,
+ host: process.env.DATABASE_HOST || '127.0.0.1',
+ port: Number(process.env.DATABASE_PORT || 5432),
+ username: process.env.DATABASE_USERNAME || 'openwa',
+ password: process.env.DATABASE_PASSWORD || 'openwa',
+ database: process.env.DATABASE_NAME || 'openwa',
+ };
+ const schema = `lid_lookup_${randomUUID().replace(/-/g, '')}`;
+ const admin = pg ? await new DataSource(server).initialize() : undefined;
+ if (admin) await admin.query(`CREATE SCHEMA "${schema}"`);
+ const entities = [LidMapping, Session];
+ const ds = await new DataSource(
+ pg
+ ? { ...server, schema, extra: { options: `-c search_path=${schema},public` }, entities, synchronize: true }
+ : { type: 'better-sqlite3', database: ':memory:', entities, synchronize: true },
+ ).initialize();
+ const [s1, s2] = ['00000001-0000-4000-8000-000000000000', '00000002-0000-4000-8000-000000000000'];
+ await ds.getRepository(Session).insert([s1, s2].map(id => ({ id, name: id, phone: '6290000000' })));
+ const repo = ds.getRepository(LidMapping);
+ const store = new LidMappingStoreService(repo);
+ const peer = new LidMappingStoreService(repo);
+ await store.onModuleInit();
+ await peer.onModuleInit();
+ const { adapter, queryWidExists } = checkOn({ knownLocally: true });
+ const engines = new EngineRegistry();
+ engines.set(s1, adapter);
+ const resolver = new SessionLidResolver(engines, store);
+ let clock = 0;
+ (resolver as unknown as { now: () => number }).now = () => clock;
+ const pending = new Set<Promise<boolean>>();
+ for (const method of ['remember', 'rememberIfUnknown'] as const) {
+ const real = store[method].bind(store);
+ jest.spyOn(store, method).mockImplementation((...args: Parameters<typeof store.remember>) => {
+ const promise = real(...(args as [string, string, string]));
+ pending.add(promise);
+ void promise.finally(() => pending.delete(promise));
+ return promise;
+ });
+ }
+ const settle = async () => {
+ for (let i = 0; i < 5; i++) {
+ await Promise.allSettled([...pending]);
+ await new Promise(resolve => setImmediate(resolve));
+ }
+ };
+ try {
+ await expect(resolver.resolveSenderPhone(s1, LID)).resolves.toBe('551187654321');
+ await settle();
+ expect(await repo.findOne({ where: { lid: '159442138038327' } })).toMatchObject({ phone: '551187654321' });
+ await peer.remember('159442138038327', '628222', s2);
+ await store.reload();
+ clock += 300_000;
+ await expect(resolver.resolveSenderPhone(s1, LID)).resolves.toBe('551187654321');
+ await settle();
+ expect(queryWidExists).not.toHaveBeenCalled();
+ expect(await repo.findOne({ where: { lid: '159442138038327' } })).toMatchObject({
+ phone: '628222',
+ sessionId: s2,
+ });
+ await peer.remember('159442138038327', null, s2);
+ await store.reload();
+ clock += 300_000;
+ await expect(resolver.resolveSenderPhone(s1, LID)).resolves.toBe('551187654321');
+ await settle();
+ expect(await repo.findOne({ where: { lid: '159442138038327' } })).toMatchObject({ phone: null });
+ for (const node of [store, peer]) {
+ const fence = new ChatScopeService(node);
+ const key = { allowedChats: [PN] };
+ expect(await fence.allows(key, LID)).toBe(false);
+ expect((await fence.scopeForFilter(key))!.allowed.has(LID)).toBe(false);
+ }
+ const restarted = new LidMappingStoreService(repo);
+ await restarted.onModuleInit();
+ expect(await restarted.findPhoneForLid(LID)).toBeNull();
+ await store.remember('159442138038327', '551187654321', s1);
+ const hidden = checkOn({ knownLocally: false, secondQuery: 'absent' });
+ engines.set(s1, hidden.adapter);
+ await expect(resolver.resolveSenderPhone(s1, LID)).resolves.toBeNull();
+ await settle();
+ expect(hidden.queryWidExists).toHaveBeenCalledTimes(1);
+ expect(await repo.findOne({ where: { lid: '159442138038327' } })).toMatchObject({ phone: null, sessionId: s1 });
+ } finally {
+ await ds.destroy();
+ if (admin) {
+ await admin.query(`DROP SCHEMA "${schema}" CASCADE`);
+ await admin.destroy();
+ }
+ }
+ });
+
it('sends a second query when the page does not, and answers the phone it reads', async () => {
const { adapter, queryWidExists } = checkOn({ knownLocally: false, secondQuery: 'fills' });
await expect(adapter.getNumberId('5511987654321')).resolves.toBe(PN);
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 620cc78a5..2bb8bc2c5 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -100,6 +100,8 @@ export interface WhatsAppWebJsConfig {
// imports resolveWebVersionPin for use in initialize().
export class WhatsAppWebJsAdapter implements IWhatsAppEngine {
+ readonly contactPhoneLookupPersistence = 'seed' as const;
+
private readonly logger = createLogger('WhatsAppWebJsAdapter');
// Bound concurrent inbound media downloads: each one holds the whole decrypted file in the browser
// page and, when within the cap, its base64 in Node, so an unbounded burst could stack many multi-MB
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 472040eb1..f9196ec8e 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -1,6 +1,6 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { In, IsNull, Raw, Repository } from 'typeorm';
+import { In, IsNull, Not, Raw, Repository } from 'typeorm';
import { LidMapping } from './lid-mapping.entity';
import { userPart } from './wa-id';
import { createLogger } from '../../common/services/logger.service';
@@ -47,8 +47,8 @@ export interface LidMappingStore {
getCached(lid: string): string | null | undefined;
/**
* Resolve any WA JID through the mirror: the phone digits for its user part, `null` when the lid
- * is known-unresolved or never seen. The webhook filter match, automation-rule match, plugin
- * engine reads, and status contact grouping all resolve through this one method so they agree.
+ * is known-unresolved, unreported or never seen. This hot-cache view may lag another process;
+ * alias authorization and rule matching await the persisted reads below.
*/
resolveLid(jid: string): string | null;
/** Sync reverse lookup: the lids currently mapped to this phone (used by the message from-filter). */
@@ -65,13 +65,14 @@ export interface LidMappingStore {
* Never rejects; resolves false when its write failed.
*/
remember(lid: string, phone: string | null, sessionId?: string): Promise<boolean>;
+ /** Keep a cached lookup for display without authorizing it or replacing a stored phone or negative. */
+ rememberIfUnknown?(lid: string, phone: string, sessionId?: string): Promise<boolean>;
}
/**
- * Backs lid resolution with the persisted {@link LidMapping} table. Resolution must be synchronous
- * (filters/dispatch can't await a query), so the table is loaded into an in-memory map on boot and kept
- * warm by write-through. A forward map (lid -> phone) serves resolution; a reverse map (phone -> lids)
- * serves the from-filter.
+ * Backs lid resolution with the persisted {@link LidMapping} table. A bounded synchronous mirror
+ * serves display and hot-cache reads, while authorization and rule matching await the table's current
+ * reported pairings. Write-through keeps the local forward and reverse maps warm.
*
* The forward map is bounded by an LRU cap (`LID_MAPPING_CACHE_MAX`, default 5000) so a long-running,
* contact-heavy account does not accumulate one entry per distinct LID ever seen into a slow memory leak.
@@ -86,6 +87,8 @@ export interface LidMappingStore {
export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
private readonly logger = createLogger('LidMappingStore');
private readonly lidToPhone = new Map<string, string | null>();
+ /** Origin of resident display-only mappings, bounded and evicted with the forward mirror. */
+ private readonly unreported = new Set<string>();
private readonly phoneToLids = new Map<string, Set<string>>();
/** Repository fallbacks in flight, one per lid, so a hot miss path can't stack duplicate queries. */
private readonly pendingLookups = new Set<string>();
@@ -111,9 +114,13 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
* maps synchronously and writes the table afterwards, so between the two a table read answers "no
* row" about a mapping that is about to exist. The forward map cannot stand in for this: the LRU
* can evict the entry inside that same window, leaving it indistinguishable from never-learned.
- * Counted per lid, so the first of two overlapping writes settling does not clear the second.
+ * Counted per lid, so the first of two overlapping writes settling does not clear the second. The
+ * latest actual report's token remains until all older writes settle, isolating their late results.
*/
- private readonly unsettledWrites = new Map<string, number>();
+ private readonly unsettledWrites = new Map<
+ string,
+ { count: number; latestReport?: object; latestOperation?: { phone: string | null } }
+ >();
/**
* Lids a write started for while their table read was in flight. That read may have run before the
* write committed, so whatever it answers predates the mapping this process now holds.
@@ -121,16 +128,17 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
private readonly racedLookups = new Set<string>();
/**
* Sessions counted as having written or reported the phone a lid holds in {@link lidToPhone} (a loaded
- * row counts its owner). One not counted that reports the same phone takes the row, in one write, and is
- * counted; one already counted writes nothing. So the row names the latest uncounted session to report
+ * row counts its owner). An uncounted session reporting the same phone takes the row and is counted
+ * after its write succeeds; one already counted preserves the owner while checking for a changed row
+ * on another node. So the row names the latest uncounted session to report
* the phone, not the latest to report it: after s1, s2, s1 report one phone it names s2, and s2's
* negative clears a phone s1 still sees. Started anew when the phone changes, dropped with the cached
- * entry, on an applied negative and on any release, and a session whose write failed leaves it.
+ * entry, on an applied negative and on any release. A failed write does not forget an earlier success.
*/
private readonly seenBy = new Map<string, Set<string>>();
/**
- * Cached lids whose phone failed to write here (see {@link unstored}). Kept only while the cache holds that
- * phone: dropped with the cached entry, and once a write of it lands or a negative clears the row.
+ * Cached phones whose report is pending or failed, or whose cached contradiction failed to persist.
+ * Kept only while the cache holds that phone, until a current write lands or a negative clears it.
*/
private readonly failedWrites = new Set<string>();
/** When a failed write was last logged, on {@link now}, and how many have failed since without a line. */
@@ -174,15 +182,20 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
take: this.maxCachedLids > 0 ? this.maxCachedLids : undefined,
});
this.lidToPhone.clear();
+ this.unreported.clear();
this.phoneToLids.clear();
this.seenBy.clear();
this.failedWrites.clear();
+ for (const writing of this.unsettledWrites.values()) {
+ delete writing.latestReport;
+ delete writing.latestOperation;
+ }
// A reload re-reads the table, so every recorded absence is a fresh question again.
this.absentFromTable.clear();
// Oldest first, so the newest row ends at the most-recent end of the LRU rather than the first
// one evicted.
for (const row of rows.reverse()) {
- this.index(row.lid, row.phone, row.sessionId);
+ this.index(row.lid, row.phone, row.sessionId, row.isReported);
}
this.logger.log(
`Loaded ${rows.length} lid->phone mappings into cache${this.maxCachedLids ? ` (cap ${this.maxCachedLids})` : ''}`,
@@ -206,12 +219,13 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
}
resolveLid(jid: string): string | null {
- return this.getCached(userPart(jid)) ?? null;
+ const lid = userPart(jid);
+ return this.unreported.has(lid) ? null : (this.getCached(lid) ?? null);
}
lidsForPhone(phone: string): string[] {
const set = this.phoneToLids.get(phone);
- return set ? [...set] : [];
+ return set ? [...set].filter(lid => !this.unreported.has(lid)) : [];
}
/**
@@ -226,7 +240,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
return (await this.readLidsForPhones([phone]))[phone];
} catch (err) {
this.logger.warn(`Could not read lids for a phone: ${err instanceof Error ? err.message : String(err)}`);
- return this.lidsForPhone(phone);
+ return this.lidsForPhone(phone).filter(lid => !this.unreported.has(lid));
}
}
@@ -238,15 +252,15 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
async phonesForLidsPersisted(lids: string[]): Promise<Record<string, string | null>> {
const out: Record<string, string | null> = {};
if (lids.length === 0) return out;
- // The mirror is only the fallback for a failed or empty table read, so it is read without getCached:
+ // The mirror is only the fallback for a failed table read, so it is read without getCached:
// that warms every miss with a findOne of its own, one per lid ahead of the batched query below.
- for (const lid of lids) out[lid] = this.lidToPhone.get(lid) ?? null;
+ for (const lid of lids) out[lid] = this.unreported.has(lid) ? null : (this.lidToPhone.get(lid) ?? null);
try {
for (const batch of chunk(lids)) {
const rows = await this.repo.find({ where: { lid: In(batch) } });
- for (const lid of batch) if (this.failedWrites.has(lid)) out[lid] = null;
+ for (const lid of batch) out[lid] = null;
// The table WINS: a stale cached negative must not shadow a mapping another node persisted.
- for (const row of rows) out[row.lid] = this.rowPhone(row.lid, row.phone);
+ for (const row of rows) out[row.lid] = this.rowPhone(row.lid, row.phone, row.isReported);
}
} catch {
// The table may not exist yet (migration pending); the mirror is the best available answer.
@@ -260,29 +274,19 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
return await this.readLidsForPhones(phones);
} catch {
// The table may not exist yet (migration pending); the cache is the best available answer.
- return Object.fromEntries(phones.map(phone => [phone, this.lidsForPhone(phone)]));
+ return Object.fromEntries(
+ phones.map(phone => [phone, this.lidsForPhone(phone).filter(lid => !this.unreported.has(lid))]),
+ );
}
}
- /**
- * A lid answers the phone its row holds ({@link rowPhone}), and a cached reverse entry stands in for a lid
- * the table has no row for (past the cache cap, or its write still in flight), unless that write failed.
- * Throws on a read error.
- */
+ /** Read only current table rows on success; a resident mapping cannot restore a deleted row. */
private async readLidsForPhones(phones: string[]): Promise<Record<string, string[]>> {
- const out: Record<string, Set<string>> = {};
- for (const phone of phones)
- out[phone] = new Set(this.lidsForPhone(phone).filter(lid => !this.failedWrites.has(lid)));
- const cachedLids = [...new Set(phones.flatMap(phone => [...out[phone]]))];
- for (const batch of chunk(cachedLids)) {
- for (const row of await this.repo.find({ where: { lid: In(batch) } })) {
- for (const phone of phones) if (row.phone !== phone) out[phone].delete(row.lid);
- }
- }
+ const out: Record<string, Set<string>> = Object.fromEntries(phones.map(phone => [phone, new Set<string>()]));
for (const batch of chunk(phones)) {
- for (const { lid, phone } of await this.repo.find({ where: { phone: In(batch) } })) {
+ for (const { lid, phone, isReported } of await this.repo.find({ where: { phone: In(batch) } })) {
if (!phone || !out[phone]) continue;
- if (this.rowPhone(lid, phone) === phone) out[phone].add(lid);
+ if (this.rowPhone(lid, phone, isReported) === phone) out[phone].add(lid);
}
}
return Object.fromEntries(phones.map(phone => [phone, [...out[phone]]]));
@@ -298,7 +302,8 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
* for the lid is not stored yet, a row that differs may be the number it replaces: the lid then answers
* none, so no fence lookup admits either one until the write lands.
*/
- private rowPhone(lid: string, phone: string | null): string | null {
+ private rowPhone(lid: string, phone: string | null, isReported = false): string | null {
+ if (!isReported || (this.unreported.has(lid) && this.unstored(lid))) return null;
const cached = this.lidToPhone.get(lid);
return this.unstored(lid) && cached !== undefined && cached !== phone ? null : phone;
}
@@ -306,24 +311,68 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
/**
* Forward lookup for callers that can await: the API-key chat fence and every chat-bound read
* behind it (message history and media, the quoted body, status and handover filters). The table
- * answers first, the in-memory mirror only when the read fails or has no row. The mirror alone is
+ * answers first, the in-memory mirror only when the read fails. The mirror alone is
* not enough: it is LRU-evicted at `LID_MAPPING_CACHE_MAX`, and nothing refreshes it when another
* node re-maps a lid in the shared table, so a cache-first answer could resolve the same lid to
* a phone the fence no longer sees, and a read behind the fence would serve that other chat. The
* row is not indexed into the cache, so a lookup cannot evict hot entries. A row is vetoed while this
- * process has a different phone for the lid in flight or failed ({@link rowPhone}); with no row, a cached
- * phone whose write failed answers none.
+ * process has a different phone for the lid in flight or failed ({@link rowPhone}); with no row, no
+ * alias is authorized until a report commits.
*/
async findPhoneForLid(jid: string): Promise<string | null> {
const lid = userPart(jid);
try {
const row = await this.repo.findOne({ where: { lid } });
- if (row) return this.rowPhone(lid, row.phone);
- if (this.failedWrites.has(lid)) return null;
+ return row ? this.rowPhone(lid, row.phone, row.isReported) : null;
} catch (err) {
this.logger.warn(`Could not read the phone for a lid: ${err instanceof Error ? err.message : String(err)}`);
}
- return this.getCached(lid) ?? null;
+ return this.unreported.has(lid) ? null : (this.getCached(lid) ?? null);
+ }
+
+ /**
+ * A cached lookup can introduce display data, but cannot replace a stored phone or negative or grant
+ * alias access. A conflicting positive revokes alias trust until an engine reports the mapping again.
+ */
+ async rememberIfUnknown(lid: string, phone: string, sessionId?: string): Promise<boolean> {
+ if (!lid) return true;
+ const cached = this.lidToPhone.get(lid);
+ const lookup = { phone };
+ if (cached && cached !== phone) {
+ this.unreported.add(lid);
+ this.seenBy.set(lid, new Set());
+ }
+ const reporters = this.seenBy.get(lid);
+ const writing = this.beginWrite(lid, lookup);
+ try {
+ await this.repo
+ .createQueryBuilder()
+ .insert()
+ .values({ lid, phone, sessionId: sessionId ?? null, updatedAt: new Date() })
+ .orIgnore()
+ .execute();
+ const { affected } = await this.repo.update(
+ { lid, phone: Raw(column => `${column} <> :lookupPhone`, { lookupPhone: phone }), isReported: true },
+ { isReported: false, updatedAt: () => '"updatedAt"' },
+ );
+ if (
+ affected &&
+ writing.latestOperation === lookup &&
+ this.seenBy.get(lid) === reporters &&
+ this.lidToPhone.has(lid)
+ )
+ this.unreported.add(lid);
+ // No optimistic mirror write: another node may already hold a newer phone or negative.
+ this.absentFromTable.delete(lid);
+ return true;
+ } catch (err) {
+ if (writing.latestOperation === lookup && this.seenBy.get(lid) === reporters && this.unreported.has(lid))
+ this.failedWrites.add(lid);
+ this.warnWriteFailed(`Could not store lid mapping: ${err instanceof Error ? err.message : String(err)}`);
+ return false;
+ } finally {
+ this.endWrite(lid, writing);
+ }
}
async remember(lid: string, phone: string | null, sessionId?: string): Promise<boolean> {
@@ -331,35 +380,89 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
const cached = this.lidToPhone.get(lid);
// Unseen-or-changed only, or a phone a session reports here for the first time: a no-op write would
// just churn updatedAt.
- if (cached === phone && (phone === null || !sessionId || this.seenBy.get(lid)?.has(sessionId))) {
- return true;
- }
+ const seen =
+ !this.unreported.has(lid) &&
+ cached === phone &&
+ (phone === null || !sessionId || this.seenBy.get(lid)?.has(sessionId));
// A negative is not cached until the table has taken it: see clear().
- if (phone !== null) this.index(lid, phone, sessionId ?? null);
- this.unsettledWrites.set(lid, (this.unsettledWrites.get(lid) ?? 0) + 1);
- if (this.pendingLookups.has(lid)) this.racedLookups.add(lid);
+ if (!seen && phone !== null) this.index(lid, phone, null);
+ if (phone !== null) this.failedWrites.add(lid);
+ const reporters = this.seenBy.get(lid);
+ const report = { phone };
+ const writing = this.beginWrite(lid, report, true);
try {
- if (phone === null) await this.clear(lid, sessionId ?? null);
+ if (seen && phone !== null) {
+ // A peer may have changed or revoked this row since this node counted the report. Keep the
+ // owner and timestamp for the same phone, but let the latest actual report replace another one.
+ const changed = '"lid_mappings"."phone" IS NULL OR "lid_mappings"."phone" <> EXCLUDED."phone"';
+ const [insert, parameters] = this.repo
+ .createQueryBuilder('lid_mappings')
+ .insert()
+ .values({ lid, phone, sessionId: sessionId ?? null, isReported: true, updatedAt: new Date() })
+ .getQueryAndParameters();
+ await this.repo.query(
+ insert +
+ ` ON CONFLICT ("lid") DO UPDATE SET "phone" = EXCLUDED."phone", "isReported" = true, ` +
+ `"sessionId" = CASE WHEN ${changed} THEN EXCLUDED."sessionId" ELSE "lid_mappings"."sessionId" END, ` +
+ `"updatedAt" = CASE WHEN ${changed} THEN EXCLUDED."updatedAt" ELSE "lid_mappings"."updatedAt" END ` +
+ `WHERE ${changed} OR "lid_mappings"."isReported" = false`,
+ parameters,
+ );
+ } else if (phone === null) await this.clear(lid, sessionId ?? null, seen, report);
else {
- await this.repo.upsert({ lid, phone, sessionId: sessionId ?? null, updatedAt: new Date() }, ['lid']);
- if (this.lidToPhone.get(lid) === phone) this.failedWrites.delete(lid);
+ await this.repo.upsert({ lid, phone, sessionId: sessionId ?? null, isReported: true, updatedAt: new Date() }, [
+ 'lid',
+ ]);
+ }
+ // Count only a stored report in this phone's current cache epoch. A late completion after
+ // P -> Q -> P must not count the first P as a report of the replacement P.
+ if (phone !== null && reporters && this.seenBy.get(lid) === reporters) {
+ const operation = writing.latestOperation;
+ let reported = !this.unreported.has(lid);
+ // A consistent lookup may have revoked the old stored phone while this actual write was
+ // in flight. Only the current reported row can establish which SQL statement landed last.
+ if (!reported && writing.latestReport === report && operation?.phone === phone) {
+ const row = await this.repo.findOne({ where: { lid } }).catch(() => null);
+ reported = row?.isReported === true && row.phone === phone;
+ }
+ if (
+ reported &&
+ this.seenBy.get(lid) === reporters &&
+ writing.latestReport === report &&
+ writing.latestOperation === operation &&
+ operation?.phone === phone
+ ) {
+ this.failedWrites.delete(lid);
+ this.unreported.delete(lid);
+ }
+ if (sessionId && this.seenBy.get(lid) === reporters) reporters.add(sessionId);
}
return true;
} catch (err) {
- // The table does not have this report, so the session's next one writes again.
- if (sessionId) this.seenBy.get(lid)?.delete(sessionId);
- if (phone !== null && this.lidToPhone.get(lid) === phone) this.failedWrites.add(lid);
this.warnWriteFailed(
`Failed to persist lid->phone mapping for ${lid}: ${err instanceof Error ? err.message : String(err)}`,
);
return false;
} finally {
- const left = (this.unsettledWrites.get(lid) ?? 1) - 1;
- if (left > 0) this.unsettledWrites.set(lid, left);
- else this.unsettledWrites.delete(lid);
+ this.endWrite(lid, writing);
}
}
+ /** Keep report and lookup ordering until all older writes settle, without counting a lookup as a report. */
+ private beginWrite(lid: string, operation: { phone: string | null }, actual = false) {
+ const writing = this.unsettledWrites.get(lid) ?? { count: 0 };
+ writing.count++;
+ writing.latestOperation = operation;
+ if (actual) writing.latestReport = operation;
+ this.unsettledWrites.set(lid, writing);
+ if (this.pendingLookups.has(lid)) this.racedLookups.add(lid);
+ return writing;
+ }
+
+ private endWrite(lid: string, writing: { count: number }): void {
+ if (this.unsettledWrites.get(lid) === writing && --writing.count === 0) this.unsettledWrites.delete(lid);
+ }
+
/**
* Record that a session found no phone for a lid. The row is shared by every session, and one account
* can see a contact's number while another cannot, so a negative replaces the row only when it holds
@@ -369,13 +472,18 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
* row is cleared the cached entry is dropped rather than set: a phone written while the statements ran may
* be the newer value, and the next read takes whichever the table holds.
*/
- private async clear(lid: string, sessionId: string | null): Promise<void> {
+ private async clear(
+ lid: string,
+ sessionId: string | null,
+ preserveEmpty: boolean | undefined,
+ report: object,
+ ): Promise<void> {
const updatedAt = new Date();
// Creates the row when there is none; an existing one is left to the conditional update.
await this.repo
.createQueryBuilder()
.insert()
- .values({ lid, phone: null, sessionId, updatedAt })
+ .values({ lid, phone: null, sessionId, isReported: true, updatedAt })
.orIgnore()
.execute();
const replaceable = [
@@ -392,10 +500,16 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
},
...(sessionId ? [{ lid, sessionId }] : []),
];
- const { affected } = await this.repo.update(replaceable, { phone: null, sessionId, updatedAt });
- if (!affected) return;
+ // A loaded negative may be stale after a peer's positive report. Recheck ownership atomically,
+ // preserving an unchanged empty row's owner and timestamp rather than trusting this mirror.
+ const eligible = preserveEmpty
+ ? replaceable.slice(1).map(where => ({ ...where, phone: Not(IsNull()) }))
+ : replaceable;
+ const { affected } = await this.repo.update(eligible, { phone: null, sessionId, isReported: true, updatedAt });
+ if (!affected || this.unsettledWrites.get(lid)?.latestReport !== report) return;
const cached = this.lidToPhone.get(lid);
this.lidToPhone.delete(lid);
+ this.unreported.delete(lid);
this.seenBy.delete(lid);
this.failedWrites.delete(lid);
if (cached) this.unindex(lid, cached);
@@ -421,9 +535,8 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
* that never got here. The rows stay: the table is shared. Never throws: the session is already gone.
*/
async releaseSession(sessionId: string): Promise<void> {
- // A session that already reported a lid's phone writes nothing when it reports it again, so a row left
- // without an owner here would stay so. Every set is dropped, even if the update fails, so each live
- // session's next report takes its rows back.
+ // A counted reporter preserves the current owner on a repeated phone report, so a released row
+ // would stay ownerless. Drop every set even if the update fails, so the next report takes ownership.
this.seenBy.clear();
try {
// updatedAt is kept: no mapping changed, and the preload ranks rows by it.
@@ -459,7 +572,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
if (writeInFlight || this.racedLookups.has(lid)) return;
// Last-write-wins: a mapping indexed while the lookup was in flight is newer.
if (row && !this.lidToPhone.has(row.lid)) {
- this.index(row.lid, row.phone, row.sessionId);
+ this.index(row.lid, row.phone, row.sessionId, row.isReported);
return;
}
if (!row && !this.lidToPhone.has(lid)) this.noteAbsent(lid);
@@ -472,13 +585,16 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
}
/** Update both in-memory indexes, dropping any stale reverse entry from a previous phone. */
- private index(lid: string, phone: string | null, sessionId: string | null): void {
+ private index(lid: string, phone: string | null, sessionId: string | null, isReported = true): void {
+ const previouslyReported = !this.unreported.has(lid);
+ if (isReported) this.unreported.delete(lid);
+ else this.unreported.add(lid);
const prev = this.lidToPhone.get(lid);
if (prev && prev !== phone) {
this.unindex(lid, prev);
}
- const seen = (prev === phone && this.seenBy.get(lid)) || new Set<string>();
- if (sessionId) seen.add(sessionId);
+ const seen = (isReported && previouslyReported && prev === phone && this.seenBy.get(lid)) || new Set<string>();
+ if (isReported && sessionId) seen.add(sessionId);
if (phone) this.seenBy.set(lid, seen);
else this.seenBy.delete(lid);
// Re-insert (delete + set) so the entry moves to the most-recent end of the LRU order even on update.
@@ -518,8 +634,14 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
if (oldest === undefined) break;
const phone = this.lidToPhone.get(oldest);
this.lidToPhone.delete(oldest);
+ this.unreported.delete(oldest);
this.seenBy.delete(oldest);
this.failedWrites.delete(oldest);
+ const writing = this.unsettledWrites.get(oldest);
+ if (writing) {
+ delete writing.latestReport;
+ delete writing.latestOperation;
+ }
if (phone) this.unindex(oldest, phone);
}
}
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index b78453c0e..a231a66ce 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -3,6 +3,7 @@ import { DataSource, FindOperator, In, Repository } from 'typeorm';
import { LidMappingStoreService } from './lid-mapping-store.service';
import { LidMapping } from './lid-mapping.entity';
import { Session } from '../../modules/session/entities/session.entity';
+import { ChatScopeService } from '../../modules/auth/chat-scope.service';
/** A where-clause value: a literal, or a TypeORM `In([...])` FindOperator. */
type Cond = string | FindOperator<unknown>;
@@ -18,7 +19,14 @@ function matches(value: string | null, cond: Cond | undefined): boolean {
/** Minimal in-memory stand-in for the TypeORM repo: just the find()/findOne()/upsert() the store uses. */
function makeFakeRepo(seed: Partial<LidMapping>[] = []) {
- const rows: LidMapping[] = seed.map(r => ({ lid: '', phone: null, sessionId: null, updatedAt: new Date(0), ...r }));
+ const rows: LidMapping[] = seed.map(r => ({
+ lid: '',
+ phone: null,
+ sessionId: null,
+ isReported: true,
+ updatedAt: new Date(0),
+ ...r,
+ }));
return {
rows,
find: jest
@@ -41,6 +49,35 @@ function makeFakeRepo(seed: Partial<LidMapping>[] = []) {
else rows.push(values as LidMapping);
return Promise.resolve({});
}),
+ createQueryBuilder: () => {
+ let values: Partial<LidMapping>;
+ const builder = {
+ insert: () => builder,
+ values: (input: Partial<LidMapping>) => {
+ values = input;
+ return builder;
+ },
+ getQueryAndParameters: () => ['', [values]],
+ };
+ return builder;
+ },
+ query: jest.fn().mockImplementation((_sql: string, [values]: [Partial<LidMapping>]) => {
+ const row = rows.find(r => r.lid === values.lid);
+ if (!row) rows.push(values as LidMapping);
+ else if (row.phone !== values.phone) Object.assign(row, values);
+ else row.isReported = true;
+ return Promise.resolve([]);
+ }),
+ update: jest.fn().mockImplementation((where: Partial<LidMapping>, values: Partial<LidMapping>) => {
+ let affected = 0;
+ for (const row of rows) {
+ if (Object.entries(where).some(([key, value]) => row[key as keyof LidMapping] !== value)) continue;
+ for (const [key, value] of Object.entries(values))
+ if (typeof value !== 'function') Object.assign(row, { [key]: value });
+ affected++;
+ }
+ return Promise.resolve({ affected });
+ }),
};
}
@@ -610,8 +647,14 @@ describe('LidMappingStoreService — deterministic preload + repository fallback
await new Promise(resolve => setImmediate(resolve));
expect(repo.findOne).toHaveBeenCalledTimes(1);
- repo.rows.push({ lid: 'lid-imported', phone: '620003', sessionId: null, updatedAt: new Date(1000) });
- repo.rows.push({ lid: 'lid-newer', phone: '620004', sessionId: null, updatedAt: new Date(2000) });
+ repo.rows.push({
+ lid: 'lid-imported',
+ phone: '620003',
+ sessionId: null,
+ isReported: true,
+ updatedAt: new Date(1000),
+ });
+ repo.rows.push({ lid: 'lid-newer', phone: '620004', sessionId: null, isReported: true, updatedAt: new Date(2000) });
await store.reload(); // cap 1: only lid-newer is preloaded, so lid-imported is never re-indexed
expect(store.getCached('lid-imported')).toBeUndefined(); // the read itself is still a miss
@@ -628,7 +671,7 @@ describe('LidMappingStoreService — deterministic preload + repository fallback
expect(repo.findOne).toHaveBeenCalledTimes(1); // 'lid-restored' is now known to have no row
// A restore brings the row back, then the post-commit reload fails.
- repo.rows.push({ lid: 'lid-restored', phone: '620005', sessionId: null, updatedAt: new Date() });
+ repo.rows.push({ lid: 'lid-restored', phone: '620005', sessionId: null, isReported: true, updatedAt: new Date() });
repo.find.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
await expect(store.reload()).resolves.toBeUndefined();
@@ -651,11 +694,20 @@ describe('LidMappingStoreService — deterministic preload + repository fallback
});
describe('LidMappingStoreService — deterministic persisted lookups (authorization path)', () => {
- it('findPhoneForLid falls back to the cache when the table has no row', async () => {
+ it('does not authorize a resident mapping removed from the table', async () => {
const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);
const store = await newStore(repo);
repo.rows.splice(0, 1); // the preload cached 111; the table no longer holds it
- expect(await store.findPhoneForLid('111@lid')).toBe('628999');
+ expect(store.getCached('111')).toBe('628999');
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: null });
+ expect(await store.findLidsForPhone('628999')).toEqual([]);
+ expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: [] });
+ const scope = new ChatScopeService(store);
+ expect(await scope.allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(false);
+ expect(await scope.allows({ allowedChats: ['111@lid'] }, '[email protected]')).toBe(false);
+ expect(await scope.allows({ allowedChats: ['111@lid'] }, '111@lid')).toBe(true);
+ expect(await scope.allows({ allowedChats: ['[email protected]'] }, '[email protected]')).toBe(true);
expect(repo.findOne).toHaveBeenCalledWith({ where: { lid: '111' } });
});
@@ -732,7 +784,7 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
}
});
- it('findLidsForPhone unions the cache with the persisted table', async () => {
+ it('findLidsForPhone reads all current persisted rows', async () => {
const repo = makeFakeRepo([
{ lid: '111', phone: '628999' },
{ lid: '222', phone: '628999' },
@@ -828,13 +880,13 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
expect(store.lidsForPhone('628999')).toEqual(['111']);
expect(await store.findLidsForPhone('628999')).toEqual([]);
expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: [] });
- // A cached lid with no row yet (its write still in flight) still answers.
+ // Removing the row also removes its alias from successful reads.
await store.remember('222', '628999');
repo.rows.splice(
repo.rows.findIndex(r => r.lid === '222'),
1,
);
- expect(await store.findLidsForPhone('628999')).toEqual(['222']);
+ expect(await store.findLidsForPhone('628999')).toEqual([]);
});
it('answers the row of a lid another node has re-mapped, in every lookup', async () => {
@@ -890,7 +942,7 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
expect(await store.lidsForPhonesPersisted(['628222', '628111'])).toEqual({ 628222: ['111'], 628111: [] });
});
- it('answers a cached phone the table has no row for yet while its first write is in flight', async () => {
+ it('authorizes a first report only once its write reaches the table', async () => {
const repo = makeFakeRepo();
const store = await newStore(repo);
let land!: () => void;
@@ -905,12 +957,16 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizat
);
const writing = store.remember('111', '628111', 'sess-1');
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: null });
+ expect(await store.findLidsForPhone('628111')).toEqual([]);
+ expect(await store.lidsForPhonesPersisted(['628111'])).toEqual({ 628111: [] });
+ land();
+ await writing;
expect(await store.findPhoneForLid('111@lid')).toBe('628111');
expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: '628111' });
expect(await store.findLidsForPhone('628111')).toEqual(['111']);
expect(await store.lidsForPhonesPersisted(['628111'])).toEqual({ 628111: ['111'] });
- land();
- await writing;
});
it('keeps answering a phone the table holds when only another session failed to take it', async () => {
@@ -1006,6 +1062,13 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
const row = (lid: string) => repo.findOne({ where: { lid } });
/** Moves the store's clock on, past or short of the interval between two warnings about failed writes. */
const later = (ms: number) => (clock += ms);
+ const settleWarm = async () => {
+ const deadline = performance.now() + 5000;
+ while ((store as unknown as { pendingLookups: Set<string> }).pendingLookups.size) {
+ if (performance.now() >= deadline) throw new Error('mapping lookup did not finish');
+ await new Promise(resolve => setTimeout(resolve, 1));
+ }
+ };
/** Holds the next call of a repository method until `release` is called; `reached` settles on entry. */
function hold(method: 'upsert' | 'update') {
@@ -1073,6 +1136,969 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
expect(await store.findPhoneForLid('333@lid')).toBeNull();
});
+ it('seeds an unknown phone without optimistically indexing a cached answer', async () => {
+ const pending = store.rememberIfUnknown('111', '628111', s1);
+ expect(store.getCached('111')).toBeUndefined();
+ await expect(pending).resolves.toBe(true);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1 });
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ expect(await store.findLidsForPhone('628111')).toEqual([]);
+ const restarted = new LidMappingStoreService(repo);
+ await restarted.onModuleInit();
+ expect(restarted.getCached('111')).toBe('628111');
+ expect(await restarted.findPhoneForLid('111@lid')).toBeNull();
+ });
+
+ it.each(['preload', 'warm', 'revoked'] as const)(
+ 'does not count a display-only owner as an actual reporter after %s',
+ async mode => {
+ if (mode === 'revoked') {
+ await store.remember('111', '628111', s1);
+ await store.rememberIfUnknown('111', '628222', s3);
+ } else await store.rememberIfUnknown('111', '628111', s1);
+ if (mode === 'preload') await store.reload();
+ else if (mode === 'warm') {
+ store.getCached('111');
+ await settleWarm();
+ }
+ await store.remember('111', '628111', s2);
+ await repo.update({ lid: '111' }, { updatedAt: new Date('2020-01-01T00:00:00Z') });
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ expect((await row('111'))!.updatedAt.getTime()).toBeGreaterThan(Date.parse('2020-01-01T00:00:00Z'));
+ },
+ );
+
+ it('applies a successful actual negative even when a cached lookup completes before its acknowledgment', async () => {
+ await store.remember('111', '628111', s1);
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const update = repo.update.bind(repo);
+ jest.spyOn(repo, 'update').mockImplementationOnce(async (...args) => {
+ const result = await update(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const negative = store.remember('111', null, s1);
+ await reached;
+ await store.rememberIfUnknown('111', '628111', s2);
+ release();
+ await expect(negative).resolves.toBe(true);
+ expect(store.resolveLid('111@lid')).toBeNull();
+ await settleWarm();
+ jest.spyOn(repo, 'findOne').mockRejectedValue(new Error('connection lost'));
+ jest.spyOn(repo, 'find').mockRejectedValue(new Error('connection lost'));
+ await noAlias(store);
+ warn.mockClear();
+ });
+
+ it.each(['628222', null])('does not seed over a stored %s or change its mirror or owner', async phone => {
+ await store.remember('111', phone, s2);
+ await store.reload();
+ await expect(store.rememberIfUnknown('111', '628111', s1)).resolves.toBe(true);
+ expect(await row('111')).toMatchObject({ phone, sessionId: s2 });
+ expect(store.getCached('111')).toBe(phone);
+ expect(store.lidsForPhone('628111')).toEqual([]);
+ if (phone) {
+ await store.remember('111', phone, s1);
+ expect(await row('111')).toMatchObject({ phone, sessionId: s1 });
+ }
+ });
+
+ it('keeps a phone stored by a peer while a cached seed waits to execute', async () => {
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ const builder = repo.createQueryBuilder().insert().values({});
+ const execute = builder.execute.bind(builder);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => (release = resolve));
+ jest.spyOn(builder, 'execute').mockImplementation(async () => {
+ await gate;
+ return execute();
+ });
+ const create = jest.spyOn(repo, 'createQueryBuilder').mockReturnValueOnce(builder as never);
+ const pending = store.rememberIfUnknown('111', '628111', s1);
+ await peer.remember('111', '628222', s2);
+ release();
+ await expect(pending).resolves.toBe(true);
+ create.mockRestore();
+ expect(await row('111')).toMatchObject({ phone: '628222', sessionId: s2 });
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ });
+
+ it('does not clear a failed actual replacement when a cached seed is ignored', async () => {
+ await store.remember('111', '628111', s1);
+ const fail = jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628222', s1)).resolves.toBe(false);
+ fail.mockRestore();
+ warn.mockClear();
+ await expect(store.rememberIfUnknown('111', '628111', s1)).resolves.toBe(true);
+ expect(store.getCached('111')).toBe('628222');
+ expect(await store.findPhoneForLid('111@lid')).toBeNull();
+ });
+
+ it('retries every failed cached seed and limits only warnings', async () => {
+ const builder = repo.createQueryBuilder().insert().values({});
+ const execute = jest.spyOn(builder, 'execute').mockRejectedValue(new Error('connection lost'));
+ const create = jest.spyOn(repo, 'createQueryBuilder').mockReturnValue(builder as never);
+ for (let i = 0; i < 1000; i++) await expect(store.rememberIfUnknown('111', '628111', s1)).resolves.toBe(false);
+ expect(execute).toHaveBeenCalledTimes(1000);
+ expect(warn).toHaveBeenCalledTimes(1);
+ later(60_000);
+ await expect(store.rememberIfUnknown('111', '628111', s1)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(2);
+ expect((warn.mock.calls as Array<[string]>)[1][0]).toContain('999 more failed');
+ create.mockRestore();
+ execute.mockRestore();
+ warn.mockClear();
+ await expect(store.rememberIfUnknown('111', '628111', s1)).resolves.toBe(true);
+ expect(await row('111')).toMatchObject({ phone: '628111' });
+ });
+
+ it('does not keep an old read absence after a cached seed commits', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => (release = resolve));
+ const read = jest.spyOn(repo, 'findOne').mockImplementationOnce(async () => {
+ await gate;
+ return null;
+ });
+ expect(store.getCached('111')).toBeUndefined();
+ await store.rememberIfUnknown('111', '628111', s1);
+ release();
+ await settleWarm();
+ expect(store.getCached('111')).toBeUndefined();
+ await settleWarm();
+ expect(store.getCached('111')).toBe('628111');
+ read.mockRestore();
+ });
+
+ it('warms a cached seed after remembering that the table had no row', async () => {
+ expect(store.getCached('111')).toBeUndefined();
+ await settleWarm();
+ await store.rememberIfUnknown('111', '628111', s1);
+ expect(store.getCached('111')).toBeUndefined();
+ await settleWarm();
+ expect(store.getCached('111')).toBe('628111');
+ });
+
+ it('does not remember a missing row read while a cached seed waits to execute', async () => {
+ const builder = repo.createQueryBuilder().insert().values({});
+ const execute = builder.execute.bind(builder);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => (release = resolve));
+ jest.spyOn(builder, 'execute').mockImplementation(async () => {
+ await gate;
+ return execute();
+ });
+ const create = jest.spyOn(repo, 'createQueryBuilder').mockReturnValueOnce(builder as never);
+ const pending = store.rememberIfUnknown('111', '628111', s1);
+ let releaseRead!: () => void;
+ const readGate = new Promise<void>(resolve => (releaseRead = resolve));
+ const read = jest.spyOn(repo, 'findOne').mockImplementationOnce(async () => {
+ await readGate;
+ return null;
+ });
+ expect(store.getCached('111')).toBeUndefined();
+ release();
+ await pending;
+ releaseRead();
+ await settleWarm();
+ create.mockRestore();
+ read.mockRestore();
+ expect(store.getCached('111')).toBeUndefined();
+ await settleWarm();
+ expect(store.getCached('111')).toBe('628111');
+ });
+
+ it('keeps the actual failed-phone veto when a cached seed cannot fit beside it', async () => {
+ const previous = process.env.LID_MAPPING_CACHE_MAX;
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ try {
+ const limited = new LidMappingStoreService(repo);
+ await limited.onModuleInit();
+ await limited.remember('111', '628111', s1);
+ const failure = jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ const limitedWarn = jest.spyOn((limited as unknown as { logger: { warn: () => void } }).logger, 'warn');
+ await expect(limited.remember('111', '628222', s1)).resolves.toBe(false);
+ failure.mockRestore();
+ limitedWarn.mockRestore();
+ await limited.rememberIfUnknown('222', '628333', s2);
+ await limited.rememberIfUnknown('111', '628111', s2);
+ expect(limited.getCached('111')).toBe('628222');
+ expect(await limited.findPhoneForLid('111@lid')).toBeNull();
+ expect(await limited.findLidsForPhone('628111')).toEqual([]);
+ } finally {
+ if (previous === undefined) delete process.env.LID_MAPPING_CACHE_MAX;
+ else process.env.LID_MAPPING_CACHE_MAX = previous;
+ }
+ });
+
+ const noAlias = async (node: LidMappingStoreService, lid = '111', phone = '628111') => {
+ expect(await node.findPhoneForLid(`${lid}@lid`)).toBeNull();
+ expect(await node.findLidsForPhone(phone)).toEqual([]);
+ expect(await node.phonesForLidsPersisted([lid])).toEqual({ [lid]: null });
+ expect(await node.lidsForPhonesPersisted([phone])).toEqual({ [phone]: [] });
+ const fence = new ChatScopeService(node);
+ expect(await fence.allows({ allowedChats: [`${phone}@c.us`] }, `${lid}@lid`)).toBe(false);
+ expect(await fence.allows({ allowedChats: [`${lid}@lid`] }, `${phone}@c.us`)).toBe(false);
+ expect((await fence.scopeForFilter({ allowedChats: [`${phone}@c.us`] }))!.allowed.has(`${lid}@lid`)).toBe(false);
+ expect((await fence.scopeForFilter({ allowedChats: [`${lid}@lid`] }))!.allowed.has(`${phone}@c.us`)).toBe(false);
+ expect(await fence.candidatesFor(`${lid}@lid`)).not.toContain(`${phone}@c.us`);
+ expect(await fence.candidatesFor(`${phone}@c.us`)).not.toContain(`${lid}@lid`);
+ expect(await fence.allows({ allowedChats: [`${lid}@lid`] }, `${lid}@lid`)).toBe(true);
+ };
+
+ it('keeps a cached seed for display without authorizing aliases, including after restart and owner release', async () => {
+ await store.rememberIfUnknown('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', isReported: false });
+ await store.reload();
+ expect(store.getCached('111')).toBe('628111');
+ await noAlias(store);
+ await store.releaseSession(s1);
+ expect(await row('111')).toMatchObject({ sessionId: null, isReported: false });
+ const restarted = new LidMappingStoreService(repo);
+ await restarted.onModuleInit();
+ expect(restarted.getCached('111')).toBe('628111');
+ expect(restarted.resolveLid('111@lid')).toBeNull();
+ expect(restarted.lidsForPhone('628111')).toEqual([]);
+ await noAlias(restarted);
+ });
+
+ it('upgrades an actual report of the same cached seed instead of skipping its write', async () => {
+ await store.rememberIfUnknown('111', '628111', s1);
+ await store.reload();
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', isReported: true });
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ });
+
+ it('revokes a conflicting lookup without replacing the stored phone, then accepts an actual same-phone report', async () => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.rememberIfUnknown('111', '628222', s2);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: false });
+ await noAlias(store);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ });
+
+ it('preserves a loaded unchanged negative owner and timestamp while checking the shared row', async () => {
+ await store.remember('111', null, s1);
+ await store.reload();
+ const original = await row('111');
+ const writes = jest.spyOn(repo, 'update');
+ for (let i = 0; i < 10; i++) await store.remember('111', null, s2);
+ expect(writes).toHaveBeenCalledTimes(10);
+ expect(await row('111')).toEqual(original);
+ });
+
+ it('rechecks a loaded negative after a peer mapped the lid and its owner logged out', async () => {
+ await store.remember('111', null, s1);
+ await store.reload();
+ expect(store.getCached('111')).toBeNull();
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628111', s2);
+ await ds.getRepository(Session).update(s2, { phone: null });
+ await store.remember('111', null, s1);
+ expect(await row('111')).toMatchObject({ phone: null, sessionId: s1 });
+ await noAlias(store);
+ await noAlias(peer);
+ });
+
+ it('takes ownership when a local conflicting lookup made the previous report untrusted', async () => {
+ await store.remember('111', '628111', s1);
+ await store.remember('111', '628111', s2);
+ await store.rememberIfUnknown('111', '628222', s3);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s2, isReported: false });
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ });
+
+ it('checks repeated actual reports without changing an unchanged owner or timestamp', async () => {
+ await store.remember('111', '628111', s1);
+ await store.remember('111', '628111', s2);
+ const original = await row('111');
+ await ds.query('CREATE TABLE mapping_updates (n integer NOT NULL)');
+ await ds.query('INSERT INTO mapping_updates VALUES (0)');
+ if (pg) {
+ await ds.query(
+ `CREATE FUNCTION count_mapping_update() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN UPDATE mapping_updates SET n = n + 1; RETURN NEW; END $$`,
+ );
+ await ds.query(
+ 'CREATE TRIGGER mapping_update AFTER UPDATE ON lid_mappings FOR EACH ROW EXECUTE FUNCTION count_mapping_update()',
+ );
+ } else {
+ await ds.query(
+ 'CREATE TRIGGER mapping_update AFTER UPDATE ON lid_mappings BEGIN UPDATE mapping_updates SET n = n + 1; END',
+ );
+ }
+ const query = jest.spyOn(repo, 'query');
+ const upsert = jest.spyOn(repo, 'upsert');
+ for (let i = 0; i < 1000; i++) await expect(store.remember('111', '628111', i % 2 ? s1 : s2)).resolves.toBe(true);
+ expect(query).toHaveBeenCalledTimes(1000);
+ expect(upsert).not.toHaveBeenCalled();
+ expect(await row('111')).toEqual(original);
+ expect(await ds.query('SELECT n FROM mapping_updates')).toEqual([{ n: 0 }]);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.rememberIfUnknown('111', '628222', s3);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toEqual(original);
+ expect(await ds.query('SELECT n FROM mapping_updates')).toEqual([{ n: 2 }]);
+ });
+
+ it('stores the latest actual phone report even when this node counted the same phone before a peer changed it', async () => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ });
+
+ it('preserves a same-phone peer owner after a repeated report fails and recovers', async () => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628111', s2);
+ await repo.update({ lid: '111' }, { updatedAt: new Date('2020-01-01T00:00:00Z') });
+ const original = await row('111');
+ jest.spyOn(repo, 'query').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(true);
+ expect(await row('111')).toEqual(original);
+ await store.remember('111', null, s1);
+ expect(await row('111')).toEqual(original);
+ });
+
+ it('counts a reporter only after its first phone write succeeds', async () => {
+ jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628111', s2);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ });
+
+ it.each(['628111', '628222'])(
+ 'keeps a newer successful report counted when an older %s write fails late',
+ async oldPhone => {
+ let reject!: (err: Error) => void;
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const older = store.remember('111', oldPhone, s1);
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628111', s2);
+ await repo.update({ lid: '111' }, { updatedAt: new Date('2020-01-01T00:00:00Z') });
+ const original = await row('111');
+ reject(new Error('connection lost'));
+ await expect(older).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(true);
+ expect(await row('111')).toEqual(original);
+ },
+ );
+
+ it('does not count an old successful phone report after the cache changes away and back', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = store.remember('111', '628111', s1);
+ await reached;
+ await store.remember('111', '628222', s2);
+ await store.remember('111', '628111', s2);
+ release();
+ await expect(older).resolves.toBe(true);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1, isReported: true });
+ });
+
+ it('counts overlapping successful reports of one phone without changing the later owner', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = store.remember('111', '628111', s1);
+ await reached;
+ await store.remember('111', '628111', s2);
+ await repo.update({ lid: '111' }, { updatedAt: new Date('2020-01-01T00:00:00Z') });
+ const original = await row('111');
+ release();
+ await expect(older).resolves.toBe(true);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toEqual(original);
+ });
+
+ it.each([
+ ['positive', true],
+ ['negative', true],
+ ['positive', false],
+ ['negative', false],
+ ] as const)(
+ 'keeps a newer phone failure veto after an older %s acknowledgment (changed phone: %s)',
+ async (kind, changed) => {
+ if (kind === 'negative') await store.remember('111', '628111', s1);
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const method = kind === 'positive' ? 'upsert' : 'update';
+ const execute = repo[method].bind(repo) as (...args: unknown[]) => Promise<unknown>;
+ jest.spyOn(repo, method).mockImplementationOnce((async (...args: unknown[]) => {
+ const result = await execute(...args);
+ entered();
+ await gate;
+ return result;
+ }) as never);
+ const older = store.remember('111', kind === 'positive' ? '628111' : null, s1);
+ await reached;
+ if (changed) await store.remember('111', '628222', s2);
+ if (kind === 'negative' && !changed)
+ jest.spyOn(repo, 'query').mockRejectedValueOnce(new Error('connection lost'));
+ else jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ if (!changed) {
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ }
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ release();
+ await expect(older).resolves.toBe(true);
+ expect(await row('111')).toMatchObject({ phone: '628222', sessionId: s2, isReported: true });
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ await store.remember('111', '628111', s1);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ },
+ );
+
+ it.each([true, false])(
+ 'does not install an old phone failure veto after a newer report succeeds (changed phone: %s)',
+ async changed => {
+ let reject!: (err: Error) => void;
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const older = store.remember('111', '628111', s1);
+ if (changed) await store.remember('111', '628222', s2);
+ await store.remember('111', '628111', s2);
+ reject(new Error('connection lost'));
+ await expect(older).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s3);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628222');
+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: '628222' });
+ expect(await store.findLidsForPhone('628222')).toEqual(['111']);
+ expect(await store.lidsForPhonesPersisted(['628222'])).toEqual({ 628222: ['111'] });
+ expect(await new ChatScopeService(store).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(true);
+ },
+ );
+
+ it('vetoes a failed conflict revocation locally and retries it without a hold', async () => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ const failed = jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(false);
+ failed.mockRestore();
+ expect(await row('111')).toMatchObject({ phone: '628111', isReported: true });
+ await noAlias(store);
+ expect(await peer.findPhoneForLid('111@lid')).toBe('628111');
+ warn.mockClear();
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(true);
+ await noAlias(peer);
+ const restarted = new LidMappingStoreService(repo);
+ await restarted.onModuleInit();
+ await noAlias(restarted);
+ });
+
+ it('keeps a failed cached contradiction veto when an older actual report is acknowledged', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = store.remember('111', '628111', s1);
+ await reached;
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ release();
+ await expect(older).resolves.toBe(true);
+ await noAlias(store);
+ await store.remember('111', '628111', s1);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ });
+
+ it.each([true, false])(
+ 'does not replay old actual trust after cached answers change away and back (revocation fails: %s)',
+ async fails => {
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = store.remember('111', '628111', s1);
+ await reached;
+ if (fails) jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(!fails);
+ expect(warn).toHaveBeenCalledTimes(fails ? 1 : 0);
+ warn.mockClear();
+ await store.rememberIfUnknown('111', '628111', s2);
+ release();
+ await expect(older).resolves.toBe(true);
+ await noAlias(store);
+ jest.spyOn(repo, 'findOne').mockRejectedValue(new Error('connection lost'));
+ jest.spyOn(repo, 'find').mockRejectedValue(new Error('connection lost'));
+ await noAlias(store);
+ warn.mockClear();
+ jest.restoreAllMocks();
+ await store.remember('111', '628111', s1);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ },
+ );
+
+ it('keeps an uncertain replacement veto when a newer actual negative also fails', async () => {
+ await store.remember('111', '628111', s1);
+ let reject!: (err: Error) => void;
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const replacing = store.remember('111', '628222', s1);
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', null, s1)).resolves.toBe(false);
+ reject(new Error('connection lost'));
+ await expect(replacing).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ });
+
+ it('keeps a pending replacement uncertain through two overlapping failed negatives', async () => {
+ await store.remember('111', '628111', s1);
+ let failPositive!: (err: Error) => void;
+ let failNegative!: (err: Error) => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ failPositive = fail;
+ }),
+ );
+ const positive = store.remember('111', '628222', s1);
+ jest.spyOn(repo, 'update').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ failNegative = fail;
+ entered();
+ }),
+ );
+ const first = store.remember('111', null, s1);
+ await reached;
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', null, s1)).resolves.toBe(false);
+ failNegative(new Error('connection lost'));
+ await expect(first).resolves.toBe(false);
+ failPositive(new Error('connection lost'));
+ await expect(positive).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ });
+
+ it('does not accept a cached old phone when the actual replacement write fails after its lookup', async () => {
+ await store.remember('111', '628111', s1);
+ let reject!: (err: Error) => void;
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const positive = store.remember('111', '628222', s1);
+ await store.rememberIfUnknown('111', '628111', s2);
+ reject(new Error('connection lost'));
+ await expect(positive).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ });
+
+ it('accepts an actual retry that commits after a consistent cached lookup revokes the older stored phone', async () => {
+ await store.remember('111', '628222', s1);
+ jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628111', s1)).resolves.toBe(false);
+ warn.mockClear();
+ const paused = hold('upsert');
+ const actual = store.remember('111', '628111', s1);
+ await paused.reached;
+ await store.rememberIfUnknown('111', '628111', s2);
+ expect(await row('111')).toMatchObject({ phone: '628222', isReported: false });
+ paused.release();
+ await expect(actual).resolves.toBe(true);
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ expect(store.resolveLid('111@lid')).toBe('628111');
+ });
+
+ it('does not restore a stale mirror when a peer report and cached revocation follow the actual SQL commit', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const actual = store.remember('111', '628111', s1);
+ await reached;
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ await store.rememberIfUnknown('111', '628111', s1);
+ release();
+ await expect(actual).resolves.toBe(true);
+ await noAlias(store);
+ jest.spyOn(repo, 'findOne').mockRejectedValue(new Error('connection lost'));
+ jest.spyOn(repo, 'find').mockRejectedValue(new Error('connection lost'));
+ await noAlias(store);
+ warn.mockClear();
+ });
+
+ it('does not restore trust from a row read that predates a newer cached revocation', async () => {
+ await store.remember('111', '628222', s1);
+ const paused = hold('upsert');
+ const actual = store.remember('111', '628111', s1);
+ await paused.reached;
+ await store.rememberIfUnknown('111', '628111', s2);
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const findOne = repo.findOne.bind(repo);
+ jest.spyOn(repo, 'findOne').mockImplementationOnce(async (...args) => {
+ const result = await findOne(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ paused.release();
+ await reached;
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ await store.rememberIfUnknown('111', '628111', s1);
+ release();
+ await expect(actual).resolves.toBe(true);
+ await noAlias(store);
+ jest.spyOn(repo, 'findOne').mockRejectedValue(new Error('connection lost'));
+ jest.spyOn(repo, 'find').mockRejectedValue(new Error('connection lost'));
+ await noAlias(store);
+ warn.mockClear();
+ });
+
+ it('keeps a newly reported phone trusted after an older cached revocation acknowledgment', async () => {
+ await store.remember('111', '628111', s1);
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const update = repo.update.bind(repo);
+ jest.spyOn(repo, 'update').mockImplementationOnce(async (...args) => {
+ const result = await update(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = store.rememberIfUnknown('111', '628222', s2);
+ await reached;
+ await store.remember('111', '628111', s1);
+ release();
+ await expect(older).resolves.toBe(true);
+ expect(store.resolveLid('111@lid')).toBe('628111');
+ jest.spyOn(repo, 'findOne').mockRejectedValueOnce(new Error('connection lost'));
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ });
+
+ it('keeps a failed actual replacement veto when a concurrent same-phone cached lookup also fails', async () => {
+ await store.remember('111', '628111', s1);
+ let reject!: (err: Error) => void;
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail;
+ }),
+ );
+ const actual = store.remember('111', '628222', s1);
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(false);
+ reject(new Error('connection lost'));
+ await expect(actual).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ await noAlias(store, '111', '628111');
+ await noAlias(store, '111', '628222');
+ });
+
+ it.each([true, false])(
+ 'accepts a successful actual retry alongside a consistent cached lookup (lookup fails: %s)',
+ async fails => {
+ await store.remember('111', '628111', s1);
+ jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await expect(store.remember('111', '628222', s1)).resolves.toBe(false);
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const upsert = repo.upsert.bind(repo);
+ jest.spyOn(repo, 'upsert').mockImplementationOnce(async (...args) => {
+ const result = await upsert(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const actual = store.remember('111', '628222', s1);
+ await reached;
+ if (fails) {
+ later(60_000);
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+ }
+ await expect(store.rememberIfUnknown('111', '628222', s2)).resolves.toBe(!fails);
+ expect(warn).toHaveBeenCalledTimes(fails ? 1 : 0);
+ warn.mockClear();
+ release();
+ await expect(actual).resolves.toBe(true);
+ expect(store.resolveLid('111@lid')).toBe('628222');
+ expect(await store.findPhoneForLid('111@lid')).toBe('628222');
+ expect(await store.findLidsForPhone('628222')).toEqual(['111']);
+ expect(await new ChatScopeService(store).allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(true);
+ },
+ );
+
+ it.each(['negative', 'seed'] as const)('keeps a reloaded phone after an old %s write acknowledgment', async kind => {
+ await store.remember('111', '628111', s1);
+ let release!: () => void;
+ let entered!: () => void;
+ const reached = new Promise<void>(resolve => {
+ entered = resolve;
+ });
+ const gate = new Promise<void>(resolve => {
+ release = resolve;
+ });
+ const update = repo.update.bind(repo);
+ jest.spyOn(repo, 'update').mockImplementationOnce(async (...args) => {
+ const result = await update(...args);
+ entered();
+ await gate;
+ return result;
+ });
+ const older = kind === 'negative' ? store.remember('111', null, s1) : store.rememberIfUnknown('111', '628333', s2);
+ await reached;
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ await store.reload();
+ release();
+ await expect(older).resolves.toBe(true);
+ expect(store.resolveLid('111@lid')).toBe('628222');
+ expect(await store.findPhoneForLid('111@lid')).toBe('628222');
+ });
+
+ it.each(['628222', '628333'])(
+ 'tests the current phone atomically when a lookup waits and %s is reported',
+ async phone => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ const paused = hold('update');
+ const lookup = store.rememberIfUnknown('111', '628222', s2);
+ await paused.reached;
+ await peer.remember('111', phone, s2);
+ paused.release();
+ await expect(lookup).resolves.toBe(true);
+ expect(await row('111')).toMatchObject({ phone, isReported: phone === '628222' });
+ await peer.remember('111', phone, s2);
+ expect(await row('111')).toMatchObject({ phone, isReported: true });
+ },
+ );
+
+ it('keeps cache-only alias refusal independent of host clock steps and restart', async () => {
+ await store.rememberIfUnknown('111', '628111', s1);
+ await store.reload();
+ const hostClock = jest.spyOn(Date, 'now');
+ try {
+ for (const wall of [Date.parse('2020-01-01T00:00:00Z'), Date.parse('2099-01-01T00:00:00Z')]) {
+ hostClock.mockReturnValue(wall);
+ await noAlias(store);
+ const restarted = new LidMappingStoreService(repo);
+ await restarted.onModuleInit();
+ await noAlias(restarted);
+ }
+ } finally {
+ hostClock.mockRestore();
+ }
+ });
+
+ it('refuses an unreported mirror fallback when its persisted row cannot be read', async () => {
+ await store.rememberIfUnknown('111', '628111', s1);
+ await store.reload();
+ const one = jest.spyOn(repo, 'findOne').mockRejectedValue(new Error('connection lost'));
+ const many = jest.spyOn(repo, 'find').mockRejectedValue(new Error('connection lost'));
+ await noAlias(store);
+ one.mockRestore();
+ many.mockRestore();
+ warn.mockClear();
+ });
+
+ it('refuses an unreported mirror when its stored row has been removed', async () => {
+ await store.rememberIfUnknown('111', '628111', s1);
+ await store.reload();
+ await repo.delete({ lid: '111' });
+ await noAlias(store);
+ expect(store.getCached('111')).toBe('628111');
+ });
+
+ it('replaces a peer-revoked different phone when an actual phone is reported again', async () => {
+ await store.remember('111', '628111', s1);
+ const peer = new LidMappingStoreService(repo);
+ await peer.onModuleInit();
+ await peer.remember('111', '628222', s2);
+ await peer.rememberIfUnknown('111', '628333', s2);
+ await store.remember('111', '628111', s1);
+ expect(await row('111')).toMatchObject({ phone: '628111', isReported: true });
+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');
+ });
+
+ it('bounds origin metadata with the display mirror', async () => {
+ const previous = process.env.LID_MAPPING_CACHE_MAX;
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ try {
+ store = new LidMappingStoreService(repo);
+ await store.onModuleInit();
+ for (let i = 0; i < 20; i++) {
+ await store.rememberIfUnknown(String(i), `628${i}`, s1);
+ store.getCached(String(i));
+ await settleWarm();
+ }
+ expect((store as unknown as { unreported: Set<string> }).unreported.size).toBe(1);
+ expect((store as unknown as { unreported: Set<string> }).unreported.has('19')).toBe(true);
+ } finally {
+ if (previous === undefined) delete process.env.LID_MAPPING_CACHE_MAX;
+ else process.env.LID_MAPPING_CACHE_MAX = previous;
+ }
+ });
+
it('leaves the phone another session stored, in the table and in the cache', async () => {
await store.remember('111', '628111', s1);
await store.remember('111', null, s2);
@@ -1142,8 +2168,8 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
{ lid: '666', phone: '628666', sessionId: s2 }, // owned by the session answering
];
await repo.insert([
- { lid: '111', phone: '628111', sessionId: s2, updatedAt: stamp },
- ...others.map(o => ({ ...o, updatedAt: stamp })),
+ { lid: '111', phone: '628111', sessionId: s2, updatedAt: stamp, isReported: true },
+ ...others.map(o => ({ ...o, updatedAt: stamp, isReported: true })),
]);
await ds.getRepository(Session).update({ id: s9 }, { phone: null });
await store.reload();
@@ -1151,7 +2177,7 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
await store.remember('111', null, s2);
expect(await row('111')).toMatchObject({ phone: null, sessionId: s2 });
- for (const other of others) expect(await row(other.lid)).toEqual({ ...other, updatedAt: stamp });
+ for (const other of others) expect(await row(other.lid)).toEqual({ ...other, updatedAt: stamp, isReported: true });
});
it('drops a phone cached here once the table holds none, whichever session cleared it', async () => {
@@ -1260,7 +2286,7 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
});
it('knows the owner of a row it loaded, so only another session reporting the phone writes', async () => {
- await repo.insert({ lid: '111', phone: '628111', sessionId: s1 });
+ await repo.insert({ lid: '111', phone: '628111', sessionId: s1, isReported: true });
await store.reload();
const upsert = jest.spyOn(repo, 'upsert');
@@ -1272,7 +2298,7 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
});
it('knows the owner of a row it warms on a miss as well', async () => {
- await repo.insert({ lid: '111', phone: '628111', sessionId: s1 }); // stored after this node loaded the table
+ await repo.insert({ lid: '111', phone: '628111', sessionId: s1, isReported: true }); // stored after this node loaded the table
for (let i = 0; i < 100 && store.getCached('111') === undefined; i++) await new Promise(r => setTimeout(r, 5));
const upsert = jest.spyOn(repo, 'upsert');
@@ -1406,17 +2432,23 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
expect(await store.findPhoneForLid('111@lid')).toBeNull();
});
- it('takes the row on the next report of a session whose negative failed to write', async () => {
+ it('keeps counted reports after a failed negative until a negative actually clears the row', async () => {
await store.remember('111', '628111', s2);
await store.remember('111', '628111', s1);
+ await repo.update({ lid: '111' }, { updatedAt: new Date('2020-01-01T00:00:00Z') });
+ const original = await row('111');
jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
await store.remember('111', null, s2);
expect(warn).toHaveBeenCalledTimes(1);
warn.mockClear();
- expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s1 });
+ expect(await row('111')).toEqual(original);
await store.remember('111', '628111', s2);
-
+ expect(await row('111')).toEqual(original);
+ await ds.getRepository(Session).update({ id: s1 }, { phone: null });
+ await store.remember('111', null, s2);
+ expect(await row('111')).toMatchObject({ phone: null, sessionId: s2 });
+ await store.remember('111', '628111', s2);
expect(await row('111')).toMatchObject({ phone: '628111', sessionId: s2 });
});
diff --git a/src/engine/identity/lid-mapping.entity.ts b/src/engine/identity/lid-mapping.entity.ts
index d2a00f5ed..4f7ccd2db 100644
--- a/src/engine/identity/lid-mapping.entity.ts
+++ b/src/engine/identity/lid-mapping.entity.ts
@@ -10,9 +10,8 @@ import { Column, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm'
* up and could not resolve) so active lookups stay one-network-call-per-unknown-lid. A negative replaces a
* phone only when the session that wrote it (or none, or one since deleted or logged out) answers it, since
* another account may not see the number. `sessionId` is the row's owner, the session that last wrote it: a
- * negative, or a report of a phone, though a session this node already counted for that phone writes
- * nothing when it reports it again (LidMappingStoreService.seenBy), so after s1, s2, s1 report one phone
- * the owner is s2. A deleted or logged-out session owns nothing. Intentionally NOT a foreign key, since the row
+ * negative, or a report of a phone. A repeated report checks the current shared row and preserves its
+ * owner and timestamp when the phone is unchanged, so after s1, s2, s1 report one phone the owner is s2. A deleted or logged-out session owns nothing. Intentionally NOT a foreign key, since the row
* outlives any one session.
*/
@Entity('lid_mappings')
@@ -30,6 +29,10 @@ export class LidMapping {
@Column({ type: 'varchar', nullable: true })
sessionId!: string | null;
+ /** True after an engine mapping report; cache-only lookups remain display data. */
+ @Column({ type: 'boolean', default: false })
+ isReported!: boolean;
+
@UpdateDateColumn()
updatedAt!: Date;
}
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 8f866c6c4..9d9b9be3e 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1284,6 +1284,12 @@ export interface ChatHistoryCapability {
* JID included — see setGroupPicture), and its consumer domain is contact data.
*/
export interface ContactCapability {
+ /**
+ * Defaults to reporting lookup answers. `seed` keeps positive lookups as display data and revokes alias
+ * trust on a conflicting phone; null still uses owner-aware clearing.
+ */
+ readonly contactPhoneLookupPersistence?: 'seed';
+
getContacts(): Promise<Contact[]>;
getContactById(contactId: string): Promise<Contact | null>;
diff --git a/src/modules/auth/chat-scope.service.spec.ts b/src/modules/auth/chat-scope.service.spec.ts
index e0170db8a..d8402eb61 100644
--- a/src/modules/auth/chat-scope.service.spec.ts
+++ b/src/modules/auth/chat-scope.service.spec.ts
@@ -90,7 +90,7 @@ describe('ChatScopeService', () => {
});
it('follows a lid another node has re-mapped, in the single check and the list filter alike', async () => {
- const rows = [{ lid: LID, phone: PHONE as string | null }];
+ const rows = [{ lid: LID, phone: PHONE as string | null, isReported: true }];
const hit = (value: string | null, cond?: string | FindOperator<unknown>) =>
cond === undefined || (cond instanceof FindOperator ? (cond.value as unknown[]).includes(value) : value === cond);
const repo = {
diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.ts
index 372f2f251..04fc058df 100644
--- a/src/modules/automation/automation-rules.service.ts
+++ b/src/modules/automation/automation-rules.service.ts
@@ -6,7 +6,7 @@ import { Repository } from 'typeorm';
import { createLogger } from '../../common/services/logger.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { chatKind } from '../../engine/identity/wa-id';
-import { evaluateFilters } from '../webhook/filters/filter-evaluator';
+import { evaluateFilters, prepareFilterLidResolver } from '../webhook/filters/filter-evaluator';
import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';
import { AutomationRule } from './entities/automation-rule.entity';
import { Session } from '../session/entities/session.entity';
@@ -181,9 +181,12 @@ export class AutomationRulesService {
}
if (rules.length === 0) return;
- // Same lid->phone resolution the webhook filter match uses, so a phone-valued sender condition
- // matches a lid-addressed sender identically in both places.
- const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;
+ const resolveLid = await prepareFilterLidResolver(
+ rules.map(rule => rule.conditions),
+ 'message.received',
+ message,
+ this.lidMappingStore ? lids => this.lidMappingStore!.phonesForLidsPersisted(lids) : undefined,
+ );
// Resolved the way the `kind` filter field resolves it, so the guard and a kind condition agree.
const kind = typeof message.kind === 'string' && message.kind ? message.kind : chatKind(chatId);
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index 22829f6df..f8f56825f 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -1611,7 +1611,7 @@ describe('InfraDataController.import/export preserves every data-DB table', () =
it('restores lid_mappings instead of dropping them on a backup→restore', async () => {
await seedSession('s1');
const lidRepo = ds.getRepository(LidMapping);
- await lidRepo.save(lidRepo.create({ lid: '111', phone: '628111', sessionId: 's1' }));
+ await lidRepo.save(lidRepo.create({ lid: '111', phone: '628111', sessionId: 's1', isReported: true }));
await lidRepo.save(lidRepo.create({ lid: '222', phone: null, sessionId: 's1' })); // negative cache
const dump = await controller.exportData();
@@ -1626,6 +1626,14 @@ describe('InfraDataController.import/export preserves every data-DB table', () =
expect(await lidRepo.count()).toBe(2);
expect((await lidRepo.findOneByOrFail({ lid: '111' })).phone).toBe('628111');
expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();
+ expect((await lidRepo.findOneByOrFail({ lid: '111' })).isReported).toBe(true);
+ expect((await lidRepo.findOneByOrFail({ lid: '222' })).isReported).toBe(false);
+
+ const mappings = (dump.tables as unknown as { lidMappings: { isReported?: boolean | number }[] }).lidMappings;
+ for (const mapping of mappings) delete mapping.isReported;
+ const legacy = await controller.importData({ tables: dump.tables });
+ expect(legacy.warnings).toEqual([]);
+ expect((await lidRepo.findOneByOrFail({ lid: '111' })).isReported).toBe(false);
});
// Restoring ONTO the instance that produced the archive is the rollback flow, and it is the one the
diff --git a/src/modules/infra/infra-data.import.pg.spec.ts b/src/modules/infra/infra-data.import.pg.spec.ts
index f9b57fdf5..7e9867ee4 100644
--- a/src/modules/infra/infra-data.import.pg.spec.ts
+++ b/src/modules/infra/infra-data.import.pg.spec.ts
@@ -134,6 +134,22 @@ describePostgres('InfraDataController.importData (postgres)', () => {
expect((await claims.find()).map(claim => claim.sessionId)).toEqual([kept]);
});
+ it('preserves reported mapping origin and restores legacy mappings as display data', async () => {
+ const mappings = ds.getRepository(LidMapping);
+ await mappings.insert([
+ { lid: '111', phone: '628111', sessionId: null, isReported: true },
+ { lid: '222', phone: '628222', sessionId: null, isReported: false },
+ ]);
+ const dump = await controller.exportData();
+ await expect(controller.importData(dump as never)).resolves.toMatchObject({ imported: true, warnings: [] });
+ expect(await mappings.findOneBy({ lid: '111' })).toMatchObject({ isReported: true });
+ expect(await mappings.findOneBy({ lid: '222' })).toMatchObject({ isReported: false });
+ const rows = (dump.tables as unknown as { lidMappings: { isReported?: boolean | number }[] }).lidMappings;
+ for (const row of rows) delete row.isReported;
+ await expect(controller.importData(dump as never)).resolves.toMatchObject({ imported: true, warnings: [] });
+ expect(await mappings.findOneBy({ lid: '111' })).toMatchObject({ phone: '628111', isReported: false });
+ });
+
// The runtime pool cancels a statement that outlives statement_timeout (30 s by default), and the
// clears of a replace-all import scale with the live tables, not with the archive. A slow trigger on
// messages stands in for a table that has grown large: with the pool's timeout lowered below it, the
diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.ts
index 28ae97518..a5ab6f30d 100644
--- a/src/modules/infra/migration-tables.types.ts
+++ b/src/modules/infra/migration-tables.types.ts
@@ -112,6 +112,7 @@ export interface BaileysStoredMessageRow {
// `DELETE FROM sessions` never clears it — it must be exported + re-inserted explicitly or a
// backup→restore into a fresh DB loses the whole cache (it self-heals via re-lookup, but lossily).
export interface LidMappingRow {
+ isReported?: boolean | number;
lid: string;
phone: string | null;
sessionId: string | null;
diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.ts
index bfff08a27..b77055c0e 100644
--- a/src/modules/infra/table-importers.ts
+++ b/src/modules/infra/table-importers.ts
@@ -323,9 +323,15 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [
defineTableImporter({
key: 'lidMappings',
label: 'lid mapping',
- sql: `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt") VALUES ($1, $2, $3, $4)`,
+ sql: `INSERT INTO lid_mappings (lid, phone, "sessionId", "updatedAt", "isReported") VALUES ($1, $2, $3, $4, $5)`,
id: (lm: LidMappingRow) => lm.lid,
- map: (lm: LidMappingRow) => [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],
+ map: (lm: LidMappingRow) => [
+ lm.lid,
+ lm.phone ?? null,
+ lm.sessionId ?? null,
+ lm.updatedAt,
+ lm.isReported === true || lm.isReported === 1,
+ ],
}),
// Import chat states (optional; not a FK, restored as a standalone per-session cache table)
diff --git a/src/modules/session/message-history-projector.spec.ts b/src/modules/session/message-history-projector.spec.ts
index 479eceecc..46aee1d72 100644
--- a/src/modules/session/message-history-projector.spec.ts
+++ b/src/modules/session/message-history-projector.spec.ts
@@ -64,6 +64,47 @@ describe('persistHistoryMessages revokes', () => {
expect(cleared.map(m => m.id)).toEqual(['W1']);
});
+ it.each([false, true])('retimes a tombstone only while its engine stays live (retired=%s)', async retired => {
+ await stored('[email protected]');
+ await repo.update({ sessionId: 's1', waMessageId: 'W1' }, { type: 'revoked', body: '' });
+ const before = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'W1' });
+ let entered!: () => void;
+ const waiting = new Promise<void>(resolve => (entered = resolve));
+ let answer!: (phone: string) => void;
+ const phone = new Promise<string>(resolve => (answer = resolve));
+ const lookup = jest.fn(() => {
+ entered();
+ return phone;
+ });
+ let live = true;
+ const notify = jest.fn();
+ const pending = persistHistoryMessages(
+ repo,
+ undefined,
+ 's1',
+ [{ ...tombstone('484848@lid'), type: 'text', body: 'earlier original' }],
+ logger,
+ () => live,
+ notify,
+ lookup,
+ );
+ try {
+ await waiting;
+ live = !retired;
+ answer('628111');
+ const cleared = await pending;
+ expect(cleared.map(message => message.id)).toEqual(retired ? [] : ['W1']);
+ const after = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'W1' });
+ expect(after.timestamp).toBe(retired ? before.timestamp : 5);
+ expect(after.createdAt).toEqual(retired ? before.createdAt : new Date(5_000));
+ expect(after).toMatchObject({ type: 'revoked', body: '' });
+ expect(notify).not.toHaveBeenCalled();
+ } finally {
+ answer('628111');
+ await pending;
+ }
+ });
+
it('leaves a row of another chat alone', async () => {
await stored('[email protected]');
diff --git a/src/modules/session/message-history-projector.ts b/src/modules/session/message-history-projector.ts
index 3d9e62feb..64dd9f896 100644
--- a/src/modules/session/message-history-projector.ts
+++ b/src/modules/session/message-history-projector.ts
@@ -3,7 +3,7 @@ import { Repository, In, Raw } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
import { buildMessageMetadata, REVOKED_ROW_PATCH } from './message-row.mapper';
-import { provablyDifferent } from './message-mutation-guard';
+import { mutationTargetsForeignRowPersisted } from './message-mutation-guard';
import { resolveFeatureFlags } from '../../config/feature-flags';
import { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';
import { LoggerService } from '../../common/services/logger.service';
@@ -21,6 +21,7 @@ export async function persistHistoryMessages(
logger: LoggerService,
isLive: () => boolean,
notifyRevoked?: (row: Message) => void,
+ resolveLid?: (jid: string) => Promise<string | null>,
): Promise<IncomingMessage[]> {
const cleared: IncomingMessage[] = [];
const storeEphemeralMessages = resolveFeatureFlags(configService).storeEphemeralMessages;
@@ -52,7 +53,7 @@ export async function persistHistoryMessages(
const chunkIds = ids.slice(i, i + CHUNK);
const existing = await messageRepository.find({
where: { sessionId: id, waMessageId: In(chunkIds) },
- select: { waMessageId: true, type: true, chatId: true },
+ select: { waMessageId: true, type: true, chatId: true, direction: true, author: true },
});
// A delete() can retire the engine while a large batch works through its chunks; its transaction
// has then already cleared this session's messages, and a row inserted after it (no FK) would
@@ -114,12 +115,21 @@ export async function persistHistoryMessages(
// lose the unique-key race or are cleared here, and a later chunk cannot resurrect the payload.
// The row keeps the chat id as its writer gave it (a REST send stores the caller's own dialect), so
// the tombstone is matched on the chat it names, not on the string.
- const storedChats = new Map(existing.map(r => [r.waMessageId, r.chatId]));
+ const storedChats = new Map(existing.map(r => [r.waMessageId, r]));
for (const messageId of chunkIds) {
const m = byId.get(messageId)!;
if (m.type !== 'revoked') continue;
- const storedChat = storedChats.get(messageId) ?? m.chatId;
- if (provablyDifferent(storedChat, m.chatId)) continue;
+ const stored = storedChats.get(messageId);
+ const storedChat = stored?.chatId ?? m.chatId;
+ if (
+ stored &&
+ (await mutationTargetsForeignRowPersisted(
+ stored,
+ { kind: 'revoke', chatId: m.chatId, fromMe: m.fromMe },
+ resolveLid,
+ ))
+ )
+ continue;
if (!isLive()) break;
await messageRepository.update(
{
@@ -141,9 +151,18 @@ export async function persistHistoryMessages(
const m = byId.get(row.waMessageId)!;
if (!isLive()) break;
const direction = m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING;
- if (provablyDifferent(row.chatId, m.chatId) || row.direction !== direction || !Number.isFinite(m.timestamp)) {
+ if (
+ (await mutationTargetsForeignRowPersisted(
+ row,
+ { kind: 'revoke', chatId: m.chatId, fromMe: m.fromMe },
+ resolveLid,
+ )) ||
+ row.direction !== direction ||
+ !Number.isFinite(m.timestamp)
+ ) {
continue;
}
+ if (!isLive()) break;
if (row.timestamp == null || row.timestamp > m.timestamp) {
const result = await messageRepository.update(
{
diff --git a/src/modules/session/message-mutation-guard.spec.ts b/src/modules/session/message-mutation-guard.spec.ts
index 100bfd1a7..d31d3054f 100644
--- a/src/modules/session/message-mutation-guard.spec.ts
+++ b/src/modules/session/message-mutation-guard.spec.ts
@@ -1,5 +1,5 @@
import { MessageDirection } from '../message/entities/message.entity';
-import { mutationTargetsForeignRow } from './message-mutation-guard';
+import { mutationTargetsForeignRow, mutationTargetsForeignRowPersisted } from './message-mutation-guard';
const OUT = MessageDirection.OUTGOING;
const IN = MessageDirection.INCOMING;
@@ -96,19 +96,22 @@ describe('mutationTargetsForeignRow', () => {
}
});
- it('does not call a lid and a phone number different, since they may be one chat', () => {
- expect(
- mutationTargetsForeignRow({ chatId: '111@lid', direction: IN }, { kind: 'edit', chatId: direct, fromMe: false }),
- ).toBeNull();
- expect(
- mutationTargetsForeignRow({ chatId: direct, direction: IN }, { kind: 'edit', chatId: '111@lid', fromMe: false }),
- ).toBeNull();
- expect(
- mutationTargetsForeignRow(
- { chatId: '111@lid', direction: IN },
- { kind: 'edit', chatId: '222@lid', fromMe: false },
- ),
- ).toBe('chat');
+ it('requires a trusted pairing before a LID can change a phone-keyed row', async () => {
+ for (const kind of ['edit', 'revoke', 'reaction'] as const) {
+ const row = { chatId: direct, direction: IN };
+ const source = { kind, chatId: '111@lid', fromMe: false };
+ expect(mutationTargetsForeignRow(row, source)).toBe('chat');
+ expect(await mutationTargetsForeignRowPersisted(row, source, () => Promise.resolve(null))).toBe('chat');
+ expect(await mutationTargetsForeignRowPersisted(row, source, () => Promise.resolve('628222'))).toBe('chat');
+ expect(await mutationTargetsForeignRowPersisted(row, source, () => Promise.resolve('628111'))).toBeNull();
+ expect(
+ await mutationTargetsForeignRowPersisted(
+ { chatId: '111@lid', direction: IN },
+ { ...source, chatId: '222@lid' },
+ () => Promise.resolve('628111'),
+ ),
+ ).toBe('chat');
+ }
});
// The send routes store the chat id as the caller wrote it, in either dialect the docs give, while the
diff --git a/src/modules/session/message-mutation-guard.ts b/src/modules/session/message-mutation-guard.ts
index 786d3703c..6e0f8bda7 100644
--- a/src/modules/session/message-mutation-guard.ts
+++ b/src/modules/session/message-mutation-guard.ts
@@ -62,25 +62,37 @@ function isOwnBroadcast(row: StoredMessageRef): boolean {
* chat with its sender. A change to it names the sender's chat, which is the chat of that message as well,
* for as long as the row keeps the list id.
*/
-function receivedThroughList(row: StoredMessageRef, chatId: string): boolean {
+function receivedThroughList(
+ row: StoredMessageRef,
+ chatId: string,
+ resolveLid?: (jid: string) => string | null,
+): boolean {
return (
row.direction === MessageDirection.INCOMING &&
entityOf(row.chatId)?.kind === 'broadcast' &&
- !provablyDifferent(row.author, chatId)
+ !provablyDifferent(row.author, chatId, resolveLid)
);
}
/**
* Whether two ids provably name different chats or people, compared by the entity they name rather than
- * by dialect or spelling. A lid against a phone number may be one person.
+ * by dialect or spelling. A LID and phone match only through a reported directory pairing.
*/
-export function provablyDifferent(a?: string | null, b?: string | null): boolean {
+export function provablyDifferent(
+ a?: string | null,
+ b?: string | null,
+ resolveLid?: (jid: string) => string | null,
+): boolean {
if (!a || !b || a === b) return false;
const left = entityOf(a);
const right = entityOf(b);
if (!left || !right) return false;
if (left.kind === right.kind) return left.id !== right.id;
- return !(isPerson(left.kind) && isPerson(right.kind));
+ if (!isPerson(left.kind) || !isPerson(right.kind)) return true;
+ const lid = left.kind === 'lid' ? a : b;
+ const phone = left.kind === 'user' ? left.id : right.id;
+ const mapped = resolveLid?.(lid);
+ return !mapped || phoneKey(mapped) !== phone;
}
/**
@@ -103,17 +115,40 @@ export function provablyDifferent(a?: string | null, b?: string | null): boolean
export function mutationTargetsForeignRow(
row: StoredMessageRef,
source: MutationSource,
+ resolveLid?: (jid: string) => string | null,
): 'chat' | 'direction' | 'author' | null {
- const listed = (source.kind === 'reaction' && isOwnBroadcast(row)) || receivedThroughList(row, source.chatId);
- if (!listed && provablyDifferent(row.chatId, source.chatId)) return 'chat';
+ const listed =
+ (source.kind === 'reaction' && isOwnBroadcast(row)) || receivedThroughList(row, source.chatId, resolveLid);
+ if (!listed && provablyDifferent(row.chatId, source.chatId, resolveLid)) return 'chat';
const group = source.chatId.endsWith('@g.us') || row.chatId.endsWith('@g.us');
const authorOnly = source.kind === 'edit' || (source.kind === 'revoke' && !group);
if (authorOnly && source.fromMe !== undefined) {
const expected = source.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING;
if (row.direction && row.direction !== expected) return 'direction';
}
- if (source.kind === 'edit' && group && source.fromMe === false && provablyDifferent(row.author, source.author)) {
+ if (
+ source.kind === 'edit' &&
+ group &&
+ source.fromMe === false &&
+ provablyDifferent(row.author, source.author, resolveLid)
+ ) {
return 'author';
}
return null;
}
+
+/** Resolve only cross-dialect comparisons through reported directory data; distinct LIDs stay distinct. */
+export async function mutationTargetsForeignRowPersisted(
+ row: StoredMessageRef,
+ source: MutationSource,
+ resolveLid?: (jid: string) => Promise<string | null>,
+): Promise<'chat' | 'direction' | 'author' | null> {
+ if (!resolveLid) return mutationTargetsForeignRow(row, source);
+ const phones = new Map<string, string | null>();
+ await Promise.all(
+ [...new Set([row.chatId, row.author, source.chatId, source.author])].map(async jid => {
+ if (jid && parseWaId(jid).kind === 'lid') phones.set(jid, await resolveLid(jid).catch(() => null));
+ }),
+ );
+ return mutationTargetsForeignRow(row, source, jid => phones.get(jid) ?? null);
+}
diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.ts
index 35be8747d..1d8022cfc 100644
--- a/src/modules/session/message-mutation-projector.ts
+++ b/src/modules/session/message-mutation-projector.ts
@@ -6,7 +6,7 @@ import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { ReactionEvent, EditedMessage } from '../../engine/interfaces/whatsapp-engine.interface';
import { updateMessageMetadata } from '../message/message-metadata';
-import { mutationTargetsForeignRow, type MutationSource } from './message-mutation-guard';
+import { mutationTargetsForeignRowPersisted, type MutationSource } from './message-mutation-guard';
/**
* Applies stored-message mutations — reactions, inbound edits, REST outbound-edit echoes — behind
@@ -25,6 +25,7 @@ export class MessageMutationProjector {
private readonly logger: LoggerService,
// Told of each row the marker below lands on.
private readonly onMarkedEdited: (sessionId: string, waMessageId: string) => void = () => undefined,
+ private readonly resolveLid?: (jid: string) => Promise<string | null>,
) {}
/**
@@ -74,7 +75,9 @@ export class MessageMutationProjector {
where: { sessionId, waMessageId },
select: { chatId: true, direction: true, author: true },
});
- return row ? { exists: true, reason: mutationTargetsForeignRow(row, source) } : { exists: false, reason: null };
+ return row
+ ? { exists: true, reason: await mutationTargetsForeignRowPersisted(row, source, this.resolveLid) }
+ : { exists: false, reason: null };
} catch {
return { exists: false, reason: null };
}
diff --git a/src/modules/session/message-projector.inbound-hold.spec.ts b/src/modules/session/message-projector.inbound-hold.spec.ts
index bc97893d1..328332e0d 100644
--- a/src/modules/session/message-projector.inbound-hold.spec.ts
+++ b/src/modules/session/message-projector.inbound-hold.spec.ts
@@ -80,7 +80,7 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {
let projector: MessageProjector;
let hookStarts: string[];
- const build = (type: string): void => {
+ const build = (type: string, findPhoneForLid?: jest.Mock): void => {
rows = [];
hookStarts = [];
insertGate = () => Promise.resolve();
@@ -131,6 +131,10 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {
hookManager as unknown as HookManager,
statusStore as unknown as StatusStoreService,
{ resolveSenderPhone: jest.fn().mockResolvedValue(null) } as unknown as SessionLidResolver,
+ undefined,
+ undefined,
+ undefined,
+ findPhoneForLid ? ({ findPhoneForLid } as never) : undefined,
);
};
@@ -161,6 +165,288 @@ describe('MessageProjector holding inbound messages (PostgreSQL)', () => {
build('postgres');
});
+ describe('reported identities before the row exists', () => {
+ const lid = '480001@lid';
+ const phone = '[email protected]';
+ const edit = (chatId: string, body: string, timestamp = 2) => ({
+ ...message('A', chatId),
+ messageId: 'A',
+ senderId: chatId,
+ hasMedia: false,
+ body,
+ timestamp,
+ });
+
+ it.each(['edit', 'revoke', 'reaction'] as const)(
+ 'waits for a reported pairing before applying a held %s',
+ async kind => {
+ const lookup = deferred<string | null>();
+ const findPhone = jest.fn(() => lookup.promise);
+ build('postgres', findPhone);
+ const ticket = admit(arrival('A', lid, false, false, false));
+ if (kind === 'edit') projector.applyMessageEditQueued('s1', edit(phone, 'edited', 2));
+ else if (kind === 'reaction')
+ projector.applyReactionQueued('s1', {
+ messageId: 'A',
+ chatId: phone,
+ senderId: phone,
+ reaction: 'yes',
+ });
+ else
+ projector.handleMessageRevoked('s1', engine, { ...message('A', phone), revokedId: 'A' } as RevokedMessage, {
+ fromMe: false,
+ });
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid), ticket)!;
+ await flush();
+ expect(findPhone).toHaveBeenCalledWith(lid);
+ expect(hookStarts).toEqual([]);
+ expect(rows).toEqual([]);
+ lookup.resolve('628001');
+ await receipt.settled;
+ await flush();
+ expect(rows[0]).toMatchObject({
+ body: kind === 'revoke' ? '' : kind === 'edit' ? 'edited' : 'body of A',
+ type: kind === 'revoke' ? 'revoked' : 'text',
+ });
+ if (kind === 'reaction') expect(rows[0].metadata).toMatchObject({ reactions: { [phone]: 'yes' } });
+ },
+ );
+
+ it.each([null, '628999'])('does not accept an unreported or different pairing (%s)', async mapped => {
+ build('postgres', jest.fn().mockResolvedValue(mapped));
+ const ticket = admit(arrival('A', lid, false, false, false));
+ projector.applyMessageEditQueued('s1', edit(phone, 'foreign', 2));
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid), ticket)!;
+ await receipt.settled;
+ await flush();
+ expect(rows[0].body).toBe('body of A');
+ expect(dispatched('message.edited')).toEqual([]);
+ });
+
+ it('keeps the arrival order when an exact edit follows an unresolved alias edit', async () => {
+ const lookup = deferred<string | null>();
+ build(
+ 'postgres',
+ jest
+ .fn()
+ .mockImplementationOnce(() => lookup.promise)
+ .mockResolvedValue('628001'),
+ );
+ const ticket = admit(arrival('A', lid, false, false, false));
+ projector.applyMessageEditQueued('s1', edit(phone, 'first', 2));
+ projector.applyMessageEditQueued('s1', edit(lid, 'last', 3));
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid), ticket)!;
+ await flush();
+ lookup.resolve('628001');
+ await receipt.settled;
+ await flush();
+ expect(dispatched('message.edited').map(change => change.body)).toEqual(['first', 'last']);
+ expect(rows[0].body).toBe('last');
+ expect(dispatched('message.received')[0].body).toBe('last');
+ });
+
+ it('waits for a pairing requested while the receive hook is running', async () => {
+ const lookup = deferred<string | null>();
+ const hook = deferred<void>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ hookManager.execute.mockImplementation(async (_event: string, data: unknown) => {
+ await hook.promise;
+ return { data };
+ });
+ const receipt = projector.handleInboundMessage(
+ 's1',
+ engine,
+ message('A', lid),
+ admit(arrival('A', lid, false, false, false)),
+ )!;
+ await flush();
+ projector.applyMessageEditQueued('s1', edit(phone, 'edited', 2));
+ hook.resolve();
+ await flush();
+ expect(rows).toEqual([]);
+ expect(dispatched('message.received')).toEqual([]);
+ lookup.resolve('628001');
+ await receipt.settled;
+ await flush();
+ expect(rows[0].body).toBe('edited');
+ expect(dispatched('message.received')[0].body).toBe('edited');
+ });
+
+ it('waits for a pairing requested during the insert before announcing its content', async () => {
+ const lookup = deferred<string | null>();
+ const inserting = deferred<void>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ insertGate = () => inserting.promise;
+ const receipt = projector.handleInboundMessage(
+ 's1',
+ engine,
+ message('A', lid),
+ admit(arrival('A', lid, false, false, false)),
+ )!;
+ await flush();
+ projector.applyMessageEditQueued('s1', edit(phone, 'edited', 2));
+ inserting.resolve();
+ await flush();
+ expect(dispatched('message.received')).toEqual([]);
+ lookup.resolve('628001');
+ await receipt.settled;
+ await flush();
+ expect(rows[0].body).toBe('edited');
+ expect(dispatched('message.received')[0].body).toBe('edited');
+ });
+
+ it.each(['edit', 'revoke'].flatMap(kind => [true, false].map(exact => ({ kind, exact }))))(
+ 'keeps SQLite persisted notifications consistent with a held $kind (exact=$exact)',
+ async ({ kind, exact }) => {
+ const hook = deferred<void>();
+ build('better-sqlite3', jest.fn().mockResolvedValue('628001'));
+ const archived: Row[] = [];
+ Object.assign(projector, {
+ chatMediaArchive: {
+ archive: jest.fn((row: Row) => {
+ archived.push({ ...row });
+ return Promise.resolve();
+ }),
+ },
+ });
+ hookManager.execute.mockImplementation(async (event: string, data: unknown) => {
+ if (event === 'message:received') await hook.promise;
+ return { data };
+ });
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid))!;
+ const target = exact ? lid : phone;
+ if (kind === 'edit') projector.applyMessageEditQueued('s1', edit(target, 'edited'));
+ else
+ projector.handleMessageRevoked('s1', engine, { ...message('A', target), revokedId: 'A' } as RevokedMessage, {
+ fromMe: false,
+ });
+ await flush();
+ hook.resolve();
+ await receipt.settled;
+ await flush();
+ expect(persistedHooks().length).toBeGreaterThan(0);
+ expect(archived).toHaveLength(1);
+ expect(archived[0]).toMatchObject({
+ body: kind === 'edit' ? 'edited' : '',
+ type: kind === 'edit' ? 'text' : 'revoked',
+ });
+ expect(
+ persistedHooks().every(
+ row =>
+ row.body === (kind === 'edit' ? 'edited' : '') && row.type === (kind === 'edit' ? 'text' : 'revoked'),
+ ),
+ ).toBe(true);
+ },
+ );
+
+ it('keeps an own-send echo behind an identity check started during its hook', async () => {
+ const lookup = deferred<string | null>();
+ const hook = deferred<void>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ hookManager.execute.mockImplementation(async (event: string, data: unknown) => {
+ if (event === 'message:sent') await hook.promise;
+ return { data };
+ });
+ projector.handleOwnSendEcho(
+ 's1',
+ engine,
+ message('A', lid, { fromMe: true }),
+ admit(arrival('A', lid, false, false, true)),
+ );
+ await flush();
+ projector.applyMessageEditQueued('s1', { ...edit(phone, 'edited'), fromMe: true });
+ hook.resolve();
+ await flush();
+ expect(rows).toEqual([]);
+ expect(dispatched('message.sent')).toEqual([]);
+ lookup.resolve('628001');
+ await flush();
+ expect(rows[0].body).toBe('edited');
+ expect(dispatched('message.sent')[0].body).toBe('edited');
+ });
+
+ it.each(['edit', 'revoke'] as const)('keeps a requested %s while its alias identity is checked', async kind => {
+ const lookup = deferred<string | null>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ const ticket = admit(arrival('A', lid, false, false, true));
+ const source = { kind, chatId: phone, fromMe: true } as const;
+ const changed =
+ kind === 'edit'
+ ? projector.recordOutboundMessageEdit('s1', 'A', 'edited', source)
+ : projector.recordRevoke('s1', 'A', source);
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid, { fromMe: true }), ticket)!;
+ await flush();
+ expect(rows).toEqual([]);
+ lookup.resolve('628001');
+ await changed;
+ await receipt.settled;
+ await flush();
+ expect(rows[0]).toMatchObject({
+ body: kind === 'edit' ? 'edited' : '',
+ type: kind === 'edit' ? 'text' : 'revoked',
+ });
+ });
+
+ it('drains a rejected identity read without applying the alias change', async () => {
+ build('postgres', jest.fn().mockRejectedValue(new Error('read unavailable')));
+ const ticket = admit(arrival('A', lid, false, false, false));
+ projector.applyMessageEditQueued('s1', edit(phone, 'foreign', 2));
+ await projector.handleInboundMessage('s1', engine, message('A', lid), ticket)!.settled;
+ await flush();
+ expect(rows[0].body).toBe('body of A');
+ expect(dispatched('message.edited')).toEqual([]);
+ });
+
+ it('does not apply a pending alias change to a replacement entry of another identity', async () => {
+ const lookup = deferred<string | null>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ admit(arrival('A', lid, false, false, false));
+ projector.applyMessageEditQueued('s1', edit(phone, 'foreign', 2));
+ await flush();
+ const entries = (projector as unknown as { inboundInFlight: Map<string, object> }).inboundInFlight;
+ const replacement = { ref: { chatId: '[email protected]', direction: 'incoming' } };
+ entries.set('s1:A', replacement);
+ lookup.resolve('628001');
+ await flush();
+ expect(replacement).not.toHaveProperty('editedBody');
+ expect(dispatched('message.edited')).toEqual([]);
+ });
+
+ it('discards a directory result after the reporting engine retires', async () => {
+ const lookup = deferred<string | null>();
+ build(
+ 'postgres',
+ jest.fn(() => lookup.promise),
+ );
+ const ticket = admit(arrival('A', lid, false, false, false));
+ projector.applyMessageEditQueued('s1', edit(phone, 'late', 2));
+ const receipt = projector.handleInboundMessage('s1', engine, message('A', lid), ticket)!;
+ await flush();
+ engines.set('s1', {} as IWhatsAppEngine);
+ lookup.resolve('628001');
+ await receipt.settled;
+ await flush();
+ expect(rows).toEqual([]);
+ expect(dispatched('message.edited')).toEqual([]);
+ expect(dispatched('message.received')).toEqual([]);
+ });
+ });
+
afterEach(() => {
process.env = { ...env };
});
diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.ts
index b1c4fc7f5..de2636ac3 100644
--- a/src/modules/session/message-projector.service.spec.ts
+++ b/src/modules/session/message-projector.service.spec.ts
@@ -435,7 +435,11 @@ describe('MessageProjector', () => {
metadata: null,
timestamp: 1_700_000_000,
};
- messageRepository.find.mockResolvedValueOnce([{ waMessageId: 'WA1', type: 'text' }]).mockResolvedValueOnce([row]);
+ messageRepository.find
+ .mockResolvedValueOnce([
+ { waMessageId: 'WA1', type: 'text', chatId: '[email protected]', direction: MessageDirection.INCOMING },
+ ])
+ .mockResolvedValueOnce([row]);
const builder = {
insert: jest.fn().mockReturnThis(),
values: jest.fn().mockReturnThis(),
@@ -1957,13 +1961,13 @@ describe('MessageProjector (inbound projection)', () => {
expect(outcome).toBeUndefined();
});
- it('reports nothing for a chat it cannot compare with the row, as a lid against a phone number', async () => {
+ it('reports a conflict for a LID without a reported pairing to the phone-keyed row', async () => {
const outcome = await repeat(
{ chatId: '99887766@lid' },
{ chatId: '[email protected]', direction: 'incoming', author: null },
);
- expect(outcome).toBeUndefined();
+ expect(outcome).toEqual({ conflict: true });
});
it('judges the message a hook left, as the row it would have written', async () => {
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index bddbb4b9e..8328e9972 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -1,3 +1,4 @@
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { Injectable, Optional } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
@@ -11,7 +12,12 @@ import { awaitNoOpenTransaction } from '../../common/utils/shared-connection';
import { SessionLidResolver } from './session-lid-resolver.service';
import { buildMessageMetadata, REVOKED_ROW_PATCH, storableWaMessageId } from './message-row.mapper';
import { MessageMutationProjector } from './message-mutation-projector';
-import { mutationTargetsForeignRow, type MutationSource, type StoredMessageRef } from './message-mutation-guard';
+import {
+ mutationTargetsForeignRow,
+ mutationTargetsForeignRowPersisted,
+ type MutationSource,
+ type StoredMessageRef,
+} from './message-mutation-guard';
import { updateMessageMetadata } from '../message/message-metadata';
import { persistHistoryMessages } from './message-history-projector';
import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';
@@ -128,6 +134,8 @@ interface InFlightEntry {
// delivery shares the entry, and its payload must not outlive the slot that accounts for it.
// Unset while the message is admitted but not yet emitted (see admitInbound).
quote?: Pick<IncomingMessage, 'chatId' | 'body'>;
+ // Only the active delivery that supplied the checked quote may replace or clear it.
+ quoteOwner?: object;
// Where the message lives and who wrote it, so a change recorded for it meanwhile is held to the same
// chat, direction and author rule as the row it will become (see mutationTargetsForeignRow).
ref?: StoredMessageRef;
@@ -144,8 +152,17 @@ interface InFlightEntry {
ackStatus?: MessageStatus;
// Latest reaction per sender; '' means the sender withdrew theirs.
reactions?: Record<string, string>;
- // Tickets sharing the entry: a repeat delivery keeps what was recorded for the first one.
+ // Deliveries sharing the entry: a repeat keeps what was recorded for the first one.
holders?: number;
+ // Shared by repeat deliveries while an identity comparison waits for the directory.
+ changes?: { pending?: Promise<void> };
+}
+
+/** Scalar arrival data and the changes this delivery's identity may inherit. */
+interface InFlightDelivery {
+ entry: InFlightEntry;
+ body: string;
+ edited: boolean;
}
/**
@@ -160,10 +177,11 @@ class InboundTurn implements InboundTicket {
readonly emitted = deferred<void>();
/** Resolved once every earlier message of the chat was emitted or dropped: the hook may start. */
readonly hookGate = deferred<void>();
+ private preparing?: Promise<void>;
constructor(
readonly engine: IWhatsAppEngine,
- readonly entry: InFlightEntry,
+ public entry: InFlightEntry,
private readonly room?: InboundRoom,
readonly s?: RoomState,
) {}
@@ -172,9 +190,21 @@ class InboundTurn implements InboundTicket {
return this.entry.revoked === true;
}
+ /** A cross-form repeat inherits changes only once its directory comparison has finished. */
+ prepareIdentity(pending: Promise<void>): void {
+ this.preparing = Promise.race([pending, this.outcome.promise.then(() => undefined)]);
+ }
+
// A message revoked before its download needs none: its row is stored cleared.
reserve(): boolean | Promise<boolean> {
if (!this.s || !this.room || this.state === 'dropped') return false;
+ if (this.preparing) {
+ const preparing = this.preparing;
+ return preparing.then(() => {
+ if (this.preparing === preparing) this.preparing = undefined;
+ return this.reserve();
+ });
+ }
if (this.entry.revoked) return this.giveUp();
return this.s.granted || this.room.wait(this.s).then(granted => granted && !this.entry.revoked);
}
@@ -278,6 +308,7 @@ export class MessageProjector {
// Optional for the same reason. Absent simply means no autoreply rules are evaluated.
@Optional()
private readonly automationRules?: AutomationRulesService,
+ @Optional() private readonly lidMappingStore?: LidMappingStoreService,
) {
this.mutationProjector = new MessageMutationProjector(
this.messageRepository,
@@ -286,6 +317,7 @@ export class MessageProjector {
this.messageMutations,
this.logger,
(sessionId, waMessageId) => this.noteMarkedEdited(sessionId, waMessageId),
+ this.lidMappingStore ? jid => this.lidMappingStore!.findPhoneForLid(jid) : undefined,
);
this.engines.onRetire((id, engine) => {
for (const t of this.tickets.get(id) ?? []) if (t.engine === engine) t.drop();
@@ -335,7 +367,12 @@ export class MessageProjector {
}
entry.holders = (entry.holders ?? 0) + 1;
const room = a.needsRoom ? this.room(id) : undefined;
- const t = new InboundTurn(engine, entry, room, room && roomState());
+ const source: MutationSource = { kind: 'edit', chatId: a.chatId, fromMe: a.fromMe, author: a.author };
+ const separate = entry.ref && mutationTargetsForeignRow(entry.ref, source) !== null;
+ const scoped: InFlightEntry = separate
+ ? { ref: a.fromMe === undefined ? undefined : refOf({ chatId: a.chatId, fromMe: a.fromMe, author: a.author }) }
+ : entry;
+ const t = new InboundTurn(engine, scoped, room, room && roomState());
let set = this.tickets.get(id);
if (!set) this.tickets.set(id, (set = new Set()));
set.add(t);
@@ -368,6 +405,17 @@ export class MessageProjector {
if (!this.engines.has(id)) this.deleteRoomIfIdle(id);
});
}
+ if (key && separate && this.lidMappingStore) {
+ const pending = this.changeInFlight(id, a.id, source, (needsRow, shared) => {
+ if (!this.engines.isLive(id, engine) || t.state === 'dropped') return;
+ if (shared && !needsRow) {
+ t.entry = shared;
+ if (shared.revoked) t.giveUp();
+ }
+ });
+ // A revoke queued during the directory read must reach the ticket before its download starts.
+ if (pending) t.prepareIdentity(pending.then(() => this.waitForInFlightChanges(id, a.id)));
+ }
return t;
}
@@ -445,7 +493,12 @@ export class MessageProjector {
const inFlight = turn
? Object.assign(turn.entry, { ref: turn.entry.ref ?? refOf(messageData) })
: this.trackInFlight(inFlightKey, messageData);
- this.arrive(inFlight, message);
+ const delivery = {
+ entry: inFlight,
+ body: message.originalBody ?? message.body,
+ edited: message.originalBody !== undefined,
+ };
+ const quoteOwner = {};
const onFailure = (err: unknown): null => {
this.logger.error(`onMessage handler failed for ${id}`, String(err));
@@ -454,14 +507,14 @@ export class MessageProjector {
// Execute hook for message received - plugins can modify or stop processing. The hook chain and
// sender resolution run concurrently across messages; the catch is attached now so a failure
// while the commit waits its turn is never an unhandled rejection.
- const prepared = this.startHookChain(id, engine, turn, messageData, messageData =>
+ const prepared = this.startHookChain(id, engine, turn, messageData, delivery, quoteOwner, messageData =>
this.hookManager
.execute('message:received', messageData, {
sessionId: id,
source: 'Engine',
accept: data => {
if (!isMessagePayload(data)) return false;
- inFlight.quote = quoteOf(data);
+ if (delivery.entry.quoteOwner === quoteOwner) delivery.entry.quote = quoteOf(data);
return true;
},
})
@@ -473,11 +526,12 @@ export class MessageProjector {
this.commitInTurn(id, message, turn, async () => {
try {
const finalMessage = await prepared;
- if (finalMessage) outcome.resolve(await this.commitInboundMessage(id, engine, finalMessage));
+ if (finalMessage) outcome.resolve(await this.commitInboundMessage(id, engine, finalMessage, delivery.entry));
} catch (err) {
onFailure(err);
} finally {
outcome.resolve(undefined); // no effect once settled above
+ this.clearQuote(delivery.entry, quoteOwner);
if (!turn) this.untrackInFlight(inFlightKey, inFlight);
}
});
@@ -496,6 +550,8 @@ export class MessageProjector {
engine: IWhatsAppEngine,
turn: InboundTurn | undefined,
messageData: InboundMessageData,
+ delivery: InFlightDelivery,
+ quoteOwner: object,
run: (message: InboundMessageData) => Promise<InboundMessageData>,
): Promise<InboundMessageData | null> {
const checked = async (): Promise<InboundMessageData | null> => {
@@ -511,7 +567,14 @@ export class MessageProjector {
where: { sessionId: id, waMessageId: data.id, type: 'revoked' },
select: { type: true, chatId: true, direction: true, author: true },
});
- if (row?.type === 'revoked' && !mutationTargetsForeignRow(row, claimOf(data))) {
+ if (
+ row?.type === 'revoked' &&
+ !(await mutationTargetsForeignRowPersisted(
+ row,
+ claimOf(data),
+ this.lidMappingStore ? jid => this.lidMappingStore!.findPhoneForLid(jid) : undefined,
+ ))
+ ) {
data = deletedPlaceholder(data);
}
} catch (error) {
@@ -524,21 +587,34 @@ export class MessageProjector {
}
}
if (!this.engines.isLive(id, engine)) return null;
- const pending = this.inboundInFlight.get(`${id}:${data.id}`);
- if (pending && !this.foreignToInFlight(pending, claimOf(data))) {
- if (data.type === 'revoked') this.holdRevoked(id, pending);
- if (pending.revoked) data = deletedPlaceholder(data);
- pending.quote = quoteOf(data);
- }
- return run(data);
+ let result: Promise<InboundMessageData> | null = null;
+ const preparing = this.changeInFlight(id, data.id, claimOf(data), (needsRow, pending) => {
+ if (!this.engines.isLive(id, engine)) return;
+ // A reused id from another identity keeps its own scalar changes, never the first delivery's.
+ delivery.entry = pending && !needsRow ? pending : { ref: refOf(data) };
+ this.arrive(delivery.entry, delivery);
+ if (pending && !needsRow) {
+ const skipHooks = turn && pending.revoked && messageData.type !== 'revoked';
+ if (data.type === 'revoked') this.holdRevoked(id, pending);
+ if (pending.revoked) data = deletedPlaceholder(data);
+ else if (pending.editedBody !== undefined) data.body = pending.editedBody;
+ if (skipHooks) {
+ result = Promise.resolve(data);
+ return;
+ }
+ pending.quote = quoteOf(data);
+ pending.quoteOwner = quoteOwner;
+ }
+ // Start the hook in this preparation turn, but never make preparation wait for the hook.
+ result = run(data);
+ });
+ if (preparing) await preparing;
+ return result;
};
if (!turn) return checked();
- const { entry } = turn;
- return turn.hookGate.promise.then(() => {
+ return turn.hookGate.promise.then(async () => {
+ await this.waitForInFlightChanges(id, messageData.id);
if (!this.engines.isLive(id, engine)) return null;
- if (entry.revoked && messageData.type !== 'revoked') return messageData;
- // A delivery that came deleted has no text for the edit to replace.
- if (entry.editedBody !== undefined && messageData.type !== 'revoked') messageData.body = entry.editedBody;
return checked();
});
}
@@ -556,21 +632,14 @@ export class MessageProjector {
/** Record a message as not yet written; a re-fire of the same id keeps the changes recorded so far. */
private trackInFlight(key: string, message: InboundMessageData): InFlightEntry {
- const { quote, ref, revoked, revokeAnnounced, editedBody, edited, ackStatus, reactions } =
- this.inboundInFlight.get(key) ?? {};
- const inFlight: InFlightEntry = {
- // A new delivery lends no unchecked content while its stored-message lookup waits.
- quote,
+ const inFlight = this.inboundInFlight.get(key) ?? {
// The first delivery of an id says whose message it is: a repeat sent from another chat must not
// take that over from it, or a change aimed through the repeat would be judged by the wrong rule.
- ref: ref ?? refOf(message),
- revoked,
- revokeAnnounced,
- editedBody,
- edited,
- ackStatus,
- reactions,
+ ref: refOf(message),
};
+ // Repeats can commit through different chat spellings, so none may forget the others' changes.
+ // A new entry lends no unchecked quote; a repeat keeps only the previous checked quote.
+ inFlight.holders = (inFlight.holders ?? 0) + 1;
this.inboundInFlight.set(key, inFlight);
return inFlight;
}
@@ -580,9 +649,9 @@ export class MessageProjector {
* engine applied itself changed that text, though a later one may have restored it (it names the arrival text only
* then, so it can equal the body), and marks the row the same way.
*/
- private arrive(entry: InFlightEntry, message: IncomingMessage): void {
- entry.body = message.originalBody ?? message.body;
- if (message.originalBody !== undefined || (entry.editedBody !== undefined && entry.editedBody !== entry.body)) {
+ private arrive(entry: InFlightEntry, arrival: Pick<InFlightDelivery, 'body' | 'edited'>): void {
+ entry.body = arrival.body;
+ if (arrival.edited || (entry.editedBody !== undefined && entry.editedBody !== entry.body)) {
entry.edited = true;
}
}
@@ -594,9 +663,16 @@ export class MessageProjector {
entry.editedBody = body;
}
- /** Drop the entry once its commit ended, unless a re-fire of the same id replaced it. */
- private untrackInFlight(key: string, inFlight: object): void {
- if (this.inboundInFlight.get(key) === inFlight) this.inboundInFlight.delete(key);
+ /** Drop the entry once every delivery sharing it has committed. */
+ private untrackInFlight(key: string, inFlight: InFlightEntry): void {
+ if (inFlight.holders) inFlight.holders--;
+ if (!inFlight.holders && this.inboundInFlight.get(key) === inFlight) this.inboundInFlight.delete(key);
+ }
+
+ private clearQuote(entry: InFlightEntry, owner: object): void {
+ if (entry.quoteOwner !== owner) return;
+ delete entry.quote;
+ delete entry.quoteOwner;
}
/**
@@ -740,10 +816,11 @@ export class MessageProjector {
id: string,
engine: IWhatsAppEngine,
finalMessage: InboundMessageData,
+ entry: InFlightEntry,
): Promise<InboundOutcome | undefined> {
- const outcome = await this.persistInboundMessage(id, engine, finalMessage);
+ const outcome = await this.persistInboundMessage(id, engine, finalMessage, entry);
if (outcome === 'repeat') return this.judgeRepeat(id, finalMessage);
- if (outcome) this.dispatchInboundMessage(id, finalMessage, outcome);
+ if (outcome) this.dispatchInboundMessage(id, finalMessage, outcome, entry);
return undefined;
}
@@ -780,6 +857,7 @@ export class MessageProjector {
id: string,
engine: IWhatsAppEngine,
incoming: IncomingMessage,
+ entry: InFlightEntry,
): Promise<InboundPersistOutcome | 'repeat' | null> {
const metadata = buildMessageMetadata(incoming);
@@ -807,8 +885,9 @@ export class MessageProjector {
// awaits. Re-check liveness so a late continuation can't persist an orphan messages row
// (the row has no FK, so a session-delete cleanup would never reap it) or dispatch for a
// session that no longer exists. Mirrors the synchronous isLiveEngine gate at entry.
+ await this.waitForInFlightChanges(id, incoming.id);
if (!this.engines.isLive(id, engine)) return null;
- const insertedCleared = this.applyHeldChanges(id, dbMessage);
+ const insertedCleared = this.applyHeldChanges(dbMessage, entry);
// De-duplicate at the source: the engine can re-fire `message` for one inbound message
// (#464). UNIQUE(sessionId, waMessageId) makes the insert the atomic dedup oracle — a
@@ -816,8 +895,10 @@ export class MessageProjector {
// happen exactly once. Fail-open: a non-conflict DB error still dispatches, so a real
// message is never dropped by a transient DB failure.
const outcome = await this.insertWithRetry(id, engine, dbMessage, 'incoming');
+ await this.waitForInFlightChanges(id, incoming.id);
+ if (!this.engines.isLive(id, engine)) return null;
if (outcome.landed === 'yes') {
- this.applyChangesMadeInFlight(id, incoming.id, insertedCleared);
+ this.applyChangesMadeInFlight(id, incoming.id, entry, insertedCleared);
return { dbMessage, persisted: true };
}
if (outcome.landed === 'stale') return null;
@@ -826,7 +907,7 @@ export class MessageProjector {
// in which case nothing dispatched yet, so dispatch fail-open (without the row-bound hook), and
// that row still has to take a revoke or edit that arrived in flight.
if (outcome.landed === 'dup' && outcome.retried) {
- this.applyChangesMadeInFlight(id, incoming.id, false, claimOf(incoming));
+ this.applyChangesMadeInFlight(id, incoming.id, entry, false, claimOf(incoming));
}
// A delivery that came deleted clears the row it lost to, as a revoke does, once the row proves to be the message.
if (outcome.landed === 'dup' && incoming.type === 'revoked') {
@@ -837,19 +918,17 @@ export class MessageProjector {
}
/**
- * PostgreSQL holds a message from its arrival, so a revoke or edit often lands before its row: write
+ * A revoke or edit can arrive while a message waits for its hook or insert: write
* the row as the change leaves it, so `message:persisted` and the media archive never see content
* that was taken back. A change landing during the insert is still applied after it. A message
* delivered deleted is written cleared on either database, as the history sync stores one, and takes
* no edit. Returns whether the row is written cleared.
*/
- private applyHeldChanges(id: string, dbMessage: Message): boolean {
+ private applyHeldChanges(dbMessage: Message, entry: InFlightEntry): boolean {
if (dbMessage.type === 'revoked') {
Object.assign(dbMessage, REVOKED_ROW_PATCH);
return true;
}
- if (!this.holdsInbound) return false;
- const entry = dbMessage.waMessageId ? this.inboundInFlight.get(`${id}:${dbMessage.waMessageId}`) : undefined;
if (entry?.revoked) Object.assign(dbMessage, REVOKED_ROW_PATCH);
else {
if (entry?.editedBody !== undefined) dbMessage.body = entry.editedBody;
@@ -924,11 +1003,10 @@ export class MessageProjector {
private applyChangesMadeInFlight(
id: string,
waMessageId: string,
+ pending: InFlightEntry,
insertedCleared = false,
lostInsert?: MutationSource,
): void {
- const pending = waMessageId ? this.inboundInFlight.get(`${id}:${waMessageId}`) : undefined;
- if (!pending) return;
const { ackStatus } = pending;
const rowChanges = Boolean(
pending.revoked || pending.editedBody !== undefined || pending.edited || pending.reactions,
@@ -1011,14 +1089,16 @@ export class MessageProjector {
* foreign to it. Without one, the revoke was judged by the caller (the engine's revoke event is).
*/
recordRevoke(sessionId: string, waMessageId: string, source?: MutationSource): Promise<void> {
- // A message not written yet takes the revoke once its row lands; the UPDATE below matches nothing.
- const inFlight = this.inboundInFlight.get(`${sessionId}:${waMessageId}`);
- if (inFlight && !(source && this.foreignToInFlight(inFlight, source))) this.holdRevoked(sessionId, inFlight);
- return new Promise(resolve =>
- this.enqueueMessageMutation(sessionId, waMessageId, () =>
- this.revokeRow(sessionId, waMessageId, true, source).finally(resolve),
- ),
- );
+ let stored: Promise<void> | undefined;
+ const pending = this.changeInFlight(sessionId, waMessageId, source, (needsRow, entry) => {
+ if (entry && !needsRow) this.holdRevoked(sessionId, entry);
+ stored = new Promise(resolve =>
+ this.enqueueMessageMutation(sessionId, waMessageId, () =>
+ this.revokeRow(sessionId, waMessageId, true, source).finally(resolve),
+ ),
+ );
+ });
+ return Promise.resolve(pending).then(() => stored);
}
/** Take back a message not written yet: its row is stored cleared, and media waiting for room needs none. */
@@ -1065,7 +1145,12 @@ export class MessageProjector {
}
/** Fan an accepted inbound message out: `message:persisted` plugin hook, webhook, websocket emit. */
- private dispatchInboundMessage(id: string, finalMessage: InboundMessageData, outcome: InboundPersistOutcome): void {
+ private dispatchInboundMessage(
+ id: string,
+ finalMessage: InboundMessageData,
+ outcome: InboundPersistOutcome,
+ entry: InFlightEntry,
+ ): void {
const { dbMessage, persisted } = outcome;
// Fire-and-forget: a plugin handler must never break the receive path. Both engine adapters
// (wwjs `message` and Baileys `upsert`) converge on this persist, so one emit covers inbound.
@@ -1091,7 +1176,7 @@ export class MessageProjector {
void this.chatMediaArchive?.archive(dbMessage).catch(() => undefined);
}
- const announced = this.withChangesMadeInFlight(id, finalMessage);
+ const announced = this.withChangesMadeInFlight(finalMessage, entry);
if (!announced) return;
// Dispatch to webhooks with potentially modified message
void this.webhookService.dispatch(id, 'message.received', announced);
@@ -1114,11 +1199,10 @@ export class MessageProjector {
* when that row is the message.
*/
private withChangesMadeInFlight(
- id: string,
message: InboundMessageData,
+ pending: InFlightEntry,
rowMarked = false,
): (InboundMessageData & { edited?: true }) | null {
- const pending = this.inboundInFlight.get(`${id}:${message.id}`);
if (pending?.revokeAnnounced) return null;
// No edit held for it, and no mark.
if (pending?.revoked || message.type === 'revoked') return deletedPlaceholder(message);
@@ -1177,17 +1261,22 @@ export class MessageProjector {
const inFlight = turn
? Object.assign(turn.entry, { ref: turn.entry.ref ?? refOf(messageData) })
: this.trackInFlight(inFlightKey, messageData);
- this.arrive(inFlight, message);
+ const delivery = {
+ entry: inFlight,
+ body: message.originalBody ?? message.body,
+ edited: message.originalBody !== undefined,
+ };
+ const quoteOwner = {};
// Execute hook for message sent - plugins can modify or stop processing. Like the inbound path,
// the hook chain runs concurrently and the commit waits its turn on the chat's queue.
- const prepared = this.startHookChain(id, engine, turn, messageData, messageData =>
+ const prepared = this.startHookChain(id, engine, turn, messageData, delivery, quoteOwner, messageData =>
this.hookManager
.execute('message:sent', messageData, {
sessionId: id,
source: 'Engine',
accept: data => {
if (!isMessagePayload(data)) return false;
- inFlight.quote = quoteOf(data);
+ if (delivery.entry.quoteOwner === quoteOwner) delivery.entry.quote = quoteOf(data);
return true;
},
})
@@ -1196,10 +1285,11 @@ export class MessageProjector {
this.commitInTurn(id, message, turn, async () => {
try {
const finalMessage = await prepared;
- if (finalMessage) await this.commitOwnSendEcho(id, engine, finalMessage);
+ if (finalMessage) await this.commitOwnSendEcho(id, engine, finalMessage, delivery.entry);
} catch (err) {
onFailure(err);
} finally {
+ this.clearQuote(delivery.entry, quoteOwner);
if (!turn) this.untrackInFlight(inFlightKey, inFlight);
}
});
@@ -1210,6 +1300,7 @@ export class MessageProjector {
id: string,
engine: IWhatsAppEngine,
finalMessage: InboundMessageData,
+ entry: InFlightEntry,
): Promise<void> {
// `continue: false` is not read here, for the same reason as the message:received path
// above: the send has already happened, so a plugin can stop the handler chain but cannot
@@ -1223,6 +1314,8 @@ export class MessageProjector {
// persistSentState additionally drops its redundant PENDING row when the echo won. The
// webhook/WS dispatch below is identical whether the insert won, lost, or failed: the
// message.sent contract is unchanged.
+ await this.waitForInFlightChanges(id, finalMessage.id);
+ if (!this.engines.isLive(id, engine)) return;
const outgoing: IncomingMessage = finalMessage;
const metadata = buildMessageMetadata(outgoing, true);
@@ -1251,15 +1344,17 @@ export class MessageProjector {
// awaits. Re-check liveness so a late continuation can't persist an orphan row
// (mirrors onMessage).
if (!this.engines.isLive(id, engine)) return;
- const insertedCleared = this.applyHeldChanges(id, dbMessage);
+ const insertedCleared = this.applyHeldChanges(dbMessage, entry);
// A unique violation means the REST send path already persisted this API-originated
// send: the dedup oracle working as intended, not an error. Any other failure (after the
// one transient retry) fails open, so a real send is never dropped on a DB fault.
const outcome = await this.insertWithRetry(id, engine, dbMessage, 'outgoing');
+ await this.waitForInFlightChanges(id, outgoing.id);
+ if (!this.engines.isLive(id, engine)) return;
if (outcome.landed === 'stale') return;
// The REST writer may have won either attempt; its row still takes the echo's pending changes.
if (outcome.landed === 'dup') {
- this.applyChangesMadeInFlight(id, outgoing.id, false, claimOf(outgoing));
+ this.applyChangesMadeInFlight(id, outgoing.id, entry, false, claimOf(outgoing));
// A delivery that came deleted clears that row, as a revoke does, once the row proves to be the message.
if (outgoing.type === 'revoked') void this.recordRevoke(id, outgoing.id, claimOf(outgoing));
// That row may be older than this delivery and edited since, the edit still being written: announced once the
@@ -1273,7 +1368,7 @@ export class MessageProjector {
if (outcome.landed === 'yes') {
// The id had no row, so a mark remembered for it was of a row removed since.
this.markedEdited.get(id)?.delete(outgoing.id);
- this.applyChangesMadeInFlight(id, outgoing.id, insertedCleared);
+ this.applyChangesMadeInFlight(id, outgoing.id, entry, insertedCleared);
// Fire-and-forget, mirroring onMessage: plugin providers (search etc.) see phone-
// composed sends exactly like API sends.
void this.hookManager
@@ -1295,7 +1390,7 @@ export class MessageProjector {
}
}
- const sent = this.withChangesMadeInFlight(id, finalMessage, rowMarked);
+ const sent = this.withChangesMadeInFlight(finalMessage, entry, rowMarked);
if (!sent) return;
void this.webhookService.dispatch(id, 'message.sent', sent);
// Emit real-time event to WebSocket clients (as message.sent, not message.received)
@@ -1479,32 +1574,25 @@ export class MessageProjector {
return;
}
const source = { kind: 'revoke', chatId: message.chatId, fromMe: actor.fromMe } as const;
- const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);
- // A message still arriving, once the entry it is held under agrees with the revoke, is taken back at
- // once: waiting for a read would let its emit run, and announce the deleted content, first. That is all
- // the entry can vouch for. A repeat of an id sent from another chat is held under it too, and the row
- // under the id may be the other chat's message, which only the row can say: the announcement and the
- // clearing of the row wait for it.
- const held = inFlight !== undefined && !this.foreignToInFlight(inFlight, source);
- if (held) {
- this.holdRevoked(id, inFlight);
- inFlight.revokeAnnounced = true;
- }
- // Otherwise judged by the stored row, which a change the entry called foreign has to find, and accept.
- const needsRow = inFlight !== undefined && !held;
- void this.mutationProjector.storedRowVerdict(id, revokedWaMessageId, source).then(verdict => {
- if (!this.engines.isLive(id, engine)) return;
- if (verdict.reason || (needsRow && !verdict.exists)) {
- if (verdict.reason) {
- this.logger.warn('Dropping a revoke aimed at a message of another chat or sender', {
- sessionId: id,
- messageId: revokedWaMessageId,
- reason: verdict.reason,
- });
- }
- return;
+ void this.changeInFlight(id, revokedWaMessageId, source, (needsRow, inFlight) => {
+ if (inFlight && !needsRow) {
+ this.holdRevoked(id, inFlight);
+ inFlight.revokeAnnounced = true;
}
- apply();
+ void this.mutationProjector.storedRowVerdict(id, revokedWaMessageId, source).then(verdict => {
+ if (!this.engines.isLive(id, engine)) return;
+ if (verdict.reason || (needsRow && !verdict.exists)) {
+ if (verdict.reason) {
+ this.logger.warn('Dropping a revoke aimed at a message of another chat or sender', {
+ sessionId: id,
+ messageId: revokedWaMessageId,
+ reason: verdict.reason,
+ });
+ }
+ return;
+ }
+ apply();
+ });
});
}
@@ -1523,52 +1611,85 @@ export class MessageProjector {
.execute('message:persisted', { sessionId: id, message: row }, { sessionId: id, source: 'SessionService' })
.catch(() => undefined);
},
+ this.lidMappingStore ? jid => this.lidMappingStore!.findPhoneForLid(jid) : undefined,
);
}
/** Reaction apply, queued on the per-message mutation chain — see MessageMutationProjector. */
applyReactionQueued(id: string, event: ReactionEvent): void {
- // A message not written yet keeps the reaction for its row; the live event still goes out now.
- const inFlight = event.messageId ? this.inboundInFlight.get(`${id}:${event.messageId}`) : undefined;
- let needsRow = false;
- if (inFlight) {
- // The row it will become would drop the change, so it is not kept for it. Nothing is announced on
- // that word alone either: a stored row of the same id (a repeat sent from another chat reached the
- // entry, not the message it repeats) is the one to ask, and without one the change goes no further.
- if (this.foreignToInFlight(inFlight, { kind: 'reaction', chatId: event.chatId })) needsRow = true;
- else (inFlight.reactions ??= {})[event.senderId] = event.reaction ?? '';
- }
- this.mutationProjector.applyReactionQueued(id, event, needsRow);
+ void this.changeInFlight(id, event.messageId, { kind: 'reaction', chatId: event.chatId }, (needsRow, entry) => {
+ if (entry && !needsRow) (entry.reactions ??= {})[event.senderId] = event.reaction ?? '';
+ this.mutationProjector.applyReactionQueued(id, event, needsRow);
+ });
}
- /** Edit apply, queued on the per-message mutation chain — see MessageMutationProjector. */
+ /** Edit apply, queued on the per-message mutation chain. */
applyMessageEditQueued(id: string, message: EditedMessage): void {
- const inFlight = this.inboundInFlight.get(`${id}:${message.messageId}`);
- let needsRow = false;
- if (inFlight) {
- // See applyReactionQueued: judged foreign, it is not kept for the row, and a stored row decides.
- const source = { kind: 'edit', chatId: message.chatId, fromMe: message.fromMe, author: message.author } as const;
- if (this.foreignToInFlight(inFlight, source)) needsRow = true;
- else this.holdEdit(inFlight, message.body);
- }
- this.mutationProjector.applyMessageEditQueued(id, message, needsRow);
+ const source = { kind: 'edit', chatId: message.chatId, fromMe: message.fromMe, author: message.author } as const;
+ void this.changeInFlight(id, message.messageId, source, (needsRow, entry) => {
+ if (entry && !needsRow) this.holdEdit(entry, message.body);
+ this.mutationProjector.applyMessageEditQueued(id, message, needsRow);
+ });
}
/**
- * Whether a change names a message of another chat, or one it may not change, judged against the
- * message still waiting for its row. Recording it for the row would carry it into `message.received`
- * and the insert, past the check the row's own update applies.
+ * Keep changes in arrival order while a cross-form identity waits for a reported directory pairing.
+ * This chain only prepares changes; it never waits for a row write or for the message's commit.
+ * Exact identities retain their synchronous path until a preceding change needs that lookup.
*/
- private foreignToInFlight(inFlight: InFlightEntry, source: MutationSource): boolean {
- if (!inFlight.ref || !source.chatId) return false;
- const foreign = mutationTargetsForeignRow(inFlight.ref, source);
- if (foreign) {
- this.logger.warn('Not keeping a change aimed at a message of another chat or sender', {
- reason: foreign,
- kind: source.kind,
- });
+ private changeInFlight(
+ id: string,
+ messageId: string,
+ source: MutationSource | undefined,
+ ready: (needsRow: boolean, entry?: InFlightEntry) => void,
+ ): void | Promise<void> {
+ const key = `${id}:${messageId}`;
+ const entry = this.inboundInFlight.get(key);
+ const foreign = entry?.ref && source?.chatId ? mutationTargetsForeignRow(entry.ref, source) : null;
+ if (!entry?.changes?.pending && (!foreign || !this.lidMappingStore)) {
+ ready(foreign !== null, entry);
+ return;
}
- return foreign !== null;
+ const changes = (entry!.changes ??= {});
+ const ref = entry!.ref;
+ const engine = this.engines.get(id);
+ const pending = (changes.pending ?? Promise.resolve())
+ .then(async () => {
+ if (this.engines.get(id) !== engine) return;
+ const current = this.inboundInFlight.get(key);
+ if (current?.changes !== changes || current.ref !== ref) return;
+ const reason =
+ current.ref && source?.chatId
+ ? await mutationTargetsForeignRowPersisted(
+ current.ref,
+ source,
+ this.lidMappingStore ? jid => this.lidMappingStore!.findPhoneForLid(jid) : undefined,
+ )
+ : null;
+ // A repeated delivery may replace the entry while the lookup awaits; only its shared identity
+ // and change chain may inherit the result. A new engine must never inherit an old callback.
+ const target = this.inboundInFlight.get(key);
+ if (this.engines.get(id) !== engine || target?.changes !== changes || target.ref !== ref) return;
+ ready(reason !== null, target);
+ })
+ .catch(err => {
+ this.logger.warn('Unable to prepare a change for an arriving message', { error: String(err) });
+ });
+ changes.pending = pending;
+ void pending.finally(() => {
+ if (changes.pending === pending) delete changes.pending;
+ });
+ return pending;
+ }
+
+ /** Drain only identity checks already queued for this message, including changes arriving during a check. */
+ private waitForInFlightChanges(id: string, messageId: string): Promise<void> | undefined {
+ const key = `${id}:${messageId}`;
+ if (!this.inboundInFlight.get(key)?.changes?.pending) return;
+ return (async () => {
+ let pending: Promise<void> | undefined;
+ while ((pending = this.inboundInFlight.get(key)?.changes?.pending)) await pending;
+ })();
}
/** Queue a message-scoped mutation. A failed operation is isolated so later events still run. */
@@ -1583,15 +1704,15 @@ export class MessageProjector {
body: string,
source?: MutationSource,
): Promise<void> {
- // With a `source`, the message still arriving takes the edit only if it agrees with it, and the row
- // only if it is not foreign to it, as for recordRevoke.
- const inFlight = this.inboundInFlight.get(`${sessionId}:${messageId}`);
- if (inFlight && !(source && this.foreignToInFlight(inFlight, source))) {
- this.holdEdit(inFlight, body);
- // Asked for by the caller, and marked as the stored row is: the text it carries does not matter.
- inFlight.edited = true;
- }
- return this.mutationProjector.recordOutboundMessageEdit(sessionId, messageId, body, source);
+ let stored: Promise<void> | undefined;
+ const pending = this.changeInFlight(sessionId, messageId, source, (needsRow, entry) => {
+ if (entry && !needsRow) {
+ this.holdEdit(entry, body);
+ entry.edited = true;
+ }
+ stored = this.mutationProjector.recordOutboundMessageEdit(sessionId, messageId, body, source);
+ });
+ return Promise.resolve(pending).then(() => stored);
}
/**
diff --git a/src/modules/session/message-projector.tombstone-identity.spec.ts b/src/modules/session/message-projector.tombstone-identity.spec.ts
new file mode 100644
index 000000000..982189408
--- /dev/null
+++ b/src/modules/session/message-projector.tombstone-identity.spec.ts
@@ -0,0 +1,812 @@
+import { DataSource, type Repository } from 'typeorm';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { LidMapping } from '../../engine/identity/lid-mapping.entity';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import type { IncomingMessage, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { HookManager } from '../../core/hooks';
+import type { EventsGateway } from '../events/events.gateway';
+import { Message, MessageDirection } from '../message/entities/message.entity';
+import type { WebhookService } from '../webhook/webhook.service';
+import type { StatusStoreService } from '../status-store/status-store.service';
+import { MessageProjector } from './message-projector.service';
+import type { SessionLidResolver } from './session-lid-resolver.service';
+import type { Session } from './entities/session.entity';
+import { deferred } from './inbound-room';
+
+const LID = '484848@lid';
+const PHONE = '[email protected]';
+const SELF = '[email protected]';
+const flush = async (): Promise<void> => {
+ for (let n = 0; n < 10; n++) await new Promise(resolve => setImmediate(resolve));
+};
+const incoming = (id: string, chatId: string, fromMe = false): IncomingMessage => ({
+ id,
+ chatId,
+ from: fromMe ? SELF : chatId,
+ to: fromMe ? chatId : SELF,
+ fromMe,
+ body: 'content',
+ type: 'text',
+ timestamp: 1_700_000_000,
+ isGroup: false,
+ kind: 'individual',
+});
+
+describe('reported identities before a tombstone delivery reaches its hooks', () => {
+ let db: DataSource;
+ let repository: Repository<Message>;
+ let mappings: LidMappingStoreService;
+ let engines: EngineRegistry;
+ let engine: IWhatsAppEngine;
+ let projector: MessageProjector;
+ let hooked: IncomingMessage[];
+ let sent: IncomingMessage[];
+ let dispatched: IncomingMessage[];
+ let emitted: IncomingMessage[];
+ let persisted: Message[];
+ let mediaConcurrency: string | undefined;
+ let hookGate: Promise<void> | undefined;
+ let hookAction:
+ ((data: IncomingMessage, accept?: (data: IncomingMessage) => boolean) => Promise<IncomingMessage>) | undefined;
+
+ beforeEach(async () => {
+ mediaConcurrency = process.env.INBOUND_MEDIA_CONCURRENCY;
+ db = await new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message, LidMapping],
+ synchronize: true,
+ }).initialize();
+ repository = db.getRepository(Message);
+ mappings = new LidMappingStoreService(db.getRepository(LidMapping));
+ engines = new EngineRegistry();
+ engine = {} as IWhatsAppEngine;
+ engines.set('s1', engine);
+ hooked = [];
+ sent = [];
+ dispatched = [];
+ emitted = [];
+ persisted = [];
+ hookGate = undefined;
+ hookAction = undefined;
+ projector = new MessageProjector(
+ repository,
+ { update: jest.fn().mockResolvedValue({ affected: 1 }) } as unknown as Repository<Session>,
+ engines,
+ new Proxy(
+ {},
+ {
+ get: (_target, key) =>
+ jest.fn((_session: string, data: IncomingMessage) => {
+ if (key === 'emitMessage' || key === 'emitMessageSent') emitted.push({ ...data });
+ }),
+ },
+ ) as unknown as EventsGateway,
+ {
+ dispatch: jest.fn((_session: string, event: string, data: IncomingMessage) => {
+ if (event === 'message.sent') sent.push({ ...data });
+ if (event === 'message.sent' || event === 'message.received') dispatched.push({ ...data });
+ return Promise.resolve();
+ }),
+ } as unknown as WebhookService,
+ {
+ execute: jest.fn(
+ async (event: string, data: IncomingMessage, options?: { accept?: (data: IncomingMessage) => boolean }) => {
+ if (event === 'message:persisted')
+ persisted.push(JSON.parse(JSON.stringify((data as unknown as { message: Message }).message)) as Message);
+ if (event === 'message:received' || event === 'message:sent') {
+ hooked.push({ ...data });
+ if (data.id === 'block') await hookGate;
+ if (hookAction) data = await hookAction(data, options?.accept);
+ }
+ return { continue: true, data };
+ },
+ ),
+ } as unknown as HookManager,
+ {} as StatusStoreService,
+ { resolveSenderPhone: jest.fn().mockResolvedValue(null) } as unknown as SessionLidResolver,
+ undefined,
+ undefined,
+ undefined,
+ mappings,
+ );
+ });
+
+ afterEach(async () => {
+ await db.destroy();
+ if (mediaConcurrency === undefined) delete process.env.INBOUND_MEDIA_CONCURRENCY;
+ else process.env.INBOUND_MEDIA_CONCURRENCY = mediaConcurrency;
+ });
+
+ const remember = async (origin: string): Promise<void> => {
+ if (origin === 'reported') await mappings.remember('484848', '628111', 's1');
+ if (origin === 'unreported') {
+ await mappings.rememberIfUnknown('484848', '628111', 's1');
+ await mappings.reload();
+ }
+ };
+ const tombstone = (chatId: string, fromMe: boolean): Promise<unknown> =>
+ repository.insert({
+ sessionId: 's1',
+ waMessageId: 'A',
+ chatId,
+ from: fromMe ? SELF : chatId,
+ to: fromMe ? chatId : SELF,
+ direction: fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,
+ body: '',
+ type: 'revoked',
+ timestamp: 1_700_000_000,
+ });
+ const deliver = (message: IncomingMessage): void => {
+ if (message.fromMe) projector.handleOwnSendEcho('s1', engine, message);
+ else projector.handleInboundMessage('s1', engine, message);
+ };
+
+ it.each(
+ ['reported', 'unreported', 'unknown'].flatMap(origin =>
+ [false, true].flatMap(reverse => [false, true].map(own => [origin, reverse, own] as const)),
+ ),
+ )('checks a durable tombstone through %s identity, reverse=%s own=%s', async (origin, reverse, own) => {
+ await remember(origin);
+ await tombstone(reverse ? LID : PHONE, own);
+ deliver(incoming('A', reverse ? PHONE : LID, own));
+ await flush();
+
+ expect(hooked).toEqual([
+ expect.objectContaining({
+ body: origin === 'reported' ? '' : 'content',
+ type: origin === 'reported' ? 'revoked' : 'text',
+ }),
+ ]);
+ expect(await repository.findOneByOrFail({ waMessageId: 'A' })).toEqual(
+ expect.objectContaining({ body: '', type: 'revoked', metadata: null }),
+ );
+ });
+
+ it.each([false, true])('takes an earlier own delivery back through a reported pair, reverse=%s', async reverse => {
+ await remember('reported');
+ const blocked = deferred<void>();
+ hookGate = blocked.promise;
+ const firstChat = reverse ? LID : PHONE;
+ deliver(incoming('block', firstChat));
+ deliver(incoming('A', firstChat, true));
+ await flush();
+ expect(hooked.some(message => message.id === 'A')).toBe(true);
+ await tombstone(firstChat, true);
+ deliver(incoming('A', reverse ? PHONE : LID, true));
+ await flush();
+ blocked.resolve();
+ await flush();
+
+ expect(sent).toHaveLength(2);
+ for (const message of sent) expect(message).toEqual(expect.objectContaining({ body: '', type: 'revoked' }));
+ });
+
+ it.each(['unknown', 'unreported'].flatMap(origin => [false, true].map(reverse => [origin, reverse] as const)))(
+ 'keeps an earlier own delivery separate from a deleted %s identity, reverse=%s',
+ async (origin, reverse) => {
+ await remember(origin);
+ const firstChat = reverse ? LID : PHONE;
+ const firstHook = deferred<void>();
+ hookAction = async data => {
+ if (data.chatId === firstChat) await firstHook.promise;
+ return data;
+ };
+ deliver(incoming('A', firstChat, true));
+ await flush();
+ await repository.insert({
+ sessionId: 's1',
+ waMessageId: 'A',
+ chatId: firstChat,
+ from: SELF,
+ to: firstChat,
+ direction: MessageDirection.OUTGOING,
+ body: 'content',
+ type: 'text',
+ timestamp: 1_700_000_000,
+ });
+ deliver({ ...incoming('A', reverse ? PHONE : LID, true), type: 'revoked' });
+ await flush();
+ const quote = projector.inFlightInbound('s1', 'A');
+ firstHook.resolve();
+ await flush();
+
+ expect(quote).toEqual({ chatId: firstChat, body: 'content' });
+ expect(sent.find(message => message.chatId === firstChat)).toEqual(
+ expect.objectContaining({ body: 'content', type: 'text' }),
+ );
+ expect(await repository.findOneByOrFail({ waMessageId: 'A' })).toEqual(
+ expect.objectContaining({ body: 'content', type: 'text' }),
+ );
+ },
+ );
+
+ it.each([false, true])('lends no quote and runs no retired hook during a reported lookup, own=%s', async own => {
+ await remember('reported');
+ await tombstone(PHONE, own);
+ const lookup = deferred<void>();
+ const findPhone = mappings.findPhoneForLid.bind(mappings);
+ jest.spyOn(mappings, 'findPhoneForLid').mockImplementation(async jid => {
+ await lookup.promise;
+ return findPhone(jid);
+ });
+ deliver(incoming('A', LID, own));
+ await flush();
+ const quoteWhileChecking = projector.inFlightInbound('s1', 'A');
+ engines.delete('s1');
+ lookup.resolve();
+ await flush();
+
+ expect(quoteWhileChecking).toBeUndefined();
+ expect(hooked).toEqual([]);
+ expect(sent).toEqual([]);
+ });
+
+ it.each(
+ ['reported', 'unknown', 'unreported'].flatMap(origin =>
+ ['edit', 'revoke'].flatMap(change =>
+ [false, true].flatMap(own => [false, true].map(admitted => [origin, change, own, admitted] as const)),
+ ),
+ ),
+ )(
+ 'keeps the winning row and consumers within %s identity after %s, own=%s admitted=%s',
+ async (origin, change, own, admitted) => {
+ await remember(origin);
+ const firstHook = deferred<void>();
+ hookAction = async data => {
+ if (data.chatId === PHONE) await firstHook.promise;
+ return data;
+ };
+ const send = (message: IncomingMessage) => {
+ const ticket = admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: message.chatId,
+ fromMe: own,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ if (own) projector.handleOwnSendEcho('s1', engine, message, ticket);
+ else projector.handleInboundMessage('s1', engine, message, ticket);
+ };
+ send({ ...incoming('A', PHONE, own), body: 'first content' });
+ await flush();
+ if (change === 'edit') {
+ projector.applyMessageEditQueued('s1', {
+ messageId: 'A',
+ chatId: PHONE,
+ fromMe: own,
+ body: 'edited first',
+ } as never);
+ } else {
+ projector.handleMessageRevoked('s1', engine, { id: 'A', revokedId: 'A', chatId: PHONE } as never, {
+ fromMe: own,
+ });
+ }
+ await flush();
+ send({ ...incoming('A', LID, own), body: 'later content' });
+ await flush();
+ const inserted = await repository.findOneByOrFail({ waMessageId: 'A' });
+ const persistedWinner = persisted.filter(message => message.chatId === LID);
+ const webhookWinner = dispatched.filter(message => message.chatId === LID);
+ const socketWinner = emitted.filter(message => message.chatId === LID);
+ firstHook.resolve();
+ await flush();
+ const final = await repository.findOneByOrFail({ waMessageId: 'A' });
+ const accepted = origin === 'reported';
+ const body = accepted ? (change === 'edit' ? 'edited first' : '') : 'later content';
+ const type = accepted && change === 'revoke' ? 'revoked' : 'text';
+ const expected = { body, type };
+
+ const expectedDispatch = accepted && change === 'revoke' ? [] : [expect.objectContaining(expected)];
+ const expectedRow: unknown = expect.objectContaining({ ...expected, chatId: LID });
+ expect({ inserted, final, persistedWinner, webhookWinner, socketWinner }).toEqual({
+ inserted: expectedRow,
+ final: expectedRow,
+ persistedWinner: [expect.objectContaining(expected)],
+ webhookWinner: expectedDispatch,
+ socketWinner: expectedDispatch,
+ });
+ expect(final.metadata?.edited).toBe(accepted && change === 'edit' ? true : undefined);
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ },
+ );
+
+ it.each(
+ ['reported', 'unknown', 'unreported'].flatMap(origin =>
+ [false, true].flatMap(own => [false, true].map(admitted => [origin, own, admitted] as const)),
+ ),
+ )('records arrival bookkeeping only within %s identity, own=%s admitted=%s', async (origin, own, admitted) => {
+ await remember(origin);
+ const hooks = deferred<void>();
+ hookAction = async data => {
+ await hooks.promise;
+ return data;
+ };
+ const send = (message: IncomingMessage) => {
+ const ticket = admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: message.chatId,
+ fromMe: own,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ if (own) projector.handleOwnSendEcho('s1', engine, message, ticket);
+ else projector.handleInboundMessage('s1', engine, message, ticket);
+ };
+ send({ ...incoming('A', PHONE, own), body: 'first content' });
+ await flush();
+ send({ ...incoming('A', LID, own), body: 'later content', originalBody: 'earlier later content' });
+ await flush();
+ const entry = (
+ projector as unknown as { inboundInFlight: Map<string, { body?: string; edited?: boolean }> }
+ ).inboundInFlight.get('s1:A');
+ const recorded = { body: entry?.body, edited: entry?.edited };
+ hooks.resolve();
+ await flush();
+
+ expect(recorded).toEqual(
+ origin === 'reported'
+ ? { body: 'earlier later content', edited: true }
+ : { body: 'first content', edited: undefined },
+ );
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ });
+
+ it.each(
+ ['unknown', 'unreported'].flatMap(origin =>
+ ['edit', 'revoke'].flatMap(change => [false, true].map(own => [origin, change, own] as const)),
+ ),
+ )('does not lend a held %s identity its earlier %s, own=%s', async (origin, change, own) => {
+ await remember(origin);
+ const firstHook = deferred<void>();
+ hookAction = async data => {
+ if (data.chatId === PHONE) await firstHook.promise;
+ return data;
+ };
+ const ticket = (chatId: string) =>
+ projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId,
+ fromMe: own,
+ needsRoom: false,
+ status: false,
+ });
+ const first = incoming('A', PHONE, own);
+ if (own) projector.handleOwnSendEcho('s1', engine, first, ticket(PHONE));
+ else projector.handleInboundMessage('s1', engine, first, ticket(PHONE));
+ await flush();
+ if (change === 'edit') {
+ projector.applyMessageEditQueued('s1', {
+ messageId: 'A',
+ chatId: PHONE,
+ fromMe: own,
+ body: 'edited first',
+ } as never);
+ } else {
+ projector.handleMessageRevoked('s1', engine, { id: 'A', revokedId: 'A', chatId: PHONE } as never, {
+ fromMe: own,
+ });
+ }
+ await flush();
+ const later = { ...incoming('A', LID, own), body: 'separate content' };
+ if (own) projector.handleOwnSendEcho('s1', engine, later, ticket(LID));
+ else projector.handleInboundMessage('s1', engine, later, ticket(LID));
+ await flush();
+ const laterHook = hooked.find(message => message.chatId === LID);
+ firstHook.resolve();
+ await flush();
+
+ expect(laterHook).toEqual(expect.objectContaining({ body: 'separate content', type: 'text' }));
+ });
+
+ it.each([false, true].flatMap(own => [false, true].map(admitted => [own, admitted] as const)))(
+ 'releases both holders after a foreign hook fails, own=%s admitted=%s',
+ async (own, admitted) => {
+ const firstHook = deferred<void>();
+ hookAction = async data => {
+ if (data.chatId === PHONE) await firstHook.promise;
+ else throw new Error('hook unavailable');
+ return data;
+ };
+ const send = (chatId: string) => {
+ const ticket = admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId,
+ fromMe: own,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ if (own) projector.handleOwnSendEcho('s1', engine, incoming('A', chatId, own), ticket);
+ else projector.handleInboundMessage('s1', engine, incoming('A', chatId, own), ticket);
+ };
+ send(PHONE);
+ await flush();
+ send(LID);
+ await flush();
+ firstHook.resolve();
+ await flush();
+
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ expect(await repository.findOneByOrFail({ waMessageId: 'A' })).toEqual(
+ expect.objectContaining({ chatId: PHONE, body: 'content' }),
+ );
+ },
+ );
+
+ it.each(
+ ['reported', 'unknown', 'unreported'].flatMap(origin =>
+ ['before-reserve', 'while-waiting'].flatMap(timing => [false, true].map(own => [origin, timing, own] as const)),
+ ),
+ )('reserves media only within %s identity after revoke %s, own=%s', async (origin, timing, own) => {
+ process.env.INBOUND_MEDIA_CONCURRENCY = '1';
+ await remember(origin);
+ const firstHook = deferred<void>();
+ hookAction = async data => {
+ if (data.chatId === PHONE) await firstHook.promise;
+ return data;
+ };
+ const admit = (id: string, chatId: string, needsRoom: boolean) =>
+ projector.admitInbound('s1', engine, {
+ id,
+ chatId,
+ fromMe: own,
+ needsRoom,
+ status: false,
+ })!;
+ const first = admit('A', PHONE, false);
+ if (own) projector.handleOwnSendEcho('s1', engine, incoming('A', PHONE, own), first);
+ else projector.handleInboundMessage('s1', engine, incoming('A', PHONE, own), first);
+ await flush();
+ const blocker = admit('blocker', '[email protected]', true);
+ expect(await blocker.reserve()).toBe(true);
+ const revoke = () =>
+ projector.handleMessageRevoked(
+ 's1',
+ engine,
+ {
+ id: 'A',
+ revokedId: 'A',
+ chatId: PHONE,
+ } as never,
+ { fromMe: own },
+ );
+ if (timing === 'before-reserve') {
+ revoke();
+ await flush();
+ }
+ const later = admit('A', LID, true);
+ let reservation: boolean | undefined;
+ const reserved = Promise.resolve(later.reserve()).then(value => (reservation = value));
+ await flush();
+ if (timing === 'while-waiting') {
+ revoke();
+ await flush();
+ }
+ const beforeRelease = reservation;
+ blocker.drop();
+ const granted = await reserved;
+ const beforeEmit = { revoked: later.revoked, state: (later as unknown as { state: string }).state };
+ const message: IncomingMessage = {
+ ...incoming('A', LID, own),
+ body: 'later content',
+ type: 'image',
+ ...(granted ? { media: { mimetype: 'image/png', data: 'eA==' } } : {}),
+ };
+ if (own) projector.handleOwnSendEcho('s1', engine, message, later);
+ else projector.handleInboundMessage('s1', engine, message, later);
+ await flush();
+ const row = await repository.findOneByOrFail({ waMessageId: 'A' });
+ const afterEmit = (later as unknown as { state: string }).state;
+ firstHook.resolve();
+ await flush();
+ const accepted = origin === 'reported';
+
+ expect({ beforeRelease, granted, beforeEmit, afterEmit }).toEqual({
+ beforeRelease: accepted ? false : undefined,
+ granted: !accepted,
+ beforeEmit: { revoked: accepted, state: 'pending' },
+ afterEmit: 'emitted',
+ });
+ expect(row).toEqual(
+ expect.objectContaining({
+ chatId: LID,
+ body: accepted ? '' : 'later content',
+ type: accepted ? 'revoked' : 'image',
+ }),
+ );
+ expect(dispatched.filter(message => message.chatId === LID)).toEqual(
+ accepted
+ ? []
+ : [expect.objectContaining({ body: 'later content', media: { mimetype: 'image/png', data: 'eA==' } })],
+ );
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ expect((projector as unknown as { tickets: Map<string, unknown> }).tickets.size).toBe(0);
+ });
+
+ it.each(['reported', 'unknown', 'unreported'])(
+ 'resolves admission identity before media takes a revoke queued during the lookup, origin=%s',
+ async origin => {
+ await remember(origin);
+ const firstHook = deferred<void>();
+ const lookup = deferred<void>();
+ hookAction = async data => {
+ await firstHook.promise;
+ return data;
+ };
+ const first = projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: PHONE,
+ fromMe: false,
+ needsRoom: false,
+ status: false,
+ })!;
+ projector.handleInboundMessage('s1', engine, incoming('A', PHONE), first);
+ await flush();
+ const findPhone = mappings.findPhoneForLid.bind(mappings);
+ jest.spyOn(mappings, 'findPhoneForLid').mockImplementation(async jid => {
+ await lookup.promise;
+ return findPhone(jid);
+ });
+ const later = projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: LID,
+ fromMe: false,
+ needsRoom: true,
+ status: false,
+ })!;
+ let result: boolean | undefined;
+ const reservation = Promise.resolve(later.reserve()).then(value => (result = value));
+ await flush();
+ const beforeLookup = result;
+ projector.handleMessageRevoked('s1', engine, { id: 'A', revokedId: 'A', chatId: PHONE } as never, {
+ fromMe: false,
+ });
+ lookup.resolve();
+ const granted = await reservation;
+ later.drop();
+ firstHook.resolve();
+ await flush();
+
+ expect(beforeLookup).toBeUndefined();
+ expect(granted).toBe(origin !== 'reported');
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ },
+ );
+
+ it.each(['drop', 'retire'])(
+ 'releases a reservation before its directory lookup finishes after %s',
+ async cancellation => {
+ const firstHook = deferred<void>();
+ const lookup = deferred<void>();
+ hookAction = async data => {
+ await firstHook.promise;
+ return data;
+ };
+ const first = projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: PHONE,
+ fromMe: false,
+ needsRoom: false,
+ status: false,
+ })!;
+ projector.handleInboundMessage('s1', engine, incoming('A', PHONE), first);
+ await flush();
+ jest.spyOn(mappings, 'findPhoneForLid').mockImplementation(async () => {
+ await lookup.promise;
+ return null;
+ });
+ const later = projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: LID,
+ fromMe: false,
+ needsRoom: true,
+ status: false,
+ })!;
+ let result: boolean | undefined;
+ const reservation = Promise.resolve(later.reserve()).then(value => (result = value));
+ await flush();
+ if (cancellation === 'retire') engines.delete('s1');
+ else later.drop();
+ await flush();
+ const beforeLookup = result;
+ lookup.resolve();
+ firstHook.resolve();
+ await reservation;
+ await flush();
+
+ expect(beforeLookup).toBe(false);
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ expect((projector as unknown as { tickets: Map<string, unknown> }).tickets.size).toBe(0);
+ },
+ );
+
+ it.each([false, true].flatMap(own => [false, true].map(admitted => [own, admitted] as const)))(
+ 'releases both holders when the engine retires during foreign preparation, own=%s admitted=%s',
+ async (own, admitted) => {
+ const firstHook = deferred<void>();
+ const lookup = deferred<void>();
+ hookAction = async data => {
+ await firstHook.promise;
+ return data;
+ };
+ jest.spyOn(mappings, 'findPhoneForLid').mockImplementation(async () => {
+ await lookup.promise;
+ return null;
+ });
+ const send = (chatId: string) => {
+ const ticket = admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId,
+ fromMe: own,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ if (own) projector.handleOwnSendEcho('s1', engine, incoming('A', chatId, own), ticket);
+ else projector.handleInboundMessage('s1', engine, incoming('A', chatId, own), ticket);
+ };
+ send(PHONE);
+ await flush();
+ send(LID);
+ await flush();
+ engines.delete('s1');
+ lookup.resolve();
+ firstHook.resolve();
+ await flush();
+
+ expect((projector as unknown as { inboundInFlight: Map<string, unknown> }).inboundInFlight.size).toBe(0);
+ expect(await repository.count()).toBe(0);
+ expect(persisted).toEqual([]);
+ expect(dispatched).toEqual([]);
+ expect(emitted).toEqual([]);
+ },
+ );
+
+ it.each([false, true])(
+ 'forgets a completed quote while a repeat is still being checked, admitted=%s',
+ async admitted => {
+ const firstHook = deferred<void>();
+ const laterRead = deferred<void>();
+ const findOne = repository.findOne.bind(repository);
+ let reads = 0;
+ jest.spyOn(repository, 'findOne').mockImplementation(async options => {
+ const row = await findOne(options);
+ if ((options.where as { type?: string }).type === 'revoked' && ++reads === 2) await laterRead.promise;
+ return row;
+ });
+ let calls = 0;
+ hookAction = async data => {
+ if (++calls === 1) await firstHook.promise;
+ return data;
+ };
+ const ticket = () =>
+ admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: PHONE,
+ fromMe: false,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ const first = projector.handleInboundMessage(
+ 's1',
+ engine,
+ { ...incoming('A', PHONE), body: 'earlier' },
+ ticket(),
+ );
+ await flush();
+ const later = projector.handleInboundMessage('s1', engine, { ...incoming('A', PHONE), body: 'later' }, ticket());
+ await flush();
+ firstHook.resolve();
+ await first?.settled;
+ await flush();
+ const whileChecking = projector.inFlightInbound('s1', 'A');
+ laterRead.resolve();
+ await later?.settled;
+ await flush();
+
+ expect(whileChecking).toBeUndefined();
+ },
+ );
+
+ it.each([false, true])('keeps a later active quote when the earlier hook finishes, admitted=%s', async admitted => {
+ const firstHook = deferred<void>();
+ const laterHook = deferred<void>();
+ let calls = 0;
+ hookAction = async (data, accept) => {
+ if (++calls === 1) {
+ await firstHook.promise;
+ const rewritten = { ...data, body: 'earlier rewrite' };
+ accept?.(rewritten);
+ return rewritten;
+ }
+ await laterHook.promise;
+ return data;
+ };
+ const ticket = () =>
+ admitted
+ ? projector.admitInbound('s1', engine, {
+ id: 'A',
+ chatId: PHONE,
+ fromMe: false,
+ needsRoom: false,
+ status: false,
+ })
+ : undefined;
+ const first = projector.handleInboundMessage('s1', engine, { ...incoming('A', PHONE), body: 'earlier' }, ticket());
+ await flush();
+ const later = projector.handleInboundMessage('s1', engine, { ...incoming('A', PHONE), body: 'later' }, ticket());
+ await flush();
+ firstHook.resolve();
+ await first?.settled;
+ await flush();
+ const whileLaterRuns = projector.inFlightInbound('s1', 'A');
+ laterHook.resolve();
+ await later?.settled;
+ await flush();
+
+ expect(whileLaterRuns).toEqual({ chatId: PHONE, body: 'later' });
+ });
+
+ it.each(['edit', 'revoke'] as const)(
+ 'prepares a %s arriving during the stored-row read before running the hook',
+ async change => {
+ await remember('reported');
+ const read = deferred<void>();
+ const lookup = deferred<void>();
+ const findOne = repository.findOne.bind(repository);
+ jest.spyOn(repository, 'findOne').mockImplementation(async options => {
+ const row = await findOne(options);
+ if ((options.where as { type?: string }).type === 'revoked') await read.promise;
+ return row;
+ });
+ const findPhone = mappings.findPhoneForLid.bind(mappings);
+ jest.spyOn(mappings, 'findPhoneForLid').mockImplementation(async jid => {
+ await lookup.promise;
+ return findPhone(jid);
+ });
+ deliver(incoming('A', LID));
+ await flush();
+ if (change === 'edit') {
+ projector.applyMessageEditQueued('s1', {
+ messageId: 'A',
+ chatId: PHONE,
+ fromMe: false,
+ body: 'first',
+ } as never);
+ projector.applyMessageEditQueued('s1', { messageId: 'A', chatId: LID, fromMe: false, body: 'latest' } as never);
+ } else {
+ projector.handleMessageRevoked('s1', engine, { id: 'A', revokedId: 'A', chatId: PHONE } as never, {
+ fromMe: false,
+ });
+ }
+ read.resolve();
+ await flush();
+ const hooksBeforeValidation = hooked.length;
+ lookup.resolve();
+ await flush();
+
+ expect(hooksBeforeValidation).toBe(0);
+ expect(hooked).toEqual([
+ expect.objectContaining({
+ body: change === 'edit' ? 'latest' : '',
+ type: change === 'edit' ? 'text' : 'revoked',
+ }),
+ ]);
+ expect(await repository.findOneByOrFail({ waMessageId: 'A' })).toEqual(
+ expect.objectContaining({
+ body: change === 'edit' ? 'latest' : '',
+ type: change === 'edit' ? 'text' : 'revoked',
+ }),
+ );
+ },
+ );
+});
diff --git a/src/modules/session/session-lid-resolver.service.spec.ts b/src/modules/session/session-lid-resolver.service.spec.ts
index 5223d4392..0bf7fa5b3 100644
--- a/src/modules/session/session-lid-resolver.service.spec.ts
+++ b/src/modules/session/session-lid-resolver.service.spec.ts
@@ -260,12 +260,15 @@ describe('SessionLidResolver', () => {
}
});
- it('is the only answer looked up again: a cached phone stays', async () => {
- await resolver.resolveSenderPhone('s1', '111@lid');
- clock += 3_600_000;
+ it('looks a cached phone up again after five minutes', async () => {
await resolver.resolveSenderPhone('s1', '111@lid');
+ resolveContactPhone.mockResolvedValue('628222');
+ clock += 299_999;
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628111222333');
+ clock += 1;
- expect(resolveContactPhone).toHaveBeenCalledTimes(1);
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628222');
+ expect(remember).toHaveBeenLastCalledWith('111', '628222', 's1');
});
it('forgets when to look it up again along with its cached answer', async () => {
@@ -279,6 +282,66 @@ describe('SessionLidResolver', () => {
});
});
+ describe('a replacement engine', () => {
+ it('keeps its cached answer when an earlier engine report of the same phone fails', async () => {
+ let failReport!: () => void;
+ remember.mockImplementationOnce(() => new Promise<boolean>(resolve => (failReport = () => resolve(false))));
+ await resolver.resolveSenderPhone('s1', '111@lid');
+ const replacement = jest.fn().mockResolvedValue('628111222333');
+ engines.set('s1', { resolveContactPhone: replacement } as unknown as IWhatsAppEngine);
+ await resolver.resolveSenderPhone('s1', '111@lid');
+
+ failReport();
+ await settle();
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628111222333');
+
+ expect(replacement).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not inherit the earlier engine cache or its unmapped retry hold', async () => {
+ await resolver.resolveSenderPhone('s1', '111@lid');
+ resolveContactPhone.mockRejectedValueOnce(new LidNotMappedError('404@lid'));
+ await resolver.resolveSenderPhone('s1', '404@lid');
+ engines.delete('s1');
+ engines.set('s1', { resolveContactPhone: () => Promise.resolve(null) } as unknown as IWhatsAppEngine);
+
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBeNull();
+ await expect(resolver.resolveSenderPhone('s1', '404@lid')).resolves.toBeNull();
+ expect(remember).toHaveBeenLastCalledWith('404', null, 's1');
+ });
+
+ it.each(['phone', 'unmapped'] as const)(
+ 'ignores a retired lookup resolving as %s while its replacement is pending',
+ async answer => {
+ let finishOld!: () => void;
+ const oldGate = new Promise<void>(resolve => (finishOld = resolve));
+ resolveContactPhone.mockImplementation(async () => {
+ await oldGate;
+ if (answer === 'unmapped') throw new LidNotMappedError('111@lid');
+ return '628111';
+ });
+ const oldLookup = resolver.resolveSenderPhone('s1', '111@lid');
+ let finishNew!: () => void;
+ const newGate = new Promise<void>(resolve => (finishNew = resolve));
+ const replacement = jest.fn(async () => {
+ await newGate;
+ return '628222';
+ });
+ engines.set('s1', { resolveContactPhone: replacement } as unknown as IWhatsAppEngine);
+ const first = resolver.resolveSenderPhone('s1', '111@lid');
+ finishOld();
+ await expect(oldLookup).resolves.toBeNull();
+ const second = resolver.resolveSenderPhone('s1', '111@lid');
+ finishNew();
+
+ await expect(Promise.all([first, second])).resolves.toEqual(['628222', '628222']);
+ expect(replacement).toHaveBeenCalledTimes(1);
+ expect(remember).toHaveBeenCalledTimes(1);
+ expect(remember).toHaveBeenCalledWith('111', '628222', 's1');
+ },
+ );
+ });
+
it('never rejects when the mapping store write fails (fire-and-forget)', async () => {
remember.mockRejectedValue(new Error('db down'));
@@ -324,6 +387,7 @@ describe('SessionLidResolver over the shared lid table', () => {
let repo: Repository<LidMapping>;
let store: LidMappingStoreService;
let resolver: SessionLidResolver;
+ let engines: EngineRegistry;
let warn: jest.SpyInstance;
let wallClock: jest.SpyInstance<number, []>;
/** The resolver's monotonic clock, in ms. */
@@ -354,7 +418,7 @@ describe('SessionLidResolver over the shared lid table', () => {
store = new LidMappingStoreService(repo);
warn = jest.spyOn((store as unknown as { logger: { warn: () => void } }).logger, 'warn');
await store.onModuleInit();
- const engines = new EngineRegistry();
+ engines = new EngineRegistry();
for (const session of [s1, s2]) {
answers[session] = P;
engines.set(session, {
@@ -421,4 +485,33 @@ describe('SessionLidResolver over the shared lid table', () => {
expect(await admitted(P)).toEqual([false, false]);
expect(warn).not.toHaveBeenCalled();
});
+
+ it('clears a newly learned number after its owner stops seeing it', async () => {
+ jest.spyOn(repo, 'upsert').mockRejectedValueOnce(new Error('connection lost'));
+ await message(s1);
+ warn.mockClear();
+ answers[s1] = Q;
+ await message(s1);
+ expect(await admitted(Q)).toEqual([true, true]);
+ answers[s1] = null;
+ answers[s2] = null;
+ await message(s2);
+ clock += 300_000;
+
+ await message(s1);
+
+ expect(await row()).toMatchObject({ phone: null, sessionId: s1 });
+ expect(await admitted(Q)).toEqual([false, false]);
+ });
+
+ it('uses the replacement account answer after its earlier engine retires', async () => {
+ await message(s1);
+ engines.delete(s1);
+ engines.set(s1, { resolveContactPhone: () => Promise.resolve(null) } as unknown as IWhatsAppEngine);
+
+ await message(s1);
+
+ expect(await row()).toMatchObject({ phone: null, sessionId: s1 });
+ expect(await admitted(P)).toEqual([false, false]);
+ });
});
diff --git a/src/modules/session/session-lid-resolver.service.ts b/src/modules/session/session-lid-resolver.service.ts
index 9ce0f1c81..6499e4f2f 100644
--- a/src/modules/session/session-lid-resolver.service.ts
+++ b/src/modules/session/session-lid-resolver.service.ts
@@ -1,5 +1,6 @@
import { Injectable, Optional } from '@nestjs/common';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { userPart } from '../../engine/identity/wa-id';
import { LidNotMappedError } from '../../common/errors/lid-not-mapped.error';
@@ -9,8 +10,8 @@ import { LidNotMappedError } from '../../common/errors/lid-not-mapped.error';
* messages (#263).
*
* Split out of SessionService because it is a self-contained read-through cache over the engine: it
- * has no lifecycle state, cannot fail the message path, and its only collaborators are the engine
- * registry and the shared lid<->phone table. Keeping it here means the eviction policy and the
+ * invalidates session entries when their engine retires and cannot fail the message path. Its only
+ * collaborators are the engine registry and the shared lid<->phone table. Keeping it here means the eviction policy and the
* fire-and-forget persistence are testable without standing up the whole session lifecycle.
*/
@Injectable()
@@ -32,12 +33,12 @@ export class SessionLidResolver {
/** Lookups under way, per key, so messages that arrive together from one sender share a single one. */
private readonly inFlight = new Map<string, Promise<string | null>>();
/**
- * When a cached negative is looked up again, per key, on {@link now}. The lid table refuses a negative while
- * another linked session owns the phone, and a cached answer is otherwise never reported again, so that
- * phone would stay mapped after its owner logged out. At most one lookup and one write per key per interval.
+ * When a cached answer is looked up again, per key, on {@link now}. A contact can change or hide its number,
+ * and the lid table can refuse a negative while another linked session owns the phone. At most one lookup
+ * and one write per key per interval.
*/
private readonly recheckAt = new Map<string, number>();
- private static readonly NEGATIVE_RECHECK_MS = 5 * 60_000;
+ private static readonly RECHECK_MS = 5 * 60_000;
/** Monotonic clock in ms, so a wall clock set back does not stretch a wait (a seam for tests). */
private readonly now = (): number => performance.now();
@@ -47,7 +48,13 @@ export class SessionLidResolver {
// an inbound-only migrated contact's `@lid` and `@c.us` rows bridge in the read-path (#583 R3 Ph2).
@Optional()
private readonly lidMappingStore?: LidMappingStoreService,
- ) {}
+ ) {
+ engines.onRetire(id => {
+ for (const map of [this.cache, this.retryAfter, this.inFlight, this.recheckAt]) {
+ for (const key of map.keys()) if (key.startsWith(`${id}:`)) map.delete(key);
+ }
+ });
+ }
/**
* Best-effort resolution, cached per session (incl. misses). Never throws — returns null on any
@@ -57,7 +64,7 @@ export class SessionLidResolver {
const key = `${sessionId}:${contactId}`;
const cached = this.cache.get(key);
if (cached !== undefined) {
- if (cached !== null || (this.recheckAt.get(key) ?? Infinity) > this.now()) return cached;
+ if ((this.recheckAt.get(key) ?? Infinity) > this.now()) return cached;
this.forget(key);
}
if ((this.retryAfter.get(key) ?? 0) > this.now()) {
@@ -67,7 +74,9 @@ export class SessionLidResolver {
// new sender, as a reconnect delivers, would otherwise start one engine lookup per message.
let lookup = this.inFlight.get(key);
if (!lookup) {
- lookup = this.lookup(sessionId, contactId, key).finally(() => this.inFlight.delete(key));
+ lookup = this.lookup(sessionId, contactId, key).finally(() => {
+ if (this.inFlight.get(key) === lookup) this.inFlight.delete(key);
+ });
this.inFlight.set(key, lookup);
}
return lookup;
@@ -76,13 +85,14 @@ export class SessionLidResolver {
/** One engine lookup for a sender, with its caching and persistence. */
private async lookup(sessionId: string, contactId: string, key: string): Promise<string | null> {
let phone: string | null;
+ const engine = this.engines.get(sessionId);
+ let failure: unknown;
// `resolved` marks a definitive engine answer: a rejection or a missing engine is a transient
// unknown, NOT "this contact has no phone", and must never overwrite a stored mapping (#1058).
// Engines reject rather than answer null when they cannot decide (a Baileys lid no cache, table
// or key store maps), so only a real "no phone" reaches the null write below.
let resolved = false;
try {
- const engine = this.engines.get(sessionId);
if (engine) {
phone = (await engine.resolveContactPhone(contactId)) ?? null;
resolved = true;
@@ -91,15 +101,17 @@ export class SessionLidResolver {
}
} catch (err) {
phone = null;
- // Only an unmapped lid waits: any other rejection (a dead page, a rate limit) is retried on the
- // sender's next message, since the engine may answer as soon as it recovers.
- if (err instanceof LidNotMappedError) {
- this.retryAfter.delete(key); // re-inserted at the newest end, so the FIFO bound drops the oldest
- if (this.retryAfter.size >= SessionLidResolver.CACHE_MAX) {
- this.retryAfter.delete(this.retryAfter.keys().next().value!);
- }
- this.retryAfter.set(key, this.now() + SessionLidResolver.RETRY_AFTER_MS);
+ failure = err;
+ }
+ if (engine && !this.engines.isLive(sessionId, engine)) return null;
+ // Only an unmapped lid waits: any other rejection (a dead page, a rate limit) is retried on the
+ // sender's next message, since the engine may answer as soon as it recovers.
+ if (failure instanceof LidNotMappedError) {
+ this.retryAfter.delete(key); // re-inserted at the newest end, so the FIFO bound drops the oldest
+ if (this.retryAfter.size >= SessionLidResolver.CACHE_MAX) {
+ this.retryAfter.delete(this.retryAfter.keys().next().value!);
}
+ this.retryAfter.set(key, this.now() + SessionLidResolver.RETRY_AFTER_MS);
}
// Only a definitive answer is cached: a transient null would otherwise stick for the process life.
if (resolved) {
@@ -112,7 +124,7 @@ export class SessionLidResolver {
}
}
this.cache.set(key, phone);
- if (phone === null) this.recheckAt.set(key, this.now() + SessionLidResolver.NEGATIVE_RECHECK_MS);
+ this.recheckAt.set(key, this.now() + SessionLidResolver.RECHECK_MS);
}
// Persist the resolution so the read-path can bridge this contact's `@lid` and `@c.us` rows even
// when the operator never sent to them (#583 R3 Phase 2). A definitive null is persisted too, so
@@ -120,21 +132,32 @@ export class SessionLidResolver {
// (#1058). Reuses the resolution above — no extra network call — and is fire-and-forget so
// dispatch never blocks/fails on it. The store keeps a phone another session stored, since that
// account may still see the number.
- if (phone || resolved) this.persist(key, sessionId, contactId, phone);
+ if (engine && (phone || resolved)) {
+ this.persist(key, sessionId, contactId, phone, engine);
+ }
return phone;
}
/**
- * Report an answer to the lid table. One the table did not take is dropped from the cache, so the sender's
+ * Report an answer to the lid table. One whose write failed is dropped from the cache, so the sender's
* next message is looked up again and reports what the engine answers then: replaying this answer could
* write it over a newer phone the table has learned since, and a negative that never lands would leave a
* number the contact hid mapped until a restart (#1058).
*/
- private persist(key: string, sessionId: string, contactId: string, phone: string | null): void {
- void this.lidMappingStore
- ?.remember(userPart(contactId), phone, sessionId)
+ private persist(
+ key: string,
+ sessionId: string,
+ contactId: string,
+ phone: string | null,
+ engine: IWhatsAppEngine,
+ ): void {
+ const stored =
+ phone && engine.contactPhoneLookupPersistence === 'seed'
+ ? this.lidMappingStore?.rememberIfUnknown(userPart(contactId), phone, sessionId)
+ : this.lidMappingStore?.remember(userPart(contactId), phone, sessionId);
+ void stored
?.then(stored => {
- if (stored === false) this.forget(key);
+ if (stored === false && this.engines.isLive(sessionId, engine)) this.forget(key);
})
.catch(() => {});
}
diff --git a/src/modules/webhook/filters/filter-evaluator.spec.ts b/src/modules/webhook/filters/filter-evaluator.spec.ts
index 93ca0e26f..38c00feb3 100644
--- a/src/modules/webhook/filters/filter-evaluator.spec.ts
+++ b/src/modules/webhook/filters/filter-evaluator.spec.ts
@@ -1,4 +1,4 @@
-import { evaluateFilters } from './filter-evaluator';
+import { evaluateFilters, prepareFilterLidResolver } from './filter-evaluator';
import { WebhookFilters } from './filter-types';
const msg = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
@@ -13,6 +13,63 @@ const msg = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
const filters = (...conditions: WebhookFilters['conditions']): WebhookFilters => ({ conditions });
+describe('prepareFilterLidResolver', () => {
+ it('batches and deduplicates both sides of registered identity conditions', async () => {
+ const f = filters(
+ { field: 'sender', operator: 'is', value: ['4:2@LID', '[email protected]'] },
+ { field: 'recipient', operator: 'isNot', value: ['4@lid'] },
+ { field: 'mentions', operator: 'is', value: ['4@lid'] },
+ { field: 'body', operator: 'contains', value: '5@lid' },
+ { field: 'unregistered', operator: 'is', value: ['6@lid'] },
+ );
+ const read = jest.fn().mockResolvedValue({ '1': '111', '2': '222', '3': '333', '4': '444' });
+ const resolve = await prepareFilterLidResolver(
+ [f, f],
+ 'message.received',
+ { author: '1:7@lid', from: '[email protected]', to: '2@lid', mentionedIds: ['3@lid', '[email protected]'] },
+ read,
+ );
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(read).toHaveBeenCalledWith(['1', '4', '2', '3']);
+ expect(resolve?.('1@lid')).toBe('111');
+ expect(resolve?.('9@lid')).toBeNull();
+ });
+
+ it('resolves a LID held only in the rule value when the payload uses a phone', async () => {
+ const f = filters({ field: 'sender', operator: 'is', value: ['1@lid'] });
+ const resolve = await prepareFilterLidResolver([f], 'message.received', msg(), () =>
+ Promise.resolve({ '1': '111' }),
+ );
+ expect(evaluateFilters(f, 'message.received', msg(), resolve)).toBe(true);
+ });
+
+ it('does not query for text, absent, malformed or other-family conditions', async () => {
+ const read = jest.fn();
+ const bad = { conditions: [null] } as unknown as WebhookFilters;
+ const text = filters({ field: 'body', operator: 'contains', value: '1@lid' });
+ await prepareFilterLidResolver([undefined, null, bad, text], 'message.received', msg(), read);
+ await prepareFilterLidResolver(
+ [filters({ field: 'sender', operator: 'is', value: ['1@lid'] })],
+ 'session.ready',
+ msg(),
+ read,
+ );
+ expect(read).not.toHaveBeenCalled();
+ expect(await prepareFilterLidResolver([text], 'message.received', msg())).toBeUndefined();
+ });
+
+ it('leaves unavailable and prototype-named identities unresolved', async () => {
+ const f = filters({ field: 'sender', operator: 'is', value: ['111'] });
+ const resolve = await prepareFilterLidResolver([f], 'message.received', msg({ from: '1@lid' }), () =>
+ Promise.reject(new Error('unavailable')),
+ );
+ expect(resolve?.('1@lid')).toBeNull();
+ expect(resolve?.('__proto__@lid')).toBeNull();
+ expect(resolve?.('constructor@lid')).toBeNull();
+ expect(evaluateFilters(f, 'message.received', msg({ from: '1@lid' }), resolve)).toBe(false);
+ });
+});
+
describe('evaluateFilters', () => {
it('passes when filters are absent or empty (additive/optional)', () => {
expect(evaluateFilters(null, 'message.received', msg())).toBe(true);
diff --git a/src/modules/webhook/filters/filter-evaluator.ts b/src/modules/webhook/filters/filter-evaluator.ts
index d020470dc..ff14b7d76 100644
--- a/src/modules/webhook/filters/filter-evaluator.ts
+++ b/src/modules/webhook/filters/filter-evaluator.ts
@@ -5,7 +5,7 @@ import {
eventFamily,
getFieldDefinition,
} from './filter-types';
-import { toNeutralJid } from '../../../engine/identity/wa-id';
+import { parseWaId, toNeutralJid } from '../../../engine/identity/wa-id';
/**
* Resolves a lid JID to its phone user-part when the mapping is known (mirrors the engine adapter's
@@ -39,6 +39,41 @@ const canonicalInput = (value: string, resolve?: LidResolver): string => {
const toStringArray = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [];
+/** Read the current aliases once for both sides of the id conditions, rather than a resident mirror. */
+export async function prepareFilterLidResolver(
+ filters: readonly (WebhookFilters | null | undefined)[],
+ event: string,
+ data: Record<string, unknown>,
+ read?: (lids: string[]) => Promise<Record<string, string | null>>,
+): Promise<LidResolver | undefined> {
+ if (!read) return undefined;
+ const lids = new Set<string>();
+ const family = eventFamily(event);
+ for (const filter of filters) {
+ if (!Array.isArray(filter?.conditions)) continue;
+ for (const condition of filter.conditions) {
+ // The caller still rejects a malformed filter on its own, without dropping its siblings.
+ try {
+ const def = getFieldDefinition(family, condition.field);
+ if (!def || (def.kind !== 'id' && def.kind !== 'idArray')) continue;
+ const value = def.resolve(data);
+ const actual = typeof value === 'string' ? [value] : toStringArray(value);
+ for (const jid of [...actual, ...toStringArray(condition.value)]) {
+ const parsed = parseWaId(jid);
+ if (parsed.kind === 'lid') lids.add(parsed.userPart);
+ }
+ } catch {
+ continue;
+ }
+ }
+ }
+ const phones: Record<string, string | null> = lids.size ? await read([...lids]).catch(() => ({})) : {};
+ return jid => {
+ const lid = parseWaId(jid).userPart;
+ return Object.hasOwn(phones, lid) ? phones[lid] : null;
+ };
+}
+
function evaluateCondition(
def: FieldDefinition,
condition: WebhookFilterCondition,
diff --git a/src/modules/webhook/filters/filter-identity.spec.ts b/src/modules/webhook/filters/filter-identity.spec.ts
new file mode 100644
index 000000000..a916cb489
--- /dev/null
+++ b/src/modules/webhook/filters/filter-identity.spec.ts
@@ -0,0 +1,153 @@
+import { ConfigService } from '@nestjs/config';
+import { ModuleRef } from '@nestjs/core';
+import { DataSource, Repository } from 'typeorm';
+import { createLogger } from '../../../common/services/logger.service';
+import { HookManager } from '../../../core/hooks';
+import { PluginCapabilityContext } from '../../../core/plugins/plugin-capability-context';
+import { PluginHostServices } from '../../../core/plugins/plugin-host-services';
+import { PluginStorageService } from '../../../core/plugins/plugin-storage.service';
+import {
+ PluginEngineReadCapability,
+ PluginInstance,
+ PluginStatus,
+ PluginType,
+} from '../../../core/plugins/plugin.interfaces';
+import { LidMapping } from '../../../engine/identity/lid-mapping.entity';
+import { LidMappingStoreService } from '../../../engine/identity/lid-mapping-store.service';
+import { AutomationRulesService } from '../../automation/automation-rules.service';
+import { AutomationRule } from '../../automation/entities/automation-rule.entity';
+import { Session } from '../../session/entities/session.entity';
+import { Webhook } from '../entities/webhook.entity';
+import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entity';
+import { WebhookDeliveryService } from '../webhook-delivery.service';
+import { WebhookOutboxService } from '../webhook-outbox.service';
+import { WebhookFilters } from './filter-types';
+
+const LID = '484848@lid';
+const P = '[email protected]';
+const Q = '[email protected]';
+const filtersFor = (jid: string): WebhookFilters => ({
+ conditions: [{ field: 'sender', operator: 'is', value: [jid] }],
+});
+const message = { from: LID, to: '[email protected]', chatId: LID, body: 'hello', type: 'text' };
+
+describe('Identity readers after a peer changes a mapping', () => {
+ let db: DataSource;
+ let reader: LidMappingStoreService;
+ let peer: LidMappingStoreService;
+
+ beforeEach(async () => {
+ db = await new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [LidMapping],
+ synchronize: true,
+ }).initialize();
+ const repo = db.getRepository(LidMapping);
+ reader = new LidMappingStoreService(repo);
+ peer = new LidMappingStoreService(repo);
+ await reader.remember('484848', '628111', 'reader');
+ await peer.reload();
+ });
+
+ afterEach(async () => {
+ await db.destroy();
+ });
+
+ async function webhookMatches(jid: string): Promise<Webhook[]> {
+ const delivery = new WebhookDeliveryService(
+ {} as Repository<Webhook>,
+ {} as Repository<WebhookDeliveryFailure>,
+ { get: (_key: string, value: unknown) => value } as ConfigService,
+ new HookManager(),
+ {} as WebhookOutboxService,
+ reader,
+ );
+ return (
+ delivery as unknown as {
+ filterMatchingWebhooks: (rows: Webhook[], event: string, data: Record<string, unknown>) => Promise<Webhook[]>;
+ }
+ ).filterMatchingWebhooks(
+ [{ id: 'w', events: ['message.received'], filters: filtersFor(jid) } as Webhook],
+ 'message.received',
+ message,
+ );
+ }
+
+ async function automationSends(jid: string): Promise<jest.Mock> {
+ const sendText = jest.fn().mockResolvedValue({});
+ const rules = new AutomationRulesService(
+ {
+ find: () => Promise.resolve([{ id: 'r', conditions: filtersFor(jid), replyText: 'reply', cooldownSeconds: 0 }]),
+ } as unknown as Repository<AutomationRule>,
+ {} as Repository<Session>,
+ { get: () => ({ sendText }) } as unknown as ModuleRef,
+ reader,
+ );
+ await rules.evaluateInbound('s', message);
+ return sendText;
+ }
+
+ function pluginCapability(): PluginEngineReadCapability {
+ const context = new PluginCapabilityContext(
+ createLogger('PluginIdentity'),
+ { getSessionPort: () => ({ getEngine: () => ({}) }) } as unknown as PluginHostServices,
+ new HookManager(),
+ {} as PluginStorageService,
+ reader,
+ );
+ const plugin: PluginInstance = {
+ manifest: {
+ id: 'identity',
+ name: 'Identity',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+ permissions: ['engine:read'],
+ sessions: ['s'],
+ },
+ status: PluginStatus.INSTALLED,
+ config: {},
+ instance: null,
+ activeSessions: ['s'],
+ };
+ return (
+ context as unknown as { buildEngineReadCapability: (p: PluginInstance) => PluginEngineReadCapability }
+ ).buildEngineReadCapability(plugin);
+ }
+
+ it('does not deliver a phone-filtered webhook after a peer revokes the alias', async () => {
+ await peer.rememberIfUnknown('484848', '628222', 'peer');
+ expect(reader.getCached('484848')).toBe('628111');
+ expect(await webhookMatches(P)).toHaveLength(0);
+ expect(await webhookMatches(LID)).toHaveLength(1);
+ });
+
+ it('does not reply under a phone rule after a peer revokes the alias', async () => {
+ await peer.rememberIfUnknown('484848', '628222', 'peer');
+ expect(await automationSends(P)).not.toHaveBeenCalled();
+ expect(await automationSends(LID)).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns the raw LID to a plugin after a peer revokes the alias', async () => {
+ await peer.rememberIfUnknown('484848', '628222', 'peer');
+ expect(await pluginCapability().canonicalChatId('s', LID)).toBe(LID);
+ });
+
+ it('uses the peer reported phone without reloading the resident mirror', async () => {
+ await peer.remember('484848', '628222', 'peer');
+ expect(reader.getCached('484848')).toBe('628111');
+ expect(await webhookMatches(P)).toHaveLength(0);
+ expect(await webhookMatches(Q)).toHaveLength(1);
+ expect(await automationSends(P)).not.toHaveBeenCalled();
+ expect(await automationSends(Q)).toHaveBeenCalledTimes(1);
+ expect(await pluginCapability().canonicalChatId('s', LID)).toBe(Q);
+ });
+
+ it('preserves matching reported aliases and exact phone inputs', async () => {
+ expect(await webhookMatches(P)).toHaveLength(1);
+ expect(await automationSends(P)).toHaveBeenCalledTimes(1);
+ expect(await pluginCapability().canonicalChatId('s', LID)).toBe(P);
+ expect(await pluginCapability().canonicalChatId('s', Q)).toBe(Q);
+ });
+});
diff --git a/src/modules/webhook/webhook-delivery.service.spec.ts b/src/modules/webhook/webhook-delivery.service.spec.ts
index 1640d3099..8e3193a5c 100644
--- a/src/modules/webhook/webhook-delivery.service.spec.ts
+++ b/src/modules/webhook/webhook-delivery.service.spec.ts
@@ -78,7 +78,7 @@ describe('WebhookDeliveryService', () => {
let configService: jest.Mocked<Partial<ConfigService>>;
let hookManager: jest.Mocked<Partial<HookManager>>;
let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;
- let lidStore: { getCached: jest.Mock; resolveLid: jest.Mock };
+ let lidStore: { getCached: jest.Mock; resolveLid: jest.Mock; phonesForLidsPersisted: jest.Mock };
let outboxService: { open: jest.Mock; close: jest.Mock; markQueued: jest.Mock };
let insertedFailures: Array<Partial<WebhookDeliveryFailure>>;
@@ -177,6 +177,9 @@ describe('WebhookDeliveryService', () => {
getCached: jest.fn().mockReturnValue(null),
// Mirrors the real implementation so tests keep driving resolution through getCached mocks.
resolveLid: jest.fn((jid: string) => (lidStore.getCached(userPart(jid)) as string | null | undefined) ?? null),
+ phonesForLidsPersisted: jest.fn((lids: string[]) =>
+ Promise.resolve(Object.fromEntries(lids.map(lid => [lid, lidStore.getCached(lid) ?? null]))),
+ ),
};
outboxService = {
diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.ts
index 9f6cc5223..295a56191 100644
--- a/src/modules/webhook/webhook-delivery.service.ts
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@ -22,7 +22,7 @@ import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-d
import { QUEUE_NAMES } from '../queue/queue-names';
import { producerReady } from '../queue/redis-connection';
import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';
-import { evaluateFilters } from './filters/filter-evaluator';
+import { evaluateFilters, prepareFilterLidResolver } from './filters/filter-evaluator';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { redactSsrfError } from '../../common/security/ssrf-guard';
import { HookManager } from '../../core/hooks';
@@ -415,7 +415,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
only: string | null,
): Promise<void> {
const webhooks = await this.loadActiveWebhooks(sessionId, event);
- const matchingWebhooks = this.filterMatchingWebhooks(
+ const matchingWebhooks = await this.filterMatchingWebhooks(
only === null ? webhooks : webhooks.filter(webhook => webhook.id === only),
event,
data,
@@ -515,16 +515,23 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
}
}
- private filterMatchingWebhooks(webhooks: Webhook[], event: string, data: Record<string, unknown>): Webhook[] {
- // Resolve a lid actor to its phone through the persistent table so a phone filter matches a
- // lid-addressed sender (e.g. an unresolved @lid group participant). Absent store -> no resolution.
- const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;
+ private async filterMatchingWebhooks(
+ webhooks: Webhook[],
+ event: string,
+ data: Record<string, unknown>,
+ ): Promise<Webhook[]> {
// A row is judged on its own: one whose stored events or filters are malformed (e.g. restored from
// a hand-edited backup) is skipped, instead of throwing here and dropping the event for every
// other webhook of the session. A `filters` that is not a plain object, or a non-array `conditions`,
// is refused explicitly: evaluateFilters reads either as "no filter", which would deliver every
// subscribed event unfiltered.
const subscribed = webhooks.filter(w => Array.isArray(w.events) && subscriptionCoversEvent(w.events, event));
+ const resolveLid = await prepareFilterLidResolver(
+ subscribed.map(w => w.filters),
+ event,
+ data,
+ this.lidMappingStore ? lids => this.lidMappingStore!.phonesForLidsPersisted(lids) : undefined,
+ );
const matching = subscribed.filter(w => {
try {
const filters: unknown = w.filters;