Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/payments/stripe/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ describe('payment-stripe', () => {
{ webhookToleranceSeconds: 0 },
)).resolves.toMatchObject({ type: 'checkout.session.completed' });
});

it('falls back to the default timestamp tolerance for invalid config values', async () => {
const raw = JSON.stringify({ type: 'checkout.session.completed' });
const secret = 'whsec_test';
const timestamp = String(Math.floor(Date.now() / 1000) - 600);
const signature = createHmac('sha256', secret)
.update(`${timestamp}.${raw}`)
.digest('hex');

await expect(adapter.verifyWebhook(
ctx({ STRIPE_WEBHOOK_SECRET: secret }),
raw,
`t=${timestamp},v1=${signature}`,
{ webhookToleranceSeconds: Number.NaN },
)).rejects.toThrow('Stripe webhook signature timestamp outside tolerance');
});
});

function ctx(secrets: Record<string, string>) {
Expand Down
12 changes: 10 additions & 2 deletions packages/payments/stripe/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ function verifyStripeSignature(
secret: string,
toleranceSeconds = 300,
): void {
const effectiveToleranceSeconds = normalizeWebhookToleranceSeconds(toleranceSeconds);

// Parse all key=value pairs preserving duplicate v1 keys.
// Stripe sends multiple v1 signatures during webhook secret rotation;
// Object.fromEntries() would silently drop all but one.
Expand All @@ -192,9 +194,9 @@ function verifyStripeSignature(

const timestampSeconds = Number(timestamp);
if (!Number.isFinite(timestampSeconds)) throw new Error('Stripe-Signature timestamp is invalid');
if (toleranceSeconds > 0) {
if (effectiveToleranceSeconds > 0) {
const age = Math.floor(Date.now() / 1000) - timestampSeconds;
if (Math.abs(age) > toleranceSeconds) throw new Error('Stripe webhook signature timestamp outside tolerance');
if (Math.abs(age) > effectiveToleranceSeconds) throw new Error('Stripe webhook signature timestamp outside tolerance');
}

const expected = createHmac('sha256', secret)
Expand All @@ -217,6 +219,12 @@ function verifyStripeSignature(
}
}

function normalizeWebhookToleranceSeconds(value: number): number {
if (value === 0) return 0;
if (Number.isFinite(value) && value > 0) return value;
return 300;
}

function normalizeStripeStatus(status: unknown): Webhook['status'] | undefined {
if (status === 'paid' || status === 'complete' || status === 'succeeded') return 'succeeded';
if (status === 'open' || status === 'processing' || status === 'requires_payment_method') return 'pending';
Expand Down
Loading