@miqro/core 1.2.5 → 1.3.4

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 (304) hide show
  1. package/README.md +34 -18
  2. package/dist/handler/api-handler.d.ts +16 -0
  3. package/dist/handler/api-handler.js +30 -5
  4. package/dist/handler/api-handler.js.map +1 -0
  5. package/dist/handler/api-router-utils.js +11 -2
  6. package/dist/handler/api-router-utils.js.map +1 -0
  7. package/dist/handler/api-router.d.ts +30 -2
  8. package/dist/handler/api-router.js +30 -0
  9. package/dist/handler/api-router.js.map +1 -0
  10. package/dist/handler/app.d.ts +1 -2
  11. package/dist/handler/app.js +96 -13
  12. package/dist/handler/app.js.map +1 -0
  13. package/dist/handler/common/context.d.ts +57 -0
  14. package/dist/handler/common/context.js +123 -0
  15. package/dist/handler/common/context.js.map +1 -0
  16. package/dist/handler/common/helpers.js +5 -0
  17. package/dist/handler/common/helpers.js.map +1 -0
  18. package/dist/handler/common/index.d.ts +2 -45
  19. package/dist/handler/common/index.js +13 -109
  20. package/dist/handler/common/index.js.map +1 -0
  21. package/dist/handler/common/router-utils.d.ts +26 -0
  22. package/dist/handler/common/router-utils.js +59 -0
  23. package/dist/handler/common/router-utils.js.map +1 -0
  24. package/dist/handler/{router.d.ts → common/router.d.ts} +7 -16
  25. package/dist/handler/common/router.js +76 -0
  26. package/dist/handler/common/router.js.map +1 -0
  27. package/dist/handler/common/tokenize-match.d.ts +18 -9
  28. package/dist/handler/common/tokenize-match.js +42 -30
  29. package/dist/handler/common/tokenize-match.js.map +1 -0
  30. package/dist/handler/feature-router.d.ts +1 -2
  31. package/dist/handler/feature-router.js +3 -2
  32. package/dist/handler/feature-router.js.map +1 -0
  33. package/dist/handler/index.d.ts +1 -5
  34. package/dist/handler/index.js +2 -5
  35. package/dist/handler/index.js.map +1 -0
  36. package/dist/{middleware → handler/middleware}/buffer.d.ts +1 -1
  37. package/dist/{middleware → handler/middleware}/buffer.js +3 -2
  38. package/dist/handler/middleware/buffer.js.map +1 -0
  39. package/dist/handler/middleware/cookie.d.ts +4 -0
  40. package/dist/handler/middleware/cookie.js +18 -0
  41. package/dist/handler/middleware/cookie.js.map +1 -0
  42. package/dist/{middleware → handler/middleware}/cors.d.ts +1 -1
  43. package/dist/{middleware → handler/middleware}/cors.js +10 -2
  44. package/dist/handler/middleware/cors.js.map +1 -0
  45. package/dist/{middleware → handler/middleware}/form.d.ts +1 -1
  46. package/dist/{middleware → handler/middleware}/form.js +8 -5
  47. package/dist/handler/middleware/form.js.map +1 -0
  48. package/dist/handler/middleware/group.d.ts +3 -0
  49. package/dist/handler/{group.js → middleware/group.js} +4 -2
  50. package/dist/handler/middleware/group.js.map +1 -0
  51. package/dist/handler/middleware/index.d.ts +13 -0
  52. package/dist/handler/middleware/index.js +64 -0
  53. package/dist/handler/middleware/index.js.map +1 -0
  54. package/dist/{middleware → handler/middleware}/json.d.ts +1 -1
  55. package/dist/{middleware → handler/middleware}/json.js +3 -2
  56. package/dist/handler/middleware/json.js.map +1 -0
  57. package/dist/{middleware → handler/middleware}/logger.d.ts +1 -1
  58. package/dist/{middleware → handler/middleware}/logger.js +1 -0
  59. package/dist/handler/middleware/logger.js.map +1 -0
  60. package/dist/handler/{parse.d.ts → middleware/parse.d.ts} +4 -3
  61. package/dist/handler/{parse.js → middleware/parse.js} +17 -7
  62. package/dist/handler/middleware/parse.js.map +1 -0
  63. package/dist/handler/middleware/session.d.ts +21 -0
  64. package/dist/handler/middleware/session.js +140 -0
  65. package/dist/handler/middleware/session.js.map +1 -0
  66. package/dist/handler/middleware/tag.d.ts +4 -0
  67. package/dist/handler/middleware/tag.js +14 -0
  68. package/dist/handler/middleware/tag.js.map +1 -0
  69. package/dist/{middleware → handler/middleware}/text.d.ts +1 -1
  70. package/dist/{middleware → handler/middleware}/text.js +3 -2
  71. package/dist/handler/middleware/text.js.map +1 -0
  72. package/dist/handler/proxy.js +5 -11
  73. package/dist/handler/proxy.js.map +1 -0
  74. package/dist/handler/{html.d.ts → response/html.d.ts} +1 -1
  75. package/dist/handler/{html.js → response/html.js} +1 -0
  76. package/dist/handler/response/html.js.map +1 -0
  77. package/dist/handler/response/index.d.ts +3 -0
  78. package/dist/{middleware → handler/response}/index.js +3 -7
  79. package/dist/handler/response/index.js.map +1 -0
  80. package/dist/handler/{response.d.ts → response/json.d.ts} +1 -1
  81. package/dist/handler/{response.js → response/json.js} +3 -2
  82. package/dist/handler/response/json.js.map +1 -0
  83. package/dist/handler/response/result.d.ts +4 -0
  84. package/dist/handler/{result.js → response/result.js} +8 -8
  85. package/dist/handler/response/result.js.map +1 -0
  86. package/dist/index.d.ts +0 -1
  87. package/dist/index.js +1 -1
  88. package/dist/index.js.map +1 -0
  89. package/dist/util/cli/index.js +3 -0
  90. package/dist/util/cli/index.js.map +1 -0
  91. package/dist/util/config/browser.js +3 -0
  92. package/dist/util/config/browser.js.map +1 -0
  93. package/dist/util/config/config.js +6 -1
  94. package/dist/util/config/config.js.map +1 -0
  95. package/dist/util/config/featuretoggle.js +1 -0
  96. package/dist/util/config/featuretoggle.js.map +1 -0
  97. package/dist/util/config/index.js +1 -0
  98. package/dist/util/config/index.js.map +1 -0
  99. package/dist/util/cookie/cookie.d.ts +50 -0
  100. package/dist/util/cookie/cookie.js +168 -0
  101. package/dist/util/cookie/cookie.js.map +1 -0
  102. package/dist/util/cookie/index.d.ts +16 -0
  103. package/dist/util/cookie/index.js +9 -0
  104. package/dist/util/cookie/index.js.map +1 -0
  105. package/dist/util/error/configfilenotfound.js +1 -0
  106. package/dist/util/error/configfilenotfound.js.map +1 -0
  107. package/dist/util/error/forbiddenerror.js +1 -0
  108. package/dist/util/error/forbiddenerror.js.map +1 -0
  109. package/dist/util/error/index.js +1 -0
  110. package/dist/util/error/index.js.map +1 -0
  111. package/dist/util/error/named.js +1 -0
  112. package/dist/util/error/named.js.map +1 -0
  113. package/dist/util/error/notfound.js +1 -0
  114. package/dist/util/error/notfound.js.map +1 -0
  115. package/dist/util/error/notimplemented.js +1 -0
  116. package/dist/util/error/notimplemented.js.map +1 -0
  117. package/dist/util/error/parsererror.js +1 -0
  118. package/dist/util/error/parsererror.js.map +1 -0
  119. package/dist/util/error/unauthorizederror.js +1 -0
  120. package/dist/util/error/unauthorizederror.js.map +1 -0
  121. package/dist/util/index.js +3 -0
  122. package/dist/util/index.js.map +1 -0
  123. package/dist/util/loader/index.js +1 -0
  124. package/dist/util/loader/index.js.map +1 -0
  125. package/dist/util/logger/common.js +1 -0
  126. package/dist/util/logger/common.js.map +1 -0
  127. package/dist/util/logger/factory.js +1 -0
  128. package/dist/util/logger/factory.js.map +1 -0
  129. package/dist/util/logger/formatter.js +1 -0
  130. package/dist/util/logger/formatter.js.map +1 -0
  131. package/dist/util/logger/index.js +1 -0
  132. package/dist/util/logger/index.js.map +1 -0
  133. package/dist/util/logger/logger.js +12 -2
  134. package/dist/util/logger/logger.js.map +1 -0
  135. package/dist/util/logger/transport.js +1 -0
  136. package/dist/util/logger/transport.js.map +1 -0
  137. package/dist/util/parser/common.d.ts +5 -5
  138. package/dist/util/parser/common.js +1 -0
  139. package/dist/util/parser/common.js.map +1 -0
  140. package/dist/util/parser/get.js +11 -1
  141. package/dist/util/parser/get.js.map +1 -0
  142. package/dist/util/parser/index.js +1 -0
  143. package/dist/util/parser/index.js.map +1 -0
  144. package/dist/util/parser/parser.d.ts +24 -3
  145. package/dist/util/parser/parser.js +46 -11
  146. package/dist/util/parser/parser.js.map +1 -0
  147. package/dist/util/parser/types/any.js +1 -0
  148. package/dist/util/parser/types/any.js.map +1 -0
  149. package/dist/util/parser/types/array.js +1 -0
  150. package/dist/util/parser/types/array.js.map +1 -0
  151. package/dist/util/parser/types/boolean.js +1 -0
  152. package/dist/util/parser/types/boolean.js.map +1 -0
  153. package/dist/util/parser/types/email.js +1 -0
  154. package/dist/util/parser/types/email.js.map +1 -0
  155. package/dist/util/parser/types/enum.js +1 -0
  156. package/dist/util/parser/types/enum.js.map +1 -0
  157. package/dist/util/parser/types/index.js +1 -0
  158. package/dist/util/parser/types/index.js.map +1 -0
  159. package/dist/util/parser/types/multiple.js +6 -2
  160. package/dist/util/parser/types/multiple.js.map +1 -0
  161. package/dist/util/parser/types/nested.js +1 -0
  162. package/dist/util/parser/types/nested.js.map +1 -0
  163. package/dist/util/parser/types/number.js +1 -0
  164. package/dist/util/parser/types/number.js.map +1 -0
  165. package/dist/util/parser/types/object.js +1 -0
  166. package/dist/util/parser/types/object.js.map +1 -0
  167. package/dist/util/parser/types/regex.js +1 -0
  168. package/dist/util/parser/types/regex.js.map +1 -0
  169. package/dist/util/parser/types/string.js +1 -0
  170. package/dist/util/parser/types/string.js.map +1 -0
  171. package/dist/util/parser/types/url.js +1 -0
  172. package/dist/util/parser/types/url.js.map +1 -0
  173. package/dist/util/request/common.d.ts +9 -0
  174. package/dist/util/request/common.js +101 -1
  175. package/dist/util/request/common.js.map +1 -0
  176. package/dist/util/request/index.js +143 -185
  177. package/dist/util/request/index.js.map +1 -0
  178. package/dist/util/session/common.d.ts +16 -0
  179. package/dist/util/session/common.js +49 -0
  180. package/dist/util/session/common.js.map +1 -0
  181. package/dist/util/session/index.d.ts +2 -16
  182. package/dist/util/session/index.js +13 -46
  183. package/dist/util/session/index.js.map +1 -0
  184. package/dist/util/session/service.d.ts +26 -0
  185. package/dist/util/session/service.js +143 -0
  186. package/dist/util/session/service.js.map +1 -0
  187. package/dist/util/test/app.js +5 -1
  188. package/dist/util/test/app.js.map +1 -0
  189. package/dist/util/test/common.js +1 -0
  190. package/dist/util/test/common.js.map +1 -0
  191. package/dist/util/test/index.js +1 -0
  192. package/dist/util/test/index.js.map +1 -0
  193. package/dist/util/uuid/index.d.ts +7 -0
  194. package/dist/util/uuid/index.js +8 -0
  195. package/dist/util/uuid/index.js.map +1 -0
  196. package/dist/util/uuid/regex.d.ts +2 -0
  197. package/dist/util/uuid/regex.js +5 -0
  198. package/dist/util/uuid/regex.js.map +1 -0
  199. package/dist/util/uuid/rng.d.ts +1 -0
  200. package/dist/util/uuid/rng.js +18 -0
  201. package/dist/util/uuid/rng.js.map +1 -0
  202. package/dist/util/uuid/stringify.d.ts +2 -0
  203. package/dist/util/uuid/stringify.js +50 -0
  204. package/dist/util/uuid/stringify.js.map +1 -0
  205. package/dist/util/uuid/v4.d.ts +5 -0
  206. package/dist/util/uuid/v4.js +27 -0
  207. package/dist/util/uuid/v4.js.map +1 -0
  208. package/dist/util/uuid/validate.d.ts +2 -0
  209. package/dist/util/uuid/validate.js +12 -0
  210. package/dist/util/uuid/validate.js.map +1 -0
  211. package/package.json +11 -13
  212. package/src/handler/api-handler.ts +56 -0
  213. package/src/handler/api-router-utils.ts +101 -0
  214. package/src/handler/api-router.ts +60 -0
  215. package/src/handler/app.ts +138 -0
  216. package/src/handler/common/context.ts +161 -0
  217. package/src/handler/common/helpers.ts +11 -0
  218. package/src/handler/common/index.ts +3 -0
  219. package/src/handler/common/router-utils.ts +67 -0
  220. package/src/handler/common/router.ts +70 -0
  221. package/src/handler/common/tokenize-match.ts +152 -0
  222. package/src/handler/feature-router.ts +90 -0
  223. package/src/handler/index.ts +8 -0
  224. package/src/handler/middleware/buffer.ts +79 -0
  225. package/src/handler/middleware/cookie.ts +19 -0
  226. package/src/handler/middleware/cors.ts +98 -0
  227. package/src/handler/middleware/form.ts +53 -0
  228. package/src/handler/middleware/group.ts +28 -0
  229. package/src/handler/middleware/index.ts +52 -0
  230. package/src/handler/middleware/json.ts +50 -0
  231. package/src/handler/middleware/logger.ts +18 -0
  232. package/src/handler/middleware/parse.ts +93 -0
  233. package/src/handler/middleware/session.ts +155 -0
  234. package/src/handler/middleware/tag.ts +15 -0
  235. package/src/handler/middleware/text.ts +40 -0
  236. package/src/handler/proxy.ts +44 -0
  237. package/src/handler/response/html.ts +36 -0
  238. package/src/handler/response/index.ts +3 -0
  239. package/src/handler/response/json.ts +19 -0
  240. package/src/handler/response/result.ts +40 -0
  241. package/src/index.ts +2 -0
  242. package/src/util/cli/index.ts +57 -0
  243. package/src/util/config/browser.ts +5 -0
  244. package/src/util/config/config.ts +93 -0
  245. package/src/util/config/featuretoggle.ts +6 -0
  246. package/src/util/config/index.ts +3 -0
  247. package/src/util/cookie/cookie.ts +207 -0
  248. package/src/util/cookie/index.ts +6 -0
  249. package/src/util/error/configfilenotfound.ts +8 -0
  250. package/src/util/error/forbiddenerror.ts +8 -0
  251. package/src/util/error/index.ts +6 -0
  252. package/src/util/error/named.ts +3 -0
  253. package/src/util/error/notfound.ts +8 -0
  254. package/src/util/error/notimplemented.ts +8 -0
  255. package/src/util/error/parsererror.ts +10 -0
  256. package/src/util/error/unauthorizederror.ts +8 -0
  257. package/src/util/index.ts +11 -0
  258. package/src/util/loader/index.ts +67 -0
  259. package/src/util/logger/common.ts +6 -0
  260. package/src/util/logger/factory.ts +45 -0
  261. package/src/util/logger/formatter.ts +9 -0
  262. package/src/util/logger/index.ts +6 -0
  263. package/src/util/logger/logger.ts +114 -0
  264. package/src/util/logger/transport.ts +69 -0
  265. package/src/util/parser/common.ts +81 -0
  266. package/src/util/parser/get.ts +42 -0
  267. package/src/util/parser/index.ts +6 -0
  268. package/src/util/parser/parser.ts +235 -0
  269. package/src/util/parser/types/any.ts +8 -0
  270. package/src/util/parser/types/array.ts +73 -0
  271. package/src/util/parser/types/boolean.ts +13 -0
  272. package/src/util/parser/types/email.ts +26 -0
  273. package/src/util/parser/types/enum.ts +29 -0
  274. package/src/util/parser/types/index.ts +12 -0
  275. package/src/util/parser/types/multiple.ts +36 -0
  276. package/src/util/parser/types/nested.ts +19 -0
  277. package/src/util/parser/types/number.ts +34 -0
  278. package/src/util/parser/types/object.ts +10 -0
  279. package/src/util/parser/types/regex.ts +17 -0
  280. package/src/util/parser/types/string.ts +23 -0
  281. package/src/util/parser/types/url.ts +35 -0
  282. package/src/util/request/common.ts +193 -0
  283. package/src/util/request/index.ts +230 -0
  284. package/src/util/session/common.ts +63 -0
  285. package/src/util/session/index.ts +2 -0
  286. package/src/util/session/service.ts +154 -0
  287. package/src/util/test/app.ts +44 -0
  288. package/src/util/test/common.ts +17 -0
  289. package/src/util/test/index.ts +2 -0
  290. package/src/util/uuid/index.ts +5 -0
  291. package/src/util/uuid/regex.ts +2 -0
  292. package/src/util/uuid/rng.ts +14 -0
  293. package/src/util/uuid/stringify.ts +53 -0
  294. package/src/util/uuid/v4.ts +30 -0
  295. package/src/util/uuid/validate.ts +8 -0
  296. package/tsconfig.json +32 -0
  297. package/dist/handler/common/response.d.ts +0 -13
  298. package/dist/handler/common/response.js +0 -54
  299. package/dist/handler/error.d.ts +0 -2
  300. package/dist/handler/error.js +0 -46
  301. package/dist/handler/group.d.ts +0 -3
  302. package/dist/handler/result.d.ts +0 -4
  303. package/dist/handler/router.js +0 -116
  304. package/dist/middleware/index.d.ts +0 -6
@@ -0,0 +1,93 @@
1
+ import { parse, Parser } from "../../util/parser";
2
+ import { ParseOptions } from "../../util/parser/common";
3
+ import { Context, Handler } from "../common";
4
+
5
+ export interface ParseRequestOptions {
6
+ headers?: ParseOptions | ParseOptions[];
7
+ query?: ParseOptions | false | ParseOptions[];
8
+ params?: ParseOptions | false | ParseOptions[];
9
+ body?: ParseOptions | false | ParseOptions[];
10
+ parser?: Parser;
11
+ }
12
+
13
+ const NO_OPTIONS: ParseOptions[] = [{
14
+ options: [],
15
+ mode: "no_extra"
16
+ }];
17
+
18
+ const ADD_EXTRA: ParseOptions[] = [{
19
+ options: [],
20
+ mode: "add_extra"
21
+ }];
22
+
23
+ const normalizeParseOptions = (option?: ParseOptions | false | ParseOptions[]): ParseOptions[] =>
24
+ option ? (option instanceof Array ? option : [option]) : (option === false ? NO_OPTIONS : ADD_EXTRA);
25
+
26
+ const parseRequestPart = (part: "query" | "body" | "params" | "headers", ctx: Context, option: ParseOptions[], parser?: Parser): void => {
27
+ const value = ctx[part] === undefined ? {} : ctx[part];
28
+ for (let i = 0; i < option.length; i++) {
29
+ const o = option[i];
30
+ try {
31
+ const parsed = (parser ? parser : { parse }).parse(`${part}`, value as any, o.options, o.mode, o.ignoreUndefined) as any;
32
+ ctx[part] = parsed;
33
+ ctx.logger.debug("req.%s parsed to [%o]", part, ctx[part]);
34
+ return;
35
+ } catch (e: any) {
36
+ if (i === option.length - 1) {
37
+ throw e;
38
+ } else {
39
+ continue;
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+
46
+ export const ParseRequest = (options: ParseRequestOptions): Handler<void> => {
47
+ const query = normalizeParseOptions(options.query);
48
+ const params = normalizeParseOptions(options.params);
49
+ const body = normalizeParseOptions(options.body);
50
+ const headers = normalizeParseOptions(options.headers);
51
+
52
+ return async (ctx: Context): Promise<void> => {
53
+ try {
54
+ try {
55
+ if (options.headers !== undefined) {
56
+ parseRequestPart("headers", ctx, headers, options.parser);
57
+ }
58
+ } catch (e) {
59
+ ctx.logger.error("error parsing headers %o", ctx.headers);
60
+ throw e;
61
+ }
62
+ try {
63
+ if (options.query !== undefined) {
64
+ parseRequestPart("query", ctx, query, options.parser);
65
+ }
66
+ } catch (e) {
67
+ ctx.logger.error("error parsing query %o", ctx.query);
68
+ throw e;
69
+ }
70
+
71
+ try {
72
+ if (options.params !== undefined) {
73
+ parseRequestPart("params", ctx, params, options.parser);
74
+ }
75
+ } catch (e) {
76
+ ctx.logger.error("error parsing params %o", ctx.params);
77
+ throw e;
78
+ }
79
+
80
+ try {
81
+ if (options.body !== undefined) {
82
+ parseRequestPart("body", ctx, body, options.parser);
83
+ }
84
+ } catch (e: any) {
85
+ ctx.logger.error("error parsing body %o", ctx.body);
86
+ throw e;
87
+ }
88
+ } catch (e: any) {
89
+ ctx.logger.warn("error parsing request: %s", e.message);
90
+ throw e;
91
+ }
92
+ }
93
+ };
@@ -0,0 +1,155 @@
1
+ import { parse } from "../../util/parser";
2
+ import { checkEnvVariables } from "../../util/config";
3
+ import { Session } from "../../util/session";
4
+ import { Context, Handler } from "../common";
5
+ import { ForbiddenError, UnAuthorizedError } from "../../util/error";
6
+
7
+ const DEFAULT_TOKEN_LOCATION = "header";
8
+ const DEFAULT_TOKEN_HEADER = "Authorization";
9
+ const DEFAULT_TOKEN_QUERY = "token";
10
+ const DEFAULT_TOKEN_COOKIE = "Authorization";
11
+ const DEFAULT_TOKEN_SET_COOKIE_HTTP_ONLY = "true";
12
+ const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
13
+ const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
14
+ const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
15
+
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
+ }
29
+ }
30
+ }
31
+
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
+ }
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
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;
88
+ }
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
+ }
151
+ }
152
+ };
153
+ };
154
+
155
+
@@ -0,0 +1,15 @@
1
+ import { Context, Handler } from "../common";
2
+
3
+ export const TagResponse = (options?: {
4
+ uuid?: boolean;
5
+ }): Handler<void> =>
6
+ async (ctx: Context): Promise<void> => {
7
+ if (options && options.uuid) {
8
+ ctx.setHeader("uuid", ctx.uuid);
9
+ }
10
+ const requestUUID = ctx.headers['request-uuid'];
11
+ if (requestUUID) {
12
+ ctx.setHeader("request-uuid", requestUUID);
13
+ }
14
+ };
15
+
@@ -0,0 +1,40 @@
1
+ import { Context, Handler } from "../common";
2
+ import { BadRequestError } from "../../util/error";
3
+ import { checkEnvVariables } from "../../util/config";
4
+ import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
5
+
6
+ export const TextParser = (options?: {
7
+ limit?: number;
8
+ type?: string;
9
+ }): Handler<void> => {
10
+ let limit = DEFAULT_READ_BUFFER_LIMIT;
11
+ let type = "plain/text";
12
+ if (options) {
13
+ limit = options.limit !== undefined ? options.limit : limit;
14
+ type = options.type !== undefined ? options.type : type;
15
+ } else {
16
+ const [limitS, typeS] =
17
+ checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "plain/text"]);
18
+ limit = parseInt(limitS, 10);
19
+ type = typeS;
20
+ }
21
+ return async (ctx: Context): Promise<void> => {
22
+ try {
23
+ const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
24
+ if (isType && ctx.buffer && ctx.buffer.length <= limit) {
25
+ const string = ctx.buffer.toString();
26
+ ctx.body = string;
27
+ } else if (isType && ctx.buffer && ctx.buffer.length > limit) {
28
+ ctx.logger.error(`ctx.buffer.length ${ctx.buffer.length} > ${limit}. To accept this body set BODY_TEXT_PARSER_LIMIT to a higher value.`);
29
+ throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
30
+ }
31
+ } catch (e: any) {
32
+ if (e && e.name === "ParseOptionsError") {
33
+ throw e;
34
+ } else {
35
+ ctx.logger.error(e);
36
+ throw new BadRequestError();
37
+ }
38
+ }
39
+ };
40
+ };
@@ -0,0 +1,44 @@
1
+ import { request, RequestOptions, RequestResponse } from "../util/request";
2
+ import { Context, Handler } from "./common";
3
+
4
+ export interface ProxyServiceInterface {
5
+ resolveRequest(ctx: Context): Promise<RequestOptions>;
6
+ }
7
+
8
+ export interface ProxyOptionsInterface {
9
+ proxyService: ProxyServiceInterface;
10
+ }
11
+
12
+ export const ProxyHandler = (options: ProxyOptionsInterface): Handler<RequestResponse> =>
13
+ async (ctx): Promise<RequestResponse> => {
14
+ const resolver = options.proxyService;
15
+ const requestConfig = await resolver.resolveRequest(ctx);
16
+ try {
17
+ ctx.logger.debug("proxy resolveRequest to [%o]", requestConfig);
18
+ const response = await request(requestConfig);
19
+ ctx.logger.trace("response %o", response);
20
+ return response;
21
+ } catch (e: any) {
22
+ ctx.logger.error("Error connecting to endpoint in [%s] [%s]", requestConfig.url, e.message);
23
+ if (e.status && e.headers && e.data) {
24
+ return e;
25
+ } else {
26
+ throw e;
27
+ }
28
+ }
29
+ }
30
+
31
+ export const ProxyResponseHandler = (): Handler<void> =>
32
+ async (ctx: Context): Promise<void> => {
33
+ if (!ctx.results || ctx.results.length === 0) {
34
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
35
+ } else {
36
+ const lastResult = ctx.results[ctx.results.length - 1];
37
+ ctx.logger.debug("response %o", lastResult);
38
+ await ctx.end({
39
+ headers: lastResult.headers,
40
+ body: lastResult.data,
41
+ status: lastResult.status
42
+ });
43
+ }
44
+ }
@@ -0,0 +1,36 @@
1
+ import { OutgoingHttpHeaders } from "http";
2
+ import { Context, Handler } from "../common";
3
+
4
+ export type HTMLResponseResult = string | { status?: number; headers?: OutgoingHttpHeaders, body?: string; template: (ctx: Context) => Promise<string>; }
5
+
6
+ export const HTMLResponseHandler = (): Handler<void> =>
7
+ async (ctx: Context): Promise<void> => {
8
+ const results = ctx.results;
9
+ const lastResult = results[results.length - 1];
10
+ ctx.logger.trace(`last result is [${lastResult}]`);
11
+ if (lastResult && typeof lastResult === "string" ||
12
+ (
13
+ (typeof lastResult.headers === "object" || lastResult.headers === undefined) &&
14
+ (typeof lastResult.status === "number" || lastResult.status === undefined) &&
15
+ (typeof lastResult.body === "string" || typeof lastResult.template === "function")
16
+ )
17
+ ) {
18
+ const status = typeof lastResult.status === "number" ? lastResult.status : 200;
19
+ const headers = typeof lastResult.headers === "object" ? lastResult.headers : {
20
+ "content-type": "text/html; charset=utf-8"
21
+ };
22
+ const toSend = lastResult.template ? await lastResult.template(ctx) : (typeof lastResult.body === "string" ? lastResult.body : lastResult);
23
+ if (typeof toSend === "string") {
24
+ ctx.logger.debug(`sending [${toSend}]`);
25
+ await ctx.end({
26
+ status,
27
+ headers,
28
+ body: toSend
29
+ });
30
+ } else {
31
+ throw new Error("html result from HTMLResponseResult not string so last result not valid");
32
+ }
33
+ } else {
34
+ throw new Error("html result from HTMLResponseResult not string so last result not valid");
35
+ }
36
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./html";
2
+ export * from "./json";
3
+ export * from "./result";
@@ -0,0 +1,19 @@
1
+ import { Context, Handler } from "../common";
2
+
3
+ export const ResponseHandler = (): Handler<void> =>
4
+ async (ctx: Context): Promise<void> => {
5
+ ctx.logger.trace("results [%o]", ctx.results);
6
+ if (!ctx.results || ctx.results.length === 0) {
7
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
8
+ } else {
9
+ const lastResult = ctx.results[ctx.results.length - 1];
10
+ ctx.logger.debug("response [%o]", lastResult);
11
+ if (lastResult !== undefined) {
12
+ await ctx.json(lastResult);
13
+ } else {
14
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
15
+ }
16
+ }
17
+ };
18
+
19
+
@@ -0,0 +1,40 @@
1
+ import { parse, Parser } from "../../util";
2
+ import { ParseOptions } from "../../util/parser/common";
3
+ import { Context, Handler } from "../common";
4
+
5
+ export const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> =>
6
+ async (ctx: Context): Promise<any> => {
7
+ if (!ctx.results || ctx.results.length === 0) {
8
+ ctx.logger.debug(`not parsing results`);
9
+ return undefined;
10
+ } else {
11
+ const index = ctx.results.length - 1;
12
+ const lastResult = ctx.results[index];
13
+ ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
14
+ try {
15
+ if (options instanceof Array) {
16
+ for (let i = 0; i < options.length; i++) {
17
+ const o = options[i];
18
+ try {
19
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
20
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
21
+ return mappedResults;
22
+ } catch (e) {
23
+ if (i === options.length - 1) {
24
+ throw e;
25
+ } else {
26
+ continue;
27
+ }
28
+ }
29
+ }
30
+ } else {
31
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
32
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
33
+ return mappedResults;
34
+ }
35
+ } catch (e) {
36
+ ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
37
+ throw e;
38
+ }
39
+ }
40
+ };
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./handler";
2
+ export * from "./util";
@@ -0,0 +1,57 @@
1
+ import { SimpleMap } from "../parser/common";
2
+ import { Logger } from "../logger";
3
+ import { Callback } from "../test";
4
+
5
+ // noinspection SpellCheckingInspection
6
+ const routeCMDModule = async (cmdArg: string | undefined, cmds: CMDMapType, logger: Logger | Console, exit = true): Promise<void> => {
7
+ if (!cmdArg) {
8
+ throw new Error("no command");
9
+ } else {
10
+ if (!cmds[cmdArg]) {
11
+ throw new Error("command " + cmdArg + " not found!");
12
+ } else {
13
+ try {
14
+ await cmds[cmdArg].cb();
15
+ } catch (e: any) {
16
+ if (e && e.message) {
17
+ logger.error(e);
18
+ }
19
+ if (exit) {
20
+ process.exit(1);
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+
27
+ // noinspection SpellCheckingInspection
28
+ export type CMDMapType = SimpleMap<{ cb: Callback<void> | Callback<Promise<void>>; description: string; section?: string; }>
29
+
30
+ export abstract class CLIUtil {
31
+ // noinspection SpellCheckingInspection
32
+ public static cliFlow(cmds: CMDMapType, usage: string, logger: Logger | Console, cmdArg = process.argv[2], exit = true): void {
33
+ const flow = async () => {
34
+ try {
35
+ await routeCMDModule(cmdArg, cmds, logger, exit);
36
+ } catch (e: any) {
37
+ if (e && e.message) {
38
+ logger.error(e.message);
39
+ }
40
+ logger.info(`${usage}`);
41
+ logger.info(`Available commands:`);
42
+ for (const cmd of Object.keys(cmds)) {
43
+ if (cmds[cmd].section) {
44
+ logger.info(`\n${cmds[cmd].section}\n`);
45
+ }
46
+ logger.info(`\t${cmd}\t${cmds[cmd].description}`);
47
+ }
48
+ if (exit) {
49
+ process.exit(1);
50
+ }
51
+ }
52
+ }
53
+ flow().catch((e) => {
54
+ logger.error(e);
55
+ });
56
+ }
57
+ }
@@ -0,0 +1,5 @@
1
+ export const isBrowser = (): boolean => {
2
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
3
+ // @ts-ignore
4
+ return typeof window !== "undefined";
5
+ }
@@ -0,0 +1,93 @@
1
+ import { resolve } from "path";
2
+
3
+ export type ConfigOutput = { [name: string]: string };
4
+
5
+ export abstract class ConfigPathResolver {
6
+
7
+ public static getSequelizeRCFilePath(): string {
8
+ return resolve(ConfigPathResolver.getBaseDirname(), `.sequelizerc`);
9
+ }
10
+
11
+ public static getConfigDirname(): string {
12
+ return resolve(ConfigPathResolver.getBaseDirname(), `config`, `${ConfigStore.getConfig("NODE_ENV", "development")}`);
13
+ }
14
+
15
+ public static getBaseDirname(): string {
16
+ const envVar = ConfigStore.getConfig("MIQRO_DIRNAME");
17
+ if (envVar) {
18
+ return envVar;
19
+ } else if (typeof process !== "undefined") {
20
+ return process.cwd();
21
+ } else {
22
+ return "";
23
+ }
24
+ }
25
+ }
26
+
27
+ export interface LoadConfigOut {
28
+ combined: ConfigOutput;
29
+ outputs: ConfigOutput[]
30
+ }
31
+
32
+ const memoryProvider: { [name: string]: string } = {};
33
+
34
+ const processEnvDefined = (typeof process !== "undefined" && typeof process.env !== "undefined");
35
+
36
+ export abstract class ConfigStore {
37
+
38
+ public static putConfig(key: string, value: string, useMemory = false): ConfigStore {
39
+ if (processEnvDefined && !useMemory) {
40
+ Object.defineProperty(process.env, key, {
41
+ value
42
+ }); // this is for webpack
43
+ } else {
44
+ // only put in memory if process.env is not detected
45
+ memoryProvider[key] = value;
46
+ }
47
+ return this;
48
+ }
49
+
50
+ public static clear(key: string, useMemory = false): ConfigStore {
51
+ if (processEnvDefined && !useMemory) {
52
+ delete process.env[key];
53
+ } else {
54
+ // only clear from memory if process.env is not detected
55
+ delete memoryProvider[key];
56
+ }
57
+ return this;
58
+ }
59
+
60
+ public static keys(useMemory = false): string[] {
61
+ if (processEnvDefined && !useMemory) {
62
+ return Object.keys(process.env);
63
+ } else {
64
+ // use memory if process.env is not detected
65
+ return Object.keys(memoryProvider);
66
+ }
67
+ }
68
+
69
+ public static getConfig(key: string, defaultValue?: string, useMemory = false): string | null {
70
+ if (processEnvDefined && !useMemory) {
71
+ return process.env[key] !== undefined ? process.env[key] as string : (defaultValue !== undefined ? defaultValue : null);
72
+ } else {
73
+ // use memory if process.env is not detected
74
+ return memoryProvider[key] !== undefined ? memoryProvider[key] : (defaultValue !== undefined ? defaultValue : null);
75
+ }
76
+ }
77
+ }
78
+ export const checkEnvVariables = (requiredEnvVariables: string[], defaults?: string[]): string[] => {
79
+ if (defaults && defaults.length !== requiredEnvVariables.length) {
80
+ throw new Error(`defaults cannot be a different length of requiredEnvVariables`);
81
+ }
82
+ return requiredEnvVariables.map((envName, index) => {
83
+ if (processEnvDefined && process.env[envName] === undefined && !defaults) {
84
+ throw new Error(`Env variable [${envName}!] not defined.`);
85
+ } else if (processEnvDefined && process.env[envName] === undefined && defaults) {
86
+ return defaults[index];
87
+ } else if (!processEnvDefined) {
88
+ throw new Error(`Env variable [${envName}!] not defined.`);
89
+ } else {
90
+ return process.env[envName] as string;
91
+ }
92
+ });
93
+ };
@@ -0,0 +1,6 @@
1
+ import { ConfigStore } from "./config";
2
+
3
+ export const isFeatureEnabled = (feature: string, defaults = true): boolean => {
4
+ const featureToggleName = `${feature.toUpperCase()}`;
5
+ return ConfigStore.getConfig(featureToggleName, String(defaults)) === "true"
6
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./browser";
2
+ export * from "./config";
3
+ export * from "./featuretoggle";