# 🔐 Authentication Module Architecture (2025)

## Overview

The authentication feature in `apps/bff` now follows a layered structure that separates HTTP concerns, orchestration logic, and infrastructure details. This document explains the layout, responsibilities, and integration points so new contributors can quickly locate code and understand the data flow.

## Security Model (TL;DR)

- **Token storage**: Access/refresh token strings are stored in **httpOnly cookies** set by the BFF.
- **API responses**: Auth endpoints return **`user` + `session` (expiry metadata)** — **token strings are never returned to the browser**.
- **Access token validation**: Per-request validation is handled by `GlobalAuthGuard`:
  - verifies JWT signature/claims
  - rejects wrong token type (expects `type: "access"` when present)
  - checks Redis blacklist (revoked access tokens)
- **Refresh token rotation**: `/api/auth/refresh` uses Redis-backed rotation with reuse detection and an **absolute refresh lifetime** (no indefinite extension).
- **CSRF**: Portal fetches token via `GET /api/security/csrf/token` and sends it as `X-CSRF-Token` on unsafe requests.

```
modules/auth/
├── application/
│   └── auth.facade.ts
├── presentation/
│   ├── http/
│   │   ├── auth.controller.ts
│   │   ├── guards/
│   │   └── interceptors/
│   └── strategies/
├── infra/
│   ├── token/
│   ├── rate-limiting/
│   └── workflows/
├── decorators/
├── domain/            (reserved for future policies/types)
└── utils/
```

### Layer Responsibilities

| Layer          | Purpose                                                                     |
| -------------- | --------------------------------------------------------------------------- |
| `presentation` | HTTP surface area (controllers, guards, interceptors, Passport strategies). |
| `application`  | Use-case orchestration (`AuthFacade`), coordinating infra + audit logging.  |
| `infra`        | Technical services: token issuance, rate limiting, WHMCS/SF workflows.      |
| `decorators`   | Shared Nest decorators (e.g., `@Public`).                                   |
| `domain`       | (Future) domain policies, constants, pure type definitions.                 |

## Presentation Layer

### Controllers (`presentation/http/auth.controller.ts`)

- Routes mirror previous `auth-zod.controller.ts` functionality.
- All validation still uses Zod schemas from `@customer-portal/domain` applied via `ZodValidationPipe`.
- Cookies are managed with `setSecureCookie` helper registered in `bootstrap.ts`.

### Guards

- `GlobalAuthGuard`: wraps Passport JWT, checks blacklist via `TokenBlacklistService`.
- `AuthThrottleGuard`: Nest Throttler-based guard for general rate limits.
- `FailedLoginThrottleGuard`: uses `AuthRateLimitService` for login attempt limiting.

### Interceptors

- `LoginResultInterceptor`: ties into `FailedLoginThrottleGuard` to clear counters on success/failure.

### Strategies (`presentation/strategies`)

- `LocalStrategy`: delegates credential validation to `AuthFacade.validateUser`.
- `JwtStrategy`: loads user via `UsersService` and maps to public profile.

## Application Layer

### `AuthFacade`

- Aggregates all auth flows: login/logout, signup, password flows, WHMCS link, token refresh, session logout.
- Injects infrastructure services (token, workflows, rate limiting), audit logging, config, and Prisma.
- Acts as single DI target for controllers, strategies, and guards.

## Infrastructure Layer

### Token (`infra/token`)

- `token.service.ts`: issues/rotates access + refresh tokens, enforces Redis-backed refresh token families.
- `token-blacklist.service.ts`: stores revoked access tokens.

### Rate Limiting (`infra/rate-limiting/auth-rate-limit.service.ts`)

- Built on `rate-limiter-flexible` with Redis storage.
- Exposes methods for login, signup, password reset, refresh token throttling.
- Handles CAPTCHA escalation via headers (config-driven, see env variables).

### Workflows (`infra/workflows`)

- `signup-workflow.service.ts`: orchestrates Salesforce + WHMCS checks and user creation.
- `password-workflow.service.ts`: request reset, change password, set password flows.
- `whmcs-link-workflow.service.ts`: links existing WHMCS accounts with portal users.

## Configuration & Env

Relevant env keys validated in `core/config/env.validation.ts`:

```bash
# Auth rate limits
LOGIN_RATE_LIMIT_LIMIT=5
LOGIN_RATE_LIMIT_TTL=900000
AUTH_REFRESH_RATE_LIMIT_LIMIT=10
AUTH_REFRESH_RATE_LIMIT_TTL=300000

# JWT hardening (optional but recommended in prod)
JWT_ISSUER=customer-portal
JWT_AUDIENCE=portal
JWT_SECRET_PREVIOUS=oldsecret1,oldsecret2

# CAPTCHA options (future integration)
AUTH_CAPTCHA_PROVIDER=none   # none|turnstile|hcaptcha
AUTH_CAPTCHA_SECRET=
AUTH_CAPTCHA_THRESHOLD=0
AUTH_CAPTCHA_ALWAYS_ON=false

# CSRF
CSRF_TOKEN_EXPIRY=3600000
CSRF_SECRET_KEY=...          # recommended in prod
CSRF_COOKIE_NAME=csrf-secret
CSRF_HEADER_NAME=X-CSRF-Token

# Redis failure-mode (security vs availability tradeoff)
AUTH_BLACKLIST_FAIL_CLOSED=false
```

Refer to `DEVELOPMENT-AUTH-SETUP.md` for dev-only overrides (`DISABLE_CSRF`, etc.).

## CSRF Summary

- `core/security/controllers/csrf.controller.ts` issues stateless HMAC tokens at `GET /api/security/csrf/token`.
- Portal fetches the token once and sends it as `X-CSRF-Token` for unsafe methods.
- `core/security/middleware/csrf.middleware.ts` validates `X-CSRF-Token` for unsafe methods and skips safe methods/exempt routes.

## Rate Limiting Summary

- `AuthRateLimitService` provides atomic Redis counters via `rate-limiter-flexible`.
- Guards/workflows invoke `consume*` methods and respond with rate-limit errors/headers.

## Integration Notes

- Use absolute imports (e.g., `@bff/modules/auth/application/auth.facade`) to avoid fragile relative paths.
- `AuthModule` exports `AuthFacade` and token services so other modules (e.g., admin tasks) can reuse them.
- Frontend API calls remain unchanged; payloads validated with existing Zod schemas.

## Future Work (Optional Enhancements)

- Populate `domain/` with password policy objects, role constants, etc.
- Add `application/commands/` for discrete use-case handlers if flows expand.
- Introduce MFA/session management when business requirements demand it.

---

**Last Updated:** 2025-10-02
