# Authentication & Security Module Rules

The following outlines the current rules, limits, and security constraints enforced by the authentication system in `node_api/src/controllers/auth.controller.js`, `auth.model.js`, and `rateLimiter.js`.

### 1. PIN Verification Limits (Login Security)
To protect user accounts from brute-force PIN guessing attacks, the system enforces a strict lockout policy.

- **Maximum Allowed Attempts:** `5` incorrect PIN entries.
- **Lockout Duration:** `15 minutes` (900 seconds).
- **Rule:** If a user enters an incorrect PIN 5 times consecutively, their account's login capability is temporarily locked. Any further attempts within the next 15 minutes will be rejected immediately, even if the correct PIN is entered.
- **Reset:** Successfully entering the correct PIN before hitting the 5-attempt limit clears the failure counter.

### 2. OTP Sending Rules (Registration & Forgot PIN)
OTP generation and dispatch are rate-limited to prevent SMS spam and control provider costs.

- **Resend Cooldown (Rate Limit):** `60 seconds`.
  - A user must wait at least 60 seconds before requesting another OTP. Attempting to resend before the 60-second window expires will be rejected.
- **Daily Maximum Limit:** `10 OTPs per day` per user.
  - A user can only request a maximum of 10 OTPs in a single day. This counter resets at midnight.
- **OTP Expiry:** `5 minutes` (300 seconds).
  - Any generated OTP becomes invalid exactly 5 minutes after it was sent.

### 3. Global Authentication Rate Limiting
To defend against DDoS attacks and automated brute-forcing across the authentication endpoints (e.g., `/login`, `/register`, `/forgot-pin`), an IP-based rate limiter is enforced globally.

- **Window:** `1 minute`.
- **Maximum Requests:** `1000 requests` per minute per IP address.
- **Block Duration:** `5 minutes`.
- **Rule:** If a single IP address makes more than 1,000 requests to any authentication route within a 1-minute window, that IP address is completely blocked from accessing authentication endpoints for the next 5 minutes.

---

## Trading Engine Module Rules

### 1. Global Trading Status (Kill Switch)
- **Rule:** The system enforces a global `TRADING_STATUS` environment variable. If set to `no`, all live market trading activities (buy, sell, modify, exit) are immediately blocked with a "Trading is temporarily unavailable due to system updates" error.
- **Exception:** The super-admin account (`uid: 11209`) bypasses this restriction to verify live market connectivity during maintenance.

### 2. Order Validation
- **Requirement:** Every order explicitly requires a valid Contest ID (`cid`), Stock ID (`sid`), and a non-zero Quantity (`qty`).
- **Margin Check:** Before an order is submitted, the user's available balance is calculated against the FNO/Equity required margin. If `margin > total available funds`, the order is strictly rejected.

---

## Wallet & Plans Module Rules

### 1. Top-up / Plan Upgrades (Security Signatures)
- **Signature Validation:** All requests to purchase or renew a subscription plan must include a secure payload signature (`sig`). If the signature does not perfectly match the server's securely stored `process.env.signature`, the transaction is rejected as invalid to prevent spoofing.
- **Bonus Deductions:** Users can opt to use their stored 'Bonus' balance to offset subscription costs up to the plan's defined `bonus_amount` threshold.

### 2. Withdrawal Concurrency Locks
- **Redis Locking:** To prevent duplicate withdrawal requests or race conditions (double-spending), the system implements a strict Redis locking mechanism (`lock:wallet:withdrawal:<uid>`). 
- **Lock TTL:** The lock persists for `10 seconds`. If a user attempts to submit a second withdrawal request while the lock is active, it is instantly rejected with "Withdrawal request is already processing."
