feat(auth): cookies helpers and CSRF middleware
This commit is contained in:
34
packages/backend/src/lib/cookies.ts
Normal file
34
packages/backend/src/lib/cookies.ts
Normal 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: '/',
|
||||
};
|
||||
}
|
||||
25
packages/backend/src/middleware/csrf.ts
Normal file
25
packages/backend/src/middleware/csrf.ts
Normal 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();
|
||||
}
|
||||
Reference in New Issue
Block a user