Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(webhook): durable dead-letter record for permanently-failed deliveries (#520)
Yudhi Armyndharis5f5a6cdde933
diff --git a/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.ts b/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.tsnew file mode 100644index 000000000..b5f2da60c--- /dev/null+++ b/src/database/migrations/1781700000000-AddWebhookDeliveryFailures.ts@@ -0,0 +1,36 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Creates `webhook_delivery_failures` — a durable, append-only log of webhook deliveries that+ * exhausted all retries, so an operator isn't blind to events lost during a receiver outage longer+ * than the retry window. No FK to sessions (operational/audit data, like `audit_logs`, that should+ * survive the session it references). Hand-authored because `synchronize` is off on the `data`+ * connection for Postgres (and optional on SQLite).+ */+export class AddWebhookDeliveryFailures1781700000000 implements MigrationInterface {+ name = 'AddWebhookDeliveryFailures1781700000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (await queryRunner.hasTable('webhook_delivery_failures')) return;+ const isPostgres = queryRunner.connection.options.type === 'postgres';++ if (isPostgres) {+ await queryRunner.query(+ `CREATE TABLE "webhook_delivery_failures" ("id" varchar PRIMARY KEY NOT NULL DEFAULT gen_random_uuid()::varchar, "webhookId" varchar NOT NULL, "sessionId" varchar NOT NULL, "event" varchar NOT NULL, "url" varchar NOT NULL, "idempotencyKey" varchar, "deliveryId" varchar, "attempts" integer NOT NULL, "lastStatusCode" integer, "lastError" text NOT NULL, "createdAt" timestamp NOT NULL DEFAULT NOW())`,+ );+ } else {+ await queryRunner.query(+ `CREATE TABLE "webhook_delivery_failures" ("id" varchar PRIMARY KEY NOT NULL, "webhookId" varchar NOT NULL, "sessionId" varchar NOT NULL, "event" varchar NOT NULL, "url" varchar NOT NULL, "idempotencyKey" varchar, "deliveryId" varchar, "attempts" integer NOT NULL, "lastStatusCode" integer, "lastError" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')))`,+ );+ }++ await queryRunner.query(+ `CREATE INDEX "IDX_webhook_delivery_failures_sessionId" ON "webhook_delivery_failures" ("sessionId")`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX "IDX_webhook_delivery_failures_sessionId"`);+ await queryRunner.query(`DROP TABLE "webhook_delivery_failures"`);+ }+}diff --git a/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.ts b/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.tsnew file mode 100644index 000000000..8dc882e18--- /dev/null+++ b/src/database/migrations/__tests__/1781700000000-AddWebhookDeliveryFailures.spec.ts@@ -0,0 +1,41 @@+import { DataSource } from 'typeorm';+import { AddWebhookDeliveryFailures1781700000000 } from '../1781700000000-AddWebhookDeliveryFailures';++describe('AddWebhookDeliveryFailures migration', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({ type: 'sqlite', database: ':memory:' });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ const tableExists = async (): Promise<boolean> => {+ const rows = await ds.query<{ name: string }[]>(+ `SELECT name FROM sqlite_master WHERE type='table' AND name='webhook_delivery_failures'`,+ );+ return rows.length > 0;+ };++ it('creates the table (insertable shape), is idempotent, and down() reverses it', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddWebhookDeliveryFailures1781700000000();++ await migration.up(runner);+ expect(await tableExists()).toBe(true);++ // Column shape sanity: a minimal row (nullables omitted, createdAt defaulted) inserts cleanly.+ await ds.query(+ `INSERT INTO "webhook_delivery_failures" ("id","webhookId","sessionId","event","url","attempts","lastError") ` ++ `VALUES ('id1','wh','s1','message.received','https://r/h',3,'HTTP 503: x')`,+ );++ await expect(migration.up(runner)).resolves.toBeUndefined(); // hasTable guard → no-op on re-run++ await migration.down(runner);+ expect(await tableExists()).toBe(false);+ });+});diff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.tsindex 60e7dc624..9e0f8b906 100644--- a/src/modules/queue/processors/webhook.processor.spec.ts+++ b/src/modules/queue/processors/webhook.processor.spec.ts@@ -3,6 +3,7 @@ import { Repository } from 'typeorm';import { ConfigService } from '@nestjs/config';import { WebhookProcessor } from './webhook.processor';import { Webhook } from '../../webhook/entities/webhook.entity';+import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';import { HookManager } from '../../../core/hooks';import { WebhookJobData } from '../../webhook/webhook.service';import { fetch as undiciFetch } from 'undici';@@ -21,6 +22,7 @@ jest.mock('undici', () => {describe('WebhookProcessor', () => {let processor: WebhookProcessor;let repo: { update: jest.Mock };+ let failureRepo: { insert: jest.Mock };let hookManager: { execute: jest.Mock };let configService: { get: jest.Mock };let mockFetch: jest.Mock;@@ -52,10 +54,12 @@ describe('WebhookProcessor', () => {beforeEach(() => {repo = { update: jest.fn().mockResolvedValue({ affected: 1 }) };+ failureRepo = { insert: jest.fn().mockResolvedValue({}) };hookManager = { execute: jest.fn().mockResolvedValue({ continue: true, data: {} }) };configService = { get: jest.fn((key: string, def?: unknown) => (key === 'webhook.timeout' ? 25000 : def)) };processor = new WebhookProcessor(repo as unknown as Repository<Webhook>,+ failureRepo as unknown as Repository<WebhookDeliveryFailure>,hookManager as unknown as HookManager,configService as unknown as ConfigService,);@@ -118,6 +122,33 @@ describe('WebhookProcessor', () => {expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());});+ it('persists a durable delivery-failure record on the final attempt (with parsed HTTP status)', async () => {+ mockFetch.mockResolvedValue({ ok: false, status: 503, statusText: 'Service Unavailable' });++ await expect(+ processor.process(makeJob({ maxRetries: 3, webhookId: 'wh-x', url: 'https://8.8.8.8/h' }, 2)),+ ).rejects.toThrow();++ expect(failureRepo.insert).toHaveBeenCalledTimes(1);+ expect(failureRepo.insert).toHaveBeenCalledWith(+ expect.objectContaining({+ webhookId: 'wh-x',+ url: 'https://8.8.8.8/h',+ sessionId: 'sess-1',+ attempts: 3,+ lastStatusCode: 503,+ lastError: 'HTTP 503: Service Unavailable',+ }),+ );+ });++ it('does NOT persist a delivery-failure record before the final attempt', async () => {+ mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });++ await expect(processor.process(makeJob({ maxRetries: 3 }, 0))).rejects.toThrow();+ expect(failureRepo.insert).not.toHaveBeenCalled();+ });+it('refuses to follow a redirect when SSRF protection is on', async () => {process.env.WEBHOOK_SSRF_PROTECT = 'true';mockFetch.mockResolvedValue({ ok: false, status: 0, type: 'opaqueredirect' });diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex 05f67f9e0..f01597e25 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -8,6 +8,8 @@ import { QUEUE_NAMES } from '../queue-names';import { workerConnectionOptions, webhookWorkerConcurrency } from '../redis-connection';import { WebhookJobData } from '../../webhook/webhook.service';import { Webhook } from '../../webhook/entities/webhook.entity';+import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';+import { recordWebhookDeliveryFailure, statusCodeFromError } from '../../webhook/utils/record-delivery-failure';import { HookManager } from '../../../core/hooks';import { withSafeFetch, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';@@ -29,6 +31,8 @@ export class WebhookProcessor extends WorkerHost {constructor(@InjectRepository(Webhook, 'data')private readonly webhookRepository: Repository<Webhook>,+ @InjectRepository(WebhookDeliveryFailure, 'data')+ private readonly failureRepository: Repository<WebhookDeliveryFailure>,private readonly hookManager: HookManager,private readonly configService: ConfigService,) {@@ -128,7 +132,8 @@ export class WebhookProcessor extends WorkerHost {action: 'webhook_failed',});- // Execute error hook only on final failure (all retries exhausted)+ // On final failure (all retries exhausted): fire the error hook AND persist a durable record so+ // the lost event is visible after the BullMQ failed-set / logs roll off.if (isFinalAttempt) {await this.hookManager.execute('webhook:error',@@ -142,6 +147,17 @@ export class WebhookProcessor extends WorkerHost {},{ sessionId, source: 'WebhookProcessor' },);+ await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {+ webhookId,+ sessionId,+ event,+ url,+ idempotencyKey: payload.idempotencyKey,+ deliveryId: payload.deliveryId,+ attempts: job.attemptsMade + 1,+ lastStatusCode: statusCodeFromError(errorMessage),+ lastError: errorMessage,+ });}// Re-throw to trigger BullMQ retrydiff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.tsindex b2bc1f227..f4da9ebad 100644--- a/src/modules/queue/queue.module.ts+++ b/src/modules/queue/queue.module.ts@@ -8,6 +8,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { WebhookProcessor } from './processors/webhook.processor';import { QUEUE_NAMES } from './queue-names';import { Webhook } from '../webhook/entities/webhook.entity';+import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';import { HooksModule } from '../../core/hooks/hooks.module';// Re-export for backward compatibility@@ -15,8 +16,8 @@ export { QUEUE_NAMES } from './queue-names';@Module({imports: [- // Required for WebhookProcessor to inject Repository<Webhook>- TypeOrmModule.forFeature([Webhook], 'data'),+ // Required for WebhookProcessor to inject Repository<Webhook> + Repository<WebhookDeliveryFailure>+ TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure], 'data'),// Required for WebhookProcessor to inject HookManagerHooksModule,BullModule.forRootAsync({diff --git a/src/modules/webhook/entities/webhook-delivery-failure.entity.ts b/src/modules/webhook/entities/webhook-delivery-failure.entity.tsnew file mode 100644index 000000000..8ef6be0d1--- /dev/null+++ b/src/modules/webhook/entities/webhook-delivery-failure.entity.ts@@ -0,0 +1,51 @@+import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from 'typeorm';++/**+ * A durable record of a webhook delivery that exhausted all of its retries. The queued path (BullMQ)+ * otherwise only leaves a `failed` job that the queue evicts after a day, and the direct fallback path+ * swallowed the final error entirely — so a receiver outage longer than the retry window silently lost+ * events with no operator-visible trail. Each terminal failure is appended here (see+ * `recordWebhookDeliveryFailure`) and surfaced via the ADMIN `GET /webhooks/delivery-failures` endpoint.+ *+ * Lives on the `data` connection (auto-loaded by the webhook entity glob).+ */+@Entity('webhook_delivery_failures')+@Index('IDX_webhook_delivery_failures_sessionId', ['sessionId'])+export class WebhookDeliveryFailure {+ @PrimaryGeneratedColumn('uuid')+ id: string;++ @Column()+ webhookId: string;++ @Column()+ sessionId: string;++ @Column()+ event: string;++ @Column()+ url: string;++ /** The idempotency key the receiver would have deduped on (lets an operator correlate the lost event). */+ @Column({ nullable: true })+ idempotencyKey: string;++ @Column({ nullable: true })+ deliveryId: string;++ /** Total attempts made before giving up. */+ @Column({ type: 'int' })+ attempts: number;++ /** Last HTTP status, when the failure was a non-2xx response (null for a network/timeout/SSRF error). */+ @Column({ type: 'int', nullable: true })+ lastStatusCode: number | null;++ @Column({ type: 'text' })+ lastError: string;++ /** When the delivery was finally abandoned. */+ @CreateDateColumn()+ createdAt: Date;+}diff --git a/src/modules/webhook/utils/record-delivery-failure.spec.ts b/src/modules/webhook/utils/record-delivery-failure.spec.tsnew file mode 100644index 000000000..8c546b41e--- /dev/null+++ b/src/modules/webhook/utils/record-delivery-failure.spec.ts@@ -0,0 +1,49 @@+import { Repository } from 'typeorm';+import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entity';+import { recordWebhookDeliveryFailure, statusCodeFromError } from './record-delivery-failure';++describe('statusCodeFromError', () => {+ it('parses the status from an "HTTP <code>: ..." message', () => {+ expect(statusCodeFromError('HTTP 503: Service Unavailable')).toBe(503);+ expect(statusCodeFromError('HTTP 404: Not Found')).toBe(404);+ });++ it('returns null for a non-HTTP error (network / timeout / SSRF)', () => {+ expect(statusCodeFromError('The operation was aborted due to timeout')).toBeNull();+ expect(statusCodeFromError('fetch failed')).toBeNull();+ });+});++describe('recordWebhookDeliveryFailure', () => {+ const input = {+ webhookId: 'wh-1',+ sessionId: 's1',+ event: 'message.received',+ url: 'https://r.example/h',+ idempotencyKey: 'k',+ deliveryId: 'd',+ attempts: 3,+ lastStatusCode: 503,+ lastError: 'HTTP 503: x',+ };++ it('inserts the failure record, defaulting a missing lastStatusCode to null', async () => {+ const insert = jest.fn().mockResolvedValue({});+ const repo = { insert } as unknown as Repository<WebhookDeliveryFailure>;+ const logger = { error: jest.fn() };++ await recordWebhookDeliveryFailure(repo, logger, { ...input, lastStatusCode: undefined });++ expect(insert).toHaveBeenCalledWith(expect.objectContaining({ webhookId: 'wh-1', lastStatusCode: null }));+ expect(logger.error).not.toHaveBeenCalled();+ });++ it('swallows a repository error so a logging hiccup cannot re-poison the delivery', async () => {+ const insert = jest.fn().mockRejectedValue(new Error('db down'));+ const repo = { insert } as unknown as Repository<WebhookDeliveryFailure>;+ const logger = { error: jest.fn() };++ await expect(recordWebhookDeliveryFailure(repo, logger, input)).resolves.toBeUndefined();+ expect(logger.error).toHaveBeenCalled();+ });+});diff --git a/src/modules/webhook/utils/record-delivery-failure.ts b/src/modules/webhook/utils/record-delivery-failure.tsnew file mode 100644index 000000000..523ce7c07--- /dev/null+++ b/src/modules/webhook/utils/record-delivery-failure.ts@@ -0,0 +1,47 @@+import { Repository } from 'typeorm';+import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entity';++export interface WebhookDeliveryFailureInput {+ webhookId: string;+ sessionId: string;+ event: string;+ url: string;+ idempotencyKey?: string;+ deliveryId?: string;+ attempts: number;+ lastStatusCode?: number | null;+ lastError: string;+}++/** Minimal logger shape — both WebhookProcessor and WebhookService pass their `createLogger` instance. */+interface ErrorLogger {+ error(message: string, ...meta: unknown[]): void;+}++/** Parse the HTTP status out of an `HTTP <code>: …` error message, else null (network/timeout/SSRF). */+export function statusCodeFromError(message: string): number | null {+ const m = /^HTTP (\d{3})\b/.exec(message);+ return m ? Number(m[1]) : null;+}++/**+ * Append a durable record of a webhook delivery that exhausted all retries. Called from BOTH terminal+ * paths — the BullMQ processor's final attempt and the direct-fallback's last attempt. Wrapped in its+ * own try/catch: persisting the failure is best-effort bookkeeping and must never throw back into (and+ * re-poison) the delivery result or the fire-and-forget dispatch loop.+ */+export async function recordWebhookDeliveryFailure(+ repo: Repository<WebhookDeliveryFailure>,+ logger: ErrorLogger,+ input: WebhookDeliveryFailureInput,+): Promise<void> {+ try {+ await repo.insert({ ...input, lastStatusCode: input.lastStatusCode ?? null });+ } catch (err) {+ logger.error(+ 'Failed to persist webhook delivery-failure record',+ err instanceof Error ? err.message : String(err),+ { webhookId: input.webhookId, deliveryId: input.deliveryId, action: 'webhook_failure_record_error' },+ );+ }+}diff --git a/src/modules/webhook/webhook-session-scope.spec.ts b/src/modules/webhook/webhook-session-scope.spec.tsindex 7d0fd695d..65b107177 100644--- a/src/modules/webhook/webhook-session-scope.spec.ts+++ b/src/modules/webhook/webhook-session-scope.spec.ts@@ -25,7 +25,8 @@ describe('WebhookService session-scoped access', () => {await ds.initialize();const repo = ds.getRepository(Webhook);const cfg = { get: () => false }; // queue.enabled = false- service = new WebhookService(repo, cfg as never, {} as never, undefined);+ // 2nd arg is the delivery-failure repo, unused by the scoped read/update/delete paths under test.+ service = new WebhookService(repo, {} as never, cfg as never, {} as never, undefined);const sessions = ds.getRepository(Session);for (const id of ['sessA', 'sessB']) {diff --git a/src/modules/webhook/webhook.module.ts b/src/modules/webhook/webhook.module.tsindex db524284a..bc18ad843 100644--- a/src/modules/webhook/webhook.module.ts+++ b/src/modules/webhook/webhook.module.ts@@ -1,6 +1,7 @@import { Module, DynamicModule, Type } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { Webhook } from './entities/webhook.entity';+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { WebhookService } from './webhook.service';import { WebhookController } from './webhook.controller';import { WebhooksListController } from './webhooks-list.controller';@@ -17,7 +18,7 @@ if (process.env.QUEUE_ENABLED === 'true') {}@Module({- imports: [TypeOrmModule.forFeature([Webhook], 'data'), EngineModule, ...queueModules],+ imports: [TypeOrmModule.forFeature([Webhook, WebhookDeliveryFailure], 'data'), EngineModule, ...queueModules],controllers: [WebhookController, WebhooksListController],providers: [WebhookService],exports: [WebhookService],diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex e8d18b187..2fec1d631 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -20,6 +20,7 @@ import * as crypto from 'crypto';import { fetch as undiciFetch } from 'undici';import { WebhookService, WebhookPayload } from './webhook.service';import { Webhook } from './entities/webhook.entity';+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { WebhookFilters } from './filters/filter-types';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { HookManager } from '../../core/hooks';@@ -48,6 +49,7 @@ function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {describe('WebhookService', () => {let service: WebhookService;let repository: jest.Mocked<Partial<Repository<Webhook>>>;+ let failureRepository: jest.Mocked<Partial<Repository<WebhookDeliveryFailure>>>;let configService: jest.Mocked<Partial<ConfigService>>;let hookManager: jest.Mocked<Partial<HookManager>>;let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;@@ -63,6 +65,11 @@ describe('WebhookService', () => {update: jest.fn(),};+ failureRepository = {+ insert: jest.fn().mockResolvedValue({}),+ find: jest.fn().mockResolvedValue([]),+ };+configService = {get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {if (key === 'queue.enabled') return false;@@ -90,6 +97,7 @@ describe('WebhookService', () => {providers: [WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },{ provide: ConfigService, useValue: configService },{ provide: HookManager, useValue: hookManager },{ provide: LidMappingStoreService, useValue: lidStore },@@ -740,6 +748,7 @@ describe('WebhookService', () => {providers: [WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },{provide: ConfigService,useValue: {@@ -799,6 +808,7 @@ describe('WebhookService', () => {providers: [WebhookService,{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },{provide: ConfigService,useValue: {@@ -849,4 +859,49 @@ describe('WebhookService', () => {);});});++ describe('delivery-failure dead-letter', () => {+ it('records a durable failure when a direct delivery exhausts its retries', async () => {+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (hookManager.execute as jest.Mock).mockResolvedValue({+ continue: true,+ data: {+ payload: {+ event: 'message.received',+ timestamp: '',+ sessionId: 'sess-1',+ idempotencyKey: 'k',+ deliveryId: 'd',+ data: {},+ },+ },+ });+ const mockFetch = undiciFetch as jest.Mock;+ mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });++ await service.dispatch('sess-1', 'message.received', {});++ expect(failureRepository.insert).toHaveBeenCalledWith(+ expect.objectContaining({+ webhookId: webhook.id,+ attempts: 1,+ lastStatusCode: 500,+ lastError: 'HTTP 500: Server Error',+ }),+ );+ mockFetch.mockReset();+ });++ it('listDeliveryFailures queries most-recent-first, optionally scoped to a session', async () => {+ (failureRepository.find as jest.Mock).mockResolvedValue([{ id: 'f1' }]);++ const out = await service.listDeliveryFailures({ sessionId: 's1', limit: 10 });++ expect(out).toHaveLength(1);+ expect(failureRepository.find).toHaveBeenCalledWith(+ expect.objectContaining({ where: { sessionId: 's1' }, order: { createdAt: 'DESC' } }),+ );+ });+ });});diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex f092aedee..29169ef16 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -6,6 +6,8 @@ import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';import * as crypto from 'crypto';import { Webhook } from './entities/webhook.entity';+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';+import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';import { CreateWebhookDto, UpdateWebhookDto } from './dto';import { createLogger } from '../../common/services/logger.service';import { ListOptions, resolveListWindow } from '../../common/utils/paginate';@@ -50,6 +52,8 @@ export class WebhookService {constructor(@InjectRepository(Webhook, 'data')private readonly webhookRepository: Repository<Webhook>,+ @InjectRepository(WebhookDeliveryFailure, 'data')+ private readonly failureRepository: Repository<WebhookDeliveryFailure>,private readonly configService: ConfigService,private readonly hookManager: HookManager,@Optional()@@ -111,6 +115,21 @@ export class WebhookService {return this.webhookRepository.find(options);}+ /**+ * Recently-failed webhook deliveries (most recent first), so an operator can see what was lost during+ * a receiver outage. ADMIN-only operational data; an optional sessionId narrows it. Bounded by the+ * shared pagination window.+ */+ async listDeliveryFailures(opts: ListOptions & { sessionId?: string } = {}): Promise<WebhookDeliveryFailure[]> {+ const { limit, offset } = resolveListWindow(opts.limit, opts.offset);+ return this.failureRepository.find({+ where: opts.sessionId ? { sessionId: opts.sessionId } : {},+ order: { createdAt: 'DESC' },+ take: limit,+ skip: offset,+ });+ }+async findOne(sessionId: string, id: string): Promise<Webhook> {// Scope by the URL's sessionId so one session cannot read/act on another's webhook by id.// A wrong-session id resolves to not-found (no cross-session existence oracle).@@ -469,6 +488,20 @@ export class WebhookService {await this.delay(delay * attempt);return this.deliverWebhook(webhook, payload, headers, attempt + 1);}+ // All direct-path retries exhausted — persist a durable failure record before giving up, mirroring+ // the queued processor's final-attempt path so the queue-disabled path isn't a blind spot.+ const errMessage = error instanceof Error ? error.message : String(error);+ await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {+ webhookId: webhook.id,+ sessionId: payload.sessionId,+ event: payload.event,+ url: webhook.url,+ idempotencyKey: payload.idempotencyKey,+ deliveryId: payload.deliveryId,+ attempts: attempt,+ lastStatusCode: statusCodeFromError(errMessage),+ lastError: errMessage,+ });throw error;}}diff --git a/src/modules/webhook/webhooks-list.controller.ts b/src/modules/webhook/webhooks-list.controller.tsindex d6fa320d4..6c1288041 100644--- a/src/modules/webhook/webhooks-list.controller.ts+++ b/src/modules/webhook/webhooks-list.controller.ts@@ -2,6 +2,7 @@ import { Controller, Get, Query } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';import { WebhookService } from './webhook.service';import { WebhookResponseDto } from './dto';+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';@@ -10,6 +11,25 @@ import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';export class WebhooksListController {constructor(private readonly webhookService: WebhookService) {}+ @Get('delivery-failures')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({ summary: 'List recently-failed webhook deliveries (all retries exhausted)' })+ @ApiResponse({ status: 200, description: 'Permanently-failed webhook deliveries, most recent first' })+ @ApiQuery({ name: 'sessionId', required: false, description: 'Filter to a single session' })+ @ApiQuery({ name: 'limit', required: false, description: 'Max records to return (1-1000, default 1000)' })+ @ApiQuery({ name: 'offset', required: false, description: 'Number of records to skip (for paging)' })+ async deliveryFailures(+ @Query('sessionId') sessionId?: string,+ @Query('limit') limit?: string,+ @Query('offset') offset?: string,+ ): Promise<WebhookDeliveryFailure[]> {+ return this.webhookService.listDeliveryFailures({+ sessionId,+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ });+ }+@Get()@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'List webhooks visible to the calling key (scoped to its allowed sessions)' })