Skip to main content

⚡ 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, Rich, and 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

┌─────────────────────────────────┐       ┌─────────────────────────────────┐
│     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:

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 -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

# 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

tunnelmate daemon start

Verify daemon health:

tunnelmate daemon status

Step 2: Open Interactive TUI Menu

Launch the interactive arrow-key menu:

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

# 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

# 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

# Remaps tunnel from port 8080 to 3000 (safely replaces the process)
tunnelmate port my-web 3000

Diagnostic Health Check

tunnelmate health my-web

Inspect Live Logs & Audit History

# 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

# 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) and configure an admin password:

# 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

# 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.

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:

loginctl enable-linger $USER

🐍 Python Library Usage

You can embed TunnelMate directly into your Python applications:

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:

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.

Metadata

Release files for tunnelmate-cli 1.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tunnelmate-cli 1.0.5
File Size Uploaded
tunnelmate_cli-1.0.5.tar.gz 58.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for tunnelmate-cli 1.0.5
File Interpreter ABI Platform
tunnelmate_cli-1.0.5-py3-none-any.whl Python 3 none any Details

Total release size: 117.3 kB

Release files / tunnelmate_cli-1.0.5.tar.gz

Download URL tunnelmate_cli-1.0.5.tar.gz
Size 58.2 kB
Tags Source
SHA-256 checksum
How to use checksums
7865acfa12e77095e4012c2a15527ee301dd3b524d3da70be9ac39c4aaa86e15
BLAKE2b-256 checksum
How to use checksums
b73b56baabf76ca63425f2fb13558f4f6b05ad16ebd4c3371fb4371b2b7e8ff9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / tunnelmate_cli-1.0.5-py3-none-any.whl

Download URL tunnelmate_cli-1.0.5-py3-none-any.whl
Size 59.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9625ba44ab694f2b86fe22ad1b1ab94f9ba25b728d83a6c5595942c23030b315
BLAKE2b-256 checksum
How to use checksums
e096b89749b7ddc44993e32859fce68dd97f0232d7afce866d3d90735d2b9e6f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release history Release notifications | RSS feed

This release

1.0.5 This release

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page