Spaces:
Paused
Paused
File size: 1,549 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 | 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' }));
});
});
|