Skip to content

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

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

feat(auth): integrate production-ready session middleware with secure cookie configurations#679
Aryan0819 wants to merge 3 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

Summary by CodeRabbit

  • Security

    • Session cookie timeout configured to 24 hours with secure flag enabled in production and sameSite policy applied based on environment.
  • Style

    • Minor code formatting refinements.

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

netlify Bot commented Jun 2, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 8f9f6de
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a1fa4eb25e3a70008e179f2
😎 Deploy Preview https://deploy-preview-679--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b5c33e8-3f57-4638-bc09-40b7ce4da19c

📥 Commits

Reviewing files that changed from the base of the PR and between 4b6ae33 and 8f9f6de.

📒 Files selected for processing (1)
  • backend/config/passportConfig.js
✅ Files skipped from review due to trivial changes (1)
  • backend/config/passportConfig.js

📝 Walkthrough

Walkthrough

Express-session in backend/server.js now sets session cookie options (24-hour maxAge, secure true in production, sameSite "none" in production otherwise "lax"). backend/config/passportConfig.js has formatting-only whitespace changes in the local strategy responses and serialized session payload.

Changes

Session and Auth

Layer / File(s) Summary
Session cookie configuration
backend/server.js
Express-session middleware explicitly sets cookie.maxAge (24h), cookie.secure when NODE_ENV === 'production', and cookie.sameSite to "none" in production otherwise "lax".
Passport formatting tweaks
backend/config/passportConfig.js
Whitespace/object-formatting changes in the local strategy failure done(...) and the successful-auth session id: user._id.toString() assignment; no behavioral changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I nibble bytes and tidy space,
Cookies set to win the race,
Secure in prod, lax when free,
Twenty-four hours of safety for me. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Changes in backend/config/passportConfig.js (formatting adjustments) are minor and unrelated to the primary #678 objective of fixing production cookie behavior. Remove the passportConfig.js formatting changes or clarify their necessity; focus the PR on the session cookie fix to avoid scope creep.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: updating session middleware with secure, production-aware cookie configurations for cross-origin authentication.
Description check ✅ Passed The description follows the template structure with all major sections: related issue, detailed explanation of problem/solution, testing approach, and type of change clearly marked.
Linked Issues check ✅ Passed Changes to backend/server.js implement the core requirement from #678: environment-aware cookie configuration with secure:true and sameSite:'none' in production to enable cross-origin session persistence.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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