Skip to content

Update Cookies (Error Coming because of different domain names of fro…#21

Merged
benazeem merged 1 commit into
mainfrom
fix/csrfTokenError
Apr 15, 2026
Merged

Update Cookies (Error Coming because of different domain names of fro…#21
benazeem merged 1 commit into
mainfrom
fix/csrfTokenError

Conversation

@benazeem

@benazeem benazeem commented Apr 15, 2026

Copy link
Copy Markdown
Owner

…ntend and backend ), the csrf header was not being able to set by the frontend

Summary by CodeRabbit

  • Security

    • Enhanced CORS validation with dynamic request origin checking and detailed logging of blocked requests.
    • Simplified CSRF protection mechanism with synchronous validation and clearer error messages for missing or invalid tokens.
  • Chores

    • Updated cookie domain configuration for production environments.
    • Optimized session data structure by removing unnecessary token hash storage.

…ntend and backend ), the csrf header was not being able to set by the frontend
Copilot AI review requested due to automatic review settings April 15, 2026 23:34
@coderabbitai

coderabbitai Bot commented Apr 15, 2026

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

The PR refactors CSRF token validation from database-backed hash verification to a simpler cookie-header comparison approach. It removes the csrfTokenHash field from session storage, updates CORS configuration to use dynamic origin validation, and simplifies the CSRF middleware from asynchronous to synchronous.

Changes

Cohort / File(s) Summary
CORS Configuration
src/config/corsConfig.ts
Replaced static origin configuration with a custom function that dynamically validates each request origin, logging blocked origins and denying requests when origin is absent or not in the allowlist.
CSRF Token Validation
src/middleware/security/requireCsrf.ts
Simplified middleware from async to sync by removing database-backed validation; now directly compares csrf-token cookie against x-csrf-token header instead of verifying against stored hash. Added distinct error messages for missing vs. invalid tokens.
Session Model & Auth Service
src/models/Session.ts, src/modules/auth/auth.service.ts
Removed csrfTokenHash field from session schema and eliminated its projection/update in token refresh flow, simplifying session storage.
Auth Module
src/modules/auth/auth.controller.ts, src/modules/auth/utils/createSessionPayload.ts
Removed csrfTokenHash from session payload creation, added conditional domain setting in cookies based on production environment, and applied minor formatting adjustments.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A token journey, simplified at last,
No database hashes to hold our past!
Cookie meets header in swift embrace,
Origins dance in their rightful place,
Sessions grow lighter, the code runs fast! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title is only partially related to the changeset. It mentions updating cookies due to domain name differences, which aligns with the domain configuration change in auth.controller.ts, but the PR's primary focus is refactoring CSRF validation from database-backed to stateless token comparison across multiple files. Revise the title to reflect the main change: consider 'Refactor CSRF validation to stateless token comparison' or 'Simplify CSRF middleware and remove database-backed validation' to better represent the core refactoring work.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/csrfTokenError

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.

@benazeem benazeem merged commit 7136ab3 into main Apr 15, 2026
5 of 6 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adjusts the auth cookie/CORS/CSRF setup to better support frontend/backend running on different (sub)domains, and simplifies CSRF verification logic.

Changes:

  • Removed csrfTokenHash persistence/usage from session creation, refresh flow, and the Session model.
  • Updated cookie configuration to optionally set a production domain (via PARENT_DOMAIN) and reformatted cookie-setting helpers.
  • Simplified CSRF middleware to validate x-csrf-token against the csrf-token cookie and tightened origin allowlisting; updated CORS origin handling to a callback-based allowlist.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/modules/auth/utils/createSessionPayload.ts Stops storing CSRF token hash in new session payloads.
src/modules/auth/auth.service.ts Removes CSRF hash selection/update during refresh; still rotates CSRF token returned to client.
src/modules/auth/auth.controller.ts Adds production cookie domain support and refactors cookie-setting formatting.
src/models/Session.ts Removes csrfTokenHash from the session schema.
src/middleware/security/requireCsrf.ts Replaces DB-backed CSRF verification with cookie/header equality + origin check.
src/config/corsConfig.ts Switches CORS origin to a callback allowlist behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +12 to 16
const origin = req.headers.origin as string | undefined;

if (origin && !ALLOWED_ORIGINS.includes(origin)) {
throw new UnauthorizedError('Invalid origin');
}

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

req.headers.origin can be string | string[] | undefined at runtime (multiple Origin headers). Casting to string can cause false rejections (array won’t match the allowlist). Normalize it the same way you do for x-csrf-token (pick the first element if it’s an array) before checking ALLOWED_ORIGINS.

Copilot uses AI. Check for mistakes.
Comment thread src/config/corsConfig.ts
callback(null, true);
} else {
console.warn('Blocked by CORS:', origin);
return callback(null, false);

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

In the CORS origin callback, callback(null, false) disables CORS headers but still allows the request to continue through the app (it’s not an actual rejection). If the intent is to actively reject disallowed origins (especially to fail preflights loudly and reduce server work), consider passing an error to the callback (or returning a 403) instead of false.

Suggested change
return callback(null, false);
return callback(new Error(`Blocked by CORS: ${origin}`));

Copilot uses AI. Check for mistakes.
Comment on lines 30 to 36
const cookieOptions: CookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
domain: process.env.NODE_ENV === 'production' ? process.env.PARENT_DOMAIN : undefined,
maxAge: ACCESS_AGE,
};

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

cookieOptions now sets a domain in production, but logoutController still clears cookies without specifying the same domain/secure/sameSite options. In browsers, clearCookie() won’t remove a cookie that was set with a Domain attribute unless you clear it with matching options, which can leave auth cookies stuck in prod. Consider centralizing cookie options for both set + clear (and ensure PARENT_DOMAIN is validated so this doesn’t silently misconfigure cookies).

Copilot uses AI. Check for mistakes.
Comment on lines +25 to 29
const csrfCookie = req.cookies['csrf-token'];

try {
verifyToken(csrfTokenValue, session.csrfTokenHash);
} catch {
throw new UnauthorizedError();
if (!csrfCookie || csrfCookie !== csrfToken) {
throw new UnauthorizedError('Invalid CSRF token');
}

Copilot AI Apr 15, 2026

Copy link

Choose a reason for hiding this comment

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

This middleware no longer validates the CSRF token against a server-side secret (previously SessionModel + csrfTokenHash), and instead accepts any request where the header matches a non-HttpOnly cookie. That’s a security regression because it removes per-session binding and makes CSRF protection fully dependent on the attacker being unable to set a cookie for the site (which becomes more relevant now that cookies can be shared via Domain). Consider reintroducing session-bound verification (DB-backed hash, or an HMAC/signed token derived from sessionId/refresh token) rather than raw equality.

Copilot uses AI. Check for mistakes.
@coderabbitai coderabbitai Bot mentioned this pull request Apr 18, 2026
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