From 140a265612bce8ccedfe591b2feace69b63dabfb Mon Sep 17 00:00:00 2001 From: Mohd Azeem Malik Date: Thu, 16 Apr 2026 05:03:59 +0530 Subject: [PATCH] Update Cookies (Error Coming because of different domain names of frontend and backend ), the csrf header was not being able to set by the frontend --- src/config/corsConfig.ts | 11 ++++-- src/middleware/security/requireCsrf.ts | 38 +++++++------------ src/models/Session.ts | 1 - src/modules/auth/auth.controller.ts | 23 +++++------ src/modules/auth/auth.service.ts | 3 +- .../auth/utils/createSessionPayload.ts | 1 - 6 files changed, 35 insertions(+), 42 deletions(-) diff --git a/src/config/corsConfig.ts b/src/config/corsConfig.ts index c4e7ae4..160d6e9 100644 --- a/src/config/corsConfig.ts +++ b/src/config/corsConfig.ts @@ -2,12 +2,17 @@ import { ALLOWED_ORIGINS } from '@constants/globalConts.js'; import type { CorsOptions } from 'cors'; const getCorsConfig = (): CorsOptions => { - const isProduction = process.env.NODE_ENV === 'production'; - const allowedOrigin = ALLOWED_ORIGINS.filter((origin): origin is string => origin !== undefined); return { - origin: allowedOrigin, + origin: (origin, callback) => { + if (!origin || allowedOrigin.includes(origin)) { + callback(null, true); + } else { + console.warn('Blocked by CORS:', origin); + return callback(null, false); + } + }, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'], diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts index 1dc05eb..420a9e2 100644 --- a/src/middleware/security/requireCsrf.ts +++ b/src/middleware/security/requireCsrf.ts @@ -1,41 +1,31 @@ -import type { Request, Response, NextFunction } from 'express'; -import { UnauthorizedError } from '@middleware/error/index.js'; -import { SessionModel } from '@models/Session.js'; -import { verifyToken } from '@utils/tokens.js'; import { ALLOWED_ORIGINS } from '@constants/globalConts.js'; +import { UnauthorizedError } from '@middleware/error/index.js'; +import { NextFunction, Request, Response } from 'express'; -export const csrfMiddleware = async (req: Request, res: Response, next: NextFunction) => { +export const csrfMiddleware = (req: Request, _res: Response, next: NextFunction) => { const unsafeMethods = ['POST', 'PUT', 'PATCH', 'DELETE']; + if (!unsafeMethods.includes(req.method)) { return next(); } - const origin = req.header('Origin') || req.headers['origin'] || req.headers.origin; - if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { + const origin = req.headers.origin as string | undefined; + + if (origin && !ALLOWED_ORIGINS.includes(origin)) { throw new UnauthorizedError('Invalid origin'); } - const csrfToken = req.headers['x-csrf-token']; + const csrfHeader = req.headers['x-csrf-token']; + const csrfToken = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader; + if (!csrfToken) { - throw new UnauthorizedError(); + throw new UnauthorizedError('Missing CSRF token'); } - const csrfTokenValue = Array.isArray(csrfToken) ? csrfToken[0] : csrfToken; - - const session = await SessionModel.findOne({ - sessionId: req.sessionId, - valid: true, - revokedAt: null, - }).select('+csrfTokenHash'); - if (!session) { - throw new UnauthorizedError(); - } + 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'); } - next(); }; diff --git a/src/models/Session.ts b/src/models/Session.ts index 6a2e476..1e06d5f 100644 --- a/src/models/Session.ts +++ b/src/models/Session.ts @@ -31,7 +31,6 @@ const sessionSchema = new Schema({ cpu: { type: String }, engine: { type: String }, refreshTokenHash: { type: String, required: true }, - csrfTokenHash: { type: String, required: true }, expiresIn: { type: Date, required: true }, createdAt: { type: Date, default: Date.now }, lastUsedAt: { type: Date, default: Date.now }, diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 410a0dd..394dea7 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -23,23 +23,27 @@ import { sendSuccess } from '@shared/response.js'; // ─── Cookie Configuration ─────────────────────────────────────────────────── -const CSRF_AGE = 15 * 24 * 60 * 60 * 1000; // 15 days +const CSRF_AGE = 15 * 24 * 60 * 60 * 1000; // 15 days const REFRESH_AGE = 15 * 24 * 60 * 60 * 1000; // 15 days -const ACCESS_AGE = 30 * 60 * 1000; // 30 minutes +const ACCESS_AGE = 30 * 60 * 1000; // 30 minutes 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, }; /** Sets the three auth cookies (access / refresh / csrf) on the response. */ -function setAuthCookies(res: Response, tokens: { accessToken: string; refreshToken: string; csrfToken: string }) { +function setAuthCookies( + res: Response, + tokens: { accessToken: string; refreshToken: string; csrfToken: string } +) { res - .cookie('access-token', tokens.accessToken, { ...cookieOptions, maxAge: ACCESS_AGE }) + .cookie('access-token', tokens.accessToken, { ...cookieOptions, maxAge: ACCESS_AGE }) .cookie('refresh-token', tokens.refreshToken, { ...cookieOptions, maxAge: REFRESH_AGE }) - .cookie('csrf-token', tokens.csrfToken, { ...cookieOptions, httpOnly: false, maxAge: CSRF_AGE }); + .cookie('csrf-token', tokens.csrfToken, { ...cookieOptions, httpOnly: false, maxAge: CSRF_AGE }); } // ─── Controllers ──────────────────────────────────────────────────────────── @@ -47,8 +51,7 @@ function setAuthCookies(res: Response, tokens: { accessToken: string; refreshTok export const registerController = async (req: Request, res: Response) => { const body = req.validatedBody as RegisterInput; const userAgent = req.headers['user-agent'] || 'unknown'; - const ip = - req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; + const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; const { user, tokens } = await registerUser({ ...body, userAgent, ip }); @@ -70,8 +73,7 @@ export const registerController = async (req: Request, res: Response) => { export const loginController = async (req: Request, res: Response) => { const body = req.validatedBody as LoginInput; const userAgent = req.headers['user-agent'] || 'unknown'; - const ip = - req.socket.remoteAddress || req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip; + const ip = req.socket.remoteAddress || req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip; const { user, tokens } = await loginUser({ ...body, userAgent, ip }); @@ -106,8 +108,7 @@ export const resetPasswordController = async (req: Request, res: Response) => { export const refreshTokenController = async (req: Request, res: Response) => { const reqRefreshToken = req.cookies['refresh-token']; const userAgent = req.headers['user-agent'] || 'unknown'; - const ip = - req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; + const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.ip || req.socket.remoteAddress; if (!reqRefreshToken) { throw new UnauthenticatedError('No refresh token, authentication failed'); diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index ae34ed7..0626d5b 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -176,7 +176,7 @@ export async function refreshTokens( userId: decoded.userId, valid: true, revokedAt: null, - }).select('+refreshTokenHash +csrfTokenHash +expiresIn'); + }).select('+refreshTokenHash +expiresIn'); if (!session || !session.refreshTokenHash || !session.expiresIn) { throw new UnauthenticatedError('No refresh token, Authentication failed'); @@ -219,7 +219,6 @@ export async function refreshTokens( }, { refreshTokenHash: hashToken(newRefreshToken), - csrfTokenHash: hashToken(newCsrfToken), lastUsedAt: new Date(), userAgent, ip: Array.isArray(ip) ? ip[0] : ip, diff --git a/src/modules/auth/utils/createSessionPayload.ts b/src/modules/auth/utils/createSessionPayload.ts index 03da6aa..f852425 100644 --- a/src/modules/auth/utils/createSessionPayload.ts +++ b/src/modules/auth/utils/createSessionPayload.ts @@ -33,7 +33,6 @@ export async function createSessionPayload({ browser: userAgentInfo.browser, os: userAgentInfo.os, refreshTokenHash: hashToken(refreshToken), - csrfTokenHash: hashToken(csrfToken), expiresIn: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), createdAt: new Date(), lastUsedAt: new Date(),