Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
APP_PORT=3000
AUTH_JWT_SECRET=change-me-in-production
AUTH_JWT_EXPIRES_IN_MINUTES=480
DB_HOST=postgres
DB_PORT=5432
DB_USER=postgres
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## [2026-03-25]
- feature: implementação da Phase 1 — Core Identity com criação de conta, login por email/senha e logout com sessão persistida.
- feature: módulo `users` mínimo, módulo `identity` funcional, JWT de transporte, hash Argon2id e migrations SQL automáticas.
- test: cobertura unitária do domínio e casos de uso, além de suites de integração e funcional para identity com Testcontainers.
- docs: README, arquitetura, comandos, handoff e status de fase atualizados para o novo fluxo.

## [2026-03-25]
- feature: bootstrap inicial do Nexus Platform com NestJS, TypeScript strict, health check e módulos placeholder.
- feature: configuração centralizada por `.env`, logger estruturado com pino, base OpenTelemetry e conexão PostgreSQL sem ORM.
Expand Down
90 changes: 66 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Nexus Platform

Multi-tenant backend platform for identity, organizations, users, access control and immutable auditability. The codebase starts as a modular monolith and keeps DDD, Clean Architecture and internal event-driven boundaries explicit from day one.
Multi-tenant backend platform for identity, organizations, users, access control and immutable auditability. The codebase is intentionally evolving as a modular monolith with DDD, Clean Architecture and explicit internal boundaries.

## 🚧 Project Status

Current Phase: **Phase 0Foundation**
Current Phase: **Phase 1Core Identity**

Notion reference: [Nexus Platform](https://www.notion.so/mrgomides/Nexus-Platform-32fe01f2262680cd9e32db2b5cdd8f7b?source=copy_link)

Expand All @@ -14,45 +14,81 @@ Notion reference: [Nexus Platform](https://www.notion.so/mrgomides/Nexus-Platfor
- TypeScript (`strict`)
- NestJS
- PostgreSQL
- `pg` with explicit repositories
- Argon2
- JWT
- Pino
- OpenTelemetry
- Docker
- GitHub Actions

## Foundation Scope
## What Phase 1 Delivers

- HTTP bootstrap with `GET /health`
- centralized environment configuration
- PostgreSQL connectivity without schema or ORM
- structured logging with correlation id support
- OpenTelemetry provider bootstrap without exporters
- placeholder business modules with no domain logic yet
- minimal `users` ownership for internal user records
- `identity` domain with `Account`, `Credential` and `Session`
- account creation with unique global email
- login with email and password
- persisted and revocable sessions
- JWT as transport contract backed by persisted sessions
- SQL migrations applied automatically during bootstrap
- HTTP validation and standardized error handling
- structured security-aware logging for identity flows

## Available Endpoints

- `GET /health`
- `POST /identity/accounts`
- `POST /identity/login`
- `POST /identity/logout`

## Login Flow

```text
Create account
-> validate full name, email and password
-> create user
-> create account
-> hash password with Argon2id
-> persist credential

Login
-> validate email
-> load account + user + credential
-> verify password hash
-> create persisted session
-> issue JWT with sub, aid, sid and jti

Logout
-> verify JWT
-> load session
-> revoke persisted session
```

## Project Structure

```text
src/
bootstrap/
config/
errors/
http/
logging/
persistence/
telemetry/
modules/
identity/
organizations/
application/
domain/
infrastructure/
users/
application/
domain/
infrastructure/
organizations/
access-control/
audit-logs/
shared/
application/
domain/
infrastructure/
events/
tenancy/
auth/
testing/
jobs/
test/
unit/
integration/
Expand All @@ -67,6 +103,8 @@ Use `.env.example` as the baseline:

```dotenv
APP_PORT=3000
AUTH_JWT_SECRET=change-me-in-production
AUTH_JWT_EXPIRES_IN_MINUTES=480
DB_HOST=postgres
DB_PORT=5432
DB_USER=postgres
Expand All @@ -75,22 +113,24 @@ DB_NAME=nexus
NODE_ENV=development
```

## Run

Local development:
## Run Locally

```bash
cp .env.example .env
npm install
npm run db:migrate
npm run start:dev
```

Docker:
The application also applies pending SQL migrations during bootstrap, so `npm run db:migrate` is the explicit operational option and app startup is the safety net.

## Run with Docker

```bash
cp .env.example .env
docker compose up -d --build
curl http://localhost:3000/health
docker compose logs -f app postgres
docker compose down -v
```

Expand All @@ -108,9 +148,11 @@ npm run test:functional

## Architecture Notes

- Modular Monolith is the deployment model.
- DDD and Clean Architecture boundaries are preserved by keeping business modules isolated and pushing operational concerns into `src/bootstrap`.
- Multi-tenancy, authorization and auditability are treated as first-class constraints, but their business rules are intentionally deferred to later phases.
- Modular Monolith remains the deployment model.
- `users` owns the internal user record and exposes a narrow contract to `identity`.
- `identity` owns `accounts`, `credentials` and `sessions`.
- PostgreSQL access stays explicit through repositories and SQL, without ORM.
- Multi-tenancy, RBAC and full auditability remain mandatory next-phase constraints and are not implemented in Phase 1.

## Documentation

Expand Down
44 changes: 27 additions & 17 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,41 @@

## Overview

Phase 0 establishes the operational shell of the Nexus Platform without introducing business logic. The repository is organized as a modular monolith with explicit domain boundaries and a clean split between bootstrap/infrastructure concerns and future domain/application code.
Phase 1 turns the foundation into a first functional slice of the platform. The repository remains a modular monolith, but now `users` and `identity` contain real domain/application/infrastructure code and a working authentication flow.

## C4-lite Diagram

```mermaid
flowchart LR
user["Developer / CI"] --> app["Nexus Platform App\nNestJS + TypeScript"]
app --> health["Health Endpoint\nGET /health"]
app --> config["Configuration Layer\n.env + typed parser"]
app --> logging["Structured Logging\npino + correlation id"]
app --> telemetry["Telemetry Bootstrap\nOpenTelemetry SDK"]
app --> database["PostgreSQL\nconnectivity only"]
app --> modules["Business Modules\nidentity, organizations, users,\naccess-control, audit-logs"]
client["HTTP Client"] --> api["Nexus Platform API\nNestJS + TypeScript"]
api --> health["Health Endpoint\nGET /health"]
api --> identity["Identity Module\naccounts, credentials, sessions"]
identity --> users["Users Module\ninternal user contract"]
identity --> jwt["JWT Transport\nHS256"]
identity --> logs["Structured Logs\naccount/login/session events"]
api --> database["PostgreSQL\nSQL migrations + explicit repositories"]
api --> telemetry["OpenTelemetry Bootstrap"]
```

## Module Boundaries

- `src/bootstrap`: app startup, HTTP entrypoints, config, logging, persistence and telemetry.
- `src/modules`: business modules reserved for domain/application/infrastructure growth without cross-module shortcuts.
- `src/shared`: shared technical and tactical building blocks that must not become a domain dumping ground.
- `src/jobs`: scheduled/background workloads reserved for future phases.
- `src/bootstrap`: startup, validation pipe, global error mapping, config, logging, migrations and database lifecycle.
- `src/modules/users`: owns the minimal internal user record consumed by `identity`.
- `src/modules/identity`: owns account creation, password hashing, login, session persistence, token issue and logout.
- `src/modules/organizations`, `src/modules/access-control`, `src/modules/audit-logs`: still placeholders for later phases.
- `src/shared`: shared technical/domain primitives that do not collapse module boundaries.

## Architectural Decisions Active in Phase 0
## Active Decisions in Phase 1

- Modular Monolith as the initial deployment model.
- PostgreSQL connectivity is established with `pg` directly, without ORM or schema ownership yet.
- No domain rules, authentication, authorization or tenant logic are implemented in the foundation.
- Multi-tenancy, deny-by-default authorization and immutable audit logs remain mandatory future constraints and must shape any new module contracts.
- PostgreSQL still uses `pg` directly with explicit repository implementations.
- SQL migrations are versioned in `migrations/` and applied automatically during bootstrap.
- Passwords are hashed with Argon2id and never persisted in clear text.
- JWT is only a transport token; revocation authority remains the persisted `sessions` table.
- Authentication errors stay generic at the HTTP boundary to avoid leaking account existence or status.

## Phase 1 Constraints Preserved

- No tenant resolution yet in the authentication flow.
- No RBAC enforcement yet.
- No full audit log append-only module yet.
- No external message bus or SSO/OIDC integration yet.
17 changes: 1 addition & 16 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
```bash
cp .env.example .env
npm install
npm run db:migrate
npm run start:dev
npm run build
npm run lint
Expand All @@ -16,19 +17,3 @@ docker compose up -d --build
docker compose down -v
docker compose logs -f app postgres
```

## Make Shortcuts

```bash
make up
make down
make build
make run
make logs
make test
make test-unit
make test-integration
make test-functional
make lint
make ci
```
50 changes: 22 additions & 28 deletions docs/handoff.md
Original file line number Diff line number Diff line change
@@ -1,43 +1,37 @@
# Handoff

## Contexto
- Objetivo da tarefa: implementar a Fase 0Foundation do Nexus Platform.
- Objetivo da tarefa: implementar a Phase 1Core Identity do Nexus Platform.
- Fase atual: concluída.
- Escopo atendido: scaffold NestJS, health endpoint, config `.env`, logging pino, telemetry base, PostgreSQL connectivity, placeholders modulares, Docker, CI e documentação operacional.

## O que foi feito
- Estrutura base do repositório criada com `src/bootstrap`, `src/modules`, `src/shared`, `test`, `docs` e `migrations`.
- App NestJS configurada com health check, logger estruturado, bootstrap de telemetry e serviço de conexão PostgreSQL sem ORM.
- Testes unitários escritos e executados; testes de integração e funcionais implementados com Testcontainers.
- Dockerfile, `docker-compose.yml`, Makefile, workflow de CI, README, changelog e docs de apoio adicionados.
- Escopo atendido: criação de conta, login com email/senha, sessão persistida/revogável, migrations SQL, validação HTTP, erros padronizados, logs estruturados e atualização documental.

## Arquivos alterados
- `package.json`, `package-lock.json`, configs TS/Jest/ESLint e `.env.example`
- `src/**`
- `package.json`, `package-lock.json`, `.env.example`
- `src/bootstrap/**`
- `src/modules/users/**`
- `src/modules/identity/**`
- `test/**`
- `Dockerfile`, `docker-compose.yml`, `Makefile`, `.github/workflows/ci.yml`
- `README.md`, `CHANGELOG.md`, `docs/**`, `.agents/decisions/0004-foundation-pg-without-orm.md`
- `migrations/0001_core_identity.sql`
- `README.md`, `CHANGELOG.md`, `docs/architecture.md`, `docs/commands.md`, `docs/phase-status.md`, `docs/handoff.md`

## Decisões tomadas
- `pg` direto foi escolhido para validar conectividade com PostgreSQL sem fixar um ORM prematuramente.
- logging foi centralizado com `nestjs-pino` e correlation id por request.
- telemetry foi inicializada com `NodeSDK` sem exporters, apenas para preparar a borda observável.
- `users` é o dono do registro mínimo de usuário e exporta contrato explícito para `identity`.
- `identity` é o dono de `accounts`, `credentials` e `sessions`.
- JWT foi mantido como contrato de transporte; revogação depende da sessão persistida.
- migrations continuam em SQL explícito com `pg`, sem ORM.

## Testes
## Testes executados
- Unit: `npm run test:unit` executado com sucesso.
- Build: `npm run build` executado com sucesso.
- Integration: implementado com Testcontainers; nesta execução local ficou pulado por indisponibilidade do daemon Docker.
- Functional: implementado com Testcontainers; nesta execução local ficou pulado por indisponibilidade do daemon Docker.

## Impactos avaliados
- Tenant: nenhuma regra implementada; fundação preserva espaço explícito para `tenant_id` e scoping futuro.
- RBAC: nenhuma decisão de autorização implementada; módulos permanecem vazios.
- Audit logs: módulo placeholder criado, sem persistência ou trilha ainda.
- Observability: logging e bootstrap de telemetry adicionados na borda.

## Riscos e pendências
- Validar `docker compose up -d --build` e smoke test `GET /health` em ambiente com daemon Docker ativo.
- Escolha futura de ORM/migrations continua em aberto e deve passar por ADR quando houver modelo de domínio real.

## Próximos passos recomendados
1. Executar a validação Docker localmente com daemon ativo e confirmar `/health` e conexão PostgreSQL via compose.
2. Iniciar a próxima fase mantendo tenant, autorização e auditoria como restrições centrais desde os primeiros contratos de módulo.
- Validar suites de integração e funcional em ambiente local ou CI com Docker ativo.
- Tenant context, memberships, RBAC e auditabilidade completa continuam pendentes para próximas fases.
- Revisar secret management para produção antes de qualquer deploy real.

## Próximos passos
1. Implementar Phase 2 com `organizations`, `memberships` e resolução explícita de tenant.
2. Acoplar autenticação ao contexto ativo de tenant sem quebrar o contrato atual de sessão.
3. Introduzir RBAC e auditoria completa em cima do principal autenticado já existente.
26 changes: 15 additions & 11 deletions docs/phase-status.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
# Phase Status

## Fase atual
- Nome: Phase 0Foundation
- Nome: Phase 1Core Identity
- Status: done
- Responsável: Codex
- Data: 2026-03-25

## Objetivo da fase
- Estabelecer a base operacional do Nexus Platform com NestJS, TypeScript strict, PostgreSQL, observabilidade mínima, Docker e CI.
- Validar a arquitetura modular com um fluxo funcional real de criação de conta, autenticação por email/senha e invalidação de sessão.

## Entradas
- `AGENTS.md` e regras em `.agents/rules/*`
- contexto do produto, mapa de módulos e ADRs 0001, 0002, 0003
- contexto do produto, mapa de módulos e ADRs 0001, 0002, 0003 e 0004
- página `Nexus Platform` no Notion

## Saídas esperadas
- aplicação subindo com `GET /health`
- conexão PostgreSQL validada
- estrutura modular criada
- documentação operacional atualizada
## Saídas entregues
- módulo `users` com contrato interno mínimo
- módulo `identity` com domínio, casos de uso, controllers e persistência
- migrations SQL para `users`, `accounts`, `credentials` e `sessions`
- validação HTTP global e tratamento padronizado de erro
- logs estruturados para `account_created`, `login_succeeded`, `login_failed` e `session_invalidated`
- documentação operacional atualizada para a fase

## Bloqueios
- daemon Docker indisponível no ambiente local durante a validação desta execução
- daemon Docker indisponível no ambiente local durante a validação desta execução, então suites de integração e funcional permaneceram puladas localmente

## Decisões / observações
- `pg` foi adotado como adapter de conexão para evitar antecipar a escolha de ORM.
- suites de integração e funcional usam Testcontainers e rodam integralmente quando Docker está disponível; localmente elas são puladas se o daemon estiver indisponível.
- `users` passou a ser o dono do registro mínimo de usuário e `identity` consome apenas o contrato interno exportado.
- JWT foi adotado apenas como contrato de transporte; a revogação real continua sendo determinada pela tabela `sessions`.
- multi-tenancy, RBAC e auditoria completa permanecem fora do escopo desta fase.
Loading
Loading