Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(database): classify unique violations precisely instead of by SQLite prefix

Yudhi Armyndharisf0ddf308fb48
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7333222a..c2a530cf7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- One precise unique-violation predicate (`23505`, `SQLITE_CONSTRAINT_UNIQUE`/`_PRIMARYKEY`): the old prefix match treated every SQLite constraint failure (FK/NOT NULL/CHECK) as a duplicate, swallowing genuine persistence failures and answering misleading 409s.
+
### Security
- `PUT /sessions/{sessionId}/webhooks/{id}` now enforces the same 16-character webhook-secret floor as create; an empty string still clears signing.
diff --git a/src/common/utils/db-errors.spec.ts b/src/common/utils/db-errors.spec.ts
index 2582a1166..9ae86c3dd 100644
--- a/src/common/utils/db-errors.spec.ts
+++ b/src/common/utils/db-errors.spec.ts
@@ -66,3 +66,36 @@ describe('isMissingTableError', () => {
expect(isMissingTableError(qfe('duplicate key value violates unique constraint', '23505'))).toBe(false);
});
});
+
+describe('isUniqueViolation', () => {
+ it('recognizes a PostgreSQL unique_violation (code 23505), wrapped or raw-shaped', () => {
+ expect(isUniqueViolation(qfe('duplicate key value violates unique constraint', '23505'))).toBe(true);
+ expect(isUniqueViolation({ driverError: { code: '23505' } })).toBe(true);
+ });
+
+ it('recognizes a SQLite unique violation by its precise code (unique or primary key)', () => {
+ expect(isUniqueViolation(qfe('UNIQUE constraint failed: templates.name', 'SQLITE_CONSTRAINT_UNIQUE'))).toBe(true);
+ expect(isUniqueViolation({ driverError: { code: 'SQLITE_CONSTRAINT_PRIMARYKEY' } })).toBe(true);
+ });
+
+ it('recognizes a SQLite unique violation by message when no code is present', () => {
+ expect(isUniqueViolation(new Error('SQLITE_CONSTRAINT: UNIQUE constraint failed: messages.sessionId'))).toBe(true);
+ });
+
+ // SQLite prefixes EVERY constraint failure with SQLITE_CONSTRAINT; a prefix match here would
+ // swallow a genuine persistence failure as "already stored" (dropped inbound messages, wrong 409s).
+ it.each([
+ ['a foreign-key violation', 'SQLITE_CONSTRAINT_FOREIGNKEY'],
+ ['a NOT NULL violation', 'SQLITE_CONSTRAINT_NOTNULL'],
+ ['a CHECK violation', 'SQLITE_CONSTRAINT_CHECK'],
+ ['the Postgres FK code', '23503'],
+ ])('returns false for %s, even when the message mentions uniqueness', (_label, code) => {
+ expect(isUniqueViolation(qfe('UNIQUE constraint failed: x', code))).toBe(false);
+ expect(isUniqueViolation({ driverError: { code } })).toBe(false);
+ });
+
+ it('returns false for an unrelated error and for null', () => {
+ expect(isUniqueViolation(new Error('boom'))).toBe(false);
+ expect(isUniqueViolation(null)).toBe(false);
+ });
+});
diff --git a/src/common/utils/db-errors.ts b/src/common/utils/db-errors.ts
index 70f7a6fb0..c595628a0 100644
--- a/src/common/utils/db-errors.ts
+++ b/src/common/utils/db-errors.ts
@@ -2,7 +2,7 @@ import { QueryFailedError } from 'typeorm';
/** Structural view of the driver errors these predicates classify, so classification survives realms. */
type DriverErrorShape = { code?: string; message?: string };
-type DriverErrorWrapperShape = { name?: unknown; message?: string; driverError?: DriverErrorShape };
+type DriverErrorWrapperShape = { name?: unknown; code?: string; message?: string; driverError?: DriverErrorShape };
// These predicates must not rely on `instanceof` alone: the errors they classify can arrive from
// another realm — better-sqlite3's native addon is cached process-wide and builds its SqliteError from
@@ -22,13 +22,25 @@ function isQueryFailedErrorLike(err: unknown): err is DriverErrorWrapperShape {
* (sqlite dev, postgres prod). Lets insert-or-converge (RMW) paths distinguish a real duplicate from an
* unrelated failure without depending on a specific driver. Add another branch if a third driver is ever
* supported.
+ *
+ * Precision matters as much as recall: SQLite prefixes EVERY constraint failure with
+ * SQLITE_CONSTRAINT (FK, NOT NULL, CHECK included), so a prefix match would swallow a genuine
+ * persistence failure as "already stored": the message-projector would mark a message
+ * isNewMessage=false on an FK error and drop it, and session/template creates would answer a
+ * misleading 409. Only the unique/primary-key suffixes classify; a decisive non-unique code wins over
+ * a misleading message.
*/
export function isUniqueViolation(err: unknown): boolean {
- if (!isQueryFailedErrorLike(err)) return false;
- const driver = err.driverError;
- const code = driver?.code ?? '';
- const message = driver?.message ?? err.message ?? '';
- return code === '23505' /* postgres */ || /UNIQUE constraint failed|SQLITE_CONSTRAINT/i.test(message);
+ if (err == null || typeof err !== 'object') return false;
+ const e = err as DriverErrorWrapperShape;
+ const code = e.driverError?.code ?? e.code;
+ if (code === '23505') return true; // postgres unique_violation
+ if (code === 'SQLITE_CONSTRAINT_UNIQUE' || code === 'SQLITE_CONSTRAINT_PRIMARYKEY') return true; // sqlite
+ // Every real constraint failure carries its suffix (FOREIGNKEY/NOTNULL/CHECK included), so those are
+ // decisive rejections. The one ambiguous shape is the BARE unsuffixed code: defer it to the message.
+ if (code != null && code !== 'SQLITE_CONSTRAINT') return false;
+ const message = e.driverError?.message ?? e.message ?? '';
+ return /UNIQUE constraint failed/i.test(message); // sqlite fallback (message only)
}
/**
diff --git a/src/common/utils/unique-constraint.util.spec.ts b/src/common/utils/unique-constraint.util.spec.ts
deleted file mode 100644
index 96b2e8eb2..000000000
--- a/src/common/utils/unique-constraint.util.spec.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { isUniqueConstraintError } from './unique-constraint.util';
-
-describe('isUniqueConstraintError', () => {
- it('recognizes a PostgreSQL unique_violation (code 23505)', () => {
- expect(isUniqueConstraintError({ driverError: { code: '23505' } })).toBe(true);
- });
-
- it('recognizes a SQLite constraint error by code', () => {
- expect(isUniqueConstraintError({ driverError: { code: 'SQLITE_CONSTRAINT_UNIQUE' } })).toBe(true);
- });
-
- it('recognizes a SQLite constraint error by message', () => {
- expect(isUniqueConstraintError(new Error('SQLITE_CONSTRAINT: UNIQUE constraint failed: messages.sessionId'))).toBe(
- true,
- );
- });
-
- it('returns false for a non-unique DB error (e.g. FK violation 23503)', () => {
- expect(isUniqueConstraintError({ driverError: { code: '23503' } })).toBe(false);
- });
-
- it('returns false for an unrelated error and for null', () => {
- expect(isUniqueConstraintError(new Error('boom'))).toBe(false);
- expect(isUniqueConstraintError(null)).toBe(false);
- });
-
- it('does not false-positive on a non-unique code whose message contains the unique phrase', () => {
- expect(isUniqueConstraintError({ driverError: { code: '23503', message: 'UNIQUE constraint failed: x' } })).toBe(
- false,
- );
- });
-});
diff --git a/src/common/utils/unique-constraint.util.ts b/src/common/utils/unique-constraint.util.ts
deleted file mode 100644
index 4e1b66853..000000000
--- a/src/common/utils/unique-constraint.util.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * True when `err` is a unique-constraint violation, across SQLite and PostgreSQL. TypeORM wraps
- * driver errors in QueryFailedError; the dialect-specific detail sits on `driverError`. Used to tell
- * a duplicate-key insert (skip it) apart from a genuine persistence failure (must not be swallowed).
- */
-export function isUniqueConstraintError(err: unknown): boolean {
- if (err == null || typeof err !== 'object') return false;
- const e = err as { code?: string; message?: string; driverError?: { code?: string; message?: string } };
- const code = e.driverError?.code ?? e.code;
- const message = e.driverError?.message ?? e.message ?? '';
- if (code === '23505') return true; // PostgreSQL unique_violation
- if (typeof code === 'string' && code.startsWith('SQLITE_CONSTRAINT')) return true; // SQLite
- if (code != null) return false; // a decisive non-unique code wins over a misleading message
- return /UNIQUE constraint failed/i.test(message); // SQLite fallback (message only)
-}
diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.ts
index fc328f166..c3e58d6a7 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -16,7 +16,7 @@ import { renderTemplate } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
import { resolveFeatureFlags } from '../../config/feature-flags';
-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { isUniqueViolation } from '../../common/utils/db-errors';
import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';
/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */
@@ -567,7 +567,7 @@ export class MessageSendService {
});
const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {
const waMessageId = message.waMessageId;
- if (!waMessageId || !isUniqueConstraintError(err)) throw err;
+ if (!waMessageId || !isUniqueViolation(err)) throw err;
const patch: QueryDeepPartialEntity<Message> = {
status: message.status,
timestamp: message.timestamp,
@@ -651,7 +651,7 @@ export class MessageSendService {
// Reconcile the earlier PENDING emission with the finalized row (#906).
this.emitPersisted(message.sessionId, message);
} catch (persistError) {
- if (result.id && isUniqueConstraintError(persistError)) {
+ if (result.id && isUniqueViolation(persistError)) {
// The engine's own-send echo (onMessageCreate) won the race and already persisted a row with
// this waMessageId. That row carries only what the engine reported — for a Baileys API send,
// a media-less marker — so merge our SENT state AND our metadata (the actual media payload)
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index f3b4ad9ed..1c85d473a 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -11,7 +11,7 @@ import { SessionLidResolver } from './session-lid-resolver.service';
import { buildMessageMetadata, storableWaMessageId } from './message-row.mapper';
import { MessageMutationProjector } from './message-mutation-projector';
import { persistHistoryMessages } from './message-history-projector';
-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { isUniqueViolation } from '../../common/utils/db-errors';
import { resolveFeatureFlags } from '../../config/feature-flags';
import { StatusStoreService } from '../status-store/status-store.service';
import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';
@@ -292,7 +292,7 @@ export class MessageProjector {
Object.assign(dbMessage, result.identifiers[0] ?? {}, result.generatedMaps?.[0] ?? {});
persisted = true;
} catch (err) {
- if (isUniqueConstraintError(err)) {
+ if (isUniqueViolation(err)) {
isNewMessage = false;
} else {
this.logger.error(`Failed to save incoming message ${incoming.id} to database`, String(err));
@@ -421,7 +421,7 @@ export class MessageProjector {
// Unique violation = the REST send path already persisted this API-originated send —
// the dedup oracle working as intended, not an error. Anything else is a real DB
// failure; fail open so a real send is never dropped on a transient DB fault.
- if (!isUniqueConstraintError(err)) {
+ if (!isUniqueViolation(err)) {
this.logger.error(`Failed to save outgoing message ${outgoing.id} to database`, String(err));
}
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 11ed9c308..c5f86e986 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -3906,7 +3906,7 @@ describe('SessionService', () => {
// The emit lives AFTER the dedup gate. A re-fire that hits the UNIQUE(sessionId, waMessageId)
// constraint must not emit message:persisted — no row was durably stored on this attempt.
const callbacks = await startAndCaptureCallbacks();
- // Emulate the SQLite UNIQUE-violation phrasing that `isUniqueConstraintError` matches via regex.
+ // Emulate the SQLite UNIQUE-violation phrasing that `isUniqueViolation` matches via regex.
(messageRepository.insert as jest.Mock).mockRejectedValueOnce(
new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'),
);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 88765e8cd..b26b9cac9 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -23,7 +23,7 @@ import { PresenceStore, type ChatPresence } from './presence-store.service';
import { SessionEngineLifecycle, resolveReconnectConfig } from './session-engine-lifecycle.service';
import { SessionOwnershipService } from './session-ownership.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { isUniqueViolation } from '../../common/utils/db-errors';
import { resolveFeatureFlags } from '../../config/feature-flags';
import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
@@ -245,7 +245,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return await manager.save(session);
});
} catch (err) {
- if (isUniqueConstraintError(err)) {
+ if (isUniqueViolation(err)) {
throw new ConflictException(`Session with name '${dto.name}' already exists`);
}
throw err;
diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.ts
index e62b85dc3..f0c2c10c6 100644
--- a/src/modules/status-store/status-store.service.ts
+++ b/src/modules/status-store/status-store.service.ts
@@ -8,7 +8,7 @@ import type { IncomingStatus } from './incoming-status';
import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';
import { StorageService } from '../../common/storage/storage.service';
import { sweepOrphanedFiles } from '../../common/storage/orphan-sweep';
-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { isUniqueViolation } from '../../common/utils/db-errors';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { userPart } from '../../engine/identity/wa-id';
import { createLogger } from '../../common/services/logger.service';
@@ -137,7 +137,7 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
// written at this point (row-first ordering), so unlike a file-first ingest there is nothing
// to reap here — the winner's own call owns its file write.
const winner = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });
- if (winner && isUniqueConstraintError(error)) return { row: winner, created: false };
+ if (winner && isUniqueViolation(error)) return { row: winner, created: false };
throw error;
}
diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.ts
index 2d8200ac8..8c2138c70 100644
--- a/src/modules/template/template.service.ts
+++ b/src/modules/template/template.service.ts
@@ -4,7 +4,7 @@ import { Repository } from 'typeorm';
import { Template } from './entities/template.entity';
import { CreateTemplateDto, UpdateTemplateDto } from './dto';
import { createLogger } from '../../common/services/logger.service';
-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
+import { isUniqueViolation } from '../../common/utils/db-errors';
@Injectable()
export class TemplateService {
@@ -29,7 +29,7 @@ export class TemplateService {
this.logger.log('Template created', { sessionId, templateId: saved.id, name: saved.name });
return saved;
} catch (err) {
- if (isUniqueConstraintError(err)) {
+ if (isUniqueViolation(err)) {
throw new ConflictException(`A template named '${dto.name}' already exists for this session`);
}
throw err;
@@ -89,7 +89,7 @@ export class TemplateService {
try {
return await this.templateRepository.save(template);
} catch (err) {
- if (isUniqueConstraintError(err)) {
+ if (isUniqueViolation(err)) {
throw new ConflictException(`A template named '${template.name}' already exists for this session`);
}
throw err;