Polar.sh Webhook Signature Verification & License Handler
plain (javascript)
13 hours ago
·
37 lines
·
7 views
1'use strict';
3const crypto = require('crypto');
5/**
6 * Verify Polar.sh webhook signature using Standard Webhooks HMAC-SHA256
7 */
8function verifyPolarWebhook(rawBody, headers, webhookSecret) {
9 const webhookId = headers['webhook-id'];
10 const webhookTimestamp = headers['webhook-timestamp'];
11 const webhookSignature = headers['webhook-signature'];
13 if (!webhookId || !webhookTimestamp || !webhookSignature || !webhookSecret) {
14 return false;
15 }
17 const signedPayload = `${webhookId}.${webhookTimestamp}.${rawBody}`;
18 const key = webhookSecret.startsWith('whsec_') ? webhookSecret.slice(6) : webhookSecret;
19 const keyBuffer = Buffer.from(key, 'base64');
21 const expectedSig = crypto
22 .createHmac('sha256', keyBuffer)
23 .update(signedPayload, 'utf8')
24 .digest('base64');
26 const passedSignatures = webhookSignature.split(' ').map(s => s.replace(/^v1,/, ''));
27 return passedSignatures.some(sig => {
28 try {
29 return crypto.timingSafeEqual(Buffer.from(sig, 'utf8'), Buffer.from(expectedSig, 'utf8'));
30 } catch {
31 return false;
32 }
33 });
34}
36module.exports = { verifyPolarWebhook };
Replies 0
No replies yet
Every reply is a note. Start a discussion, ask a question, or attach a code snippet.
Notification