Skip to content
Merged
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
74 changes: 55 additions & 19 deletions src/middleware/security/requireCsrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,72 @@ import crypto from 'crypto';
import { ALLOWED_ORIGINS } from '@constants/globalConts.js';
import { UnauthorizedError } from '@middleware/error/index.js';
import { NextFunction, Request, Response } from 'express';
import { compareHashTokens } from '@utils/tokens.js';
import logger from '@utils/logger.js';

export const csrfMiddleware = (req: Request, _res: Response, next: NextFunction) => {
const unsafeMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];
if (!unsafeMethods.includes(req.method)) return next();
const unsafeMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];

const normalizeToken = (val: string): string => {
try {
return decodeURIComponent(val).replace(/^"|"$/g, '').trim();
} catch {
return val.replace(/^"|"$/g, '').trim();
}
};

const origin = req.headers.origin || req.headers.referer;
const safeCompare = (a: string, b: string): boolean => {
const aBuf = Buffer.from(a);
const bBuf = Buffer.from(b);

if (aBuf.length !== bBuf.length) return false;

return crypto.timingSafeEqual(aBuf, bBuf);
};
Comment on lines +17 to +24

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

safeCompare duplicates the existing compareHashTokens helper in @utils/tokens.js (both do a length check and crypto.timingSafeEqual). Duplicating this logic increases maintenance cost and leaves the exported util unused after this change. Prefer reusing the shared helper (or moving/renaming so there is a single canonical implementation).

Copilot uses AI. Check for mistakes.

if (!origin) {
throw new UnauthorizedError('Missing Origin or Referer header');
export const csrfMiddleware = (req: Request, _res: Response, next: NextFunction) => {
if (!unsafeMethods.includes(req.method)) {
return next();
}

const originUrl = new URL(origin as string).origin;
if (!ALLOWED_ORIGINS.includes(originUrl)) {
throw new UnauthorizedError('Invalid origin');
const rawOrigin = req.headers.origin || req.headers.referer;

if (rawOrigin) {
try {
const originUrl = new URL(rawOrigin as string).origin;

if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));
}
Comment on lines +31 to +42

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

The middleware no longer rejects unsafe requests when both Origin and Referer headers are missing (it simply skips origin validation if rawOrigin is falsy). This is a security regression compared to the previous behavior and weakens CSRF defenses for user-agents/clients that omit these headers. Consider restoring a hard-fail for unsafe methods when neither header is present (or making the exception explicit and gated by trusted internal clients).

Suggested change
const rawOrigin = req.headers.origin || req.headers.referer;
if (rawOrigin) {
try {
const originUrl = new URL(rawOrigin as string).origin;
if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));
}
const originHeader = Array.isArray(req.headers.origin) ? req.headers.origin[0] : req.headers.origin;
const refererHeader = Array.isArray(req.headers.referer) ? req.headers.referer[0] : req.headers.referer;
const rawOrigin = originHeader || refererHeader;
if (!rawOrigin) {
return next(new UnauthorizedError('Origin or Referer header required'));
}
try {
const originUrl = new URL(rawOrigin).origin;
if (!ALLOWED_ORIGINS.includes(originUrl)) {
return next(new UnauthorizedError('Invalid origin'));
}
} catch {
return next(new UnauthorizedError('Invalid origin format'));

Copilot uses AI. Check for mistakes.
}

const csrfHeader = req.headers['x-csrf-token'];
const csrfToken = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader;
const csrfCookie = req.cookies['csrf-token'];
const csrfHeaderRaw = req.headers['x-csrf-token'];
const csrfHeader = Array.isArray(csrfHeaderRaw) ? csrfHeaderRaw[0] : csrfHeaderRaw;

if (!csrfToken || !csrfCookie) {
throw new UnauthorizedError('CSRF credentials missing');
const csrfCookieRaw = req.cookies['csrf-token'];

if (!csrfHeader || !csrfCookieRaw) {
return next(new UnauthorizedError('CSRF credentials missing'));
}

const tokenMatch = compareHashTokens(csrfToken, csrfCookie);
const csrfToken = normalizeToken(csrfHeader);
const csrfCookie = normalizeToken(csrfCookieRaw);

const isValid = safeCompare(csrfToken, csrfCookie);

if (!isValid) {
logger.warn(`'CSRF DEBUG',
header: ${csrfHeader},
cookie: ${csrfCookieRaw},
normalizedHeader: ${csrfToken},
normalizedCookie: ${csrfCookie},
headerLength: ${csrfToken.length},
cookieLength: ${csrfCookie.length},
`);
Comment on lines +59 to +67

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

logger.warn logs raw and normalized CSRF token values from both the header and cookie. CSRF tokens are secrets and can be replayed; writing them to logs is a sensitive data exposure risk (and warn level is likely to be retained in production). Remove token values from logs (at most log non-sensitive metadata like lengths or a one-way hash) and ensure any debug logging is gated behind a non-production flag and uses an appropriate log level.

Copilot uses AI. Check for mistakes.

if (!tokenMatch) {
throw new UnauthorizedError('Invalid CSRF token');
return next(new UnauthorizedError('Invalid CSRF token'));
}

next();
return next();
};
Loading