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
28 changes: 12 additions & 16 deletions src/middleware/auth/requireAuth.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
// 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;
try {
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);
Expand Down
24 changes: 15 additions & 9 deletions src/middleware/security/requireCsrf.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import crypto from 'crypto';

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.

Unused crypto import. This will be flagged by linters/formatters and adds noise; remove it (or use it directly instead of compareHashTokens).

Suggested change
import crypto from 'crypto';

Copilot uses AI. Check for mistakes.
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');
}
Comment on lines +11 to +15

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.

This change rejects unsafe-method requests that omit both Origin and Referer headers. Since csrfMiddleware is applied to all private API routes (src/routes/api.ts:20), this can break non-browser clients (mobile apps, server-to-server, CLI) that rely on cookie auth but don't send these headers. If those clients are supported, consider allowing missing Origin/Referer for same-site requests, or gating this strictness behind an environment flag/documented contract.

Copilot uses AI. Check for mistakes.

if (origin && !ALLOWED_ORIGINS.includes(origin)) {
const originUrl = new URL(origin as string).origin;

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.

new URL(origin as string) will throw for non-absolute/invalid values (e.g., Origin: null, malformed Referer). That will turn a bad request into an unhandled exception/500 instead of a clean 401. Wrap URL parsing in a try/catch and convert failures into UnauthorizedError('Invalid origin') (or similar).

Suggested change
const originUrl = new URL(origin as string).origin;
let originUrl: string;
try {
originUrl = new URL(origin as string).origin;
} catch {
throw new UnauthorizedError('Invalid origin');
}

Copilot uses AI. Check for mistakes.
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();
};
64 changes: 30 additions & 34 deletions src/utils/tokens.ts
Original file line number Diff line number Diff line change
@@ -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);
Comment on lines 36 to +43

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.

compareHashTokens now compares UTF-8 bytes of the string values, but the function name and surrounding token utilities imply hex-encoded hashes (and verifyToken uses Buffer.from(..., 'hex')). This mismatch is easy to misuse later (e.g., passing a hex digest expecting byte-level compare). Consider either decoding as 'hex' here as well, or renaming the function to something like constantTimeEqual and documenting that it compares raw strings.

Copilot uses AI. Check for mistakes.
}

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) {

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.

reduceTime is declared but unused. If it's no longer needed, remove it to avoid confusion; if it is needed, wire it into the expiresIn selection (or add a comment explaining why it's intentionally unused).

Suggested change
export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) {
export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) {
// Intentionally kept for API compatibility with callers that may still pass this flag.
// Refresh tokens currently always use the configured default expiration window.
void reduceTime;

Copilot uses AI. Check for mistakes.
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;
}
Loading