File size: 1,422 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import type { Request } from 'express';
import type Stripe from 'stripe';
import { AppException } from '../common/exceptions/app.exception.js';
import { APP_CONFIG } from '../config/app-config.js';
import type { AppConfig } from '../config/app-config.interface.js';
import { STRIPE_CLIENT } from '../stripe/stripe.constants.js';
import type { StripeWebhookRequest } from './stripe-webhook-request.interface.js';

/** Accepts only events signed by Stripe for our endpoint; the verified event is attached to the request. */
@Injectable()
export class StripeWebhookGuard implements CanActivate {
  constructor(
    @Inject(STRIPE_CLIENT) private readonly stripe: Stripe,
    @Inject(APP_CONFIG) private readonly config: AppConfig,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request & StripeWebhookRequest>();
    const signature = request.headers['stripe-signature'];
    if (!request.rawBody || typeof signature !== 'string') throw invalidSignature();
    try {
      request.stripeEvent = this.stripe.webhooks.constructEvent(request.rawBody, signature, this.config.stripe.webhookSecret);
    } catch {
      throw invalidSignature();
    }
    return true;
  }
}

const invalidSignature = () => new AppException(400, 'INVALID_SIGNATURE', 'Invalid Stripe signature.');