Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/config/corsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

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.
}
},

methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
Expand Down
38 changes: 14 additions & 24 deletions src/middleware/security/requireCsrf.ts
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

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.

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

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.

next();
};
1 change: 0 additions & 1 deletion src/models/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
23 changes: 12 additions & 11 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

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.

/** 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 });

Expand All @@ -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 });

Expand Down Expand Up @@ -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');
Expand Down
3 changes: 1 addition & 2 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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,
Expand Down
1 change: 0 additions & 1 deletion src/modules/auth/utils/createSessionPayload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading