@miqro/core 4.0.1 → 5.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/app.d.ts +15 -11
- package/build/app.js +22 -20
- package/build/app.js.map +1 -1
- package/build/common.d.ts +106 -0
- package/build/common.js +477 -0
- package/build/common.js.map +1 -0
- package/build/lib.d.ts +7 -38
- package/build/lib.js +6 -33
- package/build/lib.js.map +1 -1
- package/build/middleware/body-parser.d.ts +78 -0
- package/build/middleware/body-parser.js +548 -0
- package/build/middleware/body-parser.js.map +1 -0
- package/build/middleware/router.d.ts +114 -0
- package/build/middleware/router.js +704 -0
- package/build/middleware/router.js.map +1 -0
- package/build/middleware/session.d.ts +27 -3
- package/build/middleware/session.js +238 -18
- package/build/middleware/session.js.map +1 -1
- package/build/types.d.ts +309 -0
- package/build/types.js +455 -0
- package/build/types.js.map +1 -0
- package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
- package/build/websocket.js +316 -0
- package/build/websocket.js.map +1 -0
- package/package.json +7 -7
- package/src/app.ts +36 -32
- package/src/common.ts +528 -0
- package/src/lib.ts +63 -101
- package/src/middleware/body-parser.ts +593 -0
- package/src/middleware/router.ts +840 -0
- package/src/middleware/session.ts +249 -19
- package/src/types.ts +785 -0
- package/src/websocket.ts +356 -0
- package/build/api-router.d.ts +0 -34
- package/build/api-router.js +0 -48
- package/build/api-router.js.map +0 -1
- package/build/app-utils.d.ts +0 -13
- package/build/app-utils.js +0 -78
- package/build/app-utils.js.map +0 -1
- package/build/common/api-router-types.d.ts +0 -28
- package/build/common/api-router-types.js +0 -24
- package/build/common/api-router-types.js.map +0 -1
- package/build/common/api-router-utils.d.ts +0 -3
- package/build/common/api-router-utils.js +0 -118
- package/build/common/api-router-utils.js.map +0 -1
- package/build/common/config/config.d.ts +0 -15
- package/build/common/config/config.js +0 -38
- package/build/common/config/config.js.map +0 -1
- package/build/common/config/featuretoggle.d.ts +0 -1
- package/build/common/config/featuretoggle.js +0 -6
- package/build/common/config/featuretoggle.js.map +0 -1
- package/build/common/config/loader.d.ts +0 -13
- package/build/common/config/loader.js +0 -64
- package/build/common/config/loader.js.map +0 -1
- package/build/common/context.d.ts +0 -57
- package/build/common/context.js +0 -137
- package/build/common/context.js.map +0 -1
- package/build/common/error/badrequesterror.d.ts +0 -3
- package/build/common/error/badrequesterror.js +0 -7
- package/build/common/error/badrequesterror.js.map +0 -1
- package/build/common/error/configfilenotfound.d.ts +0 -3
- package/build/common/error/configfilenotfound.js +0 -7
- package/build/common/error/configfilenotfound.js.map +0 -1
- package/build/common/error/forbiddenerror.d.ts +0 -3
- package/build/common/error/forbiddenerror.js +0 -7
- package/build/common/error/forbiddenerror.js.map +0 -1
- package/build/common/error/notfound.d.ts +0 -3
- package/build/common/error/notfound.js +0 -7
- package/build/common/error/notfound.js.map +0 -1
- package/build/common/error/notimplemented.d.ts +0 -3
- package/build/common/error/notimplemented.js +0 -7
- package/build/common/error/notimplemented.js.map +0 -1
- package/build/common/error/unauthorizederror.d.ts +0 -3
- package/build/common/error/unauthorizederror.js +0 -7
- package/build/common/error/unauthorizederror.js.map +0 -1
- package/build/common/logger/constants.d.ts +0 -14
- package/build/common/logger/constants.js +0 -22
- package/build/common/logger/constants.js.map +0 -1
- package/build/common/logger/factory.d.ts +0 -16
- package/build/common/logger/factory.js +0 -47
- package/build/common/logger/factory.js.map +0 -1
- package/build/common/logger/interfaces.d.ts +0 -18
- package/build/common/logger/interfaces.js +0 -2
- package/build/common/logger/interfaces.js.map +0 -1
- package/build/common/logger/logger.d.ts +0 -35
- package/build/common/logger/logger.js +0 -95
- package/build/common/logger/logger.js.map +0 -1
- package/build/common/logger/transport/console.d.ts +0 -5
- package/build/common/logger/transport/console.js +0 -37
- package/build/common/logger/transport/console.js.map +0 -1
- package/build/common/logger/transport/file.d.ts +0 -2
- package/build/common/logger/transport/file.js +0 -25
- package/build/common/logger/transport/file.js.map +0 -1
- package/build/common/parser.d.ts +0 -7
- package/build/common/parser.js +0 -44
- package/build/common/parser.js.map +0 -1
- package/build/common/router-default-logger-factory.d.ts +0 -4
- package/build/common/router-default-logger-factory.js +0 -38
- package/build/common/router-default-logger-factory.js.map +0 -1
- package/build/common/router-handler.d.ts +0 -20
- package/build/common/router-handler.js +0 -154
- package/build/common/router-handler.js.map +0 -1
- package/build/common/router-types.d.ts +0 -63
- package/build/common/router-types.js +0 -86
- package/build/common/router-types.js.map +0 -1
- package/build/common/router-utils.d.ts +0 -3
- package/build/common/router-utils.js +0 -46
- package/build/common/router-utils.js.map +0 -1
- package/build/common/session/common.d.ts +0 -37
- package/build/common/session/common.js +0 -2
- package/build/common/session/common.js.map +0 -1
- package/build/common/session/service.d.ts +0 -26
- package/build/common/session/service.js +0 -154
- package/build/common/session/service.js.map +0 -1
- package/build/common/tokenize-match.d.ts +0 -19
- package/build/common/tokenize-match.js +0 -73
- package/build/common/tokenize-match.js.map +0 -1
- package/build/common/url-utils.d.ts +0 -6
- package/build/common/url-utils.js +0 -48
- package/build/common/url-utils.js.map +0 -1
- package/build/middleware/buffer.d.ts +0 -6
- package/build/middleware/buffer.js +0 -78
- package/build/middleware/buffer.js.map +0 -1
- package/build/middleware/cookie.d.ts +0 -4
- package/build/middleware/cookie.js +0 -15
- package/build/middleware/cookie.js.map +0 -1
- package/build/middleware/cors.d.ts +0 -8
- package/build/middleware/cors.js +0 -89
- package/build/middleware/cors.js.map +0 -1
- package/build/middleware/form.d.ts +0 -6
- package/build/middleware/form.js +0 -58
- package/build/middleware/form.js.map +0 -1
- package/build/middleware/group.d.ts +0 -3
- package/build/middleware/group.js +0 -77
- package/build/middleware/group.js.map +0 -1
- package/build/middleware/json.d.ts +0 -6
- package/build/middleware/json.js +0 -55
- package/build/middleware/json.js.map +0 -1
- package/build/middleware/logger.d.ts +0 -4
- package/build/middleware/logger.js +0 -16
- package/build/middleware/logger.js.map +0 -1
- package/build/middleware/parse.d.ts +0 -14
- package/build/middleware/parse.js +0 -88
- package/build/middleware/parse.js.map +0 -1
- package/build/middleware/result.d.ts +0 -9
- package/build/middleware/result.js +0 -62
- package/build/middleware/result.js.map +0 -1
- package/build/middleware/tag.d.ts +0 -4
- package/build/middleware/tag.js +0 -10
- package/build/middleware/tag.js.map +0 -1
- package/build/middleware/text.d.ts +0 -5
- package/build/middleware/text.js +0 -46
- package/build/middleware/text.js.map +0 -1
- package/build/proxy.d.ts +0 -19
- package/build/proxy.js +0 -74
- package/build/proxy.js.map +0 -1
- package/build/router.d.ts +0 -26
- package/build/router.js +0 -116
- package/build/router.js.map +0 -1
- package/build/static.d.ts +0 -14
- package/build/static.js +0 -211
- package/build/static.js.map +0 -1
- package/build/websocket/cluster.js +0 -114
- package/build/websocket/cluster.js.map +0 -1
- package/build/websocket/server.d.ts +0 -15
- package/build/websocket/server.js +0 -127
- package/build/websocket/server.js.map +0 -1
- package/build/websocket/types.d.ts +0 -39
- package/build/websocket/types.js +0 -2
- package/build/websocket/types.js.map +0 -1
- package/build/websocket/utils.d.ts +0 -8
- package/build/websocket/utils.js +0 -77
- package/build/websocket/utils.js.map +0 -1
- package/src/api-router.ts +0 -50
- package/src/app-utils.ts +0 -82
- package/src/common/api-router-types.ts +0 -52
- package/src/common/api-router-utils.ts +0 -126
- package/src/common/config/config.ts +0 -49
- package/src/common/config/featuretoggle.ts +0 -6
- package/src/common/config/loader.ts +0 -81
- package/src/common/context.ts +0 -192
- package/src/common/error/badrequesterror.ts +0 -6
- package/src/common/error/configfilenotfound.ts +0 -6
- package/src/common/error/forbiddenerror.ts +0 -6
- package/src/common/error/notfound.ts +0 -6
- package/src/common/error/notimplemented.ts +0 -6
- package/src/common/error/unauthorizederror.ts +0 -6
- package/src/common/logger/constants.ts +0 -28
- package/src/common/logger/factory.ts +0 -53
- package/src/common/logger/interfaces.ts +0 -19
- package/src/common/logger/logger.ts +0 -136
- package/src/common/logger/transport/console.ts +0 -36
- package/src/common/logger/transport/file.ts +0 -26
- package/src/common/parser.ts +0 -50
- package/src/common/router-default-logger-factory.ts +0 -44
- package/src/common/router-handler.ts +0 -186
- package/src/common/router-types.ts +0 -153
- package/src/common/router-utils.ts +0 -47
- package/src/common/session/common.ts +0 -40
- package/src/common/session/service.ts +0 -175
- package/src/common/tokenize-match.ts +0 -98
- package/src/common/url-utils.ts +0 -46
- package/src/middleware/buffer.ts +0 -82
- package/src/middleware/cookie.ts +0 -20
- package/src/middleware/cors.ts +0 -98
- package/src/middleware/form.ts +0 -61
- package/src/middleware/group.ts +0 -74
- package/src/middleware/json.ts +0 -57
- package/src/middleware/logger.ts +0 -18
- package/src/middleware/parse.ts +0 -105
- package/src/middleware/result.ts +0 -73
- package/src/middleware/tag.ts +0 -15
- package/src/middleware/text.ts +0 -47
- package/src/proxy.ts +0 -99
- package/src/router.ts +0 -140
- package/src/static.ts +0 -242
- package/src/websocket/cluster.ts +0 -128
- package/src/websocket/server.ts +0 -135
- package/src/websocket/types.ts +0 -41
- package/src/websocket/utils.ts +0 -95
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { gunzipSync } from "zlib";
|
|
2
|
+
import { parse as queryParse } from "querystring";
|
|
3
|
+
import { BadRequestError, checkEnvVariables } from "../common.js";
|
|
4
|
+
import { Request, Response, Handler, SchemaProperties, ParserMode } from "../types.js";
|
|
5
|
+
import { Parser, ParserInterface } from "@miqro/parser";
|
|
6
|
+
|
|
7
|
+
/**CORS */
|
|
8
|
+
|
|
9
|
+
const DEFAULT_CORS_ORIGINS = "*";
|
|
10
|
+
const DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
|
|
11
|
+
const DEFAULT_CORS_PREFLIGHT_CONTINUE = false;
|
|
12
|
+
|
|
13
|
+
export interface CORSOptions {
|
|
14
|
+
origins: string[] | string | undefined;
|
|
15
|
+
validate?: (origin: string | undefined, origins: string[] | string) => boolean;
|
|
16
|
+
methods?: string;
|
|
17
|
+
preflightContinue?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const isOriginAllowed = (origin: string | undefined, origins: string[] | string): boolean => {
|
|
21
|
+
if (origins instanceof Array) {
|
|
22
|
+
for (const o of origins) {
|
|
23
|
+
if (origin === o || o === "*") {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
} else {
|
|
29
|
+
return origin === origins;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const CORS = (options?: CORSOptions): Handler<void> => {
|
|
34
|
+
let origins: string[] | undefined | string;
|
|
35
|
+
let methods: string;
|
|
36
|
+
let preFlightContinue = false;
|
|
37
|
+
if (options) {
|
|
38
|
+
origins = options.origins instanceof Array ? options.origins : (options.origins ? [options.origins] : undefined);
|
|
39
|
+
methods = options.methods ? options.methods : DEFAULT_CORS_METHODS;
|
|
40
|
+
preFlightContinue = !!options.preflightContinue;
|
|
41
|
+
} else {
|
|
42
|
+
const [originsS, preFlightContinueS, methodsS] =
|
|
43
|
+
checkEnvVariables(["CORS_ORIGINS", "CORS_PREFLIGHT_CONTINUE", "CORS_METHODS"], [DEFAULT_CORS_ORIGINS, String(DEFAULT_CORS_PREFLIGHT_CONTINUE), DEFAULT_CORS_METHODS]);
|
|
44
|
+
origins = originsS.split(",").map(s => s.trim());
|
|
45
|
+
methods = methodsS;
|
|
46
|
+
preFlightContinue = preFlightContinueS.toLocaleLowerCase() === "true";
|
|
47
|
+
}
|
|
48
|
+
if (origins && origins.length === 1) {
|
|
49
|
+
origins = origins[0];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const validate: (origin: string | undefined, origins: string[] | string) => boolean =
|
|
53
|
+
options && options.validate ? options && options.validate : isOriginAllowed;
|
|
54
|
+
|
|
55
|
+
return async function CORS(req: Request, res: Response): Promise<void> {
|
|
56
|
+
// access-control-allow-origin
|
|
57
|
+
if (!origins || origins === '*') {
|
|
58
|
+
// allow any origin
|
|
59
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
60
|
+
res.addVaryHeader("Origin");
|
|
61
|
+
} else {
|
|
62
|
+
if (req.headers.origin) {
|
|
63
|
+
if (validate(req.headers.origin, origins)) {
|
|
64
|
+
// reflect origin
|
|
65
|
+
res.setHeader("Access-Control-Allow-Origin", String(req.headers.origin));
|
|
66
|
+
res.addVaryHeader("Origin");
|
|
67
|
+
} else {
|
|
68
|
+
// not allowed
|
|
69
|
+
throw new BadRequestError(`bad origin`);
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
res.setHeader("Access-Control-Allow-Origin", origins instanceof Array ? origins[0] : origins);
|
|
73
|
+
res.addVaryHeader("Origin");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (String(req.method).toUpperCase() === "OPTIONS") {
|
|
78
|
+
// access-control-request-headers
|
|
79
|
+
if (methods) {
|
|
80
|
+
res.setHeader("Access-Control-Allow-Methods", methods);
|
|
81
|
+
}
|
|
82
|
+
// reflect access-control-request-headers
|
|
83
|
+
const allowedHeaders = req.headers['access-control-request-headers'];
|
|
84
|
+
if (allowedHeaders) {
|
|
85
|
+
res.addVaryHeader("Access-Control-Request-Headers");
|
|
86
|
+
res.setHeader("Access-Control-Allow-Headers", allowedHeaders);
|
|
87
|
+
}
|
|
88
|
+
// after preflight
|
|
89
|
+
if (preFlightContinue) {
|
|
90
|
+
return;
|
|
91
|
+
} else {
|
|
92
|
+
await res.asyncEnd({
|
|
93
|
+
headers: {
|
|
94
|
+
"Content-Length": 0
|
|
95
|
+
},
|
|
96
|
+
status: 204,
|
|
97
|
+
body: undefined
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* ReadBuffer
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
export const DEFAULT_READ_BUFFER_LIMIT = 1024 * 8 * 100;
|
|
110
|
+
|
|
111
|
+
const DEFAULT_READ_BUFFER_TIMEOUT = 1000 * 40;
|
|
112
|
+
|
|
113
|
+
export function ReadBuffer(options?: {
|
|
114
|
+
limit?: number;
|
|
115
|
+
timeout?: number;
|
|
116
|
+
}): Handler<void> {
|
|
117
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
118
|
+
let timeout = DEFAULT_READ_BUFFER_TIMEOUT;
|
|
119
|
+
if (options) {
|
|
120
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
121
|
+
timeout = options.timeout !== undefined ? options.timeout : timeout;
|
|
122
|
+
} else {
|
|
123
|
+
const [limitS, timeoutS] =
|
|
124
|
+
checkEnvVariables(["READ_BUFFER_LIMIT", "READ_BUFFER_TIMEOUT"], [String(DEFAULT_READ_BUFFER_LIMIT), String(DEFAULT_READ_BUFFER_TIMEOUT)]);
|
|
125
|
+
limit = parseInt(limitS, 10);
|
|
126
|
+
timeout = parseInt(timeoutS, 10);
|
|
127
|
+
}
|
|
128
|
+
return async function ReadBuffer(req: Request, res: Response): Promise<void> {
|
|
129
|
+
return new Promise<void>((resolve, reject) => {
|
|
130
|
+
try {
|
|
131
|
+
const readTimeout = setTimeout(() => {
|
|
132
|
+
clearTimeout(readTimeout);
|
|
133
|
+
req.removeListener('error', errorListener);
|
|
134
|
+
req.removeListener('data', chunkListener);
|
|
135
|
+
req.removeListener('end', endListener);
|
|
136
|
+
res.asyncClose();
|
|
137
|
+
return;
|
|
138
|
+
}, timeout);
|
|
139
|
+
let cLength = 0;
|
|
140
|
+
const buffers: Buffer[] = [];
|
|
141
|
+
const endListener = () => {
|
|
142
|
+
clearTimeout(readTimeout);
|
|
143
|
+
req.removeListener('error', errorListener);
|
|
144
|
+
req.removeListener('data', chunkListener);
|
|
145
|
+
req.removeListener('end', endListener);
|
|
146
|
+
try {
|
|
147
|
+
const concatBuffers = Buffer.concat(buffers);
|
|
148
|
+
const responseBuffer: Buffer = req.headers["content-encoding"] === "gzip" ?
|
|
149
|
+
gunzipSync(concatBuffers) : concatBuffers;
|
|
150
|
+
req.logger.trace("ctx.buffer %o", responseBuffer);
|
|
151
|
+
req.buffer = responseBuffer;
|
|
152
|
+
resolve();
|
|
153
|
+
} catch (e) {
|
|
154
|
+
reject(e);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const errorListener = (err: Error) => {
|
|
158
|
+
clearTimeout(readTimeout);
|
|
159
|
+
req.removeListener('error', errorListener);
|
|
160
|
+
req.removeListener('data', chunkListener);
|
|
161
|
+
req.removeListener('end', endListener);
|
|
162
|
+
reject(err);
|
|
163
|
+
};
|
|
164
|
+
const chunkListener = (chunk: Buffer) => {
|
|
165
|
+
cLength += chunk.length;
|
|
166
|
+
if (cLength > limit) {
|
|
167
|
+
clearTimeout(readTimeout);
|
|
168
|
+
req.removeListener('error', errorListener);
|
|
169
|
+
req.removeListener('data', chunkListener);
|
|
170
|
+
req.removeListener('end', endListener);
|
|
171
|
+
req.logger.error(`ctx.buffer.length ${cLength} > ${limit}. To accept this body set READ_BUFFER_LIMIT to a higher value.`);
|
|
172
|
+
reject(new BadRequestError(`buffer.length ${cLength} > ${limit}`));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
buffers.push(chunk);
|
|
176
|
+
};
|
|
177
|
+
req.on('error', errorListener);
|
|
178
|
+
req.on('data', chunkListener);
|
|
179
|
+
req.on('end', endListener);
|
|
180
|
+
} catch (e) {
|
|
181
|
+
reject(e);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* URLEncodedParser
|
|
189
|
+
*/
|
|
190
|
+
|
|
191
|
+
const DEFAULT_FORM_MAX_KEYS: undefined | number = undefined;
|
|
192
|
+
|
|
193
|
+
export function URLEncodedParser(options?: {
|
|
194
|
+
limit?: number;
|
|
195
|
+
maxKeys?: number;
|
|
196
|
+
type?: string;
|
|
197
|
+
}): Handler<void> {
|
|
198
|
+
let maxKeys: undefined | number = DEFAULT_FORM_MAX_KEYS;
|
|
199
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
200
|
+
let type = "application/x-www-form-urlencoded";
|
|
201
|
+
if (options) {
|
|
202
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
203
|
+
type = options.type !== undefined ? options.type : type;
|
|
204
|
+
maxKeys = options.maxKeys !== undefined ? options.maxKeys : maxKeys;
|
|
205
|
+
} else {
|
|
206
|
+
const [limitS, typeS, maxKeysS] =
|
|
207
|
+
checkEnvVariables(["BODY_PARSER_URL_ENCODED_LIMIT", "BODY_PARSER_URL_ENCODED_TYPE", "BODY_PARSER_URL_ENCODED_MAX_KEYS"], [String(DEFAULT_READ_BUFFER_LIMIT), "application/x-www-form-urlencoded", String(DEFAULT_FORM_MAX_KEYS)]);
|
|
208
|
+
limit = parseInt(limitS, 10);
|
|
209
|
+
type = typeS;
|
|
210
|
+
maxKeys = maxKeysS !== "undefined" ? parseInt(maxKeysS, 10) : DEFAULT_FORM_MAX_KEYS;
|
|
211
|
+
}
|
|
212
|
+
const readBuffer = ReadBuffer({
|
|
213
|
+
limit
|
|
214
|
+
});
|
|
215
|
+
return async function URLEncodedParser(req: Request, res: Response): Promise<void> {
|
|
216
|
+
try {
|
|
217
|
+
const isType = req.body === undefined && req.headers["content-type"] ? req.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
218
|
+
if (isType && !req.buffer) {
|
|
219
|
+
await readBuffer(req, res);
|
|
220
|
+
}
|
|
221
|
+
if (isType && req.buffer && req.buffer.length <= limit) {
|
|
222
|
+
const string = req.buffer.toString();
|
|
223
|
+
if (string) {
|
|
224
|
+
const body = {
|
|
225
|
+
...queryParse(string, undefined, undefined, {
|
|
226
|
+
maxKeys
|
|
227
|
+
})
|
|
228
|
+
};
|
|
229
|
+
req.logger.debug("ctx.body = %s", body);
|
|
230
|
+
req.body = body;
|
|
231
|
+
}
|
|
232
|
+
} else if (isType && req.buffer && req.buffer.length > limit) {
|
|
233
|
+
req.logger.error(`ctx.buffer.length ${req.buffer.length} > ${limit}. To accept this body set BODY_PARSER_URL_ENCODED_LIMIT to a higher value.`);
|
|
234
|
+
throw new BadRequestError(`buffer.length ${req.buffer.length} > ${limit}`);
|
|
235
|
+
}
|
|
236
|
+
} catch (e: any) {
|
|
237
|
+
if (e && e.name === "BadRequestError") {
|
|
238
|
+
throw e;
|
|
239
|
+
} else {
|
|
240
|
+
req.logger.error(e);
|
|
241
|
+
throw new BadRequestError();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* JSONParser
|
|
249
|
+
*/
|
|
250
|
+
|
|
251
|
+
export function JSONParser(options?: {
|
|
252
|
+
limit?: number;
|
|
253
|
+
strict?: boolean;
|
|
254
|
+
type?: string;
|
|
255
|
+
}): Handler<void> {
|
|
256
|
+
let strict = true;
|
|
257
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
258
|
+
let type = "application/json";
|
|
259
|
+
if (options) {
|
|
260
|
+
strict = options.strict !== undefined ? options.strict : strict;
|
|
261
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
262
|
+
type = options.type !== undefined ? options.type : type;
|
|
263
|
+
} else {
|
|
264
|
+
const [limitS, strictS, typeS] =
|
|
265
|
+
checkEnvVariables(["BODY_PARSER_LIMIT", "BODY_PARSER_STRICT", "BODY_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "true", "application/json"])
|
|
266
|
+
strict = strictS === "true";
|
|
267
|
+
limit = parseInt(limitS, 10);
|
|
268
|
+
type = typeS;
|
|
269
|
+
}
|
|
270
|
+
const readBuffer = ReadBuffer({
|
|
271
|
+
limit
|
|
272
|
+
});
|
|
273
|
+
return async function JSONParser(req, res): Promise<void> {
|
|
274
|
+
try {
|
|
275
|
+
const isType = req.body === undefined && req.headers["content-type"] ? req.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
276
|
+
if (isType && !req.buffer) {
|
|
277
|
+
await readBuffer(req, res);
|
|
278
|
+
}
|
|
279
|
+
if (isType && req.buffer && req.buffer.length <= limit) {
|
|
280
|
+
const string = req.buffer.toString();
|
|
281
|
+
if (string) {
|
|
282
|
+
const parsed = JSON.parse(string);
|
|
283
|
+
if (parsed instanceof Array && strict) {
|
|
284
|
+
throw new BadRequestError(`body cannot be an array`);
|
|
285
|
+
}
|
|
286
|
+
req.logger.debug("ctx.body = %o", parsed);
|
|
287
|
+
req.body = parsed;
|
|
288
|
+
}
|
|
289
|
+
} else if (isType && req.buffer && req.buffer.length > limit) {
|
|
290
|
+
req.logger.error(`ctx.buffer.length ${req.buffer.length} > ${limit}. To accept this body set BODY_PARSER_LIMIT to a higher value.`);
|
|
291
|
+
throw new BadRequestError(`buffer.length ${req.buffer.length} > ${limit}`);
|
|
292
|
+
}
|
|
293
|
+
} catch (e: any) {
|
|
294
|
+
if (e && e.name === "BadRequestError") {
|
|
295
|
+
throw e;
|
|
296
|
+
} else {
|
|
297
|
+
req.logger.error(e);
|
|
298
|
+
throw new BadRequestError();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* TextParser
|
|
306
|
+
*/
|
|
307
|
+
|
|
308
|
+
export function TextParser(options?: {
|
|
309
|
+
limit?: number;
|
|
310
|
+
type?: string;
|
|
311
|
+
}): Handler<void> {
|
|
312
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
313
|
+
let type = "plain/text";
|
|
314
|
+
if (options) {
|
|
315
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
316
|
+
type = options.type !== undefined ? options.type : type;
|
|
317
|
+
} else {
|
|
318
|
+
const [limitS, typeS] =
|
|
319
|
+
checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "plain/text"]);
|
|
320
|
+
limit = parseInt(limitS, 10);
|
|
321
|
+
type = typeS;
|
|
322
|
+
}
|
|
323
|
+
const readBuffer = ReadBuffer({
|
|
324
|
+
limit
|
|
325
|
+
});
|
|
326
|
+
return async function TextParser(req, res): Promise<void> {
|
|
327
|
+
try {
|
|
328
|
+
const isType = req.body === undefined && req.headers["content-type"] ? req.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
329
|
+
if (isType && !req.buffer) {
|
|
330
|
+
await readBuffer(req, res);
|
|
331
|
+
}
|
|
332
|
+
if (isType && req.buffer && req.buffer.length <= limit) {
|
|
333
|
+
const string = req.buffer.toString();
|
|
334
|
+
req.logger.debug("ctx.body = %s", string);
|
|
335
|
+
req.body = string;
|
|
336
|
+
} else if (isType && req.buffer && req.buffer.length > limit) {
|
|
337
|
+
req.logger.error(`ctx.buffer.length ${req.buffer.length} > ${limit}. To accept this body set BODY_TEXT_PARSER_LIMIT to a higher value.`);
|
|
338
|
+
throw new BadRequestError(`buffer.length ${req.buffer.length} > ${limit}`);
|
|
339
|
+
}
|
|
340
|
+
} catch (e: any) {
|
|
341
|
+
if (e && e.name === "BadRequestError") {
|
|
342
|
+
throw e;
|
|
343
|
+
} else {
|
|
344
|
+
req.logger.error(e);
|
|
345
|
+
throw new BadRequestError();
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* ParseRequest
|
|
353
|
+
*/
|
|
354
|
+
|
|
355
|
+
export function assertNotUndefined<T = any>(arg?: T, message?: string): T {
|
|
356
|
+
|
|
357
|
+
if (arg === undefined) {
|
|
358
|
+
throw new Error(message ? message : "arg undefined");
|
|
359
|
+
}
|
|
360
|
+
return arg;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export const DEFAULT_PARSER = new Parser();
|
|
364
|
+
|
|
365
|
+
export interface ParseRequestOptions {
|
|
366
|
+
headers?: string | SchemaProperties | SchemaProperties[];
|
|
367
|
+
headersMode?: ParserMode;
|
|
368
|
+
query?: string | SchemaProperties | boolean | SchemaProperties[];
|
|
369
|
+
queryMode?: ParserMode;
|
|
370
|
+
params?: string | SchemaProperties | boolean | SchemaProperties[];
|
|
371
|
+
paramsMode?: ParserMode;
|
|
372
|
+
body?: string | SchemaProperties | boolean | SchemaProperties[];
|
|
373
|
+
bodyMode?: ParserMode;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const NO_OPTIONS: SchemaProperties[] = [];
|
|
377
|
+
|
|
378
|
+
const ADD_EXTRA: SchemaProperties[] = [];
|
|
379
|
+
|
|
380
|
+
function normalizeParseOptions(option?: string | SchemaProperties | SchemaProperties[] | boolean): { properties: Array<string | SchemaProperties>, mode: ParserMode | undefined; } {
|
|
381
|
+
const mode: ParserMode | undefined = typeof option === "boolean" && option ? "add_extra" : undefined;
|
|
382
|
+
return {
|
|
383
|
+
mode,
|
|
384
|
+
properties: option !== undefined && typeof option !== "string" && typeof option !== "boolean" ?
|
|
385
|
+
(option instanceof Array ? option : [option]) :
|
|
386
|
+
(typeof option === "boolean" ?
|
|
387
|
+
(option ? ADD_EXTRA : NO_OPTIONS) :
|
|
388
|
+
(typeof option === "string" ? [option] : ADD_EXTRA))
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
function parseRequestPart(part: "query" | "body" | "params" | "headers", req: Request, option: Array<SchemaProperties | string>, mode?: ParserMode, parser?: ParserInterface): void {
|
|
394
|
+
if (part === "headers" && mode === undefined) {
|
|
395
|
+
mode = "add_extra";
|
|
396
|
+
}
|
|
397
|
+
const value = req[part] === undefined ? {} : req[part];
|
|
398
|
+
for (let i = 0; i < option.length; i++) {
|
|
399
|
+
const o = option[i];
|
|
400
|
+
try {
|
|
401
|
+
req[part] = (parser ? parser : DEFAULT_PARSER).parse(value as any, typeof o === "string" ? o : {
|
|
402
|
+
type: "object",
|
|
403
|
+
properties: o,
|
|
404
|
+
mode
|
|
405
|
+
}, `${part}`) as any;
|
|
406
|
+
req.logger.debug("req.%s parsed to [%o]", part, req[part]);
|
|
407
|
+
return;
|
|
408
|
+
} catch (e: any) {
|
|
409
|
+
if (i === option.length - 1) {
|
|
410
|
+
throw e;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* ParseRequest
|
|
418
|
+
* @param options
|
|
419
|
+
* @param parser
|
|
420
|
+
* @returns
|
|
421
|
+
*/
|
|
422
|
+
|
|
423
|
+
export function ParseRequest(options: ParseRequestOptions, parser?: ParserInterface): Handler<void> {
|
|
424
|
+
const query = normalizeParseOptions(options.query);
|
|
425
|
+
const params = normalizeParseOptions(options.params);
|
|
426
|
+
const body = normalizeParseOptions(options.body);
|
|
427
|
+
const headers = normalizeParseOptions(options.headers);
|
|
428
|
+
|
|
429
|
+
return function ParseRequest(req): void {
|
|
430
|
+
try {
|
|
431
|
+
try {
|
|
432
|
+
if (options.headers !== undefined) {
|
|
433
|
+
parseRequestPart("headers", req, headers.properties, options.headersMode ? options.headersMode : headers.mode, parser);
|
|
434
|
+
}
|
|
435
|
+
} catch (e) {
|
|
436
|
+
req.logger.error("error parsing headers %o", req.headers);
|
|
437
|
+
throw e;
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
if (options.query !== undefined) {
|
|
441
|
+
parseRequestPart("query", req, query.properties, options.queryMode ? options.queryMode : query.mode, parser);
|
|
442
|
+
}
|
|
443
|
+
} catch (e) {
|
|
444
|
+
req.logger.error("error parsing query %o", req.query);
|
|
445
|
+
throw e;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
try {
|
|
449
|
+
if (options.params !== undefined) {
|
|
450
|
+
parseRequestPart("params", req, params.properties, options.paramsMode ? options.paramsMode : params.mode, parser);
|
|
451
|
+
}
|
|
452
|
+
} catch (e) {
|
|
453
|
+
req.logger.error("error parsing params %o", req.params);
|
|
454
|
+
throw e;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
try {
|
|
458
|
+
if (options.body !== undefined) {
|
|
459
|
+
parseRequestPart("body", req, body.properties, options.bodyMode ? options.bodyMode : body.mode, parser);
|
|
460
|
+
}
|
|
461
|
+
} catch (e: any) {
|
|
462
|
+
req.logger.error("error parsing body %o", req.body);
|
|
463
|
+
throw e;
|
|
464
|
+
}
|
|
465
|
+
} catch (e: any) {
|
|
466
|
+
req.logger.warn("error parsing request: %s", e.message);
|
|
467
|
+
throw e;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* ResultParser
|
|
474
|
+
* @param options
|
|
475
|
+
* @param parser
|
|
476
|
+
* @returns
|
|
477
|
+
*/
|
|
478
|
+
|
|
479
|
+
export function ResultParser(options: {
|
|
480
|
+
status?: number | number[];
|
|
481
|
+
headers?: string | SchemaProperties | SchemaProperties[];
|
|
482
|
+
headersMode?: ParserMode;
|
|
483
|
+
body?: string | boolean | SchemaProperties | SchemaProperties[];
|
|
484
|
+
bodyMode?: ParserMode;
|
|
485
|
+
}, parser?: ParserInterface): Handler {
|
|
486
|
+
const bodyParser = options.body instanceof Array ?
|
|
487
|
+
options.body :
|
|
488
|
+
typeof options.body === "boolean" ?
|
|
489
|
+
options.body === true ?
|
|
490
|
+
["any?"] : [] : (typeof options.body === "string" ? [options.body] : options.body ? [options.body] : ["any?"]);
|
|
491
|
+
const statusParserSet: Set<number> | null = options.status instanceof Array ? new Set(options.status) : options.status !== undefined ? new Set([options.status]) : null;
|
|
492
|
+
const headersParser = options.headers instanceof Array ?
|
|
493
|
+
options.headers :
|
|
494
|
+
typeof options.headers === "boolean" ?
|
|
495
|
+
options.headers === true ?
|
|
496
|
+
["any?"] : [] : (typeof options.headers === "string" ? [options.headers] : options.headers ? [options.headers] : ["any?"]);
|
|
497
|
+
|
|
498
|
+
return async function ResultParser(req, res): Promise<any> {
|
|
499
|
+
if (!req.results || req.results.length === 0) {
|
|
500
|
+
req.logger.debug(`not parsing results`);
|
|
501
|
+
return undefined;
|
|
502
|
+
} else {
|
|
503
|
+
const index = req.results.length - 1;
|
|
504
|
+
const lastResult = req.results[index] ? req.results[index] : undefined;
|
|
505
|
+
req.logger.trace(`parsing lastResult[%o]`, lastResult);
|
|
506
|
+
try {
|
|
507
|
+
const mappedLastResult = {
|
|
508
|
+
...lastResult
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
const parsedStatus = (parser ? parser : DEFAULT_PARSER)
|
|
512
|
+
.parse(lastResult.status, "number?", `ctx.results.status}`) as number | undefined;
|
|
513
|
+
if (statusParserSet) {
|
|
514
|
+
if (parsedStatus === undefined) {
|
|
515
|
+
throw new Error(`error parsing lastResult.status[${lastResult.status}] not defined as [${statusParserSet}]`);
|
|
516
|
+
} else {
|
|
517
|
+
if (statusParserSet.has(parsedStatus)) {
|
|
518
|
+
mappedLastResult.status = parsedStatus;
|
|
519
|
+
req.logger.trace(`ctx.results.status mapped to %o`, mappedLastResult.status);
|
|
520
|
+
} else {
|
|
521
|
+
throw new Error(`error parsing lastResult.status[${lastResult.status}] not defined as [${statusParserSet}]`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
} else {
|
|
525
|
+
mappedLastResult.status = parsedStatus;
|
|
526
|
+
req.logger.trace(`ctx.results.status mapped to %o`, mappedLastResult.status);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
mappedLastResult.body = parsePart(req, "body", lastResult.body, bodyParser, options.bodyMode, parser);
|
|
530
|
+
mappedLastResult.headers = parsePart(req, "headers", lastResult.headers, headersParser, options.headersMode, parser);
|
|
531
|
+
return mappedLastResult;
|
|
532
|
+
} catch (e) {
|
|
533
|
+
req.logger.error(`error parsing lastResult[%o]`, lastResult);
|
|
534
|
+
req.logger.error(e);
|
|
535
|
+
throw e;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* ResponseHandler
|
|
543
|
+
* @param req
|
|
544
|
+
* @param res
|
|
545
|
+
*/
|
|
546
|
+
|
|
547
|
+
export async function ResponseHandler(req: Request, res: Response): Promise<void> {
|
|
548
|
+
req.logger.trace("results [%o]", req.results);
|
|
549
|
+
if (!req.results || req.results.length === 0) {
|
|
550
|
+
throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
|
|
551
|
+
} else {
|
|
552
|
+
const lastResult = req.results[req.results.length - 1];
|
|
553
|
+
req.logger.debug("response [%o]", lastResult);
|
|
554
|
+
if (lastResult !== undefined) {
|
|
555
|
+
const headers = lastResult.headers;
|
|
556
|
+
const body = lastResult.body;
|
|
557
|
+
const status = lastResult.status;
|
|
558
|
+
|
|
559
|
+
const noContentType = (headers && !headers["Content-Type"]) || !headers;
|
|
560
|
+
|
|
561
|
+
if (noContentType) {
|
|
562
|
+
await res.json(body, headers, status);
|
|
563
|
+
} else {
|
|
564
|
+
await res.asyncEnd({
|
|
565
|
+
body,
|
|
566
|
+
headers,
|
|
567
|
+
status
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
} else {
|
|
571
|
+
throw new Error(`no response to send. Is your handler returning a value different than boolean 'true|false' ?`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
function parsePart(req: Request, part: "body" | "headers", value: any, args: Array<string | SchemaProperties>, mode?: ParserMode, parser?: ParserInterface) {
|
|
577
|
+
for (let i = 0; i < args.length; i++) {
|
|
578
|
+
const o = args[i];
|
|
579
|
+
try {
|
|
580
|
+
const mappedResultBody = (parser ? parser : DEFAULT_PARSER).parse(value, typeof o === "string" ? o : {
|
|
581
|
+
type: "object",
|
|
582
|
+
properties: o,
|
|
583
|
+
mode
|
|
584
|
+
}, `ctx.results.${part}`);
|
|
585
|
+
req.logger.trace(`ctx.results.%s mapped to %o`, part, mappedResultBody);
|
|
586
|
+
return mappedResultBody;
|
|
587
|
+
} catch (e) {
|
|
588
|
+
if (i === args.length - 1) {
|
|
589
|
+
throw e;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|