Metadata-Version: 2.4
Name: tunnelmate-cli
Version: 1.0.2
Summary: Cloudflare Quick Tunnel manager with CLI, Interactive TUI, Daemon IPC, and Telegram Bot
Author-email: Shashan Lumbhani <lumbhanishashan1510@gmail.com>
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.9.0
Requires-Dist: rich>=13.0.0
Requires-Dist: questionary>=2.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-telegram-bot>=20.0
Requires-Dist: httpx>=0.24.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"

# ⚡ TunnelMate — Cloudflare Quick Tunnel Manager

**TunnelMate** is a production-grade Cloudflare Quick Tunnel manager for Linux, macOS, and Windows. It provides seamless localhost ingress with zero configuration or domain registration requirements.

It features a **shared background daemon**, a **Unix Domain Socket IPC interface**, an **interactive arrow-key TUI**, a **direct CLI**, and a **Telegram bot** for remote management with inline menus, salted password authentication, and real-time subscriber notifications.

---

## 🌟 Key Features

- 🚀 **Python Library:** Complete API for tunnel creation, port remapping, URL auto-discovery, lifecycle controls, and diagnostics.
- 💻 **Interactive Arrow-Key TUI:** Built with [Typer](https://typer.tiangolo.com/), [Rich](https://github.com/Textualize/rich), and [Questionary](https://github.com/tmbo/questionary) for keyboard-driven navigation.
- ⚡ **Direct CLI:** Scriptable subcommands (`start`, `stop`, `restart`, `url`, `port`, `health`, `logs`, `history`).
- 🤖 **Telegram Bot Remote Management:** Full menu-based controls via inline keyboards, salted SHA-256 password protection, admin whitelist, one-click latest-link retrieval, and automatic broadcast notifications to subscribers.
- 🔒 **Shared Background Daemon & IPC:** Single source of truth running over a secured Unix Domain Socket (`0600` permissions) or local TCP fallback. CLI and Telegram bot share the exact same state without process conflicts or SQLite file lock contention.
- 🗄️ **Persistent SQLite Storage:** WAL-mode database storing tunnels, audit history, subscriber preferences, and settings.
- 🛡️ **Subprocess Management without `shell=True`:** Spawns `cloudflared` using explicit argument lists, POSIX process groups, and graceful SIGTERM/SIGKILL shutdown.
- 🔁 **Resilience & Auto-Recovery:** Automatic regex extraction of `https://*.trycloudflare.com` URLs, crash detection, and exponential backoff restart.
- 🩺 **Health Checks:** Diagnostic probing of both local ports/HTTP services and Cloudflare edge availability.
- 📦 **Deployment Ready:** Includes `install.sh`, systemd service files, and full test suite.

---

## 🏛️ System Architecture

```text
┌─────────────────────────────────┐       ┌─────────────────────────────────┐
│     Interactive TUI / CLI       │       │       Telegram Bot Client       │
│    (Questionary + Rich + Typer) │       │   (Inline Keyboards & Events)   │
└────────────────┬────────────────┘       └────────────────┬────────────────┘
                 │                                         │
                 │          Unix Domain Socket IPC         │
                 └───────────────────┬─────────────────────┘
                                     │
                  ┌──────────────────▼──────────────────┐
                  │       TunnelMate Daemon Service     │
                  │  ┌───────────────────────────────┐  │
                  │  │       Async IPC Server        │  │
                  │  └───────────────┬───────────────┘  │
                  │                  │                  │
                  │  ┌───────────────▼───────────────┐  │
                  │  │       Tunnel Supervisor       │  │
                  │  │  (Auto-Recovery & Health)     │  │
                  │  └───────┬───────────────┬───────┘  │
                  └──────────┼───────────────┼──────────┘
                             │               │
            ┌────────────────▼─┐           ┌─▼────────────────┐
            │   cloudflared    │           │ SQLite Database  │
            │   Subprocesses   │           │   (WAL Mode)     │
            │ (without shell)  │           └──────────────────┘
            └──────────────────┘
```

---

## 🚀 Installation

### Automated Installer (Linux / macOS)

Run the included automated installer script:

```bash
chmod +x install.sh
./install.sh
```

The script will:
1. Verify Python 3.10+
2. Download the official `cloudflared` binary for your architecture (if missing)
3. Set up the `~/.tunnelmate` directory with secure `0700` permissions
4. Install the `tunnelmate` package
5. Register systemd user service units

### Automated Installer (Windows PowerShell)

Run the included PowerShell installer in PowerShell:

```powershell
powershell -ExecutionPolicy Bypass -File .\install.ps1
```

The script will:
1. Verify Python 3.10+
2. Auto-download official `cloudflared.exe` for Windows
3. Initialize the `%USERPROFILE%\.tunnelmate` state directory
4. Install `tunnelmate` and `tunnelmate-ssh` CLI commands via pip

### Manual Setup

```bash
# 1. Clone repository & create virtual environment
git clone <repo_url> /opt/tunnelmate
cd /opt/tunnelmate
python3 -m venv .venv
source .venv/bin/activate

# 2. Install dependencies & TunnelMate package
pip install -e .

# 3. Download cloudflared binary (if not already installed on PATH)
tunnelmate install-cloudflared
```

---

## 🏁 Quick Startup Guide

### Step 1: Start the Background Daemon

```bash
tunnelmate daemon start
```

Verify daemon health:
```bash
tunnelmate daemon status
```

### Step 2: Open Interactive TUI Menu

Launch the interactive arrow-key menu:

```bash
tunnelmate menu
```

*(Or simply execute `tunnelmate` without arguments in an interactive terminal).*

The interactive menu lets you manage your tunnels, inspect health diagnostics, view logs and history, and fully manage the **Telegram Bot** (start/stop background process, view users & chat IDs, whitelist/unwhitelist admins, and configure credentials).

### Step 3: Command-Line Operations

#### Create and Start a Tunnel
```bash
# Create a tunnel for a local service on port 8080
tunnelmate create my-web --port 8080

# Start the tunnel and get the Quick Tunnel URL
tunnelmate start my-web
```

#### Fetch URL for Shell Scripts
```bash
# Prints only the URL (e.g. https://xxxx.trycloudflare.com)
tunnelmate url my-web

# Example: Open in browser directly
xdg-open $(tunnelmate url my-web)
```

#### Remap Target Port on the Fly
```bash
# Remaps tunnel from port 8080 to 3000 (safely replaces the process)
tunnelmate port my-web 3000
```

#### Diagnostic Health Check
```bash
tunnelmate health my-web
```

#### Inspect Live Logs & Audit History
```bash
# View last 50 lines of cloudflared process output
tunnelmate logs my-web --lines 50

# View lifecycle history (creation, start, URL assignments, crashes)
tunnelmate history my-web
```

#### List, Stop, and Delete Tunnels
```bash
# List all tunnels with color-coded status
tunnelmate list

# Stop a running tunnel
tunnelmate stop my-web

# Delete tunnel
tunnelmate delete my-web --yes
#### Connect to Cloudflare SSH Tunnels (`tunnelmate-ssh`)
Client computers can install TunnelMate and connect to any SSH Quick Tunnel directly without writing manual `ProxyCommand` arguments (TunnelMate auto-bootstraps `cloudflared` if missing):

```bash
# Direct SSH connection command
tunnelmate-ssh user@<trycloudflare_url>

# Example
tunnelmate-ssh shashansoni@subjective-lenses-working-subscription.trycloudflare.com

# (Or using the sub-command)
tunnelmate ssh shashansoni@subjective-lenses-working-subscription.trycloudflare.com
```

---

## 🤖 Telegram Bot Remote Management

TunnelMate includes a remote Telegram Bot interface.

### 1. Bot Configuration

Set your bot token (from [@BotFather](https://t.me/BotFather)) and configure an admin password:

```bash
# Set bot token
tunnelmate bot set-token "123456789:ABCdefGhIJKlmNoPQRstuVWXyz"

# Set administrator password (stored as salted SHA-256 hash)
tunnelmate bot set-password "YourStrongPassword"

# View all historical chats & discovered Chat IDs
tunnelmate bot chats

# Whitelist a Chat ID as Administrator
tunnelmate bot whitelist <CHAT_ID>
# (or: tunnelmate bot add-admin <CHAT_ID>)

# Remove a Chat ID from Admin Whitelist
tunnelmate bot unwhitelist <CHAT_ID>
# (or: tunnelmate bot remove-admin <CHAT_ID>)
```

### 2. Bot Process Management

```bash
# Start bot in background
tunnelmate bot start

# Check bot running status & PID
tunnelmate bot status

# Stop background bot
tunnelmate bot stop

# (Optional) Run in foreground for live debugging
tunnelmate bot run
```

### 3. Telegram Bot Features

- `/start`: Displays the interactive dashboard with inline buttons.
- `/login <password>`: Authenticates the user as an Administrator (the message is automatically deleted for privacy).
- `/logout`: Clears the admin session.
- `/create <name> <port> [protocol]`: Creates a new tunnel.
- `/port <name> <new_port>`: Updates the target port for an existing tunnel.
- **Inline Menus:**
  - `[📋 Tunnels List]`: Shows all tunnels with statuses (`🟢 Running`, `🔴 Stopped`).
  - `[▶️ Start] / [⏹️ Stop] / [🔄 Restart]`: Controls tunnels in real-time.
  - `[🔗 Latest Link]`: Retrieves the current URL with an inline `[🌐 Open]` web button.
  - `[🩺 Health Check]`: Diagnoses local port response and Cloudflare edge status.
  - `[🔔 Notifications]`: Subscribes users to instant alerts when tunnels start, change links, crash, or recover.

---

## ⚙️ Systemd Service Deployment

TunnelMate includes systemd service unit files for running both the daemon and the Telegram bot continuously in the background.

### User Mode (Recommended)

```bash
mkdir -p ~/.config/systemd/user
cp systemd/tunnelmate-daemon.service ~/.config/systemd/user/
cp systemd/tunnelmate-bot.service ~/.config/systemd/user/

systemctl --user daemon-reload

# Enable and start the daemon
systemctl --user enable --now tunnelmate-daemon

# Enable and start the Telegram bot (if token is configured)
systemctl --user enable --now tunnelmate-bot

# Check status
systemctl --user status tunnelmate-daemon
```

To enable user services to run without an active SSH session:
```bash
loginctl enable-linger $USER
```

---

## 🐍 Python Library Usage

You can embed TunnelMate directly into your Python applications:

```python
from tunnelmate.client import TunnelMateClient

client = TunnelMateClient()

# Check daemon connectivity
if not client.is_daemon_online():
    print("Daemon is offline!")
    exit(1)

# Create a tunnel
tunnel = client.create_tunnel(name="fastapi-server", port=8000)

# Start tunnel and wait for Cloudflare URL
running_tunnel = client.start_tunnel("fastapi-server")
print(f"Public URL: {running_tunnel.current_url}")

# Health check
health, details = client.check_health("fastapi-server")
print(f"Health: {health.value} - {details['message']}")

# Change port
client.change_port("fastapi-server", 8080)

# Stop tunnel
client.stop_tunnel("fastapi-server")
```

---

## 🧪 Running Tests

The test suite validates configuration, database transactions, health checks, cloudflared discovery, and IPC roundtrips:

```bash
pytest -v tests/
```

Test coverage includes:
- `test_config.py`: Salted SHA-256 password hashing and setting persistence.
- `test_db.py`: SQLite schema migrations, CRUD, history tracking, subscriber preferences.
- `test_cloudflared.py`: Architecture detection and version extraction.
- `test_health.py`: Ephemeral HTTP origin and TCP latency verification.
- `test_ipc.py`: Unix socket client-server communications and serialization.
- `test_cli.py`: Typer CLI command dispatch.

---

## 🔒 Security Specifications

1. **Subprocess Execution:** Subprocesses are started with `subprocess.Popen` without `shell=True` and with strict argument lists to eliminate shell injection vulnerabilities.
2. **IPC Socket:** The Unix domain socket file (`~/.tunnelmate/tunnelmate.sock`) is restricted to mode `0600` (readable/writable only by the owner).
3. **Database & Configuration:** State directory `~/.tunnelmate` is set to `0700` and config files are set to `0600`.
4. **Password Storage:** Telegram admin passwords use high-entropy random salts (`secrets.token_hex(16)`) and SHA-256 with constant-time equality comparisons (`secrets.compare_digest`).
5. **Systemd Sandboxing:** Included unit files feature `ProtectSystem=strict`, `PrivateTmp=true`, and explicit `ReadWritePaths`.

---

## 📄 License

MIT License. Built with ❤️ for seamless localhost ingress.
