Skip to content

RamosJSouza/secure-nestjs-rbac-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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)

Architecture Constraints

  • Single-tenant (Organization entity placeholder only)
  • Swagger intentionally exposed for integration workflows
  • Migrations only — no schema sync in production

Tech Stack

Layer Technology
Framework NestJS
Database PostgreSQL + TypeORM
Cache Redis
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.


Documentation

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

(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.


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
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

Watchers

Forks

Releases

No releases published

Contributors