Skip to content

RamosJSouza/secure-nestjs-rbac-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

98 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Prime Nest — Production-Grade Secure Backend Architecture (RBAC + JWT RS256)

A reference NestJS backend architecture designed for regulated and security-sensitive environments — payments, healthcare, enterprise SaaS, and AI-driven systems where auditability and resilience are non-negotiable.

This is not a boilerplate.
It is a security-first backend foundation shaped by real production constraints.


Built by

Ramos de Souza Janones
Senior Full-Stack Engineer — Node.js | NestJS | Distributed Systems | LLMs in Production

I design secure, scalable, audit-ready backend systems for regulated and high-risk domains.


Why This Architecture Exists

Most backend templates optimize for speed.
This architecture optimizes for:

  • Security reviews
  • Compliance readiness
  • Auditability
  • Failure containment
  • Production resilience
  • Horizontal scalability

It reflects patterns used in environments where:

  • Financial transactions cannot fail silently
  • Healthcare data must remain traceable
  • Authentication must resist token replay attacks
  • AI integrations require structured observability

Core Design Principles

1. Asymmetric JWT (RS256)

  • Private key signs tokens (server only)
  • Public key verifies tokens (safe to distribute)
  • Prevents symmetric secret leakage risks
  • Compatible with distributed validation
  • Access token: 15 minutes
  • Refresh token: 7 days
  • Rotation with reuse detection enabled

2. Refresh Token Rotation + Reuse Detection

  • If a compromised refresh token is reused:
    • Entire session family is revoked
    • Event is logged
    • Incident becomes traceable
  • No silent compromise.

3. Append-Only Audit Logging

  • Every mutation recorded
  • Correlation ID per request
  • No update/delete on audit records
  • Designed for traceability and forensic review

4. Database-Driven RBAC

  • Feature → Permission → RolePermission → Role → User
  • Permissions stored in DB
  • No hardcoded roles
  • Changes take effect immediately
  • All mutations guarded

5. Fail-Fast Configuration

  • Startup validation via Joi
  • Production refuses to boot without:
    • PRIVATE_KEY
    • PUBLIC_KEY
    • DB_SSL=true
    • ALLOWED_ORIGINS defined
  • No silent misconfiguration.

Security Model

  • Rate limiting: 100 req / 15 min per IP
  • Helmet security headers
  • Strict CORS (production required)
  • ValidationPipe (whitelist + forbidNonWhitelisted)
  • Account lockout: 5 attempts → 15-minute lock
  • Password change revokes all active sessions
  • synchronize: false in production
  • Designed to pass internal security review.

Observability & Resilience

  • Structured logging with Pino
  • Correlation ID propagation
  • Liveness & Readiness endpoints
  • Docker health checks aligned with readiness
  • Graceful shutdown on SIGTERM
  • Connection pooling (configurable)
  • Horizontal scaling supported (stateless JWT) when REDIS_HOST is set for shared cache and JWT denylist

Architecture Constraints

  • Single-tenant (no organization scoping in audit or RBAC)
  • Async audit via BullMQ when REDIS_HOST is set; synchronous fallback otherwise
  • Scheduled purge: expired sessions + audit logs older than AUDIT_RETENTION_DAYS (default 90)
  • Swagger intentionally exposed for integration workflows
  • Set REDIS_HOST in every production/replica deployment — without it, RBAC permission cache and JWT denylist are per-process (in-memory fallback)
  • Global API prefix defaults to /api (configurable via API_PREFIX)

Tech Stack

Layer Technology
Framework NestJS
Database PostgreSQL + TypeORM
Cache Redis when REDIS_HOST is set; in-memory (per process) otherwise
Auth JWT RS256
Validation Class Validator + Joi
Logging Pino
API Docs Swagger

Real-World Context Behind This Design

This architecture reflects experience in:

  • Payment systems (including PIX-related flows)
  • Healthcare platforms
  • Stripe integrations
  • AI system refactoring
  • LLM + RAG pipelines in production

When integrating AI into regulated systems, structured logs, correlation IDs, and audit trails stop being optional. They become operational requirements.


AI-Assisted Development Economics

This repository was built with intensive Claude Code assistance (Anthropic API, BYOK mode). A detailed estimate — methodology, assumptions, and dated pricing — is in Economia de Desenvolvimento e Custo de Tokens de IA (PT-BR).

Headline figures (pricing verified July 2026):

Metric Estimate
Codebase size ~6,900 TS lines (123 files, 28 specs, 8 NestJS modules)
Manual build time (senior, TDD, security-hardened) ~79 dev-days (~3.6 months)
Human steering effort with Claude Code ~8 dev-days
Development time saved ~70 dev-days (~3.2 months of 1 senior engineer)
Compression factor ~8–12×
AI token cost (central estimate, ~15M tokens) ~$130–$150
Token-cost ROI vs. saved senior labor (US) ~250–900×

Cross-check: Anthropic's enterprise benchmark (~$13/dev-active-day) × ~10 steering dev-days ≈ ~$130, consistent with the central estimate.


Documentation

Language Links
English Architecture · Authentication · RBAC · Configuration · Observability · Security
Português Arquitetura · Autenticação · RBAC · Configuração · Observabilidade · Segurança · Economia de Dev com IA

(See /docs directory)


Quick Start

  1. Configure .env
  2. Generate RSA keys
  3. Run migrations
  4. Seed RBAC
  5. Change admin credentials
  6. Start application
cp .env.example .env
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
yarn install
yarn migration:run
yarn seed:rbac
yarn dev

Important: Change the seed admin password after first deploy.

Docker

# Local development (exposes DB/Redis ports)
npm run docker:up

# Production-like (no host port exposure)
npm run docker:up:prod

For Engineering Leaders

This repository can be used as:

  • A secure backend reference implementation
  • An RBAC foundation
  • A JWT rotation example
  • An audit-ready architecture blueprint
  • A starting point for regulated SaaS systems

Contact

If you are building or modernizing a backend that must survive:

  • Security review
  • Compliance audits
  • Production incidents
  • AI integration risks

Let's connect.


Navegação (Português)

Seção Descrição
Construído por Autor e links de contato
Por que esta arquitetura existe Motivação e contexto
Princípios de design JWT RS256, rotação, auditoria, RBAC, fail-fast
Modelo de segurança Rate limit, lockout, CORS, validação
Observabilidade e resiliência Pino, health checks, graceful shutdown
Restrições de arquitetura Single-tenant, Swagger, migrations
Stack tecnológica NestJS, PostgreSQL, Redis, JWT
Contexto real Pagamentos, healthcare, AI
Economia de desenvolvimento com IA Tempo poupado, custo de tokens, ROI
Documentação Links para docs em inglês e português
Quick Start Passos para rodar o projeto
Para líderes de engenharia Casos de uso do repositório
Contato Website e LinkedIn

About

Enterprise-grade, production-ready NestJS backend template featuring RS256 JWT authentication, secure refresh token rotation, database-driven RBAC, audit logging, and hardened security best practices.

Topics

Resources

License

Code of conduct

Stars

3 stars

Watchers

1 watching

Forks

Releases

No releases published

Contributors

Languages