#!/bin/bash
# Firewall setup for Makenotwork production server (ufw).
#
# Rules:
#   - Allow all traffic on Tailscale interface (tailscale0)
#   - Allow SSH (port 22) from anywhere (needed for git SSH access)
#   - Allow HTTP/HTTPS (80/443) from anywhere (custom domains need direct access)
#   - Drop everything else
#
# HTTP/HTTPS is open to all because custom domains connect directly (on-demand
# Let's Encrypt TLS, not behind Cloudflare) and arrive from arbitrary client IPs,
# so 443 cannot be CIDR-locked to Cloudflare without breaking that paid feature.
# The IP-spoofing risk this would otherwise create is closed in Caddy instead:
#   - makenot.work subdomains: Caddy mTLS (Authenticated Origin Pulls) rejects any
#     request without a valid Cloudflare client cert before it reaches the app.
#   - custom domains (:443 block): Caddy overwrites CF-Connecting-IP with the real
#     TCP peer and strips X-Forwarded-For, so a client cannot forge the source IP
#     the app uses for rate-limiting, lockouts, and audit logs.

set -e

if [ "$(id -u)" -ne 0 ]; then
    echo "Error: Run as root"
    exit 1
fi

# Reset to defaults
ufw --force reset

# Default policies
ufw default deny incoming
ufw default allow outgoing

# Tailscale — unrestricted
ufw allow in on tailscale0

# SSH — open from anywhere (git clone over SSH)
ufw allow 22/tcp

# HTTP/HTTPS — open to all (custom domains need direct access)
# makenot.work is still protected by Caddy mTLS (Authenticated Origin Pulls)
ufw allow 80/tcp
ufw allow 443/tcp

# Enable
ufw --force enable
ufw status verbose

echo ""
echo "Firewall configured. SSH, HTTP, HTTPS open. makenot.work protected by Caddy mTLS."
