prevision / apps /prevision-api /src /webhooks /stripe-webhook.guard.ts
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
1.42 kB
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.');