Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(status,chats): restore-roundtrip author, font enum, and store/viewer hardening
Yudhi Armyndharis4de8d1b014bf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d3911a5c..9172d49ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,8 +20,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0tab refreshes immediately instead of waiting for a focus refetch — including while a contact'sviewer is already open.+### Changed++- **Status font selection now follows the real WhatsApp font enum.** `POST+ /sessions/:id/status/send-text` accepts the font indices that actually exist on the wire — 0+ (default), 1, 2, 6 (system bold), 7, 8, 9, 10 — instead of a 0–5 range that included+ non-existent indices 3–5 and rejected the valid 6–10. The dashboard viewer renders the full+ enum (bold/script/serif/mono slots approximated with generic families), and the compose+ dropdown offers the same set.+### Fixed+- **Backup restores no longer drop group sender attribution.** The data import now carries the+ `author` column (the export already wrote it), so a backup→restore keeps each group message's+ stable sender identity instead of collapsing attribution back to display names.+- **Group messages now carry a stable sender identity, so same-named participants no longer blurtogether.** Group messages persist the participant JID (new `author` column on `messages`) nextto the sender's display name, and the dashboard keys attribution runs and sender colors on that@@ -38,6 +51,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0connect-time backfill are pre-gated at the store's own 10 MB cap instead of the looser globalmedia cap, so an over-cap blob is marked omitted without ever being fetched.+- **Status store hardening.** A `@lid` query on the per-contact status endpoint now also matches+ rows stored under the contact's phone (forward resolution, mirroring the reverse); lid+ resolution is guarded to `@lid` inputs so a phone-shaped JID can never collide with a lid key;+ media skipped by the seed's download pre-gate is recorded as `over_cap` rather than+ `engine_omitted`; and a status ingest that finishes after its session was deleted no longer+ dispatches `status.received` for the retired session.++- **History backfill no longer marks the account's own posts.** Backfilled outgoing group messages+ are stored with `author` NULL, keeping the column's "null on outgoing" contract the attribution+ logic relies on.++- **Dashboard follow-through.** A websocket reconnect now also refreshes the statuses list (a+ story posted during the gap previously stayed invisible until a window-focus refetch); the+ webhook editor offers `status.received` as an explicit subscription; and a styled status+ bubble's timestamp inherits the bubble's text color instead of staying muted gray.+## [0.10.9] - 2026-07-24### Addeddiff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex 67bb64c21..039c53d2e 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -568,6 +568,13 @@color: var(--text-muted);}+/* A styled status bubble sets its own inline background + white text; let its timestamp inherit+ instead of staying the muted gray meant for the default bubble. */+.chats-page .message-bubble[style] .message-time {+ color: inherit;+ opacity: 0.75;+}+.chats-page .message-status-icon {font-size: 0.75rem;}diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex f50a6b6d8..64aa92e79 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -188,14 +188,32 @@ function StatusMedia({// user can't build a list the backend is guaranteed to reject.const STATUS_RECIPIENTS_MAX = 256;-// Approximate WhatsApp's text-status font slots with generic families (the actual faces are-// proprietary); index 0 and unknown slots keep the UI default.-const STATUS_FONT_FAMILY: Record<number, string> = {- 1: 'serif',- 2: 'monospace',- 3: 'cursive',- 4: 'fantasy',- 5: 'ui-rounded, system-ui, sans-serif',+// WhatsApp's text-status font slots — the current wire enum is {0,1,2,6,7,8,9,10} (6 is the bold+// system face); 3–5 are legacy slots older clients still emit. Approximated with generic+// families/weights since the actual faces are proprietary; slot 0 and unknown slots keep the UI+// default.+const STATUS_FONT: Record<number, { family?: string; weight?: number }> = {+ 1: { family: 'serif' },+ 2: { family: 'cursive' },+ 3: { family: 'fantasy' }, // legacy+ 4: { family: 'serif' }, // legacy+ 5: { family: 'ui-rounded, system-ui, sans-serif' }, // legacy+ 6: { weight: 700 },+ 7: { family: 'cursive' },+ 8: { family: 'serif' },+ 9: { family: 'sans-serif', weight: 800 },+ 10: { family: 'monospace', weight: 700 },+};++/** Inline style for a status item's font slot; {} when unstyled/unknown. */+const statusFontStyle = (font?: number): { fontFamily?: string; fontWeight?: number } => {+ if (font === undefined) return {};+ const slot = STATUS_FONT[font];+ if (!slot) return {};+ return {+ ...(slot.family ? { fontFamily: slot.family } : {}),+ ...(slot.weight ? { fontWeight: slot.weight } : {}),+ };};export function Chats() {@@ -783,6 +801,9 @@ export function Chats() {reconnectWasDisconnected.current = decision.wasDisconnected;if (decision.invalidate) {queryClient.invalidateQueries({ queryKey: ['messages', selectedSessionId] });+ // Statuses are live now (status.received): a story posted during the socket gap would+ // otherwise stay invisible until a focus refetch.+ queryClient.invalidateQueries({ queryKey: ['contact-statuses', selectedSessionId] });}}, [isConnected, selectedSessionId, queryClient]);@@ -1961,9 +1982,7 @@ export function Chats() {...(item.backgroundColor? { backgroundColor: item.backgroundColor, color: '#fff' }: {}),- ...(item.font && STATUS_FONT_FAMILY[item.font]- ? { fontFamily: STATUS_FONT_FAMILY[item.font] }- : {}),+ ...statusFontStyle(item.font),}: undefined}@@ -2056,7 +2075,9 @@ export function Chats() {<label>{t('chats.status.font')}</label><select value={composeFont} onChange={e => setComposeFont(e.target.value)}><option value="">{t('chats.status.fontDefault')}</option>- {[0, 1, 2, 3, 4, 5].map(f => (+ {/* The WhatsApp status font enum: 6 is the bold system face; 3–5 don't exist on+ the wire and the backend rejects them. */}+ {[0, 1, 2, 6, 7, 8, 9, 10].map(f => (<option key={f} value={f}>{f}</option>diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex 2166da6c0..f5e5f3d6d 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -105,6 +105,7 @@ const availableEventNames = ['group.leave','group.update','call.received',+ 'status.received','*',] as const;diff --git a/openapi.json b/openapi.jsonindex 7bd7e7c4b..4160ccbe8 100644--- a/openapi.json+++ b/openapi.json@@ -7541,10 +7541,18 @@},"font": {"type": "number",- "description": "Font family index (0–5).",+ "description": "Font family index from the WhatsApp status font enum: 0 (default), 1, 2, 6 (bold), 7, 8, 9, or 10. whatsapp-web.js honors only 0–7 and clamps anything above to the default.","example": 0,- "minimum": 0,- "maximum": 5+ "enum": [+ 0,+ 1,+ 2,+ 6,+ 7,+ 8,+ 9,+ 10+ ]},"recipients": {"description": "Recipient JIDs (0–256). WhatsApp Status is not posted to a group — use @c.us or @lid individuals. Required on the Baileys engine (it posts to exactly this allow-list); ignored by whatsapp-web.js, which broadcasts to the account's status-privacy audience — omit it there.",diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 5c3b968c8..1b68c4f3d 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -836,6 +836,37 @@ describe('InfraController.import/export preserves every data-DB table', () => {expect((await lidRepo.findOneByOrFail({ lid: '222' })).phone).toBeNull();});+ // The messages import column list must carry every later-added column; `author` (the group+ // sender identity) was the one that drifted — a restored backup silently lost all attribution.+ it('restores the group-sender author column on a backup→restore', async () => {+ await seedSession('s1');+ const msgRepo = ds.getRepository(Message);+ await msgRepo.save(+ msgRepo.create({+ sessionId: 's1',+ waMessageId: 'WA-A1',+ chatId: '[email protected]',+ chatName: 'Alice',+ author: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: 'hello',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ timestamp: 1700000000,+ }),+ );++ const dump = await controller.exportData();+ await msgRepo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ const restored = await msgRepo.findOneByOrFail({ waMessageId: 'WA-A1' });+ expect(restored.author).toBe('[email protected]');+ });+// DELETE FROM sessions cascades to templates + baileys_stored_messages (both FK ON DELETE CASCADE),// so an import that never re-inserts them permanently wipes both on the documented backup flow.it('restores templates and baileys_stored_messages instead of cascade-wiping them', async () => {diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 6f714c072..ca2e507b2 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -302,6 +302,8 @@ interface MessageRow {waMessageId: string | null;chatId: string;chatName: string | null;+ /** Group participant JID (nullable; added to messages after chatName — keep the import list in sync). */+ author: string | null;from: string;to: string;body: string | null;@@ -1390,14 +1392,17 @@ export class InfraController {for (const msg of data.tables.messages) {try {await insert(- `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,+ `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,[msg.id,msg.sessionId,msg.waMessageId ?? null,msg.chatId,msg.chatName ?? null,+ // Rows exported before the author column existed simply restore to NULL (legacy+ // behavior) instead of failing the whole import on an unknown key.+ msg.author ?? null,msg.from,msg.to,msg.body ?? null,diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex dbe4ddd0d..34c05e3b1 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2292,6 +2292,35 @@ describe('SessionService', () => {);});+ it('does not dispatch when the session is deleted mid-ingest', async () => {+ // ingest() awaits (findOne + media write + save); a delete() completing in that window must+ // stop the continuation before it webhooks/emits for a retired session — mirroring the+ // message.received re-check above.+ const callbacks = await startAndCaptureCallbacks();+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;+ (statusStore.ingest as jest.Mock).mockImplementationOnce(() => {+ engines.delete('sess-uuid-1');+ return Promise.resolve({ created: true, row: { waStatusId: 'st1', contactJid: '[email protected]' } });+ });++ callbacks.onMessage!(+ makeMessage({+ id: 'st1',+ from: 'status@broadcast',+ to: '[email protected]',+ chatId: 'status@broadcast',+ fromMe: false,+ isStatusBroadcast: true,+ author: '[email protected]',+ kind: 'status',+ }),+ );+ await flush();++ expect(dispatchedEvents('status.received')).toHaveLength(0);+ expect(eventsGateway.emitStatusReceived).not.toHaveBeenCalled();+ });+it('does not dispatch status.received for a duplicate delivery (ingest resolves created=false)', async () => {const callbacks = await startAndCaptureCallbacks();(statusStore.ingest as jest.Mock).mockResolvedValueOnce({@@ -3014,6 +3043,41 @@ describe('SessionService', () => {expect(messageRepository.save).not.toHaveBeenCalled(); // no longer the throwing path});+ it('persists author only for inbound history rows, never for the account’s own (fromMe) posts', async () => {+ // The Baileys history sync includes the account's own group messages (with author = self);+ // those must land with author NULL to keep the column's "null on outgoing" contract.+ const callbacks = await startAndCaptureCallbacks();+ const created: Array<Record<string, unknown>> = [];+ (messageRepository.create as jest.Mock).mockImplementation((data: Record<string, unknown>) => {+ created.push(data);+ return { ...data };+ });+ (messageRepository.find as jest.Mock).mockResolvedValue([]); // nothing pre-seen++ const histMsg = (over: Partial<IncomingMessage>): IncomingMessage => ({+ id: 'h-x',+ from: '[email protected]',+ to: '[email protected]',+ chatId: '[email protected]',+ body: 'g',+ type: 'text',+ timestamp: 1,+ fromMe: false,+ isGroup: true,+ kind: 'group',+ ...over,+ });+ callbacks.onHistoryMessages?.([+ histMsg({ id: 'h-in', fromMe: false, author: '[email protected]' }),+ histMsg({ id: 'h-out', fromMe: true, author: '[email protected]' }),+ ]);+ await flush();++ const byId = new Map(created.map(r => [r.waMessageId as string, r]));+ expect(byId.get('h-in')?.author).toBe('[email protected]');+ expect(byId.get('h-out')?.author).toBeUndefined();+ });+it('synthesizes the omitted media marker for media-free history rows (no empty bubbles)', async () => {// History sync maps messages media-free (footprint). A media row persisted WITHOUT the marker// renders as an empty bubble in the dashboard (the DB copy wins the merge over the enginediff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 98eba578e..2e9e59165 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -810,7 +810,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: id,waMessageId: m.id,chatId: m.chatId,- author: m.author,+ // Group poster for inbound rows only — the account's own backfilled group messages must+ // not carry author (the column's contract is "null on outgoing echoes").+ author: m.fromMe ? undefined : m.author,from: m.from,to: m.to,body: m.body,@@ -964,6 +966,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// for a duplicate delivery (or the winner's row after a lost insert race), and the// webhook must fire once per status, not once per (re)delivery..then(({ row, created }) => {+ // The ingest awaited; a stop()/delete() can retire this engine mid-flight — don't+ // dispatch for a session that no longer exists (mirrors message.received's re-check).+ if (!this.isLiveEngine(id, engine)) return;if (created) this.dispatchStatusReceived(id, row);}).catch(err =>diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex fd8747c5e..8d85b3820 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -118,6 +118,20 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {expect(row.mediaPath).toBeFalsy();});+ it('ingest records over_cap (not engine_omitted) when an engine-skipped blob exceeds the store cap', async () => {+ // The seed's pre-gate skips downloads above the store cap with the engine-omitted flag set —+ // the durable reason must still read over_cap on both arrival paths.+ const { row } = await service.ingest('sess', {+ waStatusId: 'w8',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', omitted: true, sizeBytes: 11 * 1024 * 1024 },+ postedAt: Date.now(),+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('over_cap');+ });+it('ingest is idempotent on (sessionId, waStatusId), flagged as not created on the duplicate', async () => {await service.ingest('sess', { waStatusId: 'dup', contactJid: '[email protected]', type: 'text', postedAt: 1 });const second = await service.ingest('sess', {@@ -406,6 +420,29 @@ describe('StatusStoreService contact identity (read-time lid resolution)', () =>expect(out).toHaveLength(1);expect(out[0].contact.id).toBe('[email protected]');});++ it("listByContact forward-resolves a lid query to rows stored under the contact's phone", async () => {+ const svc = new StatusStoreService(repository, storageService, fakeConfigService(), lidStore({ '111': '628111' }));+ await svc.ingest('sess', { waStatusId: 'l4', contactJid: '[email protected]', type: 'text', postedAt: Date.now() });++ const out = await svc.listByContact('sess', '111@lid');+ expect(out).toHaveLength(1);+ expect(out[0].contact.id).toBe('[email protected]');+ });++ 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(+ repository,+ storageService,+ fakeConfigService(),+ lidStore({ '628111': '628999' }),+ );+ await svc.ingest('sess', { waStatusId: 'l5', contactJid: '[email protected]', type: 'text', postedAt: Date.now() });++ const out = await svc.list('sess');+ expect(out[0].contact.id).toBe('[email protected]');+ });});describe('StatusStoreService.purgeExpired', () => {diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex 441bd4cf6..2f5adf1eb 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -145,7 +145,10 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {}row.mediaOmitted = true;- row.omitReason = media.omitted ? 'engine_omitted' : 'over_cap';+ // A blob the engine skipped precisely because the caller tightened the cap below it (the status+ // seed's pre-gate) is over the STORE's cap — keep the reason truthful on both arrival paths.+ row.omitReason =+ sizeBytes !== undefined && sizeBytes > maxBytes ? 'over_cap' : media.omitted ? 'engine_omitted' : 'over_cap';}// Reads exclude already-expired rows: WhatsApp hides a status the moment its 24h are up, but the@@ -166,6 +169,10 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {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`);}const rows = await this.repository.find({@@ -178,9 +185,12 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {/*** 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.+ * the contact's rows into one group. Only @lid inputs go through the map — its keys are raw digit+ * strings, so resolving a phone-shaped JID could collide with an unrelated lid. Unknown or+ * known-unresolved lids stay as-is.*/private canonicalContactJid(jid: string): string {+ if (!jid.endsWith('@lid')) return jid;const phone = this.lidMappingStore?.getCached(userPart(jid));return phone ? `${phone}@c.us` : jid;}diff --git a/src/modules/status/dto/send-text-status.dto.spec.ts b/src/modules/status/dto/send-text-status.dto.spec.tsindex 8add19ae6..8a06e27b0 100644--- a/src/modules/status/dto/send-text-status.dto.spec.ts+++ b/src/modules/status/dto/send-text-status.dto.spec.ts@@ -3,6 +3,24 @@ import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';import { SendTextStatusDto } from './send-text-status.dto';+describe('SendTextStatusDto font validation (WhatsApp font enum)', () => {+ const withFont = (font: unknown) => ({ text: 'hi', font });++ it('accepts every value in the wire enum (0, 1, 2, 6–10)', async () => {+ for (const font of [0, 1, 2, 6, 7, 8, 9, 10]) {+ const errors = await validate(plainToInstance(SendTextStatusDto, withFont(font)));+ expect(errors).toHaveLength(0);+ }+ });++ it('rejects values outside the wire enum (3–5 no longer exist on it, 11+, negatives)', async () => {+ for (const font of [3, 4, 5, 11, -1]) {+ const errors = await validate(plainToInstance(SendTextStatusDto, withFont(font)));+ expect(errors.some(e => e.property === 'font')).toBe(true);+ }+ });+});+describe('SendTextStatusDto recipients validation', () => {const valid = { text: 'hi', recipients: ['[email protected]'] };diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.tsindex 253d73a26..d613fba93 100644--- a/src/modules/status/dto/send-text-status.dto.ts+++ b/src/modules/status/dto/send-text-status.dto.ts@@ -1,4 +1,4 @@-import { IsString, IsOptional, IsInt, Min, Max, Matches, MaxLength, IsArray, ArrayMaxSize } from 'class-validator';+import { IsString, IsOptional, IsInt, IsIn, Matches, MaxLength, IsArray, ArrayMaxSize } from 'class-validator';import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';import { ToStrictNumber } from '../../../common/utils/strict-boolean';@@ -14,12 +14,17 @@ export class SendTextStatusDto {@Matches(/^#[0-9A-Fa-f]{6}$/, { message: 'backgroundColor must be a hex color (e.g., #25D366)' })backgroundColor?: string;- @ApiPropertyOptional({ description: 'Font family index (0–5).', example: 0, minimum: 0, maximum: 5 })+ @ApiPropertyOptional({+ description:+ 'Font family index from the WhatsApp status font enum: 0 (default), 1, 2, 6 (bold), 7, 8, 9, ' ++ 'or 10. whatsapp-web.js honors only 0–7 and clamps anything above to the default.',+ example: 0,+ enum: [0, 1, 2, 6, 7, 8, 9, 10],+ })@ToStrictNumber()@IsOptional()@IsInt()- @Min(0)- @Max(5)+ @IsIn([0, 1, 2, 6, 7, 8, 9, 10])font?: number;@ApiPropertyOptional({