exodus-framework 2.0.954 → 2.0.955
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/lib/app/settings.d.ts.map +1 -1
- package/lib/contracts/settings.d.ts +1 -2
- package/lib/contracts/settings.d.ts.map +1 -1
- package/lib/utils/database.d.ts +1 -1
- package/lib/utils/database.d.ts.map +1 -1
- package/package.json +1 -1
- package/lib/app/classes/broadcast.js +0 -79
- package/lib/app/classes/cache.js +0 -94
- package/lib/app/classes/communication.js +0 -99
- package/lib/app/classes/communicationcontext.js +0 -1
- package/lib/app/classes/event.js +0 -94
- package/lib/app/classes/index.js +0 -105
- package/lib/app/classes/managed.js +0 -145
- package/lib/app/classes/service.js +0 -232
- package/lib/app/classes/servicemodel.js +0 -22
- package/lib/app/classes/singleton.js +0 -26
- package/lib/app/classes/socket/clienthandler.js +0 -54
- package/lib/app/classes/socket/eventhandler.js +0 -51
- package/lib/app/classes/socket/index.js +0 -20
- package/lib/app/classes/system.js +0 -49
- package/lib/app/controller.js +0 -97
- package/lib/app/core.js +0 -47
- package/lib/app/error.js +0 -66
- package/lib/app/exodus.js +0 -97
- package/lib/app/index.js +0 -68
- package/lib/app/settings.js +0 -162
- package/lib/certificates/private_key.pem +0 -27
- package/lib/certificates/public_key.pem +0 -9
- package/lib/contracts/communication/communication.js +0 -39
- package/lib/contracts/communication/index.js +0 -27
- package/lib/contracts/communication/operation.js +0 -5
- package/lib/contracts/console.js +0 -5
- package/lib/contracts/contansts.js +0 -13
- package/lib/contracts/core.js +0 -12
- package/lib/contracts/entity.js +0 -5
- package/lib/contracts/http.js +0 -52
- package/lib/contracts/index.js +0 -104
- package/lib/contracts/messaging.js +0 -50
- package/lib/contracts/security.js +0 -5
- package/lib/contracts/service.js +0 -11
- package/lib/contracts/session.js +0 -5
- package/lib/contracts/settings.js +0 -5
- package/lib/contracts/singleton.js +0 -5
- package/lib/contracts/socket.js +0 -11
- package/lib/contracts/tasks.js +0 -1
- package/lib/controllers/api/file.js +0 -24
- package/lib/controllers/api/index.js +0 -13
- package/lib/controllers/api/log.js +0 -55
- package/lib/controllers/api/report.js +0 -55
- package/lib/controllers/index.js +0 -16
- package/lib/controllers/messaging/application.js +0 -75
- package/lib/controllers/messaging/database.js +0 -64
- package/lib/controllers/messaging/environment.js +0 -111
- package/lib/express.d.js +0 -5
- package/lib/index.js +0 -104
- package/lib/middlewares/access.js +0 -114
- package/lib/middlewares/authentication.js +0 -104
- package/lib/middlewares/file.js +0 -41
- package/lib/middlewares/index.js +0 -36
- package/lib/models/Application.js +0 -65
- package/lib/models/DatabaseHost.js +0 -62
- package/lib/models/EnvConnection.js +0 -41
- package/lib/models/Log.js +0 -67
- package/lib/models/Report.js +0 -65
- package/lib/models/System.js +0 -54
- package/lib/models/index.js +0 -82
- package/lib/routes/api/index.js +0 -16
- package/lib/routes/api/v1/index.js +0 -38
- package/lib/routes/api/v1/logs.js +0 -19
- package/lib/routes/api/v1/report.js +0 -19
- package/lib/routes/api/v1/sse.js +0 -36
- package/lib/routes/index.js +0 -27
- package/lib/routes/messaging/index.js +0 -34
- package/lib/services/database.js +0 -136
- package/lib/services/ecosystem.js +0 -46
- package/lib/services/express.js +0 -162
- package/lib/services/file.js +0 -65
- package/lib/services/file_new.js +0 -136
- package/lib/services/index.js +0 -108
- package/lib/services/log.js +0 -26
- package/lib/services/rabitmq.js +0 -187
- package/lib/services/redis.js +0 -84
- package/lib/services/security.js +0 -231
- package/lib/services/sequelize.js +0 -313
- package/lib/services/socket.js +0 -123
- package/lib/services/task/TaskServiceBase.js +0 -17
- package/lib/services/task/index.js +0 -40
- package/lib/services/task/queue/QueueService.js +0 -48
- package/lib/services/task/queue/QueueTask.js +0 -134
- package/lib/services/task/queue/SingleQueue.js +0 -68
- package/lib/services/task/queue/index.js +0 -27
- package/lib/services/task/scheduler/SchedulerService.js +0 -31
- package/lib/services/task/scheduler/SchedulerTask.js +0 -211
- package/lib/services/task/scheduler/index.js +0 -20
- package/lib/services/test.js +0 -27
- package/lib/socket.d.js +0 -3
- package/lib/tasks/index.js +0 -27
- package/lib/tasks/queue/application.js +0 -44
- package/lib/tasks/queue/environment.js +0 -92
- package/lib/tasks/queue/index.js +0 -20
- package/lib/tasks/queue/teste.js +0 -21
- package/lib/tasks/schedule/index.js +0 -13
- package/lib/tasks/schedule/restart.js +0 -19
- package/lib/tasks/schedule/teste.js +0 -61
- package/lib/utils/api.js +0 -65
- package/lib/utils/database.js +0 -157
- package/lib/utils/date.js +0 -28
- package/lib/utils/index.js +0 -60
- package/lib/utils/logger.js +0 -51
- package/lib/utils/session.js +0 -23
package/lib/services/security.js
DELETED
@@ -1,231 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
4
|
-
value: true
|
5
|
-
});
|
6
|
-
exports.default = void 0;
|
7
|
-
var crypto = _interopRequireWildcard(require("crypto"));
|
8
|
-
var fs = _interopRequireWildcard(require("fs"));
|
9
|
-
var _nodeJose = require("node-jose");
|
10
|
-
var _path = _interopRequireDefault(require("path"));
|
11
|
-
var _app = require("../app");
|
12
|
-
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
13
|
-
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
14
|
-
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
15
|
-
class SecurityService extends _app.Service {
|
16
|
-
privateKey;
|
17
|
-
publicKey;
|
18
|
-
servicePublicKey;
|
19
|
-
async onStart() {
|
20
|
-
await super.onStart();
|
21
|
-
this.checkPaths();
|
22
|
-
await this.loadPrivateKey();
|
23
|
-
await this.loadPublicKey();
|
24
|
-
await this.loadServicePublicKey();
|
25
|
-
return true;
|
26
|
-
}
|
27
|
-
checkPaths() {
|
28
|
-
!fs.existsSync(_app.Core.settings.getAuthentication().certPath) && fs.mkdirSync(_app.Core.settings.getAuthentication().certPath, {
|
29
|
-
recursive: true
|
30
|
-
});
|
31
|
-
}
|
32
|
-
|
33
|
-
/* Key Pair */
|
34
|
-
async loadPrivateKey() {
|
35
|
-
const privateKeyPath = _path.default.join(_app.Core.settings.getAuthentication().certPath, 'private_key.pem');
|
36
|
-
if (fs.existsSync(privateKeyPath)) {
|
37
|
-
const pem = fs.readFileSync(privateKeyPath, 'utf8');
|
38
|
-
this.privateKey = await _nodeJose.JWK.asKey(pem, 'pem');
|
39
|
-
} else {
|
40
|
-
const {
|
41
|
-
privateKey
|
42
|
-
} = await this.createKeyPairs();
|
43
|
-
this.privateKey = await _nodeJose.JWK.asKey(privateKey, 'pem');
|
44
|
-
const pem = this.privateKey.toPEM(true);
|
45
|
-
fs.writeFileSync(privateKeyPath, pem, 'utf8');
|
46
|
-
}
|
47
|
-
}
|
48
|
-
async loadPublicKey() {
|
49
|
-
const publicKeyPath = _path.default.join(_app.Core.settings.getAuthentication().certPath, 'public_key.pem');
|
50
|
-
const pem = this.privateKey.toPEM(false);
|
51
|
-
this.publicKey = await _nodeJose.JWK.asKey(pem, 'pem');
|
52
|
-
fs.writeFileSync(publicKeyPath, pem, 'utf8');
|
53
|
-
}
|
54
|
-
async createKeyPairs() {
|
55
|
-
const keyPair = await _nodeJose.JWK.createKey('RSA', 2048, {
|
56
|
-
alg: 'RS256',
|
57
|
-
use: 'sig',
|
58
|
-
iss: _app.Core.settings.getAuthentication().issuer
|
59
|
-
});
|
60
|
-
return {
|
61
|
-
publicKey: keyPair.toPEM(false),
|
62
|
-
privateKey: keyPair.toPEM(true)
|
63
|
-
};
|
64
|
-
}
|
65
|
-
async loadServicePublicKey() {
|
66
|
-
if (fs.existsSync(_app.Core.settings.getAuthentication().servicePublicKeyPath)) {
|
67
|
-
const pem = fs.readFileSync(_app.Core.settings.getAuthentication().servicePublicKeyPath, 'utf8');
|
68
|
-
this.servicePublicKey = await _nodeJose.JWK.asKey(pem, 'pem');
|
69
|
-
} else {
|
70
|
-
throw new Error('Não foi possível localizar o certificado de serviço. Verifique o caminho nas configurações');
|
71
|
-
}
|
72
|
-
}
|
73
|
-
async loadKeyByStr(data) {
|
74
|
-
return await _nodeJose.JWK.asKey(data, 'pem');
|
75
|
-
}
|
76
|
-
|
77
|
-
/**
|
78
|
-
* Chave privada emitida por este serviço
|
79
|
-
*
|
80
|
-
* @memberof SecurityService
|
81
|
-
*/
|
82
|
-
getPrivateKey() {
|
83
|
-
return this.privateKey;
|
84
|
-
}
|
85
|
-
/**
|
86
|
-
* Chave publica emitida por este serviço
|
87
|
-
*
|
88
|
-
* @memberof SecurityService
|
89
|
-
*/
|
90
|
-
getPublicKey() {
|
91
|
-
return this.publicKey;
|
92
|
-
}
|
93
|
-
/**
|
94
|
-
* Chave publica emitida pelo serviço do hub se sessões
|
95
|
-
*
|
96
|
-
* @memberof SecurityService
|
97
|
-
*/
|
98
|
-
getServicePublicKey() {
|
99
|
-
return this.servicePublicKey;
|
100
|
-
}
|
101
|
-
/**
|
102
|
-
* Criptografía utilizando chave publica
|
103
|
-
*
|
104
|
-
* @param {TSignData} data
|
105
|
-
* @memberof SecurityService
|
106
|
-
*/
|
107
|
-
async encrypt(data, publicKey) {
|
108
|
-
const currentTime = Math.floor(Date.now() / 1000);
|
109
|
-
const defaults = {
|
110
|
-
iat: currentTime,
|
111
|
-
exp: currentTime + _app.Core.settings.getAuthentication().signExpirationSecs,
|
112
|
-
iss: _app.Core.settings.getAuthentication().issuer
|
113
|
-
};
|
114
|
-
const payload = JSON.stringify({
|
115
|
-
...defaults,
|
116
|
-
...data
|
117
|
-
});
|
118
|
-
try {
|
119
|
-
const encrypted = await _nodeJose.JWE.createEncrypt({
|
120
|
-
format: 'compact'
|
121
|
-
}, publicKey).update(payload).final();
|
122
|
-
return encrypted;
|
123
|
-
} catch (error) {
|
124
|
-
new _app.ErrorHandler('Não foi possível criptografar os dados', error);
|
125
|
-
return false;
|
126
|
-
}
|
127
|
-
}
|
128
|
-
/**
|
129
|
-
* Descriptografia utilizando chave privada
|
130
|
-
*
|
131
|
-
* @param {string} encryptedData
|
132
|
-
* @memberof SecurityService
|
133
|
-
*/
|
134
|
-
async decrypt(encryptedData, privateKey) {
|
135
|
-
try {
|
136
|
-
const decrypted = await _nodeJose.JWE.createDecrypt(privateKey).decrypt(encryptedData);
|
137
|
-
const result = decrypted.plaintext.toString();
|
138
|
-
const parserd = JSON.parse(result);
|
139
|
-
// Tenta parsear como JSON se for objeto
|
140
|
-
return parserd.payload;
|
141
|
-
} catch (error) {
|
142
|
-
new _app.ErrorHandler('Não foi possível descriptografar os dados', error);
|
143
|
-
return false;
|
144
|
-
}
|
145
|
-
}
|
146
|
-
/**
|
147
|
-
* Realiza uma assinatura usando chave privada
|
148
|
-
*
|
149
|
-
* @param {TSignData} data
|
150
|
-
* @memberof SecurityService
|
151
|
-
*/
|
152
|
-
async sign(data, privateKey) {
|
153
|
-
const currentTime = Math.floor(Date.now() / 1000);
|
154
|
-
const defaults = {
|
155
|
-
iat: currentTime,
|
156
|
-
exp: currentTime + _app.Core.settings.getAuthentication().signExpirationSecs,
|
157
|
-
iss: _app.Core.settings.getAuthentication().issuer
|
158
|
-
};
|
159
|
-
try {
|
160
|
-
const payload = JSON.stringify({
|
161
|
-
...defaults,
|
162
|
-
...data
|
163
|
-
});
|
164
|
-
const signature = await _nodeJose.JWS.createSign({
|
165
|
-
compact: true,
|
166
|
-
fields: {
|
167
|
-
typ: 'jwt'
|
168
|
-
}
|
169
|
-
}, privateKey).update(payload, 'utf8').final();
|
170
|
-
return signature;
|
171
|
-
} catch (error) {
|
172
|
-
new _app.ErrorHandler('Erro ao assinar os dados', error);
|
173
|
-
}
|
174
|
-
}
|
175
|
-
|
176
|
-
/**
|
177
|
-
* Verifica assinatura utilizando chave publica
|
178
|
-
*
|
179
|
-
* @param {string} signature
|
180
|
-
* @memberof SecurityService
|
181
|
-
*/
|
182
|
-
async verifySignature(signature, publicKey) {
|
183
|
-
try {
|
184
|
-
const result = await _nodeJose.JWS.createVerify(publicKey).verify(signature);
|
185
|
-
const payload = result.payload.toString();
|
186
|
-
return JSON.parse(payload);
|
187
|
-
} catch (error) {
|
188
|
-
new _app.ErrorHandler('Assinatura inválida ou erro durante a verificação', error);
|
189
|
-
}
|
190
|
-
}
|
191
|
-
|
192
|
-
/**
|
193
|
-
* Criptografía de dados utilizando um buffer automático ao invés de chaves
|
194
|
-
*
|
195
|
-
* @param {(string | object)} data
|
196
|
-
* @memberof SecurityService
|
197
|
-
*/
|
198
|
-
simpleEncrypt(data) {
|
199
|
-
if (process.versions.openssl <= '1.0.1f') {
|
200
|
-
throw new Error('OpenSSL Version too old, vulnerability to Heartbleed');
|
201
|
-
}
|
202
|
-
const key = crypto.randomBytes(32);
|
203
|
-
const iv = crypto.randomBytes(16);
|
204
|
-
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
|
205
|
-
let encrypted = cipher.update(data);
|
206
|
-
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
207
|
-
return [iv.toString('hex') + ':' + encrypted.toString('hex'), key];
|
208
|
-
}
|
209
|
-
/**
|
210
|
-
* Utiliza um buffer para descriptografar dados criptografados através de simpleEncrypt()
|
211
|
-
*
|
212
|
-
* @param {string} data
|
213
|
-
* @param {Buffer} key
|
214
|
-
* @memberof SecurityService
|
215
|
-
*/
|
216
|
-
simpleDecrypt(data, key) {
|
217
|
-
try {
|
218
|
-
const textParts = data.split(':');
|
219
|
-
const iv = Buffer.from(textParts.shift(), 'hex');
|
220
|
-
const encryptedText = Buffer.from(textParts.join(':'), 'hex');
|
221
|
-
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
|
222
|
-
let decrypted = decipher.update(encryptedText);
|
223
|
-
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
224
|
-
return decrypted;
|
225
|
-
} catch (error) {
|
226
|
-
new _app.ErrorHandler('Erro durante a descriptografia de dados', error);
|
227
|
-
return false;
|
228
|
-
}
|
229
|
-
}
|
230
|
-
}
|
231
|
-
var _default = exports.default = SecurityService;
|
@@ -1,313 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
4
|
-
value: true
|
5
|
-
});
|
6
|
-
exports.default = void 0;
|
7
|
-
var _sequelize = require("sequelize");
|
8
|
-
var _app = require("../app");
|
9
|
-
var _service = _interopRequireDefault(require("../app/classes/service"));
|
10
|
-
var _models = require("../models");
|
11
|
-
var _DatabaseHost = require("../models/DatabaseHost");
|
12
|
-
var _database = require("../utils/database");
|
13
|
-
var _logger = _interopRequireDefault(require("../utils/logger"));
|
14
|
-
var _security = _interopRequireDefault(require("./security"));
|
15
|
-
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
16
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
17
|
-
|
18
|
-
/**
|
19
|
-
* Serviço de gerênciamento do banco de dados
|
20
|
-
*
|
21
|
-
* @class SequelizeService
|
22
|
-
* @extends {Service}
|
23
|
-
* @deprecated Use {@link DatabaseService}
|
24
|
-
* @implements {IService}
|
25
|
-
*/
|
26
|
-
class SequelizeService extends _service.default {
|
27
|
-
serviceDB;
|
28
|
-
models;
|
29
|
-
connections;
|
30
|
-
initializedModels;
|
31
|
-
initializingdModels;
|
32
|
-
relations;
|
33
|
-
isReconnecting = false; // Flag para evitar múltiplas tentativas simultâneas de reconexão
|
34
|
-
isMasterConnected = false; // Flag para controlar o estado da conexão
|
35
|
-
isServiceConnected = false; // Flag para controlar o estado da conexão
|
36
|
-
|
37
|
-
//# Initialization
|
38
|
-
async onServiceInit() {
|
39
|
-
await super.onServiceInit();
|
40
|
-
if (!this.models) throw new Error('Models are requireds! Call registerModels(modelsArray)');
|
41
|
-
this.serviceDB = _database.serviceDB;
|
42
|
-
this.connections = new Map();
|
43
|
-
this.initializedModels = new Map();
|
44
|
-
this.initializingdModels = new Map();
|
45
|
-
this.relations = new Map();
|
46
|
-
this.models = [...this.models, ..._models.NativeModels];
|
47
|
-
this.startAttemptDelay = 5 * 1000;
|
48
|
-
this.maxStartAttempts = 3;
|
49
|
-
}
|
50
|
-
async onStart() {
|
51
|
-
await super.onStart();
|
52
|
-
if (await this.connectDatabases()) {
|
53
|
-
this.log(`⌛️ Inicializando models`);
|
54
|
-
await this.initModels();
|
55
|
-
this.log(`✅ Models inicializados`);
|
56
|
-
return true;
|
57
|
-
}
|
58
|
-
return false;
|
59
|
-
}
|
60
|
-
async onStartFail() {
|
61
|
-
await super.onStartFail();
|
62
|
-
this.log(`Not possible to connect database`, 'danger');
|
63
|
-
}
|
64
|
-
async connectDatabases() {
|
65
|
-
if (this.isMasterConnected && this.isServiceConnected) return true;
|
66
|
-
if (this.isReconnecting) return false;
|
67
|
-
this.log(`⌛️ Connecting Sequelize to database: ${this.currentStartAttempts}/${this.maxStartAttempts}`);
|
68
|
-
try {
|
69
|
-
if (!this.isServiceConnected) {
|
70
|
-
await this.serviceDB.sync({
|
71
|
-
force: false
|
72
|
-
});
|
73
|
-
this.isServiceConnected = true;
|
74
|
-
this.log('✅ Connected service database sucessfully', 'success');
|
75
|
-
}
|
76
|
-
this.log('✅ All databases connecteds sucessfully', 'success');
|
77
|
-
return true;
|
78
|
-
} catch (error) {
|
79
|
-
(0, _logger.default)().error(error, `Not connected Sequelize to database`);
|
80
|
-
this.isReconnecting = false;
|
81
|
-
return false;
|
82
|
-
}
|
83
|
-
}
|
84
|
-
|
85
|
-
// #Database
|
86
|
-
async getDB(tenantId) {
|
87
|
-
/* master or service */
|
88
|
-
if (tenantId == _app.Core.settings.getDatabase().service.database) {
|
89
|
-
return _database.serviceDB;
|
90
|
-
}
|
91
|
-
const relation = await this.getRelation(tenantId);
|
92
|
-
if (!relation) return false;
|
93
|
-
const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
|
94
|
-
return this.connections.get(key) || (await this.initDB(tenantId));
|
95
|
-
}
|
96
|
-
async createDB(hostUuid, name) {
|
97
|
-
const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
|
98
|
-
if (!host) {
|
99
|
-
this.log('Database host information not found: ' + hostUuid);
|
100
|
-
return false;
|
101
|
-
}
|
102
|
-
const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
|
103
|
-
const connection = await this.createConnection(hostUuid);
|
104
|
-
if (connection) {
|
105
|
-
try {
|
106
|
-
const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
|
107
|
-
if (results.length === 0) {
|
108
|
-
// Se o banco de dados não existir, cria-o
|
109
|
-
await connection.query(`CREATE DATABASE ${dbQueryName};`);
|
110
|
-
this.log(`Database "${dbQueryName}" has been created.`);
|
111
|
-
return true;
|
112
|
-
} else {
|
113
|
-
this.log(`Database "${dbQueryName}" already exists.`);
|
114
|
-
return false;
|
115
|
-
}
|
116
|
-
} catch (error) {
|
117
|
-
new _app.ErrorHandler('Erro on creating database', error);
|
118
|
-
} finally {
|
119
|
-
connection.close();
|
120
|
-
}
|
121
|
-
}
|
122
|
-
return false;
|
123
|
-
}
|
124
|
-
async hasDB(hostUuid, name) {
|
125
|
-
const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
|
126
|
-
if (!host) {
|
127
|
-
this.log('Database host information not found: ' + hostUuid);
|
128
|
-
return false;
|
129
|
-
}
|
130
|
-
const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
|
131
|
-
const connection = await this.createConnection(hostUuid);
|
132
|
-
if (connection) {
|
133
|
-
try {
|
134
|
-
const [results] = await connection.query(`SHOW DATABASES LIKE '${dbQueryName}';`);
|
135
|
-
return results.length > 0;
|
136
|
-
} catch (error) {
|
137
|
-
new _app.ErrorHandler('Erro on creating database', error);
|
138
|
-
} finally {
|
139
|
-
connection.close();
|
140
|
-
}
|
141
|
-
}
|
142
|
-
return false;
|
143
|
-
}
|
144
|
-
async deleteDB(hostUuid, name) {
|
145
|
-
const dbQueryName = `${_app.Core.settings.getDatabase().service.database}_${name}`;
|
146
|
-
const connection = await this.createConnection(hostUuid);
|
147
|
-
if (connection) {
|
148
|
-
try {
|
149
|
-
await connection.query(`DROP DATABASE IF EXISTS ${dbQueryName};`);
|
150
|
-
this.log(`Database "${dbQueryName}" has been deleted.`);
|
151
|
-
return true;
|
152
|
-
} catch (error) {
|
153
|
-
return false;
|
154
|
-
} finally {
|
155
|
-
connection.close();
|
156
|
-
}
|
157
|
-
}
|
158
|
-
return false;
|
159
|
-
}
|
160
|
-
async initDB(tenantId) {
|
161
|
-
let connection = false;
|
162
|
-
if (tenantId == _app.Core.settings.getDatabase().service.database) {
|
163
|
-
connection = _database.serviceDB;
|
164
|
-
} else {
|
165
|
-
const relation = await this.getRelation(tenantId);
|
166
|
-
if (!relation) return false;
|
167
|
-
const dbName = this.getDBName(relation.envToken);
|
168
|
-
const key = `${relation.hostUuid}@${this.getDBName(relation.envToken)}`;
|
169
|
-
if (this.connections.has(key)) return this.connections.get(key);
|
170
|
-
connection = await this.createConnection(relation.hostUuid, dbName);
|
171
|
-
if (connection) {
|
172
|
-
this.log(`✅ Connected ${dbName} database sucessfully`, 'success');
|
173
|
-
this.connections.set(key, connection);
|
174
|
-
}
|
175
|
-
}
|
176
|
-
if (connection) {
|
177
|
-
await this.initModelsByConnection(tenantId, connection);
|
178
|
-
}
|
179
|
-
return connection;
|
180
|
-
}
|
181
|
-
async initModelsByConnection(tenantId, connection) {
|
182
|
-
const entities = [];
|
183
|
-
await Promise.all(this.models.map(async model => {
|
184
|
-
const modelKey = `${tenantId}#${model.name}`;
|
185
|
-
const entity = model.initialize(connection);
|
186
|
-
await entity.sync();
|
187
|
-
entities.push(entity);
|
188
|
-
this.initializedModels.set(modelKey, entity);
|
189
|
-
}));
|
190
|
-
await Promise.all(this.models.map(async model => {
|
191
|
-
model.associate(entities);
|
192
|
-
}));
|
193
|
-
}
|
194
|
-
getDBName(envToken) {
|
195
|
-
return `${_app.Core.settings.getDatabase().service.database}_${envToken}`;
|
196
|
-
}
|
197
|
-
|
198
|
-
//#Connection
|
199
|
-
reconnect(db, attempts = 2) {
|
200
|
-
db.sync().then(() => {
|
201
|
-
this.log('Database pronto', 'success');
|
202
|
-
}).catch(reason => {
|
203
|
-
this.log('Attemping to connect master database', 'warning');
|
204
|
-
(0, _logger.default)().warn('Erro ao inicializar o banco de dados, tentando novamente...', reason);
|
205
|
-
if (attempts > 0) {
|
206
|
-
setTimeout(() => this.reconnect(db, attempts - 1), 5000);
|
207
|
-
} else {
|
208
|
-
new _app.ErrorHandler('Error on connecting master database', reason);
|
209
|
-
}
|
210
|
-
});
|
211
|
-
}
|
212
|
-
async createConnection(hostUuid, database) {
|
213
|
-
const host = await _DatabaseHost.DatabaseHost.findByPk(hostUuid);
|
214
|
-
if (!host) {
|
215
|
-
this.log('createConnection:: Database host information not found: ' + hostUuid);
|
216
|
-
return false;
|
217
|
-
}
|
218
|
-
const key = await _security.default.singleton().loadKeyByStr(host.credential);
|
219
|
-
const data = await _security.default.singleton().verifySignature(host.password, key);
|
220
|
-
if (!data) {
|
221
|
-
this.log('createConnection::Error on decript password by credential: ' + hostUuid, 'danger');
|
222
|
-
return false;
|
223
|
-
}
|
224
|
-
const password = data.payload;
|
225
|
-
const queryHost = host.host.split(':');
|
226
|
-
const sequelize = new _sequelize.Sequelize({
|
227
|
-
host: queryHost[0],
|
228
|
-
port: Number(queryHost[1]),
|
229
|
-
dialect: host.dialect,
|
230
|
-
database,
|
231
|
-
username: host.username,
|
232
|
-
password: password,
|
233
|
-
define: {
|
234
|
-
timestamps: true
|
235
|
-
},
|
236
|
-
timezone: '-03:00',
|
237
|
-
logging: _app.Core.settings.getDatabase().service.log
|
238
|
-
});
|
239
|
-
return new Promise((resolve, reject) => {
|
240
|
-
sequelize.authenticate().then(async () => {
|
241
|
-
resolve(sequelize);
|
242
|
-
}).catch(reason => {
|
243
|
-
reject(reason);
|
244
|
-
});
|
245
|
-
});
|
246
|
-
}
|
247
|
-
async testConnection(data) {
|
248
|
-
const sequelize = new _sequelize.Sequelize({
|
249
|
-
host: data.host,
|
250
|
-
port: data.port,
|
251
|
-
username: data.username,
|
252
|
-
password: data.password,
|
253
|
-
dialect: data.dialect,
|
254
|
-
timezone: '-03:00',
|
255
|
-
pool: _app.Core.settings.getDatabase().service.pool,
|
256
|
-
logging: _app.Core.settings.getDatabase().service.log
|
257
|
-
});
|
258
|
-
return new Promise(resolve => {
|
259
|
-
sequelize.authenticate().then(async () => {
|
260
|
-
resolve(true);
|
261
|
-
}).catch(reason => {
|
262
|
-
new _app.ErrorHandler('teste de conexão falhou', reason);
|
263
|
-
resolve(false);
|
264
|
-
}).finally(() => {
|
265
|
-
sequelize.close();
|
266
|
-
});
|
267
|
-
});
|
268
|
-
}
|
269
|
-
|
270
|
-
//# Common
|
271
|
-
async getRelation(tenantId) {
|
272
|
-
let relation;
|
273
|
-
/* fetch relation */
|
274
|
-
if (this.relations.get(tenantId)) {
|
275
|
-
relation = this.relations.get(tenantId);
|
276
|
-
} else {
|
277
|
-
relation = await _models.EnvDBHost.findOne({
|
278
|
-
where: {
|
279
|
-
envUuid: tenantId
|
280
|
-
}
|
281
|
-
});
|
282
|
-
if (relation) {
|
283
|
-
this.relations.set(tenantId, relation);
|
284
|
-
}
|
285
|
-
}
|
286
|
-
return relation;
|
287
|
-
}
|
288
|
-
|
289
|
-
// #Entity
|
290
|
-
async getModel(model, tenantId) {
|
291
|
-
try {
|
292
|
-
const modelKey = `${tenantId}#${model.name}`;
|
293
|
-
if (!this.initializedModels.has(modelKey)) {
|
294
|
-
await this.initDB(tenantId);
|
295
|
-
}
|
296
|
-
return this.initializedModels.get(modelKey);
|
297
|
-
} catch (error) {
|
298
|
-
throw new _app.ErrorHandler('Erro ao obter o model', error);
|
299
|
-
}
|
300
|
-
}
|
301
|
-
static registerModels(models) {
|
302
|
-
this.getService().models = models;
|
303
|
-
}
|
304
|
-
async initModels() {
|
305
|
-
const tenants = await _models.EnvDBHost.findAll({
|
306
|
-
attributes: ['envUuid']
|
307
|
-
});
|
308
|
-
for (const model of this.models) {
|
309
|
-
await Promise.all(tenants.map(async t => await this.getModel(model, t.envUuid)));
|
310
|
-
}
|
311
|
-
}
|
312
|
-
}
|
313
|
-
var _default = exports.default = SequelizeService;
|
package/lib/services/socket.js
DELETED
@@ -1,123 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
4
|
-
value: true
|
5
|
-
});
|
6
|
-
exports.default = void 0;
|
7
|
-
var _socket = require("socket.io");
|
8
|
-
var _service = _interopRequireDefault(require("../app/classes/service"));
|
9
|
-
var _controller = require("../app/controller");
|
10
|
-
var _core = require("../contracts/core");
|
11
|
-
var _authentication = require("../middlewares/authentication");
|
12
|
-
var _express = _interopRequireDefault(require("./express"));
|
13
|
-
var _utils = require("../utils");
|
14
|
-
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
15
|
-
/**
|
16
|
-
* Serviço de gerênciamento de comunicação WS/WSS Socket
|
17
|
-
*
|
18
|
-
* @class SocketIOService
|
19
|
-
* @extends {Service}
|
20
|
-
* @implements {IService}
|
21
|
-
*/
|
22
|
-
class SocketIOService extends _service.default {
|
23
|
-
server;
|
24
|
-
mainRouter;
|
25
|
-
eventhandlers;
|
26
|
-
clientHandlers = [];
|
27
|
-
async onServiceClusterInit() {
|
28
|
-
await super.onServiceClusterInit();
|
29
|
-
if (!this.mainRouter) throw new Error('Need router'); //!sem router
|
30
|
-
|
31
|
-
this.eventhandlers = new Map();
|
32
|
-
}
|
33
|
-
async onExodusClusterStarted() {
|
34
|
-
await super.onExodusClusterStarted();
|
35
|
-
//! este depende de ExpressService para iniciar, por isso está aqui
|
36
|
-
|
37
|
-
try {
|
38
|
-
this.createSocket(_express.default.getService().getHttpServer());
|
39
|
-
await this.registerHandlers();
|
40
|
-
this.server.on('connection', this.onConnection.bind(this));
|
41
|
-
this.log('✅ Socket server created');
|
42
|
-
} catch (error) {
|
43
|
-
(0, _utils.logger)().error(error, `Not connected to SocketIO`);
|
44
|
-
}
|
45
|
-
}
|
46
|
-
async onConnection(socket) {
|
47
|
-
this.log(`${socket.id} conectado`);
|
48
|
-
const request = new _controller.SocketRequest(socket);
|
49
|
-
const eventsH = Array.from(this.eventhandlers.values());
|
50
|
-
const clientsH = await Promise.all(this.clientHandlers.map(async E => {
|
51
|
-
const handler = new E();
|
52
|
-
await handler.onInit(request);
|
53
|
-
return handler;
|
54
|
-
}));
|
55
|
-
clientsH.forEach(handler => handler.onConnect());
|
56
|
-
const onAny = (event, ...args) => clientsH.forEach(handler => handler.onEvent(event, args));
|
57
|
-
socket.onAny(onAny);
|
58
|
-
eventsH.forEach(handlers => {
|
59
|
-
handlers.forEach(handler => handler.onConnect(request));
|
60
|
-
});
|
61
|
-
socket.on('disconnect', () => {
|
62
|
-
this.log(`${socket.id} desconectado`);
|
63
|
-
eventsH.forEach(handlers => {
|
64
|
-
handlers.forEach(handler => handler.onDisconnect(request));
|
65
|
-
});
|
66
|
-
clientsH.forEach(handler => handler.onDisconnect());
|
67
|
-
socket.offAny(onAny);
|
68
|
-
});
|
69
|
-
this.bindEvents(socket);
|
70
|
-
}
|
71
|
-
bindEvents(socket) {
|
72
|
-
const request = new _controller.SocketRequest(socket);
|
73
|
-
const handlers = Array.from(this.eventhandlers.entries());
|
74
|
-
for (const group of handlers) {
|
75
|
-
const event = group[0];
|
76
|
-
const handlers = group[1].filter(handler => {
|
77
|
-
let isSameSide = false;
|
78
|
-
switch (handler.getSide()) {
|
79
|
-
case _core.eExecutionSide.CLUSTER:
|
80
|
-
if (this.isCluster()) isSameSide = true;
|
81
|
-
break;
|
82
|
-
case _core.eExecutionSide.MASTER:
|
83
|
-
if (this.isMaster()) isSameSide = true;
|
84
|
-
break;
|
85
|
-
case _core.eExecutionSide.ANY:
|
86
|
-
isSameSide = true;
|
87
|
-
break;
|
88
|
-
}
|
89
|
-
return handler.getActive() && isSameSide;
|
90
|
-
});
|
91
|
-
socket.on(event, (...args) => {
|
92
|
-
handlers.forEach(handler => {
|
93
|
-
handler.onEvent(request, ...args);
|
94
|
-
});
|
95
|
-
});
|
96
|
-
}
|
97
|
-
}
|
98
|
-
createSocket(app, cors = {
|
99
|
-
origin: '*'
|
100
|
-
}) {
|
101
|
-
this.server = new _socket.Server(app, {
|
102
|
-
cors
|
103
|
-
});
|
104
|
-
const middleware = new _authentication.SocketAuthenticationMiddleware();
|
105
|
-
this.server.use(middleware.decryptToken);
|
106
|
-
}
|
107
|
-
static registerRouter(router) {
|
108
|
-
this.getService().mainRouter = router;
|
109
|
-
}
|
110
|
-
static registerClientHandlers(handlers) {
|
111
|
-
this.getService().clientHandlers = handlers;
|
112
|
-
}
|
113
|
-
async registerHandlers() {
|
114
|
-
return Promise.all(this.mainRouter.map(async handler => {
|
115
|
-
handler.onInit();
|
116
|
-
const event = handler.getEvent();
|
117
|
-
const group = this.eventhandlers.get(event) || [];
|
118
|
-
group.push(handler);
|
119
|
-
this.eventhandlers.set(event, group);
|
120
|
-
}));
|
121
|
-
}
|
122
|
-
}
|
123
|
-
var _default = exports.default = SocketIOService;
|
@@ -1,17 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
4
|
-
value: true
|
5
|
-
});
|
6
|
-
exports.default = void 0;
|
7
|
-
var _app = require("../../app");
|
8
|
-
class TaskServiceBase extends _app.Service {
|
9
|
-
tasks = [];
|
10
|
-
static setTaskPath(path) {
|
11
|
-
this.getService().jobsPath = path;
|
12
|
-
}
|
13
|
-
static registerTask(task) {
|
14
|
-
this.getService().tasks.push(task);
|
15
|
-
}
|
16
|
-
}
|
17
|
-
var _default = exports.default = TaskServiceBase;
|