@miqro/core 4.0.1 → 5.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/app.d.ts +15 -11
- package/build/app.js +22 -20
- package/build/app.js.map +1 -1
- package/build/common.d.ts +106 -0
- package/build/common.js +477 -0
- package/build/common.js.map +1 -0
- package/build/lib.d.ts +7 -38
- package/build/lib.js +6 -33
- package/build/lib.js.map +1 -1
- package/build/middleware/body-parser.d.ts +78 -0
- package/build/middleware/body-parser.js +548 -0
- package/build/middleware/body-parser.js.map +1 -0
- package/build/middleware/router.d.ts +114 -0
- package/build/middleware/router.js +704 -0
- package/build/middleware/router.js.map +1 -0
- package/build/middleware/session.d.ts +27 -3
- package/build/middleware/session.js +238 -18
- package/build/middleware/session.js.map +1 -1
- package/build/types.d.ts +309 -0
- package/build/types.js +455 -0
- package/build/types.js.map +1 -0
- package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
- package/build/websocket.js +316 -0
- package/build/websocket.js.map +1 -0
- package/package.json +7 -7
- package/src/app.ts +36 -32
- package/src/common.ts +528 -0
- package/src/lib.ts +63 -101
- package/src/middleware/body-parser.ts +593 -0
- package/src/middleware/router.ts +840 -0
- package/src/middleware/session.ts +249 -19
- package/src/types.ts +785 -0
- package/src/websocket.ts +356 -0
- package/build/api-router.d.ts +0 -34
- package/build/api-router.js +0 -48
- package/build/api-router.js.map +0 -1
- package/build/app-utils.d.ts +0 -13
- package/build/app-utils.js +0 -78
- package/build/app-utils.js.map +0 -1
- package/build/common/api-router-types.d.ts +0 -28
- package/build/common/api-router-types.js +0 -24
- package/build/common/api-router-types.js.map +0 -1
- package/build/common/api-router-utils.d.ts +0 -3
- package/build/common/api-router-utils.js +0 -118
- package/build/common/api-router-utils.js.map +0 -1
- package/build/common/config/config.d.ts +0 -15
- package/build/common/config/config.js +0 -38
- package/build/common/config/config.js.map +0 -1
- package/build/common/config/featuretoggle.d.ts +0 -1
- package/build/common/config/featuretoggle.js +0 -6
- package/build/common/config/featuretoggle.js.map +0 -1
- package/build/common/config/loader.d.ts +0 -13
- package/build/common/config/loader.js +0 -64
- package/build/common/config/loader.js.map +0 -1
- package/build/common/context.d.ts +0 -57
- package/build/common/context.js +0 -137
- package/build/common/context.js.map +0 -1
- package/build/common/error/badrequesterror.d.ts +0 -3
- package/build/common/error/badrequesterror.js +0 -7
- package/build/common/error/badrequesterror.js.map +0 -1
- package/build/common/error/configfilenotfound.d.ts +0 -3
- package/build/common/error/configfilenotfound.js +0 -7
- package/build/common/error/configfilenotfound.js.map +0 -1
- package/build/common/error/forbiddenerror.d.ts +0 -3
- package/build/common/error/forbiddenerror.js +0 -7
- package/build/common/error/forbiddenerror.js.map +0 -1
- package/build/common/error/notfound.d.ts +0 -3
- package/build/common/error/notfound.js +0 -7
- package/build/common/error/notfound.js.map +0 -1
- package/build/common/error/notimplemented.d.ts +0 -3
- package/build/common/error/notimplemented.js +0 -7
- package/build/common/error/notimplemented.js.map +0 -1
- package/build/common/error/unauthorizederror.d.ts +0 -3
- package/build/common/error/unauthorizederror.js +0 -7
- package/build/common/error/unauthorizederror.js.map +0 -1
- package/build/common/logger/constants.d.ts +0 -14
- package/build/common/logger/constants.js +0 -22
- package/build/common/logger/constants.js.map +0 -1
- package/build/common/logger/factory.d.ts +0 -16
- package/build/common/logger/factory.js +0 -47
- package/build/common/logger/factory.js.map +0 -1
- package/build/common/logger/interfaces.d.ts +0 -18
- package/build/common/logger/interfaces.js +0 -2
- package/build/common/logger/interfaces.js.map +0 -1
- package/build/common/logger/logger.d.ts +0 -35
- package/build/common/logger/logger.js +0 -95
- package/build/common/logger/logger.js.map +0 -1
- package/build/common/logger/transport/console.d.ts +0 -5
- package/build/common/logger/transport/console.js +0 -37
- package/build/common/logger/transport/console.js.map +0 -1
- package/build/common/logger/transport/file.d.ts +0 -2
- package/build/common/logger/transport/file.js +0 -25
- package/build/common/logger/transport/file.js.map +0 -1
- package/build/common/parser.d.ts +0 -7
- package/build/common/parser.js +0 -44
- package/build/common/parser.js.map +0 -1
- package/build/common/router-default-logger-factory.d.ts +0 -4
- package/build/common/router-default-logger-factory.js +0 -38
- package/build/common/router-default-logger-factory.js.map +0 -1
- package/build/common/router-handler.d.ts +0 -20
- package/build/common/router-handler.js +0 -154
- package/build/common/router-handler.js.map +0 -1
- package/build/common/router-types.d.ts +0 -63
- package/build/common/router-types.js +0 -86
- package/build/common/router-types.js.map +0 -1
- package/build/common/router-utils.d.ts +0 -3
- package/build/common/router-utils.js +0 -46
- package/build/common/router-utils.js.map +0 -1
- package/build/common/session/common.d.ts +0 -37
- package/build/common/session/common.js +0 -2
- package/build/common/session/common.js.map +0 -1
- package/build/common/session/service.d.ts +0 -26
- package/build/common/session/service.js +0 -154
- package/build/common/session/service.js.map +0 -1
- package/build/common/tokenize-match.d.ts +0 -19
- package/build/common/tokenize-match.js +0 -73
- package/build/common/tokenize-match.js.map +0 -1
- package/build/common/url-utils.d.ts +0 -6
- package/build/common/url-utils.js +0 -48
- package/build/common/url-utils.js.map +0 -1
- package/build/middleware/buffer.d.ts +0 -6
- package/build/middleware/buffer.js +0 -78
- package/build/middleware/buffer.js.map +0 -1
- package/build/middleware/cookie.d.ts +0 -4
- package/build/middleware/cookie.js +0 -15
- package/build/middleware/cookie.js.map +0 -1
- package/build/middleware/cors.d.ts +0 -8
- package/build/middleware/cors.js +0 -89
- package/build/middleware/cors.js.map +0 -1
- package/build/middleware/form.d.ts +0 -6
- package/build/middleware/form.js +0 -58
- package/build/middleware/form.js.map +0 -1
- package/build/middleware/group.d.ts +0 -3
- package/build/middleware/group.js +0 -77
- package/build/middleware/group.js.map +0 -1
- package/build/middleware/json.d.ts +0 -6
- package/build/middleware/json.js +0 -55
- package/build/middleware/json.js.map +0 -1
- package/build/middleware/logger.d.ts +0 -4
- package/build/middleware/logger.js +0 -16
- package/build/middleware/logger.js.map +0 -1
- package/build/middleware/parse.d.ts +0 -14
- package/build/middleware/parse.js +0 -88
- package/build/middleware/parse.js.map +0 -1
- package/build/middleware/result.d.ts +0 -9
- package/build/middleware/result.js +0 -62
- package/build/middleware/result.js.map +0 -1
- package/build/middleware/tag.d.ts +0 -4
- package/build/middleware/tag.js +0 -10
- package/build/middleware/tag.js.map +0 -1
- package/build/middleware/text.d.ts +0 -5
- package/build/middleware/text.js +0 -46
- package/build/middleware/text.js.map +0 -1
- package/build/proxy.d.ts +0 -19
- package/build/proxy.js +0 -74
- package/build/proxy.js.map +0 -1
- package/build/router.d.ts +0 -26
- package/build/router.js +0 -116
- package/build/router.js.map +0 -1
- package/build/static.d.ts +0 -14
- package/build/static.js +0 -211
- package/build/static.js.map +0 -1
- package/build/websocket/cluster.js +0 -114
- package/build/websocket/cluster.js.map +0 -1
- package/build/websocket/server.d.ts +0 -15
- package/build/websocket/server.js +0 -127
- package/build/websocket/server.js.map +0 -1
- package/build/websocket/types.d.ts +0 -39
- package/build/websocket/types.js +0 -2
- package/build/websocket/types.js.map +0 -1
- package/build/websocket/utils.d.ts +0 -8
- package/build/websocket/utils.js +0 -77
- package/build/websocket/utils.js.map +0 -1
- package/src/api-router.ts +0 -50
- package/src/app-utils.ts +0 -82
- package/src/common/api-router-types.ts +0 -52
- package/src/common/api-router-utils.ts +0 -126
- package/src/common/config/config.ts +0 -49
- package/src/common/config/featuretoggle.ts +0 -6
- package/src/common/config/loader.ts +0 -81
- package/src/common/context.ts +0 -192
- package/src/common/error/badrequesterror.ts +0 -6
- package/src/common/error/configfilenotfound.ts +0 -6
- package/src/common/error/forbiddenerror.ts +0 -6
- package/src/common/error/notfound.ts +0 -6
- package/src/common/error/notimplemented.ts +0 -6
- package/src/common/error/unauthorizederror.ts +0 -6
- package/src/common/logger/constants.ts +0 -28
- package/src/common/logger/factory.ts +0 -53
- package/src/common/logger/interfaces.ts +0 -19
- package/src/common/logger/logger.ts +0 -136
- package/src/common/logger/transport/console.ts +0 -36
- package/src/common/logger/transport/file.ts +0 -26
- package/src/common/parser.ts +0 -50
- package/src/common/router-default-logger-factory.ts +0 -44
- package/src/common/router-handler.ts +0 -186
- package/src/common/router-types.ts +0 -153
- package/src/common/router-utils.ts +0 -47
- package/src/common/session/common.ts +0 -40
- package/src/common/session/service.ts +0 -175
- package/src/common/tokenize-match.ts +0 -98
- package/src/common/url-utils.ts +0 -46
- package/src/middleware/buffer.ts +0 -82
- package/src/middleware/cookie.ts +0 -20
- package/src/middleware/cors.ts +0 -98
- package/src/middleware/form.ts +0 -61
- package/src/middleware/group.ts +0 -74
- package/src/middleware/json.ts +0 -57
- package/src/middleware/logger.ts +0 -18
- package/src/middleware/parse.ts +0 -105
- package/src/middleware/result.ts +0 -73
- package/src/middleware/tag.ts +0 -15
- package/src/middleware/text.ts +0 -47
- package/src/proxy.ts +0 -99
- package/src/router.ts +0 -140
- package/src/static.ts +0 -242
- package/src/websocket/cluster.ts +0 -128
- package/src/websocket/server.ts +0 -135
- package/src/websocket/types.ts +0 -41
- package/src/websocket/utils.ts +0 -95
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { Context } from "../context.js";
|
|
2
|
-
|
|
3
|
-
export interface SessionHandlerOptions {
|
|
4
|
-
authService: {
|
|
5
|
-
verify(args: { token: string; ctx: Context }): Promise<Session | null>;
|
|
6
|
-
};
|
|
7
|
-
options?: {
|
|
8
|
-
tokenLocation: "header" | "query" | "cookie";
|
|
9
|
-
tokenLocationName: string | ((ctx: Context) => Promise<string>);
|
|
10
|
-
setCookieOptions?: {
|
|
11
|
-
httpOnly: boolean;
|
|
12
|
-
secure: boolean;
|
|
13
|
-
path: string | ((ctx: Context) => Promise<string>);
|
|
14
|
-
sameSite: "lax" | "strict" | "none";
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
type Dict<T = any> = {
|
|
20
|
-
[key: string]: T
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface NoTokenSession extends Dict {
|
|
24
|
-
account: string;
|
|
25
|
-
username: string;
|
|
26
|
-
groups: string[];
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
export interface Session extends NoTokenSession {
|
|
30
|
-
token: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export type GroupPolicyType = "at_least_one" | "all";
|
|
34
|
-
|
|
35
|
-
export type GroupPolicyGroups = string | string[];
|
|
36
|
-
|
|
37
|
-
export interface GroupPolicy {
|
|
38
|
-
groups: GroupPolicyGroups[];
|
|
39
|
-
groupPolicy: GroupPolicyType;
|
|
40
|
-
}
|
|
@@ -1,175 +0,0 @@
|
|
|
1
|
-
import { NoTokenSession, Session } from "./common.js";
|
|
2
|
-
import { Context } from "../context.js";
|
|
3
|
-
import { checkEnvVariables } from "../config/config.js";
|
|
4
|
-
import { UnAuthorizedError } from "../error/unauthorizederror.js";
|
|
5
|
-
import { request, RequestOptions, RequestResponse } from "@miqro/request";
|
|
6
|
-
import { Schema } from "@miqro/parser";
|
|
7
|
-
import { parse as cookieParse } from "cookie";
|
|
8
|
-
import { DEFAULT_PARSER, assertNotUndefined } from "../parser.js";
|
|
9
|
-
|
|
10
|
-
const DEFAULT_TOKEN_LOCATION = "header";
|
|
11
|
-
const DEFAULT_TOKEN_HEADER = "Authorization";
|
|
12
|
-
const DEFAULT_TOKEN_QUERY = "token";
|
|
13
|
-
const DEFAULT_TOKEN_COOKIE = "Authorization";
|
|
14
|
-
|
|
15
|
-
export interface VerifyTokenService {
|
|
16
|
-
verify(args: { token: string; ctx: Context }): Promise<Session | null>;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface VerifyEndpointServiceOptions {
|
|
20
|
-
url: string;
|
|
21
|
-
method: string;
|
|
22
|
-
tokenLocation: "header" | "query" | "cookie";
|
|
23
|
-
tokenLocationName: string | ((ctx: Context) => Promise<string>);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const NoTokenSessionSchema: Schema<NoTokenSession> = {
|
|
27
|
-
type: "object",
|
|
28
|
-
properties: {
|
|
29
|
-
username: "string",
|
|
30
|
-
account: "string",
|
|
31
|
-
groups: "string[]"
|
|
32
|
-
},
|
|
33
|
-
mode: "add_extra"
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const VerifyEndpointServiceSchema: Schema<VerifyEndpointServiceOptions> = {
|
|
37
|
-
type: "object",
|
|
38
|
-
properties: {
|
|
39
|
-
url: "string1",
|
|
40
|
-
method: "string1",
|
|
41
|
-
tokenLocation: {
|
|
42
|
-
type: "enum",
|
|
43
|
-
enumValues: ["header", "query", "cookie"]
|
|
44
|
-
},
|
|
45
|
-
tokenLocationName: "string1"
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
export class VerifyEndpointService implements VerifyTokenService {
|
|
50
|
-
|
|
51
|
-
protected options: VerifyEndpointServiceOptions;
|
|
52
|
-
|
|
53
|
-
constructor(options?: VerifyEndpointServiceOptions) {
|
|
54
|
-
if (!options) {
|
|
55
|
-
const [url, method] = checkEnvVariables(["TOKEN_VERIFY_ENDPOINT", "TOKEN_VERIFY_ENDPOINT_METHOD"]);
|
|
56
|
-
const [tokenVerifyLocation] = checkEnvVariables(["TOKEN_VERIFY_LOCATION"], [DEFAULT_TOKEN_LOCATION]);
|
|
57
|
-
let tokenLocationName;
|
|
58
|
-
switch (tokenVerifyLocation) {
|
|
59
|
-
case "header":
|
|
60
|
-
tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
|
|
61
|
-
break;
|
|
62
|
-
case "query":
|
|
63
|
-
tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
|
|
64
|
-
break;
|
|
65
|
-
case "cookie":
|
|
66
|
-
tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
|
|
67
|
-
break;
|
|
68
|
-
default:
|
|
69
|
-
throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header or query)`);
|
|
70
|
-
}
|
|
71
|
-
this.options = {
|
|
72
|
-
url, method,
|
|
73
|
-
tokenLocation: tokenVerifyLocation,
|
|
74
|
-
tokenLocationName
|
|
75
|
-
}
|
|
76
|
-
} else {
|
|
77
|
-
this.options = assertNotUndefined(DEFAULT_PARSER.parse(options, VerifyEndpointServiceSchema, "options"), "bad options");
|
|
78
|
-
}
|
|
79
|
-
if (this.options.tokenLocationName && (this.options.tokenLocationName === "__proto__" || this.options.tokenLocationName === "__prototype__")) {
|
|
80
|
-
throw new Error(`invalid tokenLocationName ${this.options.tokenLocationName}`);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
public async verify({ token, ctx }: { token: string; ctx: Context }): Promise<Session | null> {
|
|
85
|
-
try {
|
|
86
|
-
let response = null;
|
|
87
|
-
const tokenVerifyLocation = this.options.tokenLocation;
|
|
88
|
-
const url = this.options.url;
|
|
89
|
-
const method = this.options.method;
|
|
90
|
-
switch (tokenVerifyLocation) {
|
|
91
|
-
case "header":
|
|
92
|
-
const tokenHeaderLocation = 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_HEADER=[${tokenHeaderLocation}]`);
|
|
94
|
-
response = await this.getResponse({
|
|
95
|
-
url,
|
|
96
|
-
headers: {
|
|
97
|
-
[tokenHeaderLocation]: token
|
|
98
|
-
},
|
|
99
|
-
method
|
|
100
|
-
}, ctx);
|
|
101
|
-
break;
|
|
102
|
-
case "query":
|
|
103
|
-
const tokenQueryLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
|
|
104
|
-
ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
|
|
105
|
-
response = await this.getResponse({
|
|
106
|
-
url,
|
|
107
|
-
query: {
|
|
108
|
-
[tokenQueryLocation]: token
|
|
109
|
-
},
|
|
110
|
-
method
|
|
111
|
-
}, ctx);
|
|
112
|
-
break;
|
|
113
|
-
case "cookie":
|
|
114
|
-
const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
|
|
115
|
-
ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
|
|
116
|
-
response = await this.getResponse({
|
|
117
|
-
url,
|
|
118
|
-
method,
|
|
119
|
-
headers: {
|
|
120
|
-
Cookie: `${tokenCookieLocation}=${token}; Path=/; HttpOnly;`
|
|
121
|
-
}
|
|
122
|
-
}, ctx);
|
|
123
|
-
break;
|
|
124
|
-
default:
|
|
125
|
-
throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header, query or cookie)`);
|
|
126
|
-
}
|
|
127
|
-
if (response) {
|
|
128
|
-
const session = await this.decodeSession(response, token, ctx);
|
|
129
|
-
if (!this.checkSession(session, ctx)) {
|
|
130
|
-
ctx.logger.warn(`unauthorized token not valid [${token}]`);
|
|
131
|
-
return null;
|
|
132
|
-
} else {
|
|
133
|
-
ctx.logger.trace("token [%s]authorized!", token);
|
|
134
|
-
|
|
135
|
-
if (tokenVerifyLocation === "cookie" && response.headers["set-cookie"]) {
|
|
136
|
-
const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
|
|
137
|
-
const cookies = response.headers["set-cookie"].map((c: any) => cookieParse(c)).filter((c: any) => c[tokenCookieLocation] !== undefined);
|
|
138
|
-
if (cookies.length === 1) {
|
|
139
|
-
const value = cookies[0][tokenCookieLocation];
|
|
140
|
-
if (value) {
|
|
141
|
-
session.token = value; // replace token because token update via set-cookie
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
return {
|
|
146
|
-
token,
|
|
147
|
-
...session
|
|
148
|
-
} as Session;
|
|
149
|
-
}
|
|
150
|
-
} else {
|
|
151
|
-
ctx.logger.warn(`unauthorized token not valid [${token}]`);
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
154
|
-
} catch (e: any) {
|
|
155
|
-
throw new UnAuthorizedError(`Fail to authenticate token! error verifying [${token}] [${e.status}][${e.config ? e.config.url : ""}]`);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
160
|
-
protected async getResponse(config: RequestOptions, ctx?: Context): Promise<RequestResponse> {
|
|
161
|
-
return request(config);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
165
|
-
protected checkSession(session: NoTokenSession, ctx?: Context): boolean {
|
|
166
|
-
assertNotUndefined(DEFAULT_PARSER.parse(session, NoTokenSessionSchema, "session"), "bad session");
|
|
167
|
-
return true;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
171
|
-
protected async decodeSession(response: RequestResponse, token: string, ctx?: Context): Promise<NoTokenSession> {
|
|
172
|
-
const session = response.data;
|
|
173
|
-
return session as NoTokenSession;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
export interface PathParams {
|
|
2
|
-
[name: string]: string | undefined
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
export interface PathPartToken extends PathPart {
|
|
6
|
-
optional: boolean;
|
|
7
|
-
wild?: string;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export interface PathPart {
|
|
11
|
-
value: string;
|
|
12
|
-
lower: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
function pathPartTokenize(token: PathPart): PathPartToken {
|
|
16
|
-
const isWild = token.value[0] === ":";
|
|
17
|
-
const optional = token.value[token.value.length - 1] === "?";
|
|
18
|
-
const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
|
|
19
|
-
return {
|
|
20
|
-
optional,
|
|
21
|
-
wild,
|
|
22
|
-
value: token.value,
|
|
23
|
-
lower: token.lower
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export const splitPath = (path?: string): PathPart[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
|
|
28
|
-
return {
|
|
29
|
-
value: p,
|
|
30
|
-
lower: p.toLocaleLowerCase()
|
|
31
|
-
};
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
export function tokenizePath(path?: string): PathPartToken[] {
|
|
35
|
-
if (path === undefined) {
|
|
36
|
-
return [];
|
|
37
|
-
}
|
|
38
|
-
const tokens = splitPath(path).map(token => pathPartTokenize(token));
|
|
39
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
40
|
-
if (tokens[i].optional && i != tokens.length - 1) {
|
|
41
|
-
throw new Error("cannot set a path token as optional that's not the last one");
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return tokens;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartToken[], requestParts: PathPart[]): {
|
|
48
|
-
match: boolean;
|
|
49
|
-
params?: { [name: string]: string | undefined }
|
|
50
|
-
} {
|
|
51
|
-
for (let i = 0; i < pathTokens.length; i++) {
|
|
52
|
-
if (pathTokens[i].optional && i != pathTokens.length - 1) {
|
|
53
|
-
throw new Error("cannot set a path token as optional that's not the last one");
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
const lastTokenIsOptional = pathTokens.length > 0 ? pathTokens[pathTokens.length - 1].optional : false;
|
|
57
|
-
const couldBeUsingOptional = (lastTokenIsOptional &&
|
|
58
|
-
(
|
|
59
|
-
(!checkAsRouter && pathTokens.length - 1 === requestParts.length) ||
|
|
60
|
-
(checkAsRouter && pathTokens.length - 1 <= requestParts.length)
|
|
61
|
-
)
|
|
62
|
-
);
|
|
63
|
-
|
|
64
|
-
const params: { [name: string]: string | undefined } = Object.create(null);
|
|
65
|
-
|
|
66
|
-
if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
|
|
67
|
-
// similar count of tokens
|
|
68
|
-
for (let i = 0; i < requestParts.length; i++) {
|
|
69
|
-
const ctxToken = requestParts[i];
|
|
70
|
-
if (checkAsRouter && i >= pathTokens.length) {
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
if (pathTokens[i].wild || ctxToken.lower === pathTokens[i].lower) {
|
|
75
|
-
// check pass
|
|
76
|
-
const wild = pathTokens[i].wild;
|
|
77
|
-
if (wild) {
|
|
78
|
-
params[wild] = ctxToken.value;
|
|
79
|
-
}
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
return {
|
|
84
|
-
match: false,
|
|
85
|
-
params: {}
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
return {
|
|
89
|
-
match: true,
|
|
90
|
-
params
|
|
91
|
-
};
|
|
92
|
-
} else {
|
|
93
|
-
return {
|
|
94
|
-
match: false,
|
|
95
|
-
params: {}
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
}
|
package/src/common/url-utils.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
export const newURL = (input: string): URL => {
|
|
2
|
-
/*
|
|
3
|
-
remove /+ at the start of the input before using new URL ( it changes the host )
|
|
4
|
-
*/
|
|
5
|
-
let slashIndex = 0
|
|
6
|
-
for (slashIndex = 0; slashIndex < input.length; slashIndex++) {
|
|
7
|
-
if (input.charAt(slashIndex) !== "/") {
|
|
8
|
-
break;
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
const removedSlashes = input.substring(0, slashIndex - 1);
|
|
12
|
-
const ret = new URL(input.substring(slashIndex), "http://localhost");
|
|
13
|
-
// restore path
|
|
14
|
-
ret.pathname = `${slashIndex > 0 ? removedSlashes : ""}${ret.pathname}`;
|
|
15
|
-
return ret;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// adds "/" to the final of path
|
|
19
|
-
// cannot account for query or hash params so send only new URL().pathname
|
|
20
|
-
export function normalizePath(path: string): string {
|
|
21
|
-
if (typeof path !== "string") {
|
|
22
|
-
throw new Error("path not string");
|
|
23
|
-
}
|
|
24
|
-
if (path.length > 1) {
|
|
25
|
-
if (path.charAt(0) !== "/") {
|
|
26
|
-
throw new Error("path doesnt start with /");
|
|
27
|
-
}
|
|
28
|
-
if (path[path.length - 1] !== "/") {
|
|
29
|
-
return `${path}/`;
|
|
30
|
-
} else {
|
|
31
|
-
return path; // already normalized
|
|
32
|
-
}
|
|
33
|
-
} else if (path !== "/") {
|
|
34
|
-
throw new Error("path of length 1 not /");
|
|
35
|
-
} else {
|
|
36
|
-
return path; // "/"
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
|
|
41
|
-
const query: { [name: string]: string | string[] } = Object.create(null);
|
|
42
|
-
search.forEach((value: string, key: string) => {
|
|
43
|
-
query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
|
|
44
|
-
});
|
|
45
|
-
return query;
|
|
46
|
-
}
|
package/src/middleware/buffer.ts
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { gunzipSync } from "zlib";
|
|
2
|
-
import { Context, Handler } from "../common/context.js";
|
|
3
|
-
import { checkEnvVariables } from "../common/config/config.js";
|
|
4
|
-
import { BadRequestError } from "../common/error/badrequesterror.js";
|
|
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 function ReadBuffer(ctx: Context): Promise<void> {
|
|
26
|
-
return new Promise<void>((resolve, reject) => {
|
|
27
|
-
try {
|
|
28
|
-
const readTimeout = setTimeout(() => {
|
|
29
|
-
clearTimeout(readTimeout);
|
|
30
|
-
ctx.req.removeListener('error', errorListener);
|
|
31
|
-
ctx.req.removeListener('data', chunkListener);
|
|
32
|
-
ctx.req.removeListener('end', endListener);
|
|
33
|
-
ctx.close();
|
|
34
|
-
return;
|
|
35
|
-
}, timeout);
|
|
36
|
-
let cLength = 0;
|
|
37
|
-
const buffers: Buffer[] = [];
|
|
38
|
-
const endListener = () => {
|
|
39
|
-
clearTimeout(readTimeout);
|
|
40
|
-
ctx.req.removeListener('error', errorListener);
|
|
41
|
-
ctx.req.removeListener('data', chunkListener);
|
|
42
|
-
ctx.req.removeListener('end', endListener);
|
|
43
|
-
try {
|
|
44
|
-
const concatBuffers = Buffer.concat(buffers);
|
|
45
|
-
const responseBuffer: Buffer = ctx.headers["content-encoding"] === "gzip" ?
|
|
46
|
-
gunzipSync(concatBuffers) : concatBuffers;
|
|
47
|
-
ctx.logger.trace("ctx.buffer %o", responseBuffer);
|
|
48
|
-
ctx.buffer = responseBuffer;
|
|
49
|
-
resolve();
|
|
50
|
-
} catch (e) {
|
|
51
|
-
reject(e);
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
const errorListener = (err: Error) => {
|
|
55
|
-
clearTimeout(readTimeout);
|
|
56
|
-
ctx.req.removeListener('error', errorListener);
|
|
57
|
-
ctx.req.removeListener('data', chunkListener);
|
|
58
|
-
ctx.req.removeListener('end', endListener);
|
|
59
|
-
reject(err);
|
|
60
|
-
};
|
|
61
|
-
const chunkListener = (chunk: Buffer) => {
|
|
62
|
-
cLength += chunk.length;
|
|
63
|
-
if (cLength > limit) {
|
|
64
|
-
clearTimeout(readTimeout);
|
|
65
|
-
ctx.req.removeListener('error', errorListener);
|
|
66
|
-
ctx.req.removeListener('data', chunkListener);
|
|
67
|
-
ctx.req.removeListener('end', endListener);
|
|
68
|
-
ctx.logger.error(`ctx.buffer.length ${cLength} > ${limit}. To accept this body set READ_BUFFER_LIMIT to a higher value.`);
|
|
69
|
-
reject(new BadRequestError(`buffer.length ${cLength} > ${limit}`));
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
buffers.push(chunk);
|
|
73
|
-
};
|
|
74
|
-
ctx.req.on('error', errorListener);
|
|
75
|
-
ctx.req.on('data', chunkListener);
|
|
76
|
-
ctx.req.on('end', endListener);
|
|
77
|
-
} catch (e) {
|
|
78
|
-
reject(e);
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
}
|
package/src/middleware/cookie.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { Context, Handler } from "../common/context.js";
|
|
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
|
-
|
package/src/middleware/cors.ts
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
import { checkEnvVariables } from "../common/config/config.js";
|
|
2
|
-
import { Context, Handler } from "../common/context.js";
|
|
3
|
-
import { BadRequestError } from "../common/error/badrequesterror.js";
|
|
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;
|
|
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 function CORS(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
|
-
await ctx.end({
|
|
89
|
-
headers: {
|
|
90
|
-
"Content-Length": 0
|
|
91
|
-
},
|
|
92
|
-
status: 204,
|
|
93
|
-
body: undefined
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
};
|
package/src/middleware/form.ts
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { parse as queryParse } from "querystring";
|
|
2
|
-
import { DEFAULT_READ_BUFFER_LIMIT, ReadBuffer } from "./buffer.js";
|
|
3
|
-
import { Context, Handler } from "../common/context.js";
|
|
4
|
-
import { checkEnvVariables } from "../common/config/config.js";
|
|
5
|
-
import { BadRequestError } from "../common/error/badrequesterror.js";
|
|
6
|
-
|
|
7
|
-
const DEFAULT_FORM_MAX_KEYS: undefined | number = 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
|
-
const readBuffer = ReadBuffer({
|
|
29
|
-
limit
|
|
30
|
-
});
|
|
31
|
-
return async function URLEncodedParser(ctx: Context): Promise<void> {
|
|
32
|
-
try {
|
|
33
|
-
const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
|
|
34
|
-
if (isType && !ctx.buffer) {
|
|
35
|
-
await readBuffer(ctx);
|
|
36
|
-
}
|
|
37
|
-
if (isType && ctx.buffer && ctx.buffer.length <= limit) {
|
|
38
|
-
const string = ctx.buffer.toString();
|
|
39
|
-
if (string) {
|
|
40
|
-
const body = {
|
|
41
|
-
...queryParse(string, undefined, undefined, {
|
|
42
|
-
maxKeys
|
|
43
|
-
})
|
|
44
|
-
};
|
|
45
|
-
ctx.logger.debug("ctx.body = %s", body);
|
|
46
|
-
ctx.body = body;
|
|
47
|
-
}
|
|
48
|
-
} else if (isType && ctx.buffer && ctx.buffer.length > limit) {
|
|
49
|
-
ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_PARSER_URL_ENCODED_LIMIT to a higher value.`);
|
|
50
|
-
throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
|
|
51
|
-
}
|
|
52
|
-
} catch (e: any) {
|
|
53
|
-
if (e && e.name === "BadRequestError") {
|
|
54
|
-
throw e;
|
|
55
|
-
} else {
|
|
56
|
-
ctx.logger.error(e);
|
|
57
|
-
throw new BadRequestError();
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
};
|