Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(messages): archive chat media to the file store, retrievable after delivery
Yudhi Armyndharis0047cea14513
diff --git a/.env.example b/.env.exampleindex 869cc176c..edded5c24 100644--- a/.env.example+++ b/.env.example@@ -356,6 +356,21 @@ WEBHOOK_SSRF_PROTECT=true# it is deleted. Non-positive/garbage values fall back to the defaults.# STATUS_ORPHAN_SWEEP_INTERVAL_MS=3600000 # default 1h# STATUS_ORPHAN_GRACE_MS=3600000 # default 1h+# Chat-media archiving (opt-in). When enabled, each message's media is also written to the file+# store (local or S3) and served by GET /sessions/:id/messages/:chatId/:messageId/media, so it stays+# retrievable after delivery. The inline base64 copy on the message row is KEPT, so archiving+# roughly doubles storage for media under the cap — hence off by default.+# CHAT_MEDIA_ARCHIVE_ENABLED=false # default false+# Per-file cap on archived chat media. Media above it is simply not archived; the message row and+# its inline copy are unaffected. A non-positive/garbage value falls back.+# CHAT_MEDIA_ARCHIVE_MAX_BYTES=26214400 # default 25 MiB+# How long archived files are kept, in days. 0 = forever. Expiry clears the FILE and the row's+# media columns; the message row itself is never deleted by this.+# CHAT_MEDIA_ARCHIVE_TTL_DAYS=0 # default 0 (keep forever)+# Orphaned chat-media reconciliation: how often the sweep re-lists chat-media files to find ones no+# row references (crash leftovers), and how long a file must be seen unreferenced before deletion.+# CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS=3600000 # default 1h+# CHAT_MEDIA_ORPHAN_GRACE_MS=3600000 # default 1h# Cap on the final rendered text of a send-template request (after variable substitution). Over-cap# renders are rejected with 400, never silently truncated. A non-positive/garbage value falls back.# TEMPLATE_RENDER_MAX_CHARS=65536 # default 64 KiBdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 85b846809..dbad45d86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Chat media can now be archived to the file store and fetched back after delivery, via+ `GET /api/sessions/:sessionId/messages/:chatId/:messageId/media`.** Media has always been+ persisted as base64 inline on the message row, which makes it part of every row read and ties its+ lifetime to the row; there was no way to keep the file itself, put it on S3, or age it out on its+ own schedule. With `CHAT_MEDIA_ARCHIVE_ENABLED=true` each inbound message's media is additionally+ written through `StorageService` — local disk or S3, whichever is configured — and the row records+ where it went (`mediaPath`, `mediaMimetype`; a data-connection migration adds both).++ Opt-in and off by default, because the inline copy is deliberately **kept**: the dashboard renders+ from it and removing it would change the message response shape. Archiving therefore roughly+ doubles storage for media under `CHAT_MEDIA_ARCHIVE_MAX_BYTES` (25 MiB default), which is the+ trade for being able to retrieve, relocate, and expire the file independently.+ `CHAT_MEDIA_ARCHIVE_TTL_DAYS` (0 = forever) expires the archived **file** and clears the row's+ pointers; the message row itself is never deleted by retention. An hourly reconciliation sweep+ reaps archive files no row references, scoped to the `chat-media/` prefix so it can never touch+ status media sharing the same bucket. Writing is fire-and-forget off the receive path — a storage+ outage delays nothing and drops no messages. The download is served as an attachment with a+ conservative inert `Content-Type`, so an archived document (or an `image/svg+xml`) cannot render+ as active content on the API origin. Available in all five SDKs as `messages.media(...)`.++ With the flag off, behaviour is unchanged except that message responses carry two additional+ always-null fields, and no sweeps are scheduled.+### Fixed- **A crash mid-enqueue can no longer deliver a webhook twice.** The webhook producer passed a jobdiff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 0c3ed0433..127063e70 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -218,6 +218,8 @@ erDiagramjson metadatavarchar statustimestamp created_at+ varchar media_path+ varchar media_mimetype}API_KEY {@@ -410,7 +412,9 @@ CREATE TABLE messages (timestamp BIGINT, -- WhatsApp epoch seconds; read back as a JS numbermetadata JSONB,status VARCHAR NOT NULL DEFAULT 'sent', -- pending | sent | delivered | read | failed- created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ media_path VARCHAR, -- nullable; storage key of the archived media copy+ media_mimetype VARCHAR -- nullable; mimetype of that archived copy);-- Indexes (declared on the entity)diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 6738680c4..798e7603f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -926,6 +926,40 @@ Returns a bare array of `MessageReaction`:**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error+#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media++Download a message's **archived** media bytes.++This is the read side of chat-media archiving, which is **opt-in and off by default**+(`CHAT_MEDIA_ARCHIVE_ENABLED`). When enabled, each inbound message's media is written to whatever+backs `StorageService` (local disk or S3) in addition to the inline base64 copy the message row+already carries, so it stays retrievable after delivery. With archiving off, this route answers+`404` for every message.++**Auth:** API key++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| sessionId | string | Session ID |+| chatId | string | Chat ID containing the message |+| messageId | string | WhatsApp message ID whose media to download |++**Response** `200` — the raw media bytes as the response body, served as an **attachment**+(`Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`). `Content-Type` is the stored+mimetype when it is in a conservative inert set (common image/video/audio types) and+`application/octet-stream` otherwise — a document, or an `image/svg+xml`, is never served as active+content on the API origin.++**Errors:** `401` missing/invalid API key, or key not scoped to this session · `404`+`No archived media for this message` — archiving was off when the message arrived, the message+carries no media, the media was above `CHAT_MEDIA_ARCHIVE_MAX_BYTES`, or+`CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention has since cleared the file++Note: this is a three-path-segment route, so it never collides with the two-segment+`GET /messages/:chatId/history` regardless of declaration order.+#### GET /api/sessions/:sessionId/messages/batch/:batchIdGet the processing status and progress of a bulk batch.diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex f9dd98a41..5738f5474 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -255,6 +255,16 @@ curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/true_62812345678-H "X-API-Key: $API_KEY"```+#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media++Download a message's archived media. Requires `CHAT_MEDIA_ARCHIVE_ENABLED=true` to have been set+when the message arrived; `404` otherwise.++```bash+curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/[email protected]_3EB0ABCD/media" \+ -H "X-API-Key: $API_KEY" -o media.bin+```+#### GET /api/sessions/:sessionId/messages/batch/:batchIdGet the status and progress of a bulk batch.diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 417ede487..d7c6ad222 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -29,7 +29,7 @@ All five SDKs expose the same fluent surface:| Resource | Methods || --- | --- || `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, sendBulk, batchStatus, cancelBatch |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock || `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode || `webhooks` | list, get, create, update, delete, test |diff --git a/openapi.json b/openapi.jsonindex 4368ad85c..51ff603f7 100644--- a/openapi.json+++ b/openapi.json@@ -2061,6 +2061,52 @@]}},+ "/api/sessions/{sessionId}/messages/{chatId}/{messageId}/media": {+ "get": {+ "operationId": "MessageController_getChatMedia",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "chatId",+ "required": true,+ "in": "path",+ "description": "Chat ID containing the message",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "messageId",+ "required": true,+ "in": "path",+ "description": "WhatsApp message ID whose media to download",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "The archived media bytes, served as an attachment."+ },+ "404": {+ "description": "Nothing archived for this message — archiving was off when it arrived, the message carries no media, the media was above the archive cap, or retention has since cleared it."+ }+ },+ "summary": "Download a message’s archived media",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/delete": {"post": {"operationId": "MessageController_deleteMessage",diff --git a/sdk/README.md b/sdk/README.mdindex 8ce431d5f..6faf03eaa 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -25,7 +25,7 @@ All five SDKs expose the same fluent resource surface:| Resource | Methods || ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |-| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, sendBulk, batchStatus, cancelBatch |+| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock || `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode || `webhooks` | list, get, create, update, delete, test |diff --git a/sdk/go/messages.go b/sdk/go/messages.goindex f1b2cbd74..bd77e12cb 100644--- a/sdk/go/messages.go+++ b/sdk/go/messages.go@@ -137,6 +137,18 @@ func (s *MessagesService) Reactions(ctx context.Context, sessionID, chatID, messreturn out, err}+// Media fetches a message's archived media bytes. The server answers 404 when+// nothing is archived for the message (archiving off when it arrived, no media,+// over the archive cap, or cleared by retention).+func (s *MessagesService) Media(ctx context.Context, sessionID, chatID, messageID string) (*MessageMedia, error) {+ path := s.base(sessionID) + "/" + pathEscape(chatID) + "/" + pathEscape(messageID) + "/media"+ data, contentType, err := s.client.doRaw(ctx, "GET", path, nil, nil)+ if err != nil {+ return nil, err+ }+ return &MessageMedia{Data: data, ContentType: contentType}, nil+}+// SendBulk queues a batch of messages.func (s *MessagesService) SendBulk(ctx context.Context, sessionID string, body SendBulkRequest) (*BulkMessageResponse, error) {var out BulkMessageResponsediff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goindex 7b274a0da..1813d57e1 100644--- a/sdk/go/routing_test.go+++ b/sdk/go/routing_test.go@@ -91,6 +91,7 @@ func TestRouting(t *testing.T) {{"Status.List", func(c *Client) { c.Status.List(ctx, "s1") }, "GET", "/api/sessions/s1/status"},{"Status.FromContact", func(c *Client) { c.Status.FromContact(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/status/u1"},+ {"Messages.Media", func(c *Client) { c.Messages.Media(ctx, "s1", "c1", "m1") }, "GET", "/api/sessions/s1/messages/c1/m1/media"},{"Status.Media", func(c *Client) { c.Status.Media(ctx, "s1", "st1") }, "GET", "/api/sessions/s1/status/st1/media"},{"Status.SendText", func(c *Client) { c.Status.SendText(ctx, "s1", SendTextStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-text"},{"Status.SendImage", func(c *Client) { c.Status.SendImage(ctx, "s1", SendImageStatusRequest{}) }, "POST", "/api/sessions/s1/status/send-image"},diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 08048cadd..f7610d83a 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -319,3 +319,10 @@ type BatchStatusResponse struct {StartedAt string `json:"startedAt,omitempty"`CompletedAt string `json:"completedAt,omitempty"`}++// MessageMedia is a message's archived media: the raw bytes plus the served+// content type. Non-JSON on the wire, like StatusMedia.+type MessageMedia struct {+ Data []byte+ ContentType string+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex 0c698ab79..03bb39b9c 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -3,6 +3,7 @@ package com.rmyndharis.openwa.resources;import static com.rmyndharis.openwa.http.Http.encodeSegment;import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.http.BinaryResponse;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.BatchStatusResponse;import com.rmyndharis.openwa.model.BulkMessageResponse;@@ -185,6 +186,22 @@ public final class MessagesResource {ChatHistoryMessage.class);}+ /**+ * Fetch a message's archived media bytes (404 when nothing is archived for it).+ */+ public BinaryResponse media(String sessionId, String chatId, String messageId) {+ return client.requestBytes(+ HttpMethod.GET,+ "/api/sessions/"+ + encodeSegment(sessionId)+ + "/messages/"+ + encodeSegment(chatId)+ + "/"+ + encodeSegment(messageId)+ + "/media",+ null);+ }+/** Get reactions for a specific message. */public List<ReactionRecord> reactions(String sessionId, String chatId, String messageId) {return client.requestList(diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.javaindex 0326a5768..803584218 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java@@ -1,10 +1,12 @@package com.rmyndharis.openwa.resources;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;import com.rmyndharis.openwa.ClientConfig;import com.rmyndharis.openwa.OpenWAClient;+import com.rmyndharis.openwa.http.BinaryResponse;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.BulkMessageContent;import com.rmyndharis.openwa.model.BulkMessageItem;@@ -25,7 +27,9 @@ import com.rmyndharis.openwa.model.SendPollRequest;import com.rmyndharis.openwa.model.SendTemplateRequest;import com.rmyndharis.openwa.model.SendTextRequest;import com.rmyndharis.openwa.support.MockTransport;+import java.nio.charset.StandardCharsets;import java.util.List;+import java.util.Map;import org.junit.jupiter.api.Test;class MessagesResourceTest {@@ -261,4 +265,17 @@ class MessagesResourceTest {assertEquals("http://h/api/sessions/s/messages/batch/b1/cancel", tx.lastRequest().url());assertEquals(HttpMethod.POST, tx.lastRequest().method());}++ @Test+ void mediaReturnsArchivedBytes() {+ tx.respondRaw(+ 200,+ "PNG_BYTES".getBytes(StandardCharsets.UTF_8),+ Map.of("content-type", List.of("image/png")));+ BinaryResponse media = client.messages.media("s", "c1", "m1");+ assertEquals("http://h/api/sessions/s/messages/c1/m1/media", tx.lastRequest().url());+ assertEquals(HttpMethod.GET, tx.lastRequest().method());+ assertArrayEquals("PNG_BYTES".getBytes(StandardCharsets.UTF_8), media.data());+ assertEquals("image/png", media.contentType());+ }}diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex 7ef4ffedd..2b4abd877 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -7,6 +7,7 @@*/import { encodeSegment } from '../http.js';+import type { BinaryResponse } from '../http.js';import type { OpenWAClient } from '../client.js';import type {BatchStatusResponse,@@ -177,6 +178,17 @@ export class MessagesResource {});}+ /**+ * Fetch a message's archived media bytes. Requires chat-media archiving to have been enabled on+ * the gateway when the message arrived; 404 otherwise.+ */+ media(sessionId: string, chatId: string, messageId: string): Promise<BinaryResponse> {+ return this.client.requestBytes({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/messages/${encodeSegment(chatId)}/${encodeSegment(messageId)}/media`,+ });+ }+/*** Send a batch of messages asynchronously. Returns HTTP 202 with a batch id;* poll the status via {@link batchStatus}.diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.tsindex f30d3370c..95937c553 100644--- a/sdk/javascript/test/resources.test.ts+++ b/sdk/javascript/test/resources.test.ts@@ -215,6 +215,17 @@ describe('StatusResource — nested media bodies', () => {expect(t.lastCall!.body).toEqual({ video: { url: 'http://vid' }, recipients: ['[email protected]'] });});+ it('message media fetches the archived bytes with their content type', async () => {+ const t = new MockTransport().on('GET', /\/messages\/c1\/m1\/media$/, {+ text: 'PNG_BYTES',+ contentType: 'image/png',+ });+ const res = await client(t).messages.media('s', 'c1', 'm1');+ expect(t.lastCall!.method).toBe('GET');+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/messages/c1/m1/media');+ expect(res.contentType).toBe('image/png');+ });+it('media fetches the stored status bytes with their content type', async () => {const t = new MockTransport().on('GET', /\/status\/w1\/media$/, { text: 'PNG_BYTES', contentType: 'image/png' });const res = await client(t).status.media('s', 'w1');diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 10c6932a1..3b52dab6d 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -163,6 +163,16 @@ class MessagesResourcereturn $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($chatId)}/{$this->http->encodeSegment($messageId)}/reactions") ?? [];}+ /**+ * Fetch a message's archived media bytes (404 when nothing is archived for it).+ *+ * @return array{data: string, contentType: ?string}+ */+ public function media(string $sessionId, string $chatId, string $messageId): array+ {+ return $this->http->requestBinary('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($chatId)}/{$this->http->encodeSegment($messageId)}/media");+ }+/** @return array<string,mixed> */public function sendBulk(string $sessionId, array $body): array{diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpindex 0ea84ef9c..f57bc387c 100644--- a/sdk/php/tests/ResourcesTest.php+++ b/sdk/php/tests/ResourcesTest.php@@ -256,6 +256,18 @@ class ResourcesTest extends TestCase$this->assertSame(['video' => ['url' => 'http://vid'], 'recipients' => ['[email protected]']], $backend->lastCall()['body']);}+ public function testMessageMediaReturnsArchivedBytes(): void+ {+ $backend = (new MockBackend())->onRaw(200, 'PNG_BYTES', ['Content-Type' => 'image/png']);+ $client = $backend->makeClient();+ $media = $client->messages->media('s', 'c1', 'm1');+ $call = $backend->lastCall();+ $this->assertSame('GET', $call['method']);+ $this->assertSame('/api/sessions/s/messages/c1/m1/media', $call['path']);+ $this->assertSame('PNG_BYTES', $media['data']);+ $this->assertSame('image/png', $media['contentType']);+ }+public function testStatusMediaReturnsStoredBytes(): void{$backend = (new MockBackend())->onRaw(200, 'PNG_BYTES', ['Content-Type' => 'image/png']);diff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex 73e8278bb..642cce1fe 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKINGfrom .._http import quote_segmentfrom ..types import (+ MessageMedia,BatchStatusResponse,BulkMessageResponse,ChatHistoryMessage,@@ -107,6 +108,14 @@ class MessagesResource:"GET", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/{quote_segment(message_id)}/reactions")+ def media(self, session_id: str, chat_id: str, message_id: str) -> MessageMedia:+ """Fetch a message's archived media bytes (404 when nothing is archived for it)."""+ data, content_type = self._http.request_bytes(+ "GET",+ f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(chat_id)}/{quote_segment(message_id)}/media",+ )+ return {"data": data, "contentType": content_type}+def send_bulk(self, session_id: str, body: SendBulkRequest) -> BulkMessageResponse:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-bulk", body=body)diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex efb9c7dd1..d35f23e79 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -630,6 +630,13 @@ class StatusMedia(TypedDict):contentType: str | None+class MessageMedia(TypedDict):+ """A message's archived media file: raw bytes plus the served content type."""++ data: bytes+ contentType: str | None++class SendTextStatusRequest(TypedDict, total=False):# text always required; recipients required on the Baileys engine only.text: strdiff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 822a74e25..eb05f026e 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -497,6 +497,14 @@ class TestStatus:client.status.send_video("s", {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]})assert backend.calls[-1].body == {"video": {"url": "http://vid"}, "recipients": ["[email protected]"]}+ def test_message_media_fetches_archived_bytes(self):+ backend = MockBackend()+ backend.fallback = lambda _: httpx.Response(200, content=b"PNG_BYTES", headers={"content-type": "image/png"})+ res = make_client(backend).messages.media("s", "c1", "m1")+ assert backend.last_call.method == "GET"+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/messages/c1/m1/media"+ assert res == {"data": b"PNG_BYTES", "contentType": "image/png"}+def test_media_fetches_stored_status_bytes(self):backend = MockBackend()backend.fallback = lambda _: httpx.Response(200, content=b"PNG_BYTES", headers={"content-type": "image/png"})diff --git a/src/app.module.ts b/src/app.module.tsindex c57625eea..a0f752aaa 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -33,6 +33,7 @@ import { StatsModule } from './modules/stats/stats.module';import { MetricsModule } from './modules/metrics/metrics.module';import { StatusModule } from './modules/status/status.module';import { StatusStoreModule } from './modules/status-store/status-store.module';+import { ChatMediaModule } from './modules/chat-media/chat-media.module';import { CatalogModule } from './modules/catalog/catalog.module';import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';@@ -293,6 +294,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {MetricsModule, // Prometheus /api/metricsStatusModule, // Phase 3: Status/Stories APIStatusStoreModule, // Phase 3: inbound status/story TTL store (24h purge + media persistence)+ ChatMediaModule, // opt-in chat-media archive (retention purge + orphan sweep)CatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins APIAgentToolsModule, // Agent-invocable tool registry (protocol-neutral)diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex d486fec15..d57fb1e51 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -364,6 +364,36 @@ export default () => ({})(),},+ // Chat-media archiving (opt-in): a copy of each message's media in the file store, addressable+ // after delivery. Independent of the inline base64 the message row already carries.+ chatMedia: {+ // Off by default: archiving doubles storage for media under the cap, since the inline copy stays.+ archiveEnabled: process.env.CHAT_MEDIA_ARCHIVE_ENABLED === 'true',+ // Per-file cap on archived chat media (default 25 MiB). Media above it is simply not archived —+ // the message row and its inline copy are unaffected.+ maxBytes: (() => {+ const n = parseInt(process.env.CHAT_MEDIA_ARCHIVE_MAX_BYTES ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 25 * 1024 * 1024;+ })(),+ // How long an archived file is kept, in days. 0 (the default) means forever. Unlike statuses,+ // chat messages have no WhatsApp-side expiry, so retention is purely an operator policy.+ ttlDays: (() => {+ const n = parseInt(process.env.CHAT_MEDIA_ARCHIVE_TTL_DAYS ?? '', 10);+ return Number.isFinite(n) && n >= 0 ? n : 0;+ })(),+ // Cadence of the reconciliation sweep that reaps chat-media files no row references (default 1h).+ orphanSweepIntervalMs: (() => {+ const n = parseInt(process.env.CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 60 * 60 * 1000;+ })(),+ // How long an unreferenced chat-media file must be observed by the sweep before deletion+ // (default 1h), so a file mid-write is never reaped.+ orphanGraceMs: (() => {+ const n = parseInt(process.env.CHAT_MEDIA_ORPHAN_GRACE_MS ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 60 * 60 * 1000;+ })(),+ },+// Message-template renderingtemplate: {// Cap on the FINAL rendered text of a send-template request (header+body+footer joined, afterdiff --git a/src/database/migrations/1785700000000-AddMessageMediaArchive.ts b/src/database/migrations/1785700000000-AddMessageMediaArchive.tsnew file mode 100644index 000000000..b2f61e0ed--- /dev/null+++ b/src/database/migrations/1785700000000-AddMessageMediaArchive.ts@@ -0,0 +1,57 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `mediaPath` and `mediaMimetype` to the `messages` table, backing the opt-in chat-media+ * archive: a copy of the message's media in the file store (local or S3), addressable after+ * delivery through `GET /sessions/:id/messages/:chatId/:messageId/media`.+ *+ * Both are NULL for every existing row and stay NULL while `CHAT_MEDIA_ARCHIVE_ENABLED` is off,+ * which is the default — the archive is additive and changes nothing about the inline base64 copy+ * the row's `metadata.media` already carries.+ *+ * `mediaMimetype` is stored alongside the path rather than read back off `metadata.media` so the+ * archive is self-describing: the read endpoint needs a Content-Type, and sourcing it from the+ * inline copy would couple the archive to a field a future retention decision may strip.+ *+ * Hand-authored because `synchronize` is off for the `data` connection on PostgreSQL (and optional+ * on SQLite via DATABASE_SYNCHRONIZE=false). Idempotent: probes for the column first.+ *+ * NOTE: the existence check deliberately avoids `queryRunner.getTable('messages')` — since the FTS+ * migration added the STORED generated column `body_ts`, loading that table's metadata on Postgres+ * sends TypeORM looking for `typeorm_metadata`, which nothing in this migration context creates.+ * A raw dialect-aware probe sidesteps it (same reasoning as AddMessageAuthor).+ */+export class AddMessageMediaArchive1785700000000 implements MigrationInterface {+ name = 'AddMessageMediaArchive1785700000000';++ private async hasColumn(queryRunner: QueryRunner, name: string): Promise<boolean> {+ if (queryRunner.connection.options.type === 'postgres') {+ const rows = (await queryRunner.query(+ `SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'messages' AND column_name = '${name}'`,+ )) as unknown[];+ return rows.length > 0;+ }+ const rows = (await queryRunner.query(`PRAGMA table_info("messages")`)) as Array<{ name: string }>;+ return rows.some(r => r.name === name);+ }++ public async up(queryRunner: QueryRunner): Promise<void> {+ // Probed independently so a run interrupted between the two ALTERs still completes.+ if (!(await this.hasColumn(queryRunner, 'mediaPath'))) {+ await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "mediaPath" varchar NULL`);+ }+ if (!(await this.hasColumn(queryRunner, 'mediaMimetype'))) {+ await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "mediaMimetype" varchar NULL`);+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (await this.hasColumn(queryRunner, 'mediaMimetype')) {+ await queryRunner.query(`ALTER TABLE "messages" DROP COLUMN "mediaMimetype"`);+ }+ if (await this.hasColumn(queryRunner, 'mediaPath')) {+ await queryRunner.query(`ALTER TABLE "messages" DROP COLUMN "mediaPath"`);+ }+ }+}diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.tsnew file mode 100644index 000000000..59365d797--- /dev/null+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts@@ -0,0 +1,296 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { DataSource, Repository } from 'typeorm';+import { ConfigService } from '@nestjs/config';++jest.mock('archiver', () => ({ default: jest.fn() }));++import { StorageService } from '../../common/storage/storage.service';+import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';+import { ChatMediaArchiveService, CHAT_MEDIA_PREFIX } from './chat-media-archive.service';++/** A ConfigService stub that returns each call's default unless overridden by `overrides`. */+function fakeConfigService(overrides: Record<string, unknown> = {}): ConfigService {+ return {+ get: (key: string, defaultValue?: unknown) => (key in overrides ? overrides[key] : defaultValue),+ } as unknown as ConfigService;+}++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++describe('ChatMediaArchiveService', () => {+ let baseDir: string;+ let ds: DataSource;+ let repository: Repository<Message>;+ let storageService: StorageService;++ /** Build a service whose archive flag / caps / TTL are set per-test. */+ const build = (overrides: Record<string, unknown> = {}): ChatMediaArchiveService =>+ new ChatMediaArchiveService(repository, storageService, fakeConfigService(overrides));++ const enabled = (overrides: Record<string, unknown> = {}): ChatMediaArchiveService =>+ build({ 'chatMedia.archiveEnabled': true, ...overrides });++ /** Persist a message row carrying the given inline media, as the projector would have. */+ async function saveRow(media?: Record<string, unknown>, over: Partial<Message> = {}): Promise<Message> {+ return repository.save(+ repository.create({+ sessionId: 'sess-1',+ chatId: '[email protected]',+ waMessageId: `wa-${Math.random().toString(36).slice(2)}`,+ from: '[email protected]',+ to: '[email protected]',+ body: '',+ type: 'image',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.SENT,+ timestamp: 1,+ metadata: media ? { media } : undefined,+ ...over,+ }),+ );+ }++ beforeAll(async () => {+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-chat-media-'));+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Message], synchronize: true });+ await ds.initialize();+ repository = ds.getRepository(Message);+ storageService = new StorageService(+ fakeConfigService({ 'storage.type': 'local', 'storage.localPath': path.join(baseDir, 'media') }),+ );+ });++ afterAll(async () => {+ if (ds.isInitialized) await ds.destroy();+ fs.rmSync(baseDir, { recursive: true, force: true });+ });++ afterEach(async () => {+ await repository.clear();+ for await (const file of storageService.iterateFiles('')) await storageService.deleteFile(file);+ });++ describe('archive', () => {+ it('writes the blob and points the row at it, under the chat-media prefix', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });++ const key = await enabled().archive(row);++ expect(key).toMatch(new RegExp(`^${CHAT_MEDIA_PREFIX}sess-1/[0-9a-f-]{36}\\.png$`));+ expect(await storageService.getFile(key!)).toEqual(PNG);+ const reloaded = await repository.findOneByOrFail({ id: row.id });+ expect(reloaded.mediaPath).toBe(key);+ expect(reloaded.mediaMimetype).toBe('image/png');+ });++ it('leaves the inline copy untouched — archiving is additive, not a move', async () => {+ const base64 = PNG.toString('base64');+ const row = await saveRow({ mimetype: 'image/png', data: base64 });++ await enabled().archive(row);++ const reloaded = await repository.findOneByOrFail({ id: row.id });+ expect((reloaded.metadata as { media: { data: string } }).media.data).toBe(base64);+ });++ it('does nothing at all while the archive flag is off', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });++ expect(await build().archive(row)).toBeNull();++ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ const files = [];+ for await (const f of storageService.iterateFiles('')) files.push(f);+ expect(files).toEqual([]);+ });++ it.each([+ ['no media at all', undefined],+ ['media the engine omitted', { mimetype: 'image/png', omitted: true, sizeBytes: 10 }],+ ['media with no bytes', { mimetype: 'image/png' }],+ ['media with no declared mimetype', { data: 'AAAA' }],+ ])('skips %s', async (_label, media) => {+ const row = await saveRow(media);+ expect(await enabled().archive(row)).toBeNull();+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ });++ it('skips media above the archive cap without touching the row', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });++ expect(await enabled({ 'chatMedia.maxBytes': 4 }).archive(row)).toBeNull();++ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ });++ it('swallows a storage failure so the receive path is never affected', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const put = jest.spyOn(storageService, 'putFile').mockRejectedValueOnce(new Error('disk on fire'));++ await expect(enabled().archive(row)).resolves.toBeNull();++ expect(put).toHaveBeenCalled();+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ put.mockRestore();+ });++ it('leaves the written file for the orphan sweep when the row update fails', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const update = jest.spyOn(repository, 'update').mockRejectedValueOnce(new Error('db gone'));++ await expect(enabled().archive(row)).resolves.toBeNull();++ // The file exists but no row references it — exactly the state sweepOrphanedMedia reaps.+ const files = [];+ for await (const f of storageService.iterateFiles(CHAT_MEDIA_PREFIX)) files.push(f);+ expect(files).toHaveLength(1);+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ update.mockRestore();+ });+ });++ describe('getMedia', () => {+ it('resolves an archived file by session + chat + WhatsApp message id', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const key = await enabled().archive(row);++ expect(await enabled().getMedia('sess-1', row.chatId, row.waMessageId)).toEqual({+ path: key,+ mimetype: 'image/png',+ });+ });++ it('returns null for a message with nothing archived', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ expect(await enabled().getMedia('sess-1', row.chatId, row.waMessageId)).toBeNull();+ });++ it('does not leak another session’s archived media', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ await enabled().archive(row);++ expect(await enabled().getMedia('other-sess', row.chatId, row.waMessageId)).toBeNull();+ });+ });++ describe('purgeExpired', () => {+ /** Age a row past the retention window (@CreateDateColumn ignores writes on insert). */+ const backdate = (id: string, daysAgo: number): Promise<unknown> =>+ repository.query('UPDATE messages SET createdAt = ? WHERE id = ?', [+ new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString(),+ id,+ ]);++ it('keeps everything forever when the TTL is 0', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ await enabled().archive(row);+ await backdate(row.id, 3650);++ expect(await enabled({ 'chatMedia.ttlDays': 0 }).purgeExpired(Date.now())).toBe(0);+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeTruthy();+ });++ it('deletes the expired FILE and clears the columns, but keeps the message row', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const key = await enabled().archive(row);+ await backdate(row.id, 10);++ expect(await enabled({ 'chatMedia.ttlDays': 7 }).purgeExpired(Date.now())).toBe(1);++ await expect(storageService.getFile(key!)).rejects.toThrow();+ const reloaded = await repository.findOneByOrFail({ id: row.id });+ expect(reloaded.mediaPath).toBeNull();+ expect(reloaded.mediaMimetype).toBeNull();+ // The archive expiring must not take the message history with it.+ expect(reloaded.body).toBeDefined();+ });++ it('leaves a row inside the retention window alone', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ await enabled().archive(row);+ await backdate(row.id, 2);++ expect(await enabled({ 'chatMedia.ttlDays': 7 }).purgeExpired(Date.now())).toBe(0);+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeTruthy();+ });++ it('keeps the columns when the file delete fails, so the next sweep retries', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ await enabled().archive(row);+ await backdate(row.id, 10);+ const del = jest.spyOn(storageService, 'deleteFile').mockRejectedValueOnce(new Error('s3 down'));++ expect(await enabled({ 'chatMedia.ttlDays': 7 }).purgeExpired(Date.now())).toBe(0);++ // Clearing the columns here would strand the file until the orphan sweep's grace window.+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeTruthy();+ del.mockRestore();+ });+ });++ describe('sweepOrphanedMedia', () => {+ it('deletes an unreferenced file only after the grace window has passed', async () => {+ await storageService.putFile(`${CHAT_MEDIA_PREFIX}sess-1/orphan.png`, PNG);+ const svc = enabled({ 'chatMedia.orphanGraceMs': 1000 });+ const t0 = Date.now();++ expect(await svc.sweepOrphanedMedia(t0)).toBe(0); // first sighting only records first-seen+ expect(await svc.sweepOrphanedMedia(t0 + 500)).toBe(0); // still inside the grace window+ expect(await svc.sweepOrphanedMedia(t0 + 1500)).toBe(1);++ const files = [];+ for await (const f of storageService.iterateFiles(CHAT_MEDIA_PREFIX)) files.push(f);+ expect(files).toEqual([]);+ });++ it('never reaps a file a row still references, however long it sits there', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const key = await enabled().archive(row);+ const svc = enabled({ 'chatMedia.orphanGraceMs': 0 });++ expect(await svc.sweepOrphanedMedia(Date.now())).toBe(0);+ expect(await svc.sweepOrphanedMedia(Date.now() + 1_000_000)).toBe(0);+ expect(await storageService.getFile(key!)).toEqual(PNG);+ });++ it('never touches status media — the two sweeps share one bucket', async () => {+ await storageService.putFile('statuses/sess-1/story.jpg', PNG);+ const svc = enabled({ 'chatMedia.orphanGraceMs': 0 });++ expect(await svc.sweepOrphanedMedia(Date.now())).toBe(0);+ expect(await svc.sweepOrphanedMedia(Date.now() + 1_000_000)).toBe(0);+ expect(await storageService.getFile('statuses/sess-1/story.jpg')).toEqual(PNG);+ });+ });++ describe('sweep scheduling', () => {+ it('schedules no timers while archiving is off', () => {+ const setInterval = jest.spyOn(global, 'setInterval');+ const svc = build();++ svc.onModuleInit();++ // With the archive off no row can hold a mediaPath, so both sweeps would be recurring+ // no-op walks of a store they must never touch.+ expect(setInterval).not.toHaveBeenCalled();+ svc.onModuleDestroy();+ setInterval.mockRestore();+ });++ it('schedules both sweeps once archiving is on, and clears them on destroy', () => {+ const setInterval = jest.spyOn(global, 'setInterval');+ const clearInterval = jest.spyOn(global, 'clearInterval');+ const svc = enabled();++ svc.onModuleInit();+ expect(setInterval).toHaveBeenCalledTimes(2);++ svc.onModuleDestroy();+ expect(clearInterval).toHaveBeenCalledTimes(2);+ setInterval.mockRestore();+ clearInterval.mockRestore();+ });+ });+});diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.tsnew file mode 100644index 000000000..f3ddfffb8--- /dev/null+++ b/src/modules/chat-media/chat-media-archive.service.ts@@ -0,0 +1,264 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { ConfigService } from '@nestjs/config';+import { IsNull, LessThan, Not, Repository } from 'typeorm';+import { randomUUID } from 'crypto';+import { Message } from '../message/entities/message.entity';+import { StorageService } from '../../common/storage/storage.service';+import { createLogger } from '../../common/services/logger.service';++/** Storage key prefix owned by the chat-media archive; the media bucket is shared with statuses. */+export const CHAT_MEDIA_PREFIX = 'chat-media/';++/** Default per-file cap on archived chat media. */+export const DEFAULT_ARCHIVE_MAX_BYTES = 25 * 1024 * 1024;+/** Default cadence of the orphaned-file reconciliation sweep. */+const DEFAULT_ORPHAN_SWEEP_INTERVAL_MS = 60 * 60 * 1000;+/** Default grace window before an unreferenced archive file is deleted. */+const DEFAULT_ORPHAN_GRACE_MS = 60 * 60 * 1000;+/** How often the retention purge sweeps archived files past their TTL. */+const PURGE_INTERVAL_MS = 15 * 60 * 1000;++/** Subtypes whose registered mimetype name differs from the conventional file extension. */+const MIME_SUBTYPE_EXT_OVERRIDES: Record<string, string> = { jpeg: 'jpg', quicktime: 'mov' };++/** File extension to store a blob under, derived from its mimetype; 'bin' when unrecognized. */+function extFromMimetype(mimetype: string): string {+ const subtype = mimetype.split('/')[1]?.split(';')[0]?.trim().toLowerCase();+ if (!subtype || !/^[a-z0-9]+$/.test(subtype)) return 'bin';+ return MIME_SUBTYPE_EXT_OVERRIDES[subtype] ?? subtype;+}++/** The inline media shape carried on a persisted row's `metadata.media`. */+interface InlineMedia {+ mimetype?: string;+ data?: string;+ omitted?: boolean;+ sizeBytes?: number;+}++/**+ * Archives chat-message media to the file store so it stays retrievable after delivery, independent+ * of the inline base64 copy the message row already carries.+ *+ * Opt-in (`CHAT_MEDIA_ARCHIVE_ENABLED`, default off) because it doubles storage for media under the+ * cap: the inline copy is deliberately left in place, since the dashboard renders from it and+ * stripping it would break the response contract.+ *+ * Two recurring sweeps run only while archiving is enabled: a retention purge (when+ * `CHAT_MEDIA_ARCHIVE_TTL_DAYS` is non-zero) that clears files past their TTL along with the+ * columns pointing at them, and an hourly reconciliation sweep that reaps files no row references —+ * the crash leftovers of the narrow window between a file write and its row update.+ */+@Injectable()+export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('ChatMediaArchiveService');+ private purgeTimer?: ReturnType<typeof setInterval>;+ private orphanSweepTimer?: ReturnType<typeof setInterval>;+ /** First sweep sighting (epoch ms) of each unreferenced archive file, for the grace window. */+ private readonly orphanFirstSeenAt = new Map<string, number>();++ constructor(+ @InjectRepository(Message, 'data')+ private readonly repository: Repository<Message>,+ private readonly storageService: StorageService,+ private readonly configService: ConfigService,+ ) {}++ get enabled(): boolean {+ return this.configService.get<boolean>('chatMedia.archiveEnabled', false);+ }++ onModuleInit(): void {+ // Both sweeps exist only to maintain archived files. With archiving off no row can hold a+ // mediaPath, so scheduling them would be a recurring no-op walk of the store.+ if (!this.enabled) return;++ const runPurge = (): void => {+ this.purgeExpired(Date.now()).catch(err =>+ this.logger.error('Chat media purge failed', err instanceof Error ? err.stack : String(err)),+ );+ };+ runPurge(); // sweep once at startup+ this.purgeTimer = setInterval(runPurge, PURGE_INTERVAL_MS);+ this.purgeTimer.unref?.();++ const runOrphanSweep = (): void => {+ this.sweepOrphanedMedia(Date.now()).catch(err =>+ this.logger.error('Chat media orphan sweep failed', err instanceof Error ? err.stack : String(err)),+ );+ };+ runOrphanSweep(); // the first pass only records first-seen; nothing is deleted before the grace window+ const sweepIntervalMs = this.configService.get<number>(+ 'chatMedia.orphanSweepIntervalMs',+ DEFAULT_ORPHAN_SWEEP_INTERVAL_MS,+ );+ this.orphanSweepTimer = setInterval(runOrphanSweep, sweepIntervalMs);+ this.orphanSweepTimer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.purgeTimer) clearInterval(this.purgeTimer);+ if (this.orphanSweepTimer) clearInterval(this.orphanSweepTimer);+ }++ /**+ * Archive the media of an already-persisted message row, then point the row at the stored file.+ *+ * Row-first by construction — the caller persists before calling this — so a crash mid-archive+ * leaves a consistent row whose media is simply not archived, never a row pointing at a file that+ * does not exist. The reverse window (file written, row update failed) leaves an unreferenced+ * file, which is the reconciliation sweep's job.+ *+ * Never throws: archiving is a side benefit of receiving a message, and a storage hiccup must not+ * surface on the receive path. Returns the storage key when a file was written.+ */+ async archive(row: Pick<Message, 'id' | 'sessionId' | 'metadata'>): Promise<string | null> {+ if (!this.enabled) return null;++ const media = (row.metadata as { media?: InlineMedia } | null | undefined)?.media;+ if (!media?.data || media.omitted || !media.mimetype) return null;++ const maxBytes = this.configService.get<number>('chatMedia.maxBytes', DEFAULT_ARCHIVE_MAX_BYTES);+ const sizeBytes = media.sizeBytes ?? Buffer.byteLength(media.data, 'base64');+ if (sizeBytes > maxBytes) return null;++ // A random key rather than the WhatsApp message id: message ids are engine-controlled strings+ // that can carry '/' (base64 id segments), which would silently nest the object and leak the+ // id into S3 keys. The row is read on the way out anyway, so nothing is gained by a derivable+ // key. Mirrors the status store.+ const key = `${CHAT_MEDIA_PREFIX}${row.sessionId}/${randomUUID()}.${extFromMimetype(media.mimetype)}`;+ try {+ await this.storageService.putFile(key, Buffer.from(media.data, 'base64'));+ } catch (error) {+ this.logger.error(+ `Failed to archive chat media for session ${row.sessionId}, message ${row.id}`,+ error instanceof Error ? error.stack : String(error),+ );+ return null;+ }++ try {+ await this.repository.update({ id: row.id }, { mediaPath: key, mediaMimetype: media.mimetype });+ } catch (error) {+ // The file exists but no row references it — an orphan the sweep reaps after its grace+ // window. The row itself stays consistent (mediaPath still null), so nothing else to undo.+ this.logger.warn(`Chat media ${key} written but the row update failed; leaving it for the orphan sweep`, {+ error: String(error),+ });+ return null;+ }+ return key;+ }++ /**+ * Resolve the archived media of one message, addressed the way the REST layer addresses messages+ * (session + chat + WhatsApp message id). Returns null when nothing is archived for it.+ */+ async getMedia(+ sessionId: string,+ chatId: string,+ waMessageId: string,+ ): Promise<{ path: string; mimetype: string } | null> {+ const row = await this.repository.findOne({ where: { sessionId, chatId, waMessageId } });+ if (!row?.mediaPath || !row.mediaMimetype) return null;+ return { path: row.mediaPath, mimetype: row.mediaMimetype };+ }++ /**+ * Delete archived files older than the configured retention, clearing the columns that point at+ * them. The message ROW survives — retention here governs the archived blob, not the message+ * history, which has its own lifecycle.+ *+ * A row whose file delete fails keeps its columns so the next sweep retries; clearing them would+ * strand the file until the orphan sweep's grace window. A missing file counts as deleted (see+ * StorageService), so an already-gone file never wedges its row. Returns the count cleared.+ */+ async purgeExpired(now: number): Promise<number> {+ const ttlDays = this.configService.get<number>('chatMedia.ttlDays', 0);+ if (ttlDays <= 0) return 0; // 0 = keep forever++ const cutoff = new Date(now - ttlDays * 24 * 60 * 60 * 1000);+ const expired = await this.repository.find({+ where: { mediaPath: Not(IsNull()), createdAt: LessThan(cutoff) },+ select: { id: true, mediaPath: true },+ });+ if (expired.length === 0) return 0;++ const clearableIds: string[] = [];+ await Promise.all(+ expired.map(async row => {+ try {+ await this.storageService.deleteFile(row.mediaPath!);+ clearableIds.push(row.id);+ } catch (err) {+ this.logger.warn(`Failed to delete expired chat media ${row.mediaPath}; keeping the row for the next sweep`, {+ error: String(err),+ });+ }+ }),+ );++ if (clearableIds.length === 0) return 0;+ // update([]) would build an empty-criteria statement; the guard above makes that unreachable.+ await this.repository.update(clearableIds, {+ mediaPath: null as unknown as undefined,+ mediaMimetype: null as unknown as undefined,+ });+ return clearableIds.length;+ }++ /**+ * Reconcile the media store with the message rows: delete `chat-media/` files no row references.+ * Scoped to that prefix — the store is shared with status media, which this sweep must never+ * touch, and the status sweep must never touch these.+ *+ * A file is deleted only after the sweep has seen it unreferenced for at least the grace window;+ * first-seen is tracked in memory, so a restart simply restarts the grace clock (fails safe) and+ * a file mid-write is never reaped. Returns the count removed.+ */+ async sweepOrphanedMedia(now: number = Date.now()): Promise<number> {+ const graceMs = this.configService.get<number>('chatMedia.orphanGraceMs', DEFAULT_ORPHAN_GRACE_MS);+ // Stream via iterateFiles: listFiles() truncates at STORAGE_LIST_MAX_FILES (a per-call DoS+ // guard, not a completeness contract), which would strand every orphan past the cap.+ const files: string[] = [];+ for await (const file of this.storageService.iterateFiles(CHAT_MEDIA_PREFIX)) {+ if (file.startsWith(CHAT_MEDIA_PREFIX)) files.push(file);+ }+ if (files.length === 0) {+ this.orphanFirstSeenAt.clear();+ return 0;+ }++ const rows = await this.repository.find({+ where: { mediaPath: Not(IsNull()) },+ select: { mediaPath: true },+ });+ const referenced = new Set(rows.map(row => row.mediaPath));++ let removed = 0;+ const present = new Set(files);+ for (const file of files) {+ if (referenced.has(file)) {+ this.orphanFirstSeenAt.delete(file);+ continue;+ }+ const firstSeenAt = this.orphanFirstSeenAt.get(file) ?? now;+ this.orphanFirstSeenAt.set(file, firstSeenAt);+ if (now - firstSeenAt < graceMs) continue;+ try {+ await this.storageService.deleteFile(file);+ this.orphanFirstSeenAt.delete(file);+ removed += 1;+ } catch (err) {+ this.logger.warn(`Failed to delete orphaned chat media ${file}`, { error: String(err) });+ }+ }+ // Drop bookkeeping for files that are gone so the map can't grow unbounded.+ for (const key of [...this.orphanFirstSeenAt.keys()]) {+ if (!present.has(key)) this.orphanFirstSeenAt.delete(key);+ }+ if (removed > 0) this.logger.log(`Chat media orphan sweep removed ${removed} file(s)`);+ return removed;+ }+}diff --git a/src/modules/chat-media/chat-media.module.ts b/src/modules/chat-media/chat-media.module.tsnew file mode 100644index 000000000..908a88181--- /dev/null+++ b/src/modules/chat-media/chat-media.module.ts@@ -0,0 +1,18 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { ConfigModule } from '@nestjs/config';+import { Message } from '../message/entities/message.entity';+import { ChatMediaArchiveService } from './chat-media-archive.service';+import { StorageModule } from '../../common/storage/storage.module';++/**+ * Standalone so both consumers can reach the archive without a cycle: SessionModule writes to it+ * from the inbound projector, MessageModule reads from it for the media endpoint, and MessageModule+ * already imports SessionModule. Mirrors StatusStoreModule, which sits in the same position.+ */+@Module({+ imports: [TypeOrmModule.forFeature([Message], 'data'), ConfigModule, StorageModule],+ providers: [ChatMediaArchiveService],+ exports: [ChatMediaArchiveService],+})+export class ChatMediaModule {}diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex d42a243ee..8321cd9ae 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -589,6 +589,40 @@ describe('InfraDataController.import/export preserves every data-DB table', () =expect(restored.author).toBe('[email protected]');});+ // Same drift, next column along. These two matter more than most: the archived media FILES ride+ // along in the storage export, so restoring rows without their pointers leaves every file+ // referenced by nothing — and the chat-media orphan sweep deletes exactly that after its grace+ // window. The loss would surface hours after a restore that reported success.+ it('restores the chat-media archive pointers on a backup→restore', async () => {+ await seedSession('s1');+ const msgRepo = ds.getRepository(Message);+ await msgRepo.save(+ msgRepo.create({+ sessionId: 's1',+ waMessageId: 'WA-M1',+ chatId: '[email protected]',+ from: '[email protected]',+ to: '[email protected]',+ body: '',+ type: 'image',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ timestamp: 1700000000,+ mediaPath: 'chat-media/s1/1f0c8f4e-0000-4000-8000-000000000000.png',+ mediaMimetype: 'image/png',+ }),+ );++ 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-M1' });+ expect(restored.mediaPath).toBe('chat-media/s1/1f0c8f4e-0000-4000-8000-000000000000.png');+ expect(restored.mediaMimetype).toBe('image/png');+ });+// 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/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex 9257d8a31..3b42f7a7a 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -50,6 +50,13 @@ export interface MessageRow {metadata: string | Record<string, unknown> | null;status: string;createdAt: string;+ /**+ * Chat-media archive pointers (nullable; added after author — keep the import list in sync).+ * Dropping these on import would leave the archived FILES restored but unreferenced, and the+ * orphan sweep would then delete them after its grace window.+ */+ mediaPath: string | null;+ mediaMimetype: string | null;/*** Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres* source (and in backups made before it was stripped) but never a real payload column: export dropsdiff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 232a6bcdd..2c42c5863 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -105,8 +105,8 @@ export const TABLE_IMPORTERS: TableImporter[] = [defineTableImporter({key: 'messages',label: 'message',- sql: `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)`,+ sql: `INSERT INTO messages (id, "sessionId", "waMessageId", "chatId", "chatName", author, "from", "to", body, type, direction, "timestamp", metadata, status, "createdAt", "mediaPath", "mediaMimetype")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)`,id: (msg: MessageRow) => msg.id,map: (msg: MessageRow) => [msg.id,@@ -126,6 +126,11 @@ export const TABLE_IMPORTERS: TableImporter[] = [msg.metadata == null ? null : typeof msg.metadata === 'string' ? msg.metadata : JSON.stringify(msg.metadata),msg.status,msg.createdAt,+ // Archives predating the chat-media columns restore to NULL, same as author above. Carrying+ // them matters because the media FILES ride along in the storage export: restoring the rows+ // without their pointers would turn every archived file into an orphan the sweep then reaps.+ msg.mediaPath ?? null,+ msg.mediaMimetype ?? null,],}),diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex f5c84a4b3..07d4daaaf 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -88,6 +88,20 @@ export class Message {@Column({ type: jsonColumnType(), nullable: true })metadata: Record<string, unknown>;+ /**+ * Storage key of this message's archived media, or null when nothing was archived — which is the+ * case for every row while `CHAT_MEDIA_ARCHIVE_ENABLED` is off (the default), for non-media+ * messages, and for media above the archive cap. Independent of the inline base64 copy in+ * `metadata.media`, which is unaffected by archiving.+ */+ @Column({ nullable: true })+ mediaPath?: string;++ /** Mimetype of the archived media, so the read endpoint can serve a Content-Type without+ * depending on the inline copy. Null whenever `mediaPath` is. */+ @Column({ nullable: true })+ mediaMimetype?: string;+@Column({type: 'varchar',default: MessageStatus.SENT,diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 5a8b54d96..eb2420452 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -1,4 +1,4 @@-import { Controller, Post, Get, Param, Body, Query, Res, HttpCode, HttpStatus } from '@nestjs/common';+import { Controller, Post, Get, Param, Body, Query, Res, HttpCode, HttpStatus, StreamableFile } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';import type { Response } from 'express';import { MessageService } from './message.service';@@ -349,6 +349,38 @@ export class MessageController {return this.messageService.getMessageReactions(sessionId, chatId, messageId);}+ // Three path segments, so it never collides with `:chatId/history` (two) regardless of+ // declaration order — Nest/Express match on segment count first.+ @Get(':chatId/:messageId/media')+ @ApiOperation({ summary: 'Download a message’s archived media' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'chatId', description: 'Chat ID containing the message' })+ @ApiParam({ name: 'messageId', description: 'WhatsApp message ID whose media to download' })+ @ApiResponse({ status: 200, description: 'The archived media bytes, served as an attachment.' })+ @ApiResponse({+ status: 404,+ description:+ 'Nothing archived for this message — archiving was off when it arrived, the message carries no ' ++ 'media, the media was above the archive cap, or retention has since cleared it.',+ })+ async getChatMedia(+ @Param('sessionId') sessionId: string,+ @Param('chatId') chatId: string,+ @Param('messageId') messageId: string,+ @Res({ passthrough: true }) res: Response,+ ): Promise<StreamableFile> {+ const { buffer, mimetype } = await this.messageService.getChatMedia(sessionId, chatId, messageId);+ // attachment + nosniff together: the mimetype is already reduced to an inert set, and forcing a+ // download means even a mistake there cannot render as active content on the API origin. The+ // dashboard renders chat media from the inline copy, so nothing depends on inline display here.+ res.set({+ 'Content-Type': mimetype,+ 'X-Content-Type-Options': 'nosniff',+ 'Content-Disposition': 'attachment',+ });+ return new StreamableFile(buffer);+ }+// ========== Delete Message ==========@Post('delete')diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.tsindex 9abbb7041..4353019be 100644--- a/src/modules/message/message.module.ts+++ b/src/modules/message/message.module.ts@@ -7,11 +7,12 @@ import { PendingMessageReaperService } from './pending-message-reaper.service';import { MessageController } from './message.controller';import { SessionModule } from '../session/session.module';import { TemplateModule } from '../template/template.module';+import { ChatMediaModule } from '../chat-media/chat-media.module';import { Message } from './entities/message.entity';import { MessageBatch } from './entities/message-batch.entity';@Module({- imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule],+ imports: [TypeOrmModule.forFeature([Message, MessageBatch], 'data'), SessionModule, TemplateModule, ChatMediaModule],controllers: [MessageController],providers: [MessageService, BulkMessageService, MessageTypeBackfillService, PendingMessageReaperService],exports: [MessageService, BulkMessageService],diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex e369ed520..18d764fa8 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1427,4 +1427,61 @@ describe('MessageService', () => {expect(repository.delete).not.toHaveBeenCalled();});});+ // ── archived chat media (read path) ───────────────────────────────++ describe('getChatMedia', () => {+ const archived = (mimetype: string) => ({+ getMedia: jest.fn().mockResolvedValue({ path: 'chat-media/sess-1/abc.bin', mimetype }),+ });+ const storage = (buffer = Buffer.from('BYTES')) => ({ getFile: jest.fn().mockResolvedValue(buffer) });++ const build = (archive: unknown, store: unknown): MessageService =>+ new MessageService(+ repository as Repository<Message>,+ sessionService as unknown as SessionService,+ engines,+ messageProjector as unknown as MessageProjector,+ hookManager as HookManager,+ templateService as unknown as TemplateService,+ lidMappingStore as unknown as LidMappingStoreService,+ undefined,+ archive as never,+ store as never,+ );++ it('serves an inert image type unchanged', async () => {+ const svc = build(archived('image/jpeg'), storage());+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).resolves.toEqual({+ buffer: Buffer.from('BYTES'),+ mimetype: 'image/jpeg',+ });+ });++ it.each([+ ['image/svg+xml', 'scriptable despite the image/ prefix'],+ ['text/html', 'a document a sender chose the type of'],+ ['application/pdf', 'renderable by the browser plugin'],+ ['application/javascript', 'outright active content'],+ ])('downgrades %s to octet-stream (%s)', async mimetype => {+ const svc = build(archived(mimetype), storage());+ const { mimetype: served } = await svc.getChatMedia('sess-1', '[email protected]', 'wa-1');+ expect(served).toBe('application/octet-stream');+ });++ it('404s when nothing is archived for the message', async () => {+ const svc = build({ getMedia: jest.fn().mockResolvedValue(null) }, storage());+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);+ });++ it('404s when the row outlived its file', async () => {+ const enoent = Object.assign(new Error('missing'), { code: 'ENOENT' });+ const svc = build(archived('image/png'), { getFile: jest.fn().mockRejectedValue(enoent) });+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);+ });++ it('does not swallow a genuine storage fault as a 404', async () => {+ const svc = build(archived('image/png'), { getFile: jest.fn().mockRejectedValue(new Error('S3 500')) });+ await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow('S3 500');+ });+ });});diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 185b76675..a632f4e4b 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -1,4 +1,4 @@-import { Injectable, BadRequestException, Optional } from '@nestjs/common';+import { Injectable, BadRequestException, NotFoundException, Optional } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';@@ -20,6 +20,8 @@ import { parseWaId } from '../../engine/identity/wa-id';import { resolveFeatureFlags } from '../../config/feature-flags';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';+import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';+import { StorageService } from '../../common/storage/storage.service';export interface GetMessagesOptions {chatId?: string;@@ -32,6 +34,19 @@ export interface GetMessagesOptions {/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;+/**+ * Mimetypes an archived chat-media file may be served as. Everything else — documents, and notably+ * `image/svg+xml`, which is scriptable despite the `image/` prefix — is served as inert+ * octet-stream so the media endpoint cannot host active content on the API origin.+ */+const INERT_MEDIA_MIMETYPE =+ /^(image\/(jpeg|png|gif|webp|bmp)|video\/(mp4|webm|quicktime|3gpp)|audio\/(mpeg|mp4|ogg|aac|wav|webm))(;|$)/;++/** The declared mimetype when it is safe to echo back, else inert octet-stream. */+function inertMimetype(mimetype: string): string {+ return INERT_MEDIA_MIMETYPE.test(mimetype) ? mimetype : 'application/octet-stream';+}+/*** Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.*@@ -62,6 +77,12 @@ export class MessageService {private readonly lidMappingStore: LidMappingStoreService,@Optional()private readonly configService?: ConfigService,+ // Optional so the existing standalone constructions keep working; absent means the archive+ // read endpoint reports "nothing archived", which is also what a disabled archive reports.+ @Optional()+ private readonly chatMediaArchive?: ChatMediaArchiveService,+ @Optional()+ private readonly storageService?: StorageService,) {}async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {@@ -695,6 +716,36 @@ export class MessageService {return engine.getMessageReactions(chatId, messageId);}+ /**+ * Read a message's archived media back out of the file store.+ *+ * Unlike status media (only ever an image or video), chat media includes documents a sender chose+ * the type of — so the declared mimetype is echoed back only when it is inert, and the caller+ * serves the result as an attachment regardless. Both matter: an allow-list alone would still let+ * `image/svg+xml` through as active content on the API origin.+ */+ async getChatMedia(+ sessionId: string,+ chatId: string,+ messageId: string,+ ): Promise<{ buffer: Buffer; mimetype: string }> {+ const media = await this.chatMediaArchive?.getMedia(sessionId, chatId, messageId);+ if (!media || !this.storageService) {+ throw new NotFoundException('No archived media for this message');+ }+ try {+ const buffer = await this.storageService.getFile(media.path);+ return { buffer, mimetype: inertMimetype(media.mimetype) };+ } catch (error) {+ // The row outlived its file: the retention purge (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('No archived media for this message');+ }+ throw error;+ }+ }+/** Maximum messages a single getChatHistory call may request from the engine. */private static readonly MAX_CHAT_HISTORY_LIMIT = 100;diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 6fdc60eba..37f143480 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -10,6 +10,7 @@ import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';import { StatusStoreService } from '../status-store/status-store.service';+import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';import { SessionLidResolver } from './session-lid-resolver.service';import type { IncomingMessage, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';@@ -211,6 +212,7 @@ describe('MessageProjector (inbound projection)', () => {let hookManager: { execute: jest.Mock };let statusStore: { ingest: jest.Mock };let lidResolver: { resolveSenderPhone: jest.Mock };+ let chatMediaArchive: { archive: jest.Mock };const SESSION_ID = 'session-1';@@ -250,6 +252,7 @@ describe('MessageProjector (inbound projection)', () => {hookManager = { execute: jest.fn((_event: string, data: unknown) => Promise.resolve({ continue: true, data })) };statusStore = { ingest: jest.fn().mockResolvedValue({ row: {}, created: false }) };lidResolver = { resolveSenderPhone: jest.fn().mockResolvedValue(null) };+ chatMediaArchive = { archive: jest.fn().mockResolvedValue(null) };const module: TestingModule = await Test.createTestingModule({providers: [@@ -265,6 +268,7 @@ describe('MessageProjector (inbound projection)', () => {{ provide: StatusStoreService, useValue: statusStore },{ provide: SessionLidResolver, useValue: lidResolver },{ provide: ConfigService, useValue: { get: jest.fn() } },+ { provide: ChatMediaArchiveService, useValue: chatMediaArchive },],}).compile();@@ -349,5 +353,47 @@ describe('MessageProjector (inbound projection)', () => {expect(statusStore.ingest).toHaveBeenCalledTimes(1);expect(messageRepository.insert).not.toHaveBeenCalled();});++ describe('chat-media archiving', () => {+ it('hands the persisted row to the archive', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ // The row, not the engine message: the archive updates by row id, which only the+ // persisted entity carries.+ expect(chatMediaArchive.archive).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: SESSION_ID, chatId: '[email protected]' }),+ );+ });++ it('does not archive when the insert never landed', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ // A transient non-unique failure: the row has no id, so there is nothing to point at a file.+ messageRepository.insert.mockRejectedValueOnce(new Error('SQLITE_BUSY'));++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ expect(chatMediaArchive.archive).not.toHaveBeenCalled();+ // Fail-open is unchanged: a real message is still dispatched on a transient DB fault.+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.received', expect.anything());+ });++ it('keeps delivering when archiving rejects — storage must never break the receive path', async () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ chatMediaArchive.archive.mockRejectedValueOnce(new Error('bucket unreachable'));++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.received', expect.anything());+ expect(eventsGateway.emitMessage).toHaveBeenCalledWith(SESSION_ID, expect.anything());+ });+ });});});diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex bc1a824d6..cf84b92b8 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -14,6 +14,7 @@ import { persistHistoryMessages } from './message-history-projector';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';import { resolveFeatureFlags } from '../../config/feature-flags';import { StatusStoreService } from '../status-store/status-store.service';+import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';import { buildIncomingStatus } from '../status-store/incoming-status';import type { StatusUpdate } from '../status-store/entities/status-update.entity';import {@@ -100,6 +101,10 @@ export class MessageProjector {private readonly lidResolver: SessionLidResolver,@Optional()private readonly configService?: ConfigService,+ // Optional so the projector can still be constructed standalone (specs, and any wiring that+ // predates the archive). Absent simply means inbound media is not archived.+ @Optional()+ private readonly chatMediaArchive?: ChatMediaArchiveService,) {this.mutationProjector = new MessageMutationProjector(this.messageRepository,@@ -315,6 +320,11 @@ export class MessageProjector {{ sessionId: id, source: 'SessionService' },).catch(() => undefined);++ // Fire-and-forget for the same reason as the hook above: the receive path must not wait on+ // storage. Gated on `persisted` because the archive updates the row by id, and on a failed+ // insert there is no row to point at the file. A no-op unless archiving is enabled.+ void this.chatMediaArchive?.archive(dbMessage).catch(() => undefined);}// Dispatch to webhooks with potentially modified messagediff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex a55718a35..7a7dff395 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -11,11 +11,12 @@ import { SessionErrorStore } from './session-error-store.service';import { SessionController } from './session.controller';import { WebhookModule } from '../webhook/webhook.module';import { StatusStoreModule } from '../status-store/status-store.module';+import { ChatMediaModule } from '../chat-media/chat-media.module';@Module({- // WebhookModule/StatusStoreModule do not import SessionModule back, so the dependency is- // one-directional — no forwardRef() needed.- imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule],+ // WebhookModule/StatusStoreModule/ChatMediaModule do not import SessionModule back, so the+ // dependency is one-directional — no forwardRef() needed.+ imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule, ChatMediaModule],controllers: [SessionController],providers: [SessionService,