@miqro/core 1.5.7 → 1.5.10
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/dist/proxy.d.ts +3 -1
- package/dist/proxy.js +2 -0
- package/dist/proxy.js.map +1 -1
- package/dist/static.d.ts +1 -0
- package/dist/static.js +15 -0
- package/dist/static.js.map +1 -1
- package/package.json +4 -4
- package/src/api-router.ts +51 -0
- package/src/app.ts +136 -0
- package/src/common/api-router-helpers.ts +32 -0
- package/src/common/api-router-utils.ts +206 -0
- package/src/common/config/config.ts +99 -0
- package/src/common/config/featuretoggle.ts +6 -0
- package/src/common/config/index.ts +3 -0
- package/src/common/config/loader.ts +80 -0
- package/src/common/context.ts +156 -0
- package/src/common/error/badrequesterror.ts +6 -0
- package/src/common/error/configfilenotfound.ts +6 -0
- package/src/common/error/forbiddenerror.ts +6 -0
- package/src/common/error/index.ts +6 -0
- package/src/common/error/notfound.ts +6 -0
- package/src/common/error/notimplemented.ts +6 -0
- package/src/common/error/unauthorizederror.ts +6 -0
- package/src/common/helpers.ts +11 -0
- package/src/common/index.ts +7 -0
- package/src/common/logger/common.ts +6 -0
- package/src/common/logger/factory.ts +51 -0
- package/src/common/logger/formatter.ts +9 -0
- package/src/common/logger/index.ts +6 -0
- package/src/common/logger/logger.ts +114 -0
- package/src/common/logger/transport.ts +71 -0
- package/src/common/router-helpers.ts +20 -0
- package/src/common/router-utils.ts +93 -0
- package/src/common/session/common.ts +37 -0
- package/src/common/session/index.ts +2 -0
- package/src/common/session/service.ts +157 -0
- package/src/common/tokenize-match.ts +152 -0
- package/src/index.ts +7 -0
- package/src/middleware/buffer.ts +80 -0
- package/src/middleware/cookie.ts +20 -0
- package/src/middleware/cors.ts +96 -0
- package/src/middleware/form.ts +59 -0
- package/src/middleware/group.ts +68 -0
- package/src/middleware/index.ts +47 -0
- package/src/middleware/json.ts +55 -0
- package/src/middleware/logger.ts +18 -0
- package/src/middleware/parse.ts +93 -0
- package/src/middleware/session.ts +136 -0
- package/src/middleware/tag.ts +15 -0
- package/src/middleware/text.ts +45 -0
- package/src/proxy.ts +59 -0
- package/src/router.ts +301 -0
- package/src/static.ts +231 -0
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
|
|
2
|
+
import {DEFAULT_READ_BUFFER_LIMIT, ReadBuffer} from "./buffer";
|
|
3
|
+
|
|
4
|
+
export const JSONParser = (options?: {
|
|
5
|
+
limit?: number;
|
|
6
|
+
strict?: boolean;
|
|
7
|
+
type?: string;
|
|
8
|
+
}): Handler<void> => {
|
|
9
|
+
let strict = true;
|
|
10
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
11
|
+
let type = "application/json";
|
|
12
|
+
if (options) {
|
|
13
|
+
strict = options.strict !== undefined ? options.strict : strict;
|
|
14
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
15
|
+
type = options.type !== undefined ? options.type : type;
|
|
16
|
+
} else {
|
|
17
|
+
const [limitS, strictS, typeS] =
|
|
18
|
+
checkEnvVariables(["BODY_PARSER_LIMIT", "BODY_PARSER_STRICT", "BODY_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "true", "application/json"])
|
|
19
|
+
strict = strictS === "true";
|
|
20
|
+
limit = parseInt(limitS, 10);
|
|
21
|
+
type = typeS;
|
|
22
|
+
}
|
|
23
|
+
const readBuffer = ReadBuffer({
|
|
24
|
+
limit
|
|
25
|
+
});
|
|
26
|
+
return async function JSONParser(ctx: Context): Promise<void> {
|
|
27
|
+
try {
|
|
28
|
+
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
29
|
+
if (isType && !ctx.buffer) {
|
|
30
|
+
await readBuffer(ctx);
|
|
31
|
+
}
|
|
32
|
+
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
33
|
+
const string = ctx.buffer.toString();
|
|
34
|
+
if (string) {
|
|
35
|
+
const parsed = JSON.parse(string);
|
|
36
|
+
if (parsed instanceof Array && strict) {
|
|
37
|
+
throw new BadRequestError(`body cannot be an array`);
|
|
38
|
+
}
|
|
39
|
+
ctx.logger.debug("ctx.body = %o", parsed);
|
|
40
|
+
ctx.body = parsed;
|
|
41
|
+
}
|
|
42
|
+
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
43
|
+
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_PARSER_LIMIT to a higher value.`);
|
|
44
|
+
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
45
|
+
}
|
|
46
|
+
} catch (e: any) {
|
|
47
|
+
if (e && e.name === "BadRequestError") {
|
|
48
|
+
throw e;
|
|
49
|
+
} else {
|
|
50
|
+
ctx.logger.error(e);
|
|
51
|
+
throw new BadRequestError();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
};
|
|
@@ -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
|
+
function LoggerHandler(ctx: Context): 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
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {Context, Handler} from "../common";
|
|
2
|
+
import {parse, ParseOptions, ParserInterface} from "@miqro/parser";
|
|
3
|
+
|
|
4
|
+
export interface ParseRequestOptions {
|
|
5
|
+
headers?: ParseOptions | ParseOptions[];
|
|
6
|
+
query?: ParseOptions | boolean | ParseOptions[] | string;
|
|
7
|
+
params?: ParseOptions | boolean | ParseOptions[] | string;
|
|
8
|
+
body?: ParseOptions | boolean | ParseOptions[] | string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const NO_OPTIONS: ParseOptions[] = [{
|
|
12
|
+
options: [],
|
|
13
|
+
mode: "no_extra"
|
|
14
|
+
}];
|
|
15
|
+
|
|
16
|
+
const ADD_EXTRA: ParseOptions[] = [{
|
|
17
|
+
options: [],
|
|
18
|
+
mode: "add_extra"
|
|
19
|
+
}];
|
|
20
|
+
|
|
21
|
+
const normalizeParseOptions = (option?: ParseOptions | boolean | ParseOptions[] | string): ParseOptions[] | string[] =>
|
|
22
|
+
option !== undefined && typeof option !== "string" && typeof option !== "boolean" ? (option instanceof Array ? option : [option]) : (typeof option === "boolean" ? (option ? ADD_EXTRA : NO_OPTIONS) : (typeof option === "string" ? [option] : ADD_EXTRA));
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
const parseRequestPart = (part: "query" | "body" | "params" | "headers", ctx: Context, option: ParseOptions[] | string[], parser?: ParserInterface): void => {
|
|
26
|
+
const value = ctx[part] === undefined ? {} : ctx[part];
|
|
27
|
+
for (let i = 0; i < option.length; i++) {
|
|
28
|
+
const o = option[i];
|
|
29
|
+
try {
|
|
30
|
+
if (typeof o !== "string") {
|
|
31
|
+
ctx[part] = (parser ? parser : {parse}).parse(value as any, o.options, o.mode, `${part}`) as any;
|
|
32
|
+
} else {
|
|
33
|
+
ctx[part] = (parser ? parser : {parse}).parse(value as any, o, "no_extra", `${part}`) as any;
|
|
34
|
+
}
|
|
35
|
+
ctx.logger.debug("req.%s parsed to [%o]", part, ctx[part]);
|
|
36
|
+
return;
|
|
37
|
+
} catch (e: any) {
|
|
38
|
+
if (i === option.length - 1) {
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
export const ParseRequest = (options: ParseRequestOptions, parser?: ParserInterface): Handler<void> => {
|
|
47
|
+
const query = normalizeParseOptions(options.query);
|
|
48
|
+
const params = normalizeParseOptions(options.params);
|
|
49
|
+
const body = normalizeParseOptions(options.body);
|
|
50
|
+
const headers = normalizeParseOptions(options.headers);
|
|
51
|
+
|
|
52
|
+
return function ParseRequest(ctx: Context): void {
|
|
53
|
+
try {
|
|
54
|
+
try {
|
|
55
|
+
if (options.headers !== undefined) {
|
|
56
|
+
parseRequestPart("headers", ctx, headers, parser);
|
|
57
|
+
}
|
|
58
|
+
} catch (e) {
|
|
59
|
+
ctx.logger.error("error parsing headers %o", ctx.headers);
|
|
60
|
+
throw e;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
if (options.query !== undefined) {
|
|
64
|
+
parseRequestPart("query", ctx, query, parser);
|
|
65
|
+
}
|
|
66
|
+
} catch (e) {
|
|
67
|
+
ctx.logger.error("error parsing query %o", ctx.query);
|
|
68
|
+
throw e;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
if (options.params !== undefined) {
|
|
73
|
+
parseRequestPart("params", ctx, params, parser);
|
|
74
|
+
}
|
|
75
|
+
} catch (e) {
|
|
76
|
+
ctx.logger.error("error parsing params %o", ctx.params);
|
|
77
|
+
throw e;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
if (options.body !== undefined) {
|
|
82
|
+
parseRequestPart("body", ctx, body, parser);
|
|
83
|
+
}
|
|
84
|
+
} catch (e: any) {
|
|
85
|
+
ctx.logger.error("error parsing body %o", ctx.body);
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
} catch (e: any) {
|
|
89
|
+
ctx.logger.warn("error parsing request: %s", e.message);
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import {checkEnvVariables, Context, ForbiddenError, Handler, SessionHandlerOptions, UnAuthorizedError} from "../common";
|
|
2
|
+
import {parse} from "@miqro/parser";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_TOKEN_LOCATION = "header";
|
|
5
|
+
const DEFAULT_TOKEN_HEADER = "Authorization";
|
|
6
|
+
const DEFAULT_TOKEN_QUERY = "token";
|
|
7
|
+
const DEFAULT_TOKEN_COOKIE = "Authorization";
|
|
8
|
+
const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
|
|
9
|
+
const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
|
|
10
|
+
const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
|
|
11
|
+
const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
|
|
12
|
+
|
|
13
|
+
export const SessionHandler = (config: SessionHandlerOptions): Handler<void> => {
|
|
14
|
+
if (!config.options) {
|
|
15
|
+
const tokenLocation = checkEnvVariables(["TOKEN_LOCATION"], [DEFAULT_TOKEN_LOCATION])[0];
|
|
16
|
+
config.options = {
|
|
17
|
+
tokenLocation: tokenLocation as any,
|
|
18
|
+
tokenLocationName: "",
|
|
19
|
+
setCookieOptions: {
|
|
20
|
+
httpOnly: true,
|
|
21
|
+
path: "/",
|
|
22
|
+
sameSite: "strict",
|
|
23
|
+
secure: true
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
switch (tokenLocation) {
|
|
27
|
+
case "header":
|
|
28
|
+
config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
|
|
29
|
+
break;
|
|
30
|
+
case "query":
|
|
31
|
+
config.options.tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
|
|
32
|
+
break;
|
|
33
|
+
case "cookie":
|
|
34
|
+
config.options.tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
|
|
35
|
+
const [httpOnlyS, secureS, path, sameSite] = checkEnvVariables(
|
|
36
|
+
["TOKEN_SET_COOKIE_HTTP_ONLY", "TOKEN_SET_COOKIE_SECURE", "TOKEN_SET_COOKIE_PATH", "TOKEN_SET_COOKIE_SAME_SITE"],
|
|
37
|
+
[DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_SECURE, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE]);
|
|
38
|
+
config.options.setCookieOptions = {
|
|
39
|
+
httpOnly: httpOnlyS === "true",
|
|
40
|
+
secure: secureS === "true",
|
|
41
|
+
path,
|
|
42
|
+
sameSite: sameSite as any
|
|
43
|
+
};
|
|
44
|
+
break;
|
|
45
|
+
default:
|
|
46
|
+
throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
config.options = parse(config.options as any, [
|
|
50
|
+
{name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"]},
|
|
51
|
+
{name: "tokenLocationName", required: true, type: "any"},
|
|
52
|
+
{
|
|
53
|
+
name: "setCookieOptions", required: false, type: "nested", defaultValue: {
|
|
54
|
+
httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
|
|
55
|
+
secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
|
|
56
|
+
path: DEFAULT_TOKEN_SET_COOKIE_PATH,
|
|
57
|
+
sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
|
|
58
|
+
}, nestedOptions: {
|
|
59
|
+
mode: "no_extra",
|
|
60
|
+
options: [
|
|
61
|
+
{name: "httpOnly", required: true, type: "boolean"},
|
|
62
|
+
{name: "secure", required: true, type: "boolean"},
|
|
63
|
+
{name: "path", required: true, type: "any"},
|
|
64
|
+
{name: "sameSite", required: true, type: "enum", enumValues: ["lax", "strict", "none"]}
|
|
65
|
+
]
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
], "no_extra", "options") as any;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!config.authService) {
|
|
72
|
+
throw new Error("authService must be provided!");
|
|
73
|
+
}
|
|
74
|
+
if (!config.options || !config.options.setCookieOptions) {
|
|
75
|
+
throw new Error("config.options not populated!");
|
|
76
|
+
}
|
|
77
|
+
const tokenLocation = config.options.tokenLocation;
|
|
78
|
+
const tokenLocationName = config.options.tokenLocationName;
|
|
79
|
+
const setCookieOptions = config.options.setCookieOptions;
|
|
80
|
+
return async function SessionHandler(ctx: Context): Promise<void> {
|
|
81
|
+
try {
|
|
82
|
+
const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(ctx);
|
|
83
|
+
let token = null;
|
|
84
|
+
switch (tokenLocation) {
|
|
85
|
+
case "header":
|
|
86
|
+
token = ctx.headers[(tlN).toLowerCase()] as string;
|
|
87
|
+
break;
|
|
88
|
+
case "query":
|
|
89
|
+
token = ctx.query[tlN] as string;
|
|
90
|
+
break;
|
|
91
|
+
case "cookie":
|
|
92
|
+
token = ctx.cookies[tlN] ? ctx.cookies[tlN] : undefined;
|
|
93
|
+
break;
|
|
94
|
+
default:
|
|
95
|
+
throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
|
|
96
|
+
}
|
|
97
|
+
if (!token) {
|
|
98
|
+
ctx.logger.warn("No token provided!");
|
|
99
|
+
throw new ForbiddenError("NO TOKEN");
|
|
100
|
+
} else {
|
|
101
|
+
const session = await config.authService.verify({token, ctx});
|
|
102
|
+
if (!session) {
|
|
103
|
+
ctx.logger.warn("fail to authenticate token [%s]!", token);
|
|
104
|
+
throw new UnAuthorizedError();
|
|
105
|
+
} else {
|
|
106
|
+
if (tokenLocation === "cookie" && session.token !== token) {
|
|
107
|
+
const newTokenCookie = String(session.token ? session.token : token);
|
|
108
|
+
const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(ctx);
|
|
109
|
+
ctx.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
|
|
110
|
+
httpOnly: setCookieOptions.httpOnly,
|
|
111
|
+
secure: setCookieOptions.secure,
|
|
112
|
+
path: cookiePath,
|
|
113
|
+
sameSite: setCookieOptions.sameSite,
|
|
114
|
+
expires: session.expires
|
|
115
|
+
} : {
|
|
116
|
+
httpOnly: setCookieOptions.httpOnly,
|
|
117
|
+
path: cookiePath,
|
|
118
|
+
secure: setCookieOptions.secure,
|
|
119
|
+
sameSite: setCookieOptions.sameSite
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
ctx.session = session;
|
|
123
|
+
ctx.logger.debug("authenticated!");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
} catch (e: any) {
|
|
127
|
+
if (e.message && e.message === "NO TOKEN") {
|
|
128
|
+
throw e;
|
|
129
|
+
} else {
|
|
130
|
+
throw new UnAuthorizedError();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {Context, Handler} from "../common";
|
|
2
|
+
|
|
3
|
+
export const TagResponse = (options?: {
|
|
4
|
+
uuid?: boolean;
|
|
5
|
+
}): Handler<void> =>
|
|
6
|
+
function TagResponse(ctx: Context): void {
|
|
7
|
+
if (options && options.uuid) {
|
|
8
|
+
ctx.setHeader("uuid", ctx.uuid);
|
|
9
|
+
}
|
|
10
|
+
const requestUUID = ctx.headers['request-uuid'];
|
|
11
|
+
if (requestUUID) {
|
|
12
|
+
ctx.setHeader("request-uuid", requestUUID);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {BadRequestError, checkEnvVariables, Context, Handler} from "../common";
|
|
2
|
+
import {DEFAULT_READ_BUFFER_LIMIT, ReadBuffer} from "./buffer";
|
|
3
|
+
|
|
4
|
+
export const TextParser = (options?: {
|
|
5
|
+
limit?: number;
|
|
6
|
+
type?: string;
|
|
7
|
+
}): Handler<void> => {
|
|
8
|
+
let limit = DEFAULT_READ_BUFFER_LIMIT;
|
|
9
|
+
let type = "plain/text";
|
|
10
|
+
if (options) {
|
|
11
|
+
limit = options.limit !== undefined ? options.limit : limit;
|
|
12
|
+
type = options.type !== undefined ? options.type : type;
|
|
13
|
+
} else {
|
|
14
|
+
const [limitS, typeS] =
|
|
15
|
+
checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "plain/text"]);
|
|
16
|
+
limit = parseInt(limitS, 10);
|
|
17
|
+
type = typeS;
|
|
18
|
+
}
|
|
19
|
+
const readBuffer = ReadBuffer({
|
|
20
|
+
limit
|
|
21
|
+
});
|
|
22
|
+
return async function TextParser(ctx: Context): Promise<void> {
|
|
23
|
+
try {
|
|
24
|
+
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
25
|
+
if (isType && !ctx.buffer) {
|
|
26
|
+
await readBuffer(ctx);
|
|
27
|
+
}
|
|
28
|
+
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
29
|
+
const string = ctx.buffer.toString();
|
|
30
|
+
ctx.logger.debug("ctx.body = %s", string);
|
|
31
|
+
ctx.body = string;
|
|
32
|
+
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
33
|
+
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_TEXT_PARSER_LIMIT to a higher value.`);
|
|
34
|
+
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
35
|
+
}
|
|
36
|
+
} catch (e: any) {
|
|
37
|
+
if (e && e.name === "BadRequestError") {
|
|
38
|
+
throw e;
|
|
39
|
+
} else {
|
|
40
|
+
ctx.logger.error(e);
|
|
41
|
+
throw new BadRequestError();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
};
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import {Context} from "./common";
|
|
2
|
+
import {request} from "@miqro/request";
|
|
3
|
+
import {Router, RouterOptions} from "./router";
|
|
4
|
+
import {normalizePath, PathPartToken} from "./common/tokenize-match";
|
|
5
|
+
import {URL} from "url";
|
|
6
|
+
|
|
7
|
+
export interface ProxyRouterOptions extends RouterOptions {
|
|
8
|
+
url: string;
|
|
9
|
+
rejectUnauthorized?: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
class ProxyRouter extends Router {
|
|
13
|
+
private readonly proxyURL: URL;
|
|
14
|
+
private readonly rejectUnauthorized?: boolean;
|
|
15
|
+
|
|
16
|
+
constructor(options: ProxyRouterOptions) {
|
|
17
|
+
super(options);
|
|
18
|
+
const proxyURL = new URL(options.url);
|
|
19
|
+
proxyURL.pathname = normalizePath(proxyURL.pathname);
|
|
20
|
+
this.proxyURL = proxyURL;
|
|
21
|
+
this.rejectUnauthorized = options.rejectUnauthorized;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async run(ctx: Context, pathTokens?: { value: string; lower: string }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
|
|
25
|
+
|
|
26
|
+
const level = prePathTokens.length;
|
|
27
|
+
const shouldContinue = await super.run(ctx, pathTokens, prePathTokens);
|
|
28
|
+
|
|
29
|
+
if (shouldContinue) {
|
|
30
|
+
const relative = ctx.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/");
|
|
31
|
+
|
|
32
|
+
const nUrl = new URL(this.proxyURL.toString());
|
|
33
|
+
nUrl.pathname = nUrl.pathname + relative;
|
|
34
|
+
const url = nUrl.toString();
|
|
35
|
+
ctx.logger.info("proxy to %s", url.toString());
|
|
36
|
+
|
|
37
|
+
const response = await request({
|
|
38
|
+
url: url.toString(),
|
|
39
|
+
disableThrow: true,
|
|
40
|
+
rejectUnauthorized: this.rejectUnauthorized,
|
|
41
|
+
disableUserAgent: true,
|
|
42
|
+
method: ctx.method,
|
|
43
|
+
headers: ctx.headers,
|
|
44
|
+
data: ctx.method !== "GET" ? ctx.buffer : undefined
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
await ctx.end({
|
|
48
|
+
headers: response.headers,
|
|
49
|
+
body: response.data,
|
|
50
|
+
status: response.status
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return !ctx.res.headersSent;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const Proxy = (options: ProxyRouterOptions) => {
|
|
58
|
+
return new ProxyRouter(options);
|
|
59
|
+
}
|