Access Your Ubuntu AI-Agent Server with Zero Open Ports
When running autonomous terminal-based coding agents—such as Claude Code or Gemini CLI—on a home server or homelab, a practical challenge quickly emerges: how do you monitor long-running sessions, approve commands, and inspect logs from any browser or mobile device without exposing your local network?
The traditional approach—opening port 22 on your router via Port Forwarding or exposing web dashboards directly to the internet—turns your public IP into a permanent target for automated scanners and brute-force bots.
In this post, I share the exact architecture I built on an Ubuntu server: a browser-accessible terminal environment over HTTPS/WebSockets with zero open inbound ports, protected by Cloudflare Zero Trust, engineered to run 24/7 on repurposed laptop hardware with the lid closed, and hardened with 3-tier automated self-healing.
1. System Architecture & Defense-in-Depth Infographic
The core principle behind this design is complete local network isolation. No service listens on a public interface or even on the local LAN: everything binds strictly to 127.0.0.1 and reaches the internet exclusively through an outbound encrypted tunnel.
Active Defense Layers
- Zero Trust Perimeter (Cloudflare Edge + Access): Zero open ports to the internet (UFW set to default deny incoming), encrypted outbound
cloudflaredtunnel, email OTP verification, country geo-fencing, and TOTP MFA. Automated scanners cannot even reach the local services. - Loopback Isolation (
127.0.0.1): Both the web terminal (ttyd) and the mobile companion panel bind strictly to127.0.0.1, making them unreachable even from other devices on the same local Wi-Fi/LAN. - Secondary Authentication & Secret Isolation: HTTP Basic Auth on
ttydwith credentials stored outside systemd unit files (/etc/web-terminal.envwithchmod 600owned exclusively byroot). - True Session Persistence: Closing a browser tab or losing cellular signal never interrupts running processes inside
tmux.
2. Host Hardening & Closed-Lid 24/7 Operation
To repurpose a laptop as a silent 24/7 homelab node with the lid closed while keeping the local firewall completely locked down:
Local Firewall (UFW)
Because cloudflared initiates outbound connections to Cloudflare’s edge over port 443/QUIC, we can block all incoming traffic:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
Preventing Sleep When Closing the Lid (systemd-logind + GNOME)
In /etc/systemd/logind.conf, configure lid events to ignore suspension:
[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
HandleLidSwitchDocked=ignore
Disable AC inactivity sleep on the desktop power manager and reload systemd-logind:
gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-type 'nothing'
sudo systemctl restart systemd-logind
Enable automatic unattended security patches for kernel and OS packages:
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
3. Web Terminal (ttyd), Idempotent tmux Session & Mobile PWA
To render a full-featured terminal inside the browser, we use ttyd, a lightweight C daemon built on libwebsockets and xterm.js.
Credential Isolation with EnvironmentFile
Instead of hardcoding credentials inside /etc/systemd/system/web-terminal.service (which is world-readable by default), store them in a root-only environment file:
echo "TTYD_CREDENTIAL=admin:CHANGE_THIS_STRONG_PASSWORD" | sudo tee /etc/web-terminal.env
sudo chmod 600 /etc/web-terminal.env
sudo chown root:root /etc/web-terminal.env
Idempotent tmux Boot Service (tmux-agents.service)
To prevent race conditions after a power outage or reboot, an idempotent oneshot service initializes the persistent agents session before the web services attach to it:
# /etc/systemd/system/tmux-agents.service
[Unit]
Description=Initialize persistent tmux session for AI agents
After=network.target
[Service]
Type=oneshot
RemainAfterExit=yes
User=ubuntu
ExecStart=/usr/bin/tmux new-session -A -d -s agents -c /home/ubuntu/dev
ExecStop=/usr/bin/tmux kill-session -t agents
[Install]
WantedBy=multi-user.target
Web Terminal Service (web-terminal.service)
With the session guaranteed, bind ttyd strictly to 127.0.0.1:7681:
# /etc/systemd/system/web-terminal.service
[Unit]
Description=ttyd Web Terminal Service
After=network.target tmux-agents.service
[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu
EnvironmentFile=/etc/web-terminal.env
ExecStart=/usr/local/bin/ttyd -i 127.0.0.1 -p 7681 -W -c ${TTYD_CREDENTIAL} tmux new-session -A -s agents
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
Mobile Companion PWA (Voice & Push Notifications)
Typing complex commands or tmux keybindings on a smartphone screen can be tedious. To solve this, I deployed a lightweight companion web service on 127.0.0.1:8090 (agents.example.com), protected by the exact same Zero Trust policy:
- Dynamic Window Tabs: Maps each active
tmuxwindow into touch-friendly tabs. - Quick-Action Touch Keys: One-tap buttons for frequent agent prompts (
y,n,Enter,Ctrl+C). - Voice & Push Notifications: Web Speech API dictation/readout plus mobile push notifications whenever an agent finishes a long task or pauses waiting for confirmation.
4. Outbound Tunnel & Cloudflare Zero Trust Policies
With cloudflared running as a system service, /etc/cloudflared/config.yml maps both subdomains to our local loopback ports:
tunnel: <YOUR_TUNNEL_UUID>
credentials-file: /etc/cloudflared/<YOUR_TUNNEL_UUID>.json
ingress:
- hostname: term.example.com
service: http://127.0.0.1:7681
- hostname: agents.example.com
service: http://127.0.0.1:8090
- service: http_status:404
Inside Cloudflare Zero Trust → Access → Applications, both applications are governed by an explicit Allow policy:
- Include: Your authorized email address.
- Require: TOTP Authenticator MFA + Country geo-fencing rule.
- Session Duration: 6 hours (with MFA re-authentication enforced every 180 minutes).
5. 3-Tier Resilience & Automated Self-Healing
Running an unattended homelab server 24/7 requires automated recovery across software hangs, disk saturation, thermal spikes, and kernel deadlocks.
Tier 1: Service Watchdog + Disk & Thermal Guard
A systemd timer (agents-watchdog.timer) triggers /usr/local/sbin/agents-watchdog.sh (chmod 700, owned by root) every 60 seconds:
- Service Health Checks: Verifies that the
agentstmux session exists, local ports7681and8090are listening, andcloudflaredis active. If any check fails, it cleans up orphanedttydprocesses and restarts the service chain. - Preventive Disk Management: System logs are capped at 500 MB via
/etc/systemd/journald.conf.d/size-limit.conf(SystemMaxUse=500MandMaxRetentionSec=14day). Additionally, if root partition/usage reaches 85%, the watchdog automatically runsjournalctl --vacuum-size=200Mandapt-get clean. - Thermal Monitoring: Reads
lm-sensorson each run and logs a warning tojournalctlif CPU package temperature (Package id 0) reaches or exceeds 85°C.
Tier 2: Controlled Reboot with Anti-Loop Protection
If Tier 1 fails to restore service health after 3 consecutive checks tracked in /var/tmp/agents-watchdog/fail_count, the watchdog issues systemctl reboot. To prevent endless reboot loops during an external ISP outage, it logs timestamps to /var/tmp/agents-watchdog/reboots.log and blocks further reboots if 2 reboots have already occurred within the past hour.
Tier 3: Hardware Watchdog (iTCO_wdt) & Kernel Panic Recovery
If the Linux kernel hits a complete deadlock where user-space scripts can no longer run, the hardware watchdog driver (iTCO_wdt) and systemd force a physical hardware reset after 60 seconds without a heartbeat:
# /etc/modules-load.d/watchdog.conf
iTCO_wdt
# /etc/systemd/system.conf.d/watchdog.conf
[Manager]
RuntimeWatchdogSec=60s
RebootWatchdogSec=2min
# /etc/sysctl.d/99-watchdog-panic.conf
kernel.panic = 10
Resilience Testing Protocol
Before moving into daily production, I validated all three recovery tiers with controlled fault-injection tests:
- Tier 1 Test: Force-kill
ttydand destroy thetmuxsession (sudo pkill -9 ttyd && tmux kill-session -t agents), then verify automatic recovery within 60 seconds viajournalctl -t agents-watchdog. - Tier 2 Test: Temporarily stop
cloudflared(sudo systemctl disable --now cloudflared) and confirm an automatic controlled reboot after 3 consecutive failures. - Tier 3 Test: Trigger a controlled kernel panic via SysRq (
echo 1 | sudo tee /proc/sys/kernel/sysrq && echo c | sudo tee /proc/sysrq-trigger) and verify hardware watchdog reset and full stack restoration.
6. Terminal Ergonomics & Automated Dotfiles Backup
Operating inside a web terminal benefits greatly from visual clarity, fast pane navigation, and automated configuration backups.
Oh My Tmux Customizations (~/.tmux.conf.local)
With Oh My Tmux, ~/.tmux.conf is a symlink to ~/.tmux/.tmux.conf, so all user customizations belong in ~/.tmux.conf.local right before loading TPM:
# Mouse support, extended scrollback, and 1-based indexing
set -g mouse on
set -g history-limit 10000
set -g base-index 1
setw -g pane-base-index 1
# Smart automatic window renaming based on project directory or active command
set -g automatic-rename on
set -g automatic-rename-format '#{?#{==:#{pane_current_command},zsh},#{b:pane_current_path},#{pane_current_command}}'
# Background tab activity notifications
setw -g monitor-activity on
set -g visual-activity off
# Fast pane resizing (H/J/K/L) and floating btop telemetry popup (Ctrl+b + m)
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5
bind m display-popup -E -w 90% -h 85% "btop"
# Floating quick-action context menu (Ctrl+b + g)
bind g display-menu -T "#[bold]Quick tmux Actions#[default]" -x C -y C \
"Split Vertical (|)" v "split-window -h -c '#{pane_current_path}'" \
"Split Horizontal (-)" s "split-window -v -c '#{pane_current_path}'" \
"" \
"New Window" c "new-window -c '#{pane_current_path}'" \
"Rename Window" r "command-prompt -I '#W' 'rename-window -- \"%%\"'" \
"Zoom / Restore Pane" z "resize-pane -Z" \
"" \
"System Monitor (btop)" m "display-popup -E -w 90% -h 85% 'btop'" \
"" \
"Reload Config" R "source-file ~/.tmux.conf; display-message 'tmux reloaded!'"
# Session persistence across reboots
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @continuum-restore 'on'
run '~/.tmux/plugins/tpm/tpm'
Browser clipboard tip: If browser security policies block clipboard writes over OSC 52 escape sequences, holding
Shiftwhile dragging with the mouse bypassestmuxmouse capture so you can copy directly viaCtrl+Shift+C.
Oh My Zsh + Automated GitHub Backup via Deploy Key
In ~/.zshrc, combining zoxide, fzf, zsh-autosuggestions, and zsh-syntax-highlighting with a backup-dots shell alias snapshots .tmux.conf.local, .zshrc, .p10k.zsh, all custom systemd units, and the watchdog script into a local Git repository and pushes them to a private GitHub repository authenticated via a repository-scoped SSH Deploy Key (granting write access only to that single backup repository, never to the full GitHub account).
Conclusion
Pairing Cloudflare Zero Trust with ttyd, tmux, a mobile PWA companion, and a 3-tier self-healing systemd setup turns an ordinary Ubuntu machine into a resilient remote workstation for autonomous AI agents—accessible from anywhere while keeping your home network completely invisible to the public internet.