Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(status): resolve @lid contacts at read time; pre-gate seed media at the store cap

Yudhi Armyndharis8ceecf9f7cbf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2012b0f84..933d1474b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -80,6 +80,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
output) is deleted at the end of the builder stage instead of being copied into every published
image.
+- **Contacts with both a @lid and a phone identity now appear once in the status list.** Statuses
+ arriving under a contact's @lid are resolved to their phone at read time — including mappings
+ learned after the status arrived — so the same person no longer shows as two rows, and the
+ per-contact endpoint matches rows stored under either form.
+
+- **The status seed no longer downloads media the store would discard.** Media downloads during the
+ connect-time backfill are pre-gated at the store's own 10 MB cap instead of the looser global
+ media cap, so an over-cap blob is marked omitted without ever being fetched.
+
- **`npm run dev` no longer crashes on the second launch with `Cannot find module '.../dist/main'`.**
The TypeScript 6 upgrade moved the incremental build cache (`tsbuildinfo`) out of `dist/` to the
project root, where the dev server's `deleteOutDir` wipe could no longer remove it. On every start
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 3aa5bfa23..e77ad7221 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1045,7 +1045,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {
return this.unsupported('getMessageReactions');
}
- getChatHistory(_chatId: string, _limit?: number, _includeMedia?: boolean): Promise<IncomingMessage[]> {
+ getChatHistory(
+ _chatId: string,
+ _limit?: number,
+ _includeMedia?: boolean,
+ _mediaMaxBytes?: number,
+ ): Promise<IncomingMessage[]> {
return this.unsupported('getChatHistory');
}
getLabels(): Promise<Label[]> {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 106d7bb4e..ada658062 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -377,6 +377,31 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live p
expect(out[0].kind).toBe('group');
expect(out[0].isGroup).toBe(true);
});
+
+ it('skips the media download when the declared size exceeds a caller-tightened mediaMaxBytes', async () => {
+ // 12 MB passes the global 50 MiB default but not the seed's 10 MB store cap — proving the
+ // override (not the default) did the gating, and the blob is never downloaded.
+ const mediaMsg = {
+ id: { _serialized: 'M5' },
+ to: 'status@broadcast',
+ body: '',
+ type: 'image',
+ timestamp: 500,
+ fromMe: false,
+ hasMedia: true,
+ hasQuotedMsg: false,
+ _data: { size: 12 * 1024 * 1024, mimetype: 'image/jpeg' },
+ downloadMedia: jest.fn(),
+ };
+ const chat = { fetchMessages: jest.fn().mockResolvedValue([mediaMsg]) };
+ const client = { getChatById: jest.fn().mockResolvedValue(chat) };
+
+ const out = await readyAdapter(client).getChatHistory('status@broadcast', 50, true, 10 * 1024 * 1024);
+
+ expect(mediaMsg.downloadMedia).not.toHaveBeenCalled();
+ expect(out[0].media).toMatchObject({ omitted: true, sizeBytes: 12 * 1024 * 1024, mimetype: 'image/jpeg' });
+ });
});
describe('WhatsAppWebJsAdapter.sendPollMessage', () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 11624c5aa..5f979cbb6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -365,7 +365,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
* on the sender-declared size and skip the download entirely when it exceeds the cap, and (2) run the
* download through the concurrency limiter for backpressure. Returns undefined when there's no media.
*/
- private async capInboundMediaFor(msg: Message): Promise<IncomingMessage['media'] | undefined> {
+ private async capInboundMediaFor(
+ msg: Message,
+ maxBytesOverride?: number,
+ ): Promise<IncomingMessage['media'] | undefined> {
if (!isMediaDownloadEnabled()) {
const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
return {
@@ -375,13 +378,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
sizeBytes: coerceDeclaredSize(data?.size),
};
}
- const maxBytes = inboundMediaMaxBytes();
+ const maxBytes = maxBytesOverride ?? inboundMediaMaxBytes();
const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;
const declared = coerceDeclaredSize(data?.size);
if (declared > maxBytes) {
- this.logger.warn('Inbound media declared size exceeds MEDIA_DOWNLOAD_MAX_BYTES; skipped download', {
+ this.logger.warn('Inbound media declared size exceeds the cap; skipped download', {
msgId: msg.id._serialized,
sizeBytes: declared,
+ maxBytes,
});
return {
mimetype: data?.mimetype ?? '',
@@ -2111,7 +2115,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// ========== Gap Quick Wins Implementation ==========
- async getChatHistory(chatId: string, limit: number = 50, includeMedia: boolean = false): Promise<IncomingMessage[]> {
+ async getChatHistory(
+ chatId: string,
+ limit: number = 50,
+ includeMedia: boolean = false,
+ mediaMaxBytes?: number,
+ ): Promise<IncomingMessage[]> {
this.ensureReady();
const chat = await this.client!.getChatById(chatId);
const messages = await chat.fetchMessages({ limit });
@@ -2150,8 +2159,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
if (includeMedia && msg.hasMedia) {
try {
- // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the response/heap.
- const capped = await this.capInboundMediaFor(msg);
+ // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the
+ // response/heap. Callers (the status seed) can tighten the cap below the global default.
+ const capped = await this.capInboundMediaFor(msg, mediaMaxBytes);
if (capped) out.media = capped;
} catch (error) {
this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 53c9f0936..33262448c 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -617,7 +617,17 @@ export interface IWhatsAppEngine {
* non-text or foreign messages at their own layer — the engine's error is surfaced as-is.
*/
editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult>;
- getChatHistory(chatId: string, limit?: number, includeMedia?: boolean): Promise<IncomingMessage[]>;
+ /**
+ * Read a chat's recent messages, newest first. When `includeMedia` downloads blobs, an optional
+ * `mediaMaxBytes` tightens the declared-size pre-gate below the global MEDIA_DOWNLOAD_MAX_BYTES —
+ * the status seed uses it to skip downloads the store would discard as over-cap anyway.
+ */
+ getChatHistory(
+ chatId: string,
+ limit?: number,
+ includeMedia?: boolean,
+ mediaMaxBytes?: number,
+ ): Promise<IncomingMessage[]>;
// Calls
/**
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 1272c10ee..ffdc29852 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2689,8 +2689,9 @@ describe('SessionService', () => {
await flush();
// Reads the status-broadcast chat's own messages (with media), not the near-empty-at-ready
- // getBroadcasts collection.
- expect(mockEngine.getChatHistory).toHaveBeenCalledWith('status@broadcast', 50, true);
+ // getBroadcasts collection. Downloads are pre-gated at the store's 10 MB cap, not the looser
+ // global MEDIA_DOWNLOAD_MAX_BYTES — anything bigger would be discarded as over_cap on ingest.
+ expect(mockEngine.getChatHistory).toHaveBeenCalledWith('status@broadcast', 50, true, 10 * 1024 * 1024);
expect(mockEngine.getContactStatuses).not.toHaveBeenCalled();
// Two usable statuses ingested; the pseudo-JID poster is filtered out.
expect(statusStore.ingest).toHaveBeenCalledTimes(2);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index bd34e2152..81c988590 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -28,7 +28,7 @@ import { userPart } from '../../engine/identity/wa-id';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import { resolveFeatureFlags } from '../../config/feature-flags';
-import { STATUS_TTL_MS, StatusStoreService } from '../status-store/status-store.service';
+import { DEFAULT_MEDIA_MAX_BYTES, STATUS_TTL_MS, StatusStoreService } from '../status-store/status-store.service';
import { buildIncomingStatus } from '../status-store/incoming-status';
import type { StatusUpdate } from '../status-store/entities/status-update.entity';
import {
@@ -672,7 +672,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// through the very buildIncomingStatus the live onMessage path uses — so a seeded status is
// indistinguishable from one that arrives live. No status.received webhook is dispatched here:
// this is a backfill of posts that predate the connection, not a live arrival.
- const messages = await engine.getChatHistory('status@broadcast', STATUS_SEED_LIMIT, true);
+ // Pre-gate media downloads at the store's own cap: a larger blob would be discarded as
+ // over_cap on ingest anyway, so downloading it is pure waste (heap + bandwidth).
+ const mediaMaxBytes = this.configService.get<number>('status.mediaMaxBytes', DEFAULT_MEDIA_MAX_BYTES);
+ const messages = await engine.getChatHistory('status@broadcast', STATUS_SEED_LIMIT, true, mediaMaxBytes);
// getChatHistory maps a message's contact from the sync cache only, so status posters (usually
// @lid ids) come back nameless. Resolve each unique poster once via getContactById — the same
// lookup the contacts API uses, which maps the @lid to the real contact — so a seeded status
diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.ts
index c12649246..37684a3b1 100644
--- a/src/modules/status-store/status-store.service.spec.ts
+++ b/src/modules/status-store/status-store.service.spec.ts
@@ -7,6 +7,7 @@ import { ConfigService } from '@nestjs/config';
jest.mock('archiver', () => ({ default: jest.fn() }));
import { StorageService } from '../../common/storage/storage.service';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { StatusUpdate } from './entities/status-update.entity';
import { StatusStoreService } from './status-store.service';
@@ -330,6 +331,65 @@ describe('StatusStoreService ingest race (unique-constraint loser)', () => {
});
});
+describe('StatusStoreService contact identity (read-time lid resolution)', () => {
+ let baseDir: string;
+ let ds: DataSource;
+ let repository: Repository<StatusUpdate>;
+ let storageService: StorageService;
+
+ beforeEach(async () => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-status-lid-'));
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [StatusUpdate], synchronize: true });
+ await ds.initialize();
+ repository = ds.getRepository(StatusUpdate);
+ storageService = makeStorageService(path.join(baseDir, 'media'));
+ });
+
+ afterEach(async () => {
+ if (ds.isInitialized) await ds.destroy();
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ const lidStore = (mappings: Record<string, string | null>): LidMappingStoreService =>
+ ({
+ getCached: (lid: string) => (lid in mappings ? mappings[lid] : undefined),
+ lidsForPhone: (phone: string) =>
+ Object.entries(mappings)
+ .filter(([, p]) => p === phone)
+ .map(([l]) => l),
+ }) as unknown as LidMappingStoreService;
+
+ it('resolves a @lid contact to the mapped phone at read time, so both forms group together', async () => {
+ const svc = new StatusStoreService(repository, storageService, fakeConfigService(), lidStore({ '111': '628111' }));
+ const now = Date.now();
+ await svc.ingest('sess', { waStatusId: 'l1', contactJid: '111@lid', type: 'text', postedAt: now });
+ await svc.ingest('sess', { waStatusId: 'l2', contactJid: '[email protected]', type: 'text', postedAt: now + 1 });
+
+ const contacts = new Set((await svc.list('sess')).map(s => s.contact.id));
+ expect(contacts).toEqual(new Set(['[email protected]']));
+ });
+
+ it('leaves unknown and known-unresolved lids untouched', async () => {
+ const svc = new StatusStoreService(repository, storageService, fakeConfigService(), lidStore({ '222': null }));
+ const now = Date.now();
+ await svc.ingest('sess', { waStatusId: 'u1', contactJid: '222@lid', type: 'text', postedAt: now });
+ await svc.ingest('sess', { waStatusId: 'u2', contactJid: '333@lid', type: 'text', postedAt: now + 1 });
+
+ const contacts = (await svc.list('sess')).map(s => s.contact.id);
+ expect(contacts).toContain('222@lid');
+ expect(contacts).toContain('333@lid');
+ });
+
+ it("listByContact matches rows stored under the contact's lid when queried by phone", async () => {
+ const svc = new StatusStoreService(repository, storageService, fakeConfigService(), lidStore({ '111': '628111' }));
+ await svc.ingest('sess', { waStatusId: 'l3', contactJid: '111@lid', type: 'text', postedAt: Date.now() });
+
+ const out = await svc.listByContact('sess', '[email protected]');
+ expect(out).toHaveLength(1);
+ expect(out[0].contact.id).toBe('[email protected]');
+ });
+});
+
describe('StatusStoreService.purgeExpired', () => {
let baseDir: string;
let ds: DataSource;
diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.ts
index dde578fd4..441bd4cf6 100644
--- a/src/modules/status-store/status-store.service.ts
+++ b/src/modules/status-store/status-store.service.ts
@@ -1,13 +1,15 @@
-import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
+import { Injectable, OnModuleDestroy, OnModuleInit, Optional } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
-import { LessThan, MoreThan, Repository } from 'typeorm';
+import { In, LessThan, MoreThan, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import { StatusUpdate } from './entities/status-update.entity';
import type { IncomingStatus } from './incoming-status';
import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';
import { StorageService } from '../../common/storage/storage.service';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { 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
@@ -15,7 +17,9 @@ import { createLogger } from '../../common/services/logger.service';
export const STATUS_TTL_MS = 24 * 60 * 60 * 1000;
/** How often the TTL purge sweeps expired rows. */
const PURGE_INTERVAL_MS = 15 * 60 * 1000;
-const DEFAULT_MEDIA_MAX_BYTES = 10 * 1024 * 1024;
+/** Default per-file cap on persisted status media. Exported for the session service's seed, which
+ * pre-gates history downloads at the same cap so over-cap blobs are never fetched. */
+export const DEFAULT_MEDIA_MAX_BYTES = 10 * 1024 * 1024;
/** Subtypes whose registered mimetype name differs from the conventional file extension. */
const MIME_SUBTYPE_EXT_OVERRIDES: Record<string, string> = { jpeg: 'jpg', quicktime: 'mov' };
@@ -42,6 +46,9 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
private readonly repository: Repository<StatusUpdate>,
private readonly storageService: StorageService,
private readonly configService: ConfigService,
+ // Optional, mirroring WebhookService: resolution is a best-effort display concern — without the
+ // store, contacts just show under whichever JID the status arrived with.
+ @Optional() private readonly lidMappingStore?: LidMappingStoreService,
) {}
onModuleInit(): void {
@@ -153,17 +160,35 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
}
async listByContact(sessionId: string, contactJid: string): Promise<Status[]> {
+ // The same person may hold rows under both a @lid and their @c.us (the mapping was learned
+ // 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`);
+ for (const lid of this.lidMappingStore.lidsForPhone(phone)) candidates.add(`${lid}@lid`);
+ }
const rows = await this.repository.find({
- where: { sessionId, contactJid, expiresAt: MoreThan(Date.now()) },
+ where: { sessionId, contactJid: In([...candidates]), expiresAt: MoreThan(Date.now()) },
order: { postedAt: 'DESC' },
});
return rows.map(row => this.toStatus(row));
}
+ /**
+ * Canonical display form of a contact JID: resolve a @lid to its phone via the shared mapping.
+ * Read-time (not ingest-time) on purpose: a mapping learned after the status arrived still merges
+ * the contact's rows into one group. Unknown or known-unresolved lids stay as-is.
+ */
+ private canonicalContactJid(jid: string): string {
+ const phone = this.lidMappingStore?.getCached(userPart(jid));
+ return phone ? `${phone}@c.us` : jid;
+ }
+
private toStatus(row: StatusUpdate): Status {
return {
id: row.waStatusId,
- contact: { id: row.contactJid, name: row.contactName, pushName: row.contactPushName },
+ contact: { id: this.canonicalContactJid(row.contactJid), name: row.contactName, pushName: row.contactPushName },
type: row.type,
caption: row.caption,
mediaUrl: