forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhookSignature.js
More file actions
36 lines (30 loc) · 1.03 KB
/
Copy pathwebhookSignature.js
File metadata and controls
36 lines (30 loc) · 1.03 KB
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
29
30
31
32
33
34
35
36
'use strict';
const crypto = require('crypto');
const SIGNATURE_PREFIX = 'sha256=';
function sign(secret, body) {
if (typeof secret !== 'string' || secret.length === 0) {
throw new Error('signature secret must be a non-empty string');
}
const payload = typeof body === 'string' ? body : JSON.stringify(body);
const digest = crypto.createHmac('sha256', secret).update(payload).digest('hex');
return `${SIGNATURE_PREFIX}${digest}`;
}
function verify(secret, body, providedSignature) {
if (typeof providedSignature !== 'string' || !providedSignature.startsWith(SIGNATURE_PREFIX)) {
return false;
}
let expected;
try {
expected = sign(secret, body);
} catch {
return false;
}
const a = Buffer.from(expected);
const b = Buffer.from(providedSignature);
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}
function generateSecret(bytes = 32) {
return `whsec_${crypto.randomBytes(bytes).toString('hex')}`;
}
module.exports = { sign, verify, generateSecret, SIGNATURE_PREFIX };