Repository navigation
Update CSRF Checks #22
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,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'); | ||||||||||||||||
| } | ||||||||||||||||
|
Comment on lines
+11
to
+15
|
||||||||||||||||
|
|
||||||||||||||||
| if (origin && !ALLOWED_ORIGINS.includes(origin)) { | ||||||||||||||||
| const originUrl = new URL(origin as string).origin; | ||||||||||||||||
|
||||||||||||||||
| 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'); | |
| } |
| 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
|
||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| 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) { | ||||||||||||
|
||||||||||||
| 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; |
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.
Unused
cryptoimport. This will be flagged by linters/formatters and adds noise; remove it (or use it directly instead ofcompareHashTokens).