@miqro/core 1.5.15 → 1.5.18

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 (38) hide show
  1. package/dist/app-utils.d.ts +13 -0
  2. package/dist/app-utils.js +82 -0
  3. package/dist/app-utils.js.map +1 -0
  4. package/dist/app.js +6 -88
  5. package/dist/app.js.map +1 -1
  6. package/dist/common/api-router-utils.js +3 -0
  7. package/dist/common/api-router-utils.js.map +1 -1
  8. package/dist/common/config/config.js +12 -0
  9. package/dist/common/config/config.js.map +1 -1
  10. package/dist/common/config/loader.js +2 -2
  11. package/dist/common/config/loader.js.map +1 -1
  12. package/dist/common/context.js +6 -3
  13. package/dist/common/context.js.map +1 -1
  14. package/dist/common/router-handler.js +1 -1
  15. package/dist/common/router-handler.js.map +1 -1
  16. package/dist/common/session/service.js +4 -1
  17. package/dist/common/session/service.js.map +1 -1
  18. package/dist/common/tokenize-match.js +2 -2
  19. package/dist/common/tokenize-match.js.map +1 -1
  20. package/dist/router.js +3 -0
  21. package/dist/router.js.map +1 -1
  22. package/package.json +10 -10
  23. package/src/app-utils.ts +82 -0
  24. package/src/app-utils.unit.test.js +100 -0
  25. package/src/app.ts +4 -89
  26. package/src/app.unit.test.js +334 -0
  27. package/src/common/api-router-utils.ts +3 -0
  28. package/src/common/config/config.ts +12 -0
  29. package/src/common/config/loader.ts +2 -2
  30. package/src/common/context.ts +7 -3
  31. package/src/common/context.unit.test.js +286 -0
  32. package/src/common/router-handler.ts +1 -1
  33. package/src/common/session/service.ts +4 -1
  34. package/src/common/tokenize-match.ts +2 -2
  35. package/src/proxy.unit.test.js +157 -0
  36. package/src/router.ts +3 -0
  37. package/src/router.unit.test.js +397 -0
  38. package/src/setup-test.js +3 -1
@@ -34,8 +34,14 @@ const processEnvDefined = (typeof process !== "undefined" && typeof process.env
34
34
  export abstract class ConfigStore {
35
35
 
36
36
  public static putConfig(key: string, value: string): ConfigStore {
37
+ if (key === "__proto__" || key === "__prototype__") {
38
+ throw new Error("invalid key " + key);
39
+ }
37
40
  if (processEnvDefined) {
38
41
  Object.defineProperty(process.env, key, {
42
+ writable: true,
43
+ enumerable: true,
44
+ configurable: true,
39
45
  value
40
46
  }); // this is for webpack
41
47
  } else {
@@ -47,6 +53,9 @@ export abstract class ConfigStore {
47
53
  }
48
54
 
49
55
  public static clear(key: string): ConfigStore {
56
+ if (key === "__proto__" || key === "__prototype__") {
57
+ throw new Error("invalid key " + key);
58
+ }
50
59
  if (processEnvDefined) {
51
60
  delete process.env[key];
52
61
  } else {
@@ -75,6 +84,9 @@ export abstract class ConfigStore {
75
84
  }
76
85
 
77
86
  public static getConfig(key: string, defaultValue?: string): string | null {
87
+ if (key === "__proto__" || key === "__prototype__") {
88
+ throw new Error("invalid key " + key);
89
+ }
78
90
  if (processEnvDefined) {
79
91
  return process.env[key] !== undefined ? process.env[key] as string : (defaultValue !== undefined ? defaultValue : null);
80
92
  } else {
@@ -25,7 +25,7 @@ class ConfigFileNotFoundError extends Error {
25
25
  }
26
26
 
27
27
  export const loadConfigString = (envFileContent: string, combined?: ConfigOutput): ConfigOutput => {
28
- const ret: ConfigOutput = {};
28
+ const ret: ConfigOutput = Object.create(null);
29
29
  envFileContent.split("\n")
30
30
  .filter(value => value && value.length > 0 && value.substring(0, 1) !== "#")
31
31
  .forEach((line) => {
@@ -60,7 +60,7 @@ const MISSED_TO_RUNMIQRO_INIT = (configDirname: string): string => `no config lo
60
60
 
61
61
  export const loadConfig = (configDirname: string = ConfigPathResolver.getConfigDirname(), logger?: Logger): LoadConfigOut => {
62
62
  const outputs: ConfigOutput[] = [];
63
- const combined = {};
63
+ const combined = Object.create(null);
64
64
  if (existsSync(configDirname)) {
65
65
  const configFiles = readdirSync(configDirname);
66
66
  for (const configFile of configFiles) {
@@ -37,7 +37,7 @@ export class Context {
37
37
  public headers: IncomingHttpHeaders; // from this.req.headers
38
38
  public readonly cookies: { [name: string]: string }; // a middleware will fill this
39
39
  public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
40
- public params: { [name: string]: string | undefined } = {}; // the router will fill this
40
+ public params: { [name: string]: string | undefined }; // the router will fill this
41
41
  public buffer?: Buffer; // empty buffer. middleware must read it
42
42
  public readonly remoteAddress?: string;
43
43
  public body: any; // a middleware will fill this reading the buffer
@@ -48,10 +48,11 @@ export class Context {
48
48
  this.method = req.method ? req.method.toUpperCase() as string : "GET";
49
49
  this.path = normalizePath(this.url.pathname); // normalized path
50
50
  this.hash = this.url.hash;
51
+ this.params = Object.create(null);
51
52
  this.query = parseSearchParams(this.url.searchParams);
52
53
  //this.buffer = Buffer.from("");
53
54
  this.remoteAddress = req.socket.remoteAddress;
54
- this.cookies = {}; // a middleware will fill
55
+ this.cookies = Object.create(null); // a middleware will fill
55
56
  this.headers = req.headers;
56
57
  this.startMS = Date.now();
57
58
  this.results = []; // handlers will fill this
@@ -71,7 +72,7 @@ export class Context {
71
72
  const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
72
73
  const nV = value instanceof Array ? value.join(", ") : String(value);
73
74
  const newValue = current ? `${current}, ${nV}` : nV;
74
- return this.res.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
75
+ return this.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
75
76
  }
76
77
 
77
78
  public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
@@ -87,6 +88,9 @@ export class Context {
87
88
  status: number;
88
89
  headers: OutgoingHttpHeaders;
89
90
  }): Promise<void> {
91
+ if (this.res.headersSent) {
92
+ return Promise.reject(new Error("already ended"));
93
+ }
90
94
  return new Promise<void>((resolve, reject) => {
91
95
  try {
92
96
  if (this.res.headersSent) {
@@ -0,0 +1,286 @@
1
+ const {fake, requireMock} = require("@miqro/test");
2
+ const {resolve} = require("path");
3
+ const {format} = require("util");
4
+ const {strictEqual} = require("assert");
5
+ const {distPath} = require("../setup-test.js");
6
+ const {serialize} = require("cookie");
7
+
8
+ const testFilePath = resolve(distPath, "common", "context.js");
9
+
10
+ describe("context unit tests", () => {
11
+
12
+ const res = {
13
+ headersSent: false,
14
+ end: fake((body, cb) => {
15
+ res.headersSent = true
16
+ cb();
17
+ }),
18
+ setHeader: fake(() => {
19
+
20
+ }),
21
+ removeHeader: fake(() => {
22
+
23
+ })
24
+ };
25
+ const logger = "logger1";
26
+ const newURLRet = {
27
+ pathname: "pathname",
28
+ searchParams: "searchParams"
29
+ };
30
+ const parseSearchParamsRet = "parseSearchParamsRet";
31
+ const normalizePathRet = "normalizePathRet";
32
+ const newURL = fake(() => {
33
+ return newURLRet;
34
+ });
35
+ const normalizePath = fake(() => {
36
+ return normalizePathRet;
37
+ });
38
+ const parseSearchParams = fake(() => {
39
+ return parseSearchParamsRet;
40
+ });
41
+ const cookieSerializeRet = "cookieSerializeRet";
42
+ const cookieSerialize = fake(() => {
43
+ return cookieSerializeRet;
44
+ });
45
+
46
+ let Context;
47
+
48
+ before(() => {
49
+ res.headersSent = false;
50
+ cookieSerialize.reset();
51
+ res.end.reset();
52
+ res.setHeader.reset();
53
+ res.removeHeader.reset();
54
+ newURL.reset();
55
+ normalizePath.reset();
56
+ parseSearchParams.reset();
57
+ const lib = requireMock(testFilePath, {
58
+ "./logger": {},
59
+ "./session": {},
60
+ "http": {},
61
+ "./tokenize-match": {
62
+ normalizePath,
63
+ parseSearchParams
64
+ },
65
+ "url": {},
66
+ "./helpers": {
67
+ newURL
68
+ },
69
+ "cookie": {
70
+ serialize: cookieSerialize
71
+ },
72
+ }, distPath);
73
+ Context = lib.Context;
74
+ });
75
+
76
+ const uuid = "uuid1";
77
+ [{
78
+ req: {
79
+ url: "/url",
80
+ socket: {
81
+ remoteAddress: "remoteAddress"
82
+ },
83
+ headers: {
84
+ host: "fakeHost"
85
+ }
86
+ }
87
+ }, {
88
+ req: {
89
+ url: "/url",
90
+ method: "MeThoD",
91
+ socket: {
92
+ remoteAddress: "remoteAddress"
93
+ },
94
+ headers: {
95
+ host: "fakeHost"
96
+ }
97
+ }
98
+ }].forEach(({req}) => {
99
+
100
+ it(format("ctor req %o", req), async () => {
101
+ const context = new Context(uuid, req, res, logger);
102
+ strictEqual(context.uuid, uuid);
103
+ strictEqual(context.body, undefined);
104
+ strictEqual(res.removeHeader.callCount, 1);
105
+ strictEqual(res.removeHeader.callArgs[0][0], "Date");
106
+ strictEqual(context.req, req);
107
+ strictEqual(context.res, res);
108
+ strictEqual(context.query, parseSearchParamsRet);
109
+ strictEqual(cookieSerialize.callCount, 0);
110
+ strictEqual(parseSearchParams.callCount, 1);
111
+ strictEqual(parseSearchParams.callArgs[0][0], newURLRet.searchParams);
112
+ strictEqual(normalizePath.callCount, 1);
113
+ strictEqual(normalizePath.callArgs[0][0], newURLRet.pathname);
114
+ strictEqual(context.path, normalizePathRet);
115
+ strictEqual(context.method, req.method ? req.method.toUpperCase() : "GET");
116
+ strictEqual(context.logger, logger);
117
+ strictEqual(context.url, newURLRet);
118
+ strictEqual(newURL.callCount, 1);
119
+ strictEqual(newURL.callArgs[0][0], req.url);
120
+ strictEqual(newURL.callArgs[0][1], `http://${req.headers.host}`);
121
+ strictEqual(res.end.callCount, 0);
122
+ strictEqual(res.setHeader.callCount, 0);
123
+ });
124
+ });
125
+
126
+
127
+ it("this.setHeader alias for this.res.setHeader", () => {
128
+ const context = new Context(uuid, {
129
+ url: "/url",
130
+ method: "MeThoD",
131
+ socket: {
132
+ remoteAddress: "remoteAddress"
133
+ },
134
+ headers: {
135
+ host: "fakeHost"
136
+ }
137
+ }, res, logger);
138
+ context.setHeader("key", "value");
139
+ strictEqual(cookieSerialize.callCount, 0);
140
+ strictEqual(res.end.callCount, 0);
141
+ strictEqual(res.setHeader.callCount, 1);
142
+ strictEqual(res.setHeader.callArgs[0][0], "key");
143
+ strictEqual(res.setHeader.callArgs[0][1], "value");
144
+ });
145
+
146
+ it("this.close calls this.end", async () => {
147
+ const context = new Context(uuid, {
148
+ url: "/url",
149
+ method: "MeThoD",
150
+ socket: {
151
+ remoteAddress: "remoteAddress"
152
+ },
153
+ headers: {
154
+ host: "fakeHost"
155
+ }
156
+ }, res, logger);
157
+ context.end = fake(async () => {
158
+
159
+ });
160
+ await context.close();
161
+ strictEqual(cookieSerialize.callCount, 0);
162
+ strictEqual(res.end.callCount, 0);
163
+ strictEqual(res.setHeader.callCount, 0);
164
+ strictEqual(context.end.callCount, 1);
165
+ strictEqual(context.end.callArgs[0][0].status, 400);
166
+ strictEqual(context.end.callArgs[0][0].headers.connection, "close");
167
+ });
168
+
169
+ it("this.addVaryHeader", () => {
170
+ // TODO
171
+ });
172
+
173
+ it("this.setCookie alias for this.res.setHeader with cookie.serializer", async () => {
174
+ const context = new Context(uuid, {
175
+ url: "/url",
176
+ method: "MeThoD",
177
+ socket: {
178
+ remoteAddress: "remoteAddress"
179
+ },
180
+ headers: {
181
+ host: "fakeHost"
182
+ }
183
+ }, res, logger);
184
+ await context.setCookie("name", "value");
185
+ strictEqual(cookieSerialize.callCount, 1);
186
+ strictEqual(cookieSerialize.callArgs[0][0], "name");
187
+ strictEqual(cookieSerialize.callArgs[0][1], "value");
188
+ strictEqual(res.end.callCount, 0);
189
+ strictEqual(res.setHeader.callCount, 1);
190
+ strictEqual(res.setHeader.callArgs[0][0], "Set-Cookie");
191
+ strictEqual(res.setHeader.callArgs[0][1], cookieSerializeRet);
192
+ });
193
+
194
+ it("this.end with headers not sent", async () => {
195
+ const context = new Context(uuid, {
196
+ url: "/url",
197
+ method: "MeThoD",
198
+ socket: {
199
+ remoteAddress: "remoteAddress"
200
+ },
201
+ headers: {
202
+ host: "fakeHost"
203
+ }
204
+ }, res, logger);
205
+ res.headersSent = true;
206
+ try {
207
+ await context.end("end1");
208
+ strictEqual(false, true);
209
+ } catch (e) {
210
+ strictEqual(e.message, "already ended");
211
+ }
212
+ });
213
+
214
+ it("this.end with headers sent", async () => {
215
+ const context = new Context(uuid, {
216
+ url: "/url",
217
+ method: "MeThoD",
218
+ socket: {
219
+ remoteAddress: "remoteAddress"
220
+ },
221
+ headers: {
222
+ host: "fakeHost"
223
+ }
224
+ }, res, logger
225
+ );
226
+ const headers = {
227
+ key1: "value1",
228
+ key2: "value2"
229
+ };
230
+ const body = "body";
231
+ const status = "status";
232
+ await context.end({
233
+ headers,
234
+ body,
235
+ status
236
+ });
237
+ strictEqual(res.end.callCount, 1);
238
+ strictEqual(res.end.callArgs[0][0], body);
239
+ strictEqual(res.setHeader.callCount, 2);
240
+ strictEqual(res.setHeader.callArgs[0][0], "key1");
241
+ strictEqual(res.setHeader.callArgs[0][1], "value1");
242
+ strictEqual(res.setHeader.callArgs[1][0], "key2");
243
+ strictEqual(res.setHeader.callArgs[1][1], "value2");
244
+ });
245
+
246
+ [{status: "status"}, {status: undefined}].forEach(({status}) => {
247
+ [{headers: "headers"}, {status: undefined}].forEach(({headers}) => {
248
+ [{body: {attr1: "value2"}}].forEach(({body}) => {
249
+ it(format("this.json alias for this.end %o", {status, headers, body}), async () => {
250
+ const context = new Context(uuid, {
251
+ url: "/url",
252
+ method: "MeThoD",
253
+ socket: {
254
+ remoteAddress: "remoteAddress"
255
+ },
256
+ headers: {
257
+ host: "fakeHost"
258
+ }
259
+ }, res, logger);
260
+ context.end = fake(async () => {
261
+
262
+ });
263
+ await context.json(body, headers, status);
264
+ strictEqual(cookieSerialize.callCount, 0);
265
+ strictEqual(res.end.callCount, 0);
266
+ strictEqual(res.setHeader.callCount, 0);
267
+ strictEqual(context.end.callCount, 1);
268
+ strictEqual(context.end.callArgs[0][0].status, status ? status : 200);
269
+ });
270
+ });
271
+ });
272
+ });
273
+
274
+
275
+ it("this.text", () => {
276
+ // TODO
277
+ });
278
+
279
+ it("this.html", () => {
280
+ // TODO
281
+ });
282
+
283
+ it("this.redirect", () => {
284
+ // TODO
285
+ });
286
+ });
@@ -88,7 +88,7 @@ export class RouterHandler {
88
88
  router.getJSONDoc(doc, `${prePath}${nPath}`);
89
89
  } else if (this.options) {
90
90
  if (!doc[`${prePath}${nPath}`]) {
91
- doc[`${prePath}${nPath}`] = {};
91
+ doc[`${prePath}${nPath}`] = Object.create(null);
92
92
  }
93
93
  if (doc[`${prePath}${nPath}`][nMethod]) {
94
94
  throw new Error("cannot create doc routes override each other");
@@ -54,9 +54,12 @@ export class VerifyEndpointService implements VerifyTokenService {
54
54
  {name: "url", required: true, type: "string", stringMinLength: 1},
55
55
  {name: "method", required: true, type: "string", stringMinLength: 1},
56
56
  {name: "tokenLocation", required: true, type: "enum", enumValues: ["header", "query", "cookie"]},
57
- {name: "tokenLocationName", required: true, type: "any"}
57
+ {name: "tokenLocationName", required: true, type: "string"}
58
58
  ], "no_extra", "options") as any;
59
59
  }
60
+ if (this.options.tokenLocationName && (this.options.tokenLocationName === "__proto__" || this.options.tokenLocationName === "__prototype__")) {
61
+ throw new Error(`invalid tokenLocationName ${this.options.tokenLocationName}`);
62
+ }
60
63
  }
61
64
 
62
65
  public async verify({token, ctx}: { token: string; ctx: Context }): Promise<Session | null> {
@@ -1,7 +1,7 @@
1
1
  import {URLSearchParams} from "url";
2
2
 
3
3
  export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
4
- const query: { [name: string]: string | string[] } = {};
4
+ const query: { [name: string]: string | string[] } = Object.create(null);
5
5
  search.forEach((value: string, key: string) => {
6
6
  query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
7
7
  });
@@ -93,7 +93,7 @@ export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartTo
93
93
  )
94
94
  );
95
95
 
96
- const params: { [name: string]: string | undefined } = {};
96
+ const params: { [name: string]: string | undefined } = Object.create(null);
97
97
 
98
98
  if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
99
99
  // similar count of tokens
@@ -0,0 +1,157 @@
1
+ const {fake, requireMock} = require("@miqro/test");
2
+ const {resolve} = require("path");
3
+ const {strictEqual} = require("assert");
4
+ const {distPath, basePath} = require("./setup-test.js");
5
+
6
+ const testFilePath = resolve(distPath, "proxy.js");
7
+
8
+ describe("proxy unit tests", () => {
9
+ [{
10
+ fakeOptions: {
11
+ url: "http://localhost"
12
+ }
13
+ }, {
14
+ fakeOptions: {
15
+ url: "http://localhost",
16
+ rejectUnauthorized: true
17
+ }
18
+ }, {
19
+ fakeOptions: {
20
+ url: "http://localhost",
21
+ rejectUnauthorized: false
22
+ }
23
+ }].forEach(({fakeOptions}) => {
24
+ it("ctor with " + JSON.stringify(fakeOptions), async () => {
25
+ const routerCtr = fake(() => {
26
+
27
+ });
28
+
29
+ const normalizePathRet = "normalizePathRet";
30
+
31
+ const urlCtr = fake(() => {
32
+ return "fakePath";
33
+ });
34
+
35
+ class Router {
36
+ constructor(options) {
37
+ routerCtr(options);
38
+ }
39
+ }
40
+
41
+ class URL {
42
+ constructor(options) {
43
+ this.pathname = urlCtr(options);
44
+ }
45
+ }
46
+
47
+ const normalizePath = fake((args) => {
48
+ return normalizePathRet;
49
+ });
50
+
51
+ const {Proxy} = requireMock(testFilePath, {
52
+ "./common": {},
53
+ "@miqro/request": {},
54
+ "./router": {
55
+ Router
56
+ },
57
+ "./common/tokenize-match": {
58
+ normalizePath
59
+ },
60
+ "url": {
61
+ URL
62
+ },
63
+ }, basePath);
64
+ // console.dir(Object.keys(require.cache));
65
+ const router = Proxy(fakeOptions);
66
+ strictEqual(router.proxyURL.pathname, normalizePathRet);
67
+ strictEqual(router.rejectUnauthorized, fakeOptions.rejectUnauthorized);
68
+ strictEqual(router.proxyURL instanceof URL, true);
69
+ strictEqual(routerCtr.callCount, 1);
70
+ strictEqual(routerCtr.callArgs[0][0], fakeOptions);
71
+ strictEqual(urlCtr.callCount, 1);
72
+ strictEqual(urlCtr.callArgs[0][0], fakeOptions.url);
73
+ strictEqual(normalizePath.callCount, 1);
74
+ strictEqual(normalizePath.callArgs[0][0], "fakePath");
75
+ });
76
+
77
+ [{
78
+ context: {
79
+ path: "/",
80
+ res: {
81
+ headersSent: false
82
+ },
83
+ logger: {
84
+ info: fake(() => {
85
+
86
+ })
87
+ },
88
+ end: fake(()=>{
89
+
90
+ })
91
+ }
92
+ }].forEach(({context}) => {
93
+ it("this.run: super.run returns true with options " + JSON.stringify(fakeOptions) + " and context " + context.path, async () => {
94
+ const routerCtr = fake(() => {
95
+
96
+ });
97
+ const routerRun = fake(async () => {
98
+ return true;
99
+ });
100
+
101
+ const normalizePathRet = "normalizePathRet";
102
+
103
+ const urlCtr = fake(() => {
104
+ return "fakePath";
105
+ });
106
+
107
+ class Router {
108
+ constructor(options) {
109
+ routerCtr(options);
110
+ }
111
+
112
+ run() {
113
+ return routerRun(...arguments);
114
+ }
115
+ }
116
+
117
+ class URL {
118
+ constructor(options) {
119
+ this.pathname = urlCtr(options);
120
+ }
121
+ }
122
+
123
+ const normalizePath = fake((args) => {
124
+ return normalizePathRet;
125
+ });
126
+ const requestRet = {
127
+
128
+ };
129
+ const request = fake(async () => {
130
+ return requestRet;
131
+ });
132
+
133
+ const {Proxy} = requireMock(testFilePath, {
134
+ "./common": {},
135
+ "@miqro/request": {
136
+ request
137
+ },
138
+ "./router": {
139
+ Router
140
+ },
141
+ "./common/tokenize-match": {
142
+ normalizePath
143
+ },
144
+ "url": {
145
+ URL
146
+ },
147
+ }, basePath);
148
+ //console.dir(Object.keys(require.cache))
149
+ const router = Proxy(fakeOptions);
150
+ const ret = await router.run(context);
151
+ strictEqual(request.callCount, 1);
152
+ // TODO assert path
153
+ });
154
+ });
155
+ });
156
+
157
+ });
package/src/router.ts CHANGED
@@ -62,6 +62,9 @@ export class Router {
62
62
  public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
63
63
  const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
64
64
  for (const e of errorHandlers) {
65
+ if (typeof e !== "function") {
66
+ throw new Error(`errorHandler ${e} not a function!`);
67
+ }
65
68
  this.errorHandlers.push(e);
66
69
  }
67
70
  return this;