Skip to content

feat(auth): integrate production-ready session middleware with secure cookie configurations#679

Open
Aryan0819 wants to merge 2 commits into
GitMetricsLab:mainfrom
Aryan0819:main
Open

feat(auth): integrate production-ready session middleware with secure cookie configurations#679
Aryan0819 wants to merge 2 commits into
GitMetricsLab:mainfrom
Aryan0819:main

Conversation

@Aryan0819
Copy link
Copy Markdown
Contributor

@Aryan0819 Aryan0819 commented Jun 2, 2026

Add session middleware with cookie settings

Related Issue


Description

🧱 The Architectural Context:
Cross-origin resource transactions rely on strict browser-level tracking rules. For session-based authentication to maintain continuity across distinct hosting domains (e.g., a frontend hosted on Netlify communicating with a backend hosted on Render), cookies must be explicitly configured with secure, cross-site transport policies.

❌ The Failure Mechanism:
The original session configuration initialized express-session with default fallback cookie settings. While this setup works flawlessly on localhost where the frontend and backend share a common root network origin, it breaks entirely in production. Modern web browsers block cross-origin state tracking by default, causing the client browser to immediately drop and discard incoming session cookies from the server.

💥 The Impact:
Users are completely unable to log in or maintain an active authentication state on the deployed production application. Although the backend processes validation endpoints successfully and returns validation headers, the browser drops the cookie payload on subsequent API requests, throwing infinite authorization errors.

✅ The Solution:
Updated the session middleware configuration inside service.js to include a dynamic, environment-aware cookie parameter object. By programmatically assessing process.env.NODE_ENV, the cookie scales up its policy permissions to secure: true (forcing HTTPS transmission) and sameSite: "none" (authorizing cross-site storage) explicitly when running in production.


How Has This Been Tested?

Local Interoperability Regression Testing: Verified that local development on localhost:5173 retains cookie assignment under standard lax rules without breaking developer flows.

Production Environmental Simulation: Validated through mock environment settings that the cookie payload structures alter correctly to enforce strict cross-origin permissions when the production flag is triggered.


Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Add session middleware with cookie settings
@netlify
Copy link
Copy Markdown

netlify Bot commented Jun 2, 2026

Deploy Preview for github-spy failed.

Name Link
🔨 Latest commit 2f95591
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a1edcfddde37a0008c7724c

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 43 minutes and 53 seconds. 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1b1e1cba-d4af-48bb-85c9-a2a2df2a7404

📥 Commits

Reviewing files that changed from the base of the PR and between 4b6ae33 and 2f95591.

📒 Files selected for processing (1)
  • backend/config/passportConfig.js
📝 Walkthrough

Walkthrough

Express-session middleware configuration in backend/server.js is updated to explicitly set session cookie options: maxAge is set to 24 hours, secure flag is enabled conditionally for production, and sameSite policy is set to "none" in production and "lax" otherwise.

Changes

Session Cookie Configuration

Layer / File(s) Summary
Session cookie configuration and security settings
backend/server.js
Express-session middleware now explicitly configures session cookies with 24-hour maxAge, enables secure flag in production, and sets sameSite to "none" for production and "lax" otherwise.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related issues

  • GitMetricsLab/github_tracker#373: Addresses the same express-session cookie configuration concerns, adding maxAge and environment-gated secure/sameSite settings for session security.
  • GitMetricsLab/github_tracker#447: Related to express-session cookie settings modifications in backend/server.js, though focused on different sameSite/secure values.

Possibly related PRs

  • GitMetricsLab/github_tracker#467: Both modify backend/server.js session middleware cookie settings (secure and sameSite flags) for session cookie hardening.
  • GitMetricsLab/github_tracker#464: Complementary changes to session/cookie handling—this PR configures express-session cookie attributes while the related PR adjusts CORS/credential behavior to persist those session cookies.

Suggested labels

level:intermediate, quality:clean

Poem

🐰 A rabbit hops through cookie fields,
Securing sessions with maxAge that yields,
Flags set to "none" and "lax" with care,
Environment-aware, a hardened pair!
Sessions now safe for twenty-four hours to bear. 🍪

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: integrating session middleware with secure, production-ready cookie configurations for cross-origin authentication.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description check ✅ Passed The pull request description comprehensively covers all required template sections with detailed explanations of the issue, solution, and testing approach.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@backend/server.js`:
- Around line 36-40: Update session cookie config and add CSRF middleware: set
cookie.httpOnly: true in the express-session config (alongside secure and
sameSite) and install/use csurf (or implement double-submit tokens) to protect
state-changing routes; mount csurf middleware (or token validation) for the auth
routes (functions/handlers handling POST /api/auth/signup and POST
/api/auth/login and the logout handler) and ensure the CSRF token is issued to
the client (e.g., via a secure sameSite cookie or a /api/csrf-token endpoint) so
the client can include it on requests; change the logout route from GET
/api/auth/logout to a non-GET method (e.g., POST) and enforce CSRF verification
in the logout handler as well.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6122e73b-fa3a-452d-a83d-dea89ca7a1af

📥 Commits

Reviewing files that changed from the base of the PR and between 53f820b and 4b6ae33.

📒 Files selected for processing (1)
  • backend/server.js

Comment thread backend/server.js
Comment on lines +36 to +40
cookie: {
maxAge: 24 * 60 * 60 * 1000,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax"
}
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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if CSRF middleware is used in the codebase
echo "=== Searching for CSRF middleware usage ==="
rg -n -i 'csurf|csrf' --type=js

echo ""
echo "=== Checking route handlers for Content-Type validation ==="
rg -n -C3 'app\.(post|put|patch|delete)' --type=js

echo ""
echo "=== Looking at auth routes for potential CSRF concerns ==="
fd -t f 'auth' --extension js --exec cat {}

Repository: GitMetricsLab/github_tracker

Length of output: 2971


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== backend/server.js (lines around 1-120) ==="
nl -ba backend/server.js | sed -n '1,140p'

echo
echo "=== Full search for csurf/csrf usage across repo ==="
rg -n -i 'csurf|csrf' --hidden --glob '!*node_modules/*'

echo
echo "=== Search for CSRF token patterns / middleware ==="
rg -n -i 'csrftoken|csrfToken|x-csrf|xsrf' --hidden --glob '!*node_modules/*'

echo
echo "=== Search for JSON-only / content-type validation on mutation routes ==="
rg -n -i 'content-type|application\/json|req\.is\(.+json' --hidden --glob '!*node_modules/*' --type=js

Repository: GitMetricsLab/github_tracker

Length of output: 180


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== backend/server.js: session/cookie config area ==="
cat -n backend/server.js | sed -n '1,140p'

echo
echo "=== rg: express-session usage ==="
rg -n "express-session" backend/server.js

echo
echo "=== rg: cookie/sameSite/secure/maxAge in backend/server.js ==="
rg -n "cookie|sameSite|secure|maxAge" backend/server.js

echo
echo "=== repo-wide rg: CSRF middleware usage (csurf/csrf) ==="
rg -n -i 'csurf|csrf' --hidden --glob '!*node_modules/*'

echo
echo "=== repo-wide rg: csrfToken / csrftoken patterns ==="
rg -n -i 'csrftoken|csrfToken|x-csrf|xsrf' --hidden --glob '!*node_modules/*'

echo
echo "=== repo-wide rg: content-type enforcement for JSON (req.is / Content-Type checks) ==="
rg -n -i "content-type|application\/json|req\.is\([^)]*json|req\.get\(['\"]Content-Type['\"]\)" --hidden --glob '!*node_modules/*'

echo
echo "=== repo-wide rg: route handlers defined on router.(post|put|patch|delete) ==="
rg -n "router\.(post|put|patch|delete)\(" --hidden --glob '!*node_modules/*' --type=js

Repository: GitMetricsLab/github_tracker

Length of output: 2518


🏁 Script executed:

#!/bin/bash
set -u
shopt -s globstar

echo "=== backend/routes tree (js) ==="
find backend/routes -type f -maxdepth 3 2>/dev/null || true
echo
echo "=== backend/validators tree (js) ==="
find backend/validators -type f -maxdepth 3 2>/dev/null || true
echo

echo "=== repo-wide rg: CSRF middleware usage (csurf/csrf) ==="
rg -n -i 'csurf|csrf' --hidden --glob '!*node_modules/*' || true

echo
echo "=== repo-wide rg: csrfToken / csrftoken patterns ==="
rg -n -i 'csrftoken|csrfToken|x-csrf|xsrf' --hidden --glob '!*node_modules/*' || true

echo
echo "=== repo-wide rg: Content-Type / JSON-only enforcement ==="
rg -n -i "content-type|application\/json|req\.is\([^)]*json|req\.get\(['\"]Content-Type['\"]\)" --hidden --glob '!*node_modules/*' --type=js || true

echo
echo "=== repo-wide rg: mutation route definitions ==="
rg -n "router\.(post|put|patch|delete)\(" backend --hidden --glob '!*node_modules/*' --type=js || true

echo
echo "=== backend/server.js: confirm middleware order ==="
cat -n backend/server.js | sed -n '25,90p'

Repository: GitMetricsLab/github_tracker

Length of output: 2038


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== backend/routes/auth.js ==="
cat -n backend/routes/auth.js

echo
echo "=== backend/validators/validationRequest.js ==="
cat -n backend/validators/validationRequest.js

echo
echo "=== backend/validators/authValidator.js ==="
cat -n backend/validators/authValidator.js

echo
echo "=== repo-wide: search for Content-Type enforcement patterns (simple) ==="
rg -n "Content-Type|application/json|req\.is\(|req\.get\(" backend --hidden --glob '!*node_modules/*' --type=js || true

echo
echo "=== repo-wide: search for csurf/csrf tokens (simple) ==="
rg -n -i "csurf|csrfToken|xsrf|csrftoken|x-csrf" backend --hidden --glob '!*node_modules/*' --type=js || true

Repository: GitMetricsLab/github_tracker

Length of output: 4345


Add CSRF protection for cross-site session cookies (sameSite: "none")

backend/server.js sets express-session to sameSite: "none" in production (with secure enabled), which sends the session cookie on cross-site requests. The repo has no CSRF middleware/tokens (csurf/csrfToken/csrftoken etc. all missing), and the only auth routes are state-changing without CSRF checks: POST /api/auth/signup, POST /api/auth/login, and GET /api/auth/logout. CORS origin restriction does not mitigate CSRF for cookie-based requests.

  • Implement CSRF protection (e.g., csurf or double-submit tokens) for all state-changing endpoints (at least login/logout/signup)
  • Change logout from GET to a non-GET method and protect it with CSRF
  • Set cookie.httpOnly: true explicitly for defense-in-depth
🤖 Prompt for 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.

In `@backend/server.js` around lines 36 - 40, Update session cookie config and add
CSRF middleware: set cookie.httpOnly: true in the express-session config
(alongside secure and sameSite) and install/use csurf (or implement
double-submit tokens) to protect state-changing routes; mount csurf middleware
(or token validation) for the auth routes (functions/handlers handling POST
/api/auth/signup and POST /api/auth/login and the logout handler) and ensure the
CSRF token is issued to the client (e.g., via a secure sameSite cookie or a
/api/csrf-token endpoint) so the client can include it on requests; change the
logout route from GET /api/auth/logout to a non-GET method (e.g., POST) and
enforce CSRF verification in the logout handler as well.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: Production CORS Cookie Drop (Cross-Origin Block)

1 participant