-
Notifications
You must be signed in to change notification settings - Fork 44
/
webhook-signature-http-node.js
53 lines (46 loc) · 1.42 KB
/
webhook-signature-http-node.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const mbWebhookSignatureJwt = require('messagebird/lib/webhook-signature-jwt');
const http = require('http');
const { createSecretKey } = require('crypto');
const secret = createSecretKey(Buffer.from('<YOUR SIGNING KEY>', 'utf-8'));
// getProtocol try to infer original the protocol.
function getProtocol(req) {
if (
req.connection.encrypted || (typeof req.headers.forwarded !== 'undefined' && req.headers.forwarded.includes('proto=https')) || req.headers['x-forwarded-proto'] === 'https'
) {
return 'https';
}
return 'http';
}
const server = http.createServer((req, res) => {
if (!req.url.startsWith('/webhook')) {
res.statusCode = 404;
res.end();
}
let chunks = [];
req.on('data', (chunk) => {
chunks.push(chunk);
});
req.on('end', () => {
Promise.resolve()
.then(() => {
let body = Buffer.concat(chunks);
let url = `${getProtocol(req)}://${req.headers.host}${req.url}`;
let jwt = req.headers[mbWebhookSignatureJwt.SIGNATURE_HEADER_NAME];
return mbWebhookSignatureJwt.verify(
url,
body,
jwt,
secret
).then(() => {
res.statusCode = 200;
});
})
.catch((err) => {
console.log(err);
res.statusCode = 403;
}).finally(() => res.end());
});
});
server.listen(8000, 'localhost', () => {
console.log('Example webhooks hanlder listening at http://localhost:8000');
});