@miqro/core 1.3.8 → 1.4.1

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 (117) hide show
  1. package/README.md +0 -18
  2. package/dist/handler/app.d.ts +1 -2
  3. package/dist/handler/app.js +2 -3
  4. package/dist/handler/app.js.map +1 -1
  5. package/dist/handler/common/context.d.ts +2 -10
  6. package/dist/handler/common/context.js +4 -4
  7. package/dist/handler/common/context.js.map +1 -1
  8. package/dist/handler/common/index.js.map +1 -1
  9. package/dist/handler/common/router-utils.js.map +1 -1
  10. package/dist/handler/middleware/cookie.js +2 -2
  11. package/dist/handler/middleware/cookie.js.map +1 -1
  12. package/dist/handler/middleware/form.js.map +1 -1
  13. package/dist/handler/middleware/index.js.map +1 -1
  14. package/dist/handler/middleware/json.js.map +1 -1
  15. package/dist/handler/middleware/session.js.map +1 -1
  16. package/dist/handler/middleware/text.js.map +1 -1
  17. package/dist/index.d.ts +0 -1
  18. package/dist/index.js +0 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/util/cli/index.d.ts +6 -1
  21. package/dist/util/cli/index.js +26 -0
  22. package/dist/util/cli/index.js.map +1 -1
  23. package/dist/util/error/configfilenotfound.js.map +1 -1
  24. package/dist/util/error/forbiddenerror.js.map +1 -1
  25. package/dist/util/error/notfound.js.map +1 -1
  26. package/dist/util/error/notimplemented.js.map +1 -1
  27. package/dist/util/error/parsererror.js.map +1 -1
  28. package/dist/util/error/unauthorizederror.js.map +1 -1
  29. package/dist/util/index.js +0 -2
  30. package/dist/util/index.js.map +1 -1
  31. package/dist/util/logger/formatter.js +1 -1
  32. package/dist/util/logger/formatter.js.map +1 -1
  33. package/dist/util/session/service.js +2 -2
  34. package/dist/util/session/service.js.map +1 -1
  35. package/package.json +12 -4
  36. package/src/handler/app.ts +2 -2
  37. package/src/handler/common/context.ts +5 -14
  38. package/src/handler/common/index.ts +1 -2
  39. package/src/handler/common/router-utils.ts +44 -51
  40. package/src/handler/middleware/cookie.ts +12 -12
  41. package/src/handler/middleware/form.ts +1 -1
  42. package/src/handler/middleware/index.ts +24 -24
  43. package/src/handler/middleware/json.ts +1 -1
  44. package/src/handler/middleware/session.ts +128 -128
  45. package/src/handler/middleware/text.ts +1 -1
  46. package/src/index.ts +0 -1
  47. package/src/util/cli/index.ts +25 -1
  48. package/src/util/error/configfilenotfound.ts +1 -1
  49. package/src/util/error/forbiddenerror.ts +1 -1
  50. package/src/util/error/notfound.ts +1 -1
  51. package/src/util/error/notimplemented.ts +1 -1
  52. package/src/util/error/parsererror.ts +1 -1
  53. package/src/util/error/unauthorizederror.ts +1 -1
  54. package/src/util/index.ts +0 -2
  55. package/src/util/logger/formatter.ts +1 -1
  56. package/src/util/parser/common.ts +1 -1
  57. package/src/util/parser/index.ts +0 -3
  58. package/src/util/request/index.ts +1 -1
  59. package/src/util/session/index.ts +1 -1
  60. package/src/util/session/service.ts +126 -126
  61. package/dist/test/common/app.d.ts +0 -3
  62. package/dist/test/common/app.js +0 -51
  63. package/dist/test/common/app.js.map +0 -1
  64. package/dist/test/common/common.d.ts +0 -6
  65. package/dist/test/common/common.js +0 -15
  66. package/dist/test/common/common.js.map +0 -1
  67. package/dist/test/common/index.d.ts +0 -3
  68. package/dist/test/common/index.js +0 -16
  69. package/dist/test/common/index.js.map +0 -1
  70. package/dist/test/common/runner.d.ts +0 -13
  71. package/dist/test/common/runner.js +0 -92
  72. package/dist/test/common/runner.js.map +0 -1
  73. package/dist/test/index.d.ts +0 -1
  74. package/dist/test/index.js +0 -14
  75. package/dist/test/index.js.map +0 -1
  76. package/dist/test/main.d.ts +0 -1
  77. package/dist/test/main.js +0 -19
  78. package/dist/test/main.js.map +0 -1
  79. package/dist/util/cookie/cookie.d.ts +0 -50
  80. package/dist/util/cookie/cookie.js +0 -168
  81. package/dist/util/cookie/cookie.js.map +0 -1
  82. package/dist/util/cookie/index.d.ts +0 -16
  83. package/dist/util/cookie/index.js +0 -9
  84. package/dist/util/cookie/index.js.map +0 -1
  85. package/dist/util/uuid/index.d.ts +0 -7
  86. package/dist/util/uuid/index.js +0 -8
  87. package/dist/util/uuid/index.js.map +0 -1
  88. package/dist/util/uuid/regex.d.ts +0 -2
  89. package/dist/util/uuid/regex.js +0 -5
  90. package/dist/util/uuid/regex.js.map +0 -1
  91. package/dist/util/uuid/rng.d.ts +0 -1
  92. package/dist/util/uuid/rng.js +0 -18
  93. package/dist/util/uuid/rng.js.map +0 -1
  94. package/dist/util/uuid/stringify.d.ts +0 -2
  95. package/dist/util/uuid/stringify.js +0 -50
  96. package/dist/util/uuid/stringify.js.map +0 -1
  97. package/dist/util/uuid/v4.d.ts +0 -5
  98. package/dist/util/uuid/v4.js +0 -27
  99. package/dist/util/uuid/v4.js.map +0 -1
  100. package/dist/util/uuid/validate.d.ts +0 -2
  101. package/dist/util/uuid/validate.js +0 -12
  102. package/dist/util/uuid/validate.js.map +0 -1
  103. package/src/test/common/app.ts +0 -45
  104. package/src/test/common/common.ts +0 -17
  105. package/src/test/common/index.ts +0 -3
  106. package/src/test/common/runner.ts +0 -97
  107. package/src/test/index.ts +0 -1
  108. package/src/test/main.ts +0 -17
  109. package/src/util/cookie/cookie.ts +0 -207
  110. package/src/util/cookie/index.ts +0 -6
  111. package/src/util/uuid/index.ts +0 -5
  112. package/src/util/uuid/regex.ts +0 -2
  113. package/src/util/uuid/rng.ts +0 -14
  114. package/src/util/uuid/stringify.ts +0 -53
  115. package/src/util/uuid/v4.ts +0 -30
  116. package/src/util/uuid/validate.ts +0 -8
  117. package/tsconfig-test.json +0 -13
@@ -5,8 +5,8 @@ import { normalizePath, parseSearchParams } from "./tokenize-match";
5
5
  import { URL } from "url";
6
6
  import { defaultLoggerFormatter } from "../../util/logger/formatter";
7
7
  import { newURL } from "./helpers";
8
- import { UUID } from "../../util/uuid";
9
- import { COOKIE } from "../../util/cookie";
8
+ import { v4 } from "uuid";
9
+ import { CookieSerializeOptions, serialize } from "cookie";
10
10
 
11
11
  export type Method = "get" | "post" | "put" | "delete" | "patch" | "options" | "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
12
12
 
@@ -46,7 +46,7 @@ export class Context {
46
46
  this.cookies = {}; // a middleware will fill
47
47
  this.headers = req.headers;
48
48
  this.startMS = Date.now();
49
- this.uuid = UUID.v4().toString("utf-8");
49
+ this.uuid = v4().toString();
50
50
  this.results = []; // handlers will fill this
51
51
  const pathToEnv = this.path.replace(/\//ig, "_").toUpperCase();
52
52
  const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${this.method.toUpperCase()}`;
@@ -83,17 +83,8 @@ export class Context {
83
83
  public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
84
84
  return this.res.setHeader(name, value);
85
85
  }
86
- public setCookie(name: string, value: string, options?: {
87
- encode?: (uriComponent: string | number | boolean) => string;
88
- maxAge?: number | null;
89
- domain?: string;
90
- httpOnly?: boolean;
91
- secure?: boolean;
92
- path?: string;
93
- expires?: Date;
94
- sameSite?: "lax" | "strict" | "none" | true;
95
- }): ServerResponse {
96
- return this.setHeader('Set-Cookie', COOKIE.serialize(name, String(value), options));
86
+ public setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse {
87
+ return this.setHeader('Set-Cookie', serialize(name, String(value), options));
97
88
  }
98
89
  public async end({ status, headers, body }: {
99
90
  body?: any;
@@ -1,3 +1,2 @@
1
-
2
1
  export * from "./router";
3
- export * from "./context";
2
+ export * from "./context";
@@ -8,62 +8,56 @@ import { SessionHandler, SessionHandlerOptions } from "../middleware/session";
8
8
  import { GroupPolicyHandler } from "../middleware/group";
9
9
  import { GroupPolicy } from "../../util/session";
10
10
 
11
- const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> =>
12
- async (ctx: Context): Promise<any> => {
13
- if (!ctx.results || ctx.results.length === 0) {
14
- ctx.logger.debug(`not parsing results`);
15
- return undefined;
16
- } else {
17
- const index = ctx.results.length - 1;
18
- const lastResult = ctx.results[index];
19
- ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
20
- try {
21
- if (options instanceof Array) {
22
- for (let i = 0; i < options.length; i++) {
23
- const o = options[i];
24
- try {
25
- const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
26
- ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
27
- return mappedResults;
28
- } catch (e) {
29
- if (i === options.length - 1) {
30
- throw e;
31
- } else {
32
- continue;
33
- }
11
+ const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> => async (ctx: Context): Promise<any> => {
12
+ if (!ctx.results || ctx.results.length === 0) {
13
+ ctx.logger.debug(`not parsing results`);
14
+ return undefined;
15
+ } else {
16
+ const index = ctx.results.length - 1;
17
+ const lastResult = ctx.results[index];
18
+ ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
19
+ try {
20
+ if (options instanceof Array) {
21
+ for (let i = 0; i < options.length; i++) {
22
+ const o = options[i];
23
+ try {
24
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
25
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
26
+ return mappedResults;
27
+ } catch (e) {
28
+ if (i === options.length - 1) {
29
+ throw e;
30
+ } else {
31
+ continue;
34
32
  }
35
33
  }
36
- } else {
37
- const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
38
- ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
39
- return mappedResults;
40
34
  }
41
- } catch (e) {
42
- ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
43
- throw e;
35
+ } else {
36
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
37
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
38
+ return mappedResults;
44
39
  }
40
+ } catch (e) {
41
+ ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
42
+ throw e;
45
43
  }
46
- };
47
-
48
-
49
- const ResponseHandler = (): Handler<void> =>
50
- async (ctx: Context): Promise<void> => {
51
- ctx.logger.trace("results [%o]", ctx.results);
52
- if (!ctx.results || ctx.results.length === 0) {
53
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
44
+ }
45
+ };
46
+
47
+ const ResponseHandler = (): Handler<void> => async (ctx: Context): Promise<void> => {
48
+ ctx.logger.trace("results [%o]", ctx.results);
49
+ if (!ctx.results || ctx.results.length === 0) {
50
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
51
+ } else {
52
+ const lastResult = ctx.results[ctx.results.length - 1];
53
+ ctx.logger.debug("response [%o]", lastResult);
54
+ if (lastResult !== undefined) {
55
+ await ctx.json(lastResult);
54
56
  } else {
55
- const lastResult = ctx.results[ctx.results.length - 1];
56
- ctx.logger.debug("response [%o]", lastResult);
57
- if (lastResult !== undefined) {
58
- await ctx.json(lastResult);
59
- } else {
60
- throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
61
- }
57
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
62
58
  }
63
- };
64
-
65
-
66
-
59
+ }
60
+ };
67
61
 
68
62
  export interface HandlerWithOptions extends RouterHandlerOptions {
69
63
  handler: Handler | Array<Handler>;
@@ -132,7 +126,6 @@ export class RouterHandler {
132
126
  throw new Error("bad arguments");
133
127
  }
134
128
 
135
-
136
129
  if (this.options && this.options.middleware) {
137
130
  handlers = handlers.concat(this.options.middleware);
138
131
  }
@@ -236,4 +229,4 @@ export class RouterHandler {
236
229
  }
237
230
  return true;
238
231
  }
239
- }
232
+ }
@@ -1,19 +1,19 @@
1
1
  import { Handler, Context } from "../common";
2
2
 
3
- import { COOKIE } from "../../util/cookie";
3
+ import { parse } from "cookie";
4
4
 
5
5
  export const CookieParser = (options?: {
6
- decode?(value: string): string;
6
+ decode?(value: string): string;
7
7
  }): Handler<void> => {
8
- return async (ctx: Context): Promise<void> => {
9
- const cookies = COOKIE.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
- };
8
+ return async (ctx: Context): Promise<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
+ };
18
18
  }
19
19
 
@@ -31,7 +31,7 @@ export const URLEncodedParser = (options?: {
31
31
  return async (ctx: Context): Promise<void> => {
32
32
  try {
33
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) {
34
+ if (isType && !ctx.buffer) {
35
35
  await readBuffer(ctx);
36
36
  }
37
37
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
@@ -22,27 +22,27 @@ export * from "./cookie";
22
22
  export { ReadBuffer } from "./buffer";
23
23
 
24
24
  export const middleware = (): Handler[] => {
25
- const ret: Handler[] = [];
26
- if (isFeatureEnabled("REQUEST_LOGGER", true)) {
27
- ret.push(LoggerHandler());
28
- }
29
- if (isFeatureEnabled("TAG_RESPONSE", false)) {
30
- ret.push(TagResponse());
31
- }
32
- if (isFeatureEnabled("CORS", false)) {
33
- ret.push(CORS());
34
- }
35
- if (isFeatureEnabled("COOKIE_PARSER", true)) {
36
- ret.push(CookieParser());
37
- }
38
- if (isFeatureEnabled("JSON_PARSER", true)) {
39
- ret.push(JSONParser());
40
- }
41
- if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
42
- ret.push(URLEncodedParser());
43
- }
44
- if (isFeatureEnabled("TEXT_PARSER", true)) {
45
- ret.push(TextParser());
46
- }
47
- return ret;
48
- };
25
+ const ret: Handler[] = [];
26
+ if (isFeatureEnabled("REQUEST_LOGGER", true)) {
27
+ ret.push(LoggerHandler());
28
+ }
29
+ if (isFeatureEnabled("TAG_RESPONSE", false)) {
30
+ ret.push(TagResponse());
31
+ }
32
+ if (isFeatureEnabled("CORS", false)) {
33
+ ret.push(CORS());
34
+ }
35
+ if (isFeatureEnabled("COOKIE_PARSER", true)) {
36
+ ret.push(CookieParser());
37
+ }
38
+ if (isFeatureEnabled("JSON_PARSER", true)) {
39
+ ret.push(JSONParser());
40
+ }
41
+ if (isFeatureEnabled("URL_ENCODED_PARSER", true)) {
42
+ ret.push(URLEncodedParser());
43
+ }
44
+ if (isFeatureEnabled("TEXT_PARSER", true)) {
45
+ ret.push(TextParser());
46
+ }
47
+ return ret;
48
+ };
@@ -28,7 +28,7 @@ export const JSONParser = (options?: {
28
28
  return async (ctx: Context): Promise<void> => {
29
29
  try {
30
30
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
31
- if(isType && !ctx.buffer) {
31
+ if (isType && !ctx.buffer) {
32
32
  await readBuffer(ctx);
33
33
  }
34
34
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
@@ -14,142 +14,142 @@ const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
14
14
  const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
15
15
 
16
16
  export interface SessionHandlerOptions {
17
- authService: {
18
- verify(args: { token: string; ctx: Context }): Promise<Session | null>;
19
- };
20
- options?: {
21
- tokenLocation: "header" | "query" | "cookie";
22
- tokenLocationName: string | ((ctx: Context) => Promise<string>);
23
- setCookieOptions?: {
24
- httpOnly: boolean;
25
- secure: boolean;
26
- path: string | ((ctx: Context) => Promise<string>);
27
- sameSite: "lax" | "strict" | "none";
28
- }
17
+ authService: {
18
+ verify(args: { token: string; ctx: Context }): Promise<Session | null>;
19
+ };
20
+ options?: {
21
+ tokenLocation: "header" | "query" | "cookie";
22
+ tokenLocationName: string | ((ctx: Context) => Promise<string>);
23
+ setCookieOptions?: {
24
+ httpOnly: boolean;
25
+ secure: boolean;
26
+ path: string | ((ctx: Context) => Promise<string>);
27
+ sameSite: "lax" | "strict" | "none";
29
28
  }
29
+ }
30
30
  }
31
31
 
32
32
  export const SessionHandler = (config: SessionHandlerOptions): Handler<void> => {
33
- if (!config.options) {
34
- const tokenLocation = checkEnvVariables(["TOKEN_LOCATION"], [DEFAULT_TOKEN_LOCATION])[0];
35
- config.options = {
36
- tokenLocation: tokenLocation as any,
37
- tokenLocationName: "",
38
- setCookieOptions: {
39
- httpOnly: true,
40
- path: "/",
41
- sameSite: "strict",
42
- secure: true
43
- }
33
+ if (!config.options) {
34
+ const tokenLocation = checkEnvVariables(["TOKEN_LOCATION"], [DEFAULT_TOKEN_LOCATION])[0];
35
+ config.options = {
36
+ tokenLocation: tokenLocation as any,
37
+ tokenLocationName: "",
38
+ setCookieOptions: {
39
+ httpOnly: true,
40
+ path: "/",
41
+ sameSite: "strict",
42
+ secure: true
43
+ }
44
+ };
45
+ switch (tokenLocation) {
46
+ case "header":
47
+ config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
48
+ break;
49
+ case "query":
50
+ config.options.tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
51
+ break;
52
+ case "cookie":
53
+ config.options.tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
54
+ const [httpOnlyS, secureS, path, sameSite] = checkEnvVariables(
55
+ ["TOKEN_SET_COOKIE_HTTP_ONLY", "TOKEN_SET_COOKIE_SECURE", "TOKEN_SET_COOKIE_PATH", "TOKEN_SET_COOKIE_SAME_SITE"],
56
+ [DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_SECURE, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE]);
57
+ config.options.setCookieOptions = {
58
+ httpOnly: httpOnlyS === "true",
59
+ secure: secureS === "true",
60
+ path,
61
+ sameSite: sameSite as any
44
62
  };
45
- switch (tokenLocation) {
46
- case "header":
47
- config.options.tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
48
- break;
49
- case "query":
50
- config.options.tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
51
- break;
52
- case "cookie":
53
- config.options.tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
54
- const [httpOnlyS, secureS, path, sameSite] = checkEnvVariables(
55
- ["TOKEN_SET_COOKIE_HTTP_ONLY", "TOKEN_SET_COOKIE_SECURE", "TOKEN_SET_COOKIE_PATH", "TOKEN_SET_COOKIE_SAME_SITE"],
56
- [DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY, DEFAULT_TOKEN_SET_COOKIE_SECURE, DEFAULT_TOKEN_SET_COOKIE_PATH, DEFAULT_TOKEN_SET_COOKIE_SAME_SITE]);
57
- config.options.setCookieOptions = {
58
- httpOnly: httpOnlyS === "true",
59
- secure: secureS === "true",
60
- path,
61
- sameSite: sameSite as any
62
- };
63
- break;
64
- default:
65
- throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
66
- }
67
- } else {
68
- config.options = parse("options", config.options as any, [
69
- { name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"] },
70
- { name: "tokenLocationName", required: true, type: "any" },
71
- {
72
- name: "setCookieOptions", required: false, type: "nested", defaultValue: {
73
- httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
74
- secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
75
- path: DEFAULT_TOKEN_SET_COOKIE_PATH,
76
- sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
77
- }, nestedOptions: {
78
- mode: "no_extra",
79
- options: [
80
- { name: "httpOnly", required: true, type: "boolean" },
81
- { name: "secure", required: true, type: "boolean" },
82
- { name: "path", required: true, type: "any" },
83
- { name: "sameSite", required: true, type: "enum", enumValues: ["lax", "strict", "none"] }
84
- ]
85
- }
86
- }
87
- ], "no_extra") as any;
63
+ break;
64
+ default:
65
+ throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header or query)`);
88
66
  }
67
+ } else {
68
+ config.options = parse("options", config.options as any, [
69
+ { name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"] },
70
+ { name: "tokenLocationName", required: true, type: "any" },
71
+ {
72
+ name: "setCookieOptions", required: false, type: "nested", defaultValue: {
73
+ httpOnly: DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY === "true",
74
+ secure: DEFAULT_TOKEN_SET_COOKIE_SECURE === "true",
75
+ path: DEFAULT_TOKEN_SET_COOKIE_PATH,
76
+ sameSite: DEFAULT_TOKEN_SET_COOKIE_SAME_SITE,
77
+ }, nestedOptions: {
78
+ mode: "no_extra",
79
+ options: [
80
+ { name: "httpOnly", required: true, type: "boolean" },
81
+ { name: "secure", required: true, type: "boolean" },
82
+ { name: "path", required: true, type: "any" },
83
+ { name: "sameSite", required: true, type: "enum", enumValues: ["lax", "strict", "none"] }
84
+ ]
85
+ }
86
+ }
87
+ ], "no_extra") as any;
88
+ }
89
89
 
90
- if (!config.authService) {
91
- throw new Error("authService must be provided!");
92
- }
93
- if (!config.options || !config.options.setCookieOptions) {
94
- throw new Error("config.options not populated!");
95
- }
96
- const tokenLocation = config.options.tokenLocation;
97
- const tokenLocationName = config.options.tokenLocationName;
98
- const setCookieOptions = config.options.setCookieOptions;
99
- return async (ctx: Context): Promise<void> => {
100
- try {
101
- const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(ctx);
102
- let token = null;
103
- switch (tokenLocation) {
104
- case "header":
105
- token = ctx.headers[(tlN).toLowerCase()] as string;
106
- break;
107
- case "query":
108
- token = ctx.query[tlN] as string;
109
- break;
110
- case "cookie":
111
- token = ctx.cookies[tlN] ? ctx.cookies[tlN] : undefined;
112
- break;
113
- default:
114
- throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
115
- }
116
- if (!token) {
117
- ctx.logger.warn("No token provided!");
118
- throw new ForbiddenError("NO TOKEN");
119
- } else {
120
- const session = await config.authService.verify({ token, ctx });
121
- if (!session) {
122
- ctx.logger.warn("fail to authenticate token [%s]!", token);
123
- throw new UnAuthorizedError();
124
- } else {
125
- if (tokenLocation === "cookie" && session.token !== token) {
126
- const newTokenCookie = String(session.token ? session.token : token);
127
- const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(ctx);
128
- ctx.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
129
- httpOnly: setCookieOptions.httpOnly,
130
- secure: setCookieOptions.secure,
131
- path: cookiePath,
132
- sameSite: setCookieOptions.sameSite,
133
- expires: session.expires
134
- } : {
135
- httpOnly: setCookieOptions.httpOnly,
136
- path: cookiePath,
137
- secure: setCookieOptions.secure,
138
- sameSite: setCookieOptions.sameSite
139
- })
140
- }
141
- ctx.session = session;
142
- ctx.logger.debug("authenticated!");
143
- }
144
- }
145
- } catch (e: any) {
146
- if (e.message && e.message === "NO TOKEN") {
147
- throw e;
148
- } else {
149
- throw new UnAuthorizedError();
150
- }
90
+ if (!config.authService) {
91
+ throw new Error("authService must be provided!");
92
+ }
93
+ if (!config.options || !config.options.setCookieOptions) {
94
+ throw new Error("config.options not populated!");
95
+ }
96
+ const tokenLocation = config.options.tokenLocation;
97
+ const tokenLocationName = config.options.tokenLocationName;
98
+ const setCookieOptions = config.options.setCookieOptions;
99
+ return async (ctx: Context): Promise<void> => {
100
+ try {
101
+ const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(ctx);
102
+ let token = null;
103
+ switch (tokenLocation) {
104
+ case "header":
105
+ token = ctx.headers[(tlN).toLowerCase()] as string;
106
+ break;
107
+ case "query":
108
+ token = ctx.query[tlN] as string;
109
+ break;
110
+ case "cookie":
111
+ token = ctx.cookies[tlN] ? ctx.cookies[tlN] : undefined;
112
+ break;
113
+ default:
114
+ throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
115
+ }
116
+ if (!token) {
117
+ ctx.logger.warn("No token provided!");
118
+ throw new ForbiddenError("NO TOKEN");
119
+ } else {
120
+ const session = await config.authService.verify({ token, ctx });
121
+ if (!session) {
122
+ ctx.logger.warn("fail to authenticate token [%s]!", token);
123
+ throw new UnAuthorizedError();
124
+ } else {
125
+ if (tokenLocation === "cookie" && session.token !== token) {
126
+ const newTokenCookie = String(session.token ? session.token : token);
127
+ const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(ctx);
128
+ ctx.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
129
+ httpOnly: setCookieOptions.httpOnly,
130
+ secure: setCookieOptions.secure,
131
+ path: cookiePath,
132
+ sameSite: setCookieOptions.sameSite,
133
+ expires: session.expires
134
+ } : {
135
+ httpOnly: setCookieOptions.httpOnly,
136
+ path: cookiePath,
137
+ secure: setCookieOptions.secure,
138
+ sameSite: setCookieOptions.sameSite
139
+ })
140
+ }
141
+ ctx.session = session;
142
+ ctx.logger.debug("authenticated!");
151
143
  }
152
- };
144
+ }
145
+ } catch (e: any) {
146
+ if (e.message && e.message === "NO TOKEN") {
147
+ throw e;
148
+ } else {
149
+ throw new UnAuthorizedError();
150
+ }
151
+ }
152
+ };
153
153
  };
154
154
 
155
155
 
@@ -25,7 +25,7 @@ export const TextParser = (options?: {
25
25
  return async (ctx: Context): Promise<void> => {
26
26
  try {
27
27
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
28
- if(isType && !ctx.buffer) {
28
+ if (isType && !ctx.buffer) {
29
29
  await readBuffer(ctx);
30
30
  }
31
31
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
package/src/index.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from "./handler";
2
2
  export * from "./util";
3
- export * from "./test";
@@ -1,6 +1,7 @@
1
1
  import { SimpleMap } from "../parser/common";
2
2
  import { Logger } from "../logger";
3
- import { Callback } from "../../test/common";
3
+
4
+ type Callback<T = any> = (...args: any[]) => T;
4
5
 
5
6
  // noinspection SpellCheckingInspection
6
7
  const routeCMDModule = async (cmdArg: string | undefined, cmds: CMDMapType, logger: Logger | Console, exit = true): Promise<void> => {
@@ -28,6 +29,29 @@ const routeCMDModule = async (cmdArg: string | undefined, cmds: CMDMapType, logg
28
29
  export type CMDMapType = SimpleMap<{ cb: Callback<void> | Callback<Promise<void>>; description: string; section?: string; }>
29
30
 
30
31
  export abstract class CLIUtil {
32
+ public static extractFlags(args: string[]): { flags: SimpleMap<string | string[]>; cmds: string[]; } {
33
+ const flags: SimpleMap<string | string[]> = {};
34
+ const cmds: string[] = [];
35
+ for (let i = 0; i < args.length; i++) {
36
+ const arg = args[i];
37
+ if (arg.indexOf("-") === 0) {
38
+ const argName = arg.substring(arg.indexOf("--") === 0 ? 2 : 1);
39
+ const argValue = args.length > i + 1 && args[i + 1] && args[i + 1].indexOf("-") != 0 ? args[i + 1] : "";
40
+ const flag = flags[argName];
41
+ if (flag instanceof Array) {
42
+ flag.push(argValue);
43
+ } else if (flag) {
44
+ flags[argName] = [flag, argValue];
45
+ } else {
46
+ flags[argName] = argValue;
47
+ }
48
+ i++;
49
+ } else {
50
+ cmds.push(arg);
51
+ }
52
+ }
53
+ return { flags, cmds };
54
+ }
31
55
  // noinspection SpellCheckingInspection
32
56
  public static cliFlow(cmds: CMDMapType, usage: string, logger: Logger | Console, cmdArg = process.argv[2], exit = true): void {
33
57
  const flow = async () => {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class ConfigFileNotFoundError extends NamedError {
4
4
  constructor(message = "NOT FOUND") {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class ForbiddenError extends NamedError {
4
4
  constructor(message = "FORBIDDEN") {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class NotFoundError extends NamedError {
4
4
  constructor(message = "NOT FOUND") {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class MethodNotImplementedError extends NamedError {
4
4
  constructor(message = "NOT IMPLEMENTED") {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class ParseOptionsError extends NamedError {
4
4
  constructor(message = "BAD REQUEST", public argAttr?: string) {
@@ -1,4 +1,4 @@
1
- import {NamedError} from "./named";
1
+ import { NamedError } from "./named";
2
2
 
3
3
  export class UnAuthorizedError extends NamedError {
4
4
  constructor(message = "UNAUTHORIZED") {
package/src/util/index.ts CHANGED
@@ -6,5 +6,3 @@ export * from "./config";
6
6
  export * from "./logger";
7
7
  export * from "./session";
8
8
  export * from "./loader";
9
- //export * from "./uuid";
10
- //export * from "./cookie";