-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
47 lines (38 loc) · 1.41 KB
/
index.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
import verifier from 'alexa-verifier'
// the alexa API calls specify an HTTPS certificate that must be validated.
// the validation uses the request's raw POST body which isn't available from
// the body parser module. so we look for any requests that include a
// signaturecertchainurl HTTP request header, parse out the entire body as a
// text string, and set a flag on the request object so other body parser
// middlewares don't try to parse the body again
export default function alexaVerifierMiddleware (req, res, next) {
if (req._body) {
const er = 'The raw request body has already been parsed.'
return res.status(400).json({ status: 'failure', reason: er })
}
// TODO: if _rawBody is set and a string, don't obliterate it here!
// mark the request body as already having been parsed so it's ignored by
// other body parser middlewares
req._body = true
req.rawBody = ''
req.on('data', function (data) {
return req.rawBody += data
})
req.on('end', function () {
let certUrl, er, error, signature
try {
req.body = JSON.parse(req.rawBody)
} catch (error) {
er = error
req.body = { }
}
certUrl = req.headers['signaturecertchainurl']
signature = req.headers['signature-256']
verifier(certUrl, signature, req.rawBody, function (er) {
if (er)
res.status(400).json({ status: 'failure', reason: er })
else
next()
})
})
}