@oondemand/oon-core-back 0.3.3 → 0.3.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oondemand/oon-core-back",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/oondemand/oon-platform.git",
@@ -27,6 +27,7 @@ const { getAppCode, getBaseUrl } = require("../core/utils/activationProvider");
27
27
 
28
28
  const router = express.Router();
29
29
  const attempts = new Map();
30
+ const DEV_LOCAL_PATH = "/integracao/dev-local/ativar-central";
30
31
 
31
32
  function rateLimit(req, res, next) {
32
33
  const key = req.ip || "local";
@@ -111,6 +112,46 @@ function requireRootBootstrapResult(result) {
111
112
  };
112
113
  }
113
114
 
115
+ function readBasicAuthorization(req) {
116
+ const authorization = String(req.headers.authorization || "");
117
+ if (!authorization.startsWith("Basic ")) {
118
+ throw new GenericError("Informe e-mail e senha para ativar a Central.", {
119
+ statusCode: 401,
120
+ });
121
+ }
122
+ return authorization;
123
+ }
124
+
125
+ function translateProviderActivationError(error, fallback) {
126
+ if (error instanceof GenericError) return error;
127
+
128
+ const timedOut = error.code === "ECONNABORTED";
129
+ const statusCode = timedOut ? 504 : error.response?.status || 502;
130
+ const message =
131
+ error.response?.data?.message ||
132
+ error.response?.data?.error?.message ||
133
+ (timedOut
134
+ ? "A Central de Ativações não respondeu dentro do prazo."
135
+ : fallback);
136
+
137
+ return new GenericError(message, { statusCode });
138
+ }
139
+
140
+ function idOf(value) {
141
+ return value?.id || value?._id || value;
142
+ }
143
+
144
+ function summarizeDevInstance(data, appCode) {
145
+ const appId = idOf(data?.app);
146
+ return {
147
+ instanceId: `dev-local:${appId || appCode}`,
148
+ instanceCode: "dev-local",
149
+ appId: appId ? String(appId) : undefined,
150
+ tenantId: idOf(data?.tenant) ? String(idOf(data.tenant)) : undefined,
151
+ licencaId: idOf(data?.licenca) ? String(idOf(data.licenca)) : undefined,
152
+ };
153
+ }
154
+
114
155
  router.use(rateLimit);
115
156
 
116
157
  router.get(
@@ -172,7 +213,8 @@ router.get(
172
213
  });
173
214
  }
174
215
 
175
- const host = new URL(getBaseUrl(req)).hostname;
216
+ const centralAtivacaoUrl = getBaseUrl(req);
217
+ const host = new URL(centralAtivacaoUrl).hostname;
176
218
  return sendResponse({
177
219
  res,
178
220
  mode: "member-activation",
@@ -184,12 +226,14 @@ router.get(
184
226
  ...globalDefaults,
185
227
  ambiente: ambiente(),
186
228
  urlPublica: publicUrl(req),
229
+ nomeInstancia: ctx.config.name || ctx.config.slug || getAppCode(),
187
230
  },
188
231
  technical: {
189
232
  appCode: getAppCode(),
190
233
  ambiente: ambiente(),
191
234
  ecosystemRole: "member",
192
235
  centralAtivacaoHost: host,
236
+ centralAtivacaoUrl,
193
237
  },
194
238
  });
195
239
  }),
@@ -288,6 +332,149 @@ router.post(
288
332
  }),
289
333
  );
290
334
 
335
+ router.post(
336
+ "/ativar-dev-local",
337
+ asyncHandler(async (req, res) => {
338
+ assertMember();
339
+
340
+ if (ambiente() !== "desenvolvimento") {
341
+ throw new GenericError(
342
+ "A ativação self-service está disponível somente em desenvolvimento.",
343
+ { statusCode: 403 },
344
+ );
345
+ }
346
+
347
+ const authorization = readBasicAuthorization(req);
348
+ const config = activationConfig();
349
+ const instance = await ensureInstance();
350
+
351
+ if (instance.status === "ativa") {
352
+ throw new GenericError("Instância já ativada.", { statusCode: 409 });
353
+ }
354
+
355
+ if (!["nao_ativada", "validando", "erro"].includes(instance.status)) {
356
+ throw new GenericError(
357
+ "Instância não pode ser ativada neste estado.",
358
+ { statusCode: 409 },
359
+ );
360
+ }
361
+
362
+ const appCode = getAppCode();
363
+ const nomeCentral =
364
+ req.body?.nomeCentral ||
365
+ req.body?.appName ||
366
+ ctx.config.name ||
367
+ ctx.config.slug ||
368
+ appCode;
369
+ const urlPublica = req.body?.urlPublica || publicUrl(req);
370
+
371
+ event("DEV_LOCAL_ACTIVATION_STARTED", {
372
+ correlationId: req.correlationId,
373
+ appCode,
374
+ });
375
+
376
+ try {
377
+ const response = await providerPost(
378
+ req,
379
+ DEV_LOCAL_PATH,
380
+ {
381
+ appCode,
382
+ codigoApp: appCode,
383
+ nomeCentral,
384
+ appName: req.body?.appName || nomeCentral,
385
+ appSlug: req.body?.appSlug || ctx.config.slug || appCode,
386
+ ambiente: "desenvolvimento",
387
+ urlPublica,
388
+ repositorio: req.body?.repositorio,
389
+ branch: req.body?.branch,
390
+ nomeUsuario: req.body?.nomeUsuario,
391
+ nomeTenant: req.body?.nomeTenant,
392
+ },
393
+ { Authorization: authorization },
394
+ );
395
+
396
+ const data = response.data || {};
397
+ assertApp(data);
398
+
399
+ const resolvedAppCode = String(
400
+ data.app?.codigo || data.appCode || appCode,
401
+ ).toLowerCase();
402
+ const ids = summarizeDevInstance(data, resolvedAppCode);
403
+ const now = new Date();
404
+
405
+ Object.assign(instance, {
406
+ status: "ativa",
407
+ ecosystemRole: "member",
408
+ instanceId: ids.instanceId,
409
+ instanceCode: ids.instanceCode,
410
+ appCode: resolvedAppCode,
411
+ appId: ids.appId,
412
+ tenantId: ids.tenantId,
413
+ licencaId: ids.licencaId,
414
+ ambiente: "desenvolvimento",
415
+ nomeInstancia: nomeCentral,
416
+ ecosystemUrl: getBaseUrl(req),
417
+ publicUrl: urlPublica,
418
+ coreVersion: process.env.npm_package_version || "0.0.0",
419
+ appVersion: process.env.SERVICE_VERSION || "0.1.0",
420
+ credentialEncrypted: undefined,
421
+ credentialIv: undefined,
422
+ credentialAuthTag: undefined,
423
+ credentialVersion: undefined,
424
+ tenant: data.tenant,
425
+ app: data.app,
426
+ licenca: data.licenca,
427
+ parametrosGlobais: {
428
+ ...globalDefaults,
429
+ nomeInstancia: nomeCentral,
430
+ ambiente: "desenvolvimento",
431
+ urlPublica,
432
+ },
433
+ parametrosAplicacao: {
434
+ devLocal: true,
435
+ },
436
+ configurationVersion: config.configurationVersion,
437
+ ativadaEm: now,
438
+ concluidaEm: now,
439
+ ultimaValidacaoEm: now,
440
+ ultimoErro: undefined,
441
+ });
442
+
443
+ await instance.save();
444
+
445
+ event("DEV_LOCAL_ACTIVATION_COMPLETED", {
446
+ correlationId: req.correlationId,
447
+ appCode: resolvedAppCode,
448
+ });
449
+
450
+ sendResponse({
451
+ res,
452
+ statusCode: 201,
453
+ ...data,
454
+ message: data.message || "Central ativada em desenvolvimento local.",
455
+ sucesso: true,
456
+ status: "ativa",
457
+ instanceId: instance.instanceId,
458
+ });
459
+ } catch (error) {
460
+ instance.status = "erro";
461
+ instance.ultimoErro = error.response?.data?.message || error.message;
462
+ await instance.save();
463
+
464
+ event("DEV_LOCAL_ACTIVATION_FAILED", {
465
+ correlationId: req.correlationId,
466
+ appCode,
467
+ status: error.response?.status,
468
+ });
469
+
470
+ throw translateProviderActivationError(
471
+ error,
472
+ "Não foi possível ativar a Central em desenvolvimento local.",
473
+ );
474
+ }
475
+ }),
476
+ );
477
+
291
478
  router.post(
292
479
  "/validar-codigo",
293
480
  asyncHandler(async (req, res) => {
@@ -1,15 +1,21 @@
1
1
  const GenericError = require("../errors/GenericError");
2
+ const ctx = require("../context");
2
3
 
4
+ const DEFAULT_CENTRAL_ATIVACAO_URL =
5
+ "https://central-ativacao.central.oondemand.online";
3
6
  const LOGIN_PATH = "/integracao/autenticacao-aplicativos/autenticar";
4
7
  const PERMISSION_PATH = "/integracao/autenticacao-aplicativos/verificar-permissao";
5
8
 
9
+ function readCentralActivationUrl() {
10
+ return (
11
+ process.env.CENTRAL_ATIVACAO_URL ||
12
+ process.env.MEUS_APPS_BACKEND_URL ||
13
+ DEFAULT_CENTRAL_ATIVACAO_URL
14
+ );
15
+ }
16
+
6
17
  function getBaseUrl(req) {
7
- const value = process.env.CENTRAL_ATIVACAO_URL || process.env.MEUS_APPS_BACKEND_URL;
8
- if (!value) {
9
- throw new GenericError("CENTRAL_ATIVACAO_URL não configurada.", {
10
- statusCode: 500,
11
- });
12
- }
18
+ const value = readCentralActivationUrl();
13
19
 
14
20
  let parsed;
15
21
  try {
@@ -47,6 +53,9 @@ function getAppCode() {
47
53
  process.env.APP_CODIGO ||
48
54
  process.env.OON_APP_CODE ||
49
55
  process.env.OON_APP_CODIGO ||
56
+ ctx.config.appCode ||
57
+ ctx.config.appCodigo ||
58
+ ctx.config.slug ||
50
59
  "",
51
60
  )
52
61
  .trim()
@@ -66,6 +75,7 @@ function getTimeout() {
66
75
  }
67
76
 
68
77
  module.exports = {
78
+ DEFAULT_CENTRAL_ATIVACAO_URL,
69
79
  LOGIN_PATH,
70
80
  PERMISSION_PATH,
71
81
  getBaseUrl,