@miqro/core 1.2.5 → 1.3.4
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/README.md +34 -18
- package/dist/handler/api-handler.d.ts +16 -0
- package/dist/handler/api-handler.js +30 -5
- package/dist/handler/api-handler.js.map +1 -0
- package/dist/handler/api-router-utils.js +11 -2
- package/dist/handler/api-router-utils.js.map +1 -0
- package/dist/handler/api-router.d.ts +30 -2
- package/dist/handler/api-router.js +30 -0
- package/dist/handler/api-router.js.map +1 -0
- package/dist/handler/app.d.ts +1 -2
- package/dist/handler/app.js +96 -13
- package/dist/handler/app.js.map +1 -0
- package/dist/handler/common/context.d.ts +57 -0
- package/dist/handler/common/context.js +123 -0
- package/dist/handler/common/context.js.map +1 -0
- package/dist/handler/common/helpers.js +5 -0
- package/dist/handler/common/helpers.js.map +1 -0
- package/dist/handler/common/index.d.ts +2 -45
- package/dist/handler/common/index.js +13 -109
- package/dist/handler/common/index.js.map +1 -0
- package/dist/handler/common/router-utils.d.ts +26 -0
- package/dist/handler/common/router-utils.js +59 -0
- package/dist/handler/common/router-utils.js.map +1 -0
- package/dist/handler/{router.d.ts → common/router.d.ts} +7 -16
- package/dist/handler/common/router.js +76 -0
- package/dist/handler/common/router.js.map +1 -0
- package/dist/handler/common/tokenize-match.d.ts +18 -9
- package/dist/handler/common/tokenize-match.js +42 -30
- package/dist/handler/common/tokenize-match.js.map +1 -0
- package/dist/handler/feature-router.d.ts +1 -2
- package/dist/handler/feature-router.js +3 -2
- package/dist/handler/feature-router.js.map +1 -0
- package/dist/handler/index.d.ts +1 -5
- package/dist/handler/index.js +2 -5
- package/dist/handler/index.js.map +1 -0
- package/dist/{middleware → handler/middleware}/buffer.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/buffer.js +3 -2
- package/dist/handler/middleware/buffer.js.map +1 -0
- package/dist/handler/middleware/cookie.d.ts +4 -0
- package/dist/handler/middleware/cookie.js +18 -0
- package/dist/handler/middleware/cookie.js.map +1 -0
- package/dist/{middleware → handler/middleware}/cors.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/cors.js +10 -2
- package/dist/handler/middleware/cors.js.map +1 -0
- package/dist/{middleware → handler/middleware}/form.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/form.js +8 -5
- package/dist/handler/middleware/form.js.map +1 -0
- package/dist/handler/middleware/group.d.ts +3 -0
- package/dist/handler/{group.js → middleware/group.js} +4 -2
- package/dist/handler/middleware/group.js.map +1 -0
- package/dist/handler/middleware/index.d.ts +13 -0
- package/dist/handler/middleware/index.js +64 -0
- package/dist/handler/middleware/index.js.map +1 -0
- package/dist/{middleware → handler/middleware}/json.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/json.js +3 -2
- package/dist/handler/middleware/json.js.map +1 -0
- package/dist/{middleware → handler/middleware}/logger.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/logger.js +1 -0
- package/dist/handler/middleware/logger.js.map +1 -0
- package/dist/handler/{parse.d.ts → middleware/parse.d.ts} +4 -3
- package/dist/handler/{parse.js → middleware/parse.js} +17 -7
- package/dist/handler/middleware/parse.js.map +1 -0
- package/dist/handler/middleware/session.d.ts +21 -0
- package/dist/handler/middleware/session.js +140 -0
- package/dist/handler/middleware/session.js.map +1 -0
- package/dist/handler/middleware/tag.d.ts +4 -0
- package/dist/handler/middleware/tag.js +14 -0
- package/dist/handler/middleware/tag.js.map +1 -0
- package/dist/{middleware → handler/middleware}/text.d.ts +1 -1
- package/dist/{middleware → handler/middleware}/text.js +3 -2
- package/dist/handler/middleware/text.js.map +1 -0
- package/dist/handler/proxy.js +5 -11
- package/dist/handler/proxy.js.map +1 -0
- package/dist/handler/{html.d.ts → response/html.d.ts} +1 -1
- package/dist/handler/{html.js → response/html.js} +1 -0
- package/dist/handler/response/html.js.map +1 -0
- package/dist/handler/response/index.d.ts +3 -0
- package/dist/{middleware → handler/response}/index.js +3 -7
- package/dist/handler/response/index.js.map +1 -0
- package/dist/handler/{response.d.ts → response/json.d.ts} +1 -1
- package/dist/handler/{response.js → response/json.js} +3 -2
- package/dist/handler/response/json.js.map +1 -0
- package/dist/handler/response/result.d.ts +4 -0
- package/dist/handler/{result.js → response/result.js} +8 -8
- package/dist/handler/response/result.js.map +1 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -0
- package/dist/util/cli/index.js +3 -0
- package/dist/util/cli/index.js.map +1 -0
- package/dist/util/config/browser.js +3 -0
- package/dist/util/config/browser.js.map +1 -0
- package/dist/util/config/config.js +6 -1
- package/dist/util/config/config.js.map +1 -0
- package/dist/util/config/featuretoggle.js +1 -0
- package/dist/util/config/featuretoggle.js.map +1 -0
- package/dist/util/config/index.js +1 -0
- package/dist/util/config/index.js.map +1 -0
- package/dist/util/cookie/cookie.d.ts +50 -0
- package/dist/util/cookie/cookie.js +168 -0
- package/dist/util/cookie/cookie.js.map +1 -0
- package/dist/util/cookie/index.d.ts +16 -0
- package/dist/util/cookie/index.js +9 -0
- package/dist/util/cookie/index.js.map +1 -0
- package/dist/util/error/configfilenotfound.js +1 -0
- package/dist/util/error/configfilenotfound.js.map +1 -0
- package/dist/util/error/forbiddenerror.js +1 -0
- package/dist/util/error/forbiddenerror.js.map +1 -0
- package/dist/util/error/index.js +1 -0
- package/dist/util/error/index.js.map +1 -0
- package/dist/util/error/named.js +1 -0
- package/dist/util/error/named.js.map +1 -0
- package/dist/util/error/notfound.js +1 -0
- package/dist/util/error/notfound.js.map +1 -0
- package/dist/util/error/notimplemented.js +1 -0
- package/dist/util/error/notimplemented.js.map +1 -0
- package/dist/util/error/parsererror.js +1 -0
- package/dist/util/error/parsererror.js.map +1 -0
- package/dist/util/error/unauthorizederror.js +1 -0
- package/dist/util/error/unauthorizederror.js.map +1 -0
- package/dist/util/index.js +3 -0
- package/dist/util/index.js.map +1 -0
- package/dist/util/loader/index.js +1 -0
- package/dist/util/loader/index.js.map +1 -0
- package/dist/util/logger/common.js +1 -0
- package/dist/util/logger/common.js.map +1 -0
- package/dist/util/logger/factory.js +1 -0
- package/dist/util/logger/factory.js.map +1 -0
- package/dist/util/logger/formatter.js +1 -0
- package/dist/util/logger/formatter.js.map +1 -0
- package/dist/util/logger/index.js +1 -0
- package/dist/util/logger/index.js.map +1 -0
- package/dist/util/logger/logger.js +12 -2
- package/dist/util/logger/logger.js.map +1 -0
- package/dist/util/logger/transport.js +1 -0
- package/dist/util/logger/transport.js.map +1 -0
- package/dist/util/parser/common.d.ts +5 -5
- package/dist/util/parser/common.js +1 -0
- package/dist/util/parser/common.js.map +1 -0
- package/dist/util/parser/get.js +11 -1
- package/dist/util/parser/get.js.map +1 -0
- package/dist/util/parser/index.js +1 -0
- package/dist/util/parser/index.js.map +1 -0
- package/dist/util/parser/parser.d.ts +24 -3
- package/dist/util/parser/parser.js +46 -11
- package/dist/util/parser/parser.js.map +1 -0
- package/dist/util/parser/types/any.js +1 -0
- package/dist/util/parser/types/any.js.map +1 -0
- package/dist/util/parser/types/array.js +1 -0
- package/dist/util/parser/types/array.js.map +1 -0
- package/dist/util/parser/types/boolean.js +1 -0
- package/dist/util/parser/types/boolean.js.map +1 -0
- package/dist/util/parser/types/email.js +1 -0
- package/dist/util/parser/types/email.js.map +1 -0
- package/dist/util/parser/types/enum.js +1 -0
- package/dist/util/parser/types/enum.js.map +1 -0
- package/dist/util/parser/types/index.js +1 -0
- package/dist/util/parser/types/index.js.map +1 -0
- package/dist/util/parser/types/multiple.js +6 -2
- package/dist/util/parser/types/multiple.js.map +1 -0
- package/dist/util/parser/types/nested.js +1 -0
- package/dist/util/parser/types/nested.js.map +1 -0
- package/dist/util/parser/types/number.js +1 -0
- package/dist/util/parser/types/number.js.map +1 -0
- package/dist/util/parser/types/object.js +1 -0
- package/dist/util/parser/types/object.js.map +1 -0
- package/dist/util/parser/types/regex.js +1 -0
- package/dist/util/parser/types/regex.js.map +1 -0
- package/dist/util/parser/types/string.js +1 -0
- package/dist/util/parser/types/string.js.map +1 -0
- package/dist/util/parser/types/url.js +1 -0
- package/dist/util/parser/types/url.js.map +1 -0
- package/dist/util/request/common.d.ts +9 -0
- package/dist/util/request/common.js +101 -1
- package/dist/util/request/common.js.map +1 -0
- package/dist/util/request/index.js +143 -185
- package/dist/util/request/index.js.map +1 -0
- package/dist/util/session/common.d.ts +16 -0
- package/dist/util/session/common.js +49 -0
- package/dist/util/session/common.js.map +1 -0
- package/dist/util/session/index.d.ts +2 -16
- package/dist/util/session/index.js +13 -46
- package/dist/util/session/index.js.map +1 -0
- package/dist/util/session/service.d.ts +26 -0
- package/dist/util/session/service.js +143 -0
- package/dist/util/session/service.js.map +1 -0
- package/dist/util/test/app.js +5 -1
- package/dist/util/test/app.js.map +1 -0
- package/dist/util/test/common.js +1 -0
- package/dist/util/test/common.js.map +1 -0
- package/dist/util/test/index.js +1 -0
- package/dist/util/test/index.js.map +1 -0
- package/dist/util/uuid/index.d.ts +7 -0
- package/dist/util/uuid/index.js +8 -0
- package/dist/util/uuid/index.js.map +1 -0
- package/dist/util/uuid/regex.d.ts +2 -0
- package/dist/util/uuid/regex.js +5 -0
- package/dist/util/uuid/regex.js.map +1 -0
- package/dist/util/uuid/rng.d.ts +1 -0
- package/dist/util/uuid/rng.js +18 -0
- package/dist/util/uuid/rng.js.map +1 -0
- package/dist/util/uuid/stringify.d.ts +2 -0
- package/dist/util/uuid/stringify.js +50 -0
- package/dist/util/uuid/stringify.js.map +1 -0
- package/dist/util/uuid/v4.d.ts +5 -0
- package/dist/util/uuid/v4.js +27 -0
- package/dist/util/uuid/v4.js.map +1 -0
- package/dist/util/uuid/validate.d.ts +2 -0
- package/dist/util/uuid/validate.js +12 -0
- package/dist/util/uuid/validate.js.map +1 -0
- package/package.json +11 -13
- package/src/handler/api-handler.ts +56 -0
- package/src/handler/api-router-utils.ts +101 -0
- package/src/handler/api-router.ts +60 -0
- package/src/handler/app.ts +138 -0
- package/src/handler/common/context.ts +161 -0
- package/src/handler/common/helpers.ts +11 -0
- package/src/handler/common/index.ts +3 -0
- package/src/handler/common/router-utils.ts +67 -0
- package/src/handler/common/router.ts +70 -0
- package/src/handler/common/tokenize-match.ts +152 -0
- package/src/handler/feature-router.ts +90 -0
- package/src/handler/index.ts +8 -0
- package/src/handler/middleware/buffer.ts +79 -0
- package/src/handler/middleware/cookie.ts +19 -0
- package/src/handler/middleware/cors.ts +98 -0
- package/src/handler/middleware/form.ts +53 -0
- package/src/handler/middleware/group.ts +28 -0
- package/src/handler/middleware/index.ts +52 -0
- package/src/handler/middleware/json.ts +50 -0
- package/src/handler/middleware/logger.ts +18 -0
- package/src/handler/middleware/parse.ts +93 -0
- package/src/handler/middleware/session.ts +155 -0
- package/src/handler/middleware/tag.ts +15 -0
- package/src/handler/middleware/text.ts +40 -0
- package/src/handler/proxy.ts +44 -0
- package/src/handler/response/html.ts +36 -0
- package/src/handler/response/index.ts +3 -0
- package/src/handler/response/json.ts +19 -0
- package/src/handler/response/result.ts +40 -0
- package/src/index.ts +2 -0
- package/src/util/cli/index.ts +57 -0
- package/src/util/config/browser.ts +5 -0
- package/src/util/config/config.ts +93 -0
- package/src/util/config/featuretoggle.ts +6 -0
- package/src/util/config/index.ts +3 -0
- package/src/util/cookie/cookie.ts +207 -0
- package/src/util/cookie/index.ts +6 -0
- package/src/util/error/configfilenotfound.ts +8 -0
- package/src/util/error/forbiddenerror.ts +8 -0
- package/src/util/error/index.ts +6 -0
- package/src/util/error/named.ts +3 -0
- package/src/util/error/notfound.ts +8 -0
- package/src/util/error/notimplemented.ts +8 -0
- package/src/util/error/parsererror.ts +10 -0
- package/src/util/error/unauthorizederror.ts +8 -0
- package/src/util/index.ts +11 -0
- package/src/util/loader/index.ts +67 -0
- package/src/util/logger/common.ts +6 -0
- package/src/util/logger/factory.ts +45 -0
- package/src/util/logger/formatter.ts +9 -0
- package/src/util/logger/index.ts +6 -0
- package/src/util/logger/logger.ts +114 -0
- package/src/util/logger/transport.ts +69 -0
- package/src/util/parser/common.ts +81 -0
- package/src/util/parser/get.ts +42 -0
- package/src/util/parser/index.ts +6 -0
- package/src/util/parser/parser.ts +235 -0
- package/src/util/parser/types/any.ts +8 -0
- package/src/util/parser/types/array.ts +73 -0
- package/src/util/parser/types/boolean.ts +13 -0
- package/src/util/parser/types/email.ts +26 -0
- package/src/util/parser/types/enum.ts +29 -0
- package/src/util/parser/types/index.ts +12 -0
- package/src/util/parser/types/multiple.ts +36 -0
- package/src/util/parser/types/nested.ts +19 -0
- package/src/util/parser/types/number.ts +34 -0
- package/src/util/parser/types/object.ts +10 -0
- package/src/util/parser/types/regex.ts +17 -0
- package/src/util/parser/types/string.ts +23 -0
- package/src/util/parser/types/url.ts +35 -0
- package/src/util/request/common.ts +193 -0
- package/src/util/request/index.ts +230 -0
- package/src/util/session/common.ts +63 -0
- package/src/util/session/index.ts +2 -0
- package/src/util/session/service.ts +154 -0
- package/src/util/test/app.ts +44 -0
- package/src/util/test/common.ts +17 -0
- package/src/util/test/index.ts +2 -0
- package/src/util/uuid/index.ts +5 -0
- package/src/util/uuid/regex.ts +2 -0
- package/src/util/uuid/rng.ts +14 -0
- package/src/util/uuid/stringify.ts +53 -0
- package/src/util/uuid/v4.ts +30 -0
- package/src/util/uuid/validate.ts +8 -0
- package/tsconfig.json +32 -0
- package/dist/handler/common/response.d.ts +0 -13
- package/dist/handler/common/response.js +0 -54
- package/dist/handler/error.d.ts +0 -2
- package/dist/handler/error.js +0 -46
- package/dist/handler/group.d.ts +0 -3
- package/dist/handler/result.d.ts +0 -4
- package/dist/handler/router.js +0 -116
- package/dist/middleware/index.d.ts +0 -6
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { URLSearchParams } from "url";
|
|
2
|
+
import { newURLSearchParams } from "./helpers";
|
|
3
|
+
|
|
4
|
+
export const parseSearchParams = (search: URLSearchParams): { [name: string]: string | string[] } => {
|
|
5
|
+
const query: { [name: string]: string | string[] } = {};
|
|
6
|
+
search.forEach((value: string, key: string) => {
|
|
7
|
+
query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
|
|
8
|
+
});
|
|
9
|
+
return query;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// appends query params to URLSearchParams and returns a copy
|
|
13
|
+
export const mergeSearchParams = (search: URLSearchParams, append?: { [name: string]: string | string[] | number | boolean | number[] | boolean[] }): URLSearchParams => {
|
|
14
|
+
const copy = newURLSearchParams(search.toString());
|
|
15
|
+
if (!append) {
|
|
16
|
+
return copy;
|
|
17
|
+
}
|
|
18
|
+
const keys = Object.keys(append);
|
|
19
|
+
for (const k of keys) {
|
|
20
|
+
if (append[k] instanceof Array) {
|
|
21
|
+
for (const a of append[k] as Array<any>) {
|
|
22
|
+
if (copy.has(k)) {
|
|
23
|
+
copy.append(k, String(a));
|
|
24
|
+
} else {
|
|
25
|
+
copy.set(k, String(a));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
if (copy.has(k)) {
|
|
31
|
+
copy.append(k, String(append[k]));
|
|
32
|
+
} else {
|
|
33
|
+
copy.set(k, String(append[k]));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return copy;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// adds "/" to the final of path
|
|
41
|
+
// cannot account for query or hash params so send only new URL().pathname
|
|
42
|
+
export const normalizePath = (path: string): string => {
|
|
43
|
+
if (typeof path !== "string") {
|
|
44
|
+
throw new Error("path not string");
|
|
45
|
+
}
|
|
46
|
+
if (path.length > 1) {
|
|
47
|
+
if (path.charAt(0) !== "/") {
|
|
48
|
+
throw new Error("path doesnt start with /");
|
|
49
|
+
}
|
|
50
|
+
if (path[path.length - 1] !== "/") {
|
|
51
|
+
return `${path}/`;
|
|
52
|
+
} else {
|
|
53
|
+
return path; // already normalized
|
|
54
|
+
}
|
|
55
|
+
} else if (path !== "/") {
|
|
56
|
+
throw new Error("path of length 1 not /");
|
|
57
|
+
} else {
|
|
58
|
+
return path; // "/"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface PathPartToken {
|
|
63
|
+
optional: boolean;
|
|
64
|
+
wild?: string;
|
|
65
|
+
token: string;
|
|
66
|
+
lower: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const pathPartTokenize = (token: { value: string; lower: string; }): PathPartToken => {
|
|
70
|
+
const isWild = token.value[0] === ":";
|
|
71
|
+
const optional = token.value[token.value.length - 1] === "?";
|
|
72
|
+
const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
|
|
73
|
+
return {
|
|
74
|
+
optional,
|
|
75
|
+
wild,
|
|
76
|
+
token: token.value,
|
|
77
|
+
lower: token.lower
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const splitPath = (path?: string): { value: string; lower: string; }[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
|
|
82
|
+
return {
|
|
83
|
+
value: p,
|
|
84
|
+
lower: p.toLocaleLowerCase()
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
export const tokenizePath = (path?: string): PathPartToken[] => {
|
|
89
|
+
if (path === undefined) {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
const tokens = splitPath(path).map(token => pathPartTokenize(token));
|
|
93
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
94
|
+
if (tokens[i].optional && i != tokens.length - 1) {
|
|
95
|
+
throw new Error("cannot set a path token as optional that's not the last one");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return tokens;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const matchTokenizePath = (checkAsRouter: boolean, tokens: PathPartToken[], ctxTokens: { value: string; lower: string; }[]): {
|
|
102
|
+
match: boolean;
|
|
103
|
+
params?: { [name: string]: string | undefined }
|
|
104
|
+
} => {
|
|
105
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
106
|
+
if (tokens[i].optional && i != tokens.length - 1) {
|
|
107
|
+
throw new Error("cannot set a path token as optional that's not the last one");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const lastTokenIsOptional = tokens.length > 0 ? tokens[tokens.length - 1].optional : false;
|
|
111
|
+
const couldBeUsingOptional = (lastTokenIsOptional &&
|
|
112
|
+
(
|
|
113
|
+
(!checkAsRouter && tokens.length - 1 === ctxTokens.length) ||
|
|
114
|
+
(checkAsRouter && tokens.length - 1 <= ctxTokens.length)
|
|
115
|
+
)
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
const params: { [name: string]: string | undefined } = {};
|
|
119
|
+
|
|
120
|
+
if ((!checkAsRouter && tokens.length === ctxTokens.length) || couldBeUsingOptional || (checkAsRouter && tokens.length <= ctxTokens.length)) {
|
|
121
|
+
// similiar count of tokens
|
|
122
|
+
for (let i = 0; i < ctxTokens.length; i++) {
|
|
123
|
+
const ctxToken = ctxTokens[i];
|
|
124
|
+
if (checkAsRouter && i >= tokens.length) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (tokens[i].wild || ctxToken.lower === tokens[i].lower) {
|
|
129
|
+
// check pass
|
|
130
|
+
const wild = tokens[i].wild;
|
|
131
|
+
if (wild) {
|
|
132
|
+
params[wild] = ctxToken.value;
|
|
133
|
+
}
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
match: false,
|
|
139
|
+
params: {}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
match: true,
|
|
144
|
+
params
|
|
145
|
+
};
|
|
146
|
+
} else {
|
|
147
|
+
return {
|
|
148
|
+
match: false,
|
|
149
|
+
params: {}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { SimpleMap } from "../util/parser/common";
|
|
2
|
+
import { Logger } from "../util/logger";
|
|
3
|
+
import { isFeatureEnabled } from "../util/config/featuretoggle";
|
|
4
|
+
import { normalizePath } from "./common/tokenize-match";
|
|
5
|
+
import { Router, Handler, Method } from "./common";
|
|
6
|
+
|
|
7
|
+
export interface FeatureRouterPathOptions {
|
|
8
|
+
path: string | string[];
|
|
9
|
+
method: Method | Method[];
|
|
10
|
+
handler: Array<Handler> | Handler;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type FeatureRouterOptions<T extends FeatureRouterPathOptions = FeatureRouterPathOptions> = SimpleMap<T>;
|
|
14
|
+
|
|
15
|
+
const FEATURE_ROUTER_METHODS: Method[] = ["get", "post", "put", "delete", "patch", "options"];
|
|
16
|
+
|
|
17
|
+
export const FeatureRouter = (options: FeatureRouterOptions, logger?: Logger): Router => {
|
|
18
|
+
const router: Router = new Router();
|
|
19
|
+
const toSetup = Object.keys(options);
|
|
20
|
+
const enabled: string[] = [];
|
|
21
|
+
const disabled: string[] = [];
|
|
22
|
+
const enabledPaths: SimpleMap<string> = {};
|
|
23
|
+
for (const featureName of toSetup) {
|
|
24
|
+
const handlerOptions = options[featureName];
|
|
25
|
+
if (!handlerOptions) {
|
|
26
|
+
throw new Error(`no handler options for feature [${featureName}]`);
|
|
27
|
+
} else {
|
|
28
|
+
const { path, handler: implementation, method } = handlerOptions;
|
|
29
|
+
if (!method) {
|
|
30
|
+
throw new Error(`no methods for feature [${featureName}]`);
|
|
31
|
+
} else if (!implementation) {
|
|
32
|
+
throw new Error(`no implementation for feature [${featureName}]`);
|
|
33
|
+
} else if (!path) {
|
|
34
|
+
throw new Error(`no path for feature [${featureName}]`);
|
|
35
|
+
} else {
|
|
36
|
+
if (method instanceof Array) {
|
|
37
|
+
for (const m of method) {
|
|
38
|
+
if (FEATURE_ROUTER_METHODS.indexOf(m.toLowerCase() as Method) === -1) {
|
|
39
|
+
throw new Error(`feature [${featureName}] method [${m.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
} else if (FEATURE_ROUTER_METHODS.indexOf(method.toLowerCase() as Method) === -1) {
|
|
43
|
+
throw new Error(`feature [${featureName}] method [${method.toUpperCase()}] not defined! use only [${FEATURE_ROUTER_METHODS.join(",")}]`);
|
|
44
|
+
}
|
|
45
|
+
const methods = method instanceof Array ? method : [method];
|
|
46
|
+
if (isFeatureEnabled(featureName)) {
|
|
47
|
+
if (logger) {
|
|
48
|
+
logger.trace(`feature [${featureName}] enabled`);
|
|
49
|
+
}
|
|
50
|
+
enabled.push(featureName);
|
|
51
|
+
const paths = path instanceof Array ? path : [path];
|
|
52
|
+
for (const nnP of paths) {
|
|
53
|
+
const p = normalizePath(nnP);
|
|
54
|
+
for (const m of methods) {
|
|
55
|
+
if (logger) {
|
|
56
|
+
logger.info("%s", featureName);
|
|
57
|
+
logger.info("\t%s:%s", m.toUpperCase(), p);
|
|
58
|
+
if ((handlerOptions as any).___filePath) {
|
|
59
|
+
logger.info("\t%s", (handlerOptions as any).___filePath);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (enabledPaths[`${p}${m}`] !== undefined) {
|
|
63
|
+
throw new Error(`${featureName} collides with feature ${enabledPaths[`${p}${m}`]} on path ${p} method ${m}`)
|
|
64
|
+
}
|
|
65
|
+
enabledPaths[`${p}${m}`] = featureName;
|
|
66
|
+
router.use(implementation, p, m.toLocaleLowerCase() as Method);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} else {
|
|
70
|
+
if (logger) {
|
|
71
|
+
logger.debug("feature [%s] disabled", featureName);
|
|
72
|
+
}
|
|
73
|
+
disabled.push(featureName);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (logger && enabled.length > 0) {
|
|
79
|
+
logger.debug("enabled features [%s]", enabled.join(","));
|
|
80
|
+
}
|
|
81
|
+
if (logger) {
|
|
82
|
+
if (disabled.length > 0) {
|
|
83
|
+
logger.warn("disabled features [%s]", disabled.join(","));
|
|
84
|
+
logger.warn(`to enable them just add the env var <feature>=true`);
|
|
85
|
+
} else {
|
|
86
|
+
logger.debug(`no features disabled`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return router;
|
|
90
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { gunzipSync } from "zlib";
|
|
2
|
+
import { Context, Handler } from "../common";
|
|
3
|
+
import { BadRequestError } from "../../util/error";
|
|
4
|
+
import { checkEnvVariables } from "../../util/config";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_READ_BUFFER_LIMIT = 1024 * 8 * 100;
|
|
7
|
+
|
|
8
|
+
const DEFAULT_READ_BUFFER_TIMEOUT = 1000 * 40;
|
|
9
|
+
|
|
10
|
+
export const ReadBuffer = (options?: {
|
|
11
|
+
limit?: number;
|
|
12
|
+
timeout?: number;
|
|
13
|
+
}): Handler<void> => {
|
|
14
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
15
|
+
let timeout = DEFAULT_READ_BUFFER_TIMEOUT;
|
|
16
|
+
if (options) {
|
|
17
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
18
|
+
timeout = options.timeout !== undefined ? options.timeout : timeout;
|
|
19
|
+
} else {
|
|
20
|
+
const [limitS, timeoutS] =
|
|
21
|
+
checkEnvVariables(["READ_BUFFER_LIMIT", "READ_BUFFER_TIMEOUT"], [String(DEFAULT_READ_BUFFER_LIMIT), String(DEFAULT_READ_BUFFER_TIMEOUT)]);
|
|
22
|
+
limit = parseInt(limitS, 10);
|
|
23
|
+
timeout = parseInt(timeoutS, 10);
|
|
24
|
+
}
|
|
25
|
+
return async (ctx: Context): Promise<void> => new Promise<void>((resolve, reject) => {
|
|
26
|
+
try {
|
|
27
|
+
const readTimeout = setTimeout(() => {
|
|
28
|
+
clearTimeout(readTimeout);
|
|
29
|
+
ctx.req.removeListener('error', errorListener);
|
|
30
|
+
ctx.req.removeListener('data', chunkListener);
|
|
31
|
+
ctx.req.removeListener('end', endListener);
|
|
32
|
+
ctx.close();
|
|
33
|
+
return;
|
|
34
|
+
}, timeout);
|
|
35
|
+
let cLength = 0;
|
|
36
|
+
const buffers: Buffer[] = [];
|
|
37
|
+
const endListener = () => {
|
|
38
|
+
clearTimeout(readTimeout);
|
|
39
|
+
ctx.req.removeListener('error', errorListener);
|
|
40
|
+
ctx.req.removeListener('data', chunkListener);
|
|
41
|
+
ctx.req.removeListener('end', endListener);
|
|
42
|
+
try {
|
|
43
|
+
const concatBuffers = Buffer.concat(buffers);
|
|
44
|
+
const responseBuffer: Buffer = ctx.headers["content-encoding"] === "gzip" ?
|
|
45
|
+
gunzipSync(concatBuffers) : concatBuffers;
|
|
46
|
+
ctx.buffer = responseBuffer;
|
|
47
|
+
resolve();
|
|
48
|
+
} catch (e) {
|
|
49
|
+
reject(e);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const errorListener = (err: Error) => {
|
|
53
|
+
clearTimeout(readTimeout);
|
|
54
|
+
ctx.req.removeListener('error', errorListener);
|
|
55
|
+
ctx.req.removeListener('data', chunkListener);
|
|
56
|
+
ctx.req.removeListener('end', endListener);
|
|
57
|
+
reject(err);
|
|
58
|
+
};
|
|
59
|
+
const chunkListener = (chunk: Buffer) => {
|
|
60
|
+
cLength += chunk.length;
|
|
61
|
+
if (cLength > limit) {
|
|
62
|
+
clearTimeout(readTimeout);
|
|
63
|
+
ctx.req.removeListener('error', errorListener);
|
|
64
|
+
ctx.req.removeListener('data', chunkListener);
|
|
65
|
+
ctx.req.removeListener('end', endListener);
|
|
66
|
+
ctx.logger.error(`ctx.buffer.length ${cLength} > ${limit}. To accept this body set READ_BUFFER_LIMIT to a higher value.`);
|
|
67
|
+
reject(new BadRequestError(`buffer.length ${cLength} > ${limit}`));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
buffers.push(chunk);
|
|
71
|
+
};
|
|
72
|
+
ctx.req.on('error', errorListener);
|
|
73
|
+
ctx.req.on('data', chunkListener);
|
|
74
|
+
ctx.req.on('end', endListener);
|
|
75
|
+
} catch (e) {
|
|
76
|
+
reject(e);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Handler, Context } from "../common";
|
|
2
|
+
|
|
3
|
+
import { COOKIE } from "../../util/cookie";
|
|
4
|
+
|
|
5
|
+
export const CookieParser = (options?: {
|
|
6
|
+
decode?(value: string): string;
|
|
7
|
+
}): Handler<void> => {
|
|
8
|
+
return async (ctx: Context): Promise<void> => {
|
|
9
|
+
const cookies = COOKIE.parse(ctx.headers.cookie || '', options);
|
|
10
|
+
const cookieList = Object.keys(cookies);
|
|
11
|
+
for (const name of cookieList) {
|
|
12
|
+
const value = cookies[name];
|
|
13
|
+
if (value) {
|
|
14
|
+
ctx.cookies[name] = value;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Context, Handler } from "../common";
|
|
2
|
+
import { checkEnvVariables } from "../../util/config";
|
|
3
|
+
import { BadRequestError } from "../../util/error";
|
|
4
|
+
|
|
5
|
+
const DEFAULT_CORS_ORIGINS = "*";
|
|
6
|
+
const DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
|
|
7
|
+
const DEFAULT_CORS_PREFLIGHT_CONTINUE = false;
|
|
8
|
+
|
|
9
|
+
export interface CORSOptions {
|
|
10
|
+
origins: string[] | string | undefined;
|
|
11
|
+
validate?: (origin: string | undefined, origins: string[] | string) => boolean;
|
|
12
|
+
methods?: string;
|
|
13
|
+
preflightContinue?: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const isOriginAllowed = (origin: string | undefined, origins: string[] | string): boolean => {
|
|
17
|
+
if (origins instanceof Array) {
|
|
18
|
+
for (const o of origins) {
|
|
19
|
+
if (origin === o || o === "*") {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
} else {
|
|
25
|
+
return origin === origins;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const CORS = (options?: CORSOptions): Handler<void> => {
|
|
30
|
+
let origins: string[] | undefined | string;
|
|
31
|
+
let methods: string;
|
|
32
|
+
let preFlightContinue = false;
|
|
33
|
+
if (options) {
|
|
34
|
+
origins = options.origins instanceof Array ? options.origins : (options.origins ? [options.origins] : undefined);
|
|
35
|
+
methods = options.methods ? options.methods : DEFAULT_CORS_METHODS;
|
|
36
|
+
preFlightContinue = options.preflightContinue ? true : false;
|
|
37
|
+
} else {
|
|
38
|
+
const [originsS, preFlightContinueS, methodsS] =
|
|
39
|
+
checkEnvVariables(["CORS_ORIGINS", "CORS_PREFLIGHT_CONTINUE", "CORS_METHODS"], [DEFAULT_CORS_ORIGINS, String(DEFAULT_CORS_PREFLIGHT_CONTINUE), DEFAULT_CORS_METHODS]);
|
|
40
|
+
origins = originsS.split(",").map(s => s.trim());
|
|
41
|
+
methods = methodsS;
|
|
42
|
+
preFlightContinue = preFlightContinueS.toLocaleLowerCase() === "true";
|
|
43
|
+
}
|
|
44
|
+
if (origins && origins.length === 1) {
|
|
45
|
+
origins = origins[0];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const validate: (origin: string | undefined, origins: string[] | string) => boolean =
|
|
49
|
+
options && options.validate ? options && options.validate : isOriginAllowed;
|
|
50
|
+
|
|
51
|
+
return async (ctx: Context): Promise<void> => {
|
|
52
|
+
// access-control-allow-origin
|
|
53
|
+
if (!origins || origins === '*') {
|
|
54
|
+
// allow any origin
|
|
55
|
+
ctx.setHeader("Access-Control-Allow-Origin", "*");
|
|
56
|
+
ctx.addVaryHeader("Origin");
|
|
57
|
+
} else {
|
|
58
|
+
if (ctx.headers.origin) {
|
|
59
|
+
if (validate(ctx.headers.origin, origins)) {
|
|
60
|
+
// reflect origin
|
|
61
|
+
ctx.setHeader("Access-Control-Allow-Origin", String(ctx.headers.origin));
|
|
62
|
+
ctx.addVaryHeader("Origin");
|
|
63
|
+
} else {
|
|
64
|
+
// not allowed
|
|
65
|
+
throw new BadRequestError(`bad origin`);
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
ctx.setHeader("Access-Control-Allow-Origin", origins instanceof Array ? origins[0] : origins);
|
|
69
|
+
ctx.addVaryHeader("Origin");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (ctx.method.toUpperCase() === "OPTIONS") {
|
|
74
|
+
// access-control-request-headers
|
|
75
|
+
if (methods) {
|
|
76
|
+
ctx.setHeader("Access-Control-Allow-Methods", methods);
|
|
77
|
+
}
|
|
78
|
+
// reflect access-control-request-headers
|
|
79
|
+
const allowedHeaders = ctx.headers['access-control-request-headers'];
|
|
80
|
+
if (allowedHeaders) {
|
|
81
|
+
ctx.addVaryHeader("Access-Control-Request-Headers");
|
|
82
|
+
ctx.setHeader("Access-Control-Allow-Headers", allowedHeaders);
|
|
83
|
+
}
|
|
84
|
+
// after preflight
|
|
85
|
+
if (preFlightContinue) {
|
|
86
|
+
return;
|
|
87
|
+
} else {
|
|
88
|
+
ctx.end({
|
|
89
|
+
headers: {
|
|
90
|
+
"Content-Length": 0
|
|
91
|
+
},
|
|
92
|
+
status: 204,
|
|
93
|
+
body: undefined
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { parse as queryParse } from "querystring";
|
|
2
|
+
import { Context, Handler } from "../common";
|
|
3
|
+
import { BadRequestError } from "../../util/error";
|
|
4
|
+
import { checkEnvVariables } from "../../util/config";
|
|
5
|
+
import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_FORM_MAX_KEYS = undefined;
|
|
8
|
+
|
|
9
|
+
export const URLEncodedParser = (options?: {
|
|
10
|
+
limit?: number;
|
|
11
|
+
maxKeys?: number;
|
|
12
|
+
type?: string;
|
|
13
|
+
}): Handler<void> => {
|
|
14
|
+
let maxKeys: undefined | number = DEFAULT_FORM_MAX_KEYS;
|
|
15
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
16
|
+
let type = "application/x-www-form-urlencoded";
|
|
17
|
+
if (options) {
|
|
18
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
19
|
+
type = options.type !== undefined ? options.type : type;
|
|
20
|
+
maxKeys = options.maxKeys !== undefined ? options.maxKeys : maxKeys;
|
|
21
|
+
} else {
|
|
22
|
+
const [limitS, typeS, maxKeysS] =
|
|
23
|
+
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)]);
|
|
24
|
+
limit = parseInt(limitS, 10);
|
|
25
|
+
type = typeS;
|
|
26
|
+
maxKeys = maxKeysS !== "undefined" ? parseInt(maxKeysS, 10) : DEFAULT_FORM_MAX_KEYS;
|
|
27
|
+
}
|
|
28
|
+
return async (ctx: Context): Promise<void> => {
|
|
29
|
+
try {
|
|
30
|
+
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
31
|
+
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
32
|
+
const string = ctx.buffer.toString();
|
|
33
|
+
if (string) {
|
|
34
|
+
ctx.body = {
|
|
35
|
+
...queryParse(string, undefined, undefined, {
|
|
36
|
+
maxKeys
|
|
37
|
+
})
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
41
|
+
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_PARSER_URL_ENCODED_LIMIT to a higher value.`);
|
|
42
|
+
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
43
|
+
}
|
|
44
|
+
} catch (e: any) {
|
|
45
|
+
if (e && e.name === "ParseOptionsError") {
|
|
46
|
+
throw e;
|
|
47
|
+
} else {
|
|
48
|
+
ctx.logger.error(e);
|
|
49
|
+
throw new BadRequestError();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { GroupPolicy, policyCheck } from "../../util/session";
|
|
2
|
+
import { ForbiddenError, UnAuthorizedError } from "../../util/error";
|
|
3
|
+
import { Context, Handler } from "../common";
|
|
4
|
+
|
|
5
|
+
export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
|
|
6
|
+
return async (ctx: Context): Promise<void> => {
|
|
7
|
+
try {
|
|
8
|
+
if (!ctx.session) {
|
|
9
|
+
throw new UnAuthorizedError(`No Session!`);
|
|
10
|
+
} else {
|
|
11
|
+
const result = await policyCheck(ctx.session, options);
|
|
12
|
+
if (result) {
|
|
13
|
+
ctx.logger.debug("groups validated!");
|
|
14
|
+
} else {
|
|
15
|
+
ctx.logger.error("%sgroups fail to validate!", ctx && ctx.session && ctx.session.groups ? `[${ctx.session.groups.join(",")}] ` : "");
|
|
16
|
+
throw new ForbiddenError(`Invalid session. You are not permitted to do this!`);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
} catch (e: any) {
|
|
20
|
+
//(logger as Logger).warn(`request[${req.uuid}] message[${e.message}] stack[${e.stack}]`);
|
|
21
|
+
if (e.name && e.name !== "Error") {
|
|
22
|
+
throw e;
|
|
23
|
+
} else {
|
|
24
|
+
throw new UnAuthorizedError(`Invalid session. You are not permitted to do this!`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isFeatureEnabled } from "../../util/config";
|
|
2
|
+
import { Handler } from "../common";
|
|
3
|
+
|
|
4
|
+
import { LoggerHandler } from "./logger";
|
|
5
|
+
import { TagResponse } from "./tag";
|
|
6
|
+
import { CORS } from "./cors";
|
|
7
|
+
import { CookieParser } from "./cookie";
|
|
8
|
+
import { ReadBuffer } from "./buffer";
|
|
9
|
+
import { JSONParser } from "./json";
|
|
10
|
+
import { TextParser } from "./text";
|
|
11
|
+
import { URLEncodedParser } from "./form";
|
|
12
|
+
|
|
13
|
+
export * from "./logger";
|
|
14
|
+
export * from "./json";
|
|
15
|
+
export * from "./text";
|
|
16
|
+
export * from "./form";
|
|
17
|
+
export * from "./cors";
|
|
18
|
+
export * from "./session";
|
|
19
|
+
export * from "./group";
|
|
20
|
+
export * from "./parse";
|
|
21
|
+
export * from "./tag";
|
|
22
|
+
export * from "./cookie";
|
|
23
|
+
export { ReadBuffer } from "./buffer";
|
|
24
|
+
|
|
25
|
+
export const middleware = (): Handler[] => {
|
|
26
|
+
const ret: Handler[] = [];
|
|
27
|
+
if (isFeatureEnabled("REQUEST_LOGGER", true)) {
|
|
28
|
+
ret.push(LoggerHandler());
|
|
29
|
+
}
|
|
30
|
+
if (isFeatureEnabled("TAG_RESPONSE", false)) {
|
|
31
|
+
ret.push(TagResponse());
|
|
32
|
+
}
|
|
33
|
+
if (isFeatureEnabled("CORS", false)) {
|
|
34
|
+
ret.push(CORS());
|
|
35
|
+
}
|
|
36
|
+
if (isFeatureEnabled("READ_BUFFER", true)) {
|
|
37
|
+
ret.push(ReadBuffer());
|
|
38
|
+
}
|
|
39
|
+
if (isFeatureEnabled("COOKIE_PARSER", true)) {
|
|
40
|
+
ret.push(CookieParser());
|
|
41
|
+
}
|
|
42
|
+
if (isFeatureEnabled("JSON_PARSER", true)) {
|
|
43
|
+
ret.push(JSONParser());
|
|
44
|
+
}
|
|
45
|
+
if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
|
|
46
|
+
ret.push(URLEncodedParser());
|
|
47
|
+
}
|
|
48
|
+
if (isFeatureEnabled("TEXT_PARSER", true)) {
|
|
49
|
+
ret.push(TextParser());
|
|
50
|
+
}
|
|
51
|
+
return ret;
|
|
52
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Context, Handler } from "../common";
|
|
2
|
+
import { BadRequestError } from "../../util/error";
|
|
3
|
+
import { checkEnvVariables } from "../../util/config";
|
|
4
|
+
import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
|
|
5
|
+
|
|
6
|
+
export const JSONParser = (options?: {
|
|
7
|
+
limit?: number;
|
|
8
|
+
strict?: boolean;
|
|
9
|
+
type?: string;
|
|
10
|
+
}): Handler<void> => {
|
|
11
|
+
let strict = true;
|
|
12
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
13
|
+
let type = "application/json";
|
|
14
|
+
if (options) {
|
|
15
|
+
strict = options.strict !== undefined ? options.strict : strict;
|
|
16
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
17
|
+
type = options.type !== undefined ? options.type : type;
|
|
18
|
+
} else {
|
|
19
|
+
const [limitS, strictS, typeS] =
|
|
20
|
+
checkEnvVariables(["BODY_PARSER_LIMIT", "BODY_PARSER_STRICT", "BODY_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "true", "application/json"])
|
|
21
|
+
strict = strictS === "true";
|
|
22
|
+
limit = parseInt(limitS, 10);
|
|
23
|
+
type = typeS;
|
|
24
|
+
}
|
|
25
|
+
return async (ctx: Context): Promise<void> => {
|
|
26
|
+
try {
|
|
27
|
+
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
28
|
+
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
29
|
+
const string = ctx.buffer.toString();
|
|
30
|
+
if (string) {
|
|
31
|
+
const parsed = JSON.parse(string);
|
|
32
|
+
if (parsed instanceof Array && strict) {
|
|
33
|
+
throw new BadRequestError(`body cannot be an array`, 'body');
|
|
34
|
+
}
|
|
35
|
+
ctx.body = parsed;
|
|
36
|
+
}
|
|
37
|
+
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
38
|
+
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_PARSER_LIMIT to a higher value.`);
|
|
39
|
+
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
40
|
+
}
|
|
41
|
+
} catch (e: any) {
|
|
42
|
+
if (e && e.name === "ParseOptionsError") {
|
|
43
|
+
throw e;
|
|
44
|
+
} else {
|
|
45
|
+
ctx.logger.error(e);
|
|
46
|
+
throw new BadRequestError();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Context, Handler } from "../common";
|
|
2
|
+
|
|
3
|
+
export const LoggerHandler = (options?: {
|
|
4
|
+
formatter: (ctx: Context) => string;
|
|
5
|
+
}): Handler<void> =>
|
|
6
|
+
async (ctx: Context): Promise<void> => {
|
|
7
|
+
ctx.res.on("close", () => {
|
|
8
|
+
const took = Date.now() - ctx.startMS;
|
|
9
|
+
const entry = options ? options.formatter(ctx) : `status[${ctx.res.statusCode}] content-length[${(ctx.res as any)._contentLength}] [${took}]ms`;
|
|
10
|
+
if (ctx.res.statusCode < 400) {
|
|
11
|
+
ctx.logger.info(entry);
|
|
12
|
+
} else if (ctx.res.statusCode >= 400 && ctx.res.statusCode < 500) {
|
|
13
|
+
ctx.logger.warn(entry);
|
|
14
|
+
} else {
|
|
15
|
+
ctx.logger.error(entry);
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|