Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(identity): read the lid table when filtering by phone or by lid

Yudhi Armyndharise703af0f9813
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 632c93b99..e4b66b7c4 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -8,7 +8,8 @@ import { resolveNonNegativeIntEnv } from '../../config/configuration';
// Default cap on the in-memory lid->phone mirror. Every other long-lived map in the engine surface is
// bounded (the per-session lidPhoneCache is 5000); the LID mirror was the lone exception. A miss falls
-// back to engine re-resolution, so the cap trades a re-resolution for bounded memory, never data loss.
+// back to engine re-resolution (a reverse lookup reads the table), so the cap trades a re-resolution for
+// bounded memory, never data loss.
export const LID_MAPPING_CACHE_DEFAULT = 5000;
/**
@@ -45,7 +46,8 @@ export interface LidMappingStore {
* contact-heavy account does not accumulate one entry per distinct LID ever seen into a slow memory leak.
* A cache miss is warmed from the table in the background (rows past the preload cap stay resolvable)
* and otherwise falls back to engine re-resolution (the table remains the source of truth), so eviction
- * only costs a re-resolution, never data loss. The reverse map is reconciled on each eviction so it does
+ * only costs a re-resolution, never data loss. The reverse map has no such warm path (nothing looks a
+ * lid up by phone), so a phone-keyed filter uses {@link findLidsForPhone}, which reads the table. The reverse map is reconciled on each eviction so it does
* not retain entries for LIDs no longer in the forward cache.
*/
@Injectable()
@@ -148,6 +150,28 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
return set ? [...set] : [];
}
+ /**
+ * Reverse lookup that also reads the table. {@link lidsForPhone} only sees lids resident in the
+ * forward cache, and nothing phone-keyed ever warms it, so a mapping past the preload cap or
+ * evicted by the LRU would stay invisible to a phone filter for good. For callers that can await
+ * (the message and status filters, the handover gate). Table rows are not indexed into the cache,
+ * so a list query cannot evict hot forward entries. A lid this process has since re-mapped
+ * elsewhere is skipped (last-write-wins), and a read error falls back to the cache alone.
+ */
+ async findLidsForPhone(phone: string): Promise<string[]> {
+ const lids = new Set(this.lidsForPhone(phone));
+ try {
+ const rows = await this.repo.find({ select: { lid: true }, where: { phone } });
+ for (const { lid } of rows) {
+ const cached = this.lidToPhone.get(lid);
+ if (cached === undefined || cached === phone) lids.add(lid);
+ }
+ } catch (err) {
+ this.logger.warn(`Could not read lids for a phone: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ return [...lids];
+ }
+
async remember(lid: string, phone: string | null, sessionId?: string): Promise<void> {
if (!lid || this.lidToPhone.get(lid) === phone) {
return; // unseen-or-changed only; a no-op write would just churn updatedAt
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index de7ca7e6b..7711f75dc 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -7,7 +7,11 @@ function makeFakeRepo(seed: Partial<LidMapping>[] = []) {
const rows: LidMapping[] = seed.map(r => ({ lid: '', phone: null, sessionId: null, updatedAt: new Date(0), ...r }));
return {
rows,
- find: jest.fn().mockImplementation(() => Promise.resolve(rows.map(r => ({ ...r })))),
+ find: jest
+ .fn()
+ .mockImplementation((options?: { where?: { phone?: string } }) =>
+ Promise.resolve(rows.filter(r => !options?.where || r.phone === options.where.phone).map(r => ({ ...r }))),
+ ),
findOne: jest
.fn()
.mockImplementation((options: { where: { lid: string } }) =>
@@ -124,6 +128,31 @@ describe('LidMappingStoreService — LRU cap', () => {
expect(store.getCached('lid-d')).toBe('620004');
});
+ it('finds a lid by phone from the table once it has left the cache', async () => {
+ process.env.LID_MAPPING_CACHE_MAX = '1';
+ const repo = makeFakeRepo();
+ const store = new LidMappingStoreService(repo as unknown as Repository<LidMapping>);
+ await store.onModuleInit();
+
+ await store.remember('lid-a', '620001');
+ await store.remember('lid-b', '620002'); // evicts lid-a; its row stays persisted
+ expect(store.lidsForPhone('620001')).toEqual([]);
+ expect(await store.findLidsForPhone('620001')).toEqual(['lid-a']);
+ expect(await store.findLidsForPhone('620002')).toEqual(['lid-b']);
+ expect(store.getCached('lid-b')).toBe('620002'); // the table read did not evict the resident entry
+ });
+
+ it('skips a table row this process has since re-mapped, and falls back to the cache on a read error', async () => {
+ const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);
+ const store = await newStore(repo);
+ repo.upsert.mockResolvedValueOnce({}); // the re-map has not reached the table: the row is stale
+ await store.remember('111', '628000');
+ expect(await store.findLidsForPhone('628999')).toEqual([]);
+
+ repo.find.mockRejectedValueOnce(new Error('connection lost'));
+ expect(await store.findLidsForPhone('628000')).toEqual(['111']);
+ });
+
it('reconciles the reverse map on eviction (no orphan phoneToLids entries)', async () => {
process.env.LID_MAPPING_CACHE_MAX = '2';
const repo = makeFakeRepo();
diff --git a/src/modules/message/message-list-ordering.pg.spec.ts b/src/modules/message/message-list-ordering.pg.spec.ts
index 239d141c4..c3560c56b 100644
--- a/src/modules/message/message-list-ordering.pg.spec.ts
+++ b/src/modules/message/message-list-ordering.pg.spec.ts
@@ -79,7 +79,10 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';
{} as EngineRegistry,
{} as MessageProjector,
{} as HookManager,
- { lidsForPhone: () => [], getCached: () => undefined } as unknown as LidMappingStoreService,
+ {
+ findLidsForPhone: () => Promise.resolve([]),
+ findPhoneForLid: () => Promise.resolve(null),
+ } as unknown as LidMappingStoreService,
{} as SendPacingService,
{} as MessageSendService,
);
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index a089fa95b..4065a9ef6 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -10,6 +10,7 @@ import { MessageProjector } from '../session/message-projector.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { HookManager } from '../../core/hooks';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { LidMapping } from '../../engine/identity/lid-mapping.entity';
import { SendPacingService } from './send-pacing.service';
/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */
@@ -40,7 +41,7 @@ describe('MessageService', () => {
let engines: EngineRegistry;
let messageProjector: { recordOutboundMessageEdit: jest.Mock };
let hookManager: jest.Mocked<Partial<HookManager>>;
- let lidMappingStore: { lidsForPhone: jest.Mock; getCached: jest.Mock };
+ let lidMappingStore: { findLidsForPhone: jest.Mock; findPhoneForLid: jest.Mock };
let mockEngine: ReturnType<typeof createMockEngine>;
beforeEach(async () => {
@@ -68,7 +69,10 @@ describe('MessageService', () => {
.mockImplementation((_event: string, data: unknown) => Promise.resolve({ continue: true, data })),
};
- lidMappingStore = { lidsForPhone: jest.fn().mockReturnValue([]), getCached: jest.fn().mockReturnValue(undefined) };
+ lidMappingStore = {
+ findLidsForPhone: jest.fn().mockResolvedValue([]),
+ findPhoneForLid: jest.fn().mockResolvedValue(null),
+ };
const module: TestingModule = await Test.createTestingModule({
providers: [
@@ -315,18 +319,65 @@ describe('MessageService', () => {
};
it('returns the lid-authored message once the table maps the lid to that phone (the hit)', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue(['111']); // table: lid 111 -> phone 628999
+ lidMappingStore.findLidsForPhone.mockResolvedValue(['111']); // table: lid 111 -> phone 628999
const qb = makeFilteringQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
const { messages } = await service.getMessages('sess-1', { from: '628999' });
- expect(lidMappingStore.lidsForPhone).toHaveBeenCalledWith('628999');
+ expect(lidMappingStore.findLidsForPhone).toHaveBeenCalledWith('628999');
+ expect(messages.map(m => m.id).sort()).toEqual(['m-dm', 'm-lid']);
+ });
+
+ it('finds the lid-authored message through a real store whose cache no longer holds the lid', async () => {
+ // The mapping is only in the table: past the preload cap or evicted by the LRU.
+ const table = [{ lid: '111', phone: '628999' }];
+ const store = new LidMappingStoreService({
+ find: ({ where }: { where: { phone: string } }) => Promise.resolve(table.filter(r => r.phone === where.phone)),
+ } as unknown as Repository<LidMapping>);
+ const qb = makeFilteringQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+ const withStore = new MessageService(
+ repository as Repository<Message>,
+ engines,
+ messageProjector as unknown as MessageProjector,
+ hookManager as HookManager,
+ store,
+ inertPacing(),
+ {} as MessageSendService,
+ );
+
+ const { messages } = await withStore.getMessages('sess-1', { from: '628999' });
+
+ expect(store.lidsForPhone('628999')).toEqual([]);
+ expect(messages.map(m => m.id).sort()).toEqual(['m-dm', 'm-lid']);
+ });
+
+ it('finds the phone-form message for a @lid filter through a real store whose cache lacks the lid', async () => {
+ const table = [{ lid: '111', phone: '628999' }];
+ const store = new LidMappingStoreService({
+ findOne: ({ where }: { where: { lid: string } }) =>
+ Promise.resolve(table.find(r => r.lid === where.lid) ?? null),
+ } as unknown as Repository<LidMapping>);
+ const qb = makeFilteringQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+ const withStore = new MessageService(
+ repository as Repository<Message>,
+ engines,
+ messageProjector as unknown as MessageProjector,
+ hookManager as HookManager,
+ store,
+ inertPacing(),
+ {} as MessageSendService,
+ );
+
+ const { messages } = await withStore.getMessages('sess-1', { from: '111@lid' });
+
expect(messages.map(m => m.id).sort()).toEqual(['m-dm', 'm-lid']);
});
it('misses the lid-authored message when the table has no mapping (the prior silent miss)', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue([]); // unresolved: no lid -> phone row yet
+ lidMappingStore.findLidsForPhone.mockResolvedValue([]); // unresolved: no lid -> phone row yet
const qb = makeFilteringQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
@@ -346,7 +397,7 @@ describe('MessageService', () => {
const { messages } = await service.getMessages('sess-1', { from: '628999@hosted' });
expect(messages.map(m => m.id)).toEqual(['m-dm']);
- expect(lidMappingStore.lidsForPhone).toHaveBeenCalledWith('628999');
+ expect(lidMappingStore.findLidsForPhone).toHaveBeenCalledWith('628999');
const calls = qb.andWhere.mock.calls as Array<[string, { froms?: string[] }?]>;
const froms = calls.find(c => c[1]?.froms)?.[1]?.froms;
expect(froms).toEqual(expect.arrayContaining(['628999@hosted', '[email protected]', '[email protected]']));
@@ -395,7 +446,7 @@ describe('MessageService', () => {
};
it('returns group messages authored by the filtered phone (matched via author, not from)', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue([]);
+ lidMappingStore.findLidsForPhone.mockResolvedValue([]);
const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow]);
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
@@ -407,7 +458,7 @@ describe('MessageService', () => {
it('matches a group author stored as a lid once the table maps the lid to the phone', async () => {
const lidAuthorRow = { id: 'm-grp-lid', from: '[email protected]', author: '111@lid', chatId: '[email protected]' } as Message;
- lidMappingStore.lidsForPhone.mockReturnValue(['111']); // table: lid 111 -> phone 628999
+ lidMappingStore.findLidsForPhone.mockResolvedValue(['111']); // table: lid 111 -> phone 628999
const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow, lidAuthorRow]);
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
@@ -417,7 +468,7 @@ describe('MessageService', () => {
});
it('still applies the chatId filter alongside the from/author match', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue([]);
+ lidMappingStore.findLidsForPhone.mockResolvedValue([]);
const qb = makeAuthorQb([aliceGroupRow, bobGroupRow, aliceDmRow]);
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
@@ -462,8 +513,8 @@ describe('MessageService', () => {
// No `[email protected]`/`@s.whatsapp.net` and no lid-table probe with the group's digits.
expect(captured.chatIds).toEqual(['[email protected]']);
- expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
- expect(lidMappingStore.getCached).not.toHaveBeenCalled();
+ expect(lidMappingStore.findLidsForPhone).not.toHaveBeenCalled();
+ expect(lidMappingStore.findPhoneForLid).not.toHaveBeenCalled();
});
it('does not expand a status broadcast or newsletter chatId', async () => {
@@ -476,25 +527,25 @@ describe('MessageService', () => {
await service.getMessages('sess-1', { chatId: '12345@newsletter' });
expect(captured.chatIds).toEqual(['12345@newsletter']);
- expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
+ expect(lidMappingStore.findLidsForPhone).not.toHaveBeenCalled();
});
it('forward-resolves a @lid from-filter to its phone instead of minting <lid-digits>@c.us', async () => {
- lidMappingStore.getCached.mockReturnValue('628999'); // table: lid 111 -> phone 628999
+ lidMappingStore.findPhoneForLid.mockResolvedValue('628999'); // table: lid 111 -> phone 628999
const { qb, captured } = makeCaptureQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
await service.getMessages('sess-1', { from: '111@lid' });
- expect(lidMappingStore.getCached).toHaveBeenCalledWith('111');
+ expect(lidMappingStore.findPhoneForLid).toHaveBeenCalledWith('111');
expect(captured.froms).toEqual(['111@lid', '[email protected]', '[email protected]']);
expect(captured.authorFroms).toEqual(captured.froms); // same candidates drive the author match
expect(captured.froms).not.toContain('[email protected]'); // the lid's digits are not a phone
- expect(lidMappingStore.lidsForPhone).not.toHaveBeenCalled();
+ expect(lidMappingStore.findLidsForPhone).not.toHaveBeenCalled();
});
it('keeps an unresolved @lid filter to the literal id only', async () => {
- lidMappingStore.getCached.mockReturnValue(null); // known-unresolved
+ lidMappingStore.findPhoneForLid.mockResolvedValue(null); // known-unresolved
const { qb, captured } = makeCaptureQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
@@ -503,15 +554,28 @@ describe('MessageService', () => {
expect(captured.froms).toEqual(['111@lid']);
});
+ it('adds the folded <lid>@lid form for an upper-case or hosted lid filter', async () => {
+ lidMappingStore.findPhoneForLid.mockResolvedValue(null);
+ const { qb, captured } = makeCaptureQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ await service.getMessages('sess-1', { from: '111@LID' });
+ expect(captured.froms).toEqual(['111@LID', '111@lid']);
+
+ await service.getMessages('sess-1', { from: '[email protected]' });
+ expect(captured.froms).toEqual(['[email protected]', '111@lid']);
+ expect(lidMappingStore.findPhoneForLid).toHaveBeenCalledWith('111');
+ });
+
it('keeps the user-dialect expansion for a bare phone filter', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue(['111']);
+ lidMappingStore.findLidsForPhone.mockResolvedValue(['111']);
const { qb, captured } = makeCaptureQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
await service.getMessages('sess-1', { from: '628999' });
expect(captured.froms).toEqual(['628999', '[email protected]', '[email protected]', '111@lid']);
- expect(lidMappingStore.lidsForPhone).toHaveBeenCalledWith('628999');
+ expect(lidMappingStore.findLidsForPhone).toHaveBeenCalledWith('628999');
});
});
@@ -541,7 +605,7 @@ describe('MessageService', () => {
};
it('returns a @s.whatsapp.net-stored message when filtering by the neutral @c.us chat id', async () => {
- lidMappingStore.lidsForPhone.mockReturnValue([]);
+ lidMappingStore.findLidsForPhone.mockResolvedValue([]);
const qb = makeChatQb();
(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 690952173..37f438925 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -296,7 +296,7 @@ export class MessageService implements PluginMessagePort {
// Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed
// by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same
// chat, different dialect. Resolving both sides through the table keeps them equal.
- query.andWhere('message.chatId IN (:...chatIds)', { chatIds: this.resolveJidCandidates(chatId) });
+ query.andWhere('message.chatId IN (:...chatIds)', { chatIds: await this.resolveJidCandidates(chatId) });
}
if (from) {
@@ -309,7 +309,7 @@ export class MessageService implements PluginMessagePort {
// within the (sessionId, createdAt)-narrowed scan exactly as the from-only filter did, so the
// OR costs nothing the old plan didn't already pay. No new index: per-session narrowing
// dominates selectivity and a single btree cannot serve an OR across two columns anyway.
- const froms = this.resolveJidCandidates(from);
+ const froms = await this.resolveJidCandidates(from);
query.andWhere('(message.from IN (:...froms) OR message.author IN (:...authorFroms))', {
froms,
authorFroms: froms,
@@ -364,14 +364,16 @@ export class MessageService implements PluginMessagePort {
* A `@lid` input forward-resolves to its phone instead of minting `<lid-digits>@c.us` (the lid's
* digits are NOT a phone), so rows stored under the resolved form still match a raw-lid filter.
*/
- private resolveJidCandidates(value: string): string[] {
+ private async resolveJidCandidates(value: string): Promise<string[]> {
const parsed = parseWaId(value);
if (parsed.kind !== 'user' && parsed.kind !== 'lid' && parsed.kind !== 'unknown') {
return [value];
}
if (parsed.kind === 'lid') {
- const candidates = new Set<string>([value]);
- const resolved = this.lidMappingStore.getCached(parsed.userPart);
+ // The folded `<lid>@lid` form is how a raw-lid row is stored, so an upper-case or
+ // `@hosted.lid` input still matches it.
+ const candidates = new Set<string>([value, `${parsed.userPart}@lid`]);
+ const resolved = await this.lidMappingStore.findPhoneForLid(parsed.userPart);
if (resolved) {
candidates.add(`${resolved}@c.us`);
candidates.add(`${resolved}@s.whatsapp.net`);
@@ -380,7 +382,7 @@ export class MessageService implements PluginMessagePort {
}
const phone = parsed.userPart;
const candidates = new Set<string>([value, `${phone}@c.us`, `${phone}@s.whatsapp.net`]);
- for (const lid of this.lidMappingStore.lidsForPhone(phone)) {
+ for (const lid of await this.lidMappingStore.findLidsForPhone(phone)) {
candidates.add(`${lid}@lid`);
}
return [...candidates];
@@ -429,7 +431,7 @@ export class MessageService implements PluginMessagePort {
chatId: string,
messageId: string,
): Promise<{ buffer: Buffer; mimetype: string }> {
- const chatIds = this.resolveJidCandidates(chatId);
+ const chatIds = await this.resolveJidCandidates(chatId);
const media = await this.chatMediaArchive?.getMedia(sessionId, chatIds, messageId);
if (media && this.storageService) {
try {
diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.ts
index 0fcb4cbde..0d064ab34 100644
--- a/src/modules/status-store/status-store.service.spec.ts
+++ b/src/modules/status-store/status-store.service.spec.ts
@@ -8,6 +8,7 @@ jest.mock('archiver', () => ({ default: jest.fn() }));
import { StorageService } from '../../common/storage/storage.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { LidMapping } from '../../engine/identity/lid-mapping.entity';
import { userPart } from '../../engine/identity/wa-id';
import { StatusUpdate } from './entities/status-update.entity';
import { StatusStoreService } from './status-store.service';
@@ -413,11 +414,14 @@ describe('StatusStoreService contact identity (read-time lid resolution)', () =>
const getCached = (lid: string): string | null | undefined => (lid in mappings ? mappings[lid] : undefined);
return {
getCached,
+ findPhoneForLid: (lid: string) => Promise.resolve(getCached(lid) ?? null),
resolveLid: (jid: string) => getCached(userPart(jid)) ?? null,
- lidsForPhone: (phone: string) =>
- Object.entries(mappings)
- .filter(([, p]) => p === phone)
- .map(([l]) => l),
+ findLidsForPhone: (phone: string) =>
+ Promise.resolve(
+ Object.entries(mappings)
+ .filter(([, p]) => p === phone)
+ .map(([l]) => l),
+ ),
} as unknown as LidMappingStoreService;
};
@@ -460,6 +464,55 @@ describe('StatusStoreService contact identity (read-time lid resolution)', () =>
expect(out[0].contact.id).toBe('[email protected]');
});
+ it.each(['[email protected]', '111@LID', ' 111@lid '])(
+ 'listByContact treats %p as a lid, matching its phone and lid rows',
+ async query => {
+ const svc = new StatusStoreService(
+ repository,
+ storageService,
+ fakeConfigService(),
+ lidStore({ '111': '628111' }),
+ );
+ const now = Date.now();
+ await svc.ingest('sess', { waStatusId: 'h1', contactJid: '[email protected]', type: 'text', postedAt: now });
+ await svc.ingest('sess', { waStatusId: 'h2', contactJid: '111@lid', type: 'text', postedAt: now + 1 });
+
+ const out = await svc.listByContact('sess', query);
+ expect(out).toHaveLength(2);
+ },
+ );
+
+ it("listByContact never reads a lid's digits as a phone", async () => {
+ // Lid 111 is 628111. A phone 111 and the lid 999 mapped to that phone are someone else.
+ const svc = new StatusStoreService(
+ repository,
+ storageService,
+ fakeConfigService(),
+ lidStore({ '111': '628111', '999': '111' }),
+ );
+ const now = Date.now();
+ await svc.ingest('sess', { waStatusId: 'own-lid', contactJid: '111@lid', type: 'text', postedAt: now });
+ await svc.ingest('sess', { waStatusId: 'own-phone', contactJid: '[email protected]', type: 'text', postedAt: now + 1 });
+ await svc.ingest('sess', { waStatusId: 'other-phone', contactJid: '[email protected]', type: 'text', postedAt: now + 2 });
+ await svc.ingest('sess', { waStatusId: 'other-lid', contactJid: '999@lid', type: 'text', postedAt: now + 3 });
+
+ const ids = (await svc.listByContact('sess', '111@lid')).map(s => s.id).sort();
+ expect(ids).toEqual(['own-lid', 'own-phone']);
+ });
+
+ it('listByContact forward-resolves a lid the store only holds in its table, not its cache', async () => {
+ const table = [{ lid: '111', phone: '628111' }];
+ const store = new LidMappingStoreService({
+ find: () => Promise.resolve([]),
+ findOne: ({ where }: { where: { lid: string } }) => Promise.resolve(table.find(r => r.lid === where.lid) ?? null),
+ } as unknown as Repository<LidMapping>);
+ const svc = new StatusStoreService(repository, storageService, fakeConfigService(), store);
+ await svc.ingest('sess', { waStatusId: 'l6', contactJid: '[email protected]', type: 'text', postedAt: Date.now() });
+
+ const out = await svc.listByContact('sess', '111@lid');
+ expect(out).toHaveLength(1);
+ });
+
it('never resolves phone-shaped JIDs through the lid map (digit-collision guard)', async () => {
// A lid key colliding with a phone's digits must not rename a phone-form row.
const svc = new StatusStoreService(
diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.ts
index f0c2c10c6..33764050d 100644
--- a/src/modules/status-store/status-store.service.ts
+++ b/src/modules/status-store/status-store.service.ts
@@ -10,7 +10,7 @@ import { StorageService } from '../../common/storage/storage.service';
import { sweepOrphanedFiles } from '../../common/storage/orphan-sweep';
import { isUniqueViolation } from '../../common/utils/db-errors';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
-import { userPart } from '../../engine/identity/wa-id';
+import { parseWaId, userPart } from '../../engine/identity/wa-id';
import { createLogger } from '../../common/services/logger.service';
/** A status/story lives for 24h from posting, matching WhatsApp's own expiry. Exported for the
@@ -243,13 +243,20 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
// mid-window) — match every candidate so a resolved-form query doesn't silently miss lid rows.
const candidates = new Set<string>([contactJid]);
if (this.lidMappingStore) {
- const phone = userPart(contactJid);
- candidates.add(`${phone}@c.us`);
- // Forward-resolve a @lid query to its phone too, or rows ingested after the mapping was
- // learned (stored under @c.us) are missed by a consumer querying the raw lid.
- const resolved = this.lidMappingStore.getCached(phone);
- if (resolved) candidates.add(`${resolved}@c.us`);
- for (const lid of this.lidMappingStore.lidsForPhone(phone)) candidates.add(`${lid}@lid`);
+ // parseWaId classifies the input, so an upper-case or hosted.lid input is a lid too.
+ const parsed = parseWaId(contactJid);
+ if (parsed.kind === 'lid') {
+ // A lid's digits are not a phone (the map's keys are raw digits, so a phone could collide
+ // with a lid): add the folded `<lid>@lid` form it is stored under and forward-resolve it, so
+ // rows ingested after the mapping was learned (stored under @c.us) still match.
+ candidates.add(`${parsed.userPart}@lid`);
+ const resolved = await this.lidMappingStore.findPhoneForLid(parsed.userPart);
+ if (resolved) candidates.add(`${resolved}@c.us`);
+ } else {
+ const phone = userPart(contactJid);
+ candidates.add(`${phone}@c.us`);
+ for (const lid of await this.lidMappingStore.findLidsForPhone(phone)) candidates.add(`${lid}@lid`);
+ }
}
const rows = await this.repository.find({
where: { sessionId, contactJid: In([...candidates]), expiresAt: MoreThan(Date.now()) },