prevision / apps /prevision-api /src /webhooks /stripe-webhook.guard.spec.ts
github-actions[bot]
Automated Deploy: 23110475c742a5d4f03930b55bca09042215c1dd
1fe7075
Raw History Blame Contribute Delete
1.55 kB
import type { ExecutionContext } from '@nestjs/common';
import Stripe from 'stripe';
import { testConfig } from '../../test/support/test-config.js';
import { StripeWebhookGuard } from './stripe-webhook.guard.js';
const stripe = new Stripe('sk_test_fake');
const guard = new StripeWebhookGuard(stripe, testConfig());
const payload = JSON.stringify({ id: 'evt_1', object: 'event', type: 'customer.subscription.updated', data: { object: { id: 'sub_1' } } });
const contextFor = (request: object) => ({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext;
const sign = (secret = 'whsec_test_secret') => stripe.webhooks.generateTestHeaderString({ payload, secret });
describe('StripeWebhookGuard', () => {
it('accepts an event signed with our secret and attaches it', () => {
const request: Record<string, unknown> = { rawBody: Buffer.from(payload), headers: { 'stripe-signature': sign() } };
expect(guard.canActivate(contextFor(request))).toBe(true);
expect((request.stripeEvent as Stripe.Event).id).toBe('evt_1');
});
it.each([
['a wrong secret', { rawBody: Buffer.from(payload), headers: { 'stripe-signature': sign('whsec_other') } }],
['a tampered body', { rawBody: Buffer.from(payload.replace('sub_1', 'sub_2')), headers: { 'stripe-signature': sign() } }],
['no signature', { rawBody: Buffer.from(payload), headers: {} }],
])('refuses %s', (_, request) => {
expect(() => guard.canActivate(contextFor(request))).toThrow(expect.objectContaining({ code: 'INVALID_SIGNATURE' }));
});
});