diff --git a/src/middleware/auth/requireAuth.ts b/src/middleware/auth/requireAuth.ts index 5739456..b210def 100644 --- a/src/middleware/auth/requireAuth.ts +++ b/src/middleware/auth/requireAuth.ts @@ -1,19 +1,15 @@ // requireAuth.ts -import type { Request, Response, NextFunction } from "express"; -import jwt from "jsonwebtoken"; -import { UnauthenticatedError } from "@middleware/error/index.js"; -import { AccountStatus } from "@constants/userConsts.js"; +import type { Request, Response, NextFunction } from 'express'; +import jwt from 'jsonwebtoken'; +import { UnauthenticatedError } from '@middleware/error/index.js'; +import { AccountStatus } from '@constants/userConsts.js'; -export const authMiddleware = async ( - req: Request, - res: Response, - next: NextFunction -) => { +export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => { try { - const accessToken = req.cookies["access-token"]; + const accessToken = req.cookies['access-token']; if (!accessToken) { - throw new UnauthenticatedError("Authentication required"); + throw new UnauthenticatedError('Authentication required'); } let decoded; @@ -21,16 +17,16 @@ export const authMiddleware = async ( decoded = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET!) as { userId: string; sessionId: string; - role:"user"|"admin"; - accountStatus?:AccountStatus; + role: 'user' | 'admin'; + accountStatus?: AccountStatus; }; } catch (err) { - throw new UnauthenticatedError("Authentication required"); + throw new UnauthenticatedError('Authentication required'); } - + // attach user + sessionId to request req.user = { id: decoded.userId, role: decoded.role, accountStatus: decoded.accountStatus }; - req.sessionId = decoded.sessionId; + req.sessionId = decoded.sessionId; return next(); } catch (err) { next(err); diff --git a/src/middleware/security/requireCsrf.ts b/src/middleware/security/requireCsrf.ts index 420a9e2..f87ad98 100644 --- a/src/middleware/security/requireCsrf.ts +++ b/src/middleware/security/requireCsrf.ts @@ -1,31 +1,37 @@ +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'; export const csrfMiddleware = (req: Request, _res: Response, next: NextFunction) => { const unsafeMethods = ['POST', 'PUT', 'PATCH', 'DELETE']; + if (!unsafeMethods.includes(req.method)) return next(); - if (!unsafeMethods.includes(req.method)) { - return next(); - } + const origin = req.headers.origin || req.headers.referer; - const origin = req.headers.origin as string | undefined; + if (!origin) { + throw new UnauthorizedError('Missing Origin or Referer header'); + } - if (origin && !ALLOWED_ORIGINS.includes(origin)) { + const originUrl = new URL(origin as string).origin; + if (!ALLOWED_ORIGINS.includes(originUrl)) { throw new UnauthorizedError('Invalid origin'); } const csrfHeader = req.headers['x-csrf-token']; const csrfToken = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader; + const csrfCookie = req.cookies['csrf-token']; - if (!csrfToken) { - throw new UnauthorizedError('Missing CSRF token'); + if (!csrfToken || !csrfCookie) { + throw new UnauthorizedError('CSRF credentials missing'); } - const csrfCookie = req.cookies['csrf-token']; + const tokenMatch = compareHashTokens(csrfToken, csrfCookie); - if (!csrfCookie || csrfCookie !== csrfToken) { + if (!tokenMatch) { throw new UnauthorizedError('Invalid CSRF token'); } + next(); }; diff --git a/src/utils/tokens.ts b/src/utils/tokens.ts index 58516fb..cc77169 100644 --- a/src/utils/tokens.ts +++ b/src/utils/tokens.ts @@ -1,76 +1,72 @@ -import jwt, { type SignOptions } from "jsonwebtoken"; -import crypto from "crypto"; -import type { Types } from "mongoose"; -import { UnauthenticatedError } from "@middleware/error/index.js"; -import { AccountStatus } from "@constants/userConsts.js"; +import jwt, { type SignOptions } from 'jsonwebtoken'; +import crypto from 'crypto'; +import type { Types } from 'mongoose'; +import { UnauthenticatedError } from '@middleware/error/index.js'; +import { AccountStatus } from '@constants/userConsts.js'; -const ACCESS_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env - .ACCESS_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; +const ACCESS_TOKEN_EXPIRES_IN: SignOptions['expiresIn'] = process.env + .ACCESS_TOKEN_EXPIRES_IN as SignOptions['expiresIn']; const ACCESS_TOKEN_SECRET: string = process.env.ACCESS_TOKEN_SECRET!; -const REFRESH_TOKEN_EXPIRES_IN: SignOptions["expiresIn"] = process.env - .REFRESH_TOKEN_EXPIRES_IN as SignOptions["expiresIn"]; +const REFRESH_TOKEN_EXPIRES_IN: SignOptions['expiresIn'] = process.env + .REFRESH_TOKEN_EXPIRES_IN as SignOptions['expiresIn']; const REFRESH_TOKEN_SECRET: string = process.env.REFRESH_TOKEN_SECRET!; export function generateVerificationToken(bytes = 32) { - const raw = crypto.randomBytes(bytes).toString("hex"); - const hash = crypto.createHash("sha256").update(raw).digest("hex"); + const raw = crypto.randomBytes(bytes).toString('hex'); + const hash = crypto.createHash('sha256').update(raw).digest('hex'); return { raw, hash }; } export function verifyToken(rawToken: string, tokenHash: string) { - const providedHash = crypto - .createHash("sha256") - .update(rawToken) - .digest("hex"); - const tokenHashBuffer = Buffer.from(tokenHash, "hex"); - const providedHashBuffer = Buffer.from(providedHash, "hex"); + const providedHash = crypto.createHash('sha256').update(rawToken).digest('hex'); + const tokenHashBuffer = Buffer.from(tokenHash, 'hex'); + const providedHashBuffer = Buffer.from(providedHash, 'hex'); // prevent timing attacks if ( tokenHashBuffer.length !== providedHashBuffer.length || !crypto.timingSafeEqual(tokenHashBuffer, providedHashBuffer) ) { - throw new UnauthenticatedError("Invalid or expired token"); + throw new UnauthenticatedError('Invalid or expired token'); } return true; } export function compareHashTokens(hash1: string, hash2: string): boolean { - const hash1Buffer = Buffer.from(hash1, "hex"); - const hash2Buffer = Buffer.from(hash2, "hex"); - if ( - hash1Buffer.length !== hash2Buffer.length || - !crypto.timingSafeEqual(hash1Buffer, hash2Buffer) - ) { + const hash1Buffer = Buffer.from(hash1, 'utf-8'); + const hash2Buffer = Buffer.from(hash2, 'utf-8'); + if (hash1Buffer.length !== hash2Buffer.length) { return false; } - return true; + + return crypto.timingSafeEqual(hash1Buffer, hash2Buffer); } export function hashToken(rawToken: string) { - return crypto.createHash("sha256").update(rawToken).digest("hex"); + return crypto.createHash('sha256').update(rawToken).digest('hex'); } export function generateSessionId() { - return crypto.randomBytes(32).toString("hex"); + return crypto.randomBytes(32).toString('hex'); } -export function generateAccessToken(userId: Types.ObjectId, sessionId: string, role: string, accountStatus?: AccountStatus) { +export function generateAccessToken( + userId: Types.ObjectId, + sessionId: string, + role: string, + accountStatus?: AccountStatus +) { return jwt.sign({ userId, sessionId, role, accountStatus }, ACCESS_TOKEN_SECRET, { expiresIn: ACCESS_TOKEN_EXPIRES_IN, }); } -export function generateRefreshToken( - userId: Types.ObjectId, - sessionId: string, - reduceTime: boolean = false -) { +export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) { return jwt.sign({ userId, sessionId }, REFRESH_TOKEN_SECRET, { expiresIn: REFRESH_TOKEN_EXPIRES_IN, }); } export function generateCsrfToken() { - const token = crypto.randomBytes(24).toString("hex"); + const token = crypto.randomBytes(24).toString('hex'); return token; }