Repository navigation
Update Cookies (Error Coming because of different domain names of fro… #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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'); | ||
| } | ||
|
Comment on lines
+12
to
16
|
||
|
|
||
| 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'); | ||
| } | ||
|
Comment on lines
+25
to
29
|
||
|
|
||
| next(); | ||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,32 +23,35 @@ 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, | ||
| }; | ||
|
Comment on lines
30
to
36
|
||
|
|
||
| /** 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 ──────────────────────────────────────────────────────────── | ||
|
|
||
| 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'); | ||
|
|
||
There was a problem hiding this comment.
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 offalse.