feat(auth): cookies helpers and CSRF middleware

This commit is contained in:
2026-05-20 22:51:42 +02:00
parent 1ba2cab2e8
commit 0b62aad7d8
4 changed files with 92 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
import { randomBytes } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';
import { CSRF_COOKIE, CSRF_HEADER, csrfCookieOptions } from '../lib/cookies.js';
import { ApiError } from '../lib/errors.js';
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
export function ensureCsrfToken(req: Request, res: Response, next: NextFunction): void {
if (!req.cookies?.[CSRF_COOKIE]) {
const token = randomBytes(24).toString('base64url');
const expires = Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60;
res.cookie(CSRF_COOKIE, token, csrfCookieOptions(expires));
}
next();
}
export function verifyCsrf(req: Request, _res: Response, next: NextFunction): void {
if (SAFE_METHODS.has(req.method)) return next();
const cookieToken = req.cookies?.[CSRF_COOKIE];
const headerToken = req.headers[CSRF_HEADER];
if (!cookieToken || !headerToken || cookieToken !== headerToken) {
return next(new ApiError(403, 'CSRF_MISMATCH', 'CSRF token mismatch'));
}
next();
}