# Security & Compliance Guidelines

## 1. Authentication & Session Architecture

- **Token Strategy:**
  - Short-lived Access Tokens (15 minutes expiry) signed using HMAC-SHA256.
  - Long-lived Rotating Refresh Tokens (7 days expiry) stored as cryptographic SHA-256 hashes in the database.
- **Refresh Token Rotation & Family Reuse Detection:**
  - Every refresh token exchange revokes the used token and issues a new token in the same `familyId`.
  - If an already revoked token is presented, the system detects a token theft attempt and immediately revokes all active sessions belonging to that token family.
- **HttpOnly Cookies:**
  - Refresh tokens are transmitted via `HttpOnly`, `SameSite=Lax` (or `Strict` in production), and `Secure` (over HTTPS) cookies to eliminate XSS token theft vectors.
- **Password Security:**
  - Passwords hashed using bcrypt with 12 salt rounds.
  - Passwords, tokens, and raw OTPs are never stored in plaintext or output to logs.

---

## 2. Server-Enforced RBAC & Tenant Isolation

- **Role Separation:**
  - `BORROWER`: Can only access their own profile, applications, saved offers, and uploaded documents.
  - `LENDER_ADMIN` & `LENDER_STAFF`: Can only query and update loan products and applications belonging to their specific `lenderId`. Accessing records belonging to another lender is rejected with HTTP 403 Forbidden.
  - `PLATFORM_ADMIN`: Possesses platform-wide oversight, lender verification controls, system audit log inspection, and commission reconciliation authority.
- **Tenant Isolation Enforcement:**
  - Middleware and repository-layer queries inject explicit tenant boundaries (`where: { lenderId: req.user.lenderId }`).

---

## 3. Financial Calculations & Monetary Precision

- **Monetary Precision:**
  - MySQL `Decimal(12, 2)` types utilized for all monetary amounts (principals, EMIs, fees, commissions).
  - Floating-point representations (`float` / `double`) are strictly prohibited in the persistence layer.
- **EMI Formula:**
  - Standard Reducing-Balance calculation: $EMI = \frac{P \times r \times (1 + r)^n}{(1 + r)^n - 1}$
  - Explicit division-by-zero protection for 0% promotional or interest-free loans: $EMI = \frac{P}{n}$.

---

## 4. Document Security & Storage

- **Private Storage:**
  - Financial records (bank statements, salary slips, identity proofs) are never stored in public directories or served via predictable static routes.
- **Signed URLs:**
  - Uploads and downloads are authenticated using HMAC-SHA256 signed URLs with a short validity window (15 minutes).
- **Magic Bytes File Signature Verification:**
  - Files are inspected at the byte level before marking as verified:
    - PDF: `%PDF-` (`25 50 44 46`)
    - PNG: `89 50 4E 47 0D 0A 1A 0A`
    - JPEG: `FF D8 FF`
  - Spoofed extensions (e.g. executable renamed to `.pdf`) are rejected and removed.

---

## 5. Webhook Security & Replay Prevention

- **HMAC Signatures:**
  - Inbound lender webhooks require `x-lender-signature` matching `HMAC-SHA256(rawBody, LENDER_WEBHOOK_SECRET)`.
  - Constant-time comparison (`crypto.timingSafeEqual`) with safe length matching guards against timing attacks.
- **Duplicate Event Detection:**
  - Every inbound event records `eventId` in `WebhookEvent`. Duplicate events are idempotently acknowledged without re-executing state machine transitions.

---

## 6. Audit Logging

- Sensitive actions (user registration, status transitions, lender onboarding, document verifications, commission updates) record cryptographic metadata in `AuditLog` (Actor ID, Entity Type, Entity ID, Previous State, New State, Client IP, User Agent).
