Files
exposedgays/deploy/finish-after-cf-zone.py

179 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""
Run AFTER adding exposedgays.com in Cloudflare dashboard.
Completes: tunnel public hostnames (if token allows), CF DNS CNAMEs, GoDaddy NS delegation.
"""
import json
import re
import sys
import time
import urllib.error
import urllib.request
import paramiko
PASS = "Bbt9115xty9176!"
DOMAIN = "exposedgays.com"
ACCOUNT = "2599c23bbb1255dbb73e8d34b4115fda"
TUNNEL_ID = "03079a26-f14c-4622-b463-ba54a24f7472"
TUNNEL_CNAME = f"{TUNNEL_ID}.cfargotunnel.com"
CF = "https://api.cloudflare.com/client/v4"
GD = "https://api.godaddy.com/v1"
GODADDY_KEY = "2wYVpc3VT4_Gi9AsNqzJ6BtSfNz6nLDuo"
GODADDY_SECRET = "NvC3qexGAU7Rd5QExUTH6z"
EG_RULES = [
{"hostname": "exposedgays.com", "service": "https://localhost:443", "originRequest": {"noTLSVerify": True}},
{"hostname": "www.exposedgays.com", "service": "https://localhost:443", "originRequest": {"noTLSVerify": True}},
]
def load_cf_token():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("10.10.0.1", username="admin", password=PASS, timeout=15)
_, o, e = c.exec_command("cat /usr/local/etc/wan-dns-failover.env", timeout=30)
o.channel.recv_exit_status()
text = (o.read() + e.read()).decode()
c.close()
return re.search(r"CLOUDFLARE_API_TOKEN=([^\s\"']+)", text).group(1)
def cf(tok, path, method="GET", body=None):
req = urllib.request.Request(
CF + path,
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=60) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read().decode())
def gd(path, method="GET", body=None):
req = urllib.request.Request(
GD + path,
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={
"Authorization": f"sso-key {GODADDY_KEY}:{GODADDY_SECRET}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(req, timeout=45) as r:
raw = r.read().decode()
return r.status, json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
raw = e.read().decode()
try:
return e.code, json.loads(raw)
except Exception:
return e.code, {"raw": raw[:500]}
def upsert_tunnel_cnames(tok, zid):
records = cf(tok, f"/zones/{zid}/dns_records?per_page=100")[1].get("result", [])
for name in [DOMAIN, f"www.{DOMAIN}"]:
body = {"type": "CNAME", "name": name, "content": TUNNEL_CNAME, "ttl": 1, "proxied": True}
existing = next((r for r in records if r["name"] == name and r["type"] in ("A", "CNAME", "AAAA")), None)
if existing:
code, res = cf(tok, f"/zones/{zid}/dns_records/{existing['id']}", "PATCH", body)
action = "PATCH"
else:
code, res = cf(tok, f"/zones/{zid}/dns_records", "POST", body)
action = "POST"
print(f" {action} {name}: HTTP {code} success={res.get('success')} errors={res.get('errors')}")
def try_tunnel_ingress(tok):
code, body = cf(tok, f"/accounts/{ACCOUNT}/cfd_tunnel/{TUNNEL_ID}/configurations")
if code != 200 or not body.get("result"):
print("Tunnel config API blocked — add Public Hostnames manually in Zero Trust dashboard:")
print(" exposedgays.com -> https://localhost:443 (No TLS Verify)")
print(" www.exposedgays.com -> https://localhost:443 (No TLS Verify)")
return False
ingress = body["result"].get("config", {}).get("ingress", [])
hostnames = {i.get("hostname") for i in ingress if i.get("hostname")}
changed = False
for rule in EG_RULES:
if rule["hostname"] not in hostnames:
catch = next((i for i, x in enumerate(ingress) if not x.get("hostname")), len(ingress))
ingress.insert(catch, rule)
changed = True
print(" added tunnel ingress", rule["hostname"])
if not changed:
print(" tunnel ingress already has exposedgays hostnames")
return True
put_code, put = cf(
tok,
f"/accounts/{ACCOUNT}/cfd_tunnel/{TUNNEL_ID}/configurations",
"PUT",
{"config": {"ingress": ingress, "warp-routing": {"enabled": False}}},
)
print(f" PUT tunnel config HTTP {put_code} success={put.get('success')} errors={put.get('errors')}")
if put.get("success"):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("10.10.0.10", username="localadministrator", password=PASS, timeout=30)
c.exec_command(f"echo '{PASS}' | sudo -S systemctl restart cloudflared")
c.close()
time.sleep(8)
return put.get("success", False)
def main():
tok = load_cf_token()
code, zres = cf(tok, f"/zones?name={DOMAIN}")
if not zres.get("result"):
print(f"BLOCKED: {DOMAIN} not in Cloudflare yet.")
print("Add it at https://dash.cloudflare.com → Add a Site → exposedgays.com (Free plan)")
print("Then re-run: python exposedgays/deploy/finish-after-cf-zone.py")
return 1
zone = zres["result"][0]
zid = zone["id"]
nameservers = zone.get("name_servers", [])
print(f"Found zone {zid} status={zone['status']}")
print(f"Nameservers: {nameservers}")
print("\n=== Tunnel ingress ===")
try_tunnel_ingress(tok)
print("\n=== Cloudflare DNS (proxied CNAME -> tunnel) ===")
upsert_tunnel_cnames(tok, zid)
if nameservers:
print("\n=== GoDaddy NS -> Cloudflare ===")
gcode, gres = gd(f"/domains/{DOMAIN}", "PATCH", {"nameServers": nameservers})
print(f"PATCH HTTP {gcode}: {gres}")
_, after = gd(f"/domains/{DOMAIN}")
print("GoDaddy NS now:", after.get("nameServers"))
print("\nWaiting 20s...")
time.sleep(20)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("10.10.0.10", username="localadministrator", password=PASS, timeout=30)
for cmd in [
f"dig @1.1.1.1 {DOMAIN} A +short",
f"dig @1.1.1.1 www.{DOMAIN} A +short",
f"curl -sSI --max-time 20 https://{DOMAIN}/ | head -10",
f"curl -sSL --max-time 20 https://{DOMAIN}/ | head -c 200",
]:
print(f"\n$ {cmd}")
_, o, e = c.exec_command(cmd, timeout=30)
o.channel.recv_exit_status()
print((o.read() + e.read()).decode(errors="replace"))
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())