All files / src/presentation/http/routes auth.routes.ts

100% Statements 90/90
100% Branches 18/18
100% Functions 13/13
100% Lines 90/90

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494                                                                                            21x         21x     22x 22x 22x 22x 22x           22x   22x       17x               22x       1x     22x           22x           22x             22x                                 217x 217x   214x   214x                 3x 1x     2x 1x     1x         22x                                   209x 209x   204x   204x   204x   5x 4x     1x         22x                               10x   10x 1x     9x 9x   3x   3x   3x   6x 5x 5x     1x         22x                             34x   34x 1x     33x                       22x                                         13x   13x   13x   13x               22x                             2x   2x   2x   2x                                                     22x 22x   22x                                         17x   17x       22x                                               12x 12x   8x   8x   8x             8x   4x 3x     1x         22x                                       2x   2x       22x                                           4x 4x   2x   2x   2x             2x   2x 1x     1x          
import type { App } from '../../../infrastructure/http/build-app';
import { RegisterUserUseCase } from '../../../application/user/register-user.use-case';
import { AuthenticateUserUseCase } from '../../../application/user/authenticate-user.use-case';
import { RefreshUserSessionUseCase } from '../../../application/user/refresh-user-session.use-case';
import { RequestVerificationCodeUseCase } from '../../../application/user/request-verification-code.use-case';
import { VerifyPasswordlessCodeUseCase } from '../../../application/user/verify-passwordless-code.use-case';
import { ResetPasswordUseCase } from '../../../application/user/reset-password.use-case';
import { StartDemoSessionUseCase } from '../../../application/demo/start-demo-session.use-case';
import { EmailAlreadyInUseError } from '../../../application/user/errors/email-already-in-use.error';
import { InvalidCredentialsError } from '../../../application/user/errors/invalid-credentials.error';
import { InvalidTokenError } from '../../../application/user/errors/invalid-token.error';
import { InvalidVerificationCodeError } from '../../../application/user/errors/invalid-verification-code.error';
import { DomainError } from '../../../shared/errors/domain-error';
import { PrismaUserRepository } from '../../../infrastructure/database/repositories/prisma-user.repository';
import { PrismaDemoAccountRepository } from '../../../infrastructure/database/repositories/prisma-demo-account.repository';
import { PrismaVaccineRepository } from '../../../infrastructure/database/repositories/prisma-vaccine.repository';
import { CachedVaccineRepository } from '../../../infrastructure/database/repositories/cached-vaccine.repository';
import { redis } from '../../../infrastructure/cache/redis-client';
import { BcryptPasswordHasher } from '../../../infrastructure/security/bcrypt-password-hasher';
import { tokenService } from '../../../infrastructure/security/token-service.instance';
import { tokenRevocationService } from '../../../infrastructure/security/token-revocation-service.instance';
import { verificationCodeService } from '../../../infrastructure/security/verification-code-service.instance';
import { revokeRefreshTokenIfPresent } from '../../../infrastructure/security/revoke-refresh-token';
import { emailService } from '../../../infrastructure/email/email-service.instance';
import { auditLogger } from '../../../infrastructure/audit/audit-logger.instance';
import { prisma } from '../../../infrastructure/database/prisma-client';
import { env } from '../../../shared/config/env';
import { authenticate } from '../plugins/authenticate';
import { REFRESH_TOKEN_COOKIE, clearAuthCookies, setAuthCookies } from '../utils/auth-cookies';
import {
  assistedRequestBodySchema,
  authErrorResponseSchema,
  authSuccessResponseSchema,
  currentUserResponseSchema,
  demoSessionResponseSchema,
  loginBodySchema,
  passwordResetVerifyBodySchema,
  passwordlessVerifyBodySchema,
  registerBodySchema,
  registerResponseSchema,
} from '../schemas/auth.schema';
 
// Tighter than the global 100/min (build-app.ts) — these routes are the highest-value brute-force
// targets (credential stuffing on login, account enumeration on register, token guessing on refresh).
// 10 a minute in production. The value lives in env.ts (`rateLimits`): relaxed under NODE_ENV=test,
// where a spec signs in far more often than that, and in the local compose stack.
const AUTH_RATE_LIMIT = { max: env.rateLimits.authPerMinute, timeWindow: '1 minute' };
 
// Each demo is an account with about seventy rows behind it, kept for a day. A person exploring the
// app clicks it once or twice; ten an hour from one address is already somebody filling the
// database, and that is where the limit sits.
const DEMO_RATE_LIMIT = { max: env.rateLimits.demoPerHour, timeWindow: '1 hour' };
 
export async function authRoutes(app: App) {
  const userRepository = new PrismaUserRepository(prisma);
  const passwordHasher = new BcryptPasswordHasher();
  const registerUserUseCase = new RegisterUserUseCase(userRepository, passwordHasher);
  const authenticateUserUseCase = new AuthenticateUserUseCase(userRepository, passwordHasher, tokenService);
  const refreshUserSessionUseCase = new RefreshUserSessionUseCase(userRepository, tokenService, tokenRevocationService);
 
  // EmailService no-ops when RESEND_API_KEY is unset — the default everywhere except production —
  // so off-production the issued code is written to the log instead. Without that escape hatch the
  // assisted flows cannot be exercised locally or in CI at all, and they fail in the one way they
  // are built never to show: a 200 with nothing behind it.
  const logIssuedCode = env.NODE_ENV !== 'production';
 
  const requestPasswordlessCodeUseCase = new RequestVerificationCodeUseCase(
    userRepository,
    verificationCodeService,
    'passwordless',
    (to, code) => emailService.sendPasswordlessCodeEmail(to, code),
    logIssuedCode,
    // An unknown address gets a code here, and that code creates the account when it is used.
    // Password reset below stays as it was: there is no password to reset on an account that does
    // not exist, and signing someone up from a "forgot my password" screen answers a question
    // nobody asked.
    true,
  );
  const requestPasswordResetCodeUseCase = new RequestVerificationCodeUseCase(
    userRepository,
    verificationCodeService,
    'password-reset',
    (to, code) => emailService.sendPasswordResetCodeEmail(to, code),
    logIssuedCode,
  );
  const verifyPasswordlessCodeUseCase = new VerifyPasswordlessCodeUseCase(
    userRepository,
    verificationCodeService,
    tokenService,
    passwordHasher,
  );
  const resetPasswordUseCase = new ResetPasswordUseCase(
    userRepository,
    verificationCodeService,
    passwordHasher,
    tokenService,
  );
  const startDemoSessionUseCase = new StartDemoSessionUseCase(
    new CachedVaccineRepository(new PrismaVaccineRepository(prisma), redis),
    new PrismaDemoAccountRepository(prisma),
    passwordHasher,
    tokenService,
  );
 
  app.route({
    method: 'POST',
    url: '/auth/register',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Register a new user account',
      description: 'Creates a new parent/caregiver account. Does not authenticate the user automatically.',
      body: registerBodySchema,
      response: {
        201: registerResponseSchema,
        400: authErrorResponseSchema,
        409: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const user = await registerUserUseCase.execute(request.body);
 
        request.log.info({ userId: user.id }, 'auth.register_succeeded');
 
        return reply.status(201).send({
          id: user.id,
          email: user.email,
          name: user.name,
          avatarUrl: user.avatarUrl,
          emailNotificationsEnabled: user.emailNotificationsEnabled,
          createdAt: user.createdAt.toISOString(),
        });
      } catch (error) {
        if (error instanceof EmailAlreadyInUseError) {
          return reply.status(409).send({ status: 'error', message: error.message });
        }
 
        if (error instanceof DomainError) {
          return reply.status(400).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/login',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Authenticate a user',
      description:
        'Validates credentials and sets access and refresh tokens as HTTP-only, Secure, SameSite=Strict cookies. Tokens are never returned in the JSON body.',
      body: loginBodySchema,
      response: {
        200: authSuccessResponseSchema,
        400: authErrorResponseSchema,
        401: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const { accessToken, refreshToken } = await authenticateUserUseCase.execute(request.body);
 
        setAuthCookies(reply, accessToken, refreshToken);
 
        request.log.info('auth.login_succeeded');
 
        return reply.status(200).send({ status: 'ok', message: 'Authenticated successfully' });
      } catch (error) {
        if (error instanceof InvalidCredentialsError) {
          return reply.status(401).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/refresh',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: "Rotate the authenticated user's session",
      description:
        'Reads the refresh_token cookie, validates it, and — if still valid and the user still exists — issues a new access/refresh token pair as HTTP-only cookies. Returns 401 if the cookie is missing, expired, or invalid, which the frontend should treat as a hard session expiry and redirect to /login.',
      response: {
        200: authSuccessResponseSchema,
        401: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      const refreshToken = request.cookies[REFRESH_TOKEN_COOKIE];
 
      if (!refreshToken) {
        return reply.status(401).send({ status: 'error', message: 'Authentication required' });
      }
 
      try {
        const { accessToken, refreshToken: newRefreshToken } = await refreshUserSessionUseCase.execute(refreshToken);
 
        setAuthCookies(reply, accessToken, newRefreshToken);
 
        request.log.info('auth.refresh_succeeded');
 
        return reply.status(200).send({ status: 'ok', message: 'Session refreshed successfully' });
      } catch (error) {
        if (error instanceof InvalidTokenError) {
          clearAuthCookies(reply);
          return reply.status(401).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'GET',
    url: '/auth/me',
    preHandler: authenticate,
    schema: {
      tags: ['Auth'],
      summary: 'Get the authenticated user',
      description: "Returns the currently authenticated user's profile, resolved from the access_token cookie.",
      response: {
        200: currentUserResponseSchema,
        401: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      const user = await userRepository.findById(request.userId);
 
      if (!user) {
        return reply.status(401).send({ status: 'error', message: 'Authentication required' });
      }
 
      return reply.status(200).send({
        id: user.id,
        email: user.email,
        name: user.name,
        avatarUrl: user.avatarUrl,
        emailNotificationsEnabled: user.emailNotificationsEnabled,
        createdAt: user.createdAt.toISOString(),
        demoExpiresAt: user.demoExpiresAt?.toISOString() ?? null,
      });
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/demo',
    config: { rateLimit: DEMO_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Start a session in a new, disposable demo account',
      description:
        'Creates an account already holding a family (two children, their vaccine records, appointments, growth, ' +
        'milestones, medications and professionals), signs the caller into it with the same cookies /auth/login ' +
        'sets, and deletes it with everything in it 24 hours later. Each call makes a new account, so visitors ' +
        'never see each other\'s changes. The account has an undeliverable address and no usable password: its ' +
        'e-mail and password cannot be changed (both ask for the current password), so it cannot be turned into a ' +
        'permanent account, and it sends no e-mail. Limited to a few accounts per client per hour.',
      response: {
        201: demoSessionResponseSchema,
        429: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      const session = await startDemoSessionUseCase.execute();
 
      setAuthCookies(reply, session.accessToken, session.refreshToken);
 
      request.log.info({ userId: session.userId }, 'auth.demo_session_started');
 
      return reply.status(201).send({
        status: 'ok',
        message: 'Demo session started',
        expiresAt: session.expiresAt.toISOString(),
      });
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/logout',
    schema: {
      tags: ['Auth'],
      summary: 'Log out the current user',
      description:
        'Clears the access and refresh token cookies, and revokes the refresh token server-side so a copy ' +
        'leaked before logout can no longer be used to refresh the session.',
      response: {
        200: authSuccessResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      await revokeRefreshTokenIfPresent(request.cookies[REFRESH_TOKEN_COOKIE]);
 
      clearAuthCookies(reply);
 
      request.log.info('auth.logout_succeeded');
 
      return reply.status(200).send({ status: 'ok', message: 'Logged out successfully' });
    },
  });
 
  // ---------------------------------------------------------------------------------------------
  // Assisted flows: proving control of an e-mail address with a 6-digit code, instead of knowing a
  // password. Two shapes of the same machine — sign in without a password, and reset a forgotten
  // one — each a `request` that mails a code and a `verify` that ends in a session.
  //
  // Both `request` routes answer 200 with an identical body whether or not the address has an
  // account, whether or not the mail went out, and whether or not the throttle swallowed it. The
  // response is a receipt for the request, never a statement about the account, or this pair of
  // endpoints would become a way to ask which e-mails are registered in a children's health app.
  //
  // Neither verify route needs the CSRF header: the double-submit check lives in createAuthGuard,
  // which only runs on authenticated routes, and these are public exactly like /auth/login.
  // ---------------------------------------------------------------------------------------------
 
  /**
   * Two messages, because the two flows now promise different things — and neither varies by
   * address, which is the property that matters.
   *
   * Passwordless mails every address, so the hedge would be a lie in the other direction: the code
   * really is on its way, and the account is created when it comes back. Password reset still has
   * nothing to send an unknown address, so its message stays conditional, which is what keeps it
   * from answering "does this address have an account here".
   */
  const PASSWORDLESS_REQUEST_ACCEPTED = 'A code is on its way';
  const RESET_REQUEST_ACCEPTED = 'If that email has an account, a code is on its way';
 
  app.route({
    method: 'POST',
    url: '/auth/passwordless/request',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Request a sign-in code',
      description:
        'Mails a 6-digit code that can be exchanged for a session at /auth/passwordless/verify. An address with ' +
        'no account gets a code too, and using it creates the account — so this endpoint signs people up as well ' +
        'as in, and answering 200 with the same body for every address is true rather than merely uniform. The ' +
        'code is valid for 10 minutes, is single-use, allows 5 attempts, and 5 codes per address per 15 minutes.',
      body: assistedRequestBodySchema,
      response: {
        200: authSuccessResponseSchema,
        400: authErrorResponseSchema,
        429: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      await requestPasswordlessCodeUseCase.execute(request.body);
 
      return reply.status(200).send({ status: 'ok', message: PASSWORDLESS_REQUEST_ACCEPTED });
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/passwordless/verify',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Exchange a sign-in code for a session',
      description:
        'Consumes the code mailed by /auth/passwordless/request and sets the same session cookies /auth/login does. ' +
        'Creates the account when the address has none — this is where sign-up happens, never at the request step, ' +
        'so a mistyped address leaves no row behind. A new account has no name (the client asks after sign-in) and ' +
        'no usable password until its owner sets one through the reset flow. ' +
        'A wrong, expired, already-used or over-attempted code — and an address with no account — all answer 401 ' +
        'with the same message, so nothing can be inferred from the failure.',
      body: passwordlessVerifyBodySchema,
      response: {
        200: authSuccessResponseSchema,
        400: authErrorResponseSchema,
        401: authErrorResponseSchema,
        429: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const { userId, accessToken, refreshToken } = await verifyPasswordlessCodeUseCase.execute(request.body);
 
        setAuthCookies(reply, accessToken, refreshToken);
 
        request.log.info({ userId }, 'auth.passwordless_login_succeeded');
 
        auditLogger.log({
          userId,
          action: 'auth.passwordless_login',
          resourceType: 'User',
          resourceId: userId,
        });
 
        return reply.status(200).send({ status: 'ok', message: 'Authenticated successfully' });
      } catch (error) {
        if (error instanceof InvalidVerificationCodeError) {
          return reply.status(401).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/password-reset/request',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Request a password reset code',
      description:
        'Mails a 6-digit code that can be exchanged for a new password at /auth/password-reset/verify. Answers 200 ' +
        'identically for every address, registered or not. The code is valid for 10 minutes, is single-use, allows ' +
        '5 attempts, and is scoped to this flow — a sign-in code cannot be used to change a password.',
      body: assistedRequestBodySchema,
      response: {
        200: authSuccessResponseSchema,
        400: authErrorResponseSchema,
        429: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      await requestPasswordResetCodeUseCase.execute(request.body);
 
      return reply.status(200).send({ status: 'ok', message: RESET_REQUEST_ACCEPTED });
    },
  });
 
  app.route({
    method: 'POST',
    url: '/auth/password-reset/verify',
    config: { rateLimit: AUTH_RATE_LIMIT },
    schema: {
      tags: ['Auth'],
      summary: 'Set a new password with a reset code',
      description:
        'Consumes the code mailed by /auth/password-reset/request, replaces the password, and signs the user in with ' +
        'fresh cookies. Every other session is ended: refresh tokens issued before the reset stop working, so a ' +
        'device the user was resetting *because of* keeps no way back in. Access tokens already issued elsewhere ' +
        'still work until they expire (15 minutes). Failures answer 401 with the same message as any bad code.',
      body: passwordResetVerifyBodySchema,
      response: {
        200: authSuccessResponseSchema,
        400: authErrorResponseSchema,
        401: authErrorResponseSchema,
        429: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const { userId, accessToken, refreshToken } = await resetPasswordUseCase.execute(request.body);
 
        setAuthCookies(reply, accessToken, refreshToken);
 
        request.log.info({ userId }, 'auth.password_reset_succeeded');
 
        auditLogger.log({
          userId,
          action: 'auth.password_reset',
          resourceType: 'User',
          resourceId: userId,
        });
 
        return reply.status(200).send({ status: 'ok', message: 'Password updated successfully' });
      } catch (error) {
        if (error instanceof InvalidVerificationCodeError) {
          return reply.status(401).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
}