Refactor the webhook verifier to guard clauses
Node · Node · intermediate · modification
Tidies verifyWebhook by flattening the nested `if` blocks into early-return guard clauses. Pure readability refactor, behavior is identical, and the existing signature tests still pass.
verifyWebhook gates a public webhook endpoint that mutates billing state; a request it returns true for is trusted and processed.
Requirements
- Keep verifyWebhook's behavior: accept a request only when its v1 signature is a valid HMAC-SHA256 of `<timestamp>.<body>` under the secret.
- Reject requests with a missing/malformed timestamp or signature, and reject stale requests (older than MAX_AGE_SECONDS).
- Refactor the nested if-blocks into flat early-return guard clauses; the verification logic itself must not change.
Files touched
- src/webhooks/verify.js
--- src/webhooks/verify.js
// Verify a signed webhook header of the form "t=<unix>,v1=<hex hmac of `t.body`>".
function verifyWebhook(rawBody, signatureHeader, secret) {
- if (typeof signatureHeader !== 'string') {
+ if (typeof signatureHeader !== 'string')
return false;
- }
const [tsPart, sigPart] = signatureHeader.split(',');
const provided = sigPart && sigPart.startsWith('v1=') ? sigPart.slice(3) : null;
- if (!/^\d+$/.test(timestamp || '') || !SIG_HEX.test(provided || '')) {
+ if (!/^\d+$/.test(timestamp || '') || !SIG_HEX.test(provided || ''))
return false;
- }
- if (isExpired(timestamp)) {
+ if (isExpired(timestamp))
return false;
- }
+ return true;
const expected = crypto