UNPKG

2.07 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const body_parser_1 = require("body-parser");
4const exceptions_1 = require("./exceptions");
5const Types = require("./types");
6const validate_signature_1 = require("./validate-signature");
7function isValidBody(body) {
8 return (body && typeof body === "string") || Buffer.isBuffer(body);
9}
10function middleware(config) {
11 if (!config.channelSecret) {
12 throw new Error("no channel secret");
13 }
14 const secret = config.channelSecret;
15 const _middleware = async (req, res, next) => {
16 // header names are lower-cased
17 // https://nodejs.org/api/http.html#http_message_headers
18 const signature = req.headers[Types.LINE_SIGNATURE_HTTP_HEADER_NAME];
19 if (!signature) {
20 next(new exceptions_1.SignatureValidationFailed("no signature"));
21 return;
22 }
23 const body = await (async () => {
24 if (isValidBody(req.rawBody)) {
25 // rawBody is provided in Google Cloud Functions and others
26 return req.rawBody;
27 }
28 else if (isValidBody(req.body)) {
29 return req.body;
30 }
31 else {
32 // body may not be parsed yet, parse it to a buffer
33 return new Promise((resolve, reject) => body_parser_1.raw({ type: "*/*" })(req, res, (error) => error ? reject(error) : resolve(req.body)));
34 }
35 })();
36 if (!validate_signature_1.default(body, secret, signature)) {
37 next(new exceptions_1.SignatureValidationFailed("signature validation failed", signature));
38 return;
39 }
40 const strBody = Buffer.isBuffer(body) ? body.toString() : body;
41 try {
42 req.body = JSON.parse(strBody);
43 next();
44 }
45 catch (err) {
46 next(new exceptions_1.JSONParseError(err.message, strBody));
47 }
48 };
49 return (req, res, next) => {
50 _middleware(req, res, next).catch(next);
51 };
52}
53exports.default = middleware;