@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,93 @@
|
|
|
1
|
+
import {Context, Handler} from "./context";
|
|
2
|
+
import {parse, ParseOptions, ParserInterface} from "@miqro/parser";
|
|
3
|
+
import {GroupPolicy, SessionHandlerOptions} from "./session";
|
|
4
|
+
|
|
5
|
+
export const ResultParser = (options: ParseOptions | ParseOptions[] | string, parser?: ParserInterface): Handler => {
|
|
6
|
+
return async function ResultParser(ctx: Context): Promise<any> {
|
|
7
|
+
if (!ctx.results || ctx.results.length === 0) {
|
|
8
|
+
ctx.logger.debug(`not parsing results`);
|
|
9
|
+
return undefined;
|
|
10
|
+
} else {
|
|
11
|
+
const index = ctx.results.length - 1;
|
|
12
|
+
const lastResult = ctx.results[index];
|
|
13
|
+
ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
|
|
14
|
+
try {
|
|
15
|
+
if (options instanceof Array) {
|
|
16
|
+
for (let i = 0; i < options.length; i++) {
|
|
17
|
+
const o = options[i];
|
|
18
|
+
try {
|
|
19
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, o.options, o.mode, `ctx.results[${index}]`);
|
|
20
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
21
|
+
return mappedResults;
|
|
22
|
+
} catch (e) {
|
|
23
|
+
if (i === options.length - 1) {
|
|
24
|
+
throw e;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} else if (typeof options !== "string") {
|
|
29
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options.options, options.mode, `ctx.results[${index}]`);
|
|
30
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
31
|
+
return mappedResults;
|
|
32
|
+
} else {
|
|
33
|
+
const mappedResults = (parser ? parser : {parse}).parse(lastResult, options, "no_extra", `ctx.results[${index}]`);
|
|
34
|
+
ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
|
|
35
|
+
return mappedResults;
|
|
36
|
+
}
|
|
37
|
+
} catch (e) {
|
|
38
|
+
ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const ResponseHandler = (): Handler<void> => async (ctx: Context): Promise<void> => {
|
|
46
|
+
ctx.logger.trace("results [%o]", ctx.results);
|
|
47
|
+
if (!ctx.results || ctx.results.length === 0) {
|
|
48
|
+
throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
|
|
49
|
+
} else {
|
|
50
|
+
const lastResult = ctx.results[ctx.results.length - 1];
|
|
51
|
+
ctx.logger.debug("response [%o]", lastResult);
|
|
52
|
+
if (lastResult !== undefined) {
|
|
53
|
+
await ctx.json(lastResult);
|
|
54
|
+
} else {
|
|
55
|
+
throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export interface HandlerWithOptions extends RouterHandlerOptions {
|
|
61
|
+
handler: Handler | Array<Handler>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface RouteOptions {
|
|
65
|
+
name?: string;
|
|
66
|
+
description?: string;
|
|
67
|
+
policy?: GroupPolicy;
|
|
68
|
+
request?: {
|
|
69
|
+
headers?: ParseOptions | ParseOptions[];
|
|
70
|
+
query?: ParseOptions | boolean | ParseOptions[] | string;
|
|
71
|
+
params?: ParseOptions | boolean | ParseOptions[] | string;
|
|
72
|
+
body?: ParseOptions | boolean | ParseOptions[] | string;
|
|
73
|
+
};
|
|
74
|
+
response?: {
|
|
75
|
+
body?: boolean | ParseOptions | ParseOptions[] | string;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface RouteJSONDoc extends RouteOptions {
|
|
80
|
+
identifier: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface RouterJSONDoc {
|
|
84
|
+
[path: string]: {
|
|
85
|
+
[method: string]: RouteJSONDoc
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface RouterHandlerOptions extends RouteOptions {
|
|
90
|
+
parser?: ParserInterface;
|
|
91
|
+
middleware?: Handler | Handler[];
|
|
92
|
+
session?: SessionHandlerOptions | Handler;
|
|
93
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {Dict} from "@miqro/parser";
|
|
2
|
+
import {Context} from "../context";
|
|
3
|
+
|
|
4
|
+
export interface SessionHandlerOptions {
|
|
5
|
+
authService: {
|
|
6
|
+
verify(args: { token: string; ctx: Context }): Promise<Session | null>;
|
|
7
|
+
};
|
|
8
|
+
options?: {
|
|
9
|
+
tokenLocation: "header" | "query" | "cookie";
|
|
10
|
+
tokenLocationName: string | ((ctx: Context) => Promise<string>);
|
|
11
|
+
setCookieOptions?: {
|
|
12
|
+
httpOnly: boolean;
|
|
13
|
+
secure: boolean;
|
|
14
|
+
path: string | ((ctx: Context) => Promise<string>);
|
|
15
|
+
sameSite: "lax" | "strict" | "none";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface NoTokenSession extends Dict<any> {
|
|
21
|
+
account: string;
|
|
22
|
+
username: string;
|
|
23
|
+
groups: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface Session extends NoTokenSession {
|
|
27
|
+
token: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type GroupPolicyType = "at_least_one" | "all";
|
|
31
|
+
|
|
32
|
+
export type GroupPolicyGroups = string | string[];
|
|
33
|
+
|
|
34
|
+
export interface GroupPolicy {
|
|
35
|
+
groups: GroupPolicyGroups[];
|
|
36
|
+
groupPolicy: GroupPolicyType;
|
|
37
|
+
}
|
|
@@ -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,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
|
+
};
|