Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(status): harden status ingest, webhooks, and the dashboard Status tab

Yudhi Armyndharisd42db9c18299
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a0ffeb7c..905bbb983 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **New opt-in `status.received` webhook.** Subscribe a webhook to `status.received` to be notified
when a contact posts a status; the payload carries the contact, type, caption, and media flags (no
- media blob — fetch it from the media endpoint). Off by default.
+ media blob — fetch it from the media endpoint). Off by default, though a webhook subscribed to `*`
+ (all events) receives it automatically.
- **The dashboard Status tab is now functional.** It lists contacts with active statuses, opens a
read-only viewer for a contact's updates (image and video), and can post a text or image status,
@@ -27,8 +28,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
incoming message with the sender's name — coloured per participant and shown once per consecutive
run — so a thread is no longer an anonymous wall of text. One-to-one chats are unchanged.
+### Changed
+
+- **Status `recipients` is now optional on the post-status endpoints.** `POST
+ /sessions/:id/status/send-text`, `send-image`, and `send-video` accept an omitted or empty
+ `recipients` list. The Baileys engine still requires it — it posts to exactly that allow-list, so
+ an absent/empty list now 400s there with a clear message — while whatsapp-web.js, which broadcasts
+ to the account's status-privacy audience and always ignored the field, no longer needs a
+ placeholder recipient to pass validation.
+
### Fixed
+- **Contact statuses now actually ingest on the Baileys engine.** The message mapper only lifted the
+ sender's `participant` into `author` for group chats, so a status broadcast — whose chat is the
+ `status@broadcast` pseudo-JID, not a group — lost its poster, failed poster resolution, and was
+ silently dropped before reaching the 24h store. On a Baileys session the status list stayed empty
+ and `status.received` never fired. The poster is now mapped for status broadcasts too.
+
+- **`status.received` no longer fires twice for the same status.** The webhook now dispatches only
+ when ingest actually inserts a new row; a duplicate delivery (an engine re-emit after a
+ reconnect) or a lost insert race resolves the pre-existing row without re-notifying consumers.
+
+- **The status seed skips own and already-expired statuses, and survives a bad item.** The
+ connect-time backfill no longer ingests the account's own active statuses as if a contact had
+ posted them, skips statuses already past their 24-hour TTL, and one item's ingest failure no
+ longer aborts the rest of the backfill.
+
+- **Expired statuses disappear from the API immediately instead of at the next purge.** The status
+ list, per-contact list, and media endpoints now filter out rows past their 24-hour expiry rather
+ than serving them until the 15-minute purge sweep reaps them.
+
+- **Status media is served with a sanitized Content-Type.** The stored mimetype comes from
+ sender-controlled message metadata; anything outside `image/*` / `video/*` is now served as
+ `application/octet-stream` with `X-Content-Type-Options: nosniff`, so the media endpoint can't be
+ turned into active content on the API origin.
+
+- **The status viewer plays a contact's story in the right order.** Items were rendered newest-first
+ while the pane scrolls to the bottom on open, so the viewer opened on the oldest status and read
+ backwards; items are now oldest-first with the newest at the scroll position. Composing is also
+ blocked until the engine type has loaded, so a Baileys post can no longer go out without
+ recipients.
+
- **`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
@@ -45,6 +85,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`withSafeFetch` now cancels unread bodies before tearing down the connection; callers that already
stream the body (media / plugin downloads) are unchanged.
+- **Expired status media now 404s instead of 500ing when the purge races a stream.** A `GET
+ /sessions/:id/status/:statusId/media` landing in the sub-second window where the 24h purge deletes
+ the backing file mid-request previously surfaced a generic 500; a missing file now maps to the
+ same 404 as an unknown or omitted status.
+
+- **A lost status-ingest race no longer leaks an orphaned media file.** When two concurrent ingests
+ of the same status (e.g. the connect-time seed racing a live event) both wrote a media file before
+ the unique constraint settled the winner, the loser's file was referenced by no row and could
+ never be purged. The loser now deletes its own file before returning the winner's row.
+
+- **Status tab polish.** The retired Phase-1 aggregate status row no longer stacks above the
+ per-contact list; the statuses query waits for the Status tab instead of firing on every session
+ select; and picking an image file then immediately switching to a URL no longer lets the
+ late-arriving file bytes override the URL.
+
## [0.10.8] - 2026-07-23
### Added
diff --git a/dashboard/src/hooks/useContactStatuses.ts b/dashboard/src/hooks/useContactStatuses.ts
index b5a64e067..d10271627 100644
--- a/dashboard/src/hooks/useContactStatuses.ts
+++ b/dashboard/src/hooks/useContactStatuses.ts
@@ -1,10 +1,13 @@
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
import { sessionApi, type StatusUpdate } from '../services/api';
-export function useContactStatuses(sessionId: string | null): UseQueryResult<StatusUpdate[], Error> {
+export function useContactStatuses(
+ sessionId: string | null,
+ enabled = true,
+): UseQueryResult<StatusUpdate[], Error> {
return useQuery<StatusUpdate[], Error>({
queryKey: ['contact-statuses', sessionId],
queryFn: async () => (await sessionApi.getContactStatuses(sessionId!)).statuses,
- enabled: Boolean(sessionId),
+ enabled: Boolean(sessionId) && enabled,
});
}
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 51838eb94..a51783d3a 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -226,8 +226,9 @@ export function Chats() {
const channelMessages = useChannelMessages(selectedSessionId, activeChannel?.id ?? null);
// Status tab: both engines expose stored status content, so this query isn't engine-gated (unlike
- // channelsQuery above).
- const statusesQuery = useContactStatuses(selectedSessionId);
+ // channelsQuery above) — but it is tab-gated the same way, so selecting a session on another tab
+ // doesn't fire a background /status fetch nobody is looking at.
+ const statusesQuery = useContactStatuses(selectedSessionId, activeTab === 'status');
// A channel feed opens at its newest post, mirroring the chat room's initial scroll. The pane is
// also keyed by channel id, so switching channels remounts the feed instead of reusing the DOM
@@ -264,6 +265,9 @@ export function Chats() {
const [composeRecipientSearch, setComposeRecipientSearch] = useState<string>('');
const [composePosting, setComposePosting] = useState<boolean>(false);
const composeFileInputRef = useRef<HTMLInputElement | null>(null);
+ // Monotonic token invalidating an in-flight FileReader: picking a file reads asynchronously, and
+ // a URL edit (or form reset) before `onload` fires must win over the late-arriving file bytes.
+ const composeImageReadSeq = useRef(0);
// Sourced only while the modal is actually open on Baileys — no reason to fetch the full contact
// list on wwjs (no picker) or before the user has opened compose.
@@ -279,6 +283,7 @@ export function Chats() {
);
const resetComposeForm = useCallback(() => {
+ composeImageReadSeq.current += 1;
setComposeType('text');
setComposeText('');
setComposeBgColor('');
@@ -301,6 +306,7 @@ export function Chats() {
};
const handleComposeImageUrlChange = (value: string) => {
+ composeImageReadSeq.current += 1;
setComposeImageUrl(value);
if (value) {
setComposeImageBase64(null);
@@ -312,8 +318,11 @@ export function Chats() {
const file = e.target.files?.[0];
if (!file) return;
setComposeImageUrl('');
+ const myRead = ++composeImageReadSeq.current;
const reader = new FileReader();
reader.onload = event => {
+ // A URL edit or form reset since the read started supersedes these bytes — drop them.
+ if (composeImageReadSeq.current !== myRead) return;
// The backend's stripBase64DataUri unwraps a `data:...;base64,` prefix, so passing the raw
// data URL through as `base64` is safe — no need to slice it ourselves.
setComposeImageBase64(event.target?.result as string);
@@ -324,6 +333,9 @@ export function Chats() {
const composeCanSubmit =
Boolean(selectedSessionId) &&
!composePosting &&
+ // The engine type decides whether recipients are required (Baileys) or omitted (wwjs) — while
+ // it's still unknown, a Baileys submit would go out with no recipients and 400.
+ Boolean(currentEngine.data) &&
(composeType === 'text' ? composeText.trim().length > 0 : Boolean(composeImageBase64 || composeImageUrl.trim())) &&
(!isBaileysEngine || composeRecipients.length > 0);
@@ -331,12 +343,10 @@ export function Chats() {
if (!selectedSessionId || !composeCanSubmit) return;
setComposePosting(true);
try {
- // whatsapp-web.js ignores `recipients` entirely (it broadcasts to status@broadcast and only
- // logs a one-time warning if the field is non-empty), but the backend DTO still requires a
- // non-empty, JID-shaped array on every engine (SendTextStatusDto/SendImageStatusDto:
- // @ArrayMinSize(1), no @IsOptional) — an empty array 400s regardless of engine. The picker is
- // hidden on wwjs since it has no effect there; this placeholder just keeps the request valid.
- const recipients = isBaileysEngine ? composeRecipients : ['[email protected]'];
+ // whatsapp-web.js ignores `recipients` entirely (it broadcasts to status@broadcast), so none
+ // are sent — the backend DTO treats the list as optional and only the Baileys engine requires
+ // (and honors) it. The picker is hidden on wwjs since it has no effect there.
+ const recipients = isBaileysEngine ? composeRecipients : undefined;
if (composeType === 'text') {
await sessionApi.postTextStatus(selectedSessionId, composeText.trim(), recipients, {
backgroundColor: composeBgColor || undefined,
@@ -1116,8 +1126,6 @@ export function Chats() {
// Chats tab: real conversations. Channel/status-kind rows are hidden here and surfaced on their
// own tabs instead.
const filteredChats = chats.filter(c => c.kind !== 'channel' && c.kind !== 'status' && searchMatch(c));
- // Status tab: the wwjs aggregate status@broadcast row, if getChats returned one.
- const statusChats = chats.filter(c => c.kind === 'status' && searchMatch(c));
// Channels tab: same search box, filtered client-side like the other two tabs. The zero-state
// ("not subscribed to any channels") stays keyed on the unfiltered list below, so a non-matching
@@ -1127,8 +1135,10 @@ export function Chats() {
ch => ch.name.toLowerCase().includes(searchQueryLower) || ch.id.toLowerCase().includes(searchQueryLower),
);
- // Status tab: group the flat status list by contact (one row per contact, newest status first
- // within each group), newest-contact-first across groups, filtered by the same search box.
+ // Status tab: group the flat status list by contact (one row per contact), newest-contact-first
+ // across groups, filtered by the same search box. The store returns statuses newest-first
+ // (postedAt DESC); each group's items are flipped to oldest-first so the viewer reads like a
+ // WhatsApp story — newest at the bottom, where the viewer's open-at-newest scroll lands.
// A plain const (not useMemo) mirrors filteredChats/filteredChannels above — statusesQuery.data
// is already a stable, query-cached reference, so re-grouping on every render is cheap.
const byStatusContact = new Map<string, ContactStatusGroup>();
@@ -1141,6 +1151,7 @@ export function Chats() {
byStatusContact.set(item.contact.id, { contact: item.contact, items: [item], latest: item.timestamp });
}
}
+ for (const group of byStatusContact.values()) group.items.reverse();
const groupedStatuses = Array.from(byStatusContact.values())
.filter(
g =>
@@ -1369,12 +1380,10 @@ export function Chats() {
</div>
)}
- {/* Status list — the wwjs status@broadcast aggregate row, if present, followed by the
- per-contact status groups read from the store. Not engine-gated: both engines now
- have status content. */}
+ {/* Status list — per-contact status groups read from the 24h store. Not engine-gated:
+ both engines now have status content. */}
{activeTab === 'status' && (
<div className="chats-list">
- {statusChats.map(renderChatRow)}
{statusesQuery.isLoading ? (
<div className="chats-list-loading">
<Loader2 className="animate-spin" size={24} />
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index f27e12d9f..d1b954d6d 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -683,7 +683,12 @@ export const sessionApi = {
getContactStatuses: (id: string) => request<{ statuses: StatusUpdate[] }>(`/sessions/${id}/status`),
getStatusMediaBlob: (id: string, statusId: string) =>
requestBlob(`/sessions/${id}/status/${encodeURIComponent(statusId)}/media`),
- postTextStatus: (id: string, text: string, recipients: string[], extra?: { backgroundColor?: string; font?: number }) =>
+ postTextStatus: (
+ id: string,
+ text: string,
+ recipients?: string[],
+ extra?: { backgroundColor?: string; font?: number },
+ ) =>
request(`/sessions/${id}/status/send-text`, {
method: 'POST',
body: JSON.stringify({ text, recipients, ...extra }),
@@ -691,7 +696,7 @@ export const sessionApi = {
postImageStatus: (
id: string,
image: { url?: string; base64?: string; mimetype?: string },
- recipients: string[],
+ recipients?: string[],
caption?: string,
) =>
request(`/sessions/${id}/status/send-image`, {
diff --git a/openapi.json b/openapi.json
index a07b451d6..113059e81 100644
--- a/openapi.json
+++ b/openapi.json
@@ -7547,11 +7547,10 @@
"maximum": 5
},
"recipients": {
- "description": "Recipient JIDs (1–256). WhatsApp Status is not posted to a group — use @c.us or @lid individuals. Honored on the Baileys engine only: whatsapp-web.js ignores this allow-list and broadcasts to the account's status-privacy audience.",
+ "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.",
"example": [
],
- "minItems": 1,
"maxItems": 256,
"type": "array",
"items": {
@@ -7560,8 +7559,7 @@
}
},
"required": [
- "text",
- "recipients"
+ "text"
]
},
"StatusMediaInput": {
@@ -7602,11 +7600,10 @@
"maxLength": 1024
},
"recipients": {
- "description": "Recipient JIDs (1–256), @c.us or @lid. Honored on the Baileys engine only: whatsapp-web.js ignores this allow-list and broadcasts to the account's status-privacy audience.",
+ "description": "Recipient JIDs (0–256), @c.us or @lid. 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.",
"example": [
],
- "minItems": 1,
"maxItems": 256,
"type": "array",
"items": {
@@ -7615,8 +7612,7 @@
}
},
"required": [
- "image",
- "recipients"
+ "image"
]
},
"SendVideoStatusDto": {
@@ -7637,11 +7633,10 @@
"maxLength": 1024
},
"recipients": {
- "description": "Recipient JIDs (1–256), @c.us or @lid. Honored on the Baileys engine only: whatsapp-web.js ignores this allow-list and broadcasts to the account's status-privacy audience.",
+ "description": "Recipient JIDs (0–256), @c.us or @lid. 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.",
"example": [
],
- "minItems": 1,
"maxItems": 256,
"type": "array",
"items": {
@@ -7650,8 +7645,7 @@
}
},
"required": [
- "video",
- "recipients"
+ "video"
]
},
"SendProductDto": {
diff --git a/sdk/go/types_status.go b/sdk/go/types_status.go
index 53620e612..b332d71f7 100644
--- a/sdk/go/types_status.go
+++ b/sdk/go/types_status.go
@@ -39,10 +39,11 @@ type StatusResult struct {
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
-// SendTextStatusRequest posts a text status. Recipients is required.
+// SendTextStatusRequest posts a text status. Recipients is required on the Baileys
+// engine only (absent/empty → 400 there); whatsapp-web.js ignores it — leave nil.
type SendTextStatusRequest struct {
Text string `json:"text"`
- Recipients []string `json:"recipients"`
+ Recipients []string `json:"recipients,omitempty"`
BackgroundColor string `json:"backgroundColor,omitempty"`
Font *int `json:"font,omitempty"`
}
@@ -55,15 +56,17 @@ type StatusMediaInput struct {
}
// SendImageStatusRequest posts an image status (nested {image:{...}} body).
+// Recipients: required on the Baileys engine only; omit on whatsapp-web.js.
type SendImageStatusRequest struct {
Image StatusMediaInput `json:"image"`
- Recipients []string `json:"recipients"`
+ Recipients []string `json:"recipients,omitempty"`
Caption string `json:"caption,omitempty"`
}
// SendVideoStatusRequest posts a video status (nested {video:{...}} body).
+// Recipients: required on the Baileys engine only; omit on whatsapp-web.js.
type SendVideoStatusRequest struct {
Video StatusMediaInput `json:"video"`
- Recipients []string `json:"recipients"`
+ Recipients []string `json:"recipients,omitempty"`
Caption string `json:"caption,omitempty"`
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendImageStatusRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendImageStatusRequest.java
index 38176c9e2..ea5d288d5 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendImageStatusRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendImageStatusRequest.java
@@ -19,7 +19,7 @@ public record SendImageStatusRequest(StatusMediaInput image, List<String> recipi
return this;
}
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
public Builder recipients(List<String> v) {
this.recipients = v;
return this;
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextStatusRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextStatusRequest.java
index aa22455a8..c1e07ef8f 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextStatusRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTextStatusRequest.java
@@ -20,7 +20,7 @@ public record SendTextStatusRequest(String text, List<String> recipients, String
return this;
}
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
public Builder recipients(List<String> v) {
this.recipients = v;
return this;
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVideoStatusRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVideoStatusRequest.java
index 726d56117..b1f3d68d4 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVideoStatusRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVideoStatusRequest.java
@@ -19,7 +19,7 @@ public record SendVideoStatusRequest(StatusMediaInput video, List<String> recipi
return this;
}
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
public Builder recipients(List<String> v) {
this.recipients = v;
return this;
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 172d41881..dc1dc080e 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -612,8 +612,8 @@ export interface StatusResult {
export interface SendTextStatusRequest {
text: string;
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
- recipients: string[];
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
+ recipients?: string[];
/** Hex background color, e.g. `#25D366`. */
backgroundColor?: string;
/** Font index supported by WhatsApp status. */
@@ -631,16 +631,16 @@ export interface StatusMediaInput {
/** Server expects a nested `{ image: { url|base64 } }` body, not flat media fields. */
export interface SendImageStatusRequest {
image: StatusMediaInput;
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
- recipients: string[];
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
+ recipients?: string[];
caption?: string;
}
/** Server expects a nested `{ video: { url|base64 } }` body, not flat media fields. */
export interface SendVideoStatusRequest {
video: StatusMediaInput;
- /** Recipient JIDs the status is addressed to (required by the server; empty → 400). */
- recipients: string[];
+ /** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
+ recipients?: string[];
caption?: string;
}
diff --git a/sdk/php/src/Resources/StatusResource.php b/sdk/php/src/Resources/StatusResource.php
index 9e06e63f9..0ce65b10e 100644
--- a/sdk/php/src/Resources/StatusResource.php
+++ b/sdk/php/src/Resources/StatusResource.php
@@ -34,8 +34,9 @@ class StatusResource
}
/**
- * @param array<string,mixed> $body Body must include a required `recipients` key
- * (list<string> of recipient JIDs; empty -> 400).
+ * @param array<string,mixed> $body Body may include a `recipients` key (list<string> of JIDs).
+ * Required on the Baileys engine (absent/empty -> 400 there);
+ * ignored by whatsapp-web.js — omit it there.
* @return array<string,mixed>
*/
public function sendText(string $sessionId, array $body): array
@@ -44,8 +45,9 @@ class StatusResource
}
/**
- * @param array<string,mixed> $body Body must include a required `recipients` key
- * (list<string> of recipient JIDs; empty -> 400).
+ * @param array<string,mixed> $body Body may include a `recipients` key (list<string> of JIDs).
+ * Required on the Baileys engine (absent/empty -> 400 there);
+ * ignored by whatsapp-web.js — omit it there.
* @return array<string,mixed>
*/
public function sendImage(string $sessionId, array $body): array
@@ -54,8 +56,9 @@ class StatusResource
}
/**
- * @param array<string,mixed> $body Body must include a required `recipients` key
- * (list<string> of recipient JIDs; empty -> 400).
+ * @param array<string,mixed> $body Body may include a `recipients` key (list<string> of JIDs).
+ * Required on the Baileys engine (absent/empty -> 400 there);
+ * ignored by whatsapp-web.js — omit it there.
* @return array<string,mixed>
*/
public function sendVideo(string $sessionId, array $body): array
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 77354bac5..fb2aaa595 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -590,9 +590,9 @@ class StatusResult(TypedDict, total=False):
class SendTextStatusRequest(TypedDict, total=False):
- # text and recipients required; backgroundColor (hex, e.g. #25D366) and font optional.
+ # text always required; recipients required on the Baileys engine only.
text: str
- # Recipient JIDs the status is addressed to (required by the server; empty -> 400).
+ # Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.
recipients: list[str]
backgroundColor: str
font: int
@@ -610,7 +610,7 @@ class SendImageStatusRequest(TypedDict, total=False):
"""Server expects a nested ``{ image: { url|base64 } }`` body."""
image: StatusMediaInput
- # Recipient JIDs the status is addressed to (required by the server; empty -> 400).
+ # Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.
recipients: list[str]
caption: str
@@ -619,7 +619,7 @@ class SendVideoStatusRequest(TypedDict, total=False):
"""Server expects a nested ``{ video: { url|base64 } }`` body."""
video: StatusMediaInput
- # Recipient JIDs the status is addressed to (required by the server; empty -> 400).
+ # Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.
recipients: list[str]
caption: str
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index a2b783469..19f5f81dc 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -117,6 +117,29 @@ describe('configuration — plugin download cap is fail-safe', () => {
});
});
+describe('configuration — status media cap is fail-safe', () => {
+ const orig = process.env.STATUS_MEDIA_MAX_BYTES;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.STATUS_MEDIA_MAX_BYTES;
+ else process.env.STATUS_MEDIA_MAX_BYTES = orig;
+ });
+
+ it('uses the env value when it is a valid positive integer', () => {
+ process.env.STATUS_MEDIA_MAX_BYTES = '2097152';
+ expect(configuration().status.mediaMaxBytes).toBe(2097152);
+ });
+
+ it('falls back to the 10 MiB default when unset, empty, non-numeric, or non-positive', () => {
+ delete process.env.STATUS_MEDIA_MAX_BYTES;
+ expect(configuration().status.mediaMaxBytes).toBe(10 * 1024 * 1024);
+ // A non-positive value must NOT disable the per-file cap — it falls back to the default.
+ for (const bad of ['', 'abc', '0', '-5']) {
+ process.env.STATUS_MEDIA_MAX_BYTES = bad;
+ expect(configuration().status.mediaMaxBytes).toBe(10 * 1024 * 1024);
+ }
+ });
+});
+
describe('configuration search namespace', () => {
// Save/restore the SEARCH_* env vars so a CI .env that sets them cannot flake the default-value
// assertions below (mirrors the mutate-and-restore pattern used for PLUGIN_DOWNLOAD_MAX_BYTES etc.).
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index 2763f1dcf..1ab2cfa8a 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -199,6 +199,19 @@ describe('buildIncomingMessageFromBaileys', () => {
expect(r.isStatusBroadcast).toBe(true);
});
+ it('exposes the status poster from participant as author (status@broadcast is not a group)', () => {
+ const r = buildIncomingMessageFromBaileys({
+ ...base,
+ remoteJid: 'status@broadcast',
+ participant: '[email protected]',
+ });
+ expect(r.isStatusBroadcast).toBe(true);
+ expect(r.isGroup).toBe(false);
+ // Without this, buildIncomingStatus can only resolve the poster to the status@broadcast
+ // pseudo-JID itself and drops the status entirely.
+ expect(r.author).toBe('[email protected]');
+ });
+
it('carries the push name onto contact when present', () => {
const r = buildIncomingMessageFromBaileys({ ...base, pushName: 'Alice' });
expect(r.contact).toEqual({ pushName: 'Alice' });
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index 9bc7472ca..065cc9ad3 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -161,8 +161,8 @@ export interface BaileysIncomingFields {
/**
* Build a neutral {@link IncomingMessage} from extracted Baileys fields. The chat is always
* `remoteJid` (Baileys reports the conversation directly); `fromMe` only flips from/to. The group
- * sender lives in `participant` (exposed as `author`), matching the wwjs convention where `from`
- * is the group JID.
+ * sender — and likewise the poster of a status broadcast — lives in `participant` (exposed as
+ * `author`), matching the wwjs convention where `from` is the group JID / broadcast channel.
*/
export function buildIncomingMessageFromBaileys(
fields: BaileysIncomingFields,
@@ -191,7 +191,11 @@ export function buildIncomingMessageFromBaileys(
isStatusBroadcast,
};
- if (isGroup && fields.participant) {
+ // The sender behind a group message — or the poster behind a status broadcast — lives in
+ // `participant` (exposed as `author`), matching the wwjs convention where `from` is the group JID
+ // (or the shared status@broadcast channel). Without the status arm, buildIncomingStatus can only
+ // resolve the poster to the pseudo-JID itself and drops every Baileys status.
+ if ((isGroup || isStatusBroadcast) && fields.participant) {
incoming.author = normalizeJid(fields.participant);
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 3f9cbd55b..ab72a1e8e 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -111,6 +111,7 @@ import { CallNotFoundError } from '../../common/errors/call-not-found.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
+import { BadRequestException } from '@nestjs/common';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
const fakeStore = {
@@ -911,6 +912,31 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(msg).toMatchObject({ id: 'IN1', body: 'hi there', type: 'text', fromMe: false });
});
+ it('routes a status broadcast to onMessage with the poster in author (so the status store can ingest it)', async () => {
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ // A contact's status: remoteJid is the shared channel, the poster is in participant.
+ key: { remoteJid: 'status@broadcast', participant: '[email protected]', fromMe: false, id: 'ST1' },
+ message: { conversation: 'my status' },
+ messageTimestamp: 1700000002,
+ pushName: 'Alice',
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { id: string; author?: string; isStatusBroadcast: boolean };
+ // Regression lock: buildIncomingStatus needs author to resolve the poster — without it the
+ // status resolves to the status@broadcast pseudo-JID and is dropped before ingest.
+ expect(msg).toMatchObject({ id: 'ST1', isStatusBroadcast: true, author: '[email protected]' });
+ });
+
it('extracts coordinates from an ephemeral (disappearing) location message', async () => {
const onMessage = jest.fn();
const adapter = newAdapter();
@@ -3211,6 +3237,13 @@ describe('BaileysAdapter status posting', () => {
);
});
+ it('postStatus rejects an absent/empty recipients list with a 400 (Baileys posts to exactly the allow-list)', async () => {
+ const adapter = await ready();
+ await expect(adapter.postTextStatus('hello', {})).rejects.toBeInstanceOf(BadRequestException);
+ await expect(adapter.postTextStatus('hello', { recipients: [] })).rejects.toBeInstanceOf(BadRequestException);
+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();
+ });
+
it('deleteStatus revokes by constructing the key from statusId (no store lookup)', async () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'STATUS1' } });
const adapter = await ready();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 2d9967553..3aa5bfa23 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -46,6 +46,7 @@ import {
StatusPostOptions,
} from '../interfaces/whatsapp-engine.interface';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
+import { BadRequestException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
@@ -2071,6 +2072,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
*/
private async postStatus(content: AnyMessageContent, options: StatusPostOptions): Promise<StatusResult> {
this.ensureReady();
+ // Baileys posts to exactly the statusJidList allow-list, so unlike whatsapp-web.js (which
+ // broadcasts) an absent/empty recipients list would publish to nobody — reject it as a client
+ // error here rather than send a status no contact can see.
+ if (!options.recipients?.length) {
+ throw new BadRequestException('recipients is required to post a status on the Baileys engine');
+ }
const statusJidList = options.recipients.map(r => this.sessionStore.toEngineJid(r));
const sent = await this.sock!.sendMessage('status@broadcast', content, {
statusJidList,
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index d41d60825..53c9f0936 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -264,8 +264,12 @@ export interface Status {
}
export interface StatusPostOptions {
- /** REQUIRED. Neutral JIDs (@c.us / @lid) permitted to see the status. Maps to Baileys statusJidList. */
- recipients: string[];
+ /**
+ * Neutral JIDs (@c.us / @lid) permitted to see the status. Maps to Baileys statusJidList.
+ * REQUIRED on the Baileys engine (it rejects an absent/empty list with a 400); ignored by
+ * whatsapp-web.js, which broadcasts to the account's status-privacy audience.
+ */
+ recipients?: string[];
/** Hex background colour (#RRGGBB). Text status only. */
backgroundColor?: string;
/** Font index. Text status only. */
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 742eed58f..1272c10ee 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -167,7 +167,8 @@ describe('SessionService', () => {
};
statusStore = {
- ingest: jest.fn().mockResolvedValue({}),
+ // Default: nothing freshly inserted (callers only dispatch status.received on created=true).
+ ingest: jest.fn().mockResolvedValue({ row: {}, created: false }),
};
const module: TestingModule = await Test.createTestingModule({
@@ -2210,17 +2211,20 @@ describe('SessionService', () => {
expect(dispatchedEvents('message.received')).toHaveLength(0);
});
- it('dispatches status.received with the ingested row once ingest resolves', async () => {
+ it('dispatches status.received with the ingested row once ingest resolves with created=true', async () => {
const callbacks = await startAndCaptureCallbacks();
(statusStore.ingest as jest.Mock).mockResolvedValueOnce({
- waStatusId: 'st1',
- contactJid: '[email protected]',
- contactName: 'Alice',
- type: 'text',
- caption: 'hi',
- mediaOmitted: false,
- postedAt: 1000,
- expiresAt: 1000 + 86400000,
+ created: true,
+ row: {
+ waStatusId: 'st1',
+ contactJid: '[email protected]',
+ contactName: 'Alice',
+ type: 'text',
+ caption: 'hi',
+ mediaOmitted: false,
+ postedAt: 1000,
+ expiresAt: 1000 + 86400000,
+ },
});
callbacks.onMessage!(
@@ -2253,6 +2257,30 @@ describe('SessionService', () => {
);
});
+ 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({
+ created: false,
+ row: { waStatusId: 'st1', contactJid: '[email protected]' },
+ });
+
+ callbacks.onMessage!(
+ makeMessage({
+ id: 'st1',
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ fromMe: false,
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
+ }),
+ );
+ await flush();
+
+ expect(dispatchedEvents('status.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();
@@ -2604,6 +2632,7 @@ describe('SessionService', () => {
it('seeds the status store from the status-broadcast chat history when the engine reports ready', async () => {
const callbacks = await startAndCaptureCallbacks();
+ const nowSec = Math.floor(Date.now() / 1000);
mockEngine.getChatHistory.mockResolvedValue([
makeMessage({
id: 'st-a',
@@ -2614,7 +2643,7 @@ describe('SessionService', () => {
kind: 'status',
type: 'text',
body: 'hi',
- timestamp: 1700000000,
+ timestamp: nowSec,
contact: { id: '[email protected]', name: 'Alice', pushName: 'Ali' },
}),
makeMessage({
@@ -2626,7 +2655,7 @@ describe('SessionService', () => {
kind: 'status',
type: 'image',
body: '',
- timestamp: 1700000001,
+ timestamp: nowSec + 1,
}),
// Poster resolves to the shared pseudo-JID → buildIncomingStatus returns null → never ingested.
makeMessage({
@@ -2637,6 +2666,7 @@ describe('SessionService', () => {
author: 'status@broadcast',
kind: 'status',
type: 'text',
+ timestamp: nowSec + 2,
}),
]);
// st-b's message carries no cached contact name; the seed resolves it via getContactById.
@@ -2674,7 +2704,7 @@ describe('SessionService', () => {
contactPushName: 'Ali',
type: 'text',
caption: 'hi',
- postedAt: 1700000000000,
+ postedAt: nowSec * 1000,
}),
);
// st-b had no cached name, so the seed backfilled it from getContactById.
@@ -2707,7 +2737,7 @@ describe('SessionService', () => {
kind: 'status',
type: 'image',
body: '',
- timestamp: 1700000002,
+ timestamp: Math.floor(Date.now() / 1000),
media,
}),
]);
@@ -2721,6 +2751,73 @@ describe('SessionService', () => {
);
});
+ it('skips the account’s own (fromMe) statuses and statuses older than 24h when seeding', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const nowSec = Math.floor(Date.now() / 1000);
+ mockEngine.getChatHistory.mockResolvedValue([
+ // Own active status echoed in the broadcast chat — mirrors the live path's fromMe drop.
+ makeMessage({
+ id: 'st-own',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ fromMe: true,
+ kind: 'status',
+ type: 'text',
+ timestamp: nowSec,
+ }),
+ // 25 hours old — past the 24h TTL, gone from WhatsApp clients already.
+ makeMessage({
+ id: 'st-old',
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author: '[email protected]',
+ kind: 'status',
+ type: 'text',
+ timestamp: nowSec - 25 * 60 * 60,
+ }),
+ ]);
+
+ callbacks.onReady!('628123', 'Alice');
+ await flush();
+
+ expect(statusStore.ingest).not.toHaveBeenCalled();
+ });
+
+ it('keeps seeding the remaining statuses when one item’s ingest fails', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ const nowSec = Math.floor(Date.now() / 1000);
+ const seedItem = (id: string, author: string) =>
+ makeMessage({
+ id,
+ from: 'status@broadcast',
+ chatId: 'status@broadcast',
+ isStatusBroadcast: true,
+ author,
+ kind: 'status',
+ type: 'text',
+ timestamp: nowSec,
+ });
+ mockEngine.getChatHistory.mockResolvedValue([
+ seedItem('st-fail', '[email protected]'),
+ seedItem('st-ok', '[email protected]'),
+ ]);
+ (statusStore.ingest as jest.Mock)
+ .mockRejectedValueOnce(new Error('database is locked'))
+ .mockResolvedValueOnce({ row: {}, created: true });
+
+ callbacks.onReady!('628123', 'Alice');
+ await flush();
+
+ expect(statusStore.ingest).toHaveBeenCalledTimes(2);
+ expect(statusStore.ingest).toHaveBeenNthCalledWith(
+ 2,
+ 'sess-uuid-1',
+ expect.objectContaining({ waStatusId: 'st-ok' }),
+ );
+ });
+
it('swallows a status-history failure on ready (e.g. Baileys has no status chat) without throwing', async () => {
const callbacks = await startAndCaptureCallbacks();
mockEngine.getChatHistory.mockRejectedValue(new Error('not supported'));
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 8daa69ea5..bd34e2152 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 { StatusStoreService } from '../status-store/status-store.service';
+import { 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 {
@@ -693,14 +693,29 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return resolved;
};
for (const msg of messages) {
- const status = buildIncomingStatus(msg);
- if (!status) continue;
- if (!status.contactName && !status.contactPushName) {
- const poster = await resolvePoster(status.contactJid);
- status.contactName = poster.name;
- status.contactPushName = poster.pushName;
+ try {
+ // Mirrors the live path's own-send drop: the broadcast chat's history also contains the
+ // account's OWN active statuses, which must not come back as if a contact had posted them.
+ if (msg.fromMe) continue;
+ // A status whose 24h already ran out is hidden by WhatsApp and would only live until the
+ // next purge sweep — don't backfill it (its media was downloaded by getChatHistory
+ // regardless; this just skips the row).
+ if (msg.timestamp * 1000 + STATUS_TTL_MS <= Date.now()) continue;
+ const status = buildIncomingStatus(msg);
+ if (!status) continue;
+ if (!status.contactName && !status.contactPushName) {
+ const poster = await resolvePoster(status.contactJid);
+ status.contactName = poster.name;
+ status.contactPushName = poster.pushName;
+ }
+ await this.statusStore.ingest(sessionId, status);
+ } catch (itemErr) {
+ // One bad item must not abort the whole backfill.
+ this.logger.warn('Status seed item skipped', {
+ sessionId,
+ error: itemErr instanceof Error ? itemErr.message : String(itemErr),
+ });
}
- await this.statusStore.ingest(sessionId, status);
}
} catch (err) {
this.logger.debug('Status seed skipped', {
@@ -937,7 +952,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (status) {
void this.statusStore
.ingest(id, status)
- .then(row => this.dispatchStatusReceived(id, row))
+ // Dispatch only on a fresh insert: ingest also resolves with the pre-existing row
+ // 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 }) => {
+ if (created) this.dispatchStatusReceived(id, row);
+ })
.catch(err =>
this.logger.warn('Status ingest failed', {
sessionId: id,
diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.ts
index 31ec68208..1932285c8 100644
--- a/src/modules/status-store/status-store.service.spec.ts
+++ b/src/modules/status-store/status-store.service.spec.ts
@@ -42,26 +42,28 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
fs.rmSync(baseDir, { recursive: true, force: true });
});
- it('ingest writes a text row with expiresAt = postedAt + 24h', async () => {
- const row = await service.ingest('sess', {
+ it('ingest writes a text row with expiresAt = postedAt + 24h, flagged as created', async () => {
+ const postedAt = Date.now();
+ const { row, created } = await service.ingest('sess', {
waStatusId: 'w1',
contactJid: '[email protected]',
type: 'text',
caption: 'hi',
- postedAt: 1000,
+ postedAt,
});
- expect(row.expiresAt).toBe(1000 + 24 * 60 * 60 * 1000);
+ expect(created).toBe(true);
+ expect(row.expiresAt).toBe(postedAt + 24 * 60 * 60 * 1000);
expect(row.mediaOmitted).toBe(false);
expect(row.mediaPath).toBeFalsy();
});
it('ingest persists media to a file under the cap and records mediaPath', async () => {
- const row = await service.ingest('sess', {
+ const { row } = await service.ingest('sess', {
waStatusId: 'w2',
contactJid: '[email protected]',
type: 'image',
media: { mimetype: 'image/jpeg', data: Buffer.from('x').toString('base64') },
- postedAt: 2000,
+ postedAt: Date.now(),
});
expect(row.mediaPath).toBeTruthy();
expect(row.mediaMimetype).toBe('image/jpeg');
@@ -72,12 +74,12 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
});
it('ingest marks media omitted when the engine already omitted it', async () => {
- const row = await service.ingest('sess', {
+ const { row } = await service.ingest('sess', {
waStatusId: 'w3',
contactJid: '[email protected]',
type: 'image',
media: { mimetype: 'image/jpeg', omitted: true, sizeBytes: 99 },
- postedAt: 3000,
+ postedAt: Date.now(),
});
expect(row.mediaOmitted).toBe(true);
expect(row.omitReason).toBe('engine_omitted');
@@ -85,19 +87,19 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
});
it('ingest marks media omitted when sizeBytes exceeds STATUS_MEDIA_MAX_BYTES', async () => {
- const row = await service.ingest('sess', {
+ const { row } = await service.ingest('sess', {
waStatusId: 'w4',
contactJid: '[email protected]',
type: 'image',
media: { mimetype: 'image/jpeg', data: '...', sizeBytes: 999_999_999 },
- postedAt: 4000,
+ postedAt: Date.now(),
});
expect(row.mediaOmitted).toBe(true);
expect(row.omitReason).toBe('over_cap');
expect(row.mediaPath).toBeFalsy();
});
- it('ingest is idempotent on (sessionId, waStatusId)', async () => {
+ 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', {
waStatusId: 'dup',
@@ -107,7 +109,8 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
});
const rows = await repository.find({ where: { sessionId: 'sess', waStatusId: 'dup' } });
expect(rows).toHaveLength(1);
- expect(second.id).toBe(rows[0].id);
+ expect(second.row.id).toBe(rows[0].id);
+ expect(second.created).toBe(false);
});
it('list maps rows to the Status shape newest-first, media path -> mediaUrl endpoint', async () => {
@@ -115,7 +118,7 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
expect(out[0].contact.id).toBe('[email protected]');
expect(out[0].timestamp).toBeInstanceOf(Date);
expect(out[0].expiresAt).toBeInstanceOf(Date);
- // Sorted newest (highest postedAt) first: w4 (4000) precedes w1 (1000).
+ // Sorted newest (highest postedAt) first.
const postedOrder = out.map(s => s.timestamp.getTime());
expect(postedOrder).toEqual([...postedOrder].sort((a, b) => b - a));
@@ -127,8 +130,30 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
expect(textOnly.mediaUrl).toBeUndefined();
});
+ it('list and listByContact exclude already-expired rows (the purge sweep only runs every 15 min)', async () => {
+ await service.ingest('sess', {
+ waStatusId: 'stale',
+ contactJid: '[email protected]',
+ type: 'text',
+ postedAt: Date.now() - 25 * 60 * 60 * 1000, // 25h old — past the 24h TTL
+ });
+ expect((await service.list('sess')).map(s => s.id)).not.toContain('stale');
+ expect((await service.listByContact('sess', '[email protected]')).map(s => s.id)).not.toContain('stale');
+ });
+
+ it('getMedia treats an expired row as absent (404, matching "not found or expired")', async () => {
+ await service.ingest('sess', {
+ waStatusId: 'stale-media',
+ contactJid: '[email protected]',
+ type: 'image',
+ media: { mimetype: 'image/jpeg', data: Buffer.from('old').toString('base64') },
+ postedAt: Date.now() - 25 * 60 * 60 * 1000,
+ });
+ expect(await service.getMedia('sess', 'stale-media')).toBeNull();
+ });
+
it('listByContact filters to only that contact', async () => {
- await service.ingest('sess', { waStatusId: 'w5', contactJid: '[email protected]', type: 'text', postedAt: 6000 });
+ await service.ingest('sess', { waStatusId: 'w5', contactJid: '[email protected]', type: 'text', postedAt: Date.now() });
const out = await service.listByContact('sess', '[email protected]');
expect(out).toHaveLength(1);
expect(out[0].contact.id).toBe('[email protected]');
@@ -157,7 +182,7 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
putFile: jest.fn().mockRejectedValue(new Error('disk full')),
} as unknown as StorageService;
const failingService = new StatusStoreService(repository, failingStorage, fakeConfigService());
- const row = await failingService.ingest('sess', {
+ const { row } = await failingService.ingest('sess', {
waStatusId: 'w6',
contactJid: '[email protected]',
type: 'image',
@@ -175,7 +200,7 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
storageService,
fakeConfigService({ 'status.mediaMaxBytes': 0 }),
);
- const row = await strictService.ingest('sess', {
+ const { row } = await strictService.ingest('sess', {
waStatusId: 'w7',
contactJid: '[email protected]',
type: 'image',
@@ -187,6 +212,94 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
});
});
+describe('StatusStoreService ingest race (unique-constraint loser)', () => {
+ let baseDir: string;
+ let storageService: StorageService;
+
+ beforeEach(() => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-status-race-'));
+ storageService = makeStorageService(path.join(baseDir, 'media'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ const mediaDir = (): string[] => fs.readdirSync(path.join(baseDir, 'media', 'statuses', 'sess'));
+
+ it('reaps the media file it wrote when a concurrent ingest wins the unique constraint', async () => {
+ // The winner committed its own media file; the loser must not leave a second, orphaned one.
+ fs.mkdirSync(path.join(baseDir, 'media', 'statuses', 'sess'), { recursive: true });
+ fs.writeFileSync(path.join(baseDir, 'media', 'statuses', 'sess', 'winner.jpg'), 'winner');
+ const winner = new StatusUpdate();
+ winner.mediaPath = 'statuses/sess/winner.jpg';
+ // First findOne (top of ingest) sees nothing; the post-save-failure re-read returns the winner.
+ const repo = {
+ findOne: jest.fn().mockResolvedValueOnce(null).mockResolvedValue(winner),
+ save: jest.fn().mockRejectedValue(new Error('UNIQUE constraint failed')),
+ } as unknown as Repository<StatusUpdate>;
+ const service = new StatusStoreService(repo, storageService, fakeConfigService());
+
+ const { row, created } = await service.ingest('sess', {
+ waStatusId: 'raced',
+ contactJid: '[email protected]',
+ type: 'image',
+ media: { mimetype: 'image/jpeg', data: Buffer.from('loser').toString('base64') },
+ postedAt: 1000,
+ });
+
+ expect(row).toBe(winner);
+ expect(created).toBe(false);
+ expect(mediaDir()).toEqual(['winner.jpg']);
+ });
+
+ it('reaps the file it wrote when the save fails with no winner row, then rethrows', async () => {
+ const repo = {
+ findOne: jest.fn().mockResolvedValue(null),
+ save: jest.fn().mockRejectedValue(new Error('database is locked')),
+ } as unknown as Repository<StatusUpdate>;
+ const service = new StatusStoreService(repo, storageService, fakeConfigService());
+
+ await expect(
+ service.ingest('sess', {
+ waStatusId: 'raced',
+ contactJid: '[email protected]',
+ type: 'image',
+ media: { mimetype: 'image/jpeg', data: Buffer.from('loser').toString('base64') },
+ postedAt: 1000,
+ }),
+ ).rejects.toThrow('database is locked');
+
+ expect(mediaDir()).toHaveLength(0);
+ });
+
+ it('keeps the file when the re-read row is this very insert (driver errored on a commit that landed)', async () => {
+ const repo = {
+ findOne: jest
+ .fn()
+ .mockResolvedValueOnce(null)
+ // The row that "landed" references exactly the file this ingest just wrote.
+ .mockImplementation(() => {
+ const selfRow = new StatusUpdate();
+ selfRow.mediaPath = `statuses/sess/${mediaDir()[0]}`;
+ return Promise.resolve(selfRow);
+ }),
+ save: jest.fn().mockRejectedValue(new Error('driver reported failure after commit')),
+ } as unknown as Repository<StatusUpdate>;
+ const service = new StatusStoreService(repo, storageService, fakeConfigService());
+
+ await service.ingest('sess', {
+ waStatusId: 'raced',
+ contactJid: '[email protected]',
+ type: 'image',
+ media: { mimetype: 'image/jpeg', data: Buffer.from('self').toString('base64') },
+ postedAt: 1000,
+ });
+
+ expect(mediaDir()).toHaveLength(1);
+ });
+});
+
describe('StatusStoreService.purgeExpired', () => {
let baseDir: string;
let ds: DataSource;
@@ -208,14 +321,16 @@ describe('StatusStoreService.purgeExpired', () => {
fs.rmSync(baseDir, { recursive: true, force: true });
});
- const ingestWithMedia = (waStatusId: string, postedAt: number): Promise<StatusUpdate> =>
- service.ingest('sess', {
- waStatusId,
- contactJid: '[email protected]',
- type: 'image',
- media: { mimetype: 'image/jpeg', data: Buffer.from(waStatusId).toString('base64') },
- postedAt,
- });
+ const ingestWithMedia = async (waStatusId: string, postedAt: number): Promise<StatusUpdate> =>
+ (
+ await service.ingest('sess', {
+ waStatusId,
+ contactJid: '[email protected]',
+ type: 'image',
+ media: { mimetype: 'image/jpeg', data: Buffer.from(waStatusId).toString('base64') },
+ postedAt,
+ })
+ ).row;
it('deletes expired rows and their media files, keeps live ones', async () => {
const expiredWithMedia = await ingestWithMedia('expired-media', 1000);
diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.ts
index 34ca04018..c277173a5 100644
--- a/src/modules/status-store/status-store.service.ts
+++ b/src/modules/status-store/status-store.service.ts
@@ -1,7 +1,7 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
-import { LessThan, Repository } from 'typeorm';
+import { LessThan, MoreThan, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import { StatusUpdate } from './entities/status-update.entity';
import type { IncomingStatus } from './incoming-status';
@@ -9,8 +9,9 @@ import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';
import { StorageService } from '../../common/storage/storage.service';
import { createLogger } from '../../common/services/logger.service';
-/** A status/story lives for 24h from posting, matching WhatsApp's own expiry. */
-const STATUS_TTL_MS = 24 * 60 * 60 * 1000;
+/** A status/story lives for 24h from posting, matching WhatsApp's own expiry. Exported for the
+ * session service's seed, which skips backfilling statuses that have already run out their TTL. */
+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;
@@ -57,10 +58,15 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
if (this.purgeTimer) clearInterval(this.purgeTimer);
}
- /** Insert a status row (idempotent on `(sessionId, waStatusId)`), persisting any attached media. */
- async ingest(sessionId: string, s: IncomingStatus): Promise<StatusUpdate> {
+ /**
+ * Insert a status row (idempotent on `(sessionId, waStatusId)`), persisting any attached media.
+ * `created` tells the caller whether this call actually inserted the row — false for a duplicate
+ * delivery or a lost insert race — so a once-per-status side effect (the status.received webhook)
+ * doesn't fire again for a status consumers already saw.
+ */
+ async ingest(sessionId: string, s: IncomingStatus): Promise<{ row: StatusUpdate; created: boolean }> {
const existing = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });
- if (existing) return existing;
+ if (existing) return { row: existing, created: false };
const row = new StatusUpdate();
row.sessionId = sessionId;
@@ -77,13 +83,22 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
await this.attachMedia(row, sessionId, s);
try {
- return await this.repository.save(row);
+ return { row: await this.repository.save(row), created: true };
} catch (error) {
// The unique (sessionId, waStatusId) index is the idempotency backstop for a concurrent ingest
// of the same status racing past the findOne check above; the loser re-reads and returns the
// row the winner just inserted instead of surfacing a constraint violation to the caller.
const winner = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });
- if (winner) return winner;
+ // This call's row was never saved, so the file attachMedia wrote for it (its own random key)
+ // is referenced by no row, and purgeExpired — which only sweeps expired rows' files — could
+ // never reap it. Delete it here or a lost race leaks one orphan per race. The guard skips the
+ // pathological case where the re-read row is this very insert (driver errored on a commit
+ // that landed): there the file IS the persisted row's media. deleteFile treats an
+ // already-missing file as success.
+ if (row.mediaPath && row.mediaPath !== winner?.mediaPath) {
+ await this.storageService.deleteFile(row.mediaPath).catch(() => undefined);
+ }
+ if (winner) return { row: winner, created: false };
throw error;
}
}
@@ -123,13 +138,22 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
row.omitReason = media.omitted ? 'engine_omitted' : 'over_cap';
}
+ // Reads exclude already-expired rows: WhatsApp hides a status the moment its 24h are up, but the
+ // purge sweep only reaps rows every 15 minutes — without the filter an expired status would stay
+ // visible in the gap.
async list(sessionId: string): Promise<Status[]> {
- const rows = await this.repository.find({ where: { sessionId }, order: { postedAt: 'DESC' } });
+ const rows = await this.repository.find({
+ where: { sessionId, expiresAt: MoreThan(Date.now()) },
+ order: { postedAt: 'DESC' },
+ });
return rows.map(row => this.toStatus(row));
}
async listByContact(sessionId: string, contactJid: string): Promise<Status[]> {
- const rows = await this.repository.find({ where: { sessionId, contactJid }, order: { postedAt: 'DESC' } });
+ const rows = await this.repository.find({
+ where: { sessionId, contactJid, expiresAt: MoreThan(Date.now()) },
+ order: { postedAt: 'DESC' },
+ });
return rows.map(row => this.toStatus(row));
}
@@ -151,7 +175,9 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
}
async getMedia(sessionId: string, statusId: string): Promise<{ path: string; mimetype: string } | null> {
- const row = await this.repository.findOne({ where: { sessionId, waStatusId: statusId } });
+ const row = await this.repository.findOne({
+ where: { sessionId, waStatusId: statusId, expiresAt: MoreThan(Date.now()) },
+ });
if (!row || row.mediaOmitted || !row.mediaPath || !row.mediaMimetype) return null;
return { path: row.mediaPath, mimetype: row.mediaMimetype };
}
diff --git a/src/modules/status/dto/send-media-status.dto.spec.ts b/src/modules/status/dto/send-media-status.dto.spec.ts
index 8e61aebf3..c1d3e36b3 100644
--- a/src/modules/status/dto/send-media-status.dto.spec.ts
+++ b/src/modules/status/dto/send-media-status.dto.spec.ts
@@ -11,14 +11,14 @@ describe('SendImageStatusDto recipients validation', () => {
expect(errors).toHaveLength(0);
});
- it('rejects missing recipients', async () => {
+ it('accepts missing recipients (optional — whatsapp-web.js broadcasts without them)', async () => {
const errors = await validate(plainToInstance(SendImageStatusDto, { image: valid.image }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
- it('rejects an empty recipients array (-> 400)', async () => {
+ it('accepts an empty recipients array', async () => {
const errors = await validate(plainToInstance(SendImageStatusDto, { image: valid.image, recipients: [] }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
it('rejects non-string entries', async () => {
@@ -58,14 +58,14 @@ describe('SendVideoStatusDto recipients validation', () => {
expect(errors).toHaveLength(0);
});
- it('rejects missing recipients', async () => {
+ it('accepts missing recipients (optional — whatsapp-web.js broadcasts without them)', async () => {
const errors = await validate(plainToInstance(SendVideoStatusDto, { video: valid.video }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
- it('rejects an empty recipients array (-> 400)', async () => {
+ it('accepts an empty recipients array', async () => {
const errors = await validate(plainToInstance(SendVideoStatusDto, { video: valid.video, recipients: [] }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
it('rejects non-string entries', async () => {
diff --git a/src/modules/status/dto/send-media-status.dto.ts b/src/modules/status/dto/send-media-status.dto.ts
index e6321c92c..c634017e6 100644
--- a/src/modules/status/dto/send-media-status.dto.ts
+++ b/src/modules/status/dto/send-media-status.dto.ts
@@ -3,7 +3,6 @@ import {
IsOptional,
ValidateNested,
IsArray,
- ArrayMinSize,
ArrayMaxSize,
IsDefined,
IsNotEmpty,
@@ -52,22 +51,22 @@ export class SendImageStatusDto {
@MaxLength(1024)
caption?: string;
- @ApiProperty({
+ @ApiPropertyOptional({
description:
- 'Recipient JIDs (1–256), @c.us or @lid. Honored on the Baileys engine only: whatsapp-web.js ignores ' +
- "this allow-list and broadcasts to the account's status-privacy audience.",
+ 'Recipient JIDs (0–256), @c.us or @lid. 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.',
type: String,
isArray: true,
example: ['[email protected]'],
- minItems: 1,
maxItems: 256,
})
+ @IsOptional()
@IsArray()
- @ArrayMinSize(1)
@ArrayMaxSize(256)
@IsString({ each: true })
@Matches(/^\d+@(c\.us|lid)$/, { each: true, message: 'Invalid recipient JID' })
- recipients: string[];
+ recipients?: string[];
}
export class SendVideoStatusDto {
@@ -83,20 +82,20 @@ export class SendVideoStatusDto {
@MaxLength(1024)
caption?: string;
- @ApiProperty({
+ @ApiPropertyOptional({
description:
- 'Recipient JIDs (1–256), @c.us or @lid. Honored on the Baileys engine only: whatsapp-web.js ignores ' +
- "this allow-list and broadcasts to the account's status-privacy audience.",
+ 'Recipient JIDs (0–256), @c.us or @lid. 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.',
type: String,
isArray: true,
example: ['[email protected]'],
- minItems: 1,
maxItems: 256,
})
+ @IsOptional()
@IsArray()
- @ArrayMinSize(1)
@ArrayMaxSize(256)
@IsString({ each: true })
@Matches(/^\d+@(c\.us|lid)$/, { each: true, message: 'Invalid recipient JID' })
- recipients: string[];
+ recipients?: string[];
}
diff --git a/src/modules/status/dto/send-text-status.dto.spec.ts b/src/modules/status/dto/send-text-status.dto.spec.ts
index 640a3f0a5..8add19ae6 100644
--- a/src/modules/status/dto/send-text-status.dto.spec.ts
+++ b/src/modules/status/dto/send-text-status.dto.spec.ts
@@ -11,14 +11,14 @@ describe('SendTextStatusDto recipients validation', () => {
expect(errors).toHaveLength(0);
});
- it('rejects missing recipients', async () => {
+ it('accepts missing recipients (optional — whatsapp-web.js broadcasts without them)', async () => {
const errors = await validate(plainToInstance(SendTextStatusDto, { text: 'hi' }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
- it('rejects an empty recipients array (-> 400)', async () => {
+ it('accepts an empty recipients array', async () => {
const errors = await validate(plainToInstance(SendTextStatusDto, { text: 'hi', recipients: [] }));
- expect(errors.some(e => e.property === 'recipients')).toBe(true);
+ expect(errors).toHaveLength(0);
});
it('rejects non-string entries', async () => {
diff --git a/src/modules/status/dto/send-text-status.dto.ts b/src/modules/status/dto/send-text-status.dto.ts
index c400b8027..253d73a26 100644
--- a/src/modules/status/dto/send-text-status.dto.ts
+++ b/src/modules/status/dto/send-text-status.dto.ts
@@ -1,15 +1,4 @@
-import {
- IsString,
- IsOptional,
- IsInt,
- Min,
- Max,
- Matches,
- MaxLength,
- IsArray,
- ArrayMinSize,
- ArrayMaxSize,
-} from 'class-validator';
+import { IsString, IsOptional, IsInt, Min, Max, Matches, MaxLength, IsArray, ArrayMaxSize } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ToStrictNumber } from '../../../common/utils/strict-boolean';
@@ -33,21 +22,20 @@ export class SendTextStatusDto {
@Max(5)
font?: number;
- @ApiProperty({
+ @ApiPropertyOptional({
description:
- 'Recipient JIDs (1–256). WhatsApp Status is not posted to a group — use @c.us or @lid individuals. ' +
- 'Honored on the Baileys engine only: whatsapp-web.js ignores this allow-list and broadcasts to the ' +
- "account's status-privacy audience.",
+ '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.",
type: String,
isArray: true,
example: ['[email protected]'],
- minItems: 1,
maxItems: 256,
})
+ @IsOptional()
@IsArray()
- @ArrayMinSize(1)
@ArrayMaxSize(256)
@IsString({ each: true })
@Matches(/^\d+@(c\.us|lid)$/, { each: true, message: 'Invalid recipient JID' })
- recipients: string[];
+ recipients?: string[];
}
diff --git a/src/modules/status/status.controller.ts b/src/modules/status/status.controller.ts
index 5ca61abfe..605c05ff7 100644
--- a/src/modules/status/status.controller.ts
+++ b/src/modules/status/status.controller.ts
@@ -2,7 +2,6 @@ import { Controller, Get, Post, Delete, Param, Body, Res, StreamableFile } from
import type { Response } from 'express';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { StatusService } from './status.service';
-import { StorageService } from '../../common/storage/storage.service';
import { SendTextStatusDto } from './dto/send-text-status.dto';
import { SendImageStatusDto, SendVideoStatusDto } from './dto/send-media-status.dto';
import { RequireRole } from '../auth/decorators/auth.decorators';
@@ -11,10 +10,7 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';
@ApiTags('status')
@Controller('sessions/:sessionId/status')
export class StatusController {
- constructor(
- private readonly statusService: StatusService,
- private readonly storageService: StorageService,
- ) {}
+ constructor(private readonly statusService: StatusService) {}
@Get()
@ApiOperation({ summary: 'Get all contact status updates' })
@@ -41,9 +37,8 @@ export class StatusController {
@Param('statusId') statusId: string,
@Res({ passthrough: true }) res: Response,
): Promise<StreamableFile> {
- const { path, mimetype } = await this.statusService.getStatusMedia(sessionId, statusId);
- const buffer = await this.storageService.getFile(path);
- res.set({ 'Content-Type': mimetype });
+ const { buffer, mimetype } = await this.statusService.getStatusMedia(sessionId, statusId);
+ res.set({ 'Content-Type': mimetype, 'X-Content-Type-Options': 'nosniff' });
return new StreamableFile(buffer);
}
diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.ts
index 69d229c4e..3d4679a7b 100644
--- a/src/modules/status/status.service.spec.ts
+++ b/src/modules/status/status.service.spec.ts
@@ -2,6 +2,7 @@ import { BadRequestException, NotFoundException, PayloadTooLargeException } from
import { StatusService } from './status.service';
import { SessionService } from '../session/session.service';
import { StatusStoreService } from '../status-store/status-store.service';
+import { StorageService } from '../../common/storage/storage.service';
import { HookManager } from '../../core/hooks';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
@@ -19,10 +20,12 @@ describe('StatusService media validation and selection', () => {
const passThrough = (_event: string, data: unknown) => Promise.resolve({ continue: true, data });
const hookManager = { execute: jest.fn(passThrough) };
const store = { list: jest.fn(), listByContact: jest.fn(), getMedia: jest.fn() };
+ const storageService = { getFile: jest.fn() };
const service = new StatusService(
sessionService as unknown as SessionService,
hookManager as unknown as HookManager,
store as unknown as StatusStoreService,
+ storageService as unknown as StorageService,
);
beforeEach(() => {
@@ -59,13 +62,41 @@ describe('StatusService media validation and selection', () => {
await expect(service.getStatusMedia('sess', 'w1')).rejects.toBeInstanceOf(NotFoundException);
});
- it('returns the stored path and mimetype', async () => {
+ it('returns the media bytes and mimetype', async () => {
store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.jpg', mimetype: 'image/jpeg' });
+ storageService.getFile.mockResolvedValue(Buffer.from('x'));
const media = await service.getStatusMedia('sess', 'w1');
- expect(media).toEqual({ path: 'statuses/sess/x.jpg', mimetype: 'image/jpeg' });
+ expect(media).toEqual({ buffer: Buffer.from('x'), mimetype: 'image/jpeg' });
expect(store.getMedia).toHaveBeenCalledWith('sess', 'w1');
+ expect(storageService.getFile).toHaveBeenCalledWith('statuses/sess/x.jpg');
+ });
+
+ it('maps an ENOENT from the file read to NotFoundException (purge raced the request), not a 500', async () => {
+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/gone.jpg', mimetype: 'image/jpeg' });
+ const enoent = Object.assign(new Error('no such file or directory'), { code: 'ENOENT' });
+ storageService.getFile.mockRejectedValue(enoent);
+
+ await expect(service.getStatusMedia('sess', 'w1')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('rethrows non-ENOENT storage errors unchanged', async () => {
+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.jpg', mimetype: 'image/jpeg' });
+ storageService.getFile.mockRejectedValue(new Error('S3 unavailable'));
+
+ await expect(service.getStatusMedia('sess', 'w1')).rejects.toThrow('S3 unavailable');
+ });
+
+ it('serves a sender-declared non-image/video mimetype as inert application/octet-stream', async () => {
+ // The stored mimetype comes from the sender's message metadata — never trust it as a
+ // Content-Type or the endpoint could serve active content (e.g. text/html) on the API origin.
+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.bin', mimetype: 'text/html' });
+ storageService.getFile.mockResolvedValue(Buffer.from('<script>'));
+
+ const media = await service.getStatusMedia('sess', 'w1');
+
+ expect(media.mimetype).toBe('application/octet-stream');
});
});
diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.ts
index bddd24cba..66db07ada 100644
--- a/src/modules/status/status.service.ts
+++ b/src/modules/status/status.service.ts
@@ -1,17 +1,25 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { SessionService } from '../session/session.service';
import { StatusStoreService } from '../status-store/status-store.service';
+import { StorageService } from '../../common/storage/storage.service';
import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { HookManager, applySendingGate } from '../../core/hooks';
+/** Stored status media is only ever an image or video; a sender-declared mimetype outside that is
+ * served as inert octet-stream so the media endpoint can't be turned into active content (HTML/JS)
+ * on the API origin. */
+const SAFE_STATUS_MIMETYPE = /^(image|video)\//;
+
@Injectable()
export class StatusService {
- // HookManager comes from the @Global() HooksModule, so no module import is needed here.
+ // HookManager comes from the @Global() HooksModule, StorageService from the @Global()
+ // StorageModule — neither needs a module import here.
constructor(
private readonly sessionService: SessionService,
private readonly hookManager: HookManager,
private readonly store: StatusStoreService,
+ private readonly storageService: StorageService,
) {}
/**
@@ -54,12 +62,23 @@ export class StatusService {
return this.store.listByContact(sessionId, contactId);
}
- async getStatusMedia(sessionId: string, statusId: string): Promise<{ path: string; mimetype: string }> {
+ async getStatusMedia(sessionId: string, statusId: string): Promise<{ buffer: Buffer; mimetype: string }> {
const media = await this.store.getMedia(sessionId, statusId);
if (!media) {
throw new NotFoundException('Status media not found or expired');
}
- return media;
+ try {
+ const buffer = await this.storageService.getFile(media.path);
+ const mimetype = SAFE_STATUS_MIMETYPE.test(media.mimetype) ? media.mimetype : 'application/octet-stream';
+ return { buffer, mimetype };
+ } catch (error) {
+ // The row outlived its file: purgeExpired (or a concurrent delete) removed it between the
+ // DB read and this read. That's "gone", not a server fault — surface a 404.
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ throw new NotFoundException('Status media not found or expired');
+ }
+ throw error;
+ }
}
async postTextStatus(sessionId: string, text: string, options: StatusPostOptions): Promise<StatusResult> {