@miqro/core 1.5.9 → 1.5.12

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.
Files changed (47) hide show
  1. package/package.json +4 -4
  2. package/src/api-router.ts +51 -0
  3. package/src/app.ts +136 -0
  4. package/src/common/api-router-helpers.ts +32 -0
  5. package/src/common/api-router-utils.ts +206 -0
  6. package/src/common/config/config.ts +99 -0
  7. package/src/common/config/featuretoggle.ts +6 -0
  8. package/src/common/config/index.ts +3 -0
  9. package/src/common/config/loader.ts +80 -0
  10. package/src/common/context.ts +156 -0
  11. package/src/common/error/badrequesterror.ts +6 -0
  12. package/src/common/error/configfilenotfound.ts +6 -0
  13. package/src/common/error/forbiddenerror.ts +6 -0
  14. package/src/common/error/index.ts +6 -0
  15. package/src/common/error/notfound.ts +6 -0
  16. package/src/common/error/notimplemented.ts +6 -0
  17. package/src/common/error/unauthorizederror.ts +6 -0
  18. package/src/common/helpers.ts +11 -0
  19. package/src/common/index.ts +7 -0
  20. package/src/common/logger/common.ts +6 -0
  21. package/src/common/logger/factory.ts +51 -0
  22. package/src/common/logger/formatter.ts +9 -0
  23. package/src/common/logger/index.ts +6 -0
  24. package/src/common/logger/logger.ts +114 -0
  25. package/src/common/logger/transport.ts +71 -0
  26. package/src/common/router-helpers.ts +20 -0
  27. package/src/common/router-utils.ts +93 -0
  28. package/src/common/session/common.ts +37 -0
  29. package/src/common/session/index.ts +2 -0
  30. package/src/common/session/service.ts +157 -0
  31. package/src/common/tokenize-match.ts +152 -0
  32. package/src/index.ts +7 -0
  33. package/src/middleware/buffer.ts +80 -0
  34. package/src/middleware/cookie.ts +20 -0
  35. package/src/middleware/cors.ts +96 -0
  36. package/src/middleware/form.ts +59 -0
  37. package/src/middleware/group.ts +68 -0
  38. package/src/middleware/index.ts +47 -0
  39. package/src/middleware/json.ts +55 -0
  40. package/src/middleware/logger.ts +18 -0
  41. package/src/middleware/parse.ts +93 -0
  42. package/src/middleware/session.ts +136 -0
  43. package/src/middleware/tag.ts +15 -0
  44. package/src/middleware/text.ts +45 -0
  45. package/src/proxy.ts +59 -0
  46. package/src/router.ts +301 -0
  47. package/src/static.ts +231 -0
@@ -0,0 +1,157 @@
1
+ import {NoTokenSession, Session} from "./common";
2
+ import {Context} from "../context";
3
+ import {checkEnvVariables} from "../config";
4
+ import {UnAuthorizedError} from "../error";
5
+ import {request, RequestOptions, RequestResponse} from "@miqro/request";
6
+ import {parse} from "@miqro/parser";
7
+ import {parse as cookieParse} from "cookie";
8
+
9
+ const DEFAULT_TOKEN_LOCATION = "header";
10
+ const DEFAULT_TOKEN_HEADER = "Authorization";
11
+ const DEFAULT_TOKEN_QUERY = "token";
12
+ const DEFAULT_TOKEN_COOKIE = "Authorization";
13
+
14
+ export interface VerifyTokenService {
15
+ verify(args: { token: string; ctx: Context }): Promise<Session | null>;
16
+ }
17
+
18
+ export interface VerifyEndpointServiceOptions {
19
+ url: string;
20
+ method: string;
21
+ tokenLocation: "header" | "query" | "cookie";
22
+ tokenLocationName: string | ((ctx: Context) => Promise<string>);
23
+ }
24
+
25
+ export class VerifyEndpointService implements VerifyTokenService {
26
+
27
+ protected options: VerifyEndpointServiceOptions;
28
+
29
+ constructor(options?: VerifyEndpointServiceOptions) {
30
+ if (!options) {
31
+ const [url, method] = checkEnvVariables(["TOKEN_VERIFY_ENDPOINT", "TOKEN_VERIFY_ENDPOINT_METHOD"]);
32
+ const [tokenVerifyLocation] = checkEnvVariables(["TOKEN_VERIFY_LOCATION"], [DEFAULT_TOKEN_LOCATION]);
33
+ let tokenLocationName;
34
+ switch (tokenVerifyLocation) {
35
+ case "header":
36
+ tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
37
+ break;
38
+ case "query":
39
+ tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
40
+ break;
41
+ case "cookie":
42
+ tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
43
+ break;
44
+ default:
45
+ throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header or query)`);
46
+ }
47
+ this.options = {
48
+ url, method,
49
+ tokenLocation: tokenVerifyLocation,
50
+ tokenLocationName
51
+ }
52
+ } else {
53
+ this.options = parse(options as any, [
54
+ {name: "url", required: true, type: "string", stringMinLength: 1},
55
+ {name: "method", required: true, type: "string", stringMinLength: 1},
56
+ {name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"]},
57
+ {name: "tokenLocationName", required: true, type: "any"}
58
+ ], "no_extra", "options") as any;
59
+ }
60
+ }
61
+
62
+ public async verify({token, ctx}: { token: string; ctx: Context }): Promise<Session | null> {
63
+ try {
64
+ let response = null;
65
+ const tokenVerifyLocation = this.options.tokenLocation;
66
+ const url = this.options.url;
67
+ const method = this.options.method;
68
+ switch (tokenVerifyLocation) {
69
+ case "header":
70
+ const tokenHeaderLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
71
+ ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_HEADER=[${tokenHeaderLocation}]`);
72
+ response = await this.getResponse({
73
+ url,
74
+ headers: {
75
+ [tokenHeaderLocation]: token
76
+ },
77
+ method
78
+ }, ctx);
79
+ break;
80
+ case "query":
81
+ const tokenQueryLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
82
+ ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
83
+ response = await this.getResponse({
84
+ url,
85
+ query: {
86
+ [tokenQueryLocation]: token
87
+ },
88
+ method
89
+ }, ctx);
90
+ break;
91
+ case "cookie":
92
+ const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
93
+ ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
94
+ response = await this.getResponse({
95
+ url,
96
+ method,
97
+ headers: {
98
+ Cookie: `${tokenCookieLocation}=${token}; Path=/; HttpOnly;`
99
+ }
100
+ }, ctx);
101
+ break;
102
+ default:
103
+ throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header, query or cookie)`);
104
+ }
105
+ if (response) {
106
+ const session = await this.decodeSession(response, token, ctx);
107
+ if (!this.checkSession(session, ctx)) {
108
+ ctx.logger.warn(`unauthorized token not valid [${token}]`);
109
+ return null;
110
+ } else {
111
+ ctx.logger.trace("token [%s]authorized!", token);
112
+
113
+ if (tokenVerifyLocation === "cookie" && response.headers["set-cookie"]) {
114
+ const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
115
+ const cookies = response.headers["set-cookie"].map((c: any) => cookieParse(c)).filter((c: any) => c[tokenCookieLocation] !== undefined);
116
+ if (cookies.length === 1) {
117
+ const value = cookies[0][tokenCookieLocation];
118
+ if (value) {
119
+ session.token = value; // replace token because token update via set-cookie
120
+ }
121
+ }
122
+ }
123
+ return {
124
+ token,
125
+ ...session
126
+ } as Session;
127
+ }
128
+ } else {
129
+ ctx.logger.warn(`unauthorized token not valid [${token}]`);
130
+ return null;
131
+ }
132
+ } catch (e: any) {
133
+ throw new UnAuthorizedError(`Fail to authenticate token! error verifying [${token}] [${e.status}][${e.config ? e.config.url : ""}]`);
134
+ }
135
+ }
136
+
137
+ /* eslint-disable @typescript-eslint/no-unused-vars */
138
+ protected async getResponse(config: RequestOptions, ctx?: Context): Promise<RequestResponse> {
139
+ return request(config);
140
+ }
141
+
142
+ /* eslint-disable @typescript-eslint/no-unused-vars */
143
+ protected checkSession(session: NoTokenSession, ctx?: Context): boolean {
144
+ parse(session, [
145
+ {name: "username", required: true, type: "string"},
146
+ {name: "account", required: true, type: "string"},
147
+ {name: "groups", required: true, type: "array", arrayType: "string"}
148
+ ], "add_extra", "session");
149
+ return true;
150
+ }
151
+
152
+ /* eslint-disable @typescript-eslint/no-unused-vars */
153
+ protected async decodeSession(response: RequestResponse, token: string, ctx?: Context): Promise<NoTokenSession> {
154
+ const session = response.data;
155
+ return session as NoTokenSession;
156
+ }
157
+ }
@@ -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
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./app";
2
+ export * from "./router";
3
+ export * from "./static";
4
+ export * from "./api-router";
5
+ export * from "./common";
6
+ export * from "./proxy";
7
+ export * from "./middleware";
@@ -0,0 +1,80 @@
1
+ import {gunzipSync} from "zlib";
2
+ import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
3
+
4
+ export const DEFAULT_READ_BUFFER_LIMIT = 1024 * 8 * 100;
5
+
6
+ const DEFAULT_READ_BUFFER_TIMEOUT = 1000 * 40;
7
+
8
+ export const ReadBuffer = (options?: {
9
+ limit?: number;
10
+ timeout?: number;
11
+ }): Handler<void> => {
12
+ let limit = DEFAULT_READ_BUFFER_LIMIT;
13
+ let timeout = DEFAULT_READ_BUFFER_TIMEOUT;
14
+ if (options) {
15
+ limit = options.limit !== undefined ? options.limit : limit;
16
+ timeout = options.timeout !== undefined ? options.timeout : timeout;
17
+ } else {
18
+ const [limitS, timeoutS] =
19
+ checkEnvVariables(["READ_BUFFER_LIMIT", "READ_BUFFER_TIMEOUT"], [String(DEFAULT_READ_BUFFER_LIMIT), String(DEFAULT_READ_BUFFER_TIMEOUT)]);
20
+ limit = parseInt(limitS, 10);
21
+ timeout = parseInt(timeoutS, 10);
22
+ }
23
+ return async function ReadBuffer(ctx: Context): Promise<void> {
24
+ return new Promise<void>((resolve, reject) => {
25
+ try {
26
+ const readTimeout = setTimeout(() => {
27
+ clearTimeout(readTimeout);
28
+ ctx.req.removeListener('error', errorListener);
29
+ ctx.req.removeListener('data', chunkListener);
30
+ ctx.req.removeListener('end', endListener);
31
+ ctx.close();
32
+ return;
33
+ }, timeout);
34
+ let cLength = 0;
35
+ const buffers: Buffer[] = [];
36
+ const endListener = () => {
37
+ clearTimeout(readTimeout);
38
+ ctx.req.removeListener('error', errorListener);
39
+ ctx.req.removeListener('data', chunkListener);
40
+ ctx.req.removeListener('end', endListener);
41
+ try {
42
+ const concatBuffers = Buffer.concat(buffers);
43
+ const responseBuffer: Buffer = ctx.headers["content-encoding"] === "gzip" ?
44
+ gunzipSync(concatBuffers) : concatBuffers;
45
+ ctx.logger.trace("ctx.buffer %o", responseBuffer);
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
+ }
80
+ }
@@ -0,0 +1,20 @@
1
+ import {Context, Handler} from "../common";
2
+
3
+ import {parse} from "cookie";
4
+
5
+ export const CookieParser = (options?: {
6
+ decode?(value: string): string;
7
+ }): Handler<void> => {
8
+ return function CookieParser(ctx: Context): void {
9
+ const cookies = 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
+ ctx.logger.trace("cookies = %o", ctx.cookies);
18
+ };
19
+ }
20
+
@@ -0,0 +1,96 @@
1
+ import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
2
+
3
+ const DEFAULT_CORS_ORIGINS = "*";
4
+ const DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
5
+ const DEFAULT_CORS_PREFLIGHT_CONTINUE = false;
6
+
7
+ export interface CORSOptions {
8
+ origins: string[] | string | undefined;
9
+ validate?: (origin: string | undefined, origins: string[] | string) => boolean;
10
+ methods?: string;
11
+ preflightContinue?: boolean;
12
+ }
13
+
14
+ const isOriginAllowed = (origin: string | undefined, origins: string[] | string): boolean => {
15
+ if (origins instanceof Array) {
16
+ for (const o of origins) {
17
+ if (origin === o || o === "*") {
18
+ return true;
19
+ }
20
+ }
21
+ return false;
22
+ } else {
23
+ return origin === origins;
24
+ }
25
+ };
26
+
27
+ export const CORS = (options?: CORSOptions): Handler<void> => {
28
+ let origins: string[] | undefined | string;
29
+ let methods: string;
30
+ let preFlightContinue = false;
31
+ if (options) {
32
+ origins = options.origins instanceof Array ? options.origins : (options.origins ? [options.origins] : undefined);
33
+ methods = options.methods ? options.methods : DEFAULT_CORS_METHODS;
34
+ preFlightContinue = !!options.preflightContinue;
35
+ } else {
36
+ const [originsS, preFlightContinueS, methodsS] =
37
+ checkEnvVariables(["CORS_ORIGINS", "CORS_PREFLIGHT_CONTINUE", "CORS_METHODS"], [DEFAULT_CORS_ORIGINS, String(DEFAULT_CORS_PREFLIGHT_CONTINUE), DEFAULT_CORS_METHODS]);
38
+ origins = originsS.split(",").map(s => s.trim());
39
+ methods = methodsS;
40
+ preFlightContinue = preFlightContinueS.toLocaleLowerCase() === "true";
41
+ }
42
+ if (origins && origins.length === 1) {
43
+ origins = origins[0];
44
+ }
45
+
46
+ const validate: (origin: string | undefined, origins: string[] | string) => boolean =
47
+ options && options.validate ? options && options.validate : isOriginAllowed;
48
+
49
+ return async function CORS(ctx: Context): Promise<void> {
50
+ // access-control-allow-origin
51
+ if (!origins || origins === '*') {
52
+ // allow any origin
53
+ ctx.setHeader("Access-Control-Allow-Origin", "*");
54
+ ctx.addVaryHeader("Origin");
55
+ } else {
56
+ if (ctx.headers.origin) {
57
+ if (validate(ctx.headers.origin, origins)) {
58
+ // reflect origin
59
+ ctx.setHeader("Access-Control-Allow-Origin", String(ctx.headers.origin));
60
+ ctx.addVaryHeader("Origin");
61
+ } else {
62
+ // not allowed
63
+ throw new BadRequestError(`bad origin`);
64
+ }
65
+ } else {
66
+ ctx.setHeader("Access-Control-Allow-Origin", origins instanceof Array ? origins[0] : origins);
67
+ ctx.addVaryHeader("Origin");
68
+ }
69
+ }
70
+
71
+ if (ctx.method.toUpperCase() === "OPTIONS") {
72
+ // access-control-request-headers
73
+ if (methods) {
74
+ ctx.setHeader("Access-Control-Allow-Methods", methods);
75
+ }
76
+ // reflect access-control-request-headers
77
+ const allowedHeaders = ctx.headers['access-control-request-headers'];
78
+ if (allowedHeaders) {
79
+ ctx.addVaryHeader("Access-Control-Request-Headers");
80
+ ctx.setHeader("Access-Control-Allow-Headers", allowedHeaders);
81
+ }
82
+ // after preflight
83
+ if (preFlightContinue) {
84
+ return;
85
+ } else {
86
+ await ctx.end({
87
+ headers: {
88
+ "Content-Length": 0
89
+ },
90
+ status: 204,
91
+ body: undefined
92
+ });
93
+ }
94
+ }
95
+ }
96
+ };
@@ -0,0 +1,59 @@
1
+ import {parse as queryParse} from "querystring";
2
+ import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
3
+ import {DEFAULT_READ_BUFFER_LIMIT, ReadBuffer} from "./buffer";
4
+
5
+ const DEFAULT_FORM_MAX_KEYS: undefined | number = undefined;
6
+
7
+ export const URLEncodedParser = (options?: {
8
+ limit?: number;
9
+ maxKeys?: number;
10
+ type?: string;
11
+ }): Handler<void> => {
12
+ let maxKeys: undefined | number = DEFAULT_FORM_MAX_KEYS;
13
+ let limit = DEFAULT_READ_BUFFER_LIMIT;
14
+ let type = "application/x-www-form-urlencoded";
15
+ if (options) {
16
+ limit = options.limit !== undefined ? options.limit : limit;
17
+ type = options.type !== undefined ? options.type : type;
18
+ maxKeys = options.maxKeys !== undefined ? options.maxKeys : maxKeys;
19
+ } else {
20
+ const [limitS, typeS, maxKeysS] =
21
+ 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)]);
22
+ limit = parseInt(limitS, 10);
23
+ type = typeS;
24
+ maxKeys = maxKeysS !== "undefined" ? parseInt(maxKeysS, 10) : DEFAULT_FORM_MAX_KEYS;
25
+ }
26
+ const readBuffer = ReadBuffer({
27
+ limit
28
+ });
29
+ return async function URLEncodedParser(ctx: Context): Promise<void> {
30
+ try {
31
+ const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
32
+ if (isType && !ctx.buffer) {
33
+ await readBuffer(ctx);
34
+ }
35
+ if (isType && ctx.buffer && ctx.buffer.length <= limit) {
36
+ const string = ctx.buffer.toString();
37
+ if (string) {
38
+ const body = {
39
+ ...queryParse(string, undefined, undefined, {
40
+ maxKeys
41
+ })
42
+ };
43
+ ctx.logger.debug("ctx.body = %s", body);
44
+ ctx.body = body;
45
+ }
46
+ } else if (isType && ctx.buffer && ctx.buffer.length > limit) {
47
+ ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_PARSER_URL_ENCODED_LIMIT to a higher value.`);
48
+ throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
49
+ }
50
+ } catch (e: any) {
51
+ if (e && e.name === "BadRequestError") {
52
+ throw e;
53
+ } else {
54
+ ctx.logger.error(e);
55
+ throw new BadRequestError();
56
+ }
57
+ }
58
+ };
59
+ };
@@ -0,0 +1,68 @@
1
+ import {BadRequestError, Context, ForbiddenError, GroupPolicy, Handler, Session, UnAuthorizedError} from "../common";
2
+
3
+ const policyCheck = (session: Session, options: GroupPolicy): boolean => {
4
+ switch (options.groupPolicy) {
5
+ case "at_least_one":
6
+ for (const group of options.groups) {
7
+ if (group instanceof Array) {
8
+ let ret = true;
9
+ for (const g of group) {
10
+ if (session.groups.indexOf(g) === -1) {
11
+ ret = false;
12
+ break;
13
+ }
14
+ }
15
+ if (ret) {
16
+ return true;
17
+ }
18
+ } else {
19
+ if (session.groups.indexOf(group) !== -1) {
20
+ return true;
21
+ }
22
+ }
23
+ }
24
+ return false;
25
+ case "all":
26
+ for (const group of options.groups) {
27
+ if (group instanceof Array) {
28
+ for (const g of group) {
29
+ if (session.groups.indexOf(g) === -1) {
30
+ return false;
31
+ }
32
+ }
33
+ } else {
34
+ if (session.groups.indexOf(group) === -1) {
35
+ return false;
36
+ }
37
+ }
38
+ }
39
+ return true;
40
+ default:
41
+ throw new BadRequestError(`policy [${options.groupPolicy}] not implemented!!`);
42
+ }
43
+ };
44
+
45
+ export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
46
+ return function GroupPolicyHandler(ctx: Context): void {
47
+ try {
48
+ if (!ctx.session) {
49
+ throw new UnAuthorizedError(`No Session!`);
50
+ } else {
51
+ const result = policyCheck(ctx.session, options);
52
+ if (result) {
53
+ ctx.logger.debug("groups validated!");
54
+ } else {
55
+ ctx.logger.error("%sgroups fail to validate!", ctx && ctx.session && ctx.session.groups ? `[${ctx.session.groups.join(",")}] ` : "");
56
+ throw new ForbiddenError(`Invalid session. You are not permitted to do this!`);
57
+ }
58
+ }
59
+ } catch (e: any) {
60
+ //(logger as Logger).warn(`request[${req.uuid}] message[${e.message}] stack[${e.stack}]`);
61
+ if (e.name && e.name !== "Error") {
62
+ throw e;
63
+ } else {
64
+ throw new UnAuthorizedError(`Invalid session. You are not permitted to do this!`);
65
+ }
66
+ }
67
+ };
68
+ };
@@ -0,0 +1,47 @@
1
+ import {Handler, isFeatureEnabled} from "../common";
2
+
3
+ import {LoggerHandler} from "./logger";
4
+ import {TagResponse} from "./tag";
5
+ import {CORS} from "./cors";
6
+ import {CookieParser} from "./cookie";
7
+ import {JSONParser} from "./json";
8
+ import {TextParser} from "./text";
9
+ import {URLEncodedParser} from "./form";
10
+
11
+ export * from "./logger";
12
+ export * from "./json";
13
+ export * from "./text";
14
+ export * from "./form";
15
+ export * from "./cors";
16
+ export * from "./session";
17
+ export * from "./group";
18
+ export * from "./parse";
19
+ export * from "./tag";
20
+ export * from "./cookie";
21
+ export {ReadBuffer} from "./buffer";
22
+
23
+ export const middleware = (): Handler[] => {
24
+ const ret: Handler[] = [];
25
+ if (isFeatureEnabled("REQUEST_LOGGER", true)) {
26
+ ret.push(LoggerHandler());
27
+ }
28
+ if (isFeatureEnabled("TAG_RESPONSE", false)) {
29
+ ret.push(TagResponse());
30
+ }
31
+ if (isFeatureEnabled("CORS", false)) {
32
+ ret.push(CORS());
33
+ }
34
+ if (isFeatureEnabled("COOKIE_PARSER", true)) {
35
+ ret.push(CookieParser());
36
+ }
37
+ if (isFeatureEnabled("JSON_PARSER", true)) {
38
+ ret.push(JSONParser());
39
+ }
40
+ if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
41
+ ret.push(URLEncodedParser());
42
+ }
43
+ if (isFeatureEnabled("TEXT_PARSER", true)) {
44
+ ret.push(TextParser());
45
+ }
46
+ return ret;
47
+ };