heimdall-api-platform 1.0.5 → 1.0.6

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 (95) hide show
  1. package/dist/clients/http-client.js +1 -0
  2. package/dist/commons-cache.js +1 -0
  3. package/dist/commons-const.js +1 -0
  4. package/dist/commons-elasticsearch.js +1 -0
  5. package/dist/commons-errors.js +1 -0
  6. package/dist/commons-opensearch.js +1 -0
  7. package/dist/commons-splunk.js +1 -0
  8. package/dist/commons-util.js +1 -0
  9. package/dist/default-routes-docs.js +1 -0
  10. package/dist/default-routes-pos.js +1 -0
  11. package/dist/default-routes-pre.js +1 -0
  12. package/dist/environment.js +1 -0
  13. package/dist/factory/api-gateway.js +1 -0
  14. package/dist/factory/client-factory.js +1 -0
  15. package/dist/factory/function-factory.js +1 -0
  16. package/dist/factory/operation-flow-factory.js +1 -0
  17. package/dist/factory/server-factory.js +1 -0
  18. package/dist/factory/transformation-function-factory.js +1 -0
  19. package/dist/handle-route.js +1 -0
  20. package/dist/index.js +2 -0
  21. package/dist/jwt-util.js +1 -0
  22. package/dist/license/license-service.js +1 -0
  23. package/dist/models/base-context.js +1 -0
  24. package/dist/models/elastic-index-data.js +1 -0
  25. package/dist/models/flow-context.js +1 -0
  26. package/dist/models/flow-indexed.js +1 -0
  27. package/dist/models/operation-function-indexed.js +1 -0
  28. package/dist/models/operation-function-transformation-indexed.js +1 -0
  29. package/dist/models/operation-http-indexed.js +1 -0
  30. package/dist/models/operation-mock-indexed.js +1 -0
  31. package/dist/models/route-context.js +1 -0
  32. package/dist/models/security-route.js +1 -0
  33. package/dist/models/service-context.js +1 -0
  34. package/dist/models/service-group.js +1 -0
  35. package/dist/models/service-route.js +1 -0
  36. package/dist/models/splunk-data.js +1 -0
  37. package/dist/operations/abstract-operation.js +1 -0
  38. package/dist/operations/function.js +1 -0
  39. package/dist/operations/http.js +1 -0
  40. package/dist/operations/mock.js +1 -0
  41. package/dist/operations/monitor-check.js +1 -0
  42. package/dist/orchestration-flow.js +1 -0
  43. package/dist/router.js +1 -0
  44. package/dist/security-validation.js +1 -0
  45. package/dist/services/server.js +1 -0
  46. package/dist/services/template-monitorcheck-route.js +1 -0
  47. package/package.json +4 -4
  48. package/lib/clients/http-client.js +0 -296
  49. package/lib/commons-cache.js +0 -185
  50. package/lib/commons-const.js +0 -203
  51. package/lib/commons-elasticsearch.js +0 -49
  52. package/lib/commons-errors.js +0 -278
  53. package/lib/commons-opensearch.js +0 -37
  54. package/lib/commons-splunk.js +0 -105
  55. package/lib/commons-util.js +0 -669
  56. package/lib/default-routes-docs.js +0 -141
  57. package/lib/default-routes-pos.js +0 -111
  58. package/lib/default-routes-pre.js +0 -151
  59. package/lib/environment.js +0 -81
  60. package/lib/factory/api-gateway.js +0 -12
  61. package/lib/factory/client-factory.js +0 -41
  62. package/lib/factory/function-factory.js +0 -40
  63. package/lib/factory/operation-flow-factory.js +0 -64
  64. package/lib/factory/server-factory.js +0 -15
  65. package/lib/factory/transformation-function-factory.js +0 -47
  66. package/lib/handle-route.js +0 -472
  67. package/lib/index.js +0 -50
  68. package/lib/jwt-util.js +0 -38
  69. package/lib/license/license-service.js +0 -27
  70. package/lib/models/base-context.js +0 -77
  71. package/lib/models/elastic-index-data.js +0 -76
  72. package/lib/models/flow-context.js +0 -58
  73. package/lib/models/flow-indexed.js +0 -62
  74. package/lib/models/operation-function-indexed.js +0 -22
  75. package/lib/models/operation-function-transformation-indexed.js +0 -23
  76. package/lib/models/operation-http-indexed.js +0 -38
  77. package/lib/models/operation-mock-indexed.js +0 -22
  78. package/lib/models/route-context.js +0 -69
  79. package/lib/models/security-route.js +0 -41
  80. package/lib/models/service-context.js +0 -65
  81. package/lib/models/service-group.js +0 -15
  82. package/lib/models/service-route.js +0 -23
  83. package/lib/models/splunk-data.js +0 -70
  84. package/lib/operations/abstract-operation.js +0 -73
  85. package/lib/operations/function.js +0 -143
  86. package/lib/operations/http.js +0 -286
  87. package/lib/operations/mock.js +0 -34
  88. package/lib/operations/monitor-check.js +0 -151
  89. package/lib/orchestration-flow.js +0 -323
  90. package/lib/public/redoc.html +0 -152
  91. package/lib/public/swagger.html +0 -143
  92. package/lib/router.js +0 -29
  93. package/lib/security-validation.js +0 -46
  94. package/lib/services/server.js +0 -211
  95. package/lib/services/template-monitorcheck-route.js +0 -61
@@ -1,47 +0,0 @@
1
- "use strict";
2
-
3
- var Util = require("../commons-util");
4
- var Const = require("../commons-const");
5
- var Function = require("../operations/function");
6
- var BaseContext = require("../models/base-context");
7
- const { v4: uuidv4 } = require("uuid");
8
-
9
- class TransformationFunctionFactory {
10
- static create(name, context) {
11
- if (!name)
12
- return new FunctionDefault(
13
- {
14
- type: Const.FLOW_OPERATION_TYPE.FUNCTION,
15
- functionName: Const.NOT_IMPLEMENTED_FUNCTION,
16
- },
17
- context
18
- );
19
-
20
- Util.info(`stage=info method=TransformationFunctionFactory.create message=Created function name=${name}`);
21
-
22
- return new Function(
23
- {
24
- type: Const.FLOW_OPERATION_TYPE.FUNCTION,
25
- functionName: name,
26
- },
27
- context
28
- );
29
- }
30
- }
31
-
32
- class FunctionDefault extends BaseContext {
33
- constructor(options, context) {
34
- super(uuidv4(), context);
35
- this.type = options.type;
36
- this.name = options.functionName;
37
- }
38
-
39
- doExecuteFunction(options, context, callback) {
40
- callback(null, options);
41
- }
42
-
43
- doExecuteFunctionWithoutCallback(options, context) {}
44
- }
45
-
46
- module.exports = TransformationFunctionFactory;
47
- module.create = TransformationFunctionFactory.create;
@@ -1,472 +0,0 @@
1
- "use strict";
2
-
3
- const Util = require("./commons-util");
4
- const Const = require("./commons-const");
5
- const Env = require("./environment").application;
6
- const { ApiGatewayError, RequestTooManyRequests, CreateCustomError } = require("./commons-errors");
7
- const _ = require("underscore");
8
- const Step = require("step");
9
- const RouteContext = require("./models/route-context");
10
- const ValidateSecurity = require("./security-validation");
11
- const ElasticIndexData = require("./models/elastic-index-data");
12
- const Environment = require("./environment");
13
- const rateLimiter = require("redis-rate-limiter");
14
- const SplunkData = require("./models/splunk-data");
15
- const FunctionFactory = require("./factory/function-factory");
16
-
17
- const validContentTypes = [
18
- "multipart/form-data",
19
- "text/csv",
20
- "application/pdf",
21
- "application/msword",
22
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
23
- "application/vnd.ms-excel",
24
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
25
- "application/zip",
26
- "application/gzip",
27
- "application/octet-stream"
28
- ];
29
-
30
- class HandleRoute {
31
- constructor(orchestrator, serviceOptions, splunkProvider, openSearch) {
32
- if (!serviceOptions.flow) {
33
- throw ApiGatewayError("You must provide the flow to be executed.");
34
- }
35
-
36
- this.orchestrator = orchestrator;
37
- this._serviceOptions = serviceOptions;
38
- // this.elasticSearch = elasticSearch;
39
- this.splunkProvider = splunkProvider;
40
- this.openSearch = openSearch;
41
- this.redisClient = orchestrator.redisClient;
42
- this.enableRateLimit = serviceOptions.rateLimit ? true : false;
43
- this.rateLimit = serviceOptions.rateLimit;
44
- this.auditFunction = serviceOptions.auditFunction;
45
- }
46
-
47
- handleRequest(request, response, next) {
48
- let self = this;
49
-
50
- let context = new RouteContext(request, response, next, this._serviceOptions, this.orchestrator);
51
-
52
- Util.info("stage=init method=HandleRoute.handleRequest configuration", {
53
- method: context.service.method.toUpperCase(),
54
- service: context.service.name,
55
- url: context.request.url,
56
- uuid: context.uuid,
57
- body: Util.obfuscationJSON(context.body || {}),
58
- query: context.query,
59
- params: context.params,
60
- headers: Util.obfuscationJSON(context.headers || {}),
61
- });
62
-
63
- //Inicia Route Request
64
- context.init();
65
- context.service.setCurrentFlow(context.service.flow[0]);
66
-
67
- Step(
68
- function () {
69
- self.validateRateLimit(context, this);
70
- },
71
- //Valida se o Route tem segurança JWT
72
- //Todo: implementar funcao custom para validar autenticação
73
- function (error) {
74
- Util.throwErrorIfItExists(error);
75
- self.validateSecurity(context, this);
76
- },
77
- //Execute Flow
78
- function (error) {
79
- Util.throwErrorIfItExists(error);
80
- self.executeFlow(context, this);
81
- },
82
- function () {
83
- self.processResult(context);
84
- }
85
- );
86
- }
87
-
88
- indexRequest(context) {
89
-
90
- // if (this.elasticSearch.isEnabled()) {
91
-
92
- // this.elasticSearch.getInstance().index(
93
- // {
94
- // index: Environment.application.elasticSearch.indexName || Environment.application.appName,
95
- // id: context.uuid,
96
- // body: new ElasticIndexData(context),
97
- // },
98
- // (err, data) => {
99
- // //TENTATIVA DE INDEXAR NO ELASTICSEARCH
100
- // context.attemptsIndex++;
101
- // if (err) {
102
- // // console.log(err)
103
- // Util.error("stage=error method=HandleRoute.indexRequest message=Indexed Fail", {
104
- // uuid: context.uuid,
105
- // error: err,
106
- // });
107
- // //Retry Index
108
- // if (context.attemptsIndex < 10) {
109
- // Util.warning("stage=warn method=HandleRoute.indexRequest message=Retry Index", {
110
- // uuid: context.uuid,
111
- // retryIn: "30s x " + context.attemptsIndex,
112
- // attemptsIndex: context.attemptsIndex,
113
- // });
114
- // setTimeout(() => {
115
- // this.indexRequest(context);
116
- // }, 30000 * context.attemptsIndex);
117
- // }
118
- // } else {
119
- // Util.info("stage=info method=HandleRoute.indexRequest message=Indexed Successfully", {
120
- // uuid: context.uuid,
121
- // });
122
- // }
123
- // }
124
- // );
125
- // }
126
-
127
- if (this.splunkProvider.isEnabled()) {
128
- this.splunkProvider.sendEvent({
129
- event: {
130
- index: Environment.application.splunk.indexName || Environment.application.appName,
131
- type: "requests",
132
- id: context.uuid,
133
- body: new SplunkData(context),
134
- },
135
- });
136
- }
137
-
138
- if (this.openSearch.isEnabled()) {
139
- let indexNameOpenSearch = Environment.application.openSearch.indexName || Environment.application.appName;
140
-
141
- this.openSearch.getInstance().index(
142
- {
143
- index: indexNameOpenSearch,
144
- id: context.uuid,
145
- body: new ElasticIndexData(context),
146
- },
147
- (err, data) => {
148
- //TENTATIVA DE INDEXAR NO ELASTICSEARCH
149
- context.attemptsIndex++;
150
- if (err) {
151
- // console.log(err)
152
- Util.error(
153
- `stage=error method=HandleRoute.indexRequest indexName=${indexNameOpenSearch} provider=OpenSearch message=Indexed Fail requestId=${context.uuid
154
- } error=${JSON.stringify(err)}`
155
- );
156
- //Retry Index
157
- if (context.attemptsIndex < 10) {
158
- Util.warning(
159
- `stage=error method=HandleRoute.indexRequest indexName=${indexNameOpenSearch} provider=OpenSearch message=Retry Index requestId=${context.uuid} retryIn=30s x ${context.attemptsIndex} attemptsIndex=${context.attemptsIndex}`
160
- );
161
-
162
- setTimeout(() => {
163
- this.indexRequest(context);
164
- }, 30000 * context.attemptsIndex);
165
- }
166
- } else {
167
- Util.info(
168
- `stage=info method=HandleRoute.indexRequest indexName=${indexNameOpenSearch} provider=OpenSearch message=Indexed Successfully requestId=${context.uuid} indexId=${data.body._id}`
169
- );
170
- }
171
- }
172
- );
173
- }
174
- }
175
-
176
- validateSecurity(context, callback) {
177
- Step(
178
- function () {
179
- ValidateSecurity.execute(context, this);
180
- },
181
- function (error) {
182
- if (error) {
183
- context.statusCode = error.responseCode;
184
- context.error = true;
185
- context.setResult(error);
186
- }
187
- callback(error);
188
- }
189
- );
190
- }
191
-
192
- getCompileContext(context) {
193
- let customerToken = {
194
- name: "undefined",
195
- ownId: Util.generateKey(context.headers),
196
- document: "undefined",
197
- type: "undefined",
198
- phoneNumber: "undefined",
199
- };
200
-
201
- if (context.headers[Const.HEADERS.X_AUTHORIZATION]) {
202
- try {
203
- let authorizationBearer = context.headers[Const.HEADERS.X_AUTHORIZATION].replace("Bearer", "").trim();
204
- let customerTokenData = Util.tryParseJSON(Util.decodeBase64(authorizationBearer.split(".")[1]));
205
-
206
- if (Util.isJSONValid(customerTokenData)) {
207
- customerToken = {
208
- name: customerTokenData.nome,
209
- ownId: customerTokenData.ownid,
210
- document: customerTokenData.sub,
211
- type: customerTokenData.tipoToken,
212
- phoneNumber: customerTokenData.telefone,
213
- };
214
- }
215
- } catch (e) {
216
- Util.error(
217
- `stage=error method=HandleRoute.getCompileContext message=Error Get Compile Context error`,
218
- e
219
- );
220
- }
221
- }
222
-
223
- return _.extend(context, {
224
- env: Env,
225
- util: Util,
226
- customerToken: customerToken,
227
- });
228
- }
229
-
230
- compileRateLimitKey(context) {
231
- let compiled = _.template(
232
- `${context.service.name}-${this.rateLimit.key || context.headers["x-forwarded-for"]}`
233
- );
234
- let keyCompiled = compiled(this.getCompileContext(context));
235
-
236
- Util.info(
237
- `stage=error method=HandleRoute.compileRateLimitKey limitKey=${this.rateLimit.key} keyCompiled=${keyCompiled}`
238
- );
239
-
240
- return keyCompiled;
241
- }
242
-
243
- validateRateLimit(context, callback) {
244
-
245
- try {
246
-
247
- let key = this.rateLimit.hasOwnProperty("key");
248
- let rate = this.rateLimit.hasOwnProperty("rate");
249
-
250
- if (!this.redisClient.enableRedis || !key || !rate) {
251
- callback();
252
- return;
253
- }
254
-
255
- const limit = rateLimiter.create({
256
- redis: this.redisClient.writerClient,
257
- key: (context) => {
258
- return this.compileRateLimitKey(context);
259
- },
260
- rate: this.rateLimit.rate || Environment.application.requestPerSecond || "40/s", //DEFAULT
261
- });
262
-
263
- limit(context, (err, rate) => {
264
- if (err) {
265
- Util.error(
266
- `stage=error method=HandleRoute.validateRateLimit message=Rate Limit Validation Error`,
267
- err
268
- );
269
- callback();
270
- } else {
271
- Util.info("stage=info method=HandleRoute.validateRateLimit.limit", rate);
272
-
273
- if (rate.over) {
274
- Util.error(
275
- "stage=error method=HandleRoute.validateRateLimit.limit message=Rate Limit Info Over",
276
- rate
277
- );
278
-
279
- let error = new RequestTooManyRequests(
280
- "TOO_MANY_REQUESTS",
281
- new CreateCustomError("TOO_MANY_REQUESTS", "Too Many Requests")
282
- );
283
- context.service.addResult(error);
284
- context.setResult(error);
285
- context.statusCode = 429;
286
- context.error = true;
287
- callback(error);
288
- }
289
- callback();
290
- }
291
- });
292
- } catch (e) {
293
- Util.error(`stage=error method=HandleRoute.validateRateLimit message=Rate Limit Validation Error`, e);
294
- callback();
295
- }
296
- }
297
-
298
- executeFlow(context, callback) {
299
- Util.info(`stage=info method=HandleRoute.executeFlow message=Executing flow(s)`, {
300
- service: context.service.name,
301
- totalFlow: context.service.flow.length,
302
- contextUuid: context.uuid,
303
- });
304
-
305
- this.orchestrator.execute(context, callback);
306
- }
307
-
308
- generateHeadersDefault(context) {
309
- let headers = _.extend(
310
- {
311
- [Const.HEADERS.X_REQUEST_UUID_NAME]: context.uuid,
312
- [Const.HEADERS.X_REQUEST_SERVICE_NAME]: context.service.name,
313
- [Const.HEADERS.X_REQUEST_SERVICE_DESCRIPTION]: context.service.description,
314
- },
315
- context.service.responseHeaders
316
- );
317
-
318
- let contentType = headers[Const.HEADERS.CONTENT_TYPE] || this.resolveContextTypeResponse(context);
319
-
320
- headers[Const.HEADERS.CONTENT_TYPE] = contentType;
321
- headers[Const.HEADERS.X_REQUEST_DURATION_NAME] = context.timers.duration;
322
-
323
- //VERIFY COOKIES ON RESPONSE HEADERS FROM MICROSERVICES
324
- let responseCookie = context.service.headers[Const.HEADERS.SET_COOKIE.toLocaleLowerCase()] || {};
325
-
326
- //VERIFY AND CONCAT COOKIES ON RESPONSE HEADERS FROM GATEWAY
327
- const seTCookieOnRespHeaders =
328
- context.service.responseHeaders[Const.HEADERS.SET_COOKIE] ||
329
- context.service.responseHeaders[Const.HEADERS.SET_COOKIE.toLocaleLowerCase()];
330
-
331
- if (seTCookieOnRespHeaders) {
332
- if (Array.isArray(responseCookie) && responseCookie.length) {
333
- responseCookie = responseCookie.map((cookieLine) => (cookieLine += `; ${seTCookieOnRespHeaders}`));
334
- } else {
335
- responseCookie = [seTCookieOnRespHeaders];
336
- }
337
- }
338
-
339
- if (Util.nonNull(responseCookie)) {
340
- headers = _.extend(headers, {
341
- [Const.HEADERS.SET_COOKIE.toLocaleLowerCase()]: responseCookie,
342
- });
343
- }
344
-
345
- //VERIFY CONTENT TYPE FOR DOWNLOAD FILE ON RESPONSE HEADERS FROM MICROSERVICES
346
- if (validContentTypes.includes(headers[Const.HEADERS.CONTENT_TYPE]) ||
347
- validContentTypes.includes(headers[Const.HEADERS.CONTENT_TYPE.toLocaleLowerCase()])) {
348
-
349
- let responseContentDisposition =
350
- context.service.headers[Const.HEADERS.CONTENT_DISPOSITION.toLocaleLowerCase()] ||
351
- context.service.headers[Const.HEADERS.CONTENT_DISPOSITION] ||
352
- "Download_" + new Date().toDateString();
353
-
354
- headers = {
355
- ...headers,
356
- [Const.HEADERS.CONTENT_DISPOSITION.toLocaleLowerCase()]: responseContentDisposition,
357
- };
358
-
359
- }
360
-
361
- //Update Response Headers
362
- context.service.responseHeaders = headers;
363
-
364
- //NAO SETA HEADER PARA REDIRECTS E NO CONTENT PARA RESULTADOS VAZIOS
365
- if (!Util.isUrl(context.getResult())) {
366
- context.response.writeHead(
367
- Util.isEmpty(context.getResult()) ? Const.HTTP_STATUS.NO_CONTENT : context.statusCode,
368
- context.service.responseHeaders
369
- );
370
- }
371
- }
372
-
373
- resolveContextTypeResponse(context) {
374
- if (Buffer.isBuffer(context.getResult())) return Const.STREAM_CONTENT_TYPE_VALUE;
375
-
376
- if (context.getResult() !== null && typeof context.getResult() === "object")
377
- return Const.JSON_CONTENT_TYPE_VALUE;
378
-
379
- if (context.getResult() === "string") return Const.DEFAULT_CONTENT_TYPE_VALUE;
380
-
381
- return Const.DEFAULT_CONTENT_TYPE_VALUE;
382
- }
383
-
384
- resolveEndResponse(context) {
385
- //Libera resposta para o client no formato correto
386
- switch (context.getResult().constructor.name) {
387
- case Const.OBJECT_TYPE.READSTREAM: //STREAM FOR BIG FILES
388
- context.getResult().pipe(context.response);
389
- break;
390
- case Const.OBJECT_TYPE.PASSTHROUGH: //STREAM FOR BIG FILES
391
- context.getResult().pipe(context.response);
392
- break;
393
- case Const.OBJECT_TYPE.BUFFER: //BUFFER
394
- context.response.end(context.getResult());
395
- break;
396
- case Const.OBJECT_TYPE.OBJECT: //JSON
397
- context.response.end(Util.stringify(context.getResult()));
398
- break;
399
- case Const.OBJECT_TYPE.STRING: //STRING FOR HTML
400
- //VALIDA SE A RESPOSTA É UM URL VALIDA PARA REDIRECT
401
- if (Util.isUrl(context.getResult())) {
402
- context.response.redirect(302, context.getResult());
403
- } else {
404
- context.response.end(context.getResult());
405
- }
406
- break;
407
- default:
408
- context.response.end(Util.stringify(context.getResult()));
409
- }
410
- }
411
-
412
- releaseResponse(context) {
413
- //TODO: Verificar como ver se tem erro para adicionar informações adicionais
414
- if (context.error) {
415
- let responseError = Util.nonNull(context.service.currentFlow.result)
416
- ? context.service.currentFlow.result
417
- : context.service.result;
418
- let encapsuleError = context.service.currentFlow.operation.encapsuleError || true;
419
-
420
- if (encapsuleError) {
421
- context.setResult(
422
- _.extend(responseError || {}, {
423
- description: context.service.description,
424
- serviceName: context.service.name,
425
- requestId: context.uuid,
426
- })
427
- );
428
- } else {
429
- context.setResult(responseError);
430
- }
431
- }
432
-
433
- this.resolveEndResponse(context);
434
- }
435
-
436
- processResult(context) {
437
- this.handleResult(context);
438
- this.indexRequest(context);
439
- this.handleAudit(context);
440
- }
441
-
442
- handleResult(context) {
443
- //Finish Request
444
- context.end();
445
-
446
- this.generateHeadersDefault(context);
447
- this.releaseResponse(context);
448
-
449
- Util.info("stage=end method=HandleRoute.handleResult response", {
450
- method: context.service.method.toUpperCase(),
451
- service: context.service.name,
452
- route: context.request.url,
453
- uuid: context.uuid,
454
- body: Util.isJSONValid(context.getResult()) ? Util.obfuscationJSON(context.getResult()) : {},
455
- headers: context.service.responseHeaders,
456
- duration: context.timers.duration,
457
- });
458
- }
459
-
460
- handleAudit(context) {
461
- try {
462
- if (this.auditFunction) {
463
- let auditFunction = FunctionFactory.createFunctionByName(this.auditFunction);
464
- auditFunction.handle(context);
465
- }
466
- } catch (e) {
467
- Util.error(`stage=error method=HandleRoute.handleAudit message=Handle Audit Error`, e);
468
- }
469
- }
470
- }
471
-
472
- module.exports = HandleRoute;
package/lib/index.js DELETED
@@ -1,50 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict'
3
-
4
- require('dotenv').config()
5
-
6
- const APIGateway = require('./factory/api-gateway');
7
- const Environment = require('./environment');
8
- const Util = require('./commons-util');
9
- const JWTUtil = require('./jwt-util');
10
- const Errors = require('./commons-errors');
11
- const ClientFactory = require('./factory/client-factory');
12
- // const ElasticSearch = require('./commons-elasticsearch');
13
- const CommonsCache = require("./commons-cache");
14
- const Const = require('./commons-const');
15
- const ElasticIndexData = require('./models/elastic-index-data');
16
-
17
- if (process.env.NODE_ENV == 'production') {
18
- process.on('uncaughtException', function (err) {
19
- Util.error(`UncaughtException error=${Util.stringifyInfo(err)}`);
20
- console.error(err);
21
- });
22
- };
23
-
24
- process.on('SIGTERM', function () {
25
- Util.error(Util.format("Process %s was kill", process.pid));
26
- // some other closing procedures go here
27
- process.exit(0);
28
- });
29
-
30
- // Memory check:
31
- process.nextTick(function memory() {
32
- Util.warning(Util.format('Memory (Master): %s', Math.round(((process.memoryUsage().rss / 1024) / 1024)) + "MB"));
33
- var timeout = setTimeout(memory, Environment.application.memoryCheckInterval);
34
- });
35
-
36
- // Hook into commonJS module systems
37
- module.exports = {
38
- APIGateway: APIGateway,
39
- Environment: Environment,
40
- Const: Const,
41
- Util: Util,
42
- JWTUtil: JWTUtil,
43
- Errors: Errors,
44
- ClientFactory: ClientFactory,
45
- CommonsCache: CommonsCache,
46
- // ElasticSearch: ElasticSearch,
47
- Models: {
48
- ElasticIndexData: ElasticIndexData
49
- }
50
- };
package/lib/jwt-util.js DELETED
@@ -1,38 +0,0 @@
1
- 'use strict';
2
-
3
- var Util = require('./commons-util');
4
- var environment = require('./environment');
5
- var JWT = require('jsonwebtoken');
6
- var { CreateCustomError, Errors } = require('./commons-errors');
7
-
8
- function validateAccessToken(token, callback) {
9
-
10
- if (token) {
11
-
12
- JWT.verify(token, environment.application.security.secret, { algorithms: ['HS256'] }, function (err, decoded) {
13
- if (err) {
14
- Util.error(`Failed to authenticate token=${token}`, err);
15
- callback(Errors.handleSecurityError(err, null));
16
- } else {
17
- callback(null, decoded);
18
- }
19
- });
20
-
21
- } else {
22
- Util.error('Authentication token not informed.');
23
- callback(Errors.handleSecurityError(CreateCustomError('JsonWebTokenError', 'Authentication token not informed.')), null);
24
- }
25
- }
26
-
27
- function createAccessToken(payload) {
28
-
29
- var tokenJWT = JWT.sign(payload, environment.application.security.secret, {
30
- expiresIn: '365d' // 1 year
31
- });
32
-
33
- return tokenJWT;
34
-
35
- };
36
-
37
- exports.validateAccessToken = validateAccessToken;
38
- exports.createAccessToken = createAccessToken;
@@ -1,27 +0,0 @@
1
- // core/services/licenseService.js
2
- const axios = require("axios");
3
-
4
- const LICENSE_API_URL = "https://heimdall-api-platform.p4f.tech/app-key";
5
-
6
- module.exports = {
7
-
8
- async validate(appKey) {
9
-
10
- try {
11
-
12
- const response = await axios.get(`${LICENSE_API_URL}/${appKey}/validation`);
13
-
14
- if (response.status !== 200 || !response.data.active) {
15
- return null;
16
- }
17
-
18
- return response.data;
19
-
20
- } catch (err) {
21
- console.error("stage=error msg=License API validation failed", err.message);
22
- return null;
23
- }
24
-
25
- },
26
-
27
- };