Skip to content

Custom Adapters ​

The webhook module uses a ports/adapters architecture. All persistence and HTTP logic is abstracted behind port interfaces, allowing you to replace any component with a custom implementation.

Available Ports ​

Port InterfaceDefault AdapterResponsibility
WebhookEventRepositoryPrismaEventRepositoryEvent persistence
WebhookEndpointRepositoryPrismaEndpointRepositoryEndpoint CRUD and circuit breaker state
WebhookDeliveryRepositoryPrismaDeliveryRepositoryDelivery tracking, claiming, and retry
WebhookHttpClientFetchHttpClientHTTP POST with timeout and abort
WebhookSecretVaultPlaintextSecretVaultEndpoint-secret encryption and decryption

Registering Custom Adapters ​

Pass custom implementations via module options:

typescript
WebhookModule.forRoot({
  prisma: prismaService,                      // still needed for default adapters
  httpClient: myCustomHttpClient,             // implements WebhookHttpClient
  eventRepository: myCustomEventRepo,         // implements WebhookEventRepository
  endpointRepository: myCustomEndpointRepo,   // implements WebhookEndpointRepository
  deliveryRepository: myCustomDeliveryRepo,   // implements WebhookDeliveryRepository
  secretVault: myCustomSecretVault,            // implements WebhookSecretVault
});

If you provide custom implementations for all three repositories, the prisma option becomes optional.

WebhookHttpClient ​

Replace the default FetchHttpClient to use a different HTTP library or add custom behavior (e.g. mutual TLS, proxy support):

typescript
import { Injectable, Logger } from '@nestjs/common';
import {
  FetchHttpClient,
  type DeliveryResult,
  type WebhookHttpClient,
  type WebhookHttpClientRequestOptions,
} from '@nestarc/webhook';

@Injectable()
export class InstrumentedHttpClient implements WebhookHttpClient {
  private readonly transport = new FetchHttpClient();
  private readonly logger = new Logger(InstrumentedHttpClient.name);

  async post(
    url: string,
    headers: Record<string, string>,
    body: string,
    timeout: number,
    options?: WebhookHttpClientRequestOptions,
  ): Promise<DeliveryResult> {
    const result = await this.transport.post(url, headers, body, timeout, options);
    this.logger.debug({ statusCode: result.statusCode, latencyMs: result.latencyMs });
    return result;
  }
}

Since 0.13.2, the package exports WebhookHttpClientRequestOptions from the public package root. This wrapper forwards the fifth request-options argument, including validated IP addresses, to the default transport. A completely custom transport must enforce those addresses at connection time, preserve the original hostname for TLS, enforce timeouts and response-size limits, and avoid redirects. Return statusCode for non-2xx responses so permanent 4xx failures retain the correct retry classification. A four-argument implementation may type-check while losing DNS pinning.

typescript
interface DeliveryResult {
  success: boolean;
  statusCode?: number;
  body?: string;
  latencyMs: number;
  error?: string;
}

WebhookEventRepository ​

Handle event persistence with a custom storage backend:

typescript
interface WebhookEventRepository {
  saveEvent(
    eventType: string,
    payload: Record<string, unknown>,
    tenantId: string | null,
    options?: Pick<WebhookPublishOptions, 'correlationId'>,
  ): Promise<string>;

  saveEventInTransaction(
    tx: WebhookTransaction,
    eventType: string,
    payload: Record<string, unknown>,
    tenantId: string | null,
    options?: Pick<WebhookPublishOptions, 'correlationId'>,
  ): Promise<string>;

  saveEventOnceInTransaction?(
    tx: WebhookTransaction,
    eventType: string,
    payload: Record<string, unknown>,
    tenantId: string | null,
    options: Required<Pick<WebhookPublishOptions, 'idempotencyKey'>> &
      Pick<WebhookPublishOptions, 'correlationId'>,
  ): Promise<SavedWebhookEvent>;
}

Since 0.13.2, saveEvent() and saveEventInTransaction() receive optional correlation metadata; persist it without requiring an idempotency key. The extra argument is optional for compatibility, so an older adapter can compile while silently discarding it.

saveEventOnceInTransaction() is optional only for backward compatibility. A custom repository must implement it before callers pass idempotencyKey; it must atomically return the existing tenant/event-type/key match or insert a new event. Return the original event unchanged on a duplicate, including its payload and correlation metadata.

WebhookEndpointRepository ​

Manage endpoint storage and circuit breaker state:

typescript
interface WebhookEndpointRepository {
  findMatchingEndpoints(eventType: string, tenantId: string | undefined): Promise<EndpointRecord[]>;
  findMatchingEndpointsInTransaction(tx: WebhookTransaction, eventType: string, tenantId: string | undefined): Promise<EndpointRecord[]>;
  createEndpoint(input: ResolvedCreateEndpointInput): Promise<EndpointRecordWithSecret>;
  getEndpoint(id: string): Promise<EndpointRecord | null>;
  listEndpoints(tenantId?: string): Promise<EndpointRecord[]>;
  updateEndpoint(id: string, dto: UpdateEndpointDto): Promise<EndpointRecord | null>;
  rotateSecret(id: string, input: ResolvedRotateEndpointSecretInput): Promise<EndpointRecord | null>;
  deleteEndpoint(id: string): Promise<boolean>;
  resetFailures(endpointId: string): Promise<void>;
  incrementFailures(endpointId: string): Promise<number>;
  disableEndpoint(endpointId: string, reason: string): Promise<boolean>;
  recoverEligibleEndpoints(cooldownMinutes: number): Promise<number>;
}

disableEndpoint() returns true only for an active-to-inactive transition. deleteEndpoint() may reject while delivery history still references the endpoint. The repository stores vault-encrypted current and previous secrets and must preserve the configured rotation expiry.

WebhookDeliveryRepository ​

Handle delivery lifecycle, claiming, and retry:

typescript
interface WebhookDeliveryRepository {
  runInTransaction<T>(fn: (tx: WebhookTransaction) => Promise<T>): Promise<T>;
  createDeliveriesInTransaction(tx, eventId, endpointIds, maxAttempts): Promise<void>;
  claimPendingDeliveries(batchSize: number): Promise<ClaimedDelivery[]>;
  enrichDeliveries(deliveryIds: string[]): Promise<PendingDelivery[]>;
  markSent(deliveryId, attempts, result): Promise<void>;
  markFailed(deliveryId, attempts, result): Promise<void>;
  markRetry(deliveryId, attempts, nextAt, result): Promise<void>;
  recoverStaleSending(stalenessMinutes: number): Promise<number>;
  getBacklogSummary?(): Promise<DeliveryBacklogSummary>;
  getDeliveryLogs(endpointId, filters?): Promise<DeliveryRecord[]>;
  getDeliveryAttempts(deliveryId: string): Promise<DeliveryAttemptRecord[]>;
  retryDelivery(deliveryId: string, options?: RetryDeliveryOptions): Promise<boolean>;
  retryFailedDeliveries?(filters, options?): Promise<RetryFailedDeliveriesResult>;
  replayEvent?(eventId: string, options?: ReplayEventOptions, maxAttempts?: number): Promise<ReplayEventResult>;
  purgeExpiredData?(options, now?: Date): Promise<WebhookRetentionPurgeResult>;
  createTestDelivery(eventId, endpointId): Promise<void>;
}

Bulk retry, event replay, retention purge, and backlog summary are optional port methods for compatibility with older custom repositories. Their admin APIs reject unsupported operations rather than silently emulating them. The default Prisma adapter implements all of them.

Since 0.13.2, the delivery admin service passes the configured total attempt budget to the repository's replayEvent() as maxAttempts. Use it when creating replay rows; the public service still accepts only (eventId, options?). Custom retry/replay/purge implementations must coordinate on the event payload so cleanup cannot remove a newly queued payload. Return false from individual retry and skip bulk candidates when the payload was purged; replay must reject purged events. The default adapter uses event-row locks and transactions to enforce these conditions.

WebhookSecretVault ​

Use a custom vault when endpoint secrets must be encrypted at rest:

typescript
interface WebhookSecretVault {
  encrypt(plainSecret: string): Promise<string>;
  decrypt(encryptedSecret: string): Promise<string>;
}

Vault errors propagate to the caller. Handle transient KMS or network retries inside the implementation, preserve enough envelope metadata for key rotation, and keep the same vault configuration in publisher and worker processes.

In 0.13.3, the endpoint admin service and default PrismaEndpointRepository.createEndpoint() return the resolved plaintext signing key once, while the repository stores the vault-encrypted value. Provision the returned key after creation succeeds:

typescript
import { WebhookSigner } from '@nestarc/webhook';

const signingSecret = new WebhookSigner().generateSecret();
const endpoint = await endpointAdmin.createEndpoint({
  url: receiverUrl, // validated HTTPS URL
  events: ['order.created'],
  tenantId: authorizedTenantId,
  secret: signingSecret,
});

await provisionReceiver(endpoint.id, endpoint.secret);

rotateSecret() also returns the newly resolved plaintext key once. List/get APIs continue to omit secrets. The 0.13.3 creation fix changes neither tenant filters nor queued signing snapshots.

Upgrading from 0.13.2

With an encrypting vault, the 0.13.2 Prisma creation response contains ciphertext. If you remain on that release, generate the signing key before creation and provision the original signingSecret variable instead. After upgrading to 0.13.3, the returned endpoint.secret is the plaintext signing key and can be provisioned directly.

The shipped schema uses VARCHAR(255) for webhook_endpoints.secret. If the vault's ciphertext envelope can exceed 255 characters, widen this column in an application migration before enabling the vault:

sql
ALTER TABLE webhook_endpoints ALTER COLUMN secret TYPE TEXT;

The previous-secret and queued-signature columns already use TEXT. Switching from plaintext storage also requires migrating existing endpoint secrets and queued signing snapshots, or a vault that can read both formats during the transition.

Default Adapters ​

The module ships with five default adapters:

AdapterDescription
PrismaEventRepositoryStores events via Prisma raw SQL
PrismaEndpointRepositoryManages endpoints via Prisma raw SQL
PrismaDeliveryRepositoryHandles delivery lifecycle with FOR UPDATE SKIP LOCKED
FetchHttpClientUses Node.js http.request / https.request, validated address pinning, a request timeout, a 4096 UTF-16 code-unit response cap, and no redirect following
PlaintextSecretVaultStores and retrieves secrets unchanged; replace it when encryption at rest is required

TIP

The default Prisma adapters use raw SQL ($queryRaw, $executeRaw) rather than the Prisma Client query API. This avoids the need to add webhook models to your schema.prisma file.

Documentation site: MIT License. Check each package for its license.