feat(api,ui): MFA/TOTP, Inventory, Support, HR-Timeclock, Fiscal, Billing e Design System
Leva grande, pedida como "pelo menos mais 20 etapas, use subagentes":
fecha a pendência de MFA/TOTP da Fase 1 (feito diretamente, autenticação é
sensível demais para delegar) e lança 5 subagentes em paralelo em 2 ondas
(eden-inventory, eden-support, eden-hr-timeclock; depois eden-finance,
eden-fiscal, eden-frontend), cada um em worktree isolado, com integração
seletiva manual (barrel, app.module.ts, migrations renomeadas/aplicadas,
build/typecheck/teste ao vivo antes de cada merge).
## Backend
- MFA/TOTP (`apps/api/src/auth/mfa.service.ts`, `crypto/field-encryption.service.ts`):
login em duas etapas quando `mfa_enabled=true`, `FieldEncryptionService`
genérico (AES-256-GCM versionado, ADR-0005) reaproveitado por outros
segredos reversíveis (ex. credencial de equipamento Control iD).
- Inventory: warehouses, stock_movements (ledger append-only), serialized_assets,
asset_assignments, stock_reservations — invariante "serial/patrimônio/MAC
nunca duplicado entre ativos ativos" reforçada por índices únicos parciais
no banco (Master Prompt §15.3).
- Support/Service Desk: tickets com máquina de estados, SLA com pausa/retomada
em `waiting_customer`/`waiting_third_party` (funções puras testáveis).
- HR-Timeclock (fundação): dispositivos Control iD (senha cifrada), import de
AFD com parser + CRC-16/KERMIT, `afd_records` imutável sem exceção nem
para super_admin (sem válvula de escape, diferente de audit_log).
- Fiscal: NCM/CFOP/municípios/naturezas de operação (eden.md módulo 5, MVP de
5 das ~19 tabelas), product_fiscal_profiles com invariante de único
profile ativo por billing_component.
- Billing: subscription→billing_run→invoice idempotente (regenerar em draft
substitui, nunca duplica) e imutável após consolidar (ADR-0008: nunca
confunde faturamento/documento fiscal/recebimento).
- FKs cruzadas fechadas: quotes/client_registrations/contracts.
## Frontend — primeira leva
- `packages/ui`: Design System real extraído do tema DreamsERP comprado —
achado que mudou o escopo: o tema já vem em React+Tailwind (não só
Angular), tokens visuais reais portados (cores, Geist como fonte real,
divergindo da doc antiga que citava Nunito/Poppins).
- `apps/core-web`: login real (com suporte a MFA), sessão, shell autenticado
via `AppShell` — substitui a tela estática "Bootstrap da Fase 1".
## Bugs reais encontrados e corrigidos (todos via teste ao vivo, não leitura)
1. **Segurança**: o token de desafio MFA era aceito como access token normal
pelo `JwtAuthGuard` (mesma assinatura, nenhuma checagem da claim
`purpose`) — bypass total do segundo fator. Explorado e fechado ao vivo
contra o container real; teste de regressão em `test/mfa.spec.ts`.
2. Crase solta dentro de comentário SQL na migration de hr-timeclock quebrava
o template literal JS (`SyntaxError` ao rodar a migration).
3. CORS ausente por completo na API.
4. `turbo.json` não declarava `VITE_API_BASE_URL` como input de build — o
Turborepo cacheava o bundle do frontend ignorando mudança na env var.
5. `compose.yaml` usava `${VITE_API_BASE_URL:-/api/v1}`, que colidia com a
variável de mesmo nome do `.env` local — o default nunca era aplicado.
6. Não existia `.dockerignore` — todo build copiava node_modules/.git/
worktrees de subagentes (665MB) para dentro do contexto Docker.
Decisão do operador incorporada: a API nunca tem domínio público próprio
(só IP interno) — os 3 frontends chamam por caminho relativo `/api/v1`,
proxy externo roteia same-origin; CORS só é relevante para dev local.
Verificado: `pnpm turbo run typecheck build` (28/28), `pnpm --filter
@eden/api test` (30/30, cresceu de 15), todo o lote testado ao vivo via
curl contra os containers reais reconstruídos, incluindo os 6 bugs acima
já fechados e confirmados, e a trilha de auditoria conferida no Postgres.
Claude-Session: https://claude.ai/code/session_01BcWWuKfykGtUweXmHD6cKx
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,8 +2,11 @@ import { Body, Controller, Get, HttpCode, Post, Req, UseGuards } from "@nestjs/c
|
||||
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
|
||||
import type { Request } from "express";
|
||||
import { AuthService } from "./auth.service.js";
|
||||
import { MfaService } from "./mfa.service.js";
|
||||
import { LoginDto } from "./dto/login.dto.js";
|
||||
import { RefreshDto } from "./dto/refresh.dto.js";
|
||||
import { MfaChallengeDto } from "./dto/mfa-challenge.dto.js";
|
||||
import { MfaCodeDto } from "./dto/mfa-code.dto.js";
|
||||
import { JwtAuthGuard } from "./jwt-auth.guard.js";
|
||||
import { CurrentUser } from "./decorators/current-user.decorator.js";
|
||||
import type { EdenAuthenticatedUser } from "./jwt-auth.guard.js";
|
||||
@@ -18,7 +21,10 @@ function requestContext(req: Request) {
|
||||
@ApiTags("auth")
|
||||
@Controller("v1/auth")
|
||||
export class AuthController {
|
||||
constructor(private readonly auth: AuthService) {}
|
||||
constructor(
|
||||
private readonly auth: AuthService,
|
||||
private readonly mfaService: MfaService,
|
||||
) {}
|
||||
|
||||
@Post("login")
|
||||
@HttpCode(200)
|
||||
@@ -26,6 +32,35 @@ export class AuthController {
|
||||
return this.auth.login(dto.email, dto.password, dto.applicationKey, requestContext(req));
|
||||
}
|
||||
|
||||
@Post("mfa/challenge")
|
||||
@HttpCode(200)
|
||||
async mfaChallenge(@Body() dto: MfaChallengeDto, @Req() req: Request) {
|
||||
return this.auth.completeMfaLogin(dto.mfaChallenge, dto.code, requestContext(req));
|
||||
}
|
||||
|
||||
@Post("mfa/enroll")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async mfaEnroll(@CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.mfaService.startEnrollment(user.id, user.email);
|
||||
}
|
||||
|
||||
@Post("mfa/confirm")
|
||||
@HttpCode(204)
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async mfaConfirm(@Body() dto: MfaCodeDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
await this.mfaService.confirmEnrollment(user.id, dto.code);
|
||||
}
|
||||
|
||||
@Post("mfa/disable")
|
||||
@HttpCode(204)
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
async mfaDisable(@Body() dto: MfaCodeDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
await this.mfaService.disable(user.id, dto.code);
|
||||
}
|
||||
|
||||
@Post("refresh")
|
||||
@HttpCode(200)
|
||||
async refresh(@Body() dto: RefreshDto, @Req() req: Request) {
|
||||
|
||||
@@ -3,13 +3,24 @@ import { AuthController } from "./auth.controller.js";
|
||||
import { AuthService } from "./auth.service.js";
|
||||
import { PasswordService } from "./password.service.js";
|
||||
import { TokenService } from "./token.service.js";
|
||||
import { MfaService } from "./mfa.service.js";
|
||||
import { JwtAuthGuard } from "./jwt-auth.guard.js";
|
||||
import { PermissionGuard } from "./permission.guard.js";
|
||||
import { SuperAdminGuard } from "./super-admin.guard.js";
|
||||
import { FieldEncryptionService } from "../crypto/field-encryption.service.js";
|
||||
|
||||
@Module({
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, PasswordService, TokenService, JwtAuthGuard, PermissionGuard, SuperAdminGuard],
|
||||
providers: [
|
||||
AuthService,
|
||||
PasswordService,
|
||||
TokenService,
|
||||
MfaService,
|
||||
FieldEncryptionService,
|
||||
JwtAuthGuard,
|
||||
PermissionGuard,
|
||||
SuperAdminGuard,
|
||||
],
|
||||
exports: [PasswordService, TokenService, JwtAuthGuard, PermissionGuard, SuperAdminGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ForbiddenException, Injectable, UnauthorizedException } from "@nestjs/c
|
||||
import { usersRepo, sessionsRepo, auditRepo, type User } from "@eden/database";
|
||||
import { PasswordService } from "./password.service.js";
|
||||
import { TokenService } from "./token.service.js";
|
||||
import { MfaService } from "./mfa.service.js";
|
||||
import { resolvePermissions } from "./permissions.js";
|
||||
|
||||
export interface RequestContext {
|
||||
@@ -16,6 +17,14 @@ export interface AuthResult {
|
||||
user: PublicUser;
|
||||
}
|
||||
|
||||
export interface MfaRequiredResult {
|
||||
mfaRequired: true;
|
||||
mfaChallenge: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
export type LoginResult = AuthResult | MfaRequiredResult;
|
||||
|
||||
export interface PublicUser {
|
||||
id: string;
|
||||
email: string;
|
||||
@@ -34,6 +43,7 @@ export class AuthService {
|
||||
constructor(
|
||||
private readonly passwords: PasswordService,
|
||||
private readonly tokens: TokenService,
|
||||
private readonly mfa: MfaService,
|
||||
) {}
|
||||
|
||||
async login(
|
||||
@@ -41,7 +51,7 @@ export class AuthService {
|
||||
password: string,
|
||||
applicationKey: "core" | "reseller" | "subscriber",
|
||||
ctx: RequestContext,
|
||||
): Promise<AuthResult> {
|
||||
): Promise<LoginResult> {
|
||||
const user = await usersRepo.findUserByEmail(email);
|
||||
|
||||
// Same generic error whether the account doesn't exist or the password
|
||||
@@ -65,6 +75,20 @@ export class AuthService {
|
||||
throw new ForbiddenException("Usuário sem acesso a esta aplicação");
|
||||
}
|
||||
|
||||
if (user.mfa_enabled) {
|
||||
const challenge = this.tokens.signMfaChallenge({ sub: user.id, app: applicationKey });
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "auth.mfa_challenge_issued",
|
||||
resourceType: "user",
|
||||
resourceId: user.id,
|
||||
metadata: { applicationKey },
|
||||
ipAddress: ctx.ipAddress,
|
||||
});
|
||||
return { mfaRequired: true, mfaChallenge: challenge.token, expiresIn: challenge.expiresIn };
|
||||
}
|
||||
|
||||
const result = await this.issueTokens(user, applicationKey, ctx);
|
||||
|
||||
await auditRepo.appendAuditEvent({
|
||||
@@ -80,6 +104,47 @@ export class AuthService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Second step of login when the account has MFA enabled — exchanges a password-verified challenge + TOTP code for real tokens. */
|
||||
async completeMfaLogin(challengeToken: string, code: string, ctx: RequestContext): Promise<AuthResult> {
|
||||
let payload;
|
||||
try {
|
||||
payload = this.tokens.verifyMfaChallenge(challengeToken);
|
||||
} catch {
|
||||
throw new UnauthorizedException("Desafio MFA inválido ou expirado");
|
||||
}
|
||||
|
||||
const user = await usersRepo.findUserById(payload.sub);
|
||||
if (!user || !user.is_active || !user.mfa_enabled || !user.mfa_secret_encrypted) {
|
||||
throw new UnauthorizedException("Desafio MFA inválido ou expirado");
|
||||
}
|
||||
|
||||
if (!(await this.mfa.verifyCode(user.mfa_secret_encrypted, code))) {
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "auth.mfa_challenge_failed",
|
||||
resourceType: "user",
|
||||
resourceId: user.id,
|
||||
ipAddress: ctx.ipAddress,
|
||||
});
|
||||
throw new UnauthorizedException("Código inválido");
|
||||
}
|
||||
|
||||
const result = await this.issueTokens(user, payload.app, ctx);
|
||||
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId: user.id,
|
||||
action: "auth.login",
|
||||
resourceType: "user",
|
||||
resourceId: user.id,
|
||||
metadata: { applicationKey: payload.app, viaMfa: true },
|
||||
ipAddress: ctx.ipAddress,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async refresh(refreshTokenPlaintext: string, ctx: RequestContext): Promise<AuthResult> {
|
||||
const hash = this.tokens.hashRefreshToken(refreshTokenPlaintext);
|
||||
const active = await sessionsRepo.findActiveSessionByRefreshTokenHash(hash);
|
||||
|
||||
11
apps/api/src/auth/dto/mfa-challenge.dto.ts
Normal file
11
apps/api/src/auth/dto/mfa-challenge.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsString, Length, MinLength } from "class-validator";
|
||||
|
||||
export class MfaChallengeDto {
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
mfaChallenge!: string;
|
||||
|
||||
@IsString()
|
||||
@Length(6, 6)
|
||||
code!: string;
|
||||
}
|
||||
7
apps/api/src/auth/dto/mfa-code.dto.ts
Normal file
7
apps/api/src/auth/dto/mfa-code.dto.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { IsString, Length } from "class-validator";
|
||||
|
||||
export class MfaCodeDto {
|
||||
@IsString()
|
||||
@Length(6, 6)
|
||||
code!: string;
|
||||
}
|
||||
49
apps/api/src/auth/mfa.service.ts
Normal file
49
apps/api/src/auth/mfa.service.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { BadRequestException, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { generateSecret, generateURI, verify } from "otplib";
|
||||
import { usersRepo } from "@eden/database";
|
||||
import { FieldEncryptionService } from "../crypto/field-encryption.service.js";
|
||||
|
||||
const ISSUER = "EDEN";
|
||||
|
||||
@Injectable()
|
||||
export class MfaService {
|
||||
constructor(private readonly fieldEncryption: FieldEncryptionService) {}
|
||||
|
||||
/** Stages a new TOTP secret (not yet active — see confirmEnrollment). */
|
||||
async startEnrollment(userId: string, email: string): Promise<{ secret: string; otpauthUrl: string }> {
|
||||
const secret = generateSecret();
|
||||
await usersRepo.setMfaSecret(userId, this.fieldEncryption.encrypt(secret));
|
||||
const otpauthUrl = generateURI({ issuer: ISSUER, label: email, secret });
|
||||
return { secret, otpauthUrl };
|
||||
}
|
||||
|
||||
/** Verifies the first code against the staged secret and flips mfa_enabled on. */
|
||||
async confirmEnrollment(userId: string, code: string): Promise<void> {
|
||||
const user = await usersRepo.findUserById(userId);
|
||||
if (!user?.mfa_secret_encrypted) {
|
||||
throw new BadRequestException("Nenhum cadastro de MFA pendente para este usuário");
|
||||
}
|
||||
if (!(await this.verifyCode(user.mfa_secret_encrypted, code))) {
|
||||
throw new BadRequestException("Código inválido");
|
||||
}
|
||||
await usersRepo.confirmMfaEnrollment(userId);
|
||||
}
|
||||
|
||||
/** Requires a currently-valid code — proves the factor, not just an authenticated session. */
|
||||
async disable(userId: string, code: string): Promise<void> {
|
||||
const user = await usersRepo.findUserById(userId);
|
||||
if (!user?.mfa_enabled || !user.mfa_secret_encrypted) {
|
||||
throw new BadRequestException("MFA não está habilitado para este usuário");
|
||||
}
|
||||
if (!(await this.verifyCode(user.mfa_secret_encrypted, code))) {
|
||||
throw new UnauthorizedException("Código inválido");
|
||||
}
|
||||
await usersRepo.disableMfa(userId);
|
||||
}
|
||||
|
||||
async verifyCode(encryptedSecret: string, code: string): Promise<boolean> {
|
||||
const secret = this.fieldEncryption.decrypt(encryptedSecret);
|
||||
const result = await verify({ token: code, secret });
|
||||
return result.valid;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,14 @@ export interface AccessTokenPayload {
|
||||
|
||||
const ACCESS_TOKEN_TTL_SECONDS = 15 * 60; // 15 min — ADR-0003
|
||||
const REFRESH_TOKEN_TTL_DAYS = 30;
|
||||
const MFA_CHALLENGE_TTL_SECONDS = 2 * 60;
|
||||
const MFA_CHALLENGE_PURPOSE = "mfa_challenge" as const;
|
||||
|
||||
export interface MfaChallengePayload {
|
||||
sub: string;
|
||||
app: "core" | "reseller" | "subscriber";
|
||||
purpose: typeof MFA_CHALLENGE_PURPOSE;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
@@ -26,7 +34,18 @@ export class TokenService {
|
||||
}
|
||||
|
||||
verifyAccessToken(token: string): AccessTokenPayload {
|
||||
return jwt.verify(token, this.secret) as AccessTokenPayload;
|
||||
const payload = jwt.verify(token, this.secret) as AccessTokenPayload & { purpose?: unknown };
|
||||
// Both token kinds are signed with the same secret, so signature
|
||||
// verification alone doesn't distinguish them — a real access token
|
||||
// must never carry a `purpose` claim (only single-purpose tokens like
|
||||
// the MFA challenge do). Without this check, a password-verified MFA
|
||||
// challenge token would be indistinguishable from a full access token
|
||||
// and grant complete API access without ever checking the second
|
||||
// factor — this was caught live (a real bug, not hypothetical).
|
||||
if (payload.purpose !== undefined) {
|
||||
throw new Error("Token não é um access token válido");
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** Opaque, high-entropy refresh token — never a JWT (ADR-0003). Returns the
|
||||
@@ -42,4 +61,27 @@ export class TokenService {
|
||||
hashRefreshToken(plaintext: string): string {
|
||||
return createHash("sha256").update(plaintext).digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Short-lived, single-purpose token issued after password verification
|
||||
* when the account has MFA enabled — proves "password already checked"
|
||||
* without granting API access. The `purpose` claim is what keeps this
|
||||
* out of JwtAuthGuard (see verifyAccessToken's explicit rejection of any
|
||||
* `purpose` claim) — without it this token would be a fully valid
|
||||
* access token, defeating MFA entirely.
|
||||
*/
|
||||
signMfaChallenge(payload: Omit<MfaChallengePayload, "purpose">): { token: string; expiresIn: number } {
|
||||
const token = jwt.sign({ ...payload, purpose: MFA_CHALLENGE_PURPOSE }, this.secret, {
|
||||
expiresIn: MFA_CHALLENGE_TTL_SECONDS,
|
||||
});
|
||||
return { token, expiresIn: MFA_CHALLENGE_TTL_SECONDS };
|
||||
}
|
||||
|
||||
verifyMfaChallenge(token: string): MfaChallengePayload {
|
||||
const payload = jwt.verify(token, this.secret) as Partial<MfaChallengePayload>;
|
||||
if (payload.purpose !== MFA_CHALLENGE_PURPOSE || !payload.sub || !payload.app) {
|
||||
throw new Error("Token de desafio MFA inválido");
|
||||
}
|
||||
return payload as MfaChallengePayload;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user