javascript / expert
Snippet
Timing-Safe HMAC Signature Verification in Route Handlers
Protects Next.js API endpoints against timing side-channel attacks by comparing payload cryptographic HMAC signatures using node:crypto's constant-time comparison algorithm.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import crypto from 'node:crypto';export function verifyWebhookSignature(payload, signature, secret) {const hmac = crypto.createHmac('sha256', secret);hmac.update(payload, 'utf8');const expectedSignature = hmac.digest('hex');const trustedBuffer = Buffer.from(expectedSignature, 'utf8');const untrustedBuffer = Buffer.from(signature, 'utf8');if (trustedBuffer.length !== untrustedBuffer.length) {return false;}return crypto.timingSafeEqual(trustedBuffer, untrustedBuffer);}
nextjs
Breakdown
1
const hmac = crypto.createHmac('sha256', secret);
Instantiates an HMAC object initialized with SHA-256 digest algorithm and a shared secret key.
2
hmac.update(payload, 'utf8');
Streams the incoming raw payload string into the hashing digest calculation engine.
3
const expectedSignature = hmac.digest('hex');
Finalizes the HMAC computation and yields the expected hash digest encoded as a hexadecimal string.
4
return crypto.timingSafeEqual(trustedBuffer, untrustedBuffer);
Executes a constant-time comparison across byte buffers to prevent timing attack vulnerabilities.