Skip to content

feat(security): implement CSRF protection middleware#775

Merged
RUKAYAT-CODER merged 1 commit into
rinafcode:mainfrom
walexjnr:feat/526-csrf-protection
Jun 24, 2026
Merged

feat(security): implement CSRF protection middleware#775
RUKAYAT-CODER merged 1 commit into
rinafcode:mainfrom
walexjnr:feat/526-csrf-protection

Conversation

@walexjnr

Copy link
Copy Markdown
Contributor

Summary

Implements CSRF protection for all state-changing endpoints using the synchronizer token pattern backed by the existing Redis session store.

What's changed

  • New CsrfMiddleware in src/middleware/csrf/csrf.middleware.ts
  • On safe methods (GET, HEAD): generates a token stored in session, returned via X-CSRF-Token response header
  • On state-changing methods (POST, PUT, DELETE, PATCH): validates X-CSRF-Token request header against session using constant-time comparison
  • Token rotated after each successful state-changing request to prevent replay attacks
  • OPTIONS requests pass through unconditionally (CORS preflight)
  • JWT-authenticated requests (Bearer token) bypass CSRF check - Bearer auth is not CSRF-vulnerable
  • Session cookies already use SameSite=strict and httpOnly=true

closes #526

- Add CSRF middleware using synchronizer token pattern with session storage
- Generate tokens with crypto.randomBytes(32) for sufficient entropy
- Use timingSafeEqual for constant-time comparison to prevent timing attacks
- Rotate token after each state-changing request to prevent replay attacks
- Skip CSRF validation for OPTIONS requests (CORS preflight) and
  JWT-authenticated requests (Bearer token auth is not CSRF-vulnerable)
- Expose current token via X-CSRF-Token response header on safe methods
- Session SameSite=strict cookie policy already enforced in session config

closes rinafcode#526
@drips-wave

drips-wave Bot commented Jun 24, 2026

Copy link
Copy Markdown

@walexjnr Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@RUKAYAT-CODER RUKAYAT-CODER 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.

Thank you for contributing to the project

@RUKAYAT-CODER RUKAYAT-CODER merged commit 8fc40d1 into rinafcode:main Jun 24, 2026
0 of 2 checks passed
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.

Implement CSRF protection on all state-changing endpoints

2 participants