# 🔐 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.

```
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

# 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
```

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

## CSRF Summary

- `core/security/middleware/csrf.middleware.ts` now issues stateless HMAC tokens.
- On safe requests (GET/HEAD), middleware refreshes token + cookie automatically.
- Controllers just rely on middleware; no manual token handling needed.

## 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

