All files / modules/webhooks/services webhook.service.ts

98.24% Statements 112/114
92.68% Branches 38/41
100% Functions 22/22
98.14% Lines 106/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 4282x 2x 2x 2x 2x 2x   2x 2x                         2x 28x       28x   28x   28x         2x         1x 1x 1x         1x           3x 2x 1x     1x                     1x 1x   1x         2x         2x         2x       2x 1x     1x                 4x       4x 1x       3x 1x 1x 1x       2x                 2x 2x   2x         2x       2x 1x     1x 1x         2x       2x 1x     1x 1x   1x                 2x       2x       2x 2x             2x               2x     2x                           2x 2x                 3x       3x 1x     2x 2x 2x   2x         2x 1x     2x       2x   2x   2x 1x                           3x         3x 1x     2x 1x       1x 1x 1x 1x     1x                   1x 1x         6x                                 6x 6x   6x               3x       3x   3x 2x     1x           1x 1x               1x   1x                     1x             1x                                 5x   5x                               4x                                  
import { Injectable, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import * as crypto from 'crypto';
 
import { WebhookEntity, WebhookDeliveryEntity, DeliveryStatus } from '../entities';
import {
  CreateWebhookDto,
  UpdateWebhookDto,
  WebhookResponseDto,
  DeliveryResponseDto,
  TestWebhookDto,
  ListDeliveriesQueryDto,
  PaginatedDeliveriesDto,
  WebhookStatsDto,
  WEBHOOK_EVENTS,
} from '../dto';
 
@Injectable()
export class WebhookService {
  private readonly logger = new Logger(WebhookService.name);
 
  constructor(
    @InjectRepository(WebhookEntity)
    private readonly webhookRepo: Repository<WebhookEntity>,
    @InjectRepository(WebhookDeliveryEntity)
    private readonly deliveryRepo: Repository<WebhookDeliveryEntity>,
    @InjectQueue('webhooks')
    private readonly webhookQueue: Queue,
  ) {}
 
  // Generate a secure random secret
  private generateSecret(): string {
    return `whsec_${crypto.randomBytes(32).toString('hex')}`;
  }
 
  // Sign a payload with HMAC-SHA256
  signPayload(payload: object, secret: string): string {
    const timestamp = Date.now();
    const body = JSON.stringify(payload);
    const signature = crypto
      .createHmac('sha256', secret)
      .update(`${timestamp}.${body}`)
      .digest('hex');
 
    return `t=${timestamp},v1=${signature}`;
  }
 
  // Create a new webhook
  async create(tenantId: string, userId: string, dto: CreateWebhookDto): Promise<WebhookResponseDto> {
    // Validate events
    const invalidEvents = dto.events.filter((e) => !WEBHOOK_EVENTS.includes(e as any));
    if (invalidEvents.length > 0) {
      throw new BadRequestException(`Invalid events: ${invalidEvents.join(', ')}`);
    }
 
    const webhook = this.webhookRepo.create({
      tenantId,
      name: dto.name,
      description: dto.description,
      url: dto.url,
      events: dto.events,
      headers: dto.headers || {},
      secret: this.generateSecret(),
      createdBy: userId,
    });
 
    const saved = await this.webhookRepo.save(webhook);
    this.logger.log(`Webhook created: ${saved.id} for tenant ${tenantId}`);
 
    return this.toResponse(saved, true); // Include secret on creation
  }
 
  // Get all webhooks for a tenant
  async findAll(tenantId: string): Promise<WebhookResponseDto[]> {
    const webhooks = await this.webhookRepo.find({
      where: { tenantId },
      order: { createdAt: 'DESC' },
    });
 
    return Promise.all(webhooks.map((w) => this.toResponse(w)));
  }
 
  // Get a single webhook
  async findOne(tenantId: string, webhookId: string): Promise<WebhookResponseDto> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    if (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    return this.toResponse(webhook);
  }
 
  // Update a webhook
  async update(
    tenantId: string,
    webhookId: string,
    dto: UpdateWebhookDto,
  ): Promise<WebhookResponseDto> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    if (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    // Validate events if provided
    if (dto.events) {
      const invalidEvents = dto.events.filter((e) => !WEBHOOK_EVENTS.includes(e as any));
      if (invalidEvents.length > 0) {
        throw new BadRequestException(`Invalid events: ${invalidEvents.join(', ')}`);
      }
    }
 
    Object.assign(webhook, {
      name: dto.name ?? webhook.name,
      description: dto.description ?? webhook.description,
      url: dto.url ?? webhook.url,
      events: dto.events ?? webhook.events,
      headers: dto.headers ?? webhook.headers,
      isActive: dto.isActive ?? webhook.isActive,
    });
 
    const saved = await this.webhookRepo.save(webhook);
    this.logger.log(`Webhook updated: ${saved.id}`);
 
    return this.toResponse(saved);
  }
 
  // Delete a webhook
  async remove(tenantId: string, webhookId: string): Promise<void> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    if (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    await this.webhookRepo.remove(webhook);
    this.logger.log(`Webhook deleted: ${webhookId}`);
  }
 
  // Regenerate webhook secret
  async regenerateSecret(tenantId: string, webhookId: string): Promise<{ secret: string }> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    if (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    webhook.secret = this.generateSecret();
    await this.webhookRepo.save(webhook);
 
    return { secret: webhook.secret };
  }
 
  // Test a webhook
  async testWebhook(
    tenantId: string,
    webhookId: string,
    dto: TestWebhookDto,
  ): Promise<DeliveryResponseDto> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    Iif (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    const eventType = dto.eventType || 'test.ping';
    const payload = dto.payload || {
      type: 'test.ping',
      timestamp: new Date().toISOString(),
      data: { message: 'This is a test webhook delivery' },
    };
 
    // Create a delivery record
    const delivery = this.deliveryRepo.create({
      webhookId: webhook.id,
      tenantId,
      eventType,
      payload,
      status: DeliveryStatus.PENDING,
    });
 
    const saved = await this.deliveryRepo.save(delivery);
 
    // Queue for immediate delivery
    await this.webhookQueue.add(
      'deliver',
      {
        deliveryId: saved.id,
        webhookId: webhook.id,
        url: webhook.url,
        secret: webhook.secret,
        headers: webhook.headers,
        eventType,
        payload,
      },
      { priority: 1 }, // High priority for tests
    );
 
    this.logger.log(`Test webhook queued: ${saved.id}`);
    return this.toDeliveryResponse(saved);
  }
 
  // Get deliveries for a webhook
  async getDeliveries(
    tenantId: string,
    webhookId: string,
    query: ListDeliveriesQueryDto,
  ): Promise<PaginatedDeliveriesDto> {
    const webhook = await this.webhookRepo.findOne({
      where: { id: webhookId, tenantId },
    });
 
    if (!webhook) {
      throw new NotFoundException('Webhook not found');
    }
 
    const page = query.page || 1;
    const limit = Math.min(query.limit || 20, 100);
    const skip = (page - 1) * limit;
 
    const qb = this.deliveryRepo
      .createQueryBuilder('d')
      .where('d.webhook_id = :webhookId', { webhookId })
      .andWhere('d.tenant_id = :tenantId', { tenantId });
 
    if (query.status) {
      qb.andWhere('d.status = :status', { status: query.status });
    }
 
    Iif (query.eventType) {
      qb.andWhere('d.event_type = :eventType', { eventType: query.eventType });
    }
 
    qb.orderBy('d.created_at', 'DESC').skip(skip).take(limit);
 
    const [items, total] = await qb.getManyAndCount();
 
    return {
      items: items.map((d) => this.toDeliveryResponse(d)),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }
 
  // Retry a failed delivery
  async retryDelivery(
    tenantId: string,
    webhookId: string,
    deliveryId: string,
  ): Promise<DeliveryResponseDto> {
    const delivery = await this.deliveryRepo.findOne({
      where: { id: deliveryId, webhookId, tenantId },
      relations: ['webhook'],
    });
 
    if (!delivery) {
      throw new NotFoundException('Delivery not found');
    }
 
    if (delivery.status !== DeliveryStatus.FAILED) {
      throw new BadRequestException('Only failed deliveries can be retried');
    }
 
    // Reset for retry
    delivery.status = DeliveryStatus.RETRYING;
    delivery.attempt = 1;
    delivery.nextRetryAt = new Date();
    await this.deliveryRepo.save(delivery);
 
    // Queue for delivery
    await this.webhookQueue.add('deliver', {
      deliveryId: delivery.id,
      webhookId: delivery.webhookId,
      url: delivery.webhook.url,
      secret: delivery.webhook.secret,
      headers: delivery.webhook.headers,
      eventType: delivery.eventType,
      payload: delivery.payload,
    });
 
    this.logger.log(`Delivery retry queued: ${delivery.id}`);
    return this.toDeliveryResponse(delivery);
  }
 
  // Get webhook stats
  async getStats(webhookId: string): Promise<WebhookStatsDto> {
    const result = await this.deliveryRepo
      .createQueryBuilder('d')
      .select([
        'COUNT(*)::int as "totalDeliveries"',
        'COUNT(*) FILTER (WHERE d.status = :delivered)::int as "successfulDeliveries"',
        'COUNT(*) FILTER (WHERE d.status = :failed)::int as "failedDeliveries"',
        'COUNT(*) FILTER (WHERE d.status IN (:...pending))::int as "pendingDeliveries"',
        'MAX(d.delivered_at) as "lastDeliveryAt"',
      ])
      .where('d.webhook_id = :webhookId', { webhookId })
      .setParameters({
        delivered: DeliveryStatus.DELIVERED,
        failed: DeliveryStatus.FAILED,
        pending: [DeliveryStatus.PENDING, DeliveryStatus.RETRYING],
      })
      .getRawOne();
 
    const total = result.successfulDeliveries + result.failedDeliveries;
    const successRate = total > 0 ? Math.round((result.successfulDeliveries / total) * 100) : 0;
 
    return {
      ...result,
      successRate,
    };
  }
 
  // Dispatch an event to all subscribed webhooks
  async dispatch(tenantId: string, eventType: string, data: Record<string, any>): Promise<void> {
    const webhooks = await this.webhookRepo.find({
      where: { tenantId, isActive: true },
    });
 
    const subscribedWebhooks = webhooks.filter((w) => w.events.includes(eventType));
 
    if (subscribedWebhooks.length === 0) {
      return;
    }
 
    const payload = {
      type: eventType,
      timestamp: new Date().toISOString(),
      data,
    };
 
    for (const webhook of subscribedWebhooks) {
      const delivery = this.deliveryRepo.create({
        webhookId: webhook.id,
        tenantId,
        eventType,
        payload,
        status: DeliveryStatus.PENDING,
      });
 
      const saved = await this.deliveryRepo.save(delivery);
 
      await this.webhookQueue.add('deliver', {
        deliveryId: saved.id,
        webhookId: webhook.id,
        url: webhook.url,
        secret: webhook.secret,
        headers: webhook.headers,
        eventType,
        payload,
      });
    }
 
    this.logger.log(
      `Event ${eventType} dispatched to ${subscribedWebhooks.length} webhooks for tenant ${tenantId}`,
    );
  }
 
  // Get available events
  getAvailableEvents(): { name: string; description: string }[] {
    return [
      { name: 'user.created', description: 'A new user was created' },
      { name: 'user.updated', description: 'A user was updated' },
      { name: 'user.deleted', description: 'A user was deleted' },
      { name: 'subscription.created', description: 'A new subscription was created' },
      { name: 'subscription.updated', description: 'A subscription was updated' },
      { name: 'subscription.cancelled', description: 'A subscription was cancelled' },
      { name: 'invoice.paid', description: 'An invoice was paid' },
      { name: 'invoice.failed', description: 'An invoice payment failed' },
      { name: 'file.uploaded', description: 'A file was uploaded' },
      { name: 'file.deleted', description: 'A file was deleted' },
      { name: 'tenant.updated', description: 'Tenant settings were updated' },
    ];
  }
 
  // Transform entity to response DTO
  private async toResponse(webhook: WebhookEntity, includeSecret = false): Promise<WebhookResponseDto> {
    const stats = await this.getStats(webhook.id);
 
    return {
      id: webhook.id,
      name: webhook.name,
      description: webhook.description,
      url: webhook.url,
      events: webhook.events,
      headers: webhook.headers,
      isActive: webhook.isActive,
      createdAt: webhook.createdAt,
      updatedAt: webhook.updatedAt,
      ...(includeSecret && { secret: webhook.secret }),
      stats,
    };
  }
 
  private toDeliveryResponse(delivery: WebhookDeliveryEntity): DeliveryResponseDto {
    return {
      id: delivery.id,
      webhookId: delivery.webhookId,
      eventType: delivery.eventType,
      payload: delivery.payload,
      status: delivery.status,
      responseStatus: delivery.responseStatus,
      responseBody: delivery.responseBody,
      attempt: delivery.attempt,
      maxAttempts: delivery.maxAttempts,
      nextRetryAt: delivery.nextRetryAt,
      lastError: delivery.lastError,
      createdAt: delivery.createdAt,
      deliveredAt: delivery.deliveredAt,
    };
  }
}