All files / src/presentation/http/plugins auth-guard.ts

94.11% Statements 16/17
90.9% Branches 10/11
100% Functions 2/2
94.11% Lines 16/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                      21x 21x     21x 474x   474x 10x     464x 464x 464x   1x 1x                     463x 350x 350x   350x 1x          
import { FastifyReply, FastifyRequest } from 'fastify';
import { TokenService } from '../../../application/user/token-service';
import { InvalidTokenError } from '../../../application/user/errors/invalid-token.error';
import { CSRF_TOKEN_COOKIE } from '../utils/auth-cookies';
 
declare module 'fastify' {
  interface FastifyRequest {
    userId: string;
  }
}
 
const CSRF_HEADER = 'x-csrf-token';
const STATE_CHANGING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
 
export function createAuthGuard(tokenService: TokenService) {
  return async function authGuard(request: FastifyRequest, reply: FastifyReply): Promise<void> {
    const token = request.cookies.access_token;
 
    if (!token) {
      return reply.status(401).send({ status: 'error', message: 'Authentication required' });
    }
 
    try {
      const payload = tokenService.verifyAccessToken(token);
      request.userId = payload.sub;
    } catch (error) {
      Eif (error instanceof InvalidTokenError) {
        return reply.status(401).send({ status: 'error', message: error.message });
      }
 
      throw error;
    }
 
    // Double-submit CSRF check: a cross-site request can ride the SameSite=Strict-protected
    // cookies in same-site-lax edge cases (e.g. top-level GET navigations turned into POSTs by
    // some proxies) or in browsers that don't honor SameSite, but it cannot read this cookie's
    // value to also set it as a header — so a mismatch means the request didn't originate from
    // our own frontend.
    if (STATE_CHANGING_METHODS.has(request.method)) {
      const cookieToken = request.cookies[CSRF_TOKEN_COOKIE];
      const headerToken = request.headers[CSRF_HEADER];
 
      if (!cookieToken || typeof headerToken !== 'string' || headerToken !== cookieToken) {
        return reply.status(403).send({ status: 'error', message: 'Invalid or missing CSRF token' });
      }
    }
  };
}