import ApplicationComponent from "../ApplicationComponent"; import {Request, Router} from "express"; import crypto from "crypto"; import {BadRequestError} from "../HttpError"; import {AuthMiddleware} from "../auth/AuthComponent"; export default class CsrfProtectionComponent extends ApplicationComponent { private static readonly excluders: ((req: Request) => boolean)[] = []; public static getCSRFToken(session: Express.Session): string { if (typeof session.csrf !== 'string') { session.csrf = crypto.randomBytes(64).toString('base64'); } return session.csrf; } public static addExcluder(excluder: (req: Request) => boolean) { this.excluders.push(excluder); } public async handle(router: Router): Promise { router.use(async (req, res, next) => { for (const excluder of CsrfProtectionComponent.excluders) { if (excluder(req)) return next(); } if (!req.session) { throw new Error('Session is unavailable.'); } res.locals.getCSRFToken = () => { return CsrfProtectionComponent.getCSRFToken(req.session!); }; if (!['GET', 'HEAD', 'OPTIONS'].find(s => s === req.method)) { try { if (!await req.as(AuthMiddleware).getAuthGuard().isAuthenticatedViaRequest(req)) { if (req.session.csrf === undefined) { return next(new InvalidCsrfTokenError(req.baseUrl, `You weren't assigned any CSRF token.`)); } else if (req.body.csrf === undefined) { return next(new InvalidCsrfTokenError(req.baseUrl, `You didn't provide any CSRF token.`)); } else if (req.session.csrf !== req.body.csrf) { return next(new InvalidCsrfTokenError(req.baseUrl, `Tokens don't match.`)); } } } catch (e) { return next(e); } } next(); }); } } class InvalidCsrfTokenError extends BadRequestError { constructor(url: string, details: string, cause?: Error) { super( `Invalid CSRF token`, `${details} We can't process this request. Please try again.`, url, cause ); } get name(): string { return 'Invalid CSRF Token'; } get errorCode(): number { return 401; } }