Metadata-Version: 2.4
Name: tunnelmate-cli
Version: 1.5.0
Summary: TunnelMate by Shashan Lumbhani — Cloudflare Quick Tunnel manager with CLI, Interactive TUI, Daemon IPC, and Telegram Bot
Author-email: Shashan Lumbhani <lumbhanishashan1510@gmail.com>
License-Expression: 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
Requires-Dist: psutil>=5.9.0
Requires-Dist: qrcode>=7.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"

# ⚡ TunnelMate by Shashan Lumbhani

> **Production-Grade Cloudflare Quick Tunnel Manager & Cross-Platform Ingress Orchestrator**  
> *Seamless Localhost Ingress, Background Daemon, Multi-Device SSH Discovery, Server-Side Session Security, and Telegram Bot Remote Management.*

**Author:** [Shashan Lumbhani](mailto:lumbhanishashan1510@gmail.com)  
**License:** [MIT License](LICENSE)  
**Supported Platforms:** Linux, macOS, Windows (PowerShell / CMD / WSL)  
**Python Compatibility:** Python 3.10+  

[![PyPI version](https://img.shields.io/pypi/v/tunnelmate-cli.svg)](https://pypi.org/project/tunnelmate-cli/)
[![Python versions](https://img.shields.io/pypi/pyversions/tunnelmate-cli.svg)](https://pypi.org/project/tunnelmate-cli/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

---

## 📑 Table of Contents

- [⚡ TunnelMate by Shashan Lumbhani](#-tunnelmate-by-shashan-lumbhani)
  - [📑 Table of Contents](#-table-of-contents)
  - [🚨 The Problem Statement](#-the-problem-statement)
  - [💡 The Solution: What TunnelMate Delivers](#-the-solution-what-tunnelmate-delivers)
  - [🎯 Real-World Use Cases](#-real-world-use-cases)
  - [🏛️ System Architecture](#️-system-architecture)
  - [🚀 Installation \& Setup](#-installation--setup)
    - [📦 Option 1: Install via PyPI (Recommended)](#-option-1-install-via-pypi-recommended)
    - [Option 2: Automated Installer (Linux / macOS)](#option-2-automated-installer-linux--macos)
    - [Option 3: Automated Installer (Windows PowerShell)](#option-3-automated-installer-windows-powershell)
    - [Option 4: Install from Source (Manual)](#option-4-install-from-source-manual)
  - [🏁 Quick Start Guide](#-quick-start-guide)
  - [☁️ Isolated Cloudflare & Persistent Custom Domains](#️-isolated-cloudflare--persistent-custom-domains)
    - [1. 100% Isolated Binary & Credentials](#1-100-isolated-binary--credentials)
    - [2. Cloudflare Domain Auto-Discovery](#2-cloudflare-domain-auto-discovery)
    - [3. Smart Subdomain Expansion](#3-smart-subdomain-expansion)
    - [4. Managing Cloudflare Credentials & Domains](#4-managing-cloudflare-credentials--domains)
  - [🛡️ Two-Factor Authentication (TOTP 2FA)](#️-two-factor-authentication-totp-2fa)
    - [1. Security Model & Authenticator App Support](#1-security-model--authenticator-app-support)
    - [2. Terminal Compact ASCII QR Code](#2-terminal-compact-ascii-qr-code)
    - [3. Telegram Bot Photo QR Code & Remote Whitelist Access](#3-telegram-bot-photo-qr-code--remote-whitelist-access)
    - [4. CLI & Bot 2FA Commands](#4-cli--bot-2fa-commands)
  - [⏰ Task & Tunnel Scheduler (Cron)](#-task--tunnel-scheduler-cron)
    - [1. Background Daemon Engine](#1-background-daemon-engine)
    - [2. Supported Actions & Expressions](#2-supported-actions--expressions)
    - [3. Scheduler CLI & Remote Management](#3-scheduler-cli--remote-management)
  - [🔄 Automatic Daemon & Bot Restart on Updates](#-automatic-daemon--bot-restart-on-updates)
  - [🔒 Password Protection \& API Authentication](#-password-protection--api-authentication)
  - [🔗 Origin Link Rewriting (Replace URLs)](#-origin-link-rewriting-replace-urls)
  - [📈 Live Resource Usage Monitor (`tunnelmate-top`)](#-live-resource-usage-monitor-tunnelmate-top)
  - [🪟 Universal Windows \& Linux Compatibility](#-universal-windows--linux-compatibility)
  - [⚡ Multi-Device SSH Ingress (`tunnelmate-ssh`)](#-multi-device-ssh-ingress-tunnelmate-ssh)
  - [🤖 Telegram Bot Remote Management](#-telegram-bot-remote-management)
    - [1. Configuration](#1-configuration)
    - [2. Bot Process Control](#2-bot-process-control)
    - [3. Server-Side Session Management](#3-server-side-session-management)
    - [4. 100% Interactive Button-Driven Telegram Bot Experience](#4-100-interactive-button-driven-telegram-bot-experience)
  - [🔁 Reboot Persistence \& Daemon Autostart](#-reboot-persistence--daemon-autostart)
  - [🖥️ Complete CLI Command Reference](#️-complete-cli-command-reference)
  - [🐍 Python Library API](#-python-library-api)
  - [🔒 Security \& Privacy Architecture](#-security--privacy-architecture)
  - [🧪 Test Suite \& Validation](#-test-suite--validation)
  - [📄 License \& Credits](#-license--credits)

---


## 🚨 The Problem Statement

Modern software engineers, system administrators, and homelab builders face significant friction when trying to expose local servers or remotely access machines behind private networks:

1. **Carrier-Grade NAT (CGNAT) & Dynamic IPs:**  
   Most residential ISPs, mobile 4G/5G hotspots, university Wi-Fi, and corporate intranets place devices behind Carrier-Grade NAT. There is no publicly routable IPv4 address, and incoming ports cannot be opened on the upstream router.
2. **Ephemeral URL Instability & Process Death:**  
   Standard Cloudflare Quick Tunnels (`cloudflared tunnel --url http://localhost:8080`) are helpful, but closing the terminal or a transient network glitch terminates the tunnel. The newly assigned `https://*.trycloudflare.com` URL changes every restart, requiring manual re-discovery and copy-pasting.
3. **Reboot Amnesia (No Persistence Across Restarts):**  
   When a machine restarts or updates, running tunnel processes and management bots do not automatically recover without complex custom scripting. For headless servers, home workstations, and IoT gateways, this results in extended outages.
4. **Multi-Device SSH Remote Access Chaos:**  
   Managing remote SSH into multiple physical machines (e.g. office workstation, development laptop, home server) requires tracking different URLs, changing hostnames, and figuring out which machine has which URL active.
5. **OpenSSH ProxyCommand Configuration Complexity:**  
   Connecting to an SSH server over Cloudflare requires configuring `ProxyCommand cloudflared access ssh --hostname %h` inside `~/.ssh/config` on every single client computer, downloading the appropriate `cloudflared` binary for the OS, and specifying exact flags.
6. **Security, Privacy & Notification Leaks:**  
   Naive remote-management bots broadcast sensitive live tunnel URLs to anyone who triggers `/start` in Telegram. Without strict server-side session authentication, unauthorized chat users can discover private tunnels and access internal services.

---

## 💡 The Solution: What TunnelMate Delivers

**TunnelMate by Shashan Lumbhani** is an all-in-one tunnel management and remote ingress orchestrator that eliminates these hurdles:

| Challenge | How TunnelMate Solves It |
|---|---|
| **CGNAT & Closed Routers** | Creates secure outbound tunnels to Cloudflare's global edge network. Zero port forwarding, zero router configuration, and zero custom domain registration required. |
| **Process Death & URL Loss** | A background daemon runs continuously, supervises `cloudflared` subprocesses, detects disconnections, and auto-recovers with exponential backoff while persisting state in a WAL-mode SQLite database. |
| **Persistent Custom Domains** | 100% isolated Cloudflare environment (`~/.tunnelmate/cloudflared/cert.pem`). Auto-discovers domains via Cloudflare REST API; typing a subdomain prefix (e.g. `test`) instantly generates `test.yourdomain.com` without touching system files. |
| **Dynamic In-Place Updates** | Reverse proxy architecture allows remapping ports (`tunnelmate port <name> <port>`) and toggling security in-place **without downtime and without changing the public URL**. |
| **Broken Origin Links on Ingress** | Built-in Link Rewriting scans and dynamically replaces local origin URLs (e.g. `http://172.16.11.180:8090`) with public tunnel URLs across HTML, JS, CSS, JSON, and redirects. |
| **Unauthorized Remote Access** | Two-Factor Authentication (RFC 6238 TOTP) enforces 6-digit one-time codes on Telegram Bot admin logins with terminal and in-chat QR code setup. |
| **Automated Lifecycle & Health** | Built-in Task Scheduler executes tunnel actions (start, stop, restart, health) automatically using flexible cron expressions. |
| **Software Updates & Restarts** | Upgrading via `tunnelmate update` automatically reloads and restarts both background Daemon and Telegram Bot processes with zero manual intervention. |
| **System Restarts / Reboots** | Built-in autostart engine restores running tunnels and the Telegram Bot automatically when the operating system boots up. |
| **Resource & Component Visibility** | Interactive `tunnelmate-top` provides live CPU, RAM, thread count, and process status for TunnelMate and Cloudflare components. |
| **Multi-Device SSH Discovery** | Uses Telegram Bot metadata as a private, token-encrypted registry. Any number of devices can publish their active SSH tunnels, and the `tunnelmate-ssh` client discovers and presents them in an interactive menu with hostnames, devices, and detected usernames. |
| **ProxyCommand Headache** | The `tunnelmate-ssh` CLI automatically locates or installs `cloudflared` and dynamically establishes the OpenSSH `ProxyCommand` bridge on Linux, macOS, and Windows. |
| **Windows Flashing CMD Windows** | Suppresses console popups via `CREATE_NO_WINDOW` and hidden startupinfo; automatically tunes console code pages to UTF-8 and enables Virtual Terminal Processing. |
| **Security & Privacy Leaks** | Telegram notifications and menus are strictly gated behind server-side session authentication. Logged-out users receive **0 URLs or alerts**. Administrators can view active sessions via `tunnelmate bot sessions` and revoke access instantly via `tunnelmate bot revoke-sessions`. |


---

## 🎯 Real-World Use Cases

### 1. Remote SSH Access to CGNAT / Home Servers
Connect to your home workstation, Raspberry Pi, or local VM from anywhere in the world (coffee shop, airport, office) without a static public IP, port forwarding, or third-party VPN configurations.

### 2. Multi-Machine Fleet SSH Management (`tunnelmate-ssh`)
Run TunnelMate across your laptop, desktop, and remote server with the same Telegram Bot token. Launch `tunnelmate-ssh` on your client machine to instantly see all active devices, select one with arrow keys, and SSH in seamlessly.

### 3. Ephemeral Webhook & Payment Gateway Testing
Instantly expose local HTTP servers (FastAPI, Next.js, Django, Express, Flask) to public webhooks from Stripe, GitHub, Shopify, or PayPal with secure HTTPS URLs.

### 4. Client Demonstrations & Staging Previews
Share live work-in-progress web applications directly from your local development machine with clients or team members without deploying to staging servers.

### 5. Remote Server Management from Mobile (Telegram Bot)
Monitor your host machine from your phone: start, stop, or restart tunnels, change forwarded ports, inspect daemon statistics, run health checks, and receive real-time alerts when URLs update.

### 6. Dynamic Port Remapping for Multi-Service Workflows
Switch target ports on the fly (e.g. from port `3000` to `8080`) using `tunnelmate port <name> <new_port>`. TunnelMate safely swaps the running process without breaking tunnel configurations.

### 7. Automated CI/CD Preview Environments
Integrate `tunnelmate url <name>` into automated CI/CD scripts to launch temporary test tunnels and export live URLs for integration tests.

---

## 🏛️ System Architecture

```text
┌─────────────────────────────────┐       ┌─────────────────────────────────┐
│     Interactive TUI / CLI       │       │       Telegram Bot Client       │
│    (Questionary + Rich + Typer) │       │   (Session Auth + TOTP 2FA)     │
└────────────────┬────────────────┘       └────────────────┬────────────────┘
                 │                                         │
                 │          Unix Domain Socket IPC         │
                 │      (mode 0600) / Local TCP Fallback   │
                 └───────────────────┬─────────────────────┘
                                     │
                  ┌──────────────────▼──────────────────┐
                  │       TunnelMate Daemon Service     │
                  │  ┌───────────────────────────────┐  │
                  │  │       Async IPC Server        │  │
                  │  └───────────────┬───────────────┘  │
                  │                  │                  │
                  │  ┌───────────────▼───────────────┐  │
                  │  │       Tunnel Supervisor       │  │
                  │  │  (Auto-Recovery & Health)     │  │
                  │  └───────┬───────────────┬───────┘  │
                  │          │               │          │
                  │  ┌───────▼───────────────▼───────┐  │
                  │  │  Task Scheduler (Cron Engine) │  │
                  │  └───────────────┬───────────────┘  │
                  └──────────────────┼──────────────────┘
                                     │
           ┌─────────────────────────┼─────────────────────────┐
           │                         │                         │
┌──────────▼─────────┐    ┌──────────▼─────────┐    ┌──────────▼─────────┐
│ Isolated cloudflared│   │  SQLite Database   │   │  Cloudflare v4 API  │
│  Binary & cert.pem  │   │     (WAL Mode)     │   │  Domain Discovery   │
│  (No host overlap)  │   │                    │   │    & Subdomains     │
└────────────────────┘    └────────────────────┘    └────────────────────┘
```

---

## 🚀 Installation & Setup

### 📦 Option 1: Install via PyPI (Recommended)

Install the library and CLI directly from [PyPI](https://pypi.org/project/tunnelmate-cli/):

```bash
pip install tunnelmate-cli
```

*(On systems with PEP 668 managed environments, use `pip install tunnelmate-cli --break-system-packages` or install in a virtual environment / `pipx`).*

Once installed, download the official Cloudflare `cloudflared` binary with one command:

```bash
tunnelmate install-cloudflared
```

You now have full access to both `tunnelmate` and `tunnelmate-ssh` commands!

---

### Option 2: Automated Installer (Linux / macOS)

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

The script will:
1. Verify Python 3.10+
2. Download official `cloudflared` binary for your architecture (`x86_64`, `aarch64`, `armv7`)
3. Initialize `~/.tunnelmate` state directory with secure `0700` permissions
4. Install `tunnelmate` and `tunnelmate-ssh` into your environment
5. Register systemd user service units for background operation

### Option 3: 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 `%USERPROFILE%\.tunnelmate` state directory
4. Install `tunnelmate` and `tunnelmate-ssh` CLI executables

### Option 4: Install from Source (Manual)

```bash
# Clone the repository
git clone https://github.com/soni-shashan/tunnelmate.git
cd tunnelmate

# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install TunnelMate in editable mode
pip install -e .

# Auto-download official cloudflared binary
tunnelmate install-cloudflared
```

---

## 🏁 Quick Start Guide

### Step 1: Start the Background Daemon
```bash
tunnelmate daemon start
```
Verify daemon status:
```bash
tunnelmate daemon status
```

### Step 2: Open the Interactive Arrow-Key TUI Menu
Simply run:
```bash
tunnelmate
```
*(or explicitly: `tunnelmate menu`)*

The interactive menu lets you create, start, stop, restart tunnels, remap ports, view live logs, inspect daemon stats, manage Telegram Bot settings, and connect via SSH.

### Step 3: Direct CLI Commands

```bash
# Create a tunnel for a web server on port 8080
tunnelmate create my-web --port 8080

# Create a password-protected tunnel (Approach A)
tunnelmate create secure-app --port 8080 --auth --password "MySecretPass123"

# Enable or update password on an existing tunnel
tunnelmate auth my-web --password "MySecretPass123"

# Disable password protection
tunnelmate auth my-web --disable

# Create an SSH tunnel for local port 22
tunnelmate create my-ssh --port 22 --protocol tcp

# Start the tunnel and get the live trycloudflare.com URL
tunnelmate start my-web

# Print only the URL (ideal for shell scripts)
tunnelmate url my-web

# Remap target port on the fly (e.g. from 8080 to 3000)
tunnelmate port my-web 3000

# Run diagnostics on local port & Cloudflare ingress
tunnelmate health my-web

# View real-time logs (last 50 lines)
tunnelmate logs my-web --lines 50

# List all configured tunnels
tunnelmate list

# Stop a tunnel
tunnelmate stop my-web

# Delete a tunnel
tunnelmate delete my-web --yes

# Create a persistent named tunnel with auto-resolved subdomain (e.g. test.yourdomain.com)
tunnelmate create my-api --port 8080 --subdomain test

# Set up Two-Factor Authentication (TOTP 2FA)
tunnelmate 2fa setup

# Schedule periodic health checks via cron
tunnelmate schedule add my-web health "*/30 * * * *"

# Check for updates on PyPI
tunnelmate update --check

# Upgrade tunnelmate-cli and auto-restart running daemon & bot
tunnelmate update
```

---

## ☁️ Isolated Cloudflare & Persistent Custom Domains

TunnelMate supports both zero-configuration **Quick Tunnels** (`*.trycloudflare.com`) and **Production Persistent Named Tunnels on Your Own Custom Domains** (e.g., `dev.yourdomain.com`).

### 1. 100% Isolated Binary & Credentials
TunnelMate guarantees complete isolation from the host operating system's Cloudflare setup:
- **Dedicated Binary:** Stores and executes `cloudflared` exclusively from `~/.tunnelmate/bin/cloudflared`.
- **Isolated Origin Certificate:** Stores certificate files at `~/.tunnelmate/cloudflared/cert.pem` with restricted `0600` permissions.
- **Zero Host Collisions:** TunnelMate **never** modifies, overwrites, or pollutes existing system certificates in `~/.cloudflared/cert.pem`. If a certificate is detected in the system during initial setup, TunnelMate automatically copies it into its isolated directory so the host certificate remains completely untouched.

### 2. Cloudflare Domain Auto-Discovery
You don't need to manually look up Zone IDs or configure YAML files:
- When you authenticate via `tunnelmate cf-login` or configure a Tunnel Token, TunnelMate automatically extracts account credentials (`accountID`, `zoneID`, `apiToken`).
- It queries the official **Cloudflare v4 REST API** (`https://api.cloudflare.com/client/v4/zones`) to auto-discover all active domains registered under your Cloudflare account.
- Discovered domains are securely cached in `~/.tunnelmate/cloudflared/domains.json` and synchronized with the background daemon.

### 3. Smart Subdomain Expansion
Creating a tunnel on your custom domain is as simple as typing a subdomain prefix:
```bash
# If your active domain is 'example.com', passing 'test' automatically expands to 'test.example.com':
tunnelmate create my-api -p 8080 -d test

# You can also pass the full FQDN:
tunnelmate create my-api -p 8080 -d api.example.com

# Or launch immediately with 'run' using --subdomain:
tunnelmate run -p 3000 --subdomain staging
```
TunnelMate automatically:
1. Resolves the subdomain prefix against your active base domain.
2. Checks Cloudflare DNS for collisions or routes.
3. Provisions or updates the persistent named tunnel in Cloudflare.
4. Configures edge DNS routing rules pointing directly to your host machine.

### 4. Managing Cloudflare Credentials & Domains
```bash
# Authenticate with Cloudflare via browser login (opens isolated login session)
tunnelmate cf-login

# Inspect isolated credentials, origin certificate path, and discovered domains
tunnelmate cf-status

# List all discovered account domains and the current active default
tunnelmate cf-domains

# Force an immediate live refresh of account domains from Cloudflare API
tunnelmate cf-sync

# Set or update a Cloudflare Tunnel Token
tunnelmate cf-set-token "<YOUR_TUNNEL_TOKEN>"

# Remove isolated credentials, certificate, and domain cache
tunnelmate cf-remove --force
```

---

## 🛡️ Two-Factor Authentication (TOTP 2FA)

TunnelMate includes built-in Two-Factor Authentication (2FA) adhering to the **RFC 6238 TOTP (Time-Based One-Time Password)** standard.

### 1. Security Model & Authenticator App Support
- Generates 6-digit one-time security codes refreshing every 30 seconds.
- Fully compatible with standard TOTP authenticator applications:
  - **Google Authenticator** (Android / iOS)
  - **Microsoft Authenticator** (Android / iOS / Windows)
  - **Apple Passwords / Keychain** (iOS / macOS)
  - **1Password**, **Bitwarden**, **KeePassXC**, **Authy**
- Cryptographic secret keys are stored in the user-restricted `~/.tunnelmate/config.json` (`0600` permissions).
- Protects administrative actions in both the CLI and the Telegram Bot. When 2FA is active, logging into the bot requires both the administrator password **and** the live 6-digit TOTP code.

### 2. Terminal Compact ASCII QR Code
Setting up 2FA in the terminal displays a specially formatted, compact UTF-8 ASCII QR code:
```bash
tunnelmate 2fa setup
```
- Designed with double-row half-block rendering (`▀` / `▄`) to guarantee that the QR code fits cleanly within standard 80-column terminal dimensions without horizontal wrapping or line distortion.
- Simply point your phone's camera or authenticator app at the terminal screen to scan instantly!
- Displays the raw Base32 secret key and `otpauth://` URI for manual entry.
- Requires verifying a valid 6-digit code before activating to prevent accidental lockouts.

### 3. Telegram Bot Photo QR Code & Remote Whitelist Access
Administrators can also manage 2FA directly from their phone via the Telegram Bot:
- **Whitelisted Admin Privilege:** Only whitelisted chat IDs can configure 2FA.
- **In-Chat QR Code Photo:** Sending `/2fa` or `/totp` and selecting Setup dynamically generates a high-resolution PNG QR code image sent straight to your chat.
- **Privacy Protection:** Setup messages, secret keys, and QR codes are automatically deleted after verification or cancellation to leave zero trace in your chat history.

### 4. CLI & Bot 2FA Commands
```bash
# Check 2FA activation status
tunnelmate 2fa status

# Run guided interactive setup with terminal QR code
tunnelmate 2fa setup

# Test/verify a 6-digit TOTP code against your active secret
tunnelmate 2fa test 123456

# Disable 2FA (requires verification)
tunnelmate 2fa disable

# Quick alias: 'tunnelmate totp' can be used interchangeably with 'tunnelmate 2fa'
tunnelmate totp status
```

---

## ⏰ Task & Tunnel Scheduler (Cron)

TunnelMate includes an integrated background task scheduler that executes tunnel management tasks automatically on cron schedules.

### 1. Background Daemon Engine
- Runs as an asynchronous worker inside the TunnelMate daemon.
- Zero external cron dependencies or OS crontab pollution.
- All scheduled tasks and execution logs persist in the SQLite database across restarts.

### 2. Supported Actions & Expressions
Schedule any operational action for any tunnel or across all tunnels:
- **Supported Actions:** `start`, `stop`, `restart`, `health`
- **Standard 5-Field Cron Syntax:** `minute hour day-of-month month day-of-week`
  - `0 4 * * *` — Run every night at 4:00 AM
  - `*/30 * * * *` — Run every 30 minutes
  - `0 9 * * 1-5` — Run at 9:00 AM on weekdays
- **Convenient Presets:** `@hourly`, `@daily`, `@weekly`, `@monthly`

### 3. Scheduler CLI & Remote Management
```bash
# List all active and paused scheduled tasks
tunnelmate schedule list

# Schedule daily restart for a development tunnel at 4:00 AM
tunnelmate schedule add dev-api restart "0 4 * * *"

# Schedule health check every 15 minutes
tunnelmate schedule add prod-web health "*/15 * * * *"

# Immediately trigger a scheduled job out-of-band
tunnelmate schedule run <JOB_ID>

# Temporarily pause a scheduled job
tunnelmate schedule pause <JOB_ID>

# Resume a paused job
tunnelmate schedule resume <JOB_ID>

# Inspect recent execution logs for a job
tunnelmate schedule logs <JOB_ID>

# Delete a scheduled job
tunnelmate schedule delete <JOB_ID>
```
*(Whitelisted administrators can also view and trigger scheduled jobs from the Telegram Bot menu).*

---

## 🔄 Automatic Daemon & Bot Restart on Updates

Keeping your local tunnel infrastructure updated shouldn't cause configuration drift or require manual process hunting:

### 1. One-Command PyPI Upgrade
```bash
# Check PyPI for available updates
tunnelmate update --check

# Upgrade tunnelmate-cli and automatically restart running background services
tunnelmate update
```

### 2. Zero-Downtime Daemon & Bot Recovery
When `tunnelmate update` runs:
1. It verifies and downloads the latest release from [PyPI](https://pypi.org/project/tunnelmate-cli/).
2. It detects whether the **TunnelMate Daemon** or **Telegram Bot** are currently active.
3. It performs a graceful restart of both background processes with the newly installed version.
4. Active tunnels and session states are automatically restored from the WAL-mode SQLite database.

### 3. Manual Process Restarts
You can also restart services individually at any time:
```bash
# Gracefully restart the TunnelMate background daemon
tunnelmate daemon restart

# Gracefully restart the Telegram Bot
tunnelmate bot restart

# Or send /restart in Telegram chat (whitelisted admins only)
```

---

## 🔒 Password Protection & API Authentication

TunnelMate features built-in password protection for HTTP/HTTPS tunnels. When password protection is enabled, Cloudflare routes ingress traffic through an internal zero-overhead authentication reverse proxy (`AuthProxyServer`) running on `127.0.0.1` before forwarding verified requests to your local application port.

### 🌐 For Web Browsers
- Visitors opening the `trycloudflare.com` link in a browser are presented with a modern, glassmorphic dark-mode password gate branded with **⚡ TunnelMate by Shashan Lumbhani**.
- Upon entering the correct password, a cryptographically signed HMAC `tunnelmate_session` cookie is issued (HTTP-only, Lax, 24-hour expiration).
- Subsequent browsing, navigation, asset loading, and form posts pass through transparently to your local web application.

### ⚡ For APIs, Scripts, & Webhooks (GET, POST, PUT, DELETE, PATCH, etc.)
Microservices, mobile apps, CI/CD webhooks, and REST clients do not need to navigate browser cookies. Simply send the password in any request header:

```bash
# Method 1: Using X-TunnelMate-Password header
curl -H "X-TunnelMate-Password: MySecretPass123" https://your-tunnel.trycloudflare.com/api/data

# Method 2: Using Authorization Bearer token header
curl -H "Authorization: Bearer MySecretPass123" https://your-tunnel.trycloudflare.com/api/data

# POST / PUT request with JSON payload:
curl -X POST https://your-tunnel.trycloudflare.com/api/submit \
  -H "X-TunnelMate-Password: MySecretPass123" \
  -H "Content-Type: application/json" \
  -d '{"status": "active"}'
```

Both browser apps and automated API consumers operate simultaneously on the exact same tunnel!

### Managing Password Protection
- **Interactive Menu (`tunnelmate`):** Select any tunnel and choose `🔒 Configure Password Protection` to enable, update, or disable passwords with hidden input.
- **Direct CLI:**
  - `tunnelmate auth <name> --password <pwd>` (enables/updates password)
  - `tunnelmate auth <name> --disable` (disables password protection)
- **Telegram Bot:**
  - Create protected tunnels: `/create <name> <port> [protocol] [password]`
  - Real-time tunnel details show `🔒 Enabled` or `🔓 Disabled` status.

---

## 🔗 Origin Link Rewriting (Replace URLs)

When exposing internal web applications, development servers, or private dashboards through a tunnel, applications frequently generate internal links, asset paths, or HTTP redirects pointing back to the internal address (such as `http://172.16.11.180:8090/` or `http://localhost:3000/`). Browsing from external networks or mobile devices results in broken page rendering, asset loading failures, or endless buffering because the external browser attempts to contact private IP addresses directly.

TunnelMate's reverse proxy engine includes transparent **Origin Link Rewriting**:

```bash
# Enable origin link rewriting when creating a tunnel
tunnelmate create my-dashboard --port http://172.16.11.180:8090/ --rewrite-links

# Enable link rewriting on an existing tunnel
tunnelmate replace-links my-dashboard --enable

# Disable link rewriting
tunnelmate replace-links my-dashboard --disable
```

### How Link Rewriting Operates:
1. **Bidirectional Header Translation (Zero Server Rejections):** 
   - Preserves backend `Host` as `{target_host}:{target_port}` so frameworks with strict host validation (e.g. Django `ALLOWED_HOSTS`, Vite `Invalid Host header`, Ruby on Rails) never reject incoming requests with `400 Bad Request`.
   - Translates incoming `Origin` and `Referer` headers back to the local origin address so backend CSRF and CORS protections pass without `403 Forbidden`.
   - Strips restrictive `Domain=` attributes from `Set-Cookie` so session cookies bind cleanly to `trycloudflare.com`.
2. **Deep Body & API Rewriting:**
   - Rewrites plain URLs (`http://172.16.11.180:8090` → `https://xxx.trycloudflare.com`).
   - Rewrites JSON-escaped URLs (`http:\/\/172.16.11.180:8090` → `https:\/\/xxx.trycloudflare.com`) in API payloads and embedded scripts.
   - Rewrites URL-encoded parameters (e.g. OAuth callbacks, `redirect_uri`).
   - Rewrites quoted host/port configurations in JavaScript and JSON configs.
3. **Client-Side Interceptor Shim:**
   - Injects a lightweight (<1KB) zero-dependency browser interceptor into HTML responses.
   - Intercepts `window.fetch`, `XMLHttpRequest.prototype.open`, `window.open`, `navigator.sendBeacon`, `history.pushState`, form submissions, and hyperlink clicks.
   - Automatically re-routes dynamically assembled in-flight requests and button actions to the public tunnel, guaranteeing zero leaked redirects.
4. **Transparent Decompression:**
   - Handles compressed responses (gzip, deflate, brotli), decompresses in-memory, rewrites matching URLs, and recalculates `Content-Length` transparently.
5. **Zero Code Changes:**
   - Your internal services, web apps, and frameworks function immediately without having to configure reverse-proxy base URLs or reverse-proxy headers manually!

---

## 📈 Live Resource Usage Monitor (`tunnelmate-top`)

TunnelMate provides an interactive terminal resource monitor inspired by `htop` and `top`, designed specifically for TunnelMate, Cloudflare, and connected ingress components:

```bash
# Launch interactive live monitor
tunnelmate-top

# Or launch through the tunnelmate CLI:
tunnelmate top

# Or select "📈 Live Resource Monitor (tunnelmate-top)" inside the interactive TUI menu:
tunnelmate
```

### Key Capabilities:
- **Dedicated Component Isolation:** Samples metrics specifically for TunnelMate Daemon, Telegram Bot, Cloudflare worker processes (`cloudflared`), and local target processes.
- **Accurate Resource Measurement:** Tracks real-time CPU % (interval deltas), physical RAM (RSS), Virtual Memory (VMS), thread count, uptime, and operational status.
- **Interactive Hotkeys:**
  - `[q]` / `[Esc]` — Quit monitor
  - `[r]` — Force instant metrics refresh
  - `[s]` — Cycle sort column (`CPU`, `RAM`, `NAME`, `PID`)
  - `[Space]` / `[p]` — Pause / Resume live polling
  - `[+]` / `[-]` — Increase or decrease poll interval (0.5s to 5.0s)
  - `[h]` / `[?]` — Display on-screen keyboard shortcut cheat sheet
- **Scriptable Snapshot Mode:**
  ```bash
  # Output a single snapshot table and exit (ideal for cron, CI, or shell scripts)
  tunnelmate-top --once
  ```

---

## 🪟 Universal Windows & Linux Compatibility

TunnelMate is engineered for seamless operation across **Windows** (Command Prompt, PowerShell, Windows Terminal) and **all Linux distributions** (Ubuntu, Debian, Fedora, Arch, Alpine, headless servers):

1. **Zero Flashing / Blank CMD Windows on Windows:**
   - On Windows, subprocesses use `CREATE_NO_WINDOW (0x08000000)` and `STARTUPINFO` with `STARTF_USESHOWWINDOW` and `SW_HIDE (0)`.
   - Running tunnels or background daemons creates **zero blank popup console windows**.
2. **Automatic Terminal Code Page & Virtual Terminal Tuning:**
   - On startup, TunnelMate automatically activates UTF-8 code page `65001` and enables Windows Virtual Terminal Processing (`ENABLE_VIRTUAL_TERMINAL_PROCESSING`).
   - Unicode borders, status badges (`🟢 RUNNING`, `🔄 RESTARTING`), and emojis display cleanly without text overlap or font corruption.
3. **Dynamic IPC Port Allocation on Windows:**
   - Windows utilizes loopback TCP for local inter-process communication. If the default port (`53821`) is busy, the daemon automatically claims an available port and writes synchronization data to `daemon.info`, preventing socket collision errors.
4. **One-Click Daemon Initialization:**
   - If `tunnelmate` is launched when the background daemon is offline, users can press Enter on `🚀 Start Background Daemon` directly in the TUI to spawn the daemon inline.

---

## ⚡ Multi-Device SSH Ingress (`tunnelmate-ssh`)


TunnelMate includes a specialized `tunnelmate-ssh` client that turns any SSH tunnel into a frictionless remote shell without touching `~/.ssh/config`:

```bash
# 1. Interactive Mode: Auto-discover all SSH tunnels from your Telegram Bot
tunnelmate-ssh

# 2. Discover SSH tunnels using a specific Bot Token:
tunnelmate-ssh --token <YOUR_TELEGRAM_BOT_TOKEN>

# 3. List active SSH tunnels discovered from your bot:
tunnelmate-ssh --list

# 4. Direct non-interactive connection:
tunnelmate-ssh user@<trycloudflare_url>

# Examples:
tunnelmate-ssh shashansoni@subjective-lenses-working-subscription.trycloudflare.com
tunnelmate-ssh root@https://my-app.trycloudflare.com -i ~/.ssh/id_rsa
```

### How Multi-Device Discovery Works:
1. Each host machine running TunnelMate publishes its active SSH tunnels to private Telegram Bot metadata using token-derived encryption.
2. The payload contains the machine's detected hostname, device model, and current OS username (e.g. `shashansoni`).
3. Running `tunnelmate-ssh` on any client machine decrypts the registry and displays all online devices.
4. Selecting a machine auto-configures the Cloudflare `ProxyCommand` bridge and opens an SSH session immediately.

---

## 🤖 Telegram Bot Remote Management

TunnelMate includes a full-featured Telegram Bot interface for remote mobile management.

### 1. Configuration
```bash
# 1. Set Telegram Bot token (from @BotFather)
tunnelmate bot set-token "123456789:ABCdefGhIJKlmNoPQRstuVWXyz"

# 2. Set salted SHA-256 administrator password
tunnelmate bot set-password "YourStrongPassword"

# 3. View discovered chat IDs from recent interactions
tunnelmate bot chats

# 4. Whitelist a Chat ID as Administrator
tunnelmate bot whitelist <CHAT_ID>
```

### 2. Bot Process Control
```bash
# Start Telegram bot in background (enables auto-restore on reboot)
tunnelmate bot start

# Check bot running status & PID
tunnelmate bot status

# Gracefully restart background bot process
tunnelmate bot restart

# Stop background bot (disables auto-restore on reboot)
tunnelmate bot stop
```

### 3. Server-Side Session Management
Strict server-side session management guarantees that unauthenticated users cannot see live links or receive notifications:

```bash
# Inspect all registered chat IDs and their active session status
tunnelmate bot sessions

# Revoke all active sessions on the server (logs out all users immediately)
tunnelmate bot revoke-sessions
```

### 4. 100% Interactive Button-Driven Telegram Bot Experience
TunnelMate features a modern, attractive inline button UI in Telegram. You never need to memorize or type complex commands like `/login pass`, `/create name port 8080`, or `/port name 3000`. Everything is guided step-by-step through interactive buttons and smart conversational prompts:

- 🔒 **Interactive Admin Login Wizard**:
  - Click `[🔒 Login as Admin]` from the main menu.
  - The bot prompts you to enter your server administrator password.
  - If **2FA (TOTP)** is enabled, the bot prompts for your live 6-digit authenticator code.
  - **Zero Privacy Leak:** Passwords and TOTP codes are automatically deleted from Telegram chat history the instant they arrive, unlocking the full administrative dashboard.
- 🛡️ **Two-Factor Authentication (TOTP 2FA) Remote Setup**:
  - Whitelisted administrators can manage 2FA directly via `/2fa` or `/totp` or the Settings menu.
  - When initiating setup, the bot dynamically generates and delivers a high-resolution PNG QR code photo straight to your chat to scan in Google Authenticator, 1Password, Apple Passwords, etc.
  - Secret setup keys and QR codes are auto-deleted upon confirmation for complete privacy.
- ➕ **Interactive Create Tunnel Wizard (Guided Flow)**:
  - Click `[➕ Create Tunnel]` from the main menu or tunnels list.
  - **Step 1:** Enter tunnel name (e.g., `api-dev`).
  - **Step 2:** Select a target port using quick preset buttons (`[8080]`, `[3000]`, `[8000]`, `[5000]`, `[80]`, `[22]`) or enter a custom port.
  - **Step 3:** Select protocol with one click (`[🌐 HTTP]`, `[🔒 HTTPS]`, `[⚡ TCP / SSH]`).
  - **Step 4 (Custom Domains):** If Cloudflare credentials are configured, choose between `[⚡ Quick Tunnel (*.trycloudflare.com)]` and `[🌐 Persistent Subdomain (*.<active_domain>)]`. Entering a subdomain prefix (e.g. `api`) auto-expands to `api.yourdomain.com` with DNS routing.
  - **Step 5:** Choose password security (`[🔒 Yes, Enable Password]` or `[🔓 No, Public Access]`). If enabled, prompts for the password (auto-deleted) and launches the tunnel immediately!
- ✏️ **Dynamic In-Place Port Changer**:
  - Click `[✏️ Change Port]` on any tunnel detail card.
  - Choose from popular preset buttons (`8080`, `3000`, `8000`, `5000`, `80`, `22`) or type any custom port.
  - Tunnel updates immediately with zero downtime and preserves your live public URL!
- 🗑️ **Interactive Delete Confirmation**:
  - Click `[🗑️ Delete Tunnel]` on any tunnel.
  - Features confirmation dialog (`[🗑️ Yes, Delete]` / `[❌ Cancel]`) to prevent accidental deletions.
- 🔒 **Interactive Password Protection Manager**:
  - Click `[🔒 Password Auth]` or `[🔓 Add Password]` on any tunnel card.
  - Click `[🔑 Set / Change Password]` to enter a new password (message auto-deleted for privacy; preserves live URL).
  - Click `[🔓 Disable Password Protection]` for 1-click removal of the password gate (preserves live URL).
- 🔄 **Remote Process Restart (`/restart`)**:
  - Whitelisted administrators can issue `/restart` to gracefully reload and restart both the background daemon and Telegram bot remotely from their mobile device.
- 📋 **Full Process Controls & Health Checks**:
  - `[▶️ Start]`, `[⏹️ Stop]`, `[🔄 Restart]`, `[🔗 Latest Link]`, `[🩺 Health Check]`, `[🔔 Notifications]`.

*(Power-user slash commands remain supported: `/start`, `/login`, `/logout`, `/create`, `/auth`, `/port`, `/2fa`, `/totp`, `/restart`, `/cancel`)*

---

## 🔁 Reboot Persistence & Daemon Autostart

TunnelMate includes an auto-restoration engine:

```bash
# Check current autostart configuration
tunnelmate autostart status

# Enable autostart on system boot / restart
tunnelmate autostart enable

# Disable autostart on boot
tunnelmate autostart disable
```

When enabled:
- If the **Daemon** was running before a reboot, it starts automatically on system startup and restores all active tunnels.
- If the **Telegram Bot** was running before a reboot, it relaunches in the background and restores tunnel synchronization.

### Systemd User Services (Linux)
```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
systemctl --user enable --now tunnelmate-daemon
systemctl --user enable --now tunnelmate-bot

# Keep services active without an open SSH login session:
loginctl enable-linger $USER
```

---

## 🖥️ Complete CLI Command Reference

### Main Commands
| Command | Arguments | Description |
|---|---|---|
| `tunnelmate menu` | — | Open interactive arrow-key TUI dashboard |
| `tunnelmate list` | — | Display color-coded table of all configured tunnels |
| `tunnelmate create` | `<name> -p <port> [-d <subdomain\|domain>] [--auth] [--rewrite-links]` | Create a Quick Tunnel or Persistent Named Custom Domain Tunnel |
| `tunnelmate run` | `-p <port> [-d <subdomain\|domain>] [--auth] [--rewrite-links]` | Create and immediately launch a tunnel |
| `tunnelmate cf-login` | — | Authenticate with Cloudflare via browser to download isolated `cert.pem` |
| `tunnelmate cf-status` | — | Display isolated Cloudflare credentials, certificate path, and discovered domains |
| `tunnelmate cf-domains` | — | List all registered Cloudflare account domains and active base domain |
| `tunnelmate cf-sync` | — | Force live refresh of account domains from Cloudflare v4 REST API |
| `tunnelmate cf-set-token`| `[<token>]` | Set or update Cloudflare Tunnel Token for persistent tunnels |
| `tunnelmate cf-remove` | `[--force]` | Remove stored Cloudflare origin certificate, tokens, and domain cache |
| `tunnelmate start` | `<name>` | Launch tunnel subprocess and acquire live URL |
| `tunnelmate stop` | `<name>` | Gracefully stop running tunnel subprocess |
| `tunnelmate restart` | `<name>` | Restart tunnel and assign fresh trycloudflare.com URL |
| `tunnelmate port` / `target` | `<name> <port_or_url>` | Dynamically remap target port or URL on the fly (preserves public URL) |
| `tunnelmate auth` | `<name> [--enable\|--disable] [--password <pwd>]` | Configure password protection (preserves public URL) |
| `tunnelmate replace-links` | `<name> [--enable\|--disable]` | Configure origin link rewriting to replace origin URLs in responses |
| `tunnelmate top` | `[-i <sec>] [--once]` | Live interactive resource monitor for TunnelMate & Cloudflare |
| `tunnelmate-top` | `[-i <sec>] [--once]` | Standalone binary for live interactive resource monitoring |
| `tunnelmate url` | `<name>` | Output raw URL for shell scripts and piping |
| `tunnelmate health` | `<name>` | Test local service response and Cloudflare edge status |
| `tunnelmate logs` | `<name> [--lines 50]` | Stream or view recent cloudflared process logs |
| `tunnelmate history` | `<name>` | Inspect full lifecycle audit trail |
| `tunnelmate delete` | `<name> [--yes]` | Delete tunnel configuration and purge history |
| `tunnelmate update` | `[--check]` | Check PyPI and automatically upgrade CLI with daemon/bot restart |
| `tunnelmate install-cloudflared` | — | Auto-download official Cloudflare binary |
| `tunnelmate ssh` | `[target]` | Connect to Cloudflare SSH tunnel |


### Daemon Commands (`tunnelmate daemon`)
| Command | Description |
|---|---|
| `tunnelmate daemon start` | Launch background daemon service process |
| `tunnelmate daemon stop` | Stop background daemon service |
| `tunnelmate daemon restart` | Gracefully restart background daemon and reload active tunnels |
| `tunnelmate daemon status` | Check daemon PID, uptime, and IPC connectivity |
| `tunnelmate daemon run` | Run daemon in foreground (for systemd or debugging) |
| `tunnelmate daemon enable` | Enable daemon auto-launch on operating system boot |
| `tunnelmate daemon disable` | Disable daemon auto-launch on operating system boot |


### Telegram Bot Commands (`tunnelmate bot`)
| Command | Arguments | Description |
|---|---|---|
| `tunnelmate bot start` | — | Launch Telegram Bot process in background |
| `tunnelmate bot stop` | — | Stop background Telegram Bot process |
| `tunnelmate bot restart` | — | Gracefully restart background Telegram Bot process |
| `tunnelmate bot status` | — | Inspect bot process status, token, and admin whitelist |
| `tunnelmate bot set-token` | `<token>` | Configure Telegram bot API token |
| `tunnelmate bot set-password`| `<password>` | Set salted SHA-256 admin password |
| `tunnelmate bot chats` | — | List all historical chat IDs and subscriber names |
| `tunnelmate bot whitelist` | `<chat_id>` | Add Telegram Chat ID to administrator whitelist |
| `tunnelmate bot unwhitelist` | `<chat_id>` | Remove Telegram Chat ID from whitelist |
| `tunnelmate bot sessions` | — | Display active server-side session status table |
| `tunnelmate bot revoke-sessions` | — | Invalidate all active sessions (force logout) |
| `tunnelmate bot clear-tunnels` | — | Purge published SSH tunnel metadata from Telegram |
| `tunnelmate bot 2fa-status` | — | Check TOTP 2FA activation status |
| `tunnelmate bot 2fa-setup` | — | Setup TOTP 2FA with high-contrast terminal QR code |
| `tunnelmate bot 2fa-disable` | — | Disable TOTP 2FA |
| `tunnelmate bot 2fa-test` | `<code>` | Verify a 6-digit TOTP code against active secret |


### Task & Tunnel Scheduler Commands (`tunnelmate schedule` / `cron`)
| Command | Arguments | Description |
|---|---|---|
| `tunnelmate schedule list` | — | List all configured cron jobs, next run times, and statuses |
| `tunnelmate schedule add` | `<tunnel> <action> <cron>` | Schedule tunnel action (`start`, `stop`, `restart`, `health`) on a cron expression |
| `tunnelmate schedule run` | `<job_id>` | Immediately trigger a scheduled job out-of-band |
| `tunnelmate schedule pause` | `<job_id>` | Temporarily pause an active scheduled job |
| `tunnelmate schedule resume` | `<job_id>` | Resume a paused scheduled job |
| `tunnelmate schedule logs` | `<job_id> [--lines 20]` | View recent execution logs and trigger history for a job |
| `tunnelmate schedule delete` | `<job_id>` | Delete a scheduled task |


### Two-Factor Authentication Commands (`tunnelmate 2fa` / `totp`)
| Command | Arguments | Description |
|---|---|---|
| `tunnelmate 2fa status` | — | Display 2FA status, secret presence, and verification state |
| `tunnelmate 2fa setup` | — | Generate new TOTP secret, display compact terminal QR code, and verify |
| `tunnelmate 2fa disable` | — | Disable Two-Factor Authentication |
| `tunnelmate 2fa enable` | — | Re-enable existing configured Two-Factor Authentication |
| `tunnelmate 2fa test` | `<code>` | Test/validate a 6-digit code against current TOTP secret |

---

## 🐍 Python Library API

Install TunnelMate as a library in your project:

```bash
pip install tunnelmate-cli
```

Then embed TunnelMate directly into your Python scripts and services:

```python
from tunnelmate.client import TunnelMateClient

client = TunnelMateClient()

# Check daemon connectivity
if not client.is_daemon_online():
    print("Daemon is offline. Start with 'tunnelmate daemon start'")
    exit(1)

# Create and start a tunnel
client.create_tunnel(name="fastapi-app", port=8000)
tunnel = client.start_tunnel("fastapi-app")
print(f"Public Quick Tunnel URL: {tunnel.current_url}")

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

# Change target port dynamically
client.change_port("fastapi-app", 8080)

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

---

## 🔒 Security & Privacy Architecture

1. **Subprocess Isolation (No `shell=True`):**  
   All `cloudflared` instances are spawned using explicit argument lists via `subprocess.Popen` without `shell=True`. Process groups prevent orphan or zombie processes.
2. **Restricted Unix Domain Socket:**  
   The IPC socket (`~/.tunnelmate/tunnelmate.sock`) is strictly restricted to filesystem permissions `0600` (read/write only by the owning user).
3. **State Directory Permissions:**  
   The configuration and SQLite database directory `~/.tunnelmate` is initialized with permissions `0700`.
4. **Salted SHA-256 Authentication:**  
   Admin passwords use high-entropy random salts (`secrets.token_hex(16)`) and SHA-256 hashing. Password verification uses constant-time string comparisons (`secrets.compare_digest`) to prevent timing attacks.
5. **Private Encrypted SSH Tunnel Metadata:**  
   Published SSH tunnels are encrypted with token-derived keys (counter-mode HMAC keystream + SHA-256 HMAC authentication) and stored under hidden language tags. Public visitors to the bot see only the default description.
6. **Server-Side Session Verification:**  
   Broadcast notifications are strictly restricted to subscribers with an active, authenticated server session (`is_authenticated == True`). Logged-out users receive zero URLs.

---

## 🧪 Test Suite & Validation

TunnelMate comes with a comprehensive test suite covering database operations, IPC serialization, process lifecycle, password hashing, SSH discovery, and session security:

```bash
# Run all unit and integration tests
pytest -v tests/
```

Test coverage includes:
- `test_cross_platform.py` — Process termination, cross-platform paths, reboot persistence, session revocation, and notification security.
- `test_ssh_discovery.py` — Hostname parsing, token keystream encryption/decryption, username/device detection, and multi-device merging.
- `test_db.py` — SQLite schema migrations, WAL mode transactions, subscriber preferences, and session tracking.
- `test_config.py` — Salted password hashing, configuration serialization, and validation.
- `test_ipc.py` — Unix socket / TCP client-server roundtrips and serialization.
- `test_cli.py` — Typer CLI command dispatch, formatting panels, and help outputs.
- `test_health.py` — Ephemeral HTTP origin and TCP latency verification.

---

## 📄 License & Credits

Created by **Shashan Lumbhani** ([lumbhanishashan1510@gmail.com](mailto:lumbhanishashan1510@gmail.com)).  
Distributed under the **MIT License**. See `LICENSE` for details.

*Built with ❤️ for seamless, secure localhost ingress across every device.*
