rl-core-api 0.1.0 → 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rodrigo Liberti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -69,6 +69,22 @@ O pacote **não traz `.env`** — ele declara o que precisa e quebra no boot se
69
69
  faltar. Cada projeto tem os valores dele (banco próprio, segredo JWT próprio).
70
70
  Comece pelo `.env.example` do repositório.
71
71
 
72
+ ### Identidade do sistema
73
+
74
+ O core não tem nome próprio. `APP_NAME` é o do projeto, e dele saem o título do
75
+ Swagger, o remetente dos emails e o emissor exibido no app autenticador:
76
+
77
+ | Variável | Para quê | Sem declarar |
78
+ |---|---|---|
79
+ | `APP_NAME` | Nome do sistema | `Core App` |
80
+ | `APP_LOGO_URL` | Logo no cabeçalho dos emails — **URL absoluta e pública**, porque o cliente de email busca a imagem do servidor dele | só o nome, em texto |
81
+ | `APP_BRAND_COLOR` | Cor dos botões e do cabeçalho dos emails (`#RRGGBB`) | `#007bff` |
82
+ | `TOTP_ISSUER` | Emissor no app autenticador | segue o `APP_NAME` |
83
+ | `EMAIL_FROM_NAME` | Nome do remetente | segue o `APP_NAME` |
84
+
85
+ Quem já declarava `TOTP_ISSUER` ou `EMAIL_FROM_NAME` continua igual: eles só
86
+ caem no `APP_NAME` quando estão ausentes.
87
+
72
88
  Para acrescentar variáveis suas, estenda o schema:
73
89
 
74
90
  ```ts
@@ -94,6 +110,11 @@ sozinho.
94
110
  | [`rl-core-front`](https://www.npmjs.com/package/rl-core-front) | as telas em Next.js |
95
111
  | `rl_core_app` | o app Flutter, consumido por tag do git |
96
112
 
113
+ ## Changelog
114
+
115
+ As três versões andam juntas e saem de uma tag só — o que mudou em cada uma
116
+ está em [CHANGELOG.md](https://github.com/liberti1991/aplication-core/blob/main/CHANGELOG.md).
117
+
97
118
  ## Licença
98
119
 
99
120
  MIT © Rodrigo Liberti
@@ -45,9 +45,10 @@ const bootstrapCore = async (appModule, options = {}) => {
45
45
  transformOptions: { enableImplicitConversion: true },
46
46
  }));
47
47
  app.useGlobalInterceptors(new common_1.ClassSerializerInterceptor(app.get(core_1.Reflector)));
48
+ const appName = options.title ?? env.get("APP_NAME");
48
49
  if (env.get("NODE_ENV") !== "production") {
49
50
  const config = new swagger_1.DocumentBuilder()
50
- .setTitle(options.title ?? "Core API")
51
+ .setTitle(appName)
51
52
  .setDescription(options.description ?? "Auth + 2FA obrigatório (TOTP) + RBAC + auditoria")
52
53
  .setVersion(options.version ?? "1.0")
53
54
  .addBearerAuth()
@@ -58,7 +59,7 @@ const bootstrapCore = async (appModule, options = {}) => {
58
59
  }
59
60
  const port = env.get("PORT");
60
61
  await app.listen(port);
61
- logger.log(`${options.title ?? "Core API"} rodando em http://localhost:${port}/${prefix}`);
62
+ logger.log(`${appName} rodando em http://localhost:${port}/${prefix}`);
62
63
  if (env.get("NODE_ENV") !== "production") {
63
64
  logger.log(`Swagger em http://localhost:${port}/${prefix}/docs`);
64
65
  }
@@ -0,0 +1,7 @@
1
+ export interface AppBrand {
2
+ name: string;
3
+ logoUrl: string | null;
4
+ color: string;
5
+ totpIssuer: string;
6
+ emailFromName: string;
7
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -8,6 +8,9 @@ export declare const envSchema: z.ZodObject<{
8
8
  PORT: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
9
9
  API_PREFIX: z.ZodDefault<z.ZodString>;
10
10
  APP_URL: z.ZodDefault<z.ZodString>;
11
+ APP_NAME: z.ZodDefault<z.ZodString>;
12
+ APP_LOGO_URL: z.ZodOptional<z.ZodString>;
13
+ APP_BRAND_COLOR: z.ZodDefault<z.ZodString>;
11
14
  DB_HOST: z.ZodString;
12
15
  DB_PORT: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
13
16
  DB_NAME: z.ZodString;
@@ -32,7 +35,7 @@ export declare const envSchema: z.ZodObject<{
32
35
  false: "false";
33
36
  }>, z.ZodTransform<boolean, "true" | "false">>>;
34
37
  COOKIE_DOMAIN: z.ZodDefault<z.ZodString>;
35
- TOTP_ISSUER: z.ZodDefault<z.ZodString>;
38
+ TOTP_ISSUER: z.ZodOptional<z.ZodString>;
36
39
  TWO_FACTOR_EMAIL_CODE_EXPIRY: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
37
40
  BACKUP_CODES_COUNT: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
38
41
  LOGIN_MAX_ATTEMPTS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
@@ -49,7 +52,7 @@ export declare const envSchema: z.ZodObject<{
49
52
  EMAIL_USER: z.ZodString;
50
53
  EMAIL_PASSWORD: z.ZodString;
51
54
  EMAIL_FROM: z.ZodString;
52
- EMAIL_FROM_NAME: z.ZodDefault<z.ZodString>;
55
+ EMAIL_FROM_NAME: z.ZodOptional<z.ZodString>;
53
56
  PASSWORD_RESET_TOKEN_EXPIRY: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
54
57
  FIRST_ACCESS_TOKEN_EXPIRY: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
55
58
  PASSWORD_MAX_AGE_DAYS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
@@ -14,6 +14,12 @@ exports.envSchema = zod_1.z
14
14
  PORT: zod_1.z.coerce.number().int().positive().default(3108),
15
15
  API_PREFIX: zod_1.z.string().default("api"),
16
16
  APP_URL: zod_1.z.string().url().default("http://localhost:4000"),
17
+ APP_NAME: zod_1.z.string().min(1).default("Core App"),
18
+ APP_LOGO_URL: zod_1.z.string().url().optional(),
19
+ APP_BRAND_COLOR: zod_1.z
20
+ .string()
21
+ .regex(/^#[0-9a-fA-F]{6}$/, "APP_BRAND_COLOR deve ser hex (#RRGGBB)")
22
+ .default("#007bff"),
17
23
  DB_HOST: zod_1.z.string().min(1),
18
24
  DB_PORT: zod_1.z.coerce.number().int().positive().default(3306),
19
25
  DB_NAME: zod_1.z.string().min(1),
@@ -35,7 +41,7 @@ exports.envSchema = zod_1.z
35
41
  .length(64, "TOTP_ENC_KEY deve ter 64 chars hex (32 bytes)"),
36
42
  COOKIE_SECURE: booleanFromString.default(false),
37
43
  COOKIE_DOMAIN: zod_1.z.string().default("localhost"),
38
- TOTP_ISSUER: zod_1.z.string().default("Core App"),
44
+ TOTP_ISSUER: zod_1.z.string().min(1).optional(),
39
45
  TWO_FACTOR_EMAIL_CODE_EXPIRY: zod_1.z.coerce
40
46
  .number()
41
47
  .int()
@@ -53,7 +59,7 @@ exports.envSchema = zod_1.z
53
59
  EMAIL_USER: zod_1.z.string().min(1),
54
60
  EMAIL_PASSWORD: zod_1.z.string().min(1),
55
61
  EMAIL_FROM: zod_1.z.string().min(1),
56
- EMAIL_FROM_NAME: zod_1.z.string().default("Core API"),
62
+ EMAIL_FROM_NAME: zod_1.z.string().min(1).optional(),
57
63
  PASSWORD_RESET_TOKEN_EXPIRY: zod_1.z.coerce.number().int().positive().default(15),
58
64
  FIRST_ACCESS_TOKEN_EXPIRY: zod_1.z.coerce
59
65
  .number()
@@ -1,7 +1,9 @@
1
1
  import { ConfigService } from "@nestjs/config";
2
+ import { AppBrand } from "./appBrand.interface";
2
3
  import { Env } from "./env.schema";
3
4
  export declare class EnvService {
4
5
  private readonly config;
5
6
  constructor(config: ConfigService<Env, true>);
6
7
  get<K extends keyof Env>(key: K): Env[K];
8
+ brand(): AppBrand;
7
9
  }
@@ -19,6 +19,16 @@ let EnvService = class EnvService {
19
19
  get(key) {
20
20
  return this.config.get(key, { infer: true });
21
21
  }
22
+ brand() {
23
+ const name = this.get("APP_NAME");
24
+ return {
25
+ name,
26
+ logoUrl: this.get("APP_LOGO_URL") ?? null,
27
+ color: this.get("APP_BRAND_COLOR"),
28
+ totpIssuer: this.get("TOTP_ISSUER") ?? name,
29
+ emailFromName: this.get("EMAIL_FROM_NAME") ?? name,
30
+ };
31
+ }
22
32
  };
23
33
  exports.EnvService = EnvService;
24
34
  exports.EnvService = EnvService = __decorate([
@@ -6,6 +6,7 @@ export declare class MailerService {
6
6
  constructor(env: EnvService);
7
7
  private send;
8
8
  private escapeHtml;
9
+ private header;
9
10
  private layout;
10
11
  sendTwoFactorCode(to: string, code: string, userName: string): Promise<void>;
11
12
  sendPasswordReset(to: string, token: string, userName: string): Promise<void>;
@@ -62,7 +62,7 @@ let MailerService = MailerService_1 = class MailerService {
62
62
  });
63
63
  }
64
64
  async send(to, subject, html) {
65
- const from = `"${this.env.get("EMAIL_FROM_NAME")}" <${this.env.get("EMAIL_FROM")}>`;
65
+ const from = `"${this.env.brand().emailFromName}" <${this.env.get("EMAIL_FROM")}>`;
66
66
  try {
67
67
  await this.transporter.sendMail({ from, to, subject, html });
68
68
  this.logger.log(`Email enviado: ${subject} -> ${to}`);
@@ -80,23 +80,36 @@ let MailerService = MailerService_1 = class MailerService {
80
80
  .replace(/"/g, "&quot;")
81
81
  .replace(/'/g, "&#39;");
82
82
  }
83
+ header(brand) {
84
+ if (brand.logoUrl) {
85
+ return `<img src="${brand.logoUrl}" alt="${this.escapeHtml(brand.name)}" style="max-height:40px;max-width:200px;">`;
86
+ }
87
+ return `<span style="font-size:20px;font-weight:bold;color:${brand.color};">${this.escapeHtml(brand.name)}</span>`;
88
+ }
83
89
  layout(title, body) {
90
+ const brand = this.env.brand();
84
91
  return `
85
92
  <div style="font-family: Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto;">
93
+ <div style="padding-bottom:20px;border-bottom:1px solid #ddd;margin-bottom:24px;">
94
+ ${this.header(brand)}
95
+ </div>
86
96
  <h2 style="color: #333;">${title}</h2>
87
97
  ${body}
88
98
  <hr style="border: none; border-top: 1px solid #ddd; margin: 30px 0;">
89
- <p style="color: #999; font-size: 12px;">Mensagem automática, não responda.</p>
99
+ <p style="color: #999; font-size: 12px;">
100
+ Mensagem automática de ${this.escapeHtml(brand.name)}, não responda.
101
+ </p>
90
102
  </div>`;
91
103
  }
92
104
  async sendTwoFactorCode(to, code, userName) {
93
105
  const expiry = this.env.get("TWO_FACTOR_EMAIL_CODE_EXPIRY");
106
+ const color = this.env.brand().color;
94
107
  const body = `
95
108
  <p>Olá ${this.escapeHtml(userName)},</p>
96
109
  <p>Seu código de verificação (2FA) é:</p>
97
110
  <div style="text-align:center;margin:30px 0;">
98
111
  <div style="background:#f5f5f5;padding:20px;border-radius:5px;display:inline-block;">
99
- <h1 style="margin:0;font-size:36px;letter-spacing:8px;color:#007bff;">${code}</h1>
112
+ <h1 style="margin:0;font-size:36px;letter-spacing:8px;color:${color};">${code}</h1>
100
113
  </div>
101
114
  </div>
102
115
  <p><strong>Este código expira em ${expiry} minutos.</strong></p>
@@ -106,11 +119,12 @@ let MailerService = MailerService_1 = class MailerService {
106
119
  async sendPasswordReset(to, token, userName) {
107
120
  const url = `${this.env.get("APP_URL")}/reset-password?token=${token}`;
108
121
  const expiry = this.env.get("PASSWORD_RESET_TOKEN_EXPIRY");
122
+ const color = this.env.brand().color;
109
123
  const body = `
110
124
  <p>Olá ${this.escapeHtml(userName)},</p>
111
125
  <p>Recebemos uma solicitação para redefinir sua senha. Clique no botão abaixo:</p>
112
126
  <div style="text-align:center;margin:30px 0;">
113
- <a href="${url}" style="background:#007bff;color:#fff;padding:12px 30px;text-decoration:none;border-radius:5px;display:inline-block;">Redefinir senha</a>
127
+ <a href="${url}" style="background:${color};color:#fff;padding:12px 30px;text-decoration:none;border-radius:5px;display:inline-block;">Redefinir senha</a>
114
128
  </div>
115
129
  <p>Ou copie e cole este link no navegador:</p>
116
130
  <p style="word-break:break-all;color:#666;">${url}</p>
@@ -128,11 +142,12 @@ let MailerService = MailerService_1 = class MailerService {
128
142
  async sendFirstAccess(to, token, userName) {
129
143
  const url = `${this.env.get("APP_URL")}/reset-password?token=${token}`;
130
144
  const expiry = this.formatExpiry(this.env.get("FIRST_ACCESS_TOKEN_EXPIRY"));
145
+ const brand = this.env.brand();
131
146
  const body = `
132
147
  <p>Olá ${this.escapeHtml(userName)},</p>
133
- <p>Sua conta foi criada. Para acessar o sistema, defina sua senha clicando no botão abaixo:</p>
148
+ <p>Sua conta em ${this.escapeHtml(brand.name)} foi criada. Para acessar, defina sua senha clicando no botão abaixo:</p>
134
149
  <div style="text-align:center;margin:30px 0;">
135
- <a href="${url}" style="background:#007bff;color:#fff;padding:12px 30px;text-decoration:none;border-radius:5px;display:inline-block;">Definir minha senha</a>
150
+ <a href="${url}" style="background:${brand.color};color:#fff;padding:12px 30px;text-decoration:none;border-radius:5px;display:inline-block;">Definir minha senha</a>
136
151
  </div>
137
152
  <p>Ou copie e cole este link no navegador:</p>
138
153
  <p style="word-break:break-all;color:#666;">${url}</p>
@@ -57,7 +57,7 @@ let TwoFactorService = TwoFactorService_1 = class TwoFactorService {
57
57
  }
58
58
  async generateSetup(accountEmail) {
59
59
  const secret = (0, otplib_1.generateSecret)();
60
- const issuer = this.env.get("TOTP_ISSUER");
60
+ const issuer = this.env.brand().totpIssuer;
61
61
  const otpauthUrl = (0, otplib_1.generateURI)({ issuer, label: accountEmail, secret });
62
62
  const qrDataUrl = await QRCode.toDataURL(otpauthUrl);
63
63
  return { secret, otpauthUrl, qrDataUrl };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export { CoreDataSourceOptions, createCoreDataSource, } from "./core/database/cr
4
4
  export { coreMigrations, MigrationClass } from "./core/database/migrations";
5
5
  export { coreEntities } from "./coreEntities";
6
6
  export { RlCoreModule, RlCoreModuleOptions } from "./rlCore.module";
7
+ export { AppBrand } from "./core/config/appBrand.interface";
7
8
  export { ConfigModule, ConfigModuleOptions, EnvValidator, } from "./core/config/config.module";
8
9
  export { Env, envSchema, validateEnv } from "./core/config/env.schema";
9
10
  export { EnvService } from "./core/config/env.service";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rl-core-api",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Core NestJS: autenticação com 2FA, RBAC, auditoria, notificações e listagens com filtro dinâmico",
5
5
  "author": "Rodrigo Liberti",
6
6
  "license": "MIT",