Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(chat-media): archive media this account sent, behind CHAT_MEDIA_ARCHIVE_OUTBOUND

Yudhi Armyndharis0aa77082c6d8
diff --git a/.env.example b/.env.example
index 87a9161c5..7051d7c25 100644
--- a/.env.example
+++ b/.env.example
@@ -459,6 +459,10 @@ WEBHOOK_SSRF_PROTECT=true
# require archiving. The inline copy is KEPT, so archiving roughly doubles storage for media under
# the cap — hence off by default.
# CHAT_MEDIA_ARCHIVE_ENABLED=false # default false
+# Extend archiving to media this account SENT (needs CHAT_MEDIA_ARCHIVE_ENABLED=true; the retention
+# purge and orphan sweep only run while that is on). Doubles storage again for the outbound half,
+# and buys nothing for a URL-based send, whose row stores the URL rather than any bytes.
+# CHAT_MEDIA_ARCHIVE_OUTBOUND=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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b9069072c..d8e1040f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **`CHAT_MEDIA_ARCHIVE_OUTBOUND` archives media this account sent** — a sub-flag of `CHAT_MEDIA_ARCHIVE_ENABLED` (off by default), so a sent attachment gets the same durable file copy, S3 portability and TTL retention inbound media already had. Refs #1165.
+
- **Group membership requests: list, approve, reject, and a `group.join_request` event** — the join-approval queue wwebjs/Baileys both expose is now surfaced: `GET/POST .../groups/:groupId/membership-requests[/approve|/reject]` on both engines, plus a webhook/socket event when someone asks to join an administered group. Refs #1164 (discussion).
- **Own global presence: `PUT /sessions/:id/presence`** — appear online or offline on both engines; an always-online headless bot suppresses the phone's own notifications, and `available: false` hands them back. Connection-scoped (re-issue after a reconnect). Refs #871.
@@ -31,6 +33,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A URL-based send no longer discards bytes the gateway already downloaded** — merging its metadata onto the engine's own-send echo replaced that echo's real payload with the URL string, so a whatsapp-web.js URL send rendered as a bare marker after a reload.
+
- **A bulk media send lost its attachment when the engine echo won the persist race** — the batch write collided on `UNIQUE(sessionId, waMessageId)` and was swallowed into a warning, leaving only the echo's row, which on a Baileys API send carries a media-less marker; it now merges onto that row like the single-send path already did.
- **A WhatsApp Web page reload no longer kills a starting session** — a navigation landing during the first injection rejects `Client.initialize()` before whatsapp-web.js has installed its own re-inject handler, and the adapter's error channel is terminal, so one reload parked the session `FAILED` with nobody retrying (on start and on reconnect alike); the engine now retries that launch once, within the init deadline, before declaring failure.
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 4f33cbdd1..0e2d1121c 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -119,6 +119,7 @@ services:
# file has no env_file, so a variable absent from this list never reaches the container and
# the feature it gates stays off however the operator's .env is written.
- CHAT_MEDIA_ARCHIVE_ENABLED=${CHAT_MEDIA_ARCHIVE_ENABLED:-}
+ - CHAT_MEDIA_ARCHIVE_OUTBOUND=${CHAT_MEDIA_ARCHIVE_OUTBOUND:-}
- CHAT_MEDIA_ARCHIVE_MAX_BYTES=${CHAT_MEDIA_ARCHIVE_MAX_BYTES:-}
- CHAT_MEDIA_ARCHIVE_TTL_DAYS=${CHAT_MEDIA_ARCHIVE_TTL_DAYS:-}
- CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS=${CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS:-}
diff --git a/docker-compose.yml b/docker-compose.yml
index b388ca4dd..44ff79dc1 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -190,6 +190,7 @@ services:
# variable absent from this list simply never reaches the container and the feature stays off
# no matter what the operator's .env says.
- CHAT_MEDIA_ARCHIVE_ENABLED=${CHAT_MEDIA_ARCHIVE_ENABLED:-}
+ - CHAT_MEDIA_ARCHIVE_OUTBOUND=${CHAT_MEDIA_ARCHIVE_OUTBOUND:-}
- CHAT_MEDIA_ARCHIVE_MAX_BYTES=${CHAT_MEDIA_ARCHIVE_MAX_BYTES:-}
- CHAT_MEDIA_ARCHIVE_TTL_DAYS=${CHAT_MEDIA_ARCHIVE_TTL_DAYS:-}
- CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS=${CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS:-}
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 9950e417a..7fbceb21c 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1200,12 +1200,19 @@ Download a message's **stored** media bytes.
The route serves the chat-media **archive** first, and falls back to the **inline base64 copy** on
the message row when no archived file is servable. Archiving 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 copy. The inline fallback is
-what makes media **sent by this account** downloadable here — outbound messages are never archived,
-but their payload is stored inline (base64 API sends persist it on the send path; media composed on
-a linked phone is downloaded by the engine for the own-send echo). It also keeps an inbound
-message's media downloadable after `CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention purges the archived
-file, since retention leaves the inline copy in place.
+backs `StorageService` (local disk or S3) in addition to the inline copy. Media **sent by this
+account** is archived too when `CHAT_MEDIA_ARCHIVE_OUTBOUND=true` is set alongside it — off by
+default, since it doubles storage again for the outbound half.
+
+Media sent by this account is downloadable here regardless of that flag, because its payload is
+stored inline: base64 API sends persist it on the send path, and media composed on a linked phone is
+downloaded by the engine for the own-send echo. The flag buys a durable copy with its own lifecycle
+(S3 portability, TTL retention), not retrievability. A **URL-based send is the exception**: the
+gateway fetches those bytes at send time and stores none, so there is nothing to serve or archive.
+
+The inline fallback also keeps an inbound message's media downloadable after
+`CHAT_MEDIA_ARCHIVE_TTL_DAYS` retention purges the archived file, since retention leaves the inline
+copy in place.
**Auth:** API key
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 75137a7e9..67a478d4e 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -314,9 +314,9 @@ curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/unpin" \
#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media
-Download a message's stored media: the archived file when one exists
-(`CHAT_MEDIA_ARCHIVE_ENABLED=true` when the message arrived), else the inline copy on the message
-row — which covers media sent by this account; `404` when neither holds bytes.
+Download a message's stored media: the archived file when one exists (`CHAT_MEDIA_ARCHIVE_ENABLED`,
+plus `CHAT_MEDIA_ARCHIVE_OUTBOUND` for media this account sent), else the inline copy on the message
+row — which covers media sent by this account either way; `404` when neither holds bytes.
```bash
curl "$BASE/api/sessions/$SESSION_ID/messages/[email protected]/[email protected]_3EB0ABCD/media" \
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index dd3aee1b8..556d68695 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -374,6 +374,11 @@ export default () => ({
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',
+ // Extend archiving to media this account SENT. A sub-flag rather than a mode of its own, so the
+ // retention purge and orphan sweep — which only run while archiving is enabled — are guaranteed
+ // to be maintaining whatever it writes. Off by default because it doubles storage again for the
+ // outbound half, and because a URL-based send stores no bytes to archive in the first place.
+ archiveOutbound: process.env.CHAT_MEDIA_ARCHIVE_OUTBOUND === '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: (() => {
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index 32d24b4c9..84cc7aee7 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -47,6 +47,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
// Chat-media archiving. Blank-forwarded by compose like the storage keys above, so an operator
// who sets nothing must not have an empty string pin the feature off against data/.env.generated.
'CHAT_MEDIA_ARCHIVE_ENABLED',
+ 'CHAT_MEDIA_ARCHIVE_OUTBOUND',
'CHAT_MEDIA_ARCHIVE_MAX_BYTES',
'CHAT_MEDIA_ARCHIVE_TTL_DAYS',
'CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS',
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index 78a0e4b65..6ed7763f5 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -197,7 +197,7 @@ describe('validateEnv', () => {
expect(() => validateEnv({})).not.toThrow();
});
- it.each(['MEDIA_CONVERSION_ENABLED', 'CHAT_MEDIA_ARCHIVE_ENABLED'])(
+ it.each(['MEDIA_CONVERSION_ENABLED', 'CHAT_MEDIA_ARCHIVE_ENABLED', 'CHAT_MEDIA_ARCHIVE_OUTBOUND'])(
'rejects a %s typo instead of silently leaving the feature off',
key => {
// Both are read at boot with `=== 'true'`, so a typo silently disables the feature and the
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index fec1ff0cf..7dfb3697d 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -300,6 +300,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {
// conversion/archive endpoints answer as if nothing was configured. Same class as the above.
'MEDIA_CONVERSION_ENABLED',
'CHAT_MEDIA_ARCHIVE_ENABLED',
+ 'CHAT_MEDIA_ARCHIVE_OUTBOUND',
// Read with `=== 'true'` in BOTH configuration.ts and data-source.ts, and this is the one whose
// typo fails OPEN: `DATABASE_SSL=require` is the natural Postgres spelling and reads as OFF, so
// credentials and message bodies cross the wire in plaintext to a server the operator believed
diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.ts
index ee3a50942..290581d72 100644
--- a/src/modules/chat-media/chat-media-archive.service.spec.ts
+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts
@@ -117,6 +117,37 @@ describe('ChatMediaArchiveService', () => {
expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();
});
+ it.each([['https://example.com/cat.png'], ['HTTPS://example.com/cat.png'], ['http://example.com/cat.png']])(
+ 'skips the URL pointer %s rather than decoding it as base64',
+ async url => {
+ // A URL-based send stores the URL STRING as `data`. Buffer.from(url, 'base64') does not
+ // throw — it yields ~18 bytes of noise — and the archive is consulted BEFORE the inline
+ // fallback, so an archived garbage file would be served in place of the correct 404.
+ const row = await saveRow({ mimetype: 'image/png', data: url });
+
+ expect(await enabled().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('does not re-archive a row that already points at a file', async () => {
+ // Outbound rows have two possible writers (the REST/bulk persist and the engine echo), so the
+ // same row can reach archive() twice; a second write would orphan the first file.
+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });
+ const first = await enabled().archive(row);
+
+ const reloaded = await repository.findOneByOrFail({ id: row.id });
+ expect(await enabled().archive(reloaded)).toBeNull();
+
+ const files = [];
+ for await (const f of storageService.iterateFiles('')) files.push(f);
+ expect(files).toEqual([first]);
+ });
+
it('skips media above the archive cap without touching the row', async () => {
const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });
@@ -156,7 +187,7 @@ describe('ChatMediaArchiveService', () => {
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({
+ expect(await enabled().getMedia('sess-1', [row.chatId], row.waMessageId)).toEqual({
path: key,
mimetype: 'image/png',
});
@@ -164,14 +195,30 @@ describe('ChatMediaArchiveService', () => {
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();
+ 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();
+ expect(await enabled().getMedia('other-sess', [row.chatId], row.waMessageId)).toBeNull();
+ });
+
+ it('matches any of the caller’s chatId dialects', async () => {
+ // An outbound row stores the caller's literal chatId or the engine-neutral form depending on
+ // which writer won the persist race, so the archive lookup must accept both — the same
+ // duality MessageService already resolves for the inline fallback.
+ const row = await saveRow(
+ { mimetype: 'image/png', data: PNG.toString('base64') },
+ { chatId: '[email protected]', direction: MessageDirection.OUTGOING },
+ );
+ const key = await enabled().archive(row);
+
+ expect(await enabled().getMedia('sess-1', ['[email protected]', '[email protected]'], row.waMessageId)).toEqual({
+ path: key,
+ mimetype: 'image/png',
+ });
});
});
diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.ts
index f755c60cc..340b7873a 100644
--- a/src/modules/chat-media/chat-media-archive.service.ts
+++ b/src/modules/chat-media/chat-media-archive.service.ts
@@ -37,6 +37,9 @@ function extFromMimetype(mimetype: string): string {
return MIME_SUBTYPE_EXT_OVERRIDES[subtype] ?? subtype;
}
+/** `metadata.media.data` holding a remote URL (a URL-based send) rather than base64 bytes. */
+const MEDIA_URL_POINTER = /^https?:\/\//i;
+
/** The inline media shape carried on a persisted row's `metadata.media`. */
interface InlineMedia {
mimetype?: string;
@@ -121,11 +124,20 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
* 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> {
+ async archive(row: Pick<Message, 'id' | 'sessionId' | 'metadata' | 'mediaPath'>): Promise<string | null> {
if (!this.enabled) return null;
+ // Outbound rows have two possible writers (the REST/bulk persist and the engine echo), so the
+ // same row can reach here twice. A second write would leave the first file referenced by
+ // nothing but still inside the grace window — work and storage for no gain.
+ if (row.mediaPath) return null;
const media = (row.metadata as { media?: InlineMedia } | null | undefined)?.media;
if (!media?.data || media.omitted || !media.mimetype) return null;
+ // A URL-based send stores the URL STRING as `data`, not bytes. `Buffer.from(url, 'base64')`
+ // does not throw — it yields ~18 bytes of noise — and the read endpoint consults the archive
+ // BEFORE the inline copy, so archiving one would serve garbage in place of the correct 404.
+ // Same discriminator the send path and the export controller already apply to this value.
+ if (MEDIA_URL_POINTER.test(media.data)) return null;
const maxBytes = this.configService.get<number>('chatMedia.maxBytes', DEFAULT_ARCHIVE_MAX_BYTES);
const sizeBytes = media.sizeBytes ?? Buffer.byteLength(media.data, 'base64');
@@ -165,10 +177,13 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
*/
async getMedia(
sessionId: string,
- chatId: string,
+ chatIds: string[],
waMessageId: string,
): Promise<{ path: string; mimetype: string } | null> {
- const row = await this.repository.findOne({ where: { sessionId, chatId, waMessageId } });
+ // Candidates rather than one id: an outbound row stores the caller's literal chatId or the
+ // engine-neutral form depending on which writer won the persist race. The caller owns the
+ // dialect resolution (it holds the lid table), so this only has to match any of them.
+ const row = await this.repository.findOne({ where: { sessionId, chatId: In(chatIds), waMessageId } });
if (!row?.mediaPath || !row.mediaMimetype) return null;
return { path: row.mediaPath, mimetype: row.mediaMimetype };
}
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 533484887..5400ca60e 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -1512,6 +1512,23 @@ describe('MessageService', () => {
expect(saved).toEqual(expect.objectContaining({ id: 'echo-row' }));
});
+ it('does not overwrite the echo row’s downloaded bytes with a URL pointer', async () => {
+ // A wwjs echo carries the media it downloaded; a URL-based send carries only the URL string.
+ // Merging ours over theirs would discard bytes the gateway already holds — and leave a row
+ // the archive cannot use.
+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);
+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });
+
+ await service.saveOutgoingMessage('sess-1', {
+ ...bulkRow,
+ metadata: { media: { mimetype: 'image/png', data: 'https://example.com/cat.png' } },
+ });
+
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;
+ expect(patch).not.toHaveProperty('metadata');
+ });
+
it('leaves the echo row metadata alone when this write carries none', async () => {
(repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);
(repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });
@@ -1573,6 +1590,18 @@ describe('MessageService', () => {
expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });
});
+ it('keeps the echo row’s downloaded bytes rather than merging a URL pointer over them', async () => {
+ (repository.save as jest.Mock)
+ .mockImplementationOnce(msg => Promise.resolve(msg))
+ .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));
+
+ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://example.com/cat.png' });
+
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown> | undefined;
+ expect(patch).not.toHaveProperty('metadata');
+ });
+
it('does NOT delete anything on a transient (non-unique) persist error', async () => {
(repository.save as jest.Mock)
.mockImplementationOnce(msg => Promise.resolve(msg))
@@ -1687,6 +1716,71 @@ describe('MessageService', () => {
await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);
});
+ // ── outbound archiving (CHAT_MEDIA_ARCHIVE_OUTBOUND) ─────────────
+
+ describe('archiving media this account sent', () => {
+ const withFlag = (archiveOutbound: boolean, archive: { archive: jest.Mock }): 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,
+ inertPacing(),
+ {
+ get: (key: string, fallback?: unknown) =>
+ key === 'chatMedia.archiveOutbound' ? archiveOutbound : fallback,
+ } as never,
+ archive as never,
+ undefined,
+ );
+
+ it('archives a SENT outbound row when the flag is on', async () => {
+ const archive = { archive: jest.fn().mockResolvedValue('chat-media/k') };
+ const svc = withFlag(true, archive);
+
+ await svc.saveOutgoingMessage('sess-1', {
+ waMessageId: 'wa-1',
+ chatId: '[email protected]',
+ type: 'image',
+ status: MessageStatus.SENT,
+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },
+ });
+
+ expect(archive.archive).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: 'wa-1' }));
+ });
+
+ it('archives nothing while the flag is off', async () => {
+ const archive = { archive: jest.fn() };
+ const svc = withFlag(false, archive);
+
+ await svc.saveOutgoingMessage('sess-1', {
+ waMessageId: 'wa-1',
+ chatId: '[email protected]',
+ type: 'image',
+ status: MessageStatus.SENT,
+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },
+ });
+
+ expect(archive.archive).not.toHaveBeenCalled();
+ });
+
+ it('never archives a PENDING row — the merge may delete it and the reaper may rewrite it', async () => {
+ const archive = { archive: jest.fn() };
+ const svc = withFlag(true, archive);
+
+ await svc.saveOutgoingMessage('sess-1', {
+ chatId: '[email protected]',
+ type: 'image',
+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },
+ });
+
+ expect(archive.archive).not.toHaveBeenCalled();
+ });
+ });
+
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.ts
index 289d34ea5..74d48216f 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -51,6 +51,17 @@ function inertMimetype(mimetype: string): string {
return INERT_MEDIA_MIMETYPE.test(mimetype) ? mimetype : 'application/octet-stream';
}
+/**
+ * True when this write's media is only a remote-URL pointer (a URL-based send, whose bytes the
+ * engine fetches and discards). Merging such metadata onto an echo row would REPLACE bytes the
+ * gateway already downloaded — wwjs enriches its own-send echo with the real payload — leaving a
+ * row that renders as a bare marker and that the archive cannot use.
+ */
+function isUrlPointerMetadata(metadata: Record<string, unknown> | undefined): boolean {
+ const data = (metadata as { media?: { data?: unknown } } | undefined)?.media?.data;
+ return typeof data === 'string' && /^https?:\/\//i.test(data);
+}
+
/**
* Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.
*
@@ -661,8 +672,9 @@ export class MessageService {
status: message.status,
timestamp: message.timestamp,
};
- // Only when this write actually carries metadata: a text item must not blank the echo's.
- if (message.metadata) {
+ // Only when this write actually carries metadata worth merging: a text item must not blank
+ // the echo's, and a URL pointer must not replace bytes the engine already downloaded.
+ if (message.metadata && !isUrlPointerMetadata(message.metadata)) {
patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;
}
await this.messageRepository.update({ sessionId, waMessageId }, patch);
@@ -680,10 +692,23 @@ export class MessageService {
// transition (SENT / FAILED / merge) — so a provider's copy never stays stuck at PENDING (#906).
// The payload is a shallow snapshot: the same entity instance is mutated as the send progresses
// (PENDING → SENT/FAILED), and fire-and-forget execution must still see the state at emission time.
+ //
+ // Outbound archiving rides the same chokepoint rather than a call at each of the four persist
+ // sites: every terminal state of an outbound row passes here. Gated on SENT because a PENDING row
+ // may still be deleted by the dedup merge or rewritten by the pending reaper, and a FAILED one has
+ // had its payload stripped — archiving either would strand a file the row never points at.
private emitPersisted(sessionId: string, message: Message): void {
void this.hookManager
.execute('message:persisted', { sessionId, message: { ...message } }, { sessionId, source: 'MessageService' })
.catch(() => undefined);
+ if (message.status === MessageStatus.SENT && this.archiveOutboundEnabled) {
+ void this.chatMediaArchive?.archive(message).catch(() => undefined);
+ }
+ }
+
+ /** Whether media this account sent is archived too — a sub-flag of the archive itself. */
+ private get archiveOutboundEnabled(): boolean {
+ return this.configService?.get<boolean>('chatMedia.archiveOutbound', false) === true;
}
/**
@@ -737,7 +762,7 @@ export class MessageService {
},
);
const patch: QueryDeepPartialEntity<Message> = { status: MessageStatus.SENT, timestamp: result.timestamp };
- if (message.metadata) {
+ if (message.metadata && !isUrlPointerMetadata(message.metadata)) {
patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;
}
await this.messageRepository
@@ -801,7 +826,8 @@ export class MessageService {
chatId: string,
messageId: string,
): Promise<{ buffer: Buffer; mimetype: string }> {
- const media = await this.chatMediaArchive?.getMedia(sessionId, chatId, messageId);
+ const chatIds = this.resolveJidCandidates(chatId);
+ const media = await this.chatMediaArchive?.getMedia(sessionId, chatIds, messageId);
if (media && this.storageService) {
try {
return { buffer: await this.storageService.getFile(media.path), mimetype: inertMimetype(media.mimetype) };
@@ -818,7 +844,7 @@ export class MessageService {
// chatId (REST persist) or the engine-neutral form (own-send echo) depending on which writer
// won the persist race, so a literal match would 404 on half the rows this fallback exists for.
const row = await this.messageRepository.findOne({
- where: { sessionId, chatId: In(this.resolveJidCandidates(chatId)), waMessageId: messageId },
+ where: { sessionId, chatId: In(chatIds), waMessageId: messageId },
});
const inline = (row?.metadata as { media?: { data?: unknown; mimetype?: unknown; omitted?: unknown } })?.media;
if (
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index ab78f9245..f3b4ad9ed 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -435,6 +435,14 @@ export class MessageProjector {
{ sessionId: id, source: 'SessionService' },
)
.catch(() => undefined);
+
+ // Archive this send's media, mirroring onMessage. This is the ONLY path a phone-composed
+ // send takes, so the REST-side chokepoint would never see it. Opt-in twice over
+ // (CHAT_MEDIA_ARCHIVE_ENABLED + _OUTBOUND) and a no-op otherwise; archive() itself
+ // refuses a row that is already archived, so the REST writer racing us costs nothing.
+ if (this.configService?.get<boolean>('chatMedia.archiveOutbound', false) === true) {
+ void this.chatMediaArchive?.archive(dbMessage).catch(() => undefined);
+ }
}
}