Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: session-scoped bulk batch ids + orphan-message guard on delete (#531)

Yudhi Armyndharisd1205e6ccec5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2449334aa..8fddac3aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **Bulk batch ids are unique per session, not globally.** A batch id claimed by one session no longer prevents another session from using the same id — the uniqueness constraint is now scoped to `(session, batchId)`, matching the per-session lookup, so an explicit cross-session reuse no longer fails with a `500`. Reusing an id within the same session is still rejected with a clear `400`. Existing databases are migrated in place. (#531)
+- **A message arriving while a session is being deleted is no longer persisted as an orphan.** The inbound-message handler re-checks that the session is still live after its asynchronous processing, so a message that races a session deletion can't leave behind a `messages` row (which has no cascade) for a session that no longer exists. (#531)
+
## [0.7.12] - 2026-06-29
### Added
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 966990601..b1f711ea0 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3544,7 +3544,7 @@ Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `
Get application settings (environment-derived; `general`/`api`/`notifications` groups).
-**Auth:** API key — any valid role (no `@RequireRole`).
+**Auth:** API key (ADMIN). Settings expose server configuration, so a VIEWER or session-scoped key is rejected with `403`.
**Response** `200`
@@ -3571,7 +3571,7 @@ Get application settings (environment-derived; `general`/`api`/`notifications` g
Notes: raw return of an in-memory `Settings` object built once in the controller constructor from `ConfigService` (snapshotted at construction, not re-read per request). `general.sessionTimeout` is `floor(webhook.timeout / 60000)` minutes; `api.rateLimitWindow` is in ms; `enableDocs`/`notifications.*` are partly hardcoded (`enableDocs: true`, `emailEnabled: false`, `notificationEmail: ''`, `webhookAlerts: true`).
-**Errors:** `401` — missing/invalid `X-API-Key`.
+**Errors:** `401` — missing/invalid `X-API-Key` · `403` — API key lacks the ADMIN role.
#### PUT /api/settings
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index aa297c245..7efed4bf5 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -1061,7 +1061,7 @@ curl "$BASE/api/stats/sessions/9f1c2d3e-…" \
#### GET /api/settings
-Read runtime settings (env-derived). Any valid API key.
+Read runtime settings (env-derived). ADMIN key required (`403` otherwise).
```bash
curl "$BASE/api/settings" \
diff --git a/src/database/migrations/1781800000000-ScopeBatchIdUniqueToSession.ts b/src/database/migrations/1781800000000-ScopeBatchIdUniqueToSession.ts
new file mode 100644
index 000000000..8c19bf4ab
--- /dev/null
+++ b/src/database/migrations/1781800000000-ScopeBatchIdUniqueToSession.ts
@@ -0,0 +1,70 @@
+import { MigrationInterface, QueryRunner, TableUnique } from 'typeorm';
+
+/**
+ * Scope `message_batches` uniqueness from a global `UNIQUE(batch_id)` to `UNIQUE(session_id, batch_id)`.
+ *
+ * The baseline (1770108659848) made `batch_id` globally unique, so one session claiming a batch id
+ * denied it to every other session. After the application-level existence check was scoped to the
+ * session, that DB-level denial no longer matched the app logic: an explicit cross-session reuse
+ * passed the scoped pre-check and then violated the global constraint, surfacing as an unhandled 500
+ * (the project registers no exception enveloper). Making the constraint composite aligns the schema
+ * with the intended `(session_id, batch_id)` namespace — cross-session reuse is allowed, same-session
+ * reuse stays a violation (a DB backstop behind the app's clean 400).
+ *
+ * Uses the TypeORM schema API rather than raw SQL so the SQLite path (which cannot `ALTER TABLE DROP
+ * CONSTRAINT`) is handled by TypeORM's table rebuild, while Postgres gets plain `ALTER TABLE`. Both
+ * the lookup and the guards make it idempotent. Hand-authored because `synchronize` is off for the
+ * `data` connection.
+ */
+export class ScopeBatchIdUniqueToSession1781800000000 implements MigrationInterface {
+ name = 'ScopeBatchIdUniqueToSession1781800000000';
+
+ private static readonly TABLE = 'message_batches';
+ private static readonly COMPOSITE = 'UQ_message_batches_session_id_batch_id';
+ private static readonly GLOBAL = 'UQ_ff274470c0dbaff6c7d1f9795f5'; // baseline-generated name
+
+ private isGlobal(u: TableUnique): boolean {
+ return u.columnNames.length === 1 && u.columnNames[0] === 'batch_id';
+ }
+
+ private isComposite(u: TableUnique): boolean {
+ return u.columnNames.length === 2 && u.columnNames.includes('session_id') && u.columnNames.includes('batch_id');
+ }
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ const table = await queryRunner.getTable(ScopeBatchIdUniqueToSession1781800000000.TABLE);
+ if (!table) return;
+
+ const global = table.uniques.find(u => this.isGlobal(u));
+ if (global) {
+ await queryRunner.dropUniqueConstraint(ScopeBatchIdUniqueToSession1781800000000.TABLE, global);
+ }
+
+ if (!table.uniques.some(u => this.isComposite(u))) {
+ await queryRunner.createUniqueConstraint(
+ ScopeBatchIdUniqueToSession1781800000000.TABLE,
+ new TableUnique({
+ name: ScopeBatchIdUniqueToSession1781800000000.COMPOSITE,
+ columnNames: ['session_id', 'batch_id'],
+ }),
+ );
+ }
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ const table = await queryRunner.getTable(ScopeBatchIdUniqueToSession1781800000000.TABLE);
+ if (!table) return;
+
+ const composite = table.uniques.find(u => this.isComposite(u));
+ if (composite) {
+ await queryRunner.dropUniqueConstraint(ScopeBatchIdUniqueToSession1781800000000.TABLE, composite);
+ }
+
+ if (!table.uniques.some(u => this.isGlobal(u))) {
+ await queryRunner.createUniqueConstraint(
+ ScopeBatchIdUniqueToSession1781800000000.TABLE,
+ new TableUnique({ name: ScopeBatchIdUniqueToSession1781800000000.GLOBAL, columnNames: ['batch_id'] }),
+ );
+ }
+ }
+}
diff --git a/src/database/migrations/__tests__/1781800000000-ScopeBatchIdUniqueToSession.spec.ts b/src/database/migrations/__tests__/1781800000000-ScopeBatchIdUniqueToSession.spec.ts
new file mode 100644
index 000000000..a4e25f338
--- /dev/null
+++ b/src/database/migrations/__tests__/1781800000000-ScopeBatchIdUniqueToSession.spec.ts
@@ -0,0 +1,67 @@
+import { DataSource } from 'typeorm';
+import { ScopeBatchIdUniqueToSession1781800000000 } from '../1781800000000-ScopeBatchIdUniqueToSession';
+
+/**
+ * The baseline (1770108659848) created `message_batches` with a GLOBAL `UNIQUE(batch_id)`, so a
+ * batch id used by one session denied it to every other session — and, after the app-level check was
+ * scoped to the session, that denial surfaced as an unhandled 500 instead of a clean 4xx. This
+ * migration scopes the constraint to `(session_id, batch_id)`. The spec drives a real in-memory
+ * SQLite schema (the baseline DDL) so it exercises the actual constraint, not a mocked repository.
+ */
+describe('ScopeBatchIdUniqueToSession migration', () => {
+ let ds: DataSource;
+
+ // Exact baseline SQLite DDL for message_batches (1770108659848), including the global UNIQUE.
+ const BASELINE_DDL =
+ `CREATE TABLE "message_batches" ("id" varchar PRIMARY KEY NOT NULL, "batch_id" varchar NOT NULL, ` +
+ `"session_id" varchar NOT NULL, "status" varchar NOT NULL DEFAULT ('pending'), "messages" text NOT NULL, ` +
+ `"options" text, "progress" text, "results" text, "current_index" integer NOT NULL DEFAULT (0), ` +
+ `"created_at" datetime NOT NULL DEFAULT (datetime('now')), "updated_at" datetime NOT NULL DEFAULT (datetime('now')), ` +
+ `"started_at" datetime, "completed_at" datetime, CONSTRAINT "UQ_ff274470c0dbaff6c7d1f9795f5" UNIQUE ("batch_id"))`;
+
+ const insertBatch = (id: string, batchId: string, sessionId: string): Promise<unknown> =>
+ ds.query(`INSERT INTO "message_batches" ("id","batch_id","session_id","messages") VALUES (?,?,?,'[]')`, [
+ id,
+ batchId,
+ sessionId,
+ ]);
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:' });
+ await ds.initialize();
+ await ds.query(BASELINE_DDL);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ it('allows the same batch_id across sessions but still rejects it within one session', async () => {
+ const runner = ds.createQueryRunner();
+ await new ScopeBatchIdUniqueToSession1781800000000().up(runner);
+
+ await insertBatch('id1', 'campaign', 's1');
+ // Different session, same batch_id — the old global UNIQUE rejected this; the composite allows it.
+ await expect(insertBatch('id2', 'campaign', 's2')).resolves.toBeDefined();
+ // Same session reusing the batch_id is still a violation — the DB backstop for the app-level check.
+ await expect(insertBatch('id3', 'campaign', 's1')).rejects.toThrow();
+ });
+
+ it('is idempotent on re-run', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new ScopeBatchIdUniqueToSession1781800000000();
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined();
+ });
+
+ it('down() restores the global batch_id uniqueness', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new ScopeBatchIdUniqueToSession1781800000000();
+ await migration.up(runner);
+ await migration.down(runner);
+
+ await insertBatch('id1', 'campaign', 's1');
+ // Global uniqueness restored: a different session can no longer reuse the batch_id.
+ await expect(insertBatch('id2', 'campaign', 's2')).rejects.toThrow();
+ });
+});
diff --git a/src/modules/message/entities/message-batch.entity.ts b/src/modules/message/entities/message-batch.entity.ts
index 484607391..0210552cf 100644
--- a/src/modules/message/entities/message-batch.entity.ts
+++ b/src/modules/message/entities/message-batch.entity.ts
@@ -1,4 +1,4 @@
-import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
+import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Unique } from 'typeorm';
import { DateTransformer } from '../../../common/transformers/date.transformer';
import { jsonColumnType, dateColumnType } from '../../../common/utils/column-types';
@@ -37,11 +37,14 @@ export interface BatchProgress {
}
@Entity('message_batches')
+// Uniqueness is scoped to the session, not global: one session can't deny a batch id to another.
+// Migration 1781800000000 carries the same constraint on existing databases.
+@Unique('UQ_message_batches_session_id_batch_id', ['sessionId', 'batchId'])
export class MessageBatch {
@PrimaryGeneratedColumn('uuid')
id: string;
- @Column({ name: 'batch_id', unique: true })
+ @Column({ name: 'batch_id' })
batchId: string;
@Column({ name: 'session_id' })
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index b8b584f8e..9aab4e6dd 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1213,6 +1213,29 @@ describe('SessionService', () => {
expect(dispatchedEvents('message.received')).toHaveLength(1);
});
+ it('does not persist (no orphan row) when the session is deleted mid hook chain', async () => {
+ // onMessage gates on isLiveEngine synchronously at entry, then awaits the message:received hook
+ // chain before inserting. If delete() completes during that await (the engine leaves the live
+ // map), a late continuation must NOT insert: the messages row has no FK, so an orphan persisted
+ // here is exactly what the session-delete cleanup is meant to prevent.
+ const callbacks = await startAndCaptureCallbacks();
+ (messageRepository.insert as jest.Mock).mockClear();
+ (webhookService.dispatch as jest.Mock).mockClear();
+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;
+
+ // Tear the session out of the live map while message:received is still awaiting.
+ (hookManager.execute as jest.Mock).mockImplementationOnce((_event: string, data: unknown) => {
+ engines.delete('sess-uuid-1');
+ return Promise.resolve({ continue: true, data });
+ });
+
+ callbacks.onMessage!(makeMessage({ id: 'wa-orphan-1', fromMe: false }));
+ await flush();
+
+ expect(messageRepository.insert).not.toHaveBeenCalled();
+ expect(dispatchedEvents('message.received')).toHaveLength(0);
+ });
+
it('does not process an own-send status echo (type=append) — no dispatch, no WS emit, no DB write', async () => {
// Regression guard for the WhatsApp Status feature: posting a status produces an own-send echo
// that Baileys delivers as `messages.upsert` with `type: 'append'` (NOT 'notify'). The adapter's
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index a58e3bff3..688be051f 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -701,6 +701,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
});
+ // The hook chain above is async; a delete()/teardown can retire this engine while it
+ // awaits. Re-check liveness so a late continuation can't persist an orphan messages row
+ // (the row has no FK, so a session-delete cleanup would never reap it) or dispatch for a
+ // session that no longer exists. Mirrors the synchronous isLiveEngine gate at entry.
+ if (!this.isLiveEngine(id, engine)) return;
+
// De-duplicate at the source: the engine can re-fire `message` for one inbound message
// (#464). UNIQUE(sessionId, waMessageId) makes the insert the atomic dedup oracle — a
// near-simultaneous re-fire loses the race and is skipped here, so persist + webhook + WS