Skip to content

[SEC-A04] Revisión cripto: passwords y JWT_SECRET - #185

Merged
CrisNAC merged 4 commits into
devfrom
OM-558
Jun 2, 2026
Merged

CrisNAC merged 4 commits into
devfrom
OM-558

Conversation

@Benjakr04

@Benjakr04 Benjakr04 commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Mejorado el manejo de errores en la autenticación y validación de sesiones para proporcionar respuestas más consistentes.
    • Reforzada la validación de credenciales con mensajes de error genéricos.
  • Security

    • Fortalecidas las validaciones de variables de configuración críticas.
    • Implementada mayor seguridad en el proceso de gestión de sesiones.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Benjakr04, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 41 minutes and 1 second. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0ab0f1d4-2b81-4d00-943b-ee37aca3898b

📥 Commits

Reviewing files that changed from the base of the PR and between 1976822 and 236a070.

📒 Files selected for processing (5)
  • src/config/env.config.js
  • src/lib/utils/password.utils.js
  • src/modules/session/controllers/session.controllers.js
  • tests/e2e/session.test.js
  • tests/unit/session/session.controllers.test.js
📝 Walkthrough

Resumen general

Se implementa una validación de fortaleza de secretos en configuración de entorno, se introduce un módulo de utilidades de contraseña que encapsula bcrypt con validaciones, y se refactorizan los controladores de sesión hacia patrón middleware con manejo centralizado de errores y respuestas normalizadas.

Cambios

Validación de secretos y utilidades de contraseña con refactor de sesión

Capa / Archivo(s) Resumen
Validación de fortaleza de secretos
src/config/env.config.js
Se agrega validateSecretStrength() que verifica longitud mínima (32 caracteres en producción, 16 en desarrollo). Dentro de validateEnv() se integra validación de JWT_SECRET y SUPABASE_SERVICE_ROLE_KEY mediante try/catch que registra errores y detiene el proceso.
Utilidades de contraseña con bcrypt
src/lib/utils/password.utils.js
Nuevo módulo que exporta BCRYPT_ROUNDS (12 en producción, 10 en desarrollo), hashPassword() que valida y cifra, y verifyPassword() que compara sin exponer datos en claro. Manejo de errores con logging etiquetado.
Refactor de controladores a middleware
src/modules/session/controllers/session.controllers.js
Reestructuración de login, logout y userSession para recibir parámetro next y propagar errores centralizados. Se reemplaza bcrypt directo por utilidad verifyPassword(), se adoptan errores tipificados, respuestas normalizan success: true, y userSession distingue entre JWT expirado e inválido con consulta selectiva a Prisma.

Diagramas de secuencia

sequenceDiagram
  participant Cliente
  participant login as login()
  participant verifyPassword as verifyPassword()
  participant jwt as jwt.verify()
  participant BD as Prisma
  participant ManejadorErrores as next(error)
  
  Cliente->>login: POST email, password
  login->>login: Valida email/password
  login->>BD: findFirst(email, status: true)
  BD-->>login: usuario o null
  alt Usuario no existe
    login->>ManejadorErrores: UnauthorizedError
  else Usuario existe
    login->>verifyPassword: plainPassword, hashedPassword
    verifyPassword-->>login: boolean
    alt Contraseña inválida
      login->>ManejadorErrores: UnauthorizedError
    else Contraseña válida
      login->>jwt: sign({id_user, email, role}, JWT_SECRET, 30m)
      jwt-->>login: token
      login->>Cliente: success: true, user, cookie httpOnly
    end
  end
Loading

Estimación de esfuerzo de revisión

🎯 3 (Moderato) | ⏱️ ~22 minutos

PRs posiblemente relacionadas

  • CrisNAC/BackendMarketplace#180: Amplía validateEnv() en este PR; el PR #180 hace que src/server.js invoque validateEnv al arrancar y documenta variables de entorno.

  • CrisNAC/BackendMarketplace#43: Ajusta autenticación y uso del claim req.user.id_user en product-review, conectando con cambios de JWT y verificación en session.controllers.js.

  • CrisNAC/BackendMarketplace#20: Modifica el mismo archivo session.controllers.js ajustando consulta de userSession con Prisma; comparte cambios en el mismo controlador.

Revisores sugeridos

  • CrisNAC
  • leoAchu16
  • J-Kanami-PS

Poema

🐰 Un secreto fuerte protege el reinado,
contraseñas hasheadas, bien resguardadas.
Con next y errores bien organizados,
la sesión viaja segura y validada.
¡Cambios confiables que brillan en verde! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título describe de forma concisa y clara las principales adiciones de seguridad: validación de contraseñas y JWT_SECRET.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-558

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/config/env.config.js`:
- Around line 16-27: The validateSecretStrength function currently measures
secret.length without normalizing, so a secret of only spaces can pass; change
it to trim the secret (e.g., const normalized = secret == null ? '' :
secret.trim()) and use normalized.length for the minLength check, and explicitly
reject empty or whitespace-only secrets by throwing an Error (not just a
warning) with the same messaging for production; update any occurrences of
secret.length in validateSecretStrength to use the normalized value and ensure
null/undefined inputs are handled.

In `@src/lib/utils/password.utils.js`:
- Around line 51-55: The current catch in the bcrypt.compare call swallows
operational errors and returns false (causing a 401 downstream); update the
catch in src/lib/utils/password.utils.js (the bcrypt.compare(...) call) to
rethrow the original error (or throw a wrapped error preserving the original)
instead of returning false so real failures propagate to the global
errorHandler; keep returning false only when bcrypt.compare resolves to false
(password mismatch), not on exceptions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b05bcc82-cf50-4fa8-a13a-1ac7b1125175

📥 Commits

Reviewing files that changed from the base of the PR and between f300392 and 1976822.

📒 Files selected for processing (3)
  • src/config/env.config.js
  • src/lib/utils/password.utils.js
  • src/modules/session/controllers/session.controllers.js

Comment thread src/config/env.config.js
Comment thread src/lib/utils/password.utils.js Outdated
@sonarqubecloud

sonarqubecloud Bot commented Jun 2, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants