@miqro/core 1.7.0 → 1.7.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.
Files changed (159) hide show
  1. package/dist/api-router.js +0 -1
  2. package/dist/app-utils.js +0 -1
  3. package/dist/app.js +2 -3
  4. package/dist/common/api-router-utils.js +0 -1
  5. package/dist/common/api-router.js +0 -1
  6. package/dist/common/config/config.js +0 -1
  7. package/dist/common/config/featuretoggle.js +0 -1
  8. package/dist/common/config/index.js +0 -1
  9. package/dist/common/config/loader.js +0 -1
  10. package/dist/common/context.d.ts +2 -1
  11. package/dist/common/context.js +27 -12
  12. package/dist/common/error/badrequesterror.js +0 -1
  13. package/dist/common/error/configfilenotfound.js +0 -1
  14. package/dist/common/error/forbiddenerror.js +0 -1
  15. package/dist/common/error/index.js +0 -1
  16. package/dist/common/error/notfound.js +0 -1
  17. package/dist/common/error/notimplemented.js +0 -1
  18. package/dist/common/error/unauthorizederror.js +0 -1
  19. package/dist/common/helpers.js +0 -1
  20. package/dist/common/index.js +0 -1
  21. package/dist/common/logger/constants.js +0 -1
  22. package/dist/common/logger/factory.js +0 -1
  23. package/dist/common/logger/index.js +0 -1
  24. package/dist/common/logger/interfaces.js +0 -1
  25. package/dist/common/logger/logger.js +0 -1
  26. package/dist/common/logger/transport/console.js +0 -1
  27. package/dist/common/logger/transport/file.js +0 -1
  28. package/dist/common/router-handler.js +0 -1
  29. package/dist/common/router-helpers.js +0 -1
  30. package/dist/common/router-utils.js +0 -1
  31. package/dist/common/session/common.js +0 -1
  32. package/dist/common/session/index.js +0 -1
  33. package/dist/common/session/service.js +0 -1
  34. package/dist/common/tokenize-match.js +0 -1
  35. package/dist/index.js +0 -1
  36. package/dist/middleware/buffer.js +0 -1
  37. package/dist/middleware/cookie.js +0 -1
  38. package/dist/middleware/cors.js +0 -1
  39. package/dist/middleware/form.js +0 -1
  40. package/dist/middleware/group.js +0 -1
  41. package/dist/middleware/index.js +0 -1
  42. package/dist/middleware/json.js +0 -1
  43. package/dist/middleware/logger.js +0 -1
  44. package/dist/middleware/parse.js +0 -1
  45. package/dist/middleware/result.js +0 -1
  46. package/dist/middleware/session.js +0 -1
  47. package/dist/middleware/tag.js +0 -1
  48. package/dist/middleware/text.js +0 -1
  49. package/dist/proxy.js +28 -11
  50. package/dist/router.js +2 -3
  51. package/dist/static.js +0 -1
  52. package/package.json +7 -9
  53. package/dist/api-router.js.map +0 -1
  54. package/dist/app-utils.js.map +0 -1
  55. package/dist/app.js.map +0 -1
  56. package/dist/common/api-router-utils.js.map +0 -1
  57. package/dist/common/api-router.js.map +0 -1
  58. package/dist/common/config/config.js.map +0 -1
  59. package/dist/common/config/featuretoggle.js.map +0 -1
  60. package/dist/common/config/index.js.map +0 -1
  61. package/dist/common/config/loader.js.map +0 -1
  62. package/dist/common/context.js.map +0 -1
  63. package/dist/common/error/badrequesterror.js.map +0 -1
  64. package/dist/common/error/configfilenotfound.js.map +0 -1
  65. package/dist/common/error/forbiddenerror.js.map +0 -1
  66. package/dist/common/error/index.js.map +0 -1
  67. package/dist/common/error/notfound.js.map +0 -1
  68. package/dist/common/error/notimplemented.js.map +0 -1
  69. package/dist/common/error/unauthorizederror.js.map +0 -1
  70. package/dist/common/helpers.js.map +0 -1
  71. package/dist/common/index.js.map +0 -1
  72. package/dist/common/logger/constants.js.map +0 -1
  73. package/dist/common/logger/factory.js.map +0 -1
  74. package/dist/common/logger/index.js.map +0 -1
  75. package/dist/common/logger/interfaces.js.map +0 -1
  76. package/dist/common/logger/logger.js.map +0 -1
  77. package/dist/common/logger/transport/console.js.map +0 -1
  78. package/dist/common/logger/transport/file.js.map +0 -1
  79. package/dist/common/router-handler.js.map +0 -1
  80. package/dist/common/router-helpers.js.map +0 -1
  81. package/dist/common/router-utils.js.map +0 -1
  82. package/dist/common/session/common.js.map +0 -1
  83. package/dist/common/session/index.js.map +0 -1
  84. package/dist/common/session/service.js.map +0 -1
  85. package/dist/common/tokenize-match.js.map +0 -1
  86. package/dist/index.js.map +0 -1
  87. package/dist/middleware/buffer.js.map +0 -1
  88. package/dist/middleware/cookie.js.map +0 -1
  89. package/dist/middleware/cors.js.map +0 -1
  90. package/dist/middleware/form.js.map +0 -1
  91. package/dist/middleware/group.js.map +0 -1
  92. package/dist/middleware/index.js.map +0 -1
  93. package/dist/middleware/json.js.map +0 -1
  94. package/dist/middleware/logger.js.map +0 -1
  95. package/dist/middleware/parse.js.map +0 -1
  96. package/dist/middleware/result.js.map +0 -1
  97. package/dist/middleware/session.js.map +0 -1
  98. package/dist/middleware/tag.js.map +0 -1
  99. package/dist/middleware/text.js.map +0 -1
  100. package/dist/proxy.js.map +0 -1
  101. package/dist/router.js.map +0 -1
  102. package/dist/static.js.map +0 -1
  103. package/src/api-router.ts +0 -60
  104. package/src/api-router.unit.test.js +0 -273
  105. package/src/app-utils.ts +0 -82
  106. package/src/app-utils.unit.test.js +0 -100
  107. package/src/app.ts +0 -51
  108. package/src/app.unit.test.js +0 -334
  109. package/src/common/api-router-utils.ts +0 -193
  110. package/src/common/api-router.ts +0 -19
  111. package/src/common/config/config.ts +0 -111
  112. package/src/common/config/featuretoggle.ts +0 -6
  113. package/src/common/config/index.ts +0 -3
  114. package/src/common/config/loader.ts +0 -80
  115. package/src/common/context.ts +0 -167
  116. package/src/common/context.unit.test.js +0 -288
  117. package/src/common/error/badrequesterror.ts +0 -6
  118. package/src/common/error/configfilenotfound.ts +0 -6
  119. package/src/common/error/forbiddenerror.ts +0 -6
  120. package/src/common/error/index.ts +0 -6
  121. package/src/common/error/notfound.ts +0 -6
  122. package/src/common/error/notimplemented.ts +0 -6
  123. package/src/common/error/unauthorizederror.ts +0 -6
  124. package/src/common/helpers.ts +0 -11
  125. package/src/common/index.ts +0 -7
  126. package/src/common/logger/constants.ts +0 -27
  127. package/src/common/logger/factory.ts +0 -53
  128. package/src/common/logger/index.ts +0 -6
  129. package/src/common/logger/interfaces.ts +0 -19
  130. package/src/common/logger/logger.ts +0 -136
  131. package/src/common/logger/transport/console.ts +0 -34
  132. package/src/common/logger/transport/file.ts +0 -26
  133. package/src/common/router-handler.ts +0 -159
  134. package/src/common/router-helpers.ts +0 -20
  135. package/src/common/router-utils.ts +0 -95
  136. package/src/common/session/common.ts +0 -40
  137. package/src/common/session/index.ts +0 -2
  138. package/src/common/session/service.ts +0 -160
  139. package/src/common/tokenize-match.ts +0 -130
  140. package/src/index.ts +0 -7
  141. package/src/middleware/buffer.ts +0 -80
  142. package/src/middleware/cookie.ts +0 -20
  143. package/src/middleware/cors.ts +0 -96
  144. package/src/middleware/form.ts +0 -59
  145. package/src/middleware/group.ts +0 -70
  146. package/src/middleware/index.ts +0 -48
  147. package/src/middleware/json.ts +0 -55
  148. package/src/middleware/logger.ts +0 -18
  149. package/src/middleware/parse.ts +0 -93
  150. package/src/middleware/result.ts +0 -43
  151. package/src/middleware/session.ts +0 -136
  152. package/src/middleware/tag.ts +0 -15
  153. package/src/middleware/text.ts +0 -45
  154. package/src/proxy.ts +0 -77
  155. package/src/proxy.unit.test.js +0 -159
  156. package/src/router.ts +0 -112
  157. package/src/router.unit.test.js +0 -397
  158. package/src/setup-test.js +0 -5
  159. package/src/static.ts +0 -238
@@ -1,159 +0,0 @@
1
- import {matchTokenizePath, PathPart, PathParams, PathPartToken, tokenizePath} from "./tokenize-match";
2
- import {Context, Handler, Method} from "./context";
3
- import {Router} from "../router";
4
- import {parse} from "@miqro/parser";
5
- import {GroupPolicyHandler, ParseRequest, SessionHandler, ResultParser} from "../middleware";
6
- import {
7
- HandlerWithOptions,
8
- handlerWithOptionsParseOptions, ResponseHandler,
9
- RouterHandlerOptions,
10
- routerHandlerParseOptions, RouterJSONDoc
11
- } from "./router-utils";
12
-
13
- export class RouterHandler {
14
-
15
- private readonly tokens: PathPartToken[];
16
- private readonly handler: Array<Handler | Router>;
17
- private readonly isRouter: boolean;
18
- private readonly options?: RouterHandlerOptions;
19
-
20
- public constructor(
21
- handler: Array<Handler> | HandlerWithOptions | Handler | Router,
22
- private readonly path: string | undefined,
23
- private readonly method: Method | undefined,
24
- options?: RouterHandlerOptions) {
25
- this.tokens = tokenizePath(path);
26
-
27
- if (options) {
28
- options = parse(options, routerHandlerParseOptions, "no_extra", "options");
29
- }
30
-
31
- let handlers: Array<Handler | Router> = []
32
- this.isRouter = handler instanceof Router;
33
-
34
- if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
35
- // HandlerWithOptions
36
- if (options) {
37
- throw new Error("bad arguments. cannot send options with HandlerWithOptions");
38
- }
39
- handler = parse(handler, handlerWithOptionsParseOptions, "no_extra", "handler");
40
- const realHandler = (handler as HandlerWithOptions).handler;
41
- const newOptions = {
42
- ...(handler as HandlerWithOptions)
43
- };
44
- delete (newOptions as any).handler;
45
- handler = realHandler;
46
- this.options = newOptions;
47
- } else {
48
- this.options = options;
49
- }
50
- const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
51
-
52
- if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
53
- throw new Error("bad arguments");
54
- }
55
-
56
- if (this.options && this.options.middleware) {
57
- handlers = handlers.concat(this.options.middleware);
58
- }
59
- if (this.options && this.options.session) {
60
- handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
61
- }
62
- if (this.options && this.options.policy) {
63
- handlers.push(GroupPolicyHandler(this.options.policy));
64
- }
65
- if (this.options && this.options.request) {
66
- handlers.push(ParseRequest(this.options.request, this.options.parser));
67
- }
68
-
69
- handlers = handlers.concat(routeHandlers);
70
-
71
- if (this.options && this.options.response) {
72
- if (typeof this.options.response.body === "boolean" && this.options.response.body) {
73
- (handlers as Handler[]).push(ResponseHandler());
74
- } else if (this.options.response.body) {
75
- (handlers as Handler[]).push(ResultParser(this.options.response.body, this.options.parser));
76
- (handlers as Handler[]).push(ResponseHandler());
77
- }
78
- }
79
- this.handler = handlers;
80
- }
81
-
82
- public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
83
- const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
84
- const nMethod = this.method ? this.method : "";
85
-
86
- if (this.isRouter) {
87
- const router: Router = this.handler[0] as Router;
88
- router.getJSONDoc(doc, `${prePath}${nPath}`);
89
- } else if (this.options) {
90
- if (!doc[`${prePath}${nPath}`]) {
91
- doc[`${prePath}${nPath}`] = Object.create(null);
92
- }
93
- if (doc[`${prePath}${nPath}`][nMethod]) {
94
- throw new Error("cannot create doc routes override each other");
95
- }
96
- doc[`${prePath}${nPath}`][nMethod] = {
97
- description: this.options.description,
98
- name: this.options.name,
99
- identifier: `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
100
- policy: this.options.policy,
101
- request: this.options.request ? {
102
- body: this.options.request.body,
103
- headers: this.options.request.headers,
104
- params: this.options.request.params,
105
- query: this.options.request.query,
106
- } : undefined,
107
- response: this.options.response
108
- };
109
- }
110
- return doc;
111
- }
112
-
113
- public async invoke(ctx: Context, pathTokens: PathPart[], prePathTokens: PathPartToken[]): Promise<boolean> {
114
- for (let i = 0; i < this.handler.length; i++) {
115
- const h = this.handler[i];
116
- if (h instanceof Router) {
117
- if (!RouterHandler.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
118
- return false;
119
- }
120
- } else {
121
- if (!RouterHandler.pushResults(await h(ctx), ctx)) {
122
- return false;
123
- }
124
- }
125
- }
126
- return true;
127
- }
128
-
129
- public isMatch(
130
- method: string,
131
- requestParts: PathPart[],
132
- prePathTokens: PathPartToken[]): {
133
- match: boolean;
134
- params?: PathParams
135
- } {
136
- if ((this.method === undefined || this.method === method)) {
137
- if (this.path === undefined) {
138
- return {
139
- match: true
140
- };
141
- }
142
- return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), requestParts);
143
- }
144
- return {
145
- match: false
146
- };
147
- }
148
-
149
- private static pushResults(result: any, ctx: Context): boolean {
150
- if (result === false) {
151
- // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
152
- return false;
153
- } else if (result !== true && result !== undefined) {
154
- ctx.logger.trace("pushing to results [%o]", result);
155
- ctx.results.push(result);
156
- }
157
- return true;
158
- }
159
- }
@@ -1,20 +0,0 @@
1
- import {IncomingMessage} from "http";
2
- import {URL} from "url";
3
- import {newURL} from "./helpers";
4
- import {normalizePath} from "./tokenize-match";
5
- import {DEFAULT_LOGGER_FORMATTER, getLogger, Logger} from "./logger/index.js";
6
-
7
- export const defaultLoggerFactory = (uuid: string, req: IncomingMessage): Logger => {
8
- const url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
9
- const method = req.method ? req.method.toUpperCase() as string : "GET";
10
- const path = normalizePath(url.pathname); // normalized path
11
- const pathToEnv = path.replace(/\//ig, "_").toUpperCase();
12
- const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${method.toUpperCase()}`;
13
- const remoteAddress = req.socket.remoteAddress;
14
- return getLogger(identifier, {
15
- formatter: (args) => {
16
- args.message = `${method} ${url}${uuid ? ` [${uuid}]` : ""}${remoteAddress ? ` (${remoteAddress})` : ""} ${args.message}`;
17
- return DEFAULT_LOGGER_FORMATTER(args);
18
- }
19
- }, false);
20
- }
@@ -1,95 +0,0 @@
1
- import {Context, Handler} from "./context";
2
- import {ParseOptionMap, ParseOptions, ParserInterface} from "@miqro/parser";
3
- import {GroupPolicy, SessionHandlerOptions} from "./session";
4
-
5
- export const ResponseHandler = (): Handler<void> => async (ctx: Context): Promise<void> => {
6
- ctx.logger.trace("results [%o]", ctx.results);
7
- if (!ctx.results || ctx.results.length === 0) {
8
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
9
- } else {
10
- const lastResult = ctx.results[ctx.results.length - 1];
11
- ctx.logger.debug("response [%o]", lastResult);
12
- if (lastResult !== undefined) {
13
- await ctx.json(lastResult);
14
- } else {
15
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
16
- }
17
- }
18
- };
19
-
20
-
21
- export const routeParseOptions: ParseOptionMap = {
22
- name: "string?",
23
- description: "string?",
24
- policy: "GroupPolicy?",
25
- response: {
26
- type: "nested?",
27
- nestedOptions: {
28
- options: {
29
- body: "boolean?|ParseOptions[]!?|string?"
30
- },
31
- mode: "no_extra"
32
- }
33
- },
34
- request: {
35
- type: "nested?",
36
- nestedOptions: {
37
- options: {
38
- headers: "ParseOptions[]!?",
39
- query: "boolean?|ParseOptions[]!?|string?",
40
- params: "boolean?|ParseOptions[]!?|string?",
41
- body: "boolean?|ParseOptions[]!?|string?"
42
- },
43
- mode: "no_extra"
44
- }
45
- }
46
- };
47
-
48
- export interface RouteOptions {
49
- name?: string;
50
- description?: string;
51
- policy?: GroupPolicy;
52
- request?: {
53
- headers?: ParseOptions | ParseOptions[];
54
- query?: ParseOptions | boolean | ParseOptions[] | string;
55
- params?: ParseOptions | boolean | ParseOptions[] | string;
56
- body?: ParseOptions | boolean | ParseOptions[] | string;
57
- };
58
- response?: {
59
- body?: boolean | ParseOptions | ParseOptions[] | string;
60
- }
61
- }
62
-
63
- export interface RouteJSONDoc extends RouteOptions {
64
- identifier: string;
65
- }
66
-
67
- export interface RouterJSONDoc {
68
- [path: string]: {
69
- [method: string]: RouteJSONDoc
70
- }
71
- }
72
-
73
- export const routerHandlerParseOptions: ParseOptionMap = {
74
- ...routeParseOptions,
75
- parser: "ParserInterface?",
76
- middleware: "function[]!?",
77
- session: "SessionHandlerOptions?|function?"
78
- };
79
-
80
- export interface RouterHandlerOptions extends RouteOptions {
81
- parser?: ParserInterface;
82
- middleware?: Handler | Handler[];
83
- session?: SessionHandlerOptions | Handler;
84
- }
85
-
86
- export const handlerWithOptionsParseOptions: ParseOptionMap = {
87
- ...routerHandlerParseOptions,
88
- handler: "function[]!",
89
- };
90
-
91
- export interface HandlerWithOptions extends RouterHandlerOptions {
92
- handler: Handler | Array<Handler>;
93
- }
94
-
95
-
@@ -1,40 +0,0 @@
1
- import {Context} from "../context";
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,2 +0,0 @@
1
- export * from "./common";
2
- export * from "./service";
@@ -1,160 +0,0 @@
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: "string"}
58
- ], "no_extra", "options") as any;
59
- }
60
- if (this.options.tokenLocationName && (this.options.tokenLocationName === "__proto__" || this.options.tokenLocationName === "__prototype__")) {
61
- throw new Error(`invalid tokenLocationName ${this.options.tokenLocationName}`);
62
- }
63
- }
64
-
65
- public async verify({token, ctx}: { token: string; ctx: Context }): Promise<Session | null> {
66
- try {
67
- let response = null;
68
- const tokenVerifyLocation = this.options.tokenLocation;
69
- const url = this.options.url;
70
- const method = this.options.method;
71
- switch (tokenVerifyLocation) {
72
- case "header":
73
- const tokenHeaderLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
74
- ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_HEADER=[${tokenHeaderLocation}]`);
75
- response = await this.getResponse({
76
- url,
77
- headers: {
78
- [tokenHeaderLocation]: token
79
- },
80
- method
81
- }, ctx);
82
- break;
83
- case "query":
84
- const tokenQueryLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
85
- ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
86
- response = await this.getResponse({
87
- url,
88
- query: {
89
- [tokenQueryLocation]: token
90
- },
91
- method
92
- }, ctx);
93
- break;
94
- case "cookie":
95
- const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
96
- ctx.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
97
- response = await this.getResponse({
98
- url,
99
- method,
100
- headers: {
101
- Cookie: `${tokenCookieLocation}=${token}; Path=/; HttpOnly;`
102
- }
103
- }, ctx);
104
- break;
105
- default:
106
- throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header, query or cookie)`);
107
- }
108
- if (response) {
109
- const session = await this.decodeSession(response, token, ctx);
110
- if (!this.checkSession(session, ctx)) {
111
- ctx.logger.warn(`unauthorized token not valid [${token}]`);
112
- return null;
113
- } else {
114
- ctx.logger.trace("token [%s]authorized!", token);
115
-
116
- if (tokenVerifyLocation === "cookie" && response.headers["set-cookie"]) {
117
- const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(ctx);
118
- const cookies = response.headers["set-cookie"].map((c: any) => cookieParse(c)).filter((c: any) => c[tokenCookieLocation] !== undefined);
119
- if (cookies.length === 1) {
120
- const value = cookies[0][tokenCookieLocation];
121
- if (value) {
122
- session.token = value; // replace token because token update via set-cookie
123
- }
124
- }
125
- }
126
- return {
127
- token,
128
- ...session
129
- } as Session;
130
- }
131
- } else {
132
- ctx.logger.warn(`unauthorized token not valid [${token}]`);
133
- return null;
134
- }
135
- } catch (e: any) {
136
- throw new UnAuthorizedError(`Fail to authenticate token! error verifying [${token}] [${e.status}][${e.config ? e.config.url : ""}]`);
137
- }
138
- }
139
-
140
- /* eslint-disable @typescript-eslint/no-unused-vars */
141
- protected async getResponse(config: RequestOptions, ctx?: Context): Promise<RequestResponse> {
142
- return request(config);
143
- }
144
-
145
- /* eslint-disable @typescript-eslint/no-unused-vars */
146
- protected checkSession(session: NoTokenSession, ctx?: Context): boolean {
147
- parse(session, [
148
- {name: "username", required: true, type: "string"},
149
- {name: "account", required: true, type: "string"},
150
- {name: "groups", required: true, type: "array", arrayType: "string"}
151
- ], "add_extra", "session");
152
- return true;
153
- }
154
-
155
- /* eslint-disable @typescript-eslint/no-unused-vars */
156
- protected async decodeSession(response: RequestResponse, token: string, ctx?: Context): Promise<NoTokenSession> {
157
- const session = response.data;
158
- return session as NoTokenSession;
159
- }
160
- }
@@ -1,130 +0,0 @@
1
- import {URLSearchParams} from "url";
2
-
3
- export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
4
- const query: { [name: string]: string | string[] } = Object.create(null);
5
- search.forEach((value: string, key: string) => {
6
- query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
7
- });
8
- return query;
9
- }
10
-
11
- // adds "/" to the final of path
12
- // cannot account for query or hash params so send only new URL().pathname
13
- export function normalizePath(path: string): string {
14
- if (typeof path !== "string") {
15
- throw new Error("path not string");
16
- }
17
- if (path.length > 1) {
18
- if (path.charAt(0) !== "/") {
19
- throw new Error("path doesnt start with /");
20
- }
21
- if (path[path.length - 1] !== "/") {
22
- return `${path}/`;
23
- } else {
24
- return path; // already normalized
25
- }
26
- } else if (path !== "/") {
27
- throw new Error("path of length 1 not /");
28
- } else {
29
- return path; // "/"
30
- }
31
- }
32
-
33
- export interface PathParams {
34
- [name: string]: string | undefined
35
- }
36
-
37
- export interface PathPartToken extends PathPart {
38
- optional: boolean;
39
- wild?: string;
40
- }
41
-
42
- export interface PathPart {
43
- value: string;
44
- lower: string;
45
- }
46
-
47
- function pathPartTokenize(token: PathPart): PathPartToken {
48
- const isWild = token.value[0] === ":";
49
- const optional = token.value[token.value.length - 1] === "?";
50
- const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
51
- return {
52
- optional,
53
- wild,
54
- value: token.value,
55
- lower: token.lower
56
- }
57
- }
58
-
59
- export const splitPath = (path?: string): PathPart[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
60
- return {
61
- value: p,
62
- lower: p.toLocaleLowerCase()
63
- };
64
- });
65
-
66
- export function tokenizePath(path?: string): PathPartToken[] {
67
- if (path === undefined) {
68
- return [];
69
- }
70
- const tokens = splitPath(path).map(token => pathPartTokenize(token));
71
- for (let i = 0; i < tokens.length; i++) {
72
- if (tokens[i].optional && i != tokens.length - 1) {
73
- throw new Error("cannot set a path token as optional that's not the last one");
74
- }
75
- }
76
- return tokens;
77
- }
78
-
79
- export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartToken[], requestParts: PathPart[]): {
80
- match: boolean;
81
- params?: { [name: string]: string | undefined }
82
- } {
83
- for (let i = 0; i < pathTokens.length; i++) {
84
- if (pathTokens[i].optional && i != pathTokens.length - 1) {
85
- throw new Error("cannot set a path token as optional that's not the last one");
86
- }
87
- }
88
- const lastTokenIsOptional = pathTokens.length > 0 ? pathTokens[pathTokens.length - 1].optional : false;
89
- const couldBeUsingOptional = (lastTokenIsOptional &&
90
- (
91
- (!checkAsRouter && pathTokens.length - 1 === requestParts.length) ||
92
- (checkAsRouter && pathTokens.length - 1 <= requestParts.length)
93
- )
94
- );
95
-
96
- const params: { [name: string]: string | undefined } = Object.create(null);
97
-
98
- if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
99
- // similar count of tokens
100
- for (let i = 0; i < requestParts.length; i++) {
101
- const ctxToken = requestParts[i];
102
- if (checkAsRouter && i >= pathTokens.length) {
103
- break;
104
- }
105
-
106
- if (pathTokens[i].wild || ctxToken.lower === pathTokens[i].lower) {
107
- // check pass
108
- const wild = pathTokens[i].wild;
109
- if (wild) {
110
- params[wild] = ctxToken.value;
111
- }
112
- continue;
113
- }
114
-
115
- return {
116
- match: false,
117
- params: {}
118
- };
119
- }
120
- return {
121
- match: true,
122
- params
123
- };
124
- } else {
125
- return {
126
- match: false,
127
- params: {}
128
- };
129
- }
130
- }
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from "./app";
2
- export * from "./router";
3
- export * from "./static";
4
- export * from "./api-router";
5
- export * from "./common";
6
- export * from "./proxy";
7
- export * from "./middleware";