Skip to content
All writing

Tunneling to Local Machines

This post explores the tunneling options available, their security implications, and why reverse WebSockets emerged as the superior choice for production applications.

Author
Tushar Khairnar
Published
Revised
Not revised
Length
10 min read
Cover image for Tunneling to Local Machines

When building modern web applications, you sometimes need your cloud-hosted API server to communicate with processes running on users' local machines. This pattern is increasingly common for AI applications running local LLMs, developer tools accessing local filesystems, or hybrid architectures that leverage local compute resources.

This post explores the tunneling options available, their security implications, and why reverse WebSockets emerged as the superior choice for production applications.

1. What is Tunneling and Why It's Needed

Consider this architecture:

text
Browser → API Server (cloud) → Local Process (user's machine)

The challenge is clear: your API server, running in the cloud with a public IP, needs to reach a process on a user's local machine that sits behind NAT, firewalls, and has no public IP address.

Common use cases:

  • Running local LLMs (Ollama, llama.cpp) while using a cloud-based UI
  • Accessing local files for processing without uploading them
  • Executing local scripts or commands from a web interface
  • Hybrid architectures that keep sensitive data local while using cloud orchestration

The fundamental problem: inbound connections to local machines are blocked by default. We need a way to establish communication without requiring users to configure port forwarding, punch holes in firewalls, or expose their machines directly to the internet.

2. Choices Available

Several solutions exist for this problem, each with different trade-offs:

Solution Latency Setup Complexity Cost Best For
Cloudflare Tunnels Medium Medium Free tier / Pay Production, security-focused
ngrok Medium Low Free tier limited Quick prototyping
Tailscale Low Medium Free for personal When API server can join mesh
bore Medium Low Free (self-host) Simple, open source, minimal
localtunnel Medium Low Free (self-host) Subdomain support needed
Reverse WebSocket Lowest Higher (custom) Free Full control, real-time, production

3. How Each Choice Implements Tunneling

Cloudflare Tunnels

Cloudflare Tunnels use a daemon (cloudflared) that runs on the local machine and establishes an outbound connection to Cloudflare's edge network.

text
Internet → Cloudflare Edge → Tunnel → Local Service
                 ↑
         cloudflared daemon
         (outbound connection)

Setup:

bash
cloudflared tunnel login
cloudflared tunnel create my-worker
cloudflared tunnel run --url http://localhost:3001 my-worker

The local service gets a public hostname (e.g., my-worker.yourdomain.com), and all traffic routes through Cloudflare's infrastructure.

bore (Rust, Minimal)

bore is a lightweight TCP tunnel written in ~1000 lines of Rust. It uses pure TCP multiplexing:

text
                    ┌─────────────────────┐
                    │   Relay Server      │
Internet Request    │   (public IP)       │    Outbound Connection
─────────────────►  │  ┌───────────────┐  │  ◄─────────────────────
  tcp://relay:12345 │  │ Port Mapping  │  │    bore client
                    │  │ 12345 → conn1 │  │         │
                    │  └───────────────┘  │         ▼
                    └─────────────────────┘   Local Service
                                              localhost:3001

How it works:

  1. Client connects to server's control port (default 7835)
  2. Server assigns a public port (e.g., 12345)
  3. When traffic hits relay:12345, server forwards over control connection
  4. Client proxies to localhost:3001
bash
# Server
bore server --min-port 1024 --max-port 65535

# Client
bore local 3001 --to your-server.com
# Output: Listening on your-server.com:12345

localtunnel (Node.js)

localtunnel provides subdomain-based routing:

bash
# Server
npx localtunnel-server --port 8000 --domain your-lt-server.com

# Client
npx localtunnel --host https://your-lt-server.com --port 3001
# Output: your url is: https://abc123.your-lt-server.com

Protocol: HTTP for control, TCP pool for data transfer. Subdomains are assigned dynamically or can be requested.

Reverse WebSocket

Instead of the API server calling the local machine, the local machine initiates a WebSocket connection to the API server:

text
Browser → API Server ← WebSocket ← Local Process

The local process maintains a persistent WebSocket connection. When the API server needs work done locally, it sends a message over this existing connection.

python
# Local process connects TO the server
ws = websocket.connect('wss://api-server.com/ws/worker')
ws.send(json.dumps({"token": "user123"}))

# Listen for requests
for message in ws:
    request = json.loads(message)
    result = process_locally(request)
    ws.send(json.dumps({"id": request["id"], "result": result}))

4. Security Implications and How Each Tool Handles Them

Security is where these solutions diverge significantly.

Authentication

Tool Approach Risk
bore --secret flag (single shared secret) One secret for all users
localtunnel None built-in Anyone can use your relay
Cloudflare Cloudflare account + Zero Trust policies Requires CF ecosystem
Reverse WebSocket Your existing auth (JWT, sessions, etc.) Fully integrated

bore's shared secret:

bash
bore server --secret "your-secret-key"
bore local 3001 --to server.com --secret "your-secret-key"

WebSocket with per-user auth:

python
async def worker_websocket(websocket):
    auth = await websocket.receive_json()
    user = verify_jwt(auth["token"])  # Your existing auth

    if not user:
        await websocket.close(code=4001)
        return

    workers[user.id] = {"ws": websocket, "permissions": user.permissions}

TLS/Encryption

Tool TLS Status What You Need
bore None by default Add nginx/Caddy in front
localtunnel Optional Configure separately
Cloudflare Built-in Nothing extra
Reverse WebSocket Inherits from your server Already have it (wss://)

For bore/localtunnel, you need a reverse proxy:

nginx
server {
    listen 443 ssl;
    server_name *.bore.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/bore.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/bore.yourdomain.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:$server_port;
    }
}

With WebSocket, your API server already has HTTPS, so wss:// comes for free.

Abuse Potential

Open relays (bore/localtunnel) can be abused for:

  • Hosting phishing pages
  • Serving malware
  • Bypassing corporate firewalls
  • Hiding attack origin

Even with authentication, users of your relay can expose malicious content, and your server's IP gets associated with it.

Reverse WebSocket is a closed system:

  • Only authenticated users can connect
  • You control exactly what operations are permitted
  • No public URLs for local services
  • No relay infrastructure to abuse
python
# Whitelist allowed operations
allowed_ops = ['process-image', 'run-script', 'read-file']

if request.operation not in allowed_ops:
    return {"error": "Operation not permitted"}

# Per-user permissions
if request.operation == 'read-file' and 'file-access' not in user.permissions:
    return {"error": "No file access permission"}

Resource Exhaustion

Tool Rate Limiting Per-User Control
bore/localtunnel OS-level only (iptables, systemd) No
Cloudflare Built-in, configurable Yes (with Zero Trust)
Reverse WebSocket Your code, your rules Full granularity
python
# Per-user, per-plan rate limiting
user_limits = {
    "free": {"max_concurrent": 2, "requests_per_minute": 10},
    "pro": {"max_concurrent": 10, "requests_per_minute": 100},
}

def handle_request(user_id, request):
    limits = user_limits[users[user_id].plan]

    if pending_requests[user_id] >= limits["max_concurrent"]:
        raise RateLimitError("Too many concurrent requests")

Access Control on Exposed Services

With bore/localtunnel, your local service is directly exposed to the internet. Access control must be implemented in the local service itself or via an auth proxy.

With Reverse WebSocket, the local service is never exposed:

text
         Internet
            │
            ▼
      ┌───────────┐
      │ API Server │ ← Access control here
      └─────┬─────┘
            │ Private WebSocket
            ▼
      ┌───────────┐
      │ Local Node │ ← No internet exposure
      └───────────┘

DNS/Subdomain Hijacking

localtunnel is vulnerable to subdomain squatting:

bash
# Attacker grabs your usual subdomain before you
npx localtunnel --host https://your-server.com --subdomain myapp
# Now they control myapp.your-server.com

Reverse WebSocket has no DNS attack surface—identity is cryptographic (tokens), not DNS-based.

5. Best Practical Choice: Reverse WebSockets

For production applications with user accounts, Reverse WebSocket wins decisively:

Aspect bore/localtunnel Reverse WebSocket
Architecture Open relay Closed system
Security model Add-on Integrated
Auth Separate system Your existing auth
TLS Extra setup Already have it
Attack surface Relay + exposed service Just your API
Per-user control Limited Full
Operational Separate component Part of your app

When to still use bore/localtunnel:

  • Quick demos and prototypes
  • Non-authenticated public access needed
  • TCP (non-HTTP) protocols
  • Development and testing

When to use Reverse WebSocket:

  • Production with user accounts
  • Security-sensitive applications
  • You control both ends
  • Need fine-grained access control

6. Implementation: The ws-local-worker Project

Based on these findings, I implemented a complete working example using Reverse WebSocket architecture with Python (FastAPI) and React.

You can checkout source code from - ws-local-worker on Github

Project Structure

text
ws-local-worker/
├── api-server/
│   └── main.py          # FastAPI server (WebSocket hub + static files)
├── local-worker/
│   └── worker.py        # Python process that runs on user's machine
├── frontend/
│   ├── src/
│   │   ├── App.jsx      # React chat UI with streaming
│   │   └── main.jsx
│   ├── index.html
│   ├── package.json
│   └── vite.config.js
├── requirements.txt
├── start.sh
└── README.md

Architecture

text
┌─────────────────────────────────────────────────────────────────┐
│                         BROWSER                                  │
│  React App ←──── WebSocket (streaming) ────→ /ws/browser        │
└───────────────────────────┬─────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                    API SERVER (FastAPI)                          │
│  - Serves React static build                                     │
│  - WebSocket hub for workers & browsers                          │
│  - Routes messages between them                                  │
└───────────────────────────┬─────────────────────────────────────┘
                            │ WebSocket (outbound from worker)
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│                LOCAL WORKER (User's Machine)                     │
│  - Connects TO server (no inbound ports)                         │
│  - Processes requests locally                                    │
│  - Streams responses back                                        │
└─────────────────────────────────────────────────────────────────┘

Key Implementation Details

API Server (FastAPI) manages two WebSocket endpoints:

  • /ws/worker - Local workers connect here with authentication tokens
  • /ws/browser - Browser clients connect for real-time streaming
python
@app.websocket("/ws/worker")
async def worker_websocket(websocket: WebSocket):
    await websocket.accept()

    # Authenticate worker
    auth_msg = await websocket.receive_json()
    user_id = auth_msg.get("token")

    if not user_id:
        await websocket.close(code=4001, reason="Missing token")
        return

    worker = await worker_hub.register(user_id, websocket)

    # Listen for responses from worker
    while True:
        data = await websocket.receive_json()
        await handle_worker_message(worker, data)

Local Worker (Python) initiates the connection and processes requests:

python
class LocalWorker:
    async def connect(self):
        self.session = aiohttp.ClientSession()
        self.ws = await self.session.ws_connect(self.server_url)

        # Authenticate
        await self.ws.send_json({"token": self.token})

    async def handle_chat_streaming(self, data):
        response = await self.process_locally(data["message"])

        # Stream word by word
        for word in response.split(" "):
            await self.ws.send_json({
                "type": "stream_chunk",
                "request_id": data["request_id"],
                "session_id": data["session_id"],
                "content": word + " "
            })
            await asyncio.sleep(0.05)

        await self.ws.send_json({"type": "stream_end", ...})

Frontend (React) maintains a WebSocket connection for real-time updates:

javascript
const connectWebSocket = () => {
    const ws = new WebSocket(`wss://${window.location.host}/ws/browser`);

    ws.onmessage = (event) => {
        const data = JSON.parse(event.data);

        if (data.type === 'stream_chunk') {
            // Append streaming content
            setMessages(prev => {
                const newMessages = [...prev];
                newMessages[newMessages.length - 1].content += data.content;
                return newMessages;
            });
        }
    };
};

Running the Demo

bash
cd ws-local-worker

# Install dependencies
pip install -r requirements.txt
cd frontend && npm install && npm run build && cd ..

# Terminal 1: Start API server
cd api-server && uvicorn main:app --port 8000

# Terminal 2: Start local worker
cd local-worker && python worker.py --token user123

# Open browser: http://localhost:8000

Features Implemented

  1. Reverse WebSocket - Worker initiates connection (no port forwarding)
  2. Streaming responses - Word-by-word streaming like ChatGPT
  3. Token-based auth - Worker identification tied to user accounts
  4. Static file serving - FastAPI serves the React build
  5. Auto-reconnect - Worker automatically reconnects on disconnect
  6. Status indicators - UI shows connection status for both WebSocket and worker

Conclusion

While tools like Cloudflare Tunnels, bore, and localtunnel have their place for quick prototypes and development, Reverse WebSocket is the superior choice for production applications that need:

  • Integrated authentication with existing user systems
  • Fine-grained access control and rate limiting
  • Minimal attack surface
  • No external dependencies or relay infrastructure
  • Real-time streaming capabilities

The trade-off is writing more code, but this code integrates naturally into your existing application architecture rather than bolting on a separate tunneling layer with its own security concerns.

The ws-local-worker implementation demonstrates this pattern can be built with straightforward Python and JavaScript, providing a solid foundation for hybrid architectures that leverage local compute while maintaining cloud orchestration.