1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const body_parser_1 = require("body-parser");
|
4 | const exceptions_1 = require("./exceptions");
|
5 | const Types = require("./types");
|
6 | const validate_signature_1 = require("./validate-signature");
|
7 | function isValidBody(body) {
|
8 | return (body && typeof body === "string") || Buffer.isBuffer(body);
|
9 | }
|
10 | function 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 |
|
17 |
|
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 |
|
26 | return req.rawBody;
|
27 | }
|
28 | else if (isValidBody(req.body)) {
|
29 | return req.body;
|
30 | }
|
31 | else {
|
32 |
|
33 | return new Promise((resolve, reject) => (0, body_parser_1.raw)({ type: "*/*" })(req, res, (error) => error ? reject(error) : resolve(req.body)));
|
34 | }
|
35 | })();
|
36 | if (!(0, 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 | }
|
53 | exports.default = middleware;
|