Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(status): ingest inbound statuses into the store and seed from whatsapp-web.js on ready

Yudhi Armyndharis3147948d6327
diff --git a/package.json b/package.json
index cae789b66..d655301d5 100644
--- a/package.json
+++ b/package.json
@@ -148,7 +148,8 @@
},
"moduleNameMapper": {
"^@whiskeysockets/baileys$": "<rootDir>/../test/__mocks__/@whiskeysockets/baileys.ts",
- "^@whiskeysockets/baileys/(.*)$": "<rootDir>/../test/__mocks__/@whiskeysockets/baileys.ts"
+ "^@whiskeysockets/baileys/(.*)$": "<rootDir>/../test/__mocks__/@whiskeysockets/baileys.ts",
+ "^archiver$": "<rootDir>/../test/__mocks__/archiver.ts"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 169a962d7..ea67c464b 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -5,11 +5,12 @@ import { Message } from '../message/entities/message.entity';
import { SessionService } from './session.service';
import { SessionController } from './session.controller';
import { WebhookModule } from '../webhook/webhook.module';
+import { StatusStoreModule } from '../status-store/status-store.module';
@Module({
- // WebhookModule does not import SessionModule back, so the dependency is one-directional —
- // no forwardRef() needed.
- imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule],
+ // WebhookModule/StatusStoreModule do not import SessionModule back, so the dependency is
+ // one-directional — no forwardRef() needed.
+ imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule],
controllers: [SessionController],
providers: [SessionService],
exports: [SessionService],
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 86b6350ef..186ca76b6 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -20,6 +20,7 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
+import { StatusStoreService } from '../status-store/status-store.service';
import {
IncomingMessage,
EngineEventCallbacks,
@@ -62,6 +63,7 @@ describe('SessionService', () => {
let hookManager: jest.Mocked<Partial<HookManager>>;
let configService: jest.Mocked<Partial<ConfigService>>;
let lidMappingStore: jest.Mocked<Partial<LidMappingStoreService>>;
+ let statusStore: jest.Mocked<Partial<StatusStoreService>>;
let mockEngine: Record<string, jest.Mock>;
beforeEach(async () => {
@@ -119,6 +121,7 @@ describe('SessionService', () => {
sendChatState: jest.fn().mockResolvedValue(undefined),
resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),
rejectCall: jest.fn().mockResolvedValue(undefined),
+ getContactStatuses: jest.fn().mockResolvedValue([]),
};
engineFactory = {
@@ -161,6 +164,10 @@ describe('SessionService', () => {
lidsForPhone: jest.fn().mockReturnValue([]),
};
+ statusStore = {
+ ingest: jest.fn().mockResolvedValue({}),
+ };
+
const module: TestingModule = await Test.createTestingModule({
providers: [
SessionService,
@@ -182,6 +189,7 @@ describe('SessionService', () => {
{ provide: HookManager, useValue: hookManager },
{ provide: ConfigService, useValue: configService },
{ provide: LidMappingStoreService, useValue: lidMappingStore },
+ { provide: StatusStoreService, useValue: statusStore },
],
}).compile();
@@ -2173,6 +2181,33 @@ describe('SessionService', () => {
expect(dispatchedEvents('message.received')).toHaveLength(0);
});
+ it('ingests an inbound status broadcast into the status store instead of dropping it', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockClear();
+
+ callbacks.onMessage!(
+ makeMessage({
+ id: 'st1',
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ fromMe: false,
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
+ }),
+ );
+ await flush();
+
+ expect(statusStore.ingest).toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ expect.objectContaining({ waStatusId: 'st1', contactJid: '[email protected]' }),
+ );
+ // Statuses never fall through to the messages table or the message.received webhook.
+ expect(messageRepository.insert).not.toHaveBeenCalled();
+ expect(dispatchedEvents('message.received')).toHaveLength(0);
+ });
+
it('skips persist and dispatch for ephemeral messages when STORE_EPHEMERAL_MESSAGES=false', async () => {
process.env.STORE_EPHEMERAL_MESSAGES = 'false';
const callbacks = await startAndCaptureCallbacks();
@@ -2522,6 +2557,64 @@ describe('SessionService', () => {
expect(auth[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', phone: '628123', pushName: 'Alice' });
});
+ it('seeds the status store from engine.getContactStatuses() when the engine reports ready', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ mockEngine.getContactStatuses.mockResolvedValue([
+ {
+ id: 'st-a',
+ contact: { id: '[email protected]', name: 'Alice', pushName: 'Ali' },
+ type: 'text',
+ caption: 'hi',
+ backgroundColor: '#fff',
+ font: 1,
+ timestamp: new Date(1700000000000),
+ expiresAt: new Date(1700086400000),
+ },
+ {
+ id: 'st-b',
+ contact: { id: '[email protected]' },
+ type: 'image',
+ timestamp: new Date(1700000001000),
+ expiresAt: new Date(1700086401000),
+ },
+ ]);
+
+ callbacks.onReady!('628123', 'Alice');
+ await flush();
+
+ expect(statusStore.ingest).toHaveBeenCalledTimes(2);
+ expect(statusStore.ingest).toHaveBeenNthCalledWith(
+ 1,
+ 'sess-uuid-1',
+ expect.objectContaining({
+ waStatusId: 'st-a',
+ contactJid: '[email protected]',
+ contactName: 'Alice',
+ contactPushName: 'Ali',
+ type: 'text',
+ caption: 'hi',
+ backgroundColor: '#fff',
+ font: 1,
+ postedAt: 1700000000000,
+ }),
+ );
+ expect(statusStore.ingest).toHaveBeenNthCalledWith(
+ 2,
+ 'sess-uuid-1',
+ expect.objectContaining({ waStatusId: 'st-b', contactJid: '[email protected]', type: 'image' }),
+ );
+ });
+
+ it('swallows a getContactStatuses failure on ready (e.g. Baileys EngineNotSupportedError) without throwing', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ mockEngine.getContactStatuses.mockRejectedValue(new Error('not supported'));
+
+ expect(() => callbacks.onReady!('628123', 'Alice')).not.toThrow();
+ await flush();
+
+ expect(statusStore.ingest).not.toHaveBeenCalled();
+ });
+
it('dispatches session.disconnected with the reason when the engine disconnects', async () => {
const callbacks = await startAndCaptureCallbacks();
expect(typeof callbacks.onDisconnected).toBe('function');
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 770193958..534602f40 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -28,6 +28,9 @@ 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 { 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 {
IWhatsAppEngine,
EngineStatus,
@@ -234,6 +237,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly eventsGateway: EventsGateway,
private readonly webhookService: WebhookService,
private readonly hookManager: HookManager,
+ private readonly statusStore: StatusStoreService,
@Optional()
private readonly configService?: ConfigService,
// Shared lid<->phone table (global). Used to persist an inbound @lid sender's resolved phone so
@@ -645,6 +649,45 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engines.get(id) === engine;
}
+ /**
+ * Backfill currently-active statuses from the engine on connect, so the store has today's stories
+ * even for ones posted before this session came online (live posts land via onMessage). Best-effort:
+ * Baileys doesn't support this (throws EngineNotSupportedError) and any other engine error must not
+ * take down the ready path, so every failure is swallowed here. Ingest is idempotent on
+ * `(sessionId, waStatusId)`, so this can never double-count a status onMessage already ingested.
+ */
+ private async seedStatuses(sessionId: string, engine: IWhatsAppEngine): Promise<void> {
+ try {
+ const statuses = await engine.getContactStatuses();
+ for (const s of statuses) {
+ await this.statusStore.ingest(sessionId, {
+ waStatusId: s.id,
+ contactJid: s.contact.id,
+ contactName: s.contact.name,
+ contactPushName: s.contact.pushName,
+ type: s.type,
+ caption: s.caption,
+ backgroundColor: s.backgroundColor,
+ font: s.font,
+ // wwjs Status carries no inline media bytes on seed; only live onMessage attaches media.
+ postedAt: s.timestamp.getTime(),
+ });
+ }
+ } catch (err) {
+ this.logger.debug('Status seed skipped', {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ /**
+ * Hook point for the status.received dispatch (webhook/WS/hook), called once an inbound status row
+ * is ingested. Intentionally a no-op for now — wired up separately so ingest itself ships first.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ private dispatchStatusReceived(_sessionId: string, _row: StatusUpdate): void {}
+
/**
* Persist pre-connection history into the `messages` table for the chat view, without webhook/hook/ws
* dispatch (it predates the live session). De-duplicated by `waMessageId` so re-syncs never duplicate.
@@ -828,12 +871,30 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
error: err instanceof Error ? err.message : String(err),
}),
);
+
+ // Best-effort snapshot of the account's own contacts' currently-active statuses. Live status
+ // posts arrive through onMessage below; this just backfills what was already up before we
+ // connected. Not awaited — onReady must not block on it.
+ void this.seedStatuses(id, engine);
},
onMessage: (message): void => {
if (!this.isLiveEngine(id, engine)) return;
- // Status/Story posts arrive via the inbound path for some engines; don't persist or webhook them.
- // Mirrors the isStatusBroadcast guard in onMessageCreate below.
+ // Status/Story posts arrive via the inbound path for some engines; ingest them into the
+ // status store instead of the message pipeline. Mirrors the isStatusBroadcast guard in
+ // onMessageCreate below (own-send echo — that branch stays a plain drop).
if (message.isStatusBroadcast) {
+ const status = buildIncomingStatus(message);
+ if (status) {
+ void this.statusStore
+ .ingest(id, status)
+ .then(row => this.dispatchStatusReceived(id, row))
+ .catch(err =>
+ this.logger.warn('Status ingest failed', {
+ sessionId: id,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ }
return;
}
// Ephemeral/disappearing messages: skip persist + dispatch when the operator opted out.
diff --git a/test/__mocks__/archiver.ts b/test/__mocks__/archiver.ts
new file mode 100644
index 000000000..8955f2c97
--- /dev/null
+++ b/test/__mocks__/archiver.ts
@@ -0,0 +1,8 @@
+/**
+ * Unit-test stub for `archiver` (ESM-only). ts-jest runs in CommonJS mode, so any source file that
+ * imports it — directly (StorageService) or transitively (anything that injects StorageService or a
+ * module built on it, e.g. StatusStoreService) — fails to parse without this stub once pulled into the
+ * unit test graph. None of the unit suites exercise the tar/zip export path itself (that's covered by
+ * the e2e config's real `archiver` via transformIgnorePatterns), so a bare default export is enough.
+ */
+export default jest.fn();