heimdall-api-platform 1.0.4 → 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.
- package/dist/clients/http-client.js +1 -0
- package/dist/commons-cache.js +1 -0
- package/dist/commons-const.js +1 -0
- package/dist/commons-elasticsearch.js +1 -0
- package/dist/commons-errors.js +1 -0
- package/dist/commons-opensearch.js +1 -0
- package/dist/commons-splunk.js +1 -0
- package/dist/commons-util.js +1 -0
- package/dist/default-routes-docs.js +1 -0
- package/dist/default-routes-pos.js +1 -0
- package/dist/default-routes-pre.js +1 -0
- package/dist/environment.js +1 -0
- package/dist/factory/api-gateway.js +1 -0
- package/dist/factory/client-factory.js +1 -0
- package/dist/factory/function-factory.js +1 -0
- package/dist/factory/operation-flow-factory.js +1 -0
- package/dist/factory/server-factory.js +1 -0
- package/dist/factory/transformation-function-factory.js +1 -0
- package/dist/handle-route.js +1 -0
- package/dist/index.js +2 -0
- package/dist/jwt-util.js +1 -0
- package/dist/license/license-service.js +1 -0
- package/dist/models/base-context.js +1 -0
- package/dist/models/elastic-index-data.js +1 -0
- package/dist/models/flow-context.js +1 -0
- package/dist/models/flow-indexed.js +1 -0
- package/dist/models/operation-function-indexed.js +1 -0
- package/dist/models/operation-function-transformation-indexed.js +1 -0
- package/dist/models/operation-http-indexed.js +1 -0
- package/dist/models/operation-mock-indexed.js +1 -0
- package/dist/models/route-context.js +1 -0
- package/dist/models/security-route.js +1 -0
- package/dist/models/service-context.js +1 -0
- package/dist/models/service-group.js +1 -0
- package/dist/models/service-route.js +1 -0
- package/dist/models/splunk-data.js +1 -0
- package/dist/operations/abstract-operation.js +1 -0
- package/dist/operations/function.js +1 -0
- package/dist/operations/http.js +1 -0
- package/dist/operations/mock.js +1 -0
- package/dist/operations/monitor-check.js +1 -0
- package/dist/orchestration-flow.js +1 -0
- package/dist/router.js +1 -0
- package/dist/security-validation.js +1 -0
- package/dist/services/server.js +1 -0
- package/dist/services/template-monitorcheck-route.js +1 -0
- package/package.json +5 -5
- package/lib/clients/http-client.js +0 -296
- package/lib/commons-cache.js +0 -185
- package/lib/commons-const.js +0 -203
- package/lib/commons-elasticsearch.js +0 -49
- package/lib/commons-errors.js +0 -278
- package/lib/commons-opensearch.js +0 -37
- package/lib/commons-splunk.js +0 -105
- package/lib/commons-util.js +0 -669
- package/lib/default-routes-docs.js +0 -141
- package/lib/default-routes-pos.js +0 -111
- package/lib/default-routes-pre.js +0 -151
- package/lib/environment.js +0 -81
- package/lib/factory/api-gateway.js +0 -12
- package/lib/factory/client-factory.js +0 -41
- package/lib/factory/function-factory.js +0 -40
- package/lib/factory/operation-flow-factory.js +0 -64
- package/lib/factory/server-factory.js +0 -15
- package/lib/factory/transformation-function-factory.js +0 -47
- package/lib/handle-route.js +0 -472
- package/lib/index.js +0 -50
- package/lib/jwt-util.js +0 -38
- package/lib/license/license-service.js +0 -27
- package/lib/models/base-context.js +0 -77
- package/lib/models/elastic-index-data.js +0 -76
- package/lib/models/flow-context.js +0 -58
- package/lib/models/flow-indexed.js +0 -62
- package/lib/models/operation-function-indexed.js +0 -22
- package/lib/models/operation-function-transformation-indexed.js +0 -23
- package/lib/models/operation-http-indexed.js +0 -38
- package/lib/models/operation-mock-indexed.js +0 -22
- package/lib/models/route-context.js +0 -69
- package/lib/models/security-route.js +0 -41
- package/lib/models/service-context.js +0 -65
- package/lib/models/service-group.js +0 -15
- package/lib/models/service-route.js +0 -23
- package/lib/models/splunk-data.js +0 -70
- package/lib/operations/abstract-operation.js +0 -73
- package/lib/operations/function.js +0 -143
- package/lib/operations/http.js +0 -286
- package/lib/operations/mock.js +0 -34
- package/lib/operations/monitor-check.js +0 -151
- package/lib/orchestration-flow.js +0 -323
- package/lib/public/redoc.html +0 -152
- package/lib/public/swagger.html +0 -143
- package/lib/router.js +0 -29
- package/lib/security-validation.js +0 -46
- package/lib/services/server.js +0 -211
- package/lib/services/template-monitorcheck-route.js +0 -61
@@ -1,141 +0,0 @@
|
|
1
|
-
'use strict';
|
2
|
-
|
3
|
-
const fs = require('fs');
|
4
|
-
const path = require('path');
|
5
|
-
const YAML = require('yaml');
|
6
|
-
const basicAuth = require('express-basic-auth');
|
7
|
-
const env = require('./environment');
|
8
|
-
|
9
|
-
module.exports = function (server) {
|
10
|
-
|
11
|
-
const fallbackUser = 'pay2b';
|
12
|
-
const fallbackPass = generateDynamicPassword();
|
13
|
-
|
14
|
-
const { user, pass, enabled } = env.application.documentation || {};
|
15
|
-
const docsUser = user || fallbackUser;
|
16
|
-
const docsPass = pass || fallbackPass;
|
17
|
-
|
18
|
-
const isAuthEnabled = enabled === true;
|
19
|
-
|
20
|
-
if (isAuthEnabled && (!user || !pass)) {
|
21
|
-
const currentEnv = env.environment || process.env.NODE_ENV || 'development';
|
22
|
-
if (currentEnv !== 'production') {
|
23
|
-
console.warn(`[DOCS] Nenhuma credencial configurada. Usando fallback: user="${docsUser}", pass="${docsPass}"`);
|
24
|
-
}
|
25
|
-
}
|
26
|
-
|
27
|
-
if (isAuthEnabled) {
|
28
|
-
const authOptions = {
|
29
|
-
users: { [docsUser]: docsPass },
|
30
|
-
challenge: true,
|
31
|
-
unauthorizedResponse: () => 'Acesso não autorizado à documentação.'
|
32
|
-
};
|
33
|
-
|
34
|
-
server.app.use('/docs', basicAuth(authOptions));
|
35
|
-
server.app.use('/docs/swagger', basicAuth(authOptions));
|
36
|
-
}
|
37
|
-
|
38
|
-
server.app.get('/docs', (req, res) => {
|
39
|
-
const htmlPath = path.resolve(__dirname, './public/redoc.html');
|
40
|
-
const html = fs.readFileSync(htmlPath, 'utf8');
|
41
|
-
res.setHeader('Content-Type', 'text/html');
|
42
|
-
res.send(html);
|
43
|
-
});
|
44
|
-
|
45
|
-
server.app.get('/docs/openapi.yaml', (req, res) => {
|
46
|
-
const spec = generateOpenApiFromServiceGroups(server);
|
47
|
-
const yaml = YAML.stringify(spec);
|
48
|
-
res.setHeader('Content-Type', 'text/yaml');
|
49
|
-
res.send(yaml);
|
50
|
-
});
|
51
|
-
|
52
|
-
server.app.get('/docs/swagger', (req, res) => {
|
53
|
-
const htmlPath = path.resolve(__dirname, './public/swagger.html');
|
54
|
-
const html = fs.readFileSync(htmlPath, 'utf8');
|
55
|
-
res.setHeader('Content-Type', 'text/html');
|
56
|
-
res.send(html);
|
57
|
-
});
|
58
|
-
};
|
59
|
-
|
60
|
-
function generateDynamicPassword() {
|
61
|
-
const now = new Date();
|
62
|
-
const year = now.getFullYear();
|
63
|
-
const month = String(now.getMonth() + 1).padStart(2, '0');
|
64
|
-
const day = String(now.getDate()).padStart(2, '0');
|
65
|
-
return `${year}${month}${day}`;
|
66
|
-
}
|
67
|
-
|
68
|
-
function generateOpenApiFromServiceGroups(server) {
|
69
|
-
const paths = {};
|
70
|
-
|
71
|
-
server.listServiceGroup.forEach((group) => {
|
72
|
-
group.services.forEach((service) => {
|
73
|
-
const method = (service.method || 'GET').toLowerCase();
|
74
|
-
const fullPath = `/${group.basePath || ''}/${service.route || ''}`.replace(/\/+/g, '/');
|
75
|
-
const openapiPath = fullPath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
76
|
-
|
77
|
-
if (!paths[openapiPath]) {
|
78
|
-
paths[openapiPath] = {};
|
79
|
-
}
|
80
|
-
|
81
|
-
// Define qual esquema de autenticação o serviço usa
|
82
|
-
const authScheme = service.authScheme || 'accessTokenHeader';
|
83
|
-
|
84
|
-
paths[openapiPath][method] = {
|
85
|
-
summary: service.description || service.name || `${method.toUpperCase()} ${openapiPath}`,
|
86
|
-
tags: [group.description || 'default'],
|
87
|
-
operationId: `${method}_${openapiPath.replace(/[\/{}]/g, '_')}`,
|
88
|
-
parameters: [
|
89
|
-
...extractPathParams(openapiPath),
|
90
|
-
...(service.parameters || service.rawOptions?.parameters || [])
|
91
|
-
],
|
92
|
-
requestBody: service.requestBody || undefined,
|
93
|
-
responses: service.responses || {
|
94
|
-
'200': { description: 'Success' }
|
95
|
-
},
|
96
|
-
security: [{ [authScheme]: [] }]
|
97
|
-
};
|
98
|
-
});
|
99
|
-
});
|
100
|
-
|
101
|
-
return {
|
102
|
-
openapi: '3.0.3',
|
103
|
-
info: {
|
104
|
-
title: server.environment.application.appName || 'Heimdall API',
|
105
|
-
version: '1.0.0',
|
106
|
-
description: 'Documentação OpenAPI gerada automaticamente a partir dos serviços mapeados.'
|
107
|
-
},
|
108
|
-
paths,
|
109
|
-
components: {
|
110
|
-
securitySchemes: {
|
111
|
-
bearerAuth: {
|
112
|
-
type: 'http',
|
113
|
-
scheme: 'bearer',
|
114
|
-
bearerFormat: 'JWT',
|
115
|
-
description: 'Envie o token de acesso no header Authorization: Bearer {token}'
|
116
|
-
},
|
117
|
-
accessTokenHeader: {
|
118
|
-
type: 'apiKey',
|
119
|
-
name: 'X-Access-Token',
|
120
|
-
in: 'header',
|
121
|
-
description: 'Envie o token no header X-Access-Token'
|
122
|
-
}
|
123
|
-
}
|
124
|
-
}
|
125
|
-
};
|
126
|
-
}
|
127
|
-
|
128
|
-
function extractPathParams(path) {
|
129
|
-
const regex = /{([^}]+)}/g;
|
130
|
-
const params = [];
|
131
|
-
let match;
|
132
|
-
while ((match = regex.exec(path)) !== null) {
|
133
|
-
params.push({
|
134
|
-
name: match[1],
|
135
|
-
in: 'path',
|
136
|
-
required: true,
|
137
|
-
schema: { type: 'string' }
|
138
|
-
});
|
139
|
-
}
|
140
|
-
return params;
|
141
|
-
}
|
@@ -1,111 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
const multer = require("multer");
|
4
|
-
const util = require("./commons-util");
|
5
|
-
const env = require("./environment");
|
6
|
-
const constants = require("./commons-const");
|
7
|
-
const REQUEST_ACCESS_CONTROL_PROPERTY = "requestAccessControl";
|
8
|
-
|
9
|
-
const ALLOW_HEADERS_DEFAULT = Array.isArray(constants.ALLOW_HEADERS_DEFAULT)
|
10
|
-
? constants.ALLOW_HEADERS_DEFAULT.slice()
|
11
|
-
: [];
|
12
|
-
|
13
|
-
if (
|
14
|
-
env.application.hasOwnProperty(REQUEST_ACCESS_CONTROL_PROPERTY) &&
|
15
|
-
env.application.requestAccessControl.allowHeaders
|
16
|
-
) {
|
17
|
-
const customHeaders = env.application.requestAccessControl.allowHeaders;
|
18
|
-
if (Array.isArray(customHeaders)) {
|
19
|
-
ALLOW_HEADERS_DEFAULT.push(...customHeaders);
|
20
|
-
} else if (typeof customHeaders === "string") {
|
21
|
-
ALLOW_HEADERS_DEFAULT.push(...customHeaders.split(",").map(h => h.trim()));
|
22
|
-
}
|
23
|
-
}
|
24
|
-
|
25
|
-
// Remover duplicados por segurança
|
26
|
-
const UNIQUE_ALLOW_HEADERS = [...new Set(ALLOW_HEADERS_DEFAULT)];
|
27
|
-
|
28
|
-
module.exports = function (server) {
|
29
|
-
util.info("stage=init action=loadPosConfigurations");
|
30
|
-
|
31
|
-
server.app.get("/healthcheck", (_, res) => {
|
32
|
-
util.info("stage=init action=healthcheck");
|
33
|
-
res.status(200).send({ success: true });
|
34
|
-
util.info("stage=end action=healthcheck");
|
35
|
-
});
|
36
|
-
|
37
|
-
server.app.get("/monitor/health", (_, res) => {
|
38
|
-
util.info("stage=init action=monitorHealth");
|
39
|
-
res.status(200).send({ status: "UP" });
|
40
|
-
util.info("stage=end action=monitorHealth");
|
41
|
-
});
|
42
|
-
|
43
|
-
server.app.get("/monitor/info", (_, res) => {
|
44
|
-
util.info("stage=init action=monitorInfo");
|
45
|
-
res.status(200).send({
|
46
|
-
application: {
|
47
|
-
name: env.application.appName,
|
48
|
-
version: env.application.version,
|
49
|
-
},
|
50
|
-
});
|
51
|
-
util.info("stage=end action=monitorInfo");
|
52
|
-
});
|
53
|
-
|
54
|
-
server.app.get("/", (_, res) => {
|
55
|
-
util.info("stage=init action=rootAccess");
|
56
|
-
res.status(200).send({ success: true });
|
57
|
-
util.info("stage=end action=rootAccess");
|
58
|
-
});
|
59
|
-
|
60
|
-
server.app.use((req, res, __) => {
|
61
|
-
util.info(`stage=init action=requestInterceptor path=${req.path} method=${req.method}`);
|
62
|
-
|
63
|
-
const requestedMethod = req.headers["access-control-request-method"];
|
64
|
-
|
65
|
-
if (req.method.toLowerCase() === "options" && requestedMethod) {
|
66
|
-
res.header("Access-Control-Allow-Methods", [req.method, requestedMethod]);
|
67
|
-
res.header("Access-Control-Allow-Origin", req.headers.origin || "*");
|
68
|
-
res.header("Access-Control-Allow-Credentials", true);
|
69
|
-
res.header("Access-Control-Allow-Headers", UNIQUE_ALLOW_HEADERS.join(", "));
|
70
|
-
util.info(`stage=end action=preflightHandled path=${req.path} method=${req.method}`);
|
71
|
-
return res.sendStatus(200);
|
72
|
-
} else {
|
73
|
-
util.warn(`stage=end action=resourceNotFound path=${req.path} method=${req.method}`);
|
74
|
-
res.status(404).send({
|
75
|
-
code: "ResourceNotFound",
|
76
|
-
message: "Invalid URI",
|
77
|
-
});
|
78
|
-
}
|
79
|
-
});
|
80
|
-
|
81
|
-
server.app.use((err, req, res, next) => {
|
82
|
-
const serviceName = `${req.method} ${req.path}`;
|
83
|
-
|
84
|
-
if (err instanceof SyntaxError && err.status === 400 && "body" in err) {
|
85
|
-
util.error(`stage=error action=jsonSyntaxError service=${serviceName} error=${err.message}`);
|
86
|
-
return res.status(400).send({
|
87
|
-
message: "Oops! Something went wrong on our side. Please try again later.",
|
88
|
-
code: "INVALID_JSON_REQUEST",
|
89
|
-
details: "The JSON provided is malformed. Please check your request body and try again."
|
90
|
-
});
|
91
|
-
}
|
92
|
-
|
93
|
-
if (err instanceof multer.MulterError) {
|
94
|
-
util.error(`stage=error action=fileUploadError service=${serviceName} error=${err.message}`);
|
95
|
-
return res.status(400).send({
|
96
|
-
message: "Oops! Something went wrong on our side. Please try again later.",
|
97
|
-
code: "UPLOAD_FILE_ERROR",
|
98
|
-
details: err.message
|
99
|
-
});
|
100
|
-
}
|
101
|
-
|
102
|
-
util.error(`stage=error action=unexpectedError service=${serviceName} error=${err.message}`);
|
103
|
-
return res.status(500).send({
|
104
|
-
message: "Oops! Something went wrong on our side. Please try again later.",
|
105
|
-
code: "INTERNAL_SERVER_ERROR",
|
106
|
-
details: "Our team has been notified and is working to resolve the issue."
|
107
|
-
});
|
108
|
-
});
|
109
|
-
|
110
|
-
util.info("stage=end action=loadPosConfigurations");
|
111
|
-
};
|
@@ -1,151 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
const cookieParser = require("cookie-parser");
|
4
|
-
const bodyParser = require("body-parser");
|
5
|
-
const compression = require("compression");
|
6
|
-
const helmet = require("helmet");
|
7
|
-
const { contentSecurityPolicy } = require('helmet');
|
8
|
-
const throttle = require("express-throttle");
|
9
|
-
const morgan = require("morgan");
|
10
|
-
const util = require("./commons-util");
|
11
|
-
const env = require("./environment");
|
12
|
-
const constants = require("./commons-const");
|
13
|
-
const REQUEST_ACCESS_CONTROL_PROPERTY = "requestAccessControl";
|
14
|
-
|
15
|
-
const ALLOWED_ORIGINS = Array.isArray(env.application?.requestAccessControl?.allowedOrigins)
|
16
|
-
? env.application.requestAccessControl.allowedOrigins.filter(o => typeof o === "string" && o.trim() !== "")
|
17
|
-
: [];
|
18
|
-
|
19
|
-
const ALLOW_HEADERS_DEFAULT = Array.isArray(constants.ALLOW_HEADERS_DEFAULT)
|
20
|
-
? constants.ALLOW_HEADERS_DEFAULT.slice()
|
21
|
-
: [];
|
22
|
-
|
23
|
-
if (
|
24
|
-
env.application.hasOwnProperty(REQUEST_ACCESS_CONTROL_PROPERTY) &&
|
25
|
-
env.application.requestAccessControl.allowHeaders
|
26
|
-
) {
|
27
|
-
const customHeaders = env.application.requestAccessControl.allowHeaders;
|
28
|
-
if (Array.isArray(customHeaders)) {
|
29
|
-
ALLOW_HEADERS_DEFAULT.push(...customHeaders);
|
30
|
-
} else if (typeof customHeaders === "string") {
|
31
|
-
ALLOW_HEADERS_DEFAULT.push(...customHeaders.split(",").map(h => h.trim()));
|
32
|
-
}
|
33
|
-
}
|
34
|
-
|
35
|
-
const UNIQUE_ALLOW_HEADERS = [...new Set(ALLOW_HEADERS_DEFAULT)];
|
36
|
-
|
37
|
-
module.exports = function (server) {
|
38
|
-
util.info("stage=init action=loadPreConfigurations");
|
39
|
-
|
40
|
-
server.app.use((req, res, next) => {
|
41
|
-
util.info(`stage=init action=corsValidation origin=${req.headers.origin}`);
|
42
|
-
|
43
|
-
const origin = req.headers.origin;
|
44
|
-
|
45
|
-
if (isOriginAllowed(origin)) {
|
46
|
-
res.header("Access-Control-Allow-Origin", origin);
|
47
|
-
res.header("Access-Control-Allow-Credentials", "true");
|
48
|
-
util.info(`stage=end action=corsValidation result=allowed origin=${origin}`);
|
49
|
-
} else {
|
50
|
-
res.header("Access-Control-Allow-Origin", "null");
|
51
|
-
res.header("Access-Control-Allow-Credentials", "false");
|
52
|
-
util.warn(`stage=end action=corsValidation result=denied origin=${origin}`);
|
53
|
-
}
|
54
|
-
|
55
|
-
res.header("Access-Control-Allow-Headers", UNIQUE_ALLOW_HEADERS.join(", "));
|
56
|
-
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
|
57
|
-
res.header("X-Content-Type-Options", "nosniff");
|
58
|
-
res.header("X-Frame-Options", "DENY");
|
59
|
-
res.header("Pragma", "no-cache");
|
60
|
-
res.header("Expires", "0");
|
61
|
-
res.header("Connection", "close");
|
62
|
-
res.header("Accept-Encoding", "gzip");
|
63
|
-
res.header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
|
64
|
-
res.header("X-XSS-Protection", "mode=block");
|
65
|
-
|
66
|
-
util.info("stage=end action=corsHeadersApplied");
|
67
|
-
return next();
|
68
|
-
});
|
69
|
-
|
70
|
-
server.app.use(bodyParser.urlencoded({ extended: false, limit: '10mb' }));
|
71
|
-
server.app.use(bodyParser.json({ type: 'application/*', limit: '10mb' }));
|
72
|
-
server.app.use(cookieParser());
|
73
|
-
server.app.use(compression());
|
74
|
-
server.app.use(morgan("dev"));
|
75
|
-
|
76
|
-
server.app.use(helmet()); // Configurações padrão
|
77
|
-
|
78
|
-
server.app.use(contentSecurityPolicy({
|
79
|
-
directives: {
|
80
|
-
defaultSrc: ["'self'"],
|
81
|
-
imgSrc: [
|
82
|
-
"'self'",
|
83
|
-
"data:",
|
84
|
-
"http://localhost:*",
|
85
|
-
"https://*.pay2b.net",
|
86
|
-
"https://*.pay2b.io",
|
87
|
-
"https://*.pay2b.com.br",
|
88
|
-
"http://127.0.0.1:*",
|
89
|
-
"https://*.s3.amazonaws.com",
|
90
|
-
"https://*.s3.us-east-1.amazonaws.com",
|
91
|
-
"https://*.s3.sa-east-1.amazonaws.com",
|
92
|
-
"https://cdn.redoc.ly"
|
93
|
-
],
|
94
|
-
scriptSrc: [
|
95
|
-
"'self'",
|
96
|
-
"https://cdn.redoc.ly",
|
97
|
-
"https://*.pay2b.com.br",
|
98
|
-
'https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui-bundle.js',
|
99
|
-
'https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui-standalone-preset.js',
|
100
|
-
'https://cdn.jsdelivr.net/npm/swagger-ui-dist/swagger-ui.css',
|
101
|
-
"'unsafe-inline'"
|
102
|
-
],
|
103
|
-
workerSrc: ["'self'", "blob:"],
|
104
|
-
objectSrc: ["'none'"],
|
105
|
-
upgradeInsecureRequests: [],
|
106
|
-
}
|
107
|
-
}));
|
108
|
-
|
109
|
-
server.app.use(throttle({
|
110
|
-
burst: env.application.requestPerSecond,
|
111
|
-
rate: `${env.application.requestPerSecond / 2}/s`,
|
112
|
-
ip: true,
|
113
|
-
}));
|
114
|
-
|
115
|
-
server.app.use((req, res, next) => {
|
116
|
-
res.shouldKeepAlive = false;
|
117
|
-
next();
|
118
|
-
});
|
119
|
-
|
120
|
-
util.info("stage=end action=loadPreConfigurations");
|
121
|
-
};
|
122
|
-
|
123
|
-
/**
|
124
|
-
* Valida se a origem é permitida.
|
125
|
-
*/
|
126
|
-
function isOriginAllowed(origin) {
|
127
|
-
if (!origin) {
|
128
|
-
util.warn("stage=error action=isOriginAllowed reason=missingOrigin");
|
129
|
-
return true;
|
130
|
-
}
|
131
|
-
|
132
|
-
// Se não houver nenhuma origem configurada, permite todas
|
133
|
-
if (ALLOWED_ORIGINS.length === 0) {
|
134
|
-
util.warn(`stage=warn action=isOriginAllowed reason=allowedAllOrigins origin=${origin}`);
|
135
|
-
return true;
|
136
|
-
}
|
137
|
-
|
138
|
-
try {
|
139
|
-
const parsedOrigin = new URL(origin);
|
140
|
-
const isAllowed = ALLOWED_ORIGINS.includes(parsedOrigin.origin);
|
141
|
-
|
142
|
-
if (!isAllowed) {
|
143
|
-
util.warn(`stage=error action=isOriginAllowed reason=originNotAllowed origin=${origin}`);
|
144
|
-
}
|
145
|
-
|
146
|
-
return isAllowed;
|
147
|
-
} catch (err) {
|
148
|
-
util.warn(`stage=error action=isOriginAllowed reason=invalidOriginFormat origin=${origin}`);
|
149
|
-
return false;
|
150
|
-
}
|
151
|
-
}
|
package/lib/environment.js
DELETED
@@ -1,81 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
const fs = require("fs");
|
4
|
-
const path = require("path");
|
5
|
-
|
6
|
-
class Environment {
|
7
|
-
constructor() {
|
8
|
-
this.environment = process.env.NODE_ENV || "development";
|
9
|
-
process.env.NODE_ENV = this.environment;
|
10
|
-
this.application = this.loadConfig(`${this.environment}-application.js`);
|
11
|
-
this.mappingServices = this.loadConfig(`${this.environment}-mapping-services.js`);
|
12
|
-
this.mappingClients = this.loadConfig(`${this.environment}-mapping-clients.js`);
|
13
|
-
this.applyDefaultConfig();
|
14
|
-
this.initApplicationConfig();
|
15
|
-
}
|
16
|
-
|
17
|
-
/**
|
18
|
-
* Load configuration file.
|
19
|
-
* @param {string} fileName - Configuration file name.
|
20
|
-
* @returns {Object} Configuration object or empty object if file not found.
|
21
|
-
*/
|
22
|
-
loadConfig(fileName) {
|
23
|
-
const filePath = path.join(process.cwd(), "config", fileName);
|
24
|
-
try {
|
25
|
-
if (fs.existsSync(filePath)) {
|
26
|
-
return require(filePath);
|
27
|
-
} else {
|
28
|
-
console.warn(`Config file not found: ${filePath}. Returning empty object.`);
|
29
|
-
return [];
|
30
|
-
}
|
31
|
-
} catch (error) {
|
32
|
-
console.error(`Error loading config file: ${filePath}`, error);
|
33
|
-
return [];
|
34
|
-
}
|
35
|
-
}
|
36
|
-
|
37
|
-
/**
|
38
|
-
* Apply default configurations if they are missing.
|
39
|
-
*/
|
40
|
-
applyDefaultConfig() {
|
41
|
-
if (!this.application.logger) {
|
42
|
-
this.application.logger = {
|
43
|
-
Console: {
|
44
|
-
level: process.env.loggerLevel || "info",
|
45
|
-
},
|
46
|
-
};
|
47
|
-
}
|
48
|
-
}
|
49
|
-
|
50
|
-
/**
|
51
|
-
* Initialize application configuration.
|
52
|
-
*/
|
53
|
-
initApplicationConfig() {
|
54
|
-
try {
|
55
|
-
const packageJson = require(path.join(process.cwd(), "package.json"));
|
56
|
-
this.application.version = packageJson.version || "unknown";
|
57
|
-
} catch (error) {
|
58
|
-
console.warn("package.json not found. Setting version to 'unknown'.");
|
59
|
-
this.application.version = "unknown";
|
60
|
-
}
|
61
|
-
|
62
|
-
this.application.startServer =
|
63
|
-
this.application.startServer !== undefined ? this.application.startServer : true;
|
64
|
-
}
|
65
|
-
|
66
|
-
/**
|
67
|
-
* Get the current environment details.
|
68
|
-
* @returns {Object} Environment configuration.
|
69
|
-
*/
|
70
|
-
getEnvironmentDetails() {
|
71
|
-
return {
|
72
|
-
environment: this.environment,
|
73
|
-
application: this.application,
|
74
|
-
mappingServices: this.mappingServices,
|
75
|
-
mappingClients: this.mappingClients,
|
76
|
-
startServer: this.application.startServer,
|
77
|
-
};
|
78
|
-
}
|
79
|
-
}
|
80
|
-
|
81
|
-
module.exports = new Environment().getEnvironmentDetails();
|
@@ -1,41 +0,0 @@
|
|
1
|
-
'use strict';
|
2
|
-
|
3
|
-
const Util = require('../commons-util');
|
4
|
-
const HttpClient = require('../clients/http-client');
|
5
|
-
const Environment = require('../environment');
|
6
|
-
const MappingClients = Environment.mappingClients;
|
7
|
-
const CacheClient = {};
|
8
|
-
|
9
|
-
var ClientFactory = (function() {
|
10
|
-
|
11
|
-
function createByName(clientName) {
|
12
|
-
|
13
|
-
if (!clientName) {
|
14
|
-
Util.throwErrorIfItExists(new Error('The client name can not be empty.'));
|
15
|
-
} else if (!MappingClients[clientName]) {
|
16
|
-
Util.throwErrorIfItExists(new Error('Invalid client name=' + clientName));
|
17
|
-
} else {
|
18
|
-
var options = MappingClients[clientName];
|
19
|
-
try {
|
20
|
-
|
21
|
-
if (CacheClient[clientName]) {
|
22
|
-
return CacheClient[clientName];
|
23
|
-
} else {
|
24
|
-
Util.info("Created client name=" + clientName);
|
25
|
-
var httpClient = new HttpClient(options);
|
26
|
-
CacheClient[clientName] = httpClient;
|
27
|
-
return httpClient;
|
28
|
-
}
|
29
|
-
} catch (error) {
|
30
|
-
Util.throwErrorIfItExists(new Error('Invalid client name=' + clientName));
|
31
|
-
}
|
32
|
-
}
|
33
|
-
}
|
34
|
-
|
35
|
-
return {
|
36
|
-
createByName: createByName
|
37
|
-
};
|
38
|
-
|
39
|
-
})();
|
40
|
-
|
41
|
-
module.exports = ClientFactory;
|
@@ -1,40 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
const Util = require("../commons-util");
|
4
|
-
const Errors = require("../commons-errors");
|
5
|
-
const path = require("path");
|
6
|
-
|
7
|
-
const CACHE_FUNCTION = {};
|
8
|
-
|
9
|
-
exports.createFunctionByName = (options) => {
|
10
|
-
|
11
|
-
let name = options.functionName || null;
|
12
|
-
let dir = options.dir || "";
|
13
|
-
let fileFunctionPath = path.resolve(process.cwd() + `/functions/${dir}/${name}`);
|
14
|
-
|
15
|
-
if (name) {
|
16
|
-
try {
|
17
|
-
if (CACHE_FUNCTION[fileFunctionPath]) {
|
18
|
-
Util.info(
|
19
|
-
`stage=info method=FunctionFactory.createFunctionByName message=Cache function=${fileFunctionPath} in Cache`
|
20
|
-
);
|
21
|
-
return CACHE_FUNCTION[fileFunctionPath];
|
22
|
-
} else {
|
23
|
-
let CreateFunction = require(fileFunctionPath);
|
24
|
-
Util.info(
|
25
|
-
`stage=info method=FunctionFactory.createFunctionByName message=Create function=${name} path=${fileFunctionPath}`
|
26
|
-
);
|
27
|
-
CACHE_FUNCTION[fileFunctionPath] = CreateFunction;
|
28
|
-
return CreateFunction;
|
29
|
-
}
|
30
|
-
} catch (error) {
|
31
|
-
Util.error(
|
32
|
-
`stage=error method=FunctionFactory.createFunctionByName function name=${name} path=${fileFunctionPath}`,
|
33
|
-
error
|
34
|
-
);
|
35
|
-
throw error;
|
36
|
-
}
|
37
|
-
} else {
|
38
|
-
throw new Errors.ApiGatewayError("Error to create function");
|
39
|
-
}
|
40
|
-
};
|
@@ -1,64 +0,0 @@
|
|
1
|
-
'use strict';
|
2
|
-
|
3
|
-
var Util = require('../commons-util');
|
4
|
-
var Const = require('../commons-const');
|
5
|
-
var HttpOperation = require('../operations/http');
|
6
|
-
var FunctionOperation = require('../operations/function');
|
7
|
-
var MockOperation = require('../operations/mock');
|
8
|
-
var MonitorCheckOperation = require('../operations/monitor-check');
|
9
|
-
|
10
|
-
class OperationFlowFactory {
|
11
|
-
|
12
|
-
constructor() {
|
13
|
-
}
|
14
|
-
|
15
|
-
/*
|
16
|
-
iterate : IterateOperation,
|
17
|
-
cached : CachedOperation,
|
18
|
-
flow : ExecuteFlowOperation,
|
19
|
-
render : RenderOperation,
|
20
|
-
if : IfOperation,
|
21
|
-
throw : ThrowOperation
|
22
|
-
*/
|
23
|
-
|
24
|
-
static getRegisteredOperations(options) {
|
25
|
-
switch (options.type) {
|
26
|
-
case Const.FLOW_OPERATION_TYPE.HTTP:
|
27
|
-
return {
|
28
|
-
New: HttpOperation,
|
29
|
-
description: `[${options.clientName}]/${options.path}`
|
30
|
-
};
|
31
|
-
case Const.FLOW_OPERATION_TYPE.FUNCTION:
|
32
|
-
return {
|
33
|
-
New: FunctionOperation,
|
34
|
-
description: `${options.functionName}.js`
|
35
|
-
};
|
36
|
-
case Const.FLOW_OPERATION_TYPE.MOCK:
|
37
|
-
return {
|
38
|
-
New: MockOperation,
|
39
|
-
description: options.file
|
40
|
-
};
|
41
|
-
case Const.FLOW_OPERATION_TYPE.MONITOR_CHECK:
|
42
|
-
return {
|
43
|
-
New: MonitorCheckOperation,
|
44
|
-
description: options.clientName
|
45
|
-
};
|
46
|
-
default:
|
47
|
-
Util.throwErrorIfItExists(new Error('Invalid operation type: ' + options.type));
|
48
|
-
break;
|
49
|
-
};
|
50
|
-
};
|
51
|
-
|
52
|
-
static createOperationByType(options, context) {
|
53
|
-
|
54
|
-
let operation = this.getRegisteredOperations(options);
|
55
|
-
|
56
|
-
Util.info(`Created operation=${options.type} for ${operation.description}`);
|
57
|
-
return new operation.New(options, context);
|
58
|
-
|
59
|
-
};
|
60
|
-
|
61
|
-
};
|
62
|
-
module.exports = OperationFlowFactory;
|
63
|
-
module.getRegisteredOperations = OperationFlowFactory.getRegisteredOperations;
|
64
|
-
module.createOperationByType = OperationFlowFactory.createOperationByType;
|
@@ -1,15 +0,0 @@
|
|
1
|
-
'use strict';
|
2
|
-
|
3
|
-
const Util = require('../commons-util');
|
4
|
-
var environment = require('../environment');
|
5
|
-
const Server = require('../services/server')
|
6
|
-
|
7
|
-
module.exports = {
|
8
|
-
createServer: (options) => {
|
9
|
-
try {
|
10
|
-
return new Server(options || environment);
|
11
|
-
} catch (error) {
|
12
|
-
Util.throwErrorIfItExists(error);
|
13
|
-
}
|
14
|
-
}
|
15
|
-
};
|