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,34 @@
import type { CookieOptions } from 'express';
export const SID_COOKIE = 'flashcard_sid';
export const CSRF_COOKIE = 'flashcard_csrf';
export const CSRF_HEADER = 'x-csrf-token';
export function sidCookieOptions(expiresAtSec: number): CookieOptions {
return {
httpOnly: true,
sameSite: 'lax',
secure: process.env.COOKIE_SECURE === 'true',
path: '/',
expires: new Date(expiresAtSec * 1000),
};
}
export function csrfCookieOptions(expiresAtSec: number): CookieOptions {
return {
httpOnly: false,
sameSite: 'lax',
secure: process.env.COOKIE_SECURE === 'true',
path: '/',
expires: new Date(expiresAtSec * 1000),
};
}
export function clearCookieOptions(): CookieOptions {
return {
httpOnly: true,
sameSite: 'lax',
secure: process.env.COOKIE_SECURE === 'true',
path: '/',
};
}

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();
}