Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(systemd): cloudflared tunnel + boot-race watchdog (#319)
Aurora Capital12321f8c0239
diff --git a/claude-ops/scripts/systemd/README-cloudflared.md b/claude-ops/scripts/systemd/README-cloudflared.mdnew file mode 100644index 00000000..a3dbce03--- /dev/null+++ b/claude-ops/scripts/systemd/README-cloudflared.md@@ -0,0 +1,75 @@+# Cloudflared tunnel + watchdog++Optional units for exposing the pocket-ops-ui (or any local service) through+a Cloudflare named tunnel with Zero Trust Access in front. Skip these units+if you only access the pocket UI over Tailscale.++## What's here++| File | Purpose |+|---|---|+| `cloudflared.service` | Runs `cloudflared tunnel run --token …` with `Restart=always` so the daemon self-heals on crash or token reload. |+| `cloudflared-watchdog.sh` | Detects the boot-time race where cloudflared starts before its v2 dashboard config arrives and gets stuck serving 503s with empty ingress. Restarts cloudflared when the running process's journal shows `No ingress rules` AND the dashboard has at least one configured hostname. |+| `cloudflared-watchdog.service` | Oneshot wrapper that invokes the script. |+| `cloudflared-watchdog.timer` | Runs the oneshot every 5 minutes (first fire 2 min after boot). |++## Setup++1. **Create a named tunnel** in the Cloudflare Zero Trust dashboard+ (Networks → Tunnels → Create a tunnel → Cloudflared). Copy the token.++2. **Edit `/etc/systemd/system/cloudflared.service`** after install — replace+ the `${CLOUDFLARED_TUNNEL_TOKEN}` placeholder with the real token string.+ This file is installed verbatim by `install-systemd-units.sh` and the+ token MUST be substituted out-of-band; do not commit it to git.++3. **Create `/etc/cloudflared-watchdog.env`** with `chmod 600`:++ ```+ CLOUDFLARE_API_TOKEN=<token with Account:Tunnel:Read>+ ```++ Generate this in the Cloudflare dashboard under My Profile → API Tokens.+ Scope to `Account: Cloudflare Tunnel: Read` only — the watchdog only+ reads the v2 config, never mutates it.++4. **Add ingress rules** to the tunnel in the Cloudflare dashboard+ (Public Hostname tab). The watchdog only restarts cloudflared if the+ dashboard has at least one configured hostname.++5. **Reload + enable**:++ ```+ sudo systemctl daemon-reload+ sudo systemctl enable --now cloudflared.service+ sudo systemctl enable --now cloudflared-watchdog.timer+ ```++## Failure mode the watchdog catches++On cold boot, systemd can start `cloudflared` seconds before Cloudflare's+control plane has pushed the v2 dashboard config to the local agent. The+agent registers with the edge but loads no ingress rules — logs:++```+WRN No ingress rules were defined in provided config (if any) nor from the+ cli, cloudflared will return 503 for all incoming HTTP requests+```++systemd sees the process as healthy (it never crashes), so the existing+`Restart=on-failure` policy doesn't trigger. Users hit `503 currently+unable to handle this request` on every gated hostname until someone+SSH-restarts cloudflared.++The watchdog closes this gap:++1. Fetches the live tunnel config via the Cloudflare API.+2. Counts ingress entries that actually have a `hostname`.+3. If hostnames are configured upstream **but** the journal shows the+ `No ingress rules` warning anywhere after the cloudflared process's+ `ExecMainStartTimestamp`, restart cloudflared so it re-pulls the v2+ config from the edge.++The journal-window scoping prevents restart loops: once cloudflared has+been restarted cleanly and is serving traffic, the historical warning is+no longer "in the current run" and the watchdog goes quiet.diff --git a/claude-ops/scripts/systemd/cloudflared-watchdog.service b/claude-ops/scripts/systemd/cloudflared-watchdog.servicenew file mode 100644index 00000000..96984fd5--- /dev/null+++ b/claude-ops/scripts/systemd/cloudflared-watchdog.service@@ -0,0 +1,7 @@+[Unit]+Description=cloudflared watchdog — restart when tunnel has empty ingress+After=cloudflared.service++[Service]+Type=oneshot+ExecStart=/usr/local/bin/cloudflared-watchdog.shdiff --git a/claude-ops/scripts/systemd/cloudflared-watchdog.sh b/claude-ops/scripts/systemd/cloudflared-watchdog.shnew file mode 100755index 00000000..b3712c20--- /dev/null+++ b/claude-ops/scripts/systemd/cloudflared-watchdog.sh@@ -0,0 +1,77 @@+#!/usr/bin/env bash+# cloudflared-watchdog — self-heal when the tunnel has no usable ingress.+#+# Symptoms this catches (the boot-time empty-ingress outage):+# cloudflared.service running and registered, but no ingress rules loaded+# (boot-time race: cloudflared started before Cloudflare pushed the v2+# dashboard config). cloudflared returns 503 for every request, but+# systemd thinks it's healthy because the process is up.+#+# Strategy:+# 1. Read tunnel token from cloudflared.service to derive ACCOUNT + TUNNEL.+# 2. Fetch v2 dashboard config from Cloudflare API; count hostnames.+# 3. If hostnames > 0 AND the journal has 'No ingress rules' AFTER the+# current cloudflared process start time → restart it.+#+# Requires /etc/cloudflared-watchdog.env with:+# CLOUDFLARE_API_TOKEN=<token with Account:Tunnel:Read>++set -u+LOG_TAG='cloudflared-watchdog'+ENV_FILE='/etc/cloudflared-watchdog.env'+UNIT='/etc/systemd/system/cloudflared.service'++log() { logger -t "$LOG_TAG" -- "$*"; echo "[$LOG_TAG] $*" >&2; }++[[ -r $ENV_FILE ]] || { log "missing $ENV_FILE — exit 0"; exit 0; }+# shellcheck disable=SC1090+. $ENV_FILE+[[ -n ${CLOUDFLARE_API_TOKEN:-} ]] || { log 'CLOUDFLARE_API_TOKEN unset — exit 0'; exit 0; }++TOKEN_B64=$(grep -oE 'token [A-Za-z0-9+/=]+' $UNIT | head -1 | awk '{print $2}')+[[ -n $TOKEN_B64 ]] || { log 'no tunnel token in unit — exit 0'; exit 0; }++DECODED=$(echo "$TOKEN_B64" | base64 -d 2>/dev/null || true)+ACCOUNT=$(echo "$DECODED" | python3 -c 'import sys,json; print(json.load(sys.stdin)["a"])' 2>/dev/null || true)+TUNNEL=$(echo "$DECODED" | python3 -c 'import sys,json; print(json.load(sys.stdin)["t"])' 2>/dev/null || true)+[[ -n $ACCOUNT && -n $TUNNEL ]] || { log 'token decode failed — exit 0'; exit 0; }++CONFIG_JSON=$(curl -sf -m 10 -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \+ "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT/cfd_tunnel/$TUNNEL/configurations" 2>/dev/null || true)+[[ -n $CONFIG_JSON ]] || { log 'cloudflare api unreachable — exit 0'; exit 0; }++HOSTNAME_COUNT=$(echo "$CONFIG_JSON" | python3 -c '+import json, sys+try:+ d = json.load(sys.stdin)+ ing = d.get("result", {}).get("config", {}).get("ingress", [])+ print(sum(1 for r in ing if r.get("hostname")))+except Exception:+ print(0)+' 2>/dev/null || echo 0)++if [[ $HOSTNAME_COUNT -lt 1 ]]; then+ log "dashboard config has zero hostnames — nothing to enforce"+ exit 0+fi++# Get the cloudflared process start timestamp (ExecMainStartTimestamp).+# Only count 'No ingress rules' warnings that appear AFTER this — older+# warnings refer to a previous run we already self-healed from.+START_TS=$(systemctl show cloudflared -p ExecMainStartTimestamp --value 2>/dev/null)+if [[ -z $START_TS || $START_TS == 'n/a' ]]; then+ log 'cloudflared not running according to systemd — exit 0'+ exit 0+fi++NO_INGRESS_RECENT=$(journalctl -u cloudflared --since "$START_TS" --no-pager 2>/dev/null \+ | grep -c 'No ingress rules were defined' || true)++if [[ $NO_INGRESS_RECENT -gt 0 ]]; then+ log "empty-ingress state in current run (hostnames=$HOSTNAME_COUNT, started=$START_TS) — restarting cloudflared"+ systemctl restart cloudflared+ exit 0+fi++log "ok: hostnames=$HOSTNAME_COUNT, current run is clean"+exit 0diff --git a/claude-ops/scripts/systemd/cloudflared-watchdog.timer b/claude-ops/scripts/systemd/cloudflared-watchdog.timernew file mode 100644index 00000000..da80a90c--- /dev/null+++ b/claude-ops/scripts/systemd/cloudflared-watchdog.timer@@ -0,0 +1,11 @@+[Unit]+Description=Run cloudflared-watchdog every 5 minutes++[Timer]+OnBootSec=2min+OnUnitActiveSec=5min+Unit=cloudflared-watchdog.service+AccuracySec=15s++[Install]+WantedBy=timers.targetdiff --git a/claude-ops/scripts/systemd/cloudflared.service b/claude-ops/scripts/systemd/cloudflared.servicenew file mode 100644index 00000000..2daac85e--- /dev/null+++ b/claude-ops/scripts/systemd/cloudflared.service@@ -0,0 +1,16 @@+[Unit]+Description=cloudflared+After=network-online.target+Wants=network-online.target+StartLimitIntervalSec=300+StartLimitBurst=5++[Service]+TimeoutStartSec=30+Type=notify+ExecStart=/usr/local/bin/cloudflared --no-autoupdate tunnel run --token ${CLOUDFLARED_TUNNEL_TOKEN}+Restart=always+RestartSec=10s++[Install]+WantedBy=multi-user.targetdiff --git a/claude-ops/scripts/systemd/install-systemd-units.sh b/claude-ops/scripts/systemd/install-systemd-units.shindex b127c99f..be8488c3 100644--- a/claude-ops/scripts/systemd/install-systemd-units.sh+++ b/claude-ops/scripts/systemd/install-systemd-units.sh@@ -43,6 +43,9 @@ UNITS=(pocket-whatsapp-bridge.timerwhatsapp-baileys.servicepocket-ops-ui.service+ cloudflared.service+ cloudflared-watchdog.service+ cloudflared-watchdog.timer)for unit in "${UNITS[@]}"; do@@ -70,6 +73,23 @@ for svc in whatsapp-baileys.service pocket-ops-ui.service; doecho " enabled $svc"done+# Cloudflared tunnel (optional — only enable when /etc/cloudflared-watchdog.env+# exists and the unit ExecStart has been populated with a tunnel token).+if [[ -f /etc/cloudflared-watchdog.env ]] \+ && grep -q 'tunnel run --token ' /etc/systemd/system/cloudflared.service \+ && ! grep -q '${CLOUDFLARED_TUNNEL_TOKEN}' /etc/systemd/system/cloudflared.service; then+ systemctl enable cloudflared.service+ echo " enabled cloudflared.service"+ systemctl enable cloudflared-watchdog.timer+ echo " enabled cloudflared-watchdog.timer"+else+ echo " SKIP cloudflared — /etc/cloudflared-watchdog.env missing OR token placeholder still present"+ echo " edit /etc/systemd/system/cloudflared.service to replace \${CLOUDFLARED_TUNNEL_TOKEN}"+ echo " with the real tunnel token from your Cloudflare Zero Trust dashboard,"+ echo " then write /etc/cloudflared-watchdog.env (chmod 600) with:"+ echo " CLOUDFLARE_API_TOKEN=<token with Account:Tunnel:Read scope>"+fi+# Timers (oneshot services triggered by timers)for timer in \pocket-watcher.timer \