Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: correct six defects in the send-pacing and restriction work

Yudhi Armyndharis6614812fcea1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b4a97b79..beea82bfa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,7 +39,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
block the contact or touch the chat.
The two engines address the entry differently — whatsapp-web.js by bare phone number, Baileys by
- JID — so the adapters convert from the neutral contact id. Neither syncs through to the device
+ JID — so the adapters convert from the neutral contact id. A privacy id (`…@lid`) is refused with
+ a `400`: the addressbook is keyed by phone number and a lid's digits are not one, so an unguarded
+ lid would be stored as if it were a real phone. Neither syncs through to the device
addressbook: both are called with their sync-to-device flag off, so the behaviour does not depend
on which engine is running.
@@ -124,13 +126,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- **A crash mid-enqueue can no longer deliver a webhook twice.** The webhook producer passed a job
- name but no job id, so BullMQ treated every `add()` as a new job: a process that died between the
- enqueue and its bookkeeping could re-enqueue the same delivery on the next attempt, and nothing
- downstream would notice — deduplication rested entirely on the receiver honouring
- `X-OpenWA-Delivery-Id`. The job id is now that same delivery id, which gives BullMQ exactly-once
- enqueue semantics and puts both dedupe boundaries on one identifier. The id is minted per webhook
- per dispatch, so an event fanning out to several subscriptions still produces one job each.
+- **The webhook producer now enqueues idempotently.** It passed a job name but no job id, so BullMQ
+ treated every `add()` as a brand-new job. The job id is now the delivery id, matching the ingress
+ producer and putting BullMQ's dedupe boundary and the receiver's on one identifier. The id is
+ minted per webhook per dispatch, so an event fanning out to several subscriptions still produces
+ one job each.
+
+ Scoped honestly: this is hardening, not a fix for an observed duplicate. No path in the gateway
+ currently re-enqueues an existing delivery id — it is minted per dispatch and never persisted, and
+ BullMQ retries a failed job rather than re-adding it — so the deduplication cannot fire today. It
+ exists so that any future replay path (a redrive, a persisted outbox) cannot double-deliver by
+ construction. **Receivers must still honour `X-OpenWA-Delivery-Id`:** the one real at-least-once
+ window is unchanged, because when `add()` fails the producer falls back to delivering over HTTP
+ directly, and if that `add()` had in fact reached Redis both copies are sent — a job id cannot
+ dedupe a delivery that never went through the queue.
- **The bundled Redis no longer risks silently dropping queued jobs.** BullMQ requires the
`noeviction` maxmemory policy; both Redis launch paths — `docker-compose.yml` and the
dashboard-orchestrated container — started `redis-server` with `--appendonly yes` alone, leaving
diff --git a/docker-compose.yml b/docker-compose.yml
index 9c1093464..c2c876ae3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -169,6 +169,14 @@ services:
- S3_SECRET_KEY=${S3_SECRET_KEY:-}
- S3_REGION=${S3_REGION:-}
- S3_BUCKET=${S3_BUCKET:-}
+ # Chat-media archiving (opt-in). Forwarded explicitly: this file has no env_file, so a
+ # 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_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:-}
+ - CHAT_MEDIA_ORPHAN_GRACE_MS=${CHAT_MEDIA_ORPHAN_GRACE_MS:-}
# Redis. Blank-forwarded (see Database note) so a dashboard enable/disable applies; a real host
# value pins.
- REDIS_ENABLED=${REDIS_ENABLED:-}
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index c520e1af3..d14b0c67a 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1946,7 +1946,11 @@ contact record — it does not block, delete, or otherwise touch the chat.
> addressbook. Both engines are called with their sync-to-device flag off, so behaviour matches
> across engines rather than depending on which one is running.
-**Errors:** `400` session not active or invalid request · `401` missing/invalid API key · `403` key lacks OPERATOR role
+> **A privacy id (`…@lid`) is refused with `400`.** The addressbook is keyed by phone number, and a
+> lid's digits are not one — whatsapp-web.js takes a bare number here, so an unguarded lid would be
+> stored as if it were a real phone. Pass a phone-based contact id instead.
+
+**Errors:** `400` session not active, invalid request, or a `@lid` contact id · `401` missing/invalid API key · `403` key lacks OPERATOR role
#### DELETE /api/sessions/:sessionId/contacts/:contactId
@@ -1956,7 +1960,7 @@ Remove a contact from the account's addressbook. Does not block the contact or d
**Response** `200` — `{ "success": true, "message": "Contact deleted" }`
-**Errors:** `400` session not active · `401` missing/invalid API key · `403` key lacks OPERATOR role
+**Errors:** `400` session not active, or a `@lid` contact id (same reason as the `PUT` above) · `401` missing/invalid API key · `403` key lacks OPERATOR role
#### POST /api/sessions/:sessionId/contacts/:contactId/block
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 5967841d4..e7b75732f 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -144,7 +144,7 @@ _✅ #17 `getProduct` — wired on Baileys (#905); see §Catalog / Products / Or
These are honestly out of reach of a clean adapter wiring because the installed library exposes no first-class symbol. Listed so operators can plan around them rather than file unactionable bugs.
-**baileys (9 cells):**
+**baileys (10 cells):**
- `getSubscribedChannels` — no enumerate-newsletters query; all 19 newsletter members of `Socket/newsletter.d.ts` address a single newsletter (by jid, by invite key, or by creating one). Needs a raw WMex/app-state hack.
- `getLabels` / `getLabelById` / `getChatLabels` — no label read symbol; only writes (`Types/Label.d.ts` is types-only). Workaround: capture labels from the `messaging-history.set` app-state event into an in-memory cache (relay hack, no on-demand refresh).
@@ -152,6 +152,7 @@ These are honestly out of reach of a clean adapter wiring because the installed
- `getMessageReactions` — no on-demand fetch; reactions only arrive via the `messages.reaction` event. Partial local path: persist each event into the `messageStore`, then read (no historical backfill).
- `getContactStatus` / `getContactStatuses` — `fetchStatus` returns the _about_ text, not 24h stories; stories only surface as `status@broadcast` messages. The engine-level Baileys adapter methods remain unimplemented (`501`); however, the REST API reads are served from the `StatusStoreService` accumulator (see §Status — read above), so API-level parity is shipped.
- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).
+- `votePoll` — no vote-SEND helper at all; the library only decrypts INCOMING votes (`decryptPollVote`). Sending one means hand-building a `proto.Message.PollUpdateMessage` with HMAC-SHA256 vote encryption keyed by the poll creation's `messageSecret`. Supported on whatsapp-web.js.
**wwjs (6 cells):**
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java
index 197c4bf6e..155606b29 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupSettings.java
@@ -30,13 +30,13 @@ public record GroupSettings(Boolean announce, Boolean locked, Integer ephemeralS
return this;
}
- /** Disappearing-message timer in seconds ({@code 0} disables). Not supported on the whatsapp-web.js engine. */
/** Who may add participants: "all" (any member) or "admins" (admins only). */
public Builder memberAddMode(String v) {
this.memberAddMode = v;
return this;
}
+ /** Disappearing-message timer in seconds ({@code 0} disables). Not supported on the whatsapp-web.js engine. */
public Builder ephemeralSeconds(Integer v) {
this.ephemeralSeconds = v;
return this;
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index 68f54d714..12137f85e 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -44,6 +44,13 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
// forward too (otherwise it could shadow a value in data/.env.generated).
'S3_ACCESS_KEY',
'S3_SECRET_KEY',
+ // 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_MAX_BYTES',
+ 'CHAT_MEDIA_ARCHIVE_TTL_DAYS',
+ 'CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS',
+ 'CHAT_MEDIA_ORPHAN_GRACE_MS',
// Redis selection + connection details (#488)
'REDIS_ENABLED',
'REDIS_HOST',
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 8dd3e3638..3c424a03d 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -1,7 +1,5 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';
-// Runtime (not type-only): the pin message type is a wire-format enum value, not just a type.
-import { proto } from '@whiskeysockets/baileys';
import {
ChatState,
ContactCard,
@@ -427,6 +425,10 @@ export class BaileysMessaging {
async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {
this.host.ensureReady();
const target = await this.requireStored(messageId);
+ // Read the enum through the LAZY loader rather than a static import. @whiskeysockets/baileys is
+ // pure ESM and every other site in this codebase defers it to first connect; a module-scope
+ // require would drag ~590 modules into boot even for whatsapp-web.js-only processes.
+ const { proto } = await this.host.loadLib();
await this.sock().sendMessage(chatId, {
pin: target.key,
type: proto.PinInChat.Type.PIN_FOR_ALL,
@@ -439,6 +441,7 @@ export class BaileysMessaging {
async unpinMessage(chatId: string, messageId: string): Promise<void> {
this.host.ensureReady();
const target = await this.requireStored(messageId);
+ const { proto } = await this.host.loadLib();
// `time` is meaningless for an unpin and is omitted rather than sent as a dummy value.
await this.sock().sendMessage(chatId, { pin: target.key, type: proto.PinInChat.Type.UNPIN_FOR_ALL });
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 2834b4f2f..f7b810ee4 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -846,20 +846,28 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks
describe('archiveChat', () => {
it('archives via Client.archiveChat, not Chat.archive (which resolves void)', async () => {
const archiveChat = jest.fn().mockResolvedValue(true);
- const unarchiveChat = jest.fn().mockResolvedValue(true);
+ const unarchiveChat = jest.fn().mockResolvedValue(false);
await expect(readyAdapter({ archiveChat, unarchiveChat }).archiveChat(USER, true)).resolves.toBe(true);
expect(archiveChat).toHaveBeenCalledWith(USER);
expect(unarchiveChat).not.toHaveBeenCalled();
});
- it('unarchives via Client.unarchiveChat', async () => {
+ it("reports a successful UNARCHIVE as true, ignoring the library's new-state return value", async () => {
+ // Client.unarchiveChat resolves the chat's new archive state — hard-coded FALSE
+ // (Client.js:2023-2031) — not a success flag. Passing it through reported every successful
+ // unarchive as success:false, which this API documents as "the engine declined to act".
const archiveChat = jest.fn().mockResolvedValue(true);
const unarchiveChat = jest.fn().mockResolvedValue(false);
- await expect(readyAdapter({ archiveChat, unarchiveChat }).archiveChat(USER, false)).resolves.toBe(false);
+ await expect(readyAdapter({ archiveChat, unarchiveChat }).archiveChat(USER, false)).resolves.toBe(true);
expect(unarchiveChat).toHaveBeenCalledWith(USER);
expect(archiveChat).not.toHaveBeenCalled();
});
+ it('reports false only when the engine actually threw', async () => {
+ const unarchiveChat = jest.fn().mockRejectedValue(new Error('Evaluation failed'));
+ await expect(readyAdapter({ unarchiveChat }).archiveChat(USER, false)).resolves.toBe(false);
+ });
+
it('reports false instead of throwing when the engine call fails', async () => {
const archiveChat = jest.fn().mockRejectedValue(new Error('Evaluation failed'));
await expect(readyAdapter({ archiveChat }).archiveChat(USER, true)).resolves.toBe(false);
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index dd1fab050..031aa2a08 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -85,9 +85,22 @@ export class WwebjsChats {
async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
this.host.ensureReady();
try {
- // Client.archiveChat/unarchiveChat, NOT Chat.archive() — the Chat method resolves void, so it
- // gives nothing to report back; the client pair resolves the chat's new pin/archive state.
- return archive ? await this.client().archiveChat(chatId) : await this.client().unarchiveChat(chatId);
+ // Client.archiveChat/unarchiveChat, NOT Chat.archive() — the Chat method resolves void.
+ //
+ // Their return value is deliberately DISCARDED. Despite looking like a success flag they
+ // resolve the chat's NEW ARCHIVE STATE, hard-coded: archiveChat always returns true and
+ // unarchiveChat always returns false (Client.js:2009-2031, "Changes and returns the archive
+ // state of the Chat"). Surfacing that as `success` reports every successful UNARCHIVE as
+ // success:false — which this API's contract defines as "the engine declined to act".
+ //
+ // whatsapp-web.js offers no refusal signal here at all, so the honest answer is "it did not
+ // throw": an unknown chat makes the page-side Cmd.archiveChat reject, which lands below.
+ if (archive) {
+ await this.client().archiveChat(chatId);
+ } else {
+ await this.client().unarchiveChat(chatId);
+ }
+ return true;
} catch (error) {
this.host.logger.error(`Error ${archive ? 'archiving' : 'unarchiving'} chat ${chatId}`, String(error));
return false;
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 59365d797..ee3a50942 100644
--- a/src/modules/chat-media/chat-media-archive.service.spec.ts
+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts
@@ -1,7 +1,7 @@
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
-import { DataSource, Repository } from 'typeorm';
+import { DataSource, IsNull, Not, Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
jest.mock('archiver', () => ({ default: jest.fn() }));
@@ -230,6 +230,59 @@ describe('ChatMediaArchiveService', () => {
});
});
+ describe('purgeExpired batching (backlog safety)', () => {
+ 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,
+ ]);
+
+ /** Seed `n` archived+expired rows without paying for real base64 writes. */
+ async function seedExpired(n: number): Promise<void> {
+ for (let i = 0; i < n; i++) {
+ const row = await saveRow(undefined, {
+ mediaPath: `${CHAT_MEDIA_PREFIX}sess-1/f${i}.png`,
+ mediaMimetype: 'image/png',
+ });
+ await storageService.putFile(`${CHAT_MEDIA_PREFIX}sess-1/f${i}.png`, PNG);
+ await backdate(row.id, 10);
+ }
+ }
+
+ it('drains a backlog spanning many batches, and never exceeds the batch size in one statement', async () => {
+ // The archive's default TTL is 0, so the first run after an operator sets a retention can
+ // face an unbounded backlog. Unbatched, the single UPDATE ... WHERE id IN (...) blows past
+ // the driver's bind-parameter ceiling AFTER the files are already deleted — the rows then
+ // point at missing files forever, and every later tick fails the same way.
+ await seedExpired(1250); // > 2 x PURGE_BATCH_SIZE (500)
+ const svc = enabled({ 'chatMedia.ttlDays': 7 });
+ const update = jest.spyOn(repository, 'update');
+
+ expect(await svc.purgeExpired(Date.now())).toBe(1250);
+
+ const biggest = Math.max(...update.mock.calls.map(c => (Array.isArray(c[0]) ? c[0].length : 1)));
+ expect(biggest).toBeLessThanOrEqual(500);
+ expect(update.mock.calls.length).toBeGreaterThan(1);
+ expect(await repository.count({ where: { mediaPath: Not(IsNull()) } })).toBe(0);
+ // The message rows themselves survive retention — only the archived blob expires.
+ expect(await repository.count()).toBe(1250);
+ update.mockRestore();
+ });
+
+ it('stops instead of spinning when every delete in a batch fails', async () => {
+ await seedExpired(3);
+ const del = jest.spyOn(storageService, 'deleteFile').mockRejectedValue(new Error('s3 down'));
+ const svc = enabled({ 'chatMedia.ttlDays': 7 });
+
+ expect(await svc.purgeExpired(Date.now())).toBe(0);
+
+ // One batch attempted, not an endless re-select of the same undeletable rows.
+ expect(del.mock.calls.length).toBe(3);
+ expect(await repository.count({ where: { mediaPath: Not(IsNull()) } })).toBe(3);
+ 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);
@@ -255,6 +308,40 @@ describe('ChatMediaArchiveService', () => {
expect(await storageService.getFile(key!)).toEqual(PNG);
});
+ it('reconciles in bounded chunks instead of loading the whole store into memory', async () => {
+ // With the default TTL of 0 the archive grows without bound, so materialising every key AND
+ // every archived row (as the first implementation did) turns the hourly sweep into a memory
+ // spike proportional to the store. Each query must see only its own chunk of keys.
+ for (let i = 0; i < 1200; i++) await storageService.putFile(`${CHAT_MEDIA_PREFIX}sess-1/o${i}.png`, PNG);
+ const find = jest.spyOn(repository, 'find');
+ const svc = enabled({ 'chatMedia.orphanGraceMs': 0 });
+
+ expect(await svc.sweepOrphanedMedia(Date.now())).toBe(1200);
+
+ expect(find.mock.calls.length).toBeGreaterThan(1);
+ for (const [opts] of find.mock.calls) {
+ const where = (opts as { where?: { mediaPath?: { _value?: unknown[] } } })?.where;
+ const ids = where?.mediaPath?._value;
+ // Every lookup is an IN over a bounded key list, never an unfiltered "all archived rows".
+ expect(Array.isArray(ids)).toBe(true);
+ expect((ids as unknown[]).length).toBeLessThanOrEqual(500);
+ }
+ find.mockRestore();
+ });
+
+ it('keeps referenced files across a chunk boundary', async () => {
+ // A referenced file must survive even when it lands in a different chunk from its row.
+ for (let i = 0; i < 600; i++) await storageService.putFile(`${CHAT_MEDIA_PREFIX}sess-1/p${i}.png`, PNG);
+ const row = await saveRow(undefined, {
+ mediaPath: `${CHAT_MEDIA_PREFIX}sess-1/p599.png`,
+ mediaMimetype: 'image/png',
+ });
+ const svc = enabled({ 'chatMedia.orphanGraceMs': 0 });
+
+ expect(await svc.sweepOrphanedMedia(Date.now())).toBe(599);
+ expect(await storageService.getFile((await repository.findOneByOrFail({ id: row.id })).mediaPath!)).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 });
diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.ts
index f3ddfffb8..f755c60cc 100644
--- a/src/modules/chat-media/chat-media-archive.service.ts
+++ b/src/modules/chat-media/chat-media-archive.service.ts
@@ -1,7 +1,7 @@
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 { In, IsNull, LessThan, Not, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import { Message } from '../message/entities/message.entity';
import { StorageService } from '../../common/storage/storage.service';
@@ -18,6 +18,14 @@ const DEFAULT_ORPHAN_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
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;
+/** Rows cleared per purge statement. Keeps the id list far below the drivers' bind-parameter
+ * ceilings (SQLite 32766, Postgres 65535) and bounds how much work one failure can undo. */
+const PURGE_BATCH_SIZE = 500;
+/** Cap on batches per run, so one tick cannot monopolise the process draining a huge backlog;
+ * whatever is left is picked up by the next scheduled run. */
+const PURGE_MAX_BATCHES_PER_RUN = 200;
+/** Archive keys reconciled per orphan-sweep query — bounds peak memory independently of store size. */
+const SWEEP_CHUNK_SIZE = 500;
/** Subtypes whose registered mimetype name differs from the conventional file extension. */
const MIME_SUBTYPE_EXT_OVERRIDES: Record<string, string> = { jpeg: 'jpg', quicktime: 'mov' };
@@ -179,15 +187,26 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
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;
+ let cleared = 0;
- const clearableIds: string[] = [];
- await Promise.all(
- expired.map(async row => {
+ // Batched, not one pass. The archive's default TTL is 0 (keep forever), so the first run after
+ // an operator sets a retention can face an arbitrarily large backlog — unlike the status store,
+ // whose 24h TTL bounds every batch by construction. Unbatched that backlog broke three ways at
+ // once: tens of thousands of concurrent deletes, and a single `UPDATE ... WHERE id IN (...)`
+ // past the driver's bind-parameter ceiling (SQLite 32766, Postgres 65535) that throws AFTER the
+ // files are already gone — leaving rows pointing at deleted files, and every later tick
+ // repeating the same failure. Draining in bounded batches keeps each statement small and makes
+ // partial progress durable.
+ for (let batch = 0; batch < PURGE_MAX_BATCHES_PER_RUN; batch++) {
+ const expired = await this.repository.find({
+ where: { mediaPath: Not(IsNull()), createdAt: LessThan(cutoff) },
+ select: { id: true, mediaPath: true },
+ take: PURGE_BATCH_SIZE,
+ });
+ if (expired.length === 0) break;
+
+ const clearableIds: string[] = [];
+ for (const row of expired) {
try {
await this.storageService.deleteFile(row.mediaPath!);
clearableIds.push(row.id);
@@ -196,16 +215,24 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
error: String(err),
});
}
- }),
- );
+ }
+
+ // Every delete in the batch failed: the same rows would be re-selected forever, so stop
+ // rather than spin. The next scheduled run retries them.
+ if (clearableIds.length === 0) break;
+
+ await this.repository.update(clearableIds, {
+ mediaPath: null as unknown as undefined,
+ mediaMimetype: null as unknown as undefined,
+ });
+ cleared += clearableIds.length;
+
+ // A short batch means the backlog is drained; anything else costs an extra empty query.
+ if (expired.length < PURGE_BATCH_SIZE) break;
+ }
- 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;
+ if (cleared > 0) this.logger.log(`Chat media retention purge cleared ${cleared} file(s)`);
+ return cleared;
}
/**
@@ -219,44 +246,53 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
*/
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) });
+ // Keys still unreferenced at the end of THIS pass. Bounded by the orphan count (normally ~0),
+ // not by the size of the store, so it can safely drive the bookkeeping prune below.
+ const stillOrphaned = new Set<string>();
+
+ // Reconciled in chunks rather than as two whole-store sets. iterateFiles streams (listFiles
+ // truncates at STORAGE_LIST_MAX_FILES, which would strand every orphan past the cap), but
+ // collecting every key AND every archived row into memory would undo that: with the default
+ // TTL of 0 the archive grows without bound, so a mature gateway would spend an hourly spike
+ // holding millions of key strings. Each chunk asks the DB only which of ITS keys are
+ // referenced — an indexed lookup over a bounded id list.
+ let chunk: string[] = [];
+ const flush = async (): Promise<void> => {
+ if (chunk.length === 0) return;
+ const rows = await this.repository.find({ where: { mediaPath: In(chunk) }, select: { mediaPath: true } });
+ const referenced = new Set(rows.map(row => row.mediaPath));
+ for (const file of chunk) {
+ if (referenced.has(file)) {
+ this.orphanFirstSeenAt.delete(file);
+ continue;
+ }
+ stillOrphaned.add(file);
+ 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);
+ stillOrphaned.delete(file);
+ removed += 1;
+ } catch (err) {
+ this.logger.warn(`Failed to delete orphaned chat media ${file}`, { error: String(err) });
+ }
}
+ chunk = [];
+ };
+
+ for await (const file of this.storageService.iterateFiles(CHAT_MEDIA_PREFIX)) {
+ if (!file.startsWith(CHAT_MEDIA_PREFIX)) continue;
+ chunk.push(file);
+ if (chunk.length >= SWEEP_CHUNK_SIZE) await flush();
}
- // Drop bookkeeping for files that are gone so the map can't grow unbounded.
+ await flush();
+ // Drop bookkeeping for anything not still orphaned this pass — the file is gone, or a row now
+ // references it. Keyed off the orphan set rather than a full listing so this stays bounded too.
for (const key of [...this.orphanFirstSeenAt.keys()]) {
- if (!present.has(key)) this.orphanFirstSeenAt.delete(key);
+ if (!stillOrphaned.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/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.ts
index f37282ed9..fdb41c706 100644
--- a/src/modules/contact/contact.service.spec.ts
+++ b/src/modules/contact/contact.service.spec.ts
@@ -96,4 +96,28 @@ describe('ContactService', () => {
expect(out).toEqual({ '[email protected]': 'https://pps/1.jpg', '[email protected]': null });
expect(Date.now() - started).toBeLessThan(12_000);
}, 15_000);
+
+ describe('addressbook writes reject a privacy id', () => {
+ // The lid's digits are NOT a phone number (see the note on
+ // MessageService.resolveJidCandidates). whatsapp-web.js takes a bare NUMBER for the
+ // addressbook, so an unguarded @lid would be stored as if it were a real phone —
+ // silently creating an entry for a number that does not exist.
+ it.each([
+ ['upsertContact', (svc: ContactService) => svc.upsertContact('s1', '159442138038327@lid', 'Ada')],
+ ['deleteContact', (svc: ContactService) => svc.deleteContact('s1', '159442138038327@lid')],
+ ])('%s refuses an @lid contact id with a 400', (_name, call) => {
+ const upsertContact = jest.fn();
+ const deleteContact = jest.fn();
+ const svc = makeService({ upsertContact, deleteContact });
+ expect(() => call(svc)).toThrow(BadRequestException);
+ expect(upsertContact).not.toHaveBeenCalled();
+ expect(deleteContact).not.toHaveBeenCalled();
+ });
+
+ it('still allows a normal phone-based contact id through to the engine', async () => {
+ const upsertContact = jest.fn().mockResolvedValue(undefined);
+ await makeService({ upsertContact }).upsertContact('s1', '[email protected]', 'Ada', 'Lovelace');
+ expect(upsertContact).toHaveBeenCalledWith('[email protected]', 'Ada', 'Lovelace');
+ });
+ });
});
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index b081d762c..0c6b71634 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -1,7 +1,8 @@
-import { Injectable, NotFoundException } from '@nestjs/common';
+import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { paginate, ListOptions } from '../../common/utils/paginate';
+import { parseWaId } from '../../engine/identity/wa-id';
/**
* Owns engine access for contact operations so the "session not started" guard and
@@ -101,11 +102,31 @@ export class ContactService {
return this.getEngine(sessionId).blockContact(contactId);
}
+ /**
+ * An addressbook entry is keyed by a PHONE NUMBER, so a privacy-id (`@lid`) contact cannot be
+ * saved or removed: the lid's digits are not a phone number, and whatsapp-web.js — which takes a
+ * bare number rather than a JID — would happily store them as one, silently creating an
+ * addressbook entry for a number that does not exist.
+ *
+ * Refused rather than forward-resolved through the lid mapping: the mapping is best-effort, and a
+ * write that lands under the wrong number is worse than one the caller is told to redo with a
+ * phone-based id.
+ */
+ private assertAddressable(contactId: string): void {
+ if (parseWaId(contactId).kind === 'lid') {
+ throw new BadRequestException(
+ `Contact ${contactId} is a privacy id (@lid) with no known phone number; the addressbook is keyed by phone number, so pass a phone-based contact id instead`,
+ );
+ }
+ }
+
upsertContact(sessionId: string, contactId: string, firstName: string, lastName?: string) {
+ this.assertAddressable(contactId);
return this.getEngine(sessionId).upsertContact(contactId, firstName, lastName);
}
deleteContact(sessionId: string, contactId: string) {
+ this.assertAddressable(contactId);
return this.getEngine(sessionId).deleteContact(contactId);
}
diff --git a/src/modules/docker/compose-parity.spec.ts b/src/modules/docker/compose-parity.spec.ts
index 2c9ddc9aa..8a504de3f 100644
--- a/src/modules/docker/compose-parity.spec.ts
+++ b/src/modules/docker/compose-parity.spec.ts
@@ -235,6 +235,21 @@ describe('DockerService managed specs ↔ docker-compose.yml parity', () => {
expect(cfg.Env).toBeUndefined();
});
+ it('forwards every CHAT_MEDIA_* variable the app reads to the api container', () => {
+ // docker-compose.yml has NO env_file — the `environment:` list is an explicit allow-list, so a
+ // variable missing from it never reaches the container and the feature it gates stays silently
+ // off however the operator's .env is written. Exactly how AUTO_START_SESSIONS was inert before
+ // v0.12.0. Derived from configuration.ts rather than hardcoded, so a new flag cannot be added
+ // to the app and forgotten here.
+ const configSrc = readFileSync(join(__dirname, '..', '..', 'config', 'configuration.ts'), 'utf8');
+ const read = [...new Set(configSrc.match(/CHAT_MEDIA_[A-Z_]+/g) ?? [])];
+ expect(read.length).toBeGreaterThan(0);
+
+ const api = (compose.services as Record<string, { environment?: string[] }>)['openwa-api'];
+ const forwarded = new Set((api.environment ?? []).map(line => line.split('=')[0]));
+ expect(read.filter(name => !forwarded.has(name))).toEqual([]);
+ });
+
it('redis: sets the noeviction maxmemory policy BullMQ requires, on both launch paths', async () => {
const cfg = await capture('redis');
// The parity assertion above only proves the two launch paths AGREE — dropping the flag from
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index d7f6ebb22..2694641e1 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -1521,9 +1521,15 @@ describe('MessageService', () => {
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) });
+ it.each([
+ ['local ENOENT', Object.assign(new Error('missing'), { code: 'ENOENT' })],
+ // S3 reports a miss with a .name and NO .code — an ENOENT-only check turned this into a 500
+ // on the one backend where retention/lifecycle rules make a missing object most likely.
+ ['S3 NoSuchKey', Object.assign(new Error('NoSuchKey'), { name: 'NoSuchKey' })],
+ ['S3 NotFound', Object.assign(new Error('NotFound'), { name: 'NotFound' })],
+ ['S3 404 metadata', Object.assign(new Error('gone'), { $metadata: { httpStatusCode: 404 } })],
+ ])('404s when the row outlived its file (%s)', async (_label, err) => {
+ const svc = build(archived('image/png'), { getFile: jest.fn().mockRejectedValue(err) });
await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);
});
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 9afaada25..be3bcfb62 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -50,6 +50,22 @@ function inertMimetype(mimetype: string): string {
return INERT_MEDIA_MIMETYPE.test(mimetype) ? mimetype : 'application/octet-stream';
}
+/**
+ * True when a storage read failed because the object is simply not there.
+ *
+ * Both backends must be covered, and they report it differently: the local backend raises a POSIX
+ * `ENOENT` (a `.code`), while S3 raises `NoSuchKey`/`NotFound`, which carries a `.name` and no
+ * `.code` at all — `getS3File` rethrows that original error when the local read-through also misses
+ * (storage.service.ts:448-459). Checking only `.code` therefore turned a missing S3 object into a
+ * 500 on the one backend where retention and bucket lifecycle rules make it most likely.
+ */
+function isMissingObjectError(error: unknown): boolean {
+ const e = error as { code?: string; name?: string; $metadata?: { httpStatusCode?: number } };
+ return (
+ e?.code === 'ENOENT' || e?.name === 'NoSuchKey' || e?.name === 'NotFound' || e?.$metadata?.httpStatusCode === 404
+ );
+}
+
/**
* Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.
*
@@ -742,7 +758,7 @@ export class MessageService {
} 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') {
+ if (isMissingObjectError(error)) {
throw new NotFoundException('No archived media for this message');
}
throw error;