# VPS IP-Based Backend & User Token Authentication Implementation Plan

## Goal Description
Implement and deploy a **24/7 Multi-Tenant Backend** hosted on the VPS at **`http://148.113.1.66:8000`** with strict **User Token Authentication (`Authorization: Bearer <USER_TOKEN>`)** on every single API endpoint.

This architecture ensures:
1. **Public IP API Access**: Accessible directly at `http://148.113.1.66:8000` without requiring a domain name immediately.
2. **User Token Isolation**: Every API call from the app must pass the user's JWT token. Each user only sees and controls their own bots, modules, broadcasts, subscriber stats, and logs.
3. **24/7 Bot Cloud Engine**: The Telegram bots run continuously on the VPS in the background. When users close the Android app, their bots remain live 24/7 handling `/start`, welcome greetings, Force-Join channel checks, and broadcast dispatches.
4. **Quota Enforcement**: Strictly enforced per user token (1 Bot per user, max 500 subscribers per bot in Free Tier).

---

## Architecture Diagram

```mermaid
sequenceDiagram
    autonumber
    actor Creator as Android App (User)
    participant VPS as VPS FastAPI Backend (148.113.1.66:8000)
    participant DB as PostgreSQL Database
    participant Engine as 24/7 Bot Runner (aiogram)
    participant TG as Telegram Cloud API
    actor Sub as Telegram User

    Note over Creator,VPS: 1. Auth & Token Acquisition
    Creator->>VPS: POST /api/v1/auth/login (email, password)
    VPS->>DB: Verify credentials & generate JWT
    VPS-->>Creator: 200 OK { access_token: "JWT_TOKEN", user_id: 1 }
    Creator->>Creator: Store JWT securely in Preferences

    Note over Creator,VPS: 2. Add Bot with User Token
    Creator->>VPS: POST /api/v1/bots + Header [Bearer JWT_TOKEN]
    VPS->>VPS: Verify User Token (Check 1-bot free quota)
    VPS->>TG: GET /getMe (Validate bot token)
    VPS->>DB: Save bot & initial modules
    VPS->>Engine: Spawn 24/7 bot listener
    VPS-->>Creator: 201 Created { bot: @username, status: "online" }

    Note over Engine,TG: 3. 24/7 Background Bot Operation
    Sub->>TG: Send /start to Bot
    TG->>Engine: Deliver message
    Engine->>DB: Check & Register Subscriber (500 max limit)
    alt Force Join Enabled
        Engine->>TG: getChatMember(channel=@channel, user=Sub)
        alt Not Joined
            Engine-->>TG: Send "Please join @channel first" + Button
        else Joined
            Engine-->>TG: Send Custom Welcome Greeting + Buttons
        end
    else Normal Welcome
        Engine-->>TG: Send Custom Welcome Greeting + Buttons
    end
    Engine->>DB: Record action in bot_logs
```

---

## User Review Required

> [!IMPORTANT]
> **API Base URL & Cleartext Traffic**:
> The API will run on `http://148.113.1.66:8000`. The Android app already has `cleartextTrafficPermitted="true"` configured in `network_security_config.xml`, allowing HTTP requests directly without SSL certificate barriers.

> [!TIP]
> **User Token Lifecycle**:
> - Registration/Login returns a signed JWT token valid for 30 days.
> - The Android app automatically adds the header `Authorization: Bearer <USER_TOKEN>` to all requests.
> - If a token expires or is invalid, the app catches HTTP 401 and prompts the user to log in again.

---

## API Specification (`http://148.113.1.66:8000`)

### 1. Authentication Endpoints (Public)
| Method | Endpoint | Description | Request Body | Response |
| :--- | :--- | :--- | :--- | :--- |
| `POST` | `/api/v1/auth/register` | Register new user | `{ "email", "password", "name" }` | `{ "access_token", "user" }` |
| `POST` | `/api/v1/auth/login` | Log in | `{ "email", "password" }` | `{ "access_token", "user" }` |

### 2. Protected Endpoints (Requires `Authorization: Bearer <USER_TOKEN>`)
| Method | Endpoint | Description | Isolation / Quota Rule |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/v1/auth/me` | Current user profile | Returns user's plan (`Free`), bot quota (`1/1`), and subscriber saturation (`0/500`). |
| `DELETE` | `/api/v1/auth/account` | Delete account | Deletes user, stops their bots, purges all data (Play Store compliance). |
| `GET` | `/api/v1/bots` | List user's bots | Returns **only** bots belonging to the authenticated user. |
| `POST` | `/api/v1/bots` | Add Telegram bot | Validates via `getMe`. **Rejects if user already has 1 bot** (Free plan limit). |
| `DELETE` | `/api/v1/bots/{bot_id}` | Delete bot | Stops 24/7 background runner and removes bot. |
| `GET` | `/api/v1/bots/{bot_id}/health` | Bot health ping | Returns live latency (ms), online/offline status, and active module badges. |
| `GET` | `/api/v1/bots/{bot_id}/modules` | Get modules config | Returns Welcome text, inline buttons, Force Join channel, Broadcast & Logs state. |
| `PUT` | `/api/v1/bots/{bot_id}/modules` | Update modules config | Updates configuration in DB; bot runner applies changes immediately. |
| `POST` | `/api/v1/bots/{bot_id}/broadcast` | Send broadcast | Dispatches broadcast to all subscribers of this bot (rate-limited at 25 msgs/sec). |
| `GET` | `/api/v1/bots/{bot_id}/logs` | Get bot event logs | Filterable paginated logs (INFO, SUCCESS, WARN, ERROR). |
| `GET` | `/api/v1/bots/{bot_id}/stats` | Dashboard metrics | Total users (max 500), messages sent, 7-day activity graph data. |

---

## Proposed Changes

### Component 1: VPS Backend Service (`/root/tgbot_backend`)

#### [NEW] `requirements.txt`
```text
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
sqlalchemy>=2.0.36
asyncpg>=0.30.0
aiosqlite>=0.20.0
pydantic>=2.10.0
python-jose[cryptography]>=3.3.0
passlib[bcrypt]>=1.7.4
aiogram>=3.15.0
httpx>=0.28.0
python-multipart>=0.0.19
```

#### [NEW] `app/main.py`
FastAPI app entry point configuring:
- CORS middleware (`allow_origins=["*"]`)
- Route routers (`auth`, `bots`, `modules`, `broadcast`, `stats`)
- Startup & Shutdown event hooks for the 24/7 Bot Runner Manager.

#### [NEW] `app/core/security.py`
- Password hashing with `bcrypt`.
- JWT token generation & verification (`jwt.decode`).
- FastAPI `Depends(get_current_user)` dependency for token extraction from `Authorization: Bearer <token>`.

#### [NEW] `app/core/database.py` & `app/models/`
PostgreSQL / SQLite async engine with models:
- `User`: `id`, `email`, `password_hash`, `name`, `plan_tier` ("Free"), `max_bots` (1), `max_users` (500), `created_at`.
- `Bot`: `id`, `user_id`, `name`, `username`, `token`, `is_active`, `subscriber_count`, `messages_sent`.
- `BotModules`: `bot_id`, `welcome_enabled`, `welcome_text`, `welcome_buttons_json`, `fsub_enabled`, `fsub_channel`, `broadcast_enabled`, `logs_enabled`.
- `BotSubscriber`: `id`, `bot_id`, `tg_user_id`, `first_name`, `username`, `joined_at`.
- `BotLog`: `id`, `bot_id`, `level`, `message`, `timestamp`.

#### [NEW] `app/services/bot_runner.py`
- Background manager maintaining active `aiogram.Bot` and `Dispatcher` instances for all active bots.
- Implements:
  - Welcome `/start` handler with inline buttons.
  - Force Join channel membership check via `bot.get_chat_member(chat_id, user_id)`.
  - Subscriber registry (stops accepting new subscribers once 500 limit is reached).
  - Rate-limited broadcast dispatcher.

#### [NEW] `/etc/systemd/system/tgbot-backend.service`
Systemd daemon ensuring the backend stays running 24/7 on port 8000 and restarts automatically on reboot.

---

### Component 2: Android App Integration (`/root/MyBrain`)

#### [NEW] `composeApp/.../data/api/TgBotBackendApi.kt`
Ktor HTTP client configured with:
- `baseUrl = "http://148.113.1.66:8000"`
- Auth plugin attaching `Authorization: Bearer <USER_TOKEN>`.
- Client methods for `login`, `register`, `getBots`, `addBot`, `getModules`, `updateModules`, `sendBroadcast`, `getLogs`, `getStats`.

#### [MODIFY] `MainViewModel.kt`
- Hook `login`, `register`, and `logout` to the backend API.
- Store JWT token in `PrefsConstants.USER_AUTH_TOKEN`.
- Replace local bot flows with live API calls to `http://148.113.1.66:8000`.

#### [MODIFY] `LoginRegisterScreen.kt`
- Connect form submission to real backend authentication.
- Show clear error banners for invalid credentials or email collisions.

#### [MODIFY] `SettingsScreen.kt`
- Add "Delete Account" button calling `DELETE /api/v1/auth/account`.

---

## Verification Plan

### 1. Backend Server Verification
- Launch backend on port 8000:
  ```bash
  curl -I http://148.113.1.66:8000/docs
  ```
  Expected: `HTTP/1.1 200 OK` (Swagger UI).
- Test User Registration & Token generation:
  ```bash
  curl -X POST http://148.113.1.66:8000/api/v1/auth/register \
    -H "Content-Type: application/json" \
    -d '{"email":"test@example.com","password":"password123","name":"Creator"}'
  ```
  Expected: JSON response with `access_token`.
- Test Token Protection:
  ```bash
  # Calling /api/v1/bots without token
  curl -X GET http://148.113.1.66:8000/api/v1/bots
  # Expected: HTTP 401 Unauthorized

  # Calling /api/v1/bots with Bearer token
  curl -X GET http://148.113.1.66:8000/api/v1/bots -H "Authorization: Bearer <TOKEN>"
  # Expected: HTTP 200 OK []
  ```

### 2. 24/7 Bot Operation Test
1. Add a bot token via the API with user token.
2. Open Telegram app on a mobile phone and message the bot `/start`.
3. Verify that the bot replies immediately with the Welcome greeting and checks Force Join.
4. Verify that the subscriber is recorded in the database.

### 3. Android APK Compilation & End-to-End Test
- Rebuild APK:
  ```bash
  cd /root/MyBrain && ./gradlew :androidApp:assembleDebug
  ```
- Copy to `/root/TGBOT-Builder.apk` and test login, bot addition, and module controls from the Android UI.
