exodus-framework 2.0.955 → 2.0.956

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 (105) hide show
  1. package/lib/app/classes/broadcast.js +79 -0
  2. package/lib/app/classes/cache.js +94 -0
  3. package/lib/app/classes/communication.js +99 -0
  4. package/lib/app/classes/communicationcontext.js +1 -0
  5. package/lib/app/classes/event.js +94 -0
  6. package/lib/app/classes/index.js +105 -0
  7. package/lib/app/classes/managed.js +145 -0
  8. package/lib/app/classes/service.js +232 -0
  9. package/lib/app/classes/servicemodel.js +22 -0
  10. package/lib/app/classes/singleton.js +26 -0
  11. package/lib/app/classes/socket/clienthandler.js +54 -0
  12. package/lib/app/classes/socket/eventhandler.js +51 -0
  13. package/lib/app/classes/socket/index.js +20 -0
  14. package/lib/app/classes/system.js +49 -0
  15. package/lib/app/controller.js +97 -0
  16. package/lib/app/core.js +47 -0
  17. package/lib/app/error.js +66 -0
  18. package/lib/app/exodus.js +97 -0
  19. package/lib/app/index.js +68 -0
  20. package/lib/app/settings.js +161 -0
  21. package/lib/certificates/private_key.pem +27 -0
  22. package/lib/certificates/public_key.pem +9 -0
  23. package/lib/contracts/communication/communication.js +39 -0
  24. package/lib/contracts/communication/index.js +27 -0
  25. package/lib/contracts/communication/operation.js +5 -0
  26. package/lib/contracts/console.js +5 -0
  27. package/lib/contracts/contansts.js +13 -0
  28. package/lib/contracts/core.js +12 -0
  29. package/lib/contracts/entity.js +5 -0
  30. package/lib/contracts/http.js +52 -0
  31. package/lib/contracts/index.js +104 -0
  32. package/lib/contracts/messaging.js +50 -0
  33. package/lib/contracts/security.js +5 -0
  34. package/lib/contracts/service.js +11 -0
  35. package/lib/contracts/session.js +5 -0
  36. package/lib/contracts/settings.js +5 -0
  37. package/lib/contracts/singleton.js +5 -0
  38. package/lib/contracts/socket.js +11 -0
  39. package/lib/contracts/tasks.js +1 -0
  40. package/lib/controllers/api/file.js +24 -0
  41. package/lib/controllers/api/index.js +13 -0
  42. package/lib/controllers/api/log.js +55 -0
  43. package/lib/controllers/api/report.js +55 -0
  44. package/lib/controllers/index.js +16 -0
  45. package/lib/controllers/messaging/application.js +75 -0
  46. package/lib/controllers/messaging/database.js +64 -0
  47. package/lib/controllers/messaging/environment.js +111 -0
  48. package/lib/express.d.js +5 -0
  49. package/lib/index.js +104 -0
  50. package/lib/middlewares/access.js +114 -0
  51. package/lib/middlewares/authentication.js +104 -0
  52. package/lib/middlewares/file.js +41 -0
  53. package/lib/middlewares/index.js +36 -0
  54. package/lib/models/Application.js +65 -0
  55. package/lib/models/DatabaseHost.js +62 -0
  56. package/lib/models/EnvConnection.js +41 -0
  57. package/lib/models/Log.js +67 -0
  58. package/lib/models/Report.js +65 -0
  59. package/lib/models/System.js +54 -0
  60. package/lib/models/index.js +82 -0
  61. package/lib/routes/api/index.js +16 -0
  62. package/lib/routes/api/v1/index.js +38 -0
  63. package/lib/routes/api/v1/logs.js +19 -0
  64. package/lib/routes/api/v1/report.js +19 -0
  65. package/lib/routes/api/v1/sse.js +36 -0
  66. package/lib/routes/index.js +27 -0
  67. package/lib/routes/messaging/index.js +34 -0
  68. package/lib/services/database.js +136 -0
  69. package/lib/services/ecosystem.js +46 -0
  70. package/lib/services/express.js +162 -0
  71. package/lib/services/file.js +65 -0
  72. package/lib/services/file_new.js +136 -0
  73. package/lib/services/index.js +108 -0
  74. package/lib/services/log.js +26 -0
  75. package/lib/services/rabitmq.js +187 -0
  76. package/lib/services/redis.js +84 -0
  77. package/lib/services/security.js +231 -0
  78. package/lib/services/sequelize.js +313 -0
  79. package/lib/services/socket.js +123 -0
  80. package/lib/services/task/TaskServiceBase.js +17 -0
  81. package/lib/services/task/index.js +40 -0
  82. package/lib/services/task/queue/QueueService.js +48 -0
  83. package/lib/services/task/queue/QueueTask.js +134 -0
  84. package/lib/services/task/queue/SingleQueue.js +68 -0
  85. package/lib/services/task/queue/index.js +27 -0
  86. package/lib/services/task/scheduler/SchedulerService.js +31 -0
  87. package/lib/services/task/scheduler/SchedulerTask.js +211 -0
  88. package/lib/services/task/scheduler/index.js +20 -0
  89. package/lib/services/test.js +27 -0
  90. package/lib/socket.d.js +3 -0
  91. package/lib/tasks/index.js +27 -0
  92. package/lib/tasks/queue/application.js +44 -0
  93. package/lib/tasks/queue/environment.js +92 -0
  94. package/lib/tasks/queue/index.js +20 -0
  95. package/lib/tasks/queue/teste.js +21 -0
  96. package/lib/tasks/schedule/index.js +13 -0
  97. package/lib/tasks/schedule/restart.js +19 -0
  98. package/lib/tasks/schedule/teste.js +61 -0
  99. package/lib/utils/api.js +65 -0
  100. package/lib/utils/database.js +157 -0
  101. package/lib/utils/date.js +28 -0
  102. package/lib/utils/index.js +60 -0
  103. package/lib/utils/logger.js +51 -0
  104. package/lib/utils/session.js +23 -0
  105. package/package.json +1 -1
@@ -0,0 +1,231 @@
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;
@@ -0,0 +1,313 @@
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.mainDb;
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().main.database) {
89
+ return _database.mainDb;
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().main.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().main.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().main.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().main.database) {
163
+ connection = _database.mainDb;
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().main.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;
@@ -0,0 +1,123 @@
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;
@@ -0,0 +1,17 @@
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;