fix htmx refactor route mismatches and remaining TODO items

- wireguard: POST /peers with JSON encoding (was /add-peer)
- rules: delete by rule_id in URL path (was JSON body); pass rule objects with id from server; add hx-disable to initial render
- nat: port forward delete uses URL path params to match blueprint
- nat: masquerade toggle uses native hx-post/hx-vals (was inline fetch)
- app.js renderers updated to use URL path deletes for rules and forwards
- remove TODO.md
This commit is contained in:
2026-05-17 01:15:52 +00:00
parent 0e7090a2cb
commit 37039351be
26 changed files with 1737 additions and 848 deletions
+22
View File
@@ -4,6 +4,8 @@ webui/api/certs.py - ACME certificate management API blueprint.
Exposed at /api/certs/* and delegates to lib.acme.
"""
import logging
from flask import Blueprint, jsonify, request
from lib.acme import (
@@ -15,6 +17,7 @@ from lib.acme import (
set_email,
)
logger = logging.getLogger(__name__)
bp = Blueprint("certs", __name__)
@@ -41,6 +44,7 @@ def list_certs_bp():
try:
return _ok(list_certs())
except RuntimeError as exc:
logger.error("Failed to list certificates: %s", exc)
return _error(str(exc), 500)
@@ -52,6 +56,7 @@ def cert_details(domain):
except ValueError as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to get cert info for '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -68,11 +73,17 @@ def issue_bp():
return _error("'domain' is required", 400)
webroot = body.get("webroot")
try:
logger.info("Certificate issuance requested for '%s' via API", domain)
result = issue(domain, webroot=webroot)
if result.get("success"):
logger.info("Certificate issued for '%s'", domain)
return _ok(None)
logger.error(
"Certificate issuance failed for '%s': %s", domain, result.get("error")
)
return _error(result.get("error", "Unknown error"), 500)
except RuntimeError as exc:
logger.error("Exception issuing cert for '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -84,11 +95,17 @@ def issue_bp():
@bp.route("/<domain>/renew", methods=["POST"])
def renew_bp(domain):
try:
logger.info("Certificate renewal requested for '%s' via API", domain)
result = renew(domain)
if result.get("success"):
logger.info("Certificate renewed for '%s'", domain)
return _ok(None)
logger.error(
"Certificate renewal failed for '%s': %s", domain, result.get("error")
)
return _error(result.get("error", "Unknown error"), 500)
except RuntimeError as exc:
logger.error("Exception renewing cert for '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -104,11 +121,14 @@ def remove_bp(domain):
except ValueError as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to verify cert '%s': %s", domain, exc)
return _error(str(exc), 500)
try:
remove(domain)
logger.info("Certificate removed for '%s' via API", domain)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to remove cert '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -125,6 +145,8 @@ def set_email_bp():
return _error("'email' is required", 400)
try:
set_email(email)
logger.info("ACME email set via API: %s", email)
return _ok({"email": email})
except RuntimeError as exc:
logger.error("Failed to set ACME email: %s", exc)
return _error(str(exc), 500)
+85 -11
View File
@@ -4,6 +4,8 @@ webui/api/dhcp.py - DHCP/DNS (dnsmasq) management API blueprint.
Exposed at /api/dhcp/* and delegates all operations to lib.dnsmasq.
"""
import logging
from flask import Blueprint, jsonify, request
from lib.dnsmasq import (
@@ -12,11 +14,14 @@ from lib.dnsmasq import (
apply_config,
get_config,
get_lease_table,
remove_dhcp_range,
remove_dns_record,
remove_static_lease,
save_config,
set_dhcp_range,
)
logger = logging.getLogger(__name__)
bp = Blueprint("dhcp", __name__)
@@ -53,6 +58,7 @@ def get_config_bp():
try:
return _ok(get_config())
except RuntimeError as exc:
logger.error("Failed to read DHCP config: %s", exc)
return _error(str(exc), 500)
@@ -65,6 +71,7 @@ def post_config():
save_config(body)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to save DHCP config: %s", exc)
return _error(str(exc), 500)
@@ -79,6 +86,7 @@ def patch_config():
save_config(merged)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to patch DHCP config: %s", exc)
return _error(str(exc), 500)
@@ -86,13 +94,76 @@ def patch_config():
def apply_bp():
try:
apply_config()
logger.info("dnsmasq config applied via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to apply dnsmasq config: %s", exc)
return _error(str(exc), 500)
# ---------------------------------------------------------------------------
# Leases
# Status
# ---------------------------------------------------------------------------
@bp.route("/status", methods=["GET"])
def status_bp():
try:
from lib.dnsmasq import get_status as dnsmasq_status
return _ok(dnsmasq_status())
except RuntimeError as exc:
logger.error("Failed to get DHCP status: %s", exc)
return _error(str(exc), 500)
# ---------------------------------------------------------------------------
# DHCP ranges
# ---------------------------------------------------------------------------
@bp.route("/ranges", methods=["POST"])
def add_range_bp():
body = request.get_json(silent=True) or {}
iface = body.get("interface", "").strip() or None
start = body.get("start", "").strip()
end = body.get("end", "").strip()
lease_time = body.get("lease_time", "12h")
if not start or not end:
return _error("'start' and 'end' are required", 400)
try:
set_dhcp_range(
iface if iface else "",
start,
end,
lease_time=lease_time,
)
logger.info("DHCP range added via API: %s-%s", start, end)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to add DHCP range: %s", exc)
return _error(str(exc), 500)
@bp.route("/ranges", methods=["DELETE"])
def remove_range_bp():
body = request.get_json(silent=True) or {}
iface = body.get("interface", "").strip() or ""
start = body.get("start", "").strip()
end = body.get("end", "").strip()
if not start or not end:
return _error("'start' and 'end' are required", 400)
try:
remove_dhcp_range(iface, start, end)
logger.info("DHCP range removed via API: %s-%s", start, end)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to remove DHCP range: %s", exc)
return _error(str(exc), 500)
# ---------------------------------------------------------------------------
# Static leases
# ---------------------------------------------------------------------------
@@ -101,6 +172,7 @@ def leases_bp():
try:
return _ok(get_lease_table())
except RuntimeError as exc:
logger.error("Failed to read lease table: %s", exc)
return _error(str(exc), 500)
@@ -119,16 +191,15 @@ def add_static_lease_bp():
return _error("'mac' and 'ip' are required", 400)
try:
add_static_lease(mac, ip, hostname)
logger.info("Static lease added via API: %s -> %s", mac, ip)
return _ok({"mac": mac, "ip": ip, "hostname": hostname})
except RuntimeError as exc:
logger.error("Failed to add static lease: %s", exc)
return _error(str(exc), 500)
@bp.route("/static-lease", methods=["DELETE"])
def remove_static_lease_bp():
mac = request.args.get("mac", "").strip()
if not mac:
return _error("Query parameter 'mac' is required", 400)
@bp.route("/static-lease/<mac>", methods=["DELETE"])
def remove_static_lease_bp(mac):
current = get_config()
found = any(
lease["mac"].lower() == mac.lower()
@@ -138,8 +209,10 @@ def remove_static_lease_bp():
return _error(f"No static lease found for MAC '{mac}'", 404)
try:
remove_static_lease(mac)
logger.info("Static lease removed via API: %s", mac)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to remove static lease: %s", exc)
return _error(str(exc), 500)
@@ -158,16 +231,15 @@ def add_dns_record_bp():
return _error("'name' and 'address' are required", 400)
try:
add_dns_record(name, address, hostname)
logger.info("DNS record added via API: %s -> %s", name, address)
return _ok({"name": name, "address": address, "hostname": hostname})
except RuntimeError as exc:
logger.error("Failed to add DNS record: %s", exc)
return _error(str(exc), 500)
@bp.route("/dns-record", methods=["DELETE"])
def remove_dns_record_bp():
name = request.args.get("name", "").strip()
if not name:
return _error("Query parameter 'name' is required", 400)
@bp.route("/dns-record/<name>", methods=["DELETE"])
def remove_dns_record_bp(name):
current = get_config()
found = any(
r["name"] == name for r in current.get("dns", {}).get("custom_records", [])
@@ -176,6 +248,8 @@ def remove_dns_record_bp():
return _error(f"No DNS record found for '{name}'", 404)
try:
remove_dns_record(name)
logger.info("DNS record removed via API: %s", name)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to remove DNS record: %s", exc)
return _error(str(exc), 500)
+77 -52
View File
@@ -4,6 +4,8 @@ webui/api/firewall.py - Firewall (firewalld) management API blueprint.
Exposed at /api/firewall/* and delegates all mutations to lib.firewall.
"""
import logging
from flask import Blueprint, jsonify, request
from lib.firewall import (
@@ -20,13 +22,14 @@ from lib.firewall import (
get_rich_rules,
get_services,
get_zone_info,
remove_forward_port,
remove_rich_rule,
remove_forward_port_by_id,
remove_rich_rule_by_id,
set_masquerade,
set_zone_interfaces,
set_zone_services,
)
logger = logging.getLogger(__name__)
bp = Blueprint("firewall", __name__)
@@ -53,6 +56,7 @@ def config_get_bp():
try:
return _ok(config_get())
except Exception as exc:
logger.error("Failed to read firewall config: %s", exc)
return _error(str(exc), 500)
@@ -66,6 +70,7 @@ def config_set_bp():
try:
config_set(body)
pending_info = config_pending()
logger.info("Firewall config saved (%d zones)", len(body["zones"]))
return _ok(
{
"config_saved": True,
@@ -75,6 +80,7 @@ def config_set_bp():
}
)
except Exception as exc:
logger.error("Failed to save firewall config: %s", exc)
return _error(str(exc), 500)
@@ -84,8 +90,10 @@ def config_apply_bp():
from lib.firewall import config_apply as _config_apply
result = _config_apply()
logger.info("Firewall config applied: %s", result.get("applied_zones", []))
return _ok(result)
except Exception as exc:
logger.error("Failed to apply firewall config: %s", exc)
return _error(str(exc), 500)
@@ -94,6 +102,7 @@ def config_pending_bp():
try:
return _ok(config_pending())
except Exception as exc:
logger.error("Failed to check pending config: %s", exc)
return _error(str(exc), 500)
@@ -107,16 +116,9 @@ def list_zones():
try:
active = get_active_zones()
available = get_available_zones()
return jsonify(
{
"ok": True,
"data": {
"active": active,
"available": available,
},
}
)
return _ok({"active": active, "available": available})
except RuntimeError as exc:
logger.error("Failed to list zones: %s", exc)
return _error(str(exc), 500)
@@ -126,8 +128,9 @@ def zone_details(name):
if name not in get_available_zones():
return _error(f"Zone '{name}' does not exist", 404)
info = get_zone_info(name)
return jsonify({"ok": True, "data": info})
return _ok(info)
except RuntimeError as exc:
logger.error("Failed to get zone '%s' info: %s", name, exc)
return _error(str(exc), 500)
@@ -142,8 +145,10 @@ def create_zone_bp():
if zone_name in get_available_zones():
return _error(f"Zone '{zone_name}' already exists", 400)
create_zone(zone_name, target)
logger.info("Zone '%s' created via API", zone_name)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to create zone '%s': %s", zone_name, exc)
return _error(str(exc), 500)
@@ -154,8 +159,10 @@ def delete_zone_bp(name):
if name not in available:
return _error(f"Zone '{name}' does not exist", 404)
delete_zone(name)
logger.info("Zone '%s' deleted via API", name)
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to delete zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -172,8 +179,10 @@ def set_zone_interfaces_bp(name):
return _error("'interfaces' must be a list", 400)
try:
set_zone_interfaces(name, interfaces)
logger.info("Zone '%s' interfaces updated: %s", name, interfaces)
return _ok({"zone": name, "interfaces": interfaces})
except RuntimeError as exc:
logger.error("Failed to set interfaces for zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -192,6 +201,7 @@ def set_zone_services_bp(name):
set_zone_services(name, services)
return _ok({"zone": name, "services": services})
except RuntimeError as exc:
logger.error("Failed to set services for zone '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -205,6 +215,7 @@ def list_services():
try:
return _ok(get_services())
except RuntimeError as exc:
logger.error("Failed to list services: %s", exc)
return _error(str(exc), 500)
@@ -213,6 +224,7 @@ def list_interfaces():
try:
return _ok(get_interfaces())
except RuntimeError as exc:
logger.error("Failed to list interfaces: %s", exc)
return _error(str(exc), 500)
@@ -229,23 +241,11 @@ def add_rich_rule_bp():
if not zone or not rule:
return _error("Both 'zone' and 'rule' are required", 400)
try:
add_rich_rule(zone, rule)
return _ok({"zone": zone, "rule": rule})
except RuntimeError as exc:
return _error(str(exc), 500)
@bp.route("/rich-rules", methods=["DELETE"])
def remove_rich_rule_bp():
body = request.get_json(silent=True) or {}
zone = body.get("zone", "").strip()
rule = body.get("rule", "").strip()
if not zone or not rule:
return _error("Both 'zone' and 'rule' are required", 400)
try:
remove_rich_rule(zone, rule)
return _ok({"zone": zone, "rule": rule})
entry = add_rich_rule(zone, rule)
logger.info("Rich rule added to zone '%s': %s", zone, rule[:80])
return _ok({"zone": zone, "id": entry["id"], "rule": rule})
except RuntimeError as exc:
logger.error("Failed to add rich rule to zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -253,8 +253,35 @@ def remove_rich_rule_bp():
def list_rich_rules(zone):
try:
rules = get_rich_rules(zone)
return _ok(rules)
from lib.firewall import config_get as firewall_config_get
cfg = firewall_config_get()
cfg_entries = cfg.get("zones", {}).get(zone, {}).get("rich_rules", [])
result = []
for rule_str in rules:
matched = next(
(e for e in cfg_entries if e.get("rule") == rule_str), None
)
if matched:
result.append({"id": matched["id"], "rule": rule_str})
else:
result.append({"rule": rule_str})
return _ok(result)
except RuntimeError as exc:
logger.error("Failed to get rich rules for zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@bp.route("/rich-rules/<zone>/<rule_id>", methods=["DELETE"])
def remove_rich_rule_bp(zone, rule_id):
try:
remove_rich_rule_by_id(zone, rule_id)
logger.info("Rich rule '%s' removed from zone '%s'", rule_id, zone)
return _ok({"zone": zone, "id": rule_id})
except ValueError as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove rich rule from zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -272,8 +299,14 @@ def set_masquerade_bp():
return _error("'zone' and 'enable' (bool) are required", 400)
try:
set_masquerade(zone, bool(enable))
logger.info(
"Masquerade %s on zone '%s' via API",
"enabled" if enable else "disabled",
zone,
)
return _ok({"zone": zone, "masquerade": bool(enable)})
except RuntimeError as exc:
logger.error("Failed to set masquerade on zone '%s': %s", zone, exc)
return _error(str(exc), 500)
@@ -293,38 +326,30 @@ def add_forward_port_bp():
if not zone or port is None or not proto:
return _error("'zone', 'port', and 'proto' are required", 400)
try:
add_forward_port(
entry = add_forward_port(
zone,
int(port),
proto,
toaddr=str(toaddr) if toaddr else None,
toport=int(toport) if toport else None,
)
return _ok({"zone": zone, "port": int(port), "proto": proto})
return _ok(
{"zone": zone, "id": entry["id"], "port": int(port), "proto": proto}
)
except (ValueError, RuntimeError) as exc:
code = 400 if isinstance(exc, ValueError) else 500
logger.error("Failed to add forward port: %s", exc)
return _error(str(exc), code)
@bp.route("/forward-port", methods=["DELETE"])
def remove_forward_port_bp():
body = request.get_json(silent=True) or {}
zone = body.get("zone", "").strip()
port = body.get("port")
proto = body.get("proto", "").strip()
toaddr = body.get("toaddr")
toport = body.get("toport")
if not zone or port is None or not proto:
return _error("'zone', 'port', and 'proto' are required", 400)
@bp.route("/forward-port/<zone>/<int:port>/<proto>", methods=["DELETE"])
def remove_forward_port_bp(zone, port, proto):
try:
remove_forward_port(
zone,
int(port),
proto,
toaddr=str(toaddr) if toaddr else None,
toport=int(toport) if toport else None,
)
return _ok({"zone": zone, "port": int(port), "proto": proto})
except (ValueError, RuntimeError) as exc:
code = 400 if isinstance(exc, ValueError) else 500
return _error(str(exc), code)
remove_forward_port_by_id(zone, port, proto)
logger.info("Forward port %s/%s removed from zone '%s'", port, proto, zone)
return _ok({"zone": zone, "port": port, "proto": proto})
except ValueError as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to remove forward port from zone '%s': %s", zone, exc)
return _error(str(exc), 500)
+99
View File
@@ -0,0 +1,99 @@
"""
webui/api/logs.py - Log viewing API blueprint.
Serves log content to the /logs page via HTMX endpoints:
/api/logs/journal — systemd journal for vacuum-wall
/api/logs/nginx/access — nginx access log tail
/api/logs/nginx/error — nginx error log tail
/api/logs/dnsmasq — systemd journal for dnsmasq
/api/logs/app — Vacuum Wall application log file
"""
import logging
import subprocess
from pathlib import Path
from flask import Blueprint, render_template_string
logger = logging.getLogger(__name__)
bp = Blueprint("logs", __name__)
PROJECT_DIR = Path(__file__).resolve().parent.parent
APP_LOG_FILE = PROJECT_DIR / "data" / "logs" / "vacuum-wall.log"
_MAX_LINES = 200
def _tail_file(path: str, n: int = _MAX_LINES) -> str:
"""Return the last *n* lines of a file."""
try:
with open(path) as f:
lines = f.readlines()
return "".join(lines[-n:])
except FileNotFoundError:
return "(log file not found)\n"
except PermissionError:
return "(permission denied)\n"
def _sudo_journalctl(unit: str, n: int = _MAX_LINES) -> str:
"""Run ``sudo journalctl -u <unit> --no-pager -n <n>`` and return output."""
try:
result = subprocess.run(
["sudo", "journalctl", "-u", unit, "--no-pager", "-n", str(n)],
capture_output=True,
text=True,
timeout=10,
)
output = result.stdout.strip()
return output if output else f"(no journal entries for {unit})\n"
except (subprocess.TimeoutExpired, FileNotFoundError) as exc:
return f"(error reading journal: {exc})\n"
_LOG_LINE_TEMPLATE = """\
{% for line in lines %}
<div class="log-line{% if 'ERROR' in line %} log-error{% elif 'WARN' in line %} log-warn{% endif %}">{{ line | e }}</div>
{% endfor %}"""
def _render_log_lines(text: str) -> str:
"""Render raw log text into HTML fragment with line-by-line coloring."""
lines = text.rstrip("\n").split("\n") if text.strip() else []
return render_template_string(_LOG_LINE_TEMPLATE, lines=lines)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@bp.route("/journal")
def journal():
text = _sudo_journalctl("vacuum-wall")
return _render_log_lines(text)
@bp.route("/nginx/access")
def nginx_access():
text = _tail_file("/var/log/nginx/access.log")
return _render_log_lines(text)
@bp.route("/nginx/error")
def nginx_error():
text = _tail_file("/var/log/nginx/error.log")
return _render_log_lines(text)
@bp.route("/dnsmasq")
def dnsmasq():
text = _sudo_journalctl("dnsmasq")
return _render_log_lines(text)
@bp.route("/app")
def app_log():
text = _tail_file(str(APP_LOG_FILE))
return _render_log_lines(text)
+17 -1
View File
@@ -4,6 +4,8 @@ webui/api/proxy.py - Nginx proxy domain management API blueprint.
Exposed at /api/proxy/* and delegates to lib.nginx.
"""
import logging
from flask import Blueprint, jsonify, request
from lib.nginx import (
@@ -17,6 +19,7 @@ from lib.nginx import (
update_domain,
)
logger = logging.getLogger(__name__)
bp = Blueprint("proxy", __name__)
@@ -43,6 +46,7 @@ def list_domains():
try:
return _ok(get_domains())
except RuntimeError as exc:
logger.error("Failed to list proxy domains: %s", exc)
return _error(str(exc), 500)
@@ -65,8 +69,10 @@ def add_domain_bp():
add_domain(
domain, backend_host, int(backend_port), backend_proto, cert, extra_headers
)
logger.info("Proxy domain added via API: %s", domain)
return _ok({"domain": domain})
except (ValueError, RuntimeError) as exc:
logger.error("Failed to add proxy domain '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -79,6 +85,7 @@ def domain_details(domain):
return _error(f"Domain '{domain}' not found", 404)
return _ok({"domain": domain, **entry})
except RuntimeError as exc:
logger.error("Failed to get domain details: %s", exc)
return _error(str(exc), 500)
@@ -89,10 +96,12 @@ def update_domain_bp(domain):
return _error("Request body must be a JSON object with fields to update", 400)
try:
update_domain(domain, **body)
logger.info("Proxy domain '%s' updated via API", domain)
return _ok({"domain": domain})
except KeyError as exc:
return _error(str(exc), 404)
except RuntimeError as exc:
logger.error("Failed to update domain '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -103,8 +112,10 @@ def remove_domain_bp(domain):
if domain not in cfg.get("domains", {}):
return _error(f"Domain '{domain}' not found", 404)
remove_domain(domain)
logger.info("Proxy domain removed via API: %s", domain)
return _ok({"domain": domain})
except RuntimeError as exc:
logger.error("Failed to remove domain '%s': %s", domain, exc)
return _error(str(exc), 500)
@@ -117,8 +128,10 @@ def remove_domain_bp(domain):
def apply_bp():
try:
apply()
logger.info("nginx config applied via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to apply nginx config: %s", exc)
return _error(str(exc), 500)
@@ -128,8 +141,9 @@ def test_bp():
valid, output = test_config()
if valid:
return _ok({"valid": True, "output": output})
return jsonify({"ok": False, "error": output, "valid": False}), 400
return _error(output, 400)
except RuntimeError as exc:
logger.error("nginx config test failed: %s", exc)
return _error(str(exc), 500)
@@ -150,7 +164,9 @@ def management_bp():
auth_pass = body.get("auth_pass")
try:
set_management_proxy(domain, flask_host, int(flask_port), auth_user, auth_pass)
logger.info("Management proxy configured via API: %s", domain)
return _ok(None)
except (ValueError, RuntimeError) as exc:
code = 400 if isinstance(exc, ValueError) else 500
logger.error("Failed to set management proxy: %s", exc)
return _error(str(exc), code)
+34 -7
View File
@@ -4,6 +4,8 @@ webui/api/wireguard.py - WireGuard tunnel management API blueprint.
Exposed at /api/wireguard/* and delegates to lib.wireguard.
"""
import logging
from flask import Blueprint, jsonify, request
from lib.wireguard import (
@@ -20,6 +22,7 @@ from lib.wireguard import (
status,
)
logger = logging.getLogger(__name__)
bp = Blueprint("wireguard", __name__)
@@ -51,6 +54,7 @@ def get_config_bp():
safe["interface"].pop("private_key", None)
return _ok(safe)
except RuntimeError as exc:
logger.error("Failed to read WireGuard config: %s", exc)
return _error(str(exc), 500)
@@ -67,6 +71,7 @@ def post_config():
safe["interface"].pop("private_key", None)
return _ok(safe)
except RuntimeError as exc:
logger.error("Failed to save WireGuard config: %s", exc)
return _error(str(exc), 500)
@@ -79,8 +84,21 @@ def post_config():
def apply_bp():
try:
apply()
logger.info("WireGuard tunnel applied via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to apply WireGuard config: %s", exc)
return _error(str(exc), 500)
@bp.route("/up", methods=["POST"])
def up_bp():
try:
apply()
logger.info("WireGuard tunnel started via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to start WireGuard tunnel: %s", exc)
return _error(str(exc), 500)
@@ -88,8 +106,10 @@ def apply_bp():
def down_bp():
try:
down()
logger.info("WireGuard tunnel brought down via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to bring down WireGuard tunnel: %s", exc)
return _error(str(exc), 500)
@@ -103,6 +123,7 @@ def status_bp():
try:
return _ok(status())
except RuntimeError as exc:
logger.error("Failed to get WireGuard status: %s", exc)
return _error(str(exc), 500)
@@ -115,8 +136,10 @@ def status_bp():
def initialize_bp():
try:
initialize()
logger.info("WireGuard initialized via API")
return _ok(None)
except RuntimeError as exc:
logger.error("Failed to initialize WireGuard: %s", exc)
return _error(str(exc), 500)
@@ -125,7 +148,7 @@ def initialize_bp():
# ---------------------------------------------------------------------------
@bp.route("/add-peer", methods=["POST"])
@bp.route("/peers", methods=["POST"])
def add_peer_bp():
body = request.get_json(silent=True) or {}
name = body.get("name", "").strip()
@@ -141,23 +164,24 @@ def add_peer_bp():
)
safe = dict(peer)
safe.pop("private_key", None)
logger.info("WireGuard peer '%s' added via API", name)
return _ok(safe)
except RuntimeError as exc:
logger.error("Failed to add peer '%s': %s", name, exc)
return _error(str(exc), 500)
@bp.route("/remove-peer", methods=["DELETE"])
def remove_peer_bp():
name = request.args.get("name", "").strip()
if not name:
return _error("Query parameter 'name' is required", 400)
@bp.route("/peers/<name>", methods=["DELETE"])
def remove_peer_bp(name):
try:
cfg = get_config()
if name not in cfg.get("peers", {}):
return _error(f"Peer '{name}' not found", 404)
remove_peer(name)
logger.info("WireGuard peer '%s' removed via API", name)
return _ok({"name": name})
except RuntimeError as exc:
logger.error("Failed to remove peer '%s': %s", name, exc)
return _error(str(exc), 500)
@@ -166,6 +190,7 @@ def peers_bp():
try:
return _ok(get_peers())
except RuntimeError as exc:
logger.error("Failed to list WireGuard peers: %s", exc)
return _error(str(exc), 500)
@@ -174,6 +199,7 @@ def peer_status_bp():
try:
return _ok(get_peer_status())
except RuntimeError as exc:
logger.error("Failed to get WireGuard peer status: %s", exc)
return _error(str(exc), 500)
@@ -196,12 +222,13 @@ def generate_client_bp():
server_pubkey = cfg["interface"].get("public_key", "")
if not server_endpoint:
_ = cfg["interface"].get("listen_port", 51820)
# Can't auto-derive public IP; ask user to provide it
return _error(
"Field 'server_endpoint' is required (e.g., '203.0.113.1:51820')", 400
)
conf_text = generate_client_conf(name, server_endpoint, server_pubkey)
logger.info("Client config generated for peer '%s' via API", name)
return _ok({"config": conf_text})
except (KeyError, ValueError, RuntimeError) as exc:
code = 404 if isinstance(exc, (KeyError, ValueError)) else 500
logger.error("Failed to generate client config for '%s': %s", name, exc)
return _error(str(exc), code)
+70 -4
View File
@@ -7,9 +7,12 @@ and enforces basic authentication before proxying to this port.
import logging
import os
import sys
import time
from datetime import datetime
from pathlib import Path
from flask import Flask, render_template
from flask import Flask, render_template, request
from lib.acme import get_email, list_certs
from lib.dnsmasq import get_config as dnsmasq_config
@@ -22,6 +25,7 @@ from lib.firewall import (
get_interfaces,
get_zone_info,
)
from lib.logging import setup_logging
from lib.nginx import get_config as nginx_config
from lib.nginx import get_domains
from lib.wireguard import get_config as wg_config
@@ -29,9 +33,28 @@ from lib.wireguard import status as wg_status
from webui.api.certs import bp as certs_bp
from webui.api.dhcp import bp as dhcp_bp
from webui.api.firewall import bp as firewall_bp
from webui.api.logs import bp as logs_bp
from webui.api.proxy import bp as proxy_bp
from webui.api.wireguard import bp as wireguard_bp
# ---------------------------------------------------------------------------
# Logging — must be first so subsequent modules inherit the config
# ---------------------------------------------------------------------------
PROJECT_DIR = Path(__file__).resolve().parent.parent
setup_logging()
logger = logging.getLogger(__name__)
logger.info(
"Python %s.%s.%s",
sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro,
)
logger.info("Project directory: %s", PROJECT_DIR)
logger.info("Process ID: %d", os.getpid())
# ---------------------------------------------------------------------------
# App factory
# ---------------------------------------------------------------------------
@@ -44,6 +67,44 @@ app.register_blueprint(dhcp_bp, url_prefix="/api/dhcp")
app.register_blueprint(proxy_bp, url_prefix="/api/proxy")
app.register_blueprint(certs_bp, url_prefix="/api/certs")
app.register_blueprint(wireguard_bp, url_prefix="/api/wireguard")
app.register_blueprint(logs_bp, url_prefix="/api/logs")
BLUEPRINTS = [
("firewall", firewall_bp),
("dhcp", dhcp_bp),
("proxy", proxy_bp),
("certs", certs_bp),
("wireguard", wireguard_bp),
("logs", logs_bp),
]
for name, _ in BLUEPRINTS:
logger.info("Registered blueprint '%s' at /api/%s", name, name)
# ---------------------------------------------------------------------------
# Request logging
# ---------------------------------------------------------------------------
@app.before_request
def _log_request_start():
request._start_time = time.monotonic()
@app.after_request
def _log_request_finish(response):
elapsed_ms = (
time.monotonic() - getattr(request, "_start_time", time.monotonic())
) * 1000
logger.info(
"%s %s -> %d (%.1f ms)",
request.method,
request.path,
response.status_code,
elapsed_ms,
)
return response
# ---------------------------------------------------------------------------
@@ -117,8 +178,6 @@ def json_pretty_filter(value):
# Page routes
# ---------------------------------------------------------------------------
logger = logging.getLogger(__name__)
def _safely(fn, default=None):
"""Call *fn* and return *default* on any exception."""
@@ -204,7 +263,13 @@ def zones_page():
@app.route("/rules")
def rules_page():
zones = list(_safely(get_active_zones, {}).keys())
return render_template("rules.html", zones=zones)
raw = _safely(config_get, {})
rules = {}
for zname, zcfg in raw.get("zones", {}).items():
rr = zcfg.get("rich_rules", [])
if rr:
rules[zname] = rr
return render_template("rules.html", zones=zones, rules=rules or None)
@app.route("/nat")
@@ -252,4 +317,5 @@ def logs_page():
if __name__ == "__main__":
logger.info("Starting Flask on 127.0.0.1:9090")
app.run(host="127.0.0.1", port=9090)
+289 -113
View File
@@ -1,137 +1,86 @@
// Toast notification system
function showToast(message, type = "info") {
const container = document.querySelector(".toast") || createToastContainer();
const toast = document.createElement("div");
toast.className = `toast-message toast-${type}`;
// Toast notifications
const showToast = (message, type, duration = 4000) => {
const container = document.getElementById('toast-container');
if (!container) return;
const toast = document.createElement('div');
toast.className = 'toast toast-' + type;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(() => toast.classList.add('show'));
setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translateX(40px)";
toast.style.transition = "all 0.3s ease";
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 5000);
}
}, duration);
};
function createToastContainer() {
const el = document.createElement("div");
el.className = "toast";
document.body.appendChild(el);
return el;
}
const showSuccessToast = (msg) => showToast(msg, 'success');
const showErrorToast = (msg) => showToast(msg, 'error');
// Modal helpers
function openModal(id) {
const modal = document.getElementById(id);
if (modal) modal.classList.add("show");
}
const openModal = (id) => {
const el = document.getElementById(id);
if (el) el.classList.add('active');
};
function closeModal(id) {
const modal = document.getElementById(id);
if (modal) modal.classList.remove("show");
}
const closeModal = (id) => {
const el = document.getElementById(id);
if (el) el.classList.remove('active');
};
// Confirm dialog
function confirmAction(message, onConfirm) {
const existing = document.getElementById("confirm-modal");
if (existing) existing.remove();
// Tab switching
const switchTab = (tabName) => {
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.tab').forEach(el => el.classList.remove('active'));
document.getElementById('tab-' + tabName).classList.add('active');
const clickedTab = document.querySelector('.tab[data-tab="' + tabName + '"]');
if (clickedTab) clickedTab.classList.add('active');
};
const modal = document.createElement("div");
modal.id = "confirm-modal";
modal.className = "modal";
modal.innerHTML = `
<div class="modal-content">
<p class="mb-2">${message}</p>
<div style="display:flex; gap:0.75rem; justify-content:flex-end;">
<button class="btn btn-outline" id="confirm-cancel">Cancel</button>
<button class="btn btn-danger" id="confirm-ok">Confirm</button>
</div>
</div>`;
document.body.appendChild(modal);
openModal("confirm-modal");
document.getElementById("confirm-cancel").onclick = () => closeModal("confirm-modal");
modal.addEventListener("click", (e) => {
if (e.target === modal) closeModal("confirm-modal");
});
}
function setupConfirmCallback(callback) {
document.getElementById("confirm-ok")?.addEventListener("click", () => {
closeModal("confirm-modal");
callback();
});
}
// Auto-refresh with HTMX
function startAutoRefresh(endpoint, target, interval) {
const el = document.createElement("div");
el.setAttribute("hx-get", endpoint);
el.setAttribute("hx-target", `#${target}`);
el.setAttribute("hx-swap", "innerHTML");
el.setAttribute("hx-trigger", `every ${interval}s`);
el.setAttribute("hx-swap-oob", "true");
document.body.appendChild(el);
}
// Time formatting
function formatTime(seconds) {
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
return `${Math.floor(seconds / 86400)}d ${Math.floor((seconds % 86400) / 3600)}h`;
}
// Bytes formatting
function formatBytes(bytes) {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0)} ${units[i]}`;
}
// Form helpers
function resetForm(formId) {
const form = document.getElementById(formId);
if (form) form.reset();
}
function fillForm(formId, data) {
const form = document.getElementById(formId);
if (!form) return;
for (const [key, value] of Object.entries(data)) {
const input = form.querySelector(`[name="${key}"]`);
if (input) input.value = value;
}
}
// Refresh a container from a JSON GET endpoint using a renderer callback
const refreshTable = (url, container, renderer) => {
fetch(url)
.then(r => r.json())
.then(data => {
const json = data.ok ? data.data : data;
container.innerHTML = renderer(json);
htmx.process(container);
})
.catch(() => {});
};
// HTMX event handlers
document.body.addEventListener("htmx:afterSwap", (evt) => {
const toastHeader = evt.detail.xhr?.getResponseHeader("X-Toast");
document.body.addEventListener('htmx:afterSwap', (evt) => {
const toastHeader = evt.detail.xhr?.getResponseHeader('X-Toast');
if (toastHeader) {
const parts = toastHeader.split(":");
const msg = parts.slice(1).join(":").trim();
showToast(msg, parts[0]?.trim() || "info");
const parts = toastHeader.split(':');
const msg = parts.slice(1).join(':').trim();
showToast(msg, parts[0]?.trim() || 'info');
}
});
document.body.addEventListener("htmx:responseError", (evt) => {
document.body.addEventListener('htmx:responseError', (evt) => {
const status = evt.detail.xhr?.status || 0;
showToast(`Request failed (${status})`, "error");
const json = evt.detail.xhr?.response;
let msg = 'Request failed (' + status + ')';
try {
const parsed = JSON.parse(json);
if (parsed.error) msg = parsed.error;
} catch (e) {}
showToast(msg, 'error');
});
document.body.addEventListener("htmx:beforeRequest", (evt) => {
const target = evt.target;
const btn = target.closest(".btn");
document.body.addEventListener('htmx:beforeRequest', (evt) => {
const btn = evt.target.closest('.btn');
if (btn) {
btn.dataset.originalText = btn.textContent;
btn.disabled = true;
btn.textContent = "Loading...";
btn.textContent = 'Loading...';
}
});
document.body.addEventListener("htmx:afterRequest", (evt) => {
const target = evt.target;
const btn = target.closest(".btn");
document.body.addEventListener('htmx:afterRequest', (evt) => {
const btn = evt.target.closest('.btn');
if (btn && btn.dataset.originalText !== undefined) {
btn.disabled = false;
btn.textContent = btn.dataset.originalText;
@@ -139,9 +88,236 @@ document.body.addEventListener("htmx:afterRequest", (evt) => {
}
});
// Close on escape
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
document.querySelectorAll(".modal.show").forEach((m) => m.classList.remove("show"));
// Keyboard: Escape closes all modals
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
document.querySelectorAll('.modal-overlay.active').forEach(el => el.classList.remove('active'));
}
});
// -------- Renderer helpers for htmx-driven DOM updates --------
const renderZones = (data) => {
const active = Array.isArray(data) ? data : (data.active || []);
if (!active.length) return '<div class="card"><div class="text-muted text-sm">No zones configured. Create a zone to get started.</div></div>';
return active.map(zone =>
'<div class="card" style="position:relative;">' +
'<div style="display:flex;justify-content:space-between;align-items:flex-start;">' +
'<div><h3 style="font-size:16px;color:var(--accent);">' + escHtml(zone.name) + '</h3>' +
'<div class="text-muted text-sm" style="margin-bottom:10px;">' + (zone.target ? 'Target: ' + escHtml(zone.target) : '') + '</div></div></div>' +
'<div class="text-sm mb-4"><div class="text-muted" style="margin-bottom:4px;">Interfaces</div>' +
(zone.interfaces && zone.interfaces.length ? zone.interfaces.map(i => '<span class="badge badge-info">' + escHtml(i) + '</span>').join('') : '<span class="text-muted">None</span>') +
'</div><div class="text-sm mb-4"><div class="text-muted" style="margin-bottom:4px;">Services</div>' +
(zone.services && zone.services.length ? zone.services.map(s => '<span class="badge badge-success">' + escHtml(s) + '</span>').join('') : '<span class="text-muted">None</span>') +
'</div><div style="display:flex;justify-content:flex-end;gap:6px;margin-top:12px;">' +
'<form hx-delete="/api/firewall/zones/' + escAttr(zone.name) + '" hx-swap="none" hx-confirm="Delete zone ' + escHtml(zone.name) + '? This will affect traffic to its interfaces." hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/firewall/zones\', document.getElementById(\'zone-grid\'), renderZones); showSuccessToast(\'Zone deleted\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button></form></div></div>'
).join('');
};
const renderRules = (data) => {
let html = '';
let zoneRules = {};
const cfgZones = data && data.zones ? data.zones : null;
if (cfgZones) {
Object.keys(cfgZones).forEach(zname => {
const rr = cfgZones[zname].rich_rules || [];
if (rr.length) zoneRules[zname] = rr;
});
} else {
zoneRules = data || {};
}
Object.keys(zoneRules).forEach(zone => {
let entries = zoneRules[zone];
if (!Array.isArray(entries)) entries = [];
html += '<div class="card"><h3>Zone: <span style="color:var(--accent);">' + escHtml(zone || '(default)') + '</span></h3>';
if (entries.length) {
html += '<table><thead><tr><th>#</th><th>Rule</th><th style="width:80px;">Action</th></tr></thead><tbody>';
entries.forEach((entry, i) => {
let ruleId, ruleText;
if (typeof entry === 'object' && entry.rule) {
ruleId = entry.id;
ruleText = entry.rule;
} else {
ruleId = null;
ruleText = String(entry);
}
html += '<tr><td class="text-muted">' + (i + 1) + '</td>' +
'<td style="font-family:monospace;font-size:12px;word-break:break-all;" hx-disable>' + escHtml(ruleText) + '</td>' +
'<td><form hx-delete="/api/firewall/rich-rules/' + escAttr(zone) + (ruleId ? '/' + encodeURIComponent(ruleId) : '') + '"' +
(ruleId ? '' : ' hx-encoding="json" hx-vals=\'{"rule": ' + JSON.stringify(ruleText) + ' }\'') +
' hx-swap="none" hx-confirm="Remove rule ' + escHtml(ruleText.substring(0, 40)) + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/firewall/config\', document.getElementById(\'rules-container\'), renderRules); showSuccessToast(\'Rule removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></td></tr>';
});
html += '</tbody></table>';
} else {
html += '<div class="text-muted text-sm">No rich rules configured for this zone.</div>';
}
html += '</div>';
});
return html || '<div class="card"><div class="text-muted text-sm">No rules loaded.</div></div>';
};
const renderForwards = (forwards) => {
if (!forwards.length) return '<tr><td colspan="6" class="text-muted text-sm">No port forwarding rules configured</td></tr>';
return forwards.map(fwd => {
const proto = fwd['proxy-protocol'] || fwd.proto;
return '<tr><td><strong>' + escHtml(fwd.zone) + '</strong></td>' +
'<td><span class="badge badge-info">' + escHtml(proto) + '</span></td>' +
'<td>' + fwd.port + '</td><td>' + escHtml(fwd['to-addr'] || fwd.toaddr) + '</td>' +
'<td>' + (fwd['to-port'] || fwd.toport || '-') + '</td>' +
'<td><form hx-delete="/api/firewall/forward-port/' + encodeURIComponent(fwd.zone) + '/' + fwd.port + '/' + encodeURIComponent(proto) + '" hx-swap="none" hx-confirm="Remove forward rule ' + fwd.port + '/' + proto + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/firewall/config\', document.getElementById(\'forward-rows\'), renderForwardsFromConfig); showSuccessToast(\'Rule removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></td></tr>';
}).join('');
};
const renderForwardsFromConfig = (data) => {
const zones = data.zones || {};
const forwards = [];
Object.keys(zones).forEach(name => {
zones[name].forward_ports = zones[name].forward_ports || [];
zones[name].forward_ports.forEach(fwd => {
forwards.push({
zone: name,
'proxy-protocol': fwd['proxy-protocol'] || fwd.proto,
port: fwd.port,
'to-addr': fwd['to-addr'] || fwd.toaddr,
'to-port': fwd['to-port'] || fwd.toport
});
});
});
return renderForwards(forwards);
};
const renderRanges = (ranges) => {
if (!ranges.length) return '<tr><td colspan="5" class="text-muted text-sm">No DHCP ranges configured</td></tr>';
return ranges.map(rng =>
'<tr><td>' + escHtml(rng.interface || '(global)') + '</td>' +
'<td>' + escHtml(rng.start) + '</td><td>' + escHtml(rng.end) + '</td>' +
'<td>' + escHtml(rng.lease_time || '1h') + '</td>' +
'<td><form hx-delete="/api/dhcp/ranges" hx-encoding="json" hx-vals=\'{"interface": "' + escAttr(rng.interface || '') + '", "start": "' + escAttr(rng.start) + '", "end": "' + escAttr(rng.end) + '"}\' hx-swap="none" hx-confirm="Remove DHCP range ' + escHtml(rng.start) + ' - ' + escHtml(rng.end) + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/dhcp/config\', document.getElementById(\'range-rows\'), renderRanges); showSuccessToast(\'Range removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></td></tr>'
).join('');
};
const renderStaticLeases = (leases) => {
if (!leases.length) return '<tr><td colspan="4" class="text-muted text-sm">No static leases configured</td></tr>';
return leases.map(lease =>
'<tr><td>' + escHtml(lease.mac) + '</td><td>' + escHtml(lease.ip) + '</td>' +
'<td>' + escHtml(lease.hostname || '-') + '</td>' +
'<td><form hx-delete="/api/dhcp/static-lease/' + encodeURIComponent(lease.mac) + '" hx-swap="none" hx-confirm="Remove lease ' + escHtml(lease.mac) + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/dhcp/config\', document.getElementById(\'lease-rows\'), renderStaticLeases); showSuccessToast(\'Lease removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></td></tr>'
).join('');
};
const renderDnsRecords = (records) => {
if (!records.length) return '<tr><td colspan="3" class="text-muted text-sm">No custom DNS records</td></tr>';
return records.map(rec =>
'<tr><td><strong>' + escHtml(rec.name || 'unnamed') + '</strong></td>' +
'<td class="text-sm">' + escHtml(rec.address || '-') + '</td>' +
'<td><form hx-delete="/api/dhcp/dns-record/' + encodeURIComponent(rec.name) + '" hx-swap="none" hx-confirm="Remove DNS record ' + escHtml(rec.name || 'unnamed') + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/dhcp/config\', document.getElementById(\'dns-rows\'), renderDnsRecords); showSuccessToast(\'Record removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></td></tr>'
).join('');
};
const renderDomains = (domains) => {
if (!domains.length) return '<tr><td colspan="6" class="text-muted text-sm">No proxy domains configured. Add a domain to start terminating SSL.</td></tr>';
return domains.map(d => {
let certHtml = '<span class="badge badge-danger">' + (d.cert_status || 'No cert') + '</span>';
if (d.cert_status === 'expired') certHtml = '<span class="badge badge-danger">Expired</span>';
else if (d.cert_status === 'valid' || d.cert_status === 'active') certHtml = '<span class="badge badge-success">Valid</span>';
else if (typeof d.days_remaining === 'number') {
if (d.days_remaining <= 0) certHtml = '<span class="badge badge-danger">Expired</span>';
else if (d.days_remaining <= 30) certHtml = '<span class="badge badge-warning">' + d.days_remaining + 'd</span>';
else certHtml = '<span class="badge badge-success">Valid</span>';
}
return '<tr><td><strong>' + escHtml(d.domain) + '</strong></td>' +
'<td>' + escHtml(d.backend_host || '-') + '</td>' +
'<td>' + (d.backend_port || '-') + '</td>' +
'<td><span class="badge badge-info">' + escHtml(d.protocol || 'http') + '</span></td>' +
'<td>' + certHtml + '</td>' +
'<td><div class="flex gap-2">' +
'<button class="btn btn-sm btn-outline" onclick="openEditDomainModal(\'' + escAttr(d.domain) + '\', ' + JSON.stringify(d) + ')">Edit</button>' +
'<form hx-delete="/api/proxy/domains/' + escAttr(d.domain) + '" hx-swap="none" hx-confirm="Remove proxy for ' + escHtml(d.domain) + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/proxy/domains\', document.getElementById(\'domain-rows\'), renderDomains); showSuccessToast(\'Domain removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button></form></div></td></tr>';
}).join('');
};
const renderPeers = (peers) => {
if (!peers.length) return '<tr><td colspan="7" class="text-muted text-sm">No peers configured. Add a peer above.</td></tr>';
return peers.map(peer =>
'<tr><td><span class="status-dot ' + (peer.latest_handshake ? 'status-up' : 'status-down') + '"></span>' +
'<strong>' + escHtml(peer.name || 'unnamed') + '</strong></td>' +
'<td style="font-family:monospace;font-size:11px;">' + escHtml((peer.public_key || 'N/A').substring(0, 20)) + '...</td>' +
'<td class="text-sm">' + escHtml(peer.allowed_ips || '-') + '</td>' +
'<td class="text-sm">' + escHtml(peer.endpoint || '-') + '</td>' +
'<td class="text-sm">' + escHtml(peer.latest_handshake || 'Never') + '</td>' +
'<td class="text-sm"><div>Recv: ' + escHtml(peer.transfer_recv || '0') + '</div><div>Sent: ' + escHtml(peer.transfer_sent || '0') + '</div></td>' +
'<td><div class="flex gap-2">' +
'<button class="btn btn-sm btn-outline" onclick="downloadPeerConfig(\'' + escAttr(peer.name) + '\')">Config</button>' +
'<form hx-delete="/api/wireguard/peers/' + encodeURIComponent(peer.name) + '" hx-swap="none" hx-confirm="Remove peer ' + escHtml(peer.name) + '?" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/wireguard/peers\', document.getElementById(\'peer-rows\'), renderPeers); showSuccessToast(\'Peer removed\'); }">' +
'<button type="submit" class="btn btn-sm btn-danger">Remove</button></form></div></td></tr>'
).join('');
};
const renderCerts = (certs) => {
if (!certs.length) return '<tr><td colspan="5" class="text-muted text-sm">No certificates found. Issue a certificate to get started.</td></tr>';
return certs.map(cert => {
const days = cert.days_remaining;
let badgeHtml;
if (cert.expired || (days !== undefined && days <= 0)) {
badgeHtml = '<span class="badge badge-danger">Expired' + (days !== undefined ? ' (' + days + 'd ago)' : '') + '</span>';
} else if (days !== undefined && days <= 30) {
badgeHtml = '<span class="badge badge-warning">' + days + ' days</span>';
} else {
badgeHtml = '<span class="badge badge-success">' + (days !== undefined ? days + ' days' : 'N/A') + '</span>';
}
return '<tr><td><strong>' + escHtml(cert.domain || 'unknown') + '</strong></td>' +
'<td class="text-sm">' + escHtml(cert.issuer || '-') + '</td>' +
'<td>' + escHtml(cert.expiry || 'N/A') + '</td>' +
'<td>' + badgeHtml + '</td>' +
'<td><form hx-post="/api/certs/' + escAttr(cert.domain) + '/renew" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable(\'/api/certs/list\', document.getElementById(\'cert-rows\'), renderCerts); showSuccessToast(\'Renewal started for ' + escHtml(cert.domain) + '\'); }">' +
'<button type="submit" class="btn btn-sm btn-outline">Renew</button></form></td></tr>';
}).join('');
};
const renderInterfaces = (interfaces) => {
if (!interfaces.length) return '<tr><td colspan="5" class="text-muted text-sm">No interfaces found</td></tr>';
return interfaces.map(iface => {
const zoneOptions = (iface.zones || []).map(z =>
'<option value="' + escAttr(z) + '"' + (z === iface.zone ? ' selected' : '') + '>' + escHtml(z) + '</option>'
).join('');
return '<tr><td><strong>' + escHtml(iface.name) + '</strong></td>' +
'<td class="text-muted">' + escHtml(iface.mac || 'N/A') + '</td>' +
'<td>' + (iface.ips && iface.ips.length ? iface.ips.map(ip => escHtml(ip)).join(', ') : 'N/A') + '</td>' +
'<td><span class="status-dot ' + (iface.state === 'up' ? 'status-up' : 'status-down') + '"></span>' +
(iface.state === 'up' ? 'Up' : 'Down') + '</td>' +
'<td><select hx-on::change="assignZone(\'' + escAttr(iface.name) + '\', this)">' + zoneOptions + '</select></td></tr>';
}).join('');
};
const assignZone = (ifaceName, selectEl) => {
fetch('/api/firewall/zones/' + encodeURIComponent(selectEl.value) + '/interfaces', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ interfaces: [ifaceName] })
})
.then(r => {
if (r.ok) {
showSuccessToast(ifaceName + ' assigned to ' + selectEl.value);
refreshTable('/api/firewall/interfaces', document.getElementById('interface-list'), renderInterfaces);
}
else return r.json().then(j => { throw new Error(j.error || r.statusText); });
})
.catch(e => { showErrorToast(e.message); });
};
const escHtml = (s) => {
const div = document.createElement('div');
div.appendChild(document.createTextNode(s));
return div.innerHTML;
};
const escAttr = (s) => {
return String(s).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#39;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};
+1 -52
View File
@@ -592,57 +592,6 @@
<div class="toast-container" id="toast-container"></div>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
<script>
function showToast(message, type, duration) {
duration = duration || 4000;
var container = document.getElementById('toast-container');
if (!container) return;
var toast = document.createElement('div');
toast.className = 'toast toast-' + type;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(function() { toast.classList.add('show'); });
setTimeout(function() {
toast.classList.remove('show');
setTimeout(function() { toast.remove(); }, 300);
}, duration);
}
function openModal(id) {
var el = document.getElementById(id);
if (el) el.classList.add('active');
}
function closeModal(id) {
var el = document.getElementById(id);
if (el) el.classList.remove('active');
}
function switchTab(tabName) {
document.querySelectorAll('.tab-content').forEach(function(el) { el.classList.remove('active'); });
document.querySelectorAll('.tab').forEach(function(el) { el.classList.remove('active'); });
document.getElementById('tab-' + tabName).classList.add('active');
var clickedTab = document.querySelector('.tab[data-tab="' + tabName + '"]');
if (clickedTab) clickedTab.classList.add('active');
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.htmx-on-success').forEach(function(el) {
var msg = el.getAttribute('data-success') || 'Operation successful';
var type = el.getAttribute('data-type') || 'success';
el.addEventListener('htmx:afterRequest', function(evt) {
if (evt.detail && evt.detail.successful) {
showToast(msg, type);
}
});
});
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
document.querySelectorAll('.modal-overlay.active').forEach(function(el) { el.classList.remove('active'); });
}
});
</script>
<script src="/static/app.js"></script>
</body>
</html>
+3 -3
View File
@@ -21,7 +21,7 @@
<th style="width:120px;">Actions</th>
</tr>
</thead>
<tbody>
<tbody id="cert-rows">
{% for cert in (certs or []) %}
<tr>
<td><strong>{{ cert.get('domain', 'unknown') }}</strong></td>
@@ -38,7 +38,7 @@
{% endif %}
</td>
<td>
<form hx-post="/api/certs/renew/{{ cert.get('domain', '') }}" hx-swap="none" class="htmx-on-success" data-success="Renewal started for {{ cert.domain }}" onsuccess="setTimeout(function(){ location.reload(); }, 2000);">
<form hx-post="/api/certs/{{ cert.get('domain', '') }}/renew" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/certs/list', document.getElementById('cert-rows'), renderCerts); showSuccessToast('Renewal started for {{ cert.domain }}'); }">
<button type="submit" class="btn btn-sm btn-outline">Renew</button>
</form>
</td>
@@ -57,7 +57,7 @@
<div class="modal-overlay" id="issue-cert-modal" onclick="if(event.target===this) closeModal('issue-cert-modal')">
<div class="modal">
<h2>Issue New Certificate</h2>
<form hx-post="/api/certs/issue" hx-swap="none" class="htmx-on-success" data-success="Certificate issuance started" onsuccess="setTimeout(function(){closeModal('issue-cert-modal'); location.reload();}, 500);">
<form hx-post="/api/certs/issue" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ closeModal('issue-cert-modal'); refreshTable('/api/certs/list', document.getElementById('cert-rows'), renderCerts); showSuccessToast('Certificate issuance started'); }">
<div class="form-group">
<label for="cert-domain">Domain</label>
<input type="text" id="cert-domain" name="domain" placeholder="example.com" required>
+20 -20
View File
@@ -13,7 +13,7 @@
<div class="section-title">DHCP Ranges</div>
<div class="card mb-4">
<form hx-post="/api/dhcp/ranges" hx-swap="none" class="htmx-on-success" data-success="DHCP range added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/dhcp/ranges" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('range-rows'), renderRanges); showSuccessToast('DHCP range added'); }">
<div class="inline-form">
<div class="form-group">
<label for="range-interface">Interface</label>
@@ -50,7 +50,7 @@
<th style="width:80px;">Action</th>
</tr>
</thead>
<tbody>
<tbody id="range-rows">
{% for rng in ((config or {}).get('dhcp_ranges', []) or []) %}
<tr>
<td>{{ rng.get('interface', '(global)') }}</td>
@@ -58,8 +58,8 @@
<td>{{ rng.get('end', '') }}</td>
<td>{{ rng.get('lease_time', '1h') }}</td>
<td>
<form hx-delete="/api/dhcp/ranges/{{ rng.get('start', '') }}/{{ rng.get('end', '') }}" hx-swap="none" class="htmx-on-success" data-success="Range removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove this range?')">Remove</button>
<form hx-delete="/api/dhcp/ranges" hx-encoding="json" hx-vals='{"interface": "{{ rng.get("interface", "") }}", "start": "{{ rng.get("start", "") }}", "end": "{{ rng.get("end", "") }}" }' hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('range-rows'), renderRanges); showSuccessToast('Range removed'); }">
<button type="submit" class="btn btn-sm btn-danger" hx-confirm="Remove DHCP range {{ rng.get('start', '') }} - {{ rng.get('end', '') }}?">Remove</button>
</form>
</td>
</tr>
@@ -78,7 +78,7 @@
<div class="section-title">Static Leases</div>
<div class="card mb-4">
<form hx-post="/api/dhcp/leases/static" hx-swap="none" class="htmx-on-success" data-success="Static lease added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/dhcp/static-lease" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('lease-rows'), renderStaticLeases); showSuccessToast('Static lease added'); }">
<div class="inline-form">
<div class="form-group">
<label for="lease-mac">MAC Address</label>
@@ -105,15 +105,15 @@
<th style="width:80px;">Action</th>
</tr>
</thead>
<tbody>
<tbody id="lease-rows">
{% for lease in ((config or {}).get('static_leases', []) or []) %}
<tr>
<td>{{ lease.get('mac', '') }}</td>
<td>{{ lease.get('ip', '') }}</td>
<td>{{ lease.get('hostname', '-') }}</td>
<td>
<form hx-delete="/api/dhcp/leases/static/{{ lease.get('mac', '') }}" hx-swap="none" class="htmx-on-success" data-success="Lease removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove this lease?')">Remove</button>
<form hx-delete="/api/dhcp/static-lease/{{ lease.get('mac', '') }}" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('lease-rows'), renderStaticLeases); showSuccessToast('Lease removed'); }">
<button type="submit" class="btn btn-sm btn-danger" hx-confirm="Remove lease {{ lease.get('mac', '') }}?">Remove</button>
</form>
</td>
</tr>
@@ -132,15 +132,15 @@
<div class="section-title">Custom DNS Records</div>
<div class="card mb-4">
<form hx-post="/api/dhcp/dns/records" hx-swap="none" class="htmx-on-success" data-success="DNS record added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/dhcp/dns-record" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('dns-rows'), renderDnsRecords); showSuccessToast('DNS record added'); }">
<div class="inline-form">
<div class="form-group">
<label for="dns-ip">IP Address</label>
<input type="text" id="dns-ip" name="ip" placeholder="192.168.1.10" required style="width:160px;">
<input type="text" id="dns-ip" name="address" placeholder="192.168.1.10" required style="width:160px;">
</div>
<div class="form-group">
<label for="dns-hostname">Hostname / Domain</label>
<input type="text" id="dns-hostname" name="hostname" placeholder="host.local" required style="width:200px;">
<input type="text" id="dns-hostname" name="name" placeholder="host.local" required style="width:200px;">
</div>
<button type="submit" class="btn btn-primary">Add Record</button>
</div>
@@ -149,19 +149,19 @@
<table>
<thead>
<tr>
<th>IP</th>
<th>Hostname</th>
<th>Name</th>
<th>Address</th>
<th style="width:80px;">Action</th>
</tr>
</thead>
<tbody>
<tbody id="dns-rows">
{% for rec in ((config or {}).get('dns_records', []) or []) %}
<tr>
<td>{{ rec.get('ip', '') }}</td>
<td>{{ rec.get('hostname', '') }}</td>
<td>
<form hx-delete="/api/dhcp/dns/records/{{ rec.get('ip', '') }}/{{ rec.get('hostname', '') }}" hx-swap="none" class="htmx-on-success" data-success="Record removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove this record?')">Remove</button>
<td><strong>{{ rec.get('name', 'unnamed') }}</strong></td>
<td class="text-sm">{{ rec.get('address', '-') }}</td>
<td>
<form hx-delete="/api/dhcp/dns-record/{{ rec.get('name', '') }}" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/dhcp/config', document.getElementById('dns-rows'), renderDnsRecords); showSuccessToast('Record removed'); }">
<button type="submit" class="btn btn-sm btn-danger" hx-confirm="Remove DNS record {{ rec.get('name', '') }}?">Remove</button>
</form>
</td>
</tr>
@@ -208,7 +208,7 @@
</tbody>
</table>
<div class="mt-2 text-right">
<button class="btn btn-sm btn-outline" hx-post="/api/dhcp/reload" hx-swap="none" class="htmx-on-success" data-success="Dnsmasq configuration reloaded">Apply &amp; Restart Dnsmasq</button>
<button class="btn btn-sm btn-outline" hx-post="/api/dhcp/apply" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ showSuccessToast('Dnsmasq configuration reloaded'); }">Apply &amp; Restart Dnsmasq</button>
</div>
</div>
{% endblock %}
+2 -29
View File
@@ -18,10 +18,9 @@
<th>IP Address</th>
<th>State</th>
<th>Zone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tbody id="interface-list">
{% for iface in (interfaces or []) %}
<tr>
<td><strong>{{ iface.get('name', 'unknown') }}</strong></td>
@@ -39,12 +38,7 @@
<td>
{% if zones %}
<select
class="htmx-on-success"
data-success="Zone updated for {{ iface.name }}"
hx-post="/api/firewall/zones/__ZONE__/interfaces/{{ iface.name }}"
hx-swap="none"
hx-select-oob="#toast-container *"
onchange="assignInterfaceToZone(this, '{{ iface.name }}', '{{ iface.get('zone', '') }}')"
hx-on::change="fetch('/api/firewall/zones/'+encodeURIComponent(this.value)+'/interfaces',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({interfaces:['{{ iface.name }}']})}).then(r=>{if(!r.ok)throw r}).then(r=>r.ok?(showSuccessToast('{{ iface.name }} assigned to '+this.value),refreshTable('/api/firewall/interfaces',document.getElementById('interface-list'),renderInterfaces)):r.json().then(j=>{throw new Error(j.error||r.statusText)})).catch(e=>{showErrorToast(e.message);this.selectedIndex=0})"
>
{% for zone in zones %}
<option value="{{ zone.get('name', '') }}" {% if zone.get('name') == iface.get('zone') %}selected{% endif %}>{{ zone.get('name', '') }}</option>
@@ -54,9 +48,6 @@
<span class="text-muted">No zones configured</span>
{% endif %}
</td>
<td>
<button class="btn btn-sm btn-outline" onclick="assignInterfaceToZone(this.previousElementSibling, '{{ iface.name }}', null)">Apply</button>
</td>
</tr>
{% endfor %}
{% if not (interfaces or []) %}
@@ -67,22 +58,4 @@
</tbody>
</table>
</div>
<script>
function assignInterfaceToZone(selectEl, ifaceName, currentZone) {
var zoneName = selectEl.value;
var url = '/api/firewall/zones/' + encodeURIComponent(zoneName) + '/interfaces/' + encodeURIComponent(ifaceName);
fetch(url, { method: 'POST' })
.then(function(res) {
if (res.ok) {
showToast('Assigned ' + ifaceName + ' to zone ' + zoneName, 'success');
} else {
return res.text().then(function(txt) { throw new Error(txt); });
}
})
.catch(function(err) {
showToast('Failed to assign: ' + err.message, 'error');
});
}
</script>
{% endblock %}
+69 -36
View File
@@ -13,9 +13,7 @@
<input type="checkbox" id="auto-refresh-toggle" onchange="toggleAutoRefresh()">
<span class="slider"></span>
</label>
<span class="htmx-indicator text-sm" style="color:var(--accent);">
<span id="refresh-indicator" style="display:none;">Refreshing...</span>
</span>
<span class="htmx-indicator text-sm" style="color:var(--accent);">Refreshing...</span>
</div>
</div>
@@ -24,15 +22,16 @@
<button class="tab" data-tab="nginx-access" onclick="switchTab('nginx-access')">Nginx Access</button>
<button class="tab" data-tab="nginx-error" onclick="switchTab('nginx-error')">Nginx Error</button>
<button class="tab" data-tab="dnsmasq" onclick="switchTab('dnsmasq')">Dnsmasq</button>
<button class="tab" data-tab="app" onclick="switchTab('app')">App</button>
</div>
<div id="tab-journal" class="tab-content active">
<div class="card" style="padding:0;overflow:hidden;">
<div class="log-viewer" id="log-journal"
hx-get="/api/logs/journal"
hx-trigger="every {{ (refresh_interval | default(15)) }}s"
hx-swap="innerHTML"
hx-indicator="#refresh-indicator">
hx-get="/api/logs/journal"
hx-trigger="none"
hx-swap="innerHTML"
hx-indicator=".page-header .htmx-indicator">
Loading journal entries...
</div>
</div>
@@ -41,10 +40,10 @@
<div id="tab-nginx-access" class="tab-content">
<div class="card" style="padding:0;overflow:hidden;">
<div class="log-viewer" id="log-nginx-access"
hx-get="/api/logs/nginx/access"
hx-trigger="every {{ (refresh_interval | default(15)) }}s"
hx-swap="innerHTML"
hx-indicator="#refresh-indicator">
hx-get="/api/logs/nginx/access"
hx-trigger="none"
hx-swap="innerHTML"
hx-indicator=".page-header .htmx-indicator">
Loading Nginx access log...
</div>
</div>
@@ -53,10 +52,10 @@
<div id="tab-nginx-error" class="tab-content">
<div class="card" style="padding:0;overflow:hidden;">
<div class="log-viewer" id="log-nginx-error"
hx-get="/api/logs/nginx/error"
hx-trigger="every {{ (refresh_interval | default(15)) }}s"
hx-swap="innerHTML"
hx-indicator="#refresh-indicator">
hx-get="/api/logs/nginx/error"
hx-trigger="none"
hx-swap="innerHTML"
hx-indicator=".page-header .htmx-indicator">
Loading Nginx error log...
</div>
</div>
@@ -65,42 +64,76 @@
<div id="tab-dnsmasq" class="tab-content">
<div class="card" style="padding:0;overflow:hidden;">
<div class="log-viewer" id="log-dnsmasq"
hx-get="/api/logs/dnsmasq"
hx-trigger="every {{ (refresh_interval | default(15)) }}s"
hx-swap="innerHTML"
hx-indicator="#refresh-indicator">
hx-get="/api/logs/dnsmasq"
hx-trigger="none"
hx-swap="innerHTML"
hx-indicator=".page-header .htmx-indicator">
Loading dnsmasq log...
</div>
</div>
</div>
<div id="tab-app" class="tab-content">
<div class="card" style="padding:0;overflow:hidden;">
<div class="log-viewer" id="log-app"
hx-get="/api/logs/app"
hx-trigger="none"
hx-swap="innerHTML"
hx-indicator=".page-header .htmx-indicator">
Loading app log...
</div>
</div>
</div>
<script>
var autoRefreshTimer = null;
var refreshInterval = {{ (refresh_interval | default(15)) }};
var currentTab = 'journal';
function setActivePolling() {
document.querySelectorAll('.log-viewer').forEach(function(el) {
htmx.abort(el);
el.setAttribute('hx-trigger', 'none');
});
var activeEl = document.getElementById('log-' + currentTab);
if (activeEl) {
activeEl.setAttribute('hx-trigger', 'every ' + refreshInterval + 's');
}
}
function loadActiveTab() {
var activeEl = document.getElementById('log-' + currentTab);
if (activeEl) {
htmx.ajax('GET', activeEl);
}
}
var origSwitchTab = switchTab;
switchTab = function(tabName) {
currentTab = tabName;
if (typeof origSwitchTab === 'function') {
origSwitchTab(tabName);
}
if (document.getElementById('auto-refresh-toggle').checked) {
setActivePolling();
}
loadActiveTab();
};
function toggleAutoRefresh() {
var toggle = document.getElementById('auto-refresh-toggle');
var indicators = document.querySelectorAll('.log-viewer');
if (toggle.checked) {
indicators.forEach(function(el) {
el.setAttribute('hx-trigger', 'every 15s');
hx.trigger(el, 'htmx:refresh');
});
setActivePolling();
loadActiveTab();
} else {
indicators.forEach(function(el) {
el.setAttribute('hx-trigger', 'never');
document.querySelectorAll('.log-viewer').forEach(function(el) {
htmx.abort(el);
el.setAttribute('hx-trigger', 'none');
});
}
}
document.addEventListener('htmx:beforeRequest', function(evt) {
if (evt.detail && evt.detail.path && evt.detail.path.startsWith('/api/logs')) {
document.getElementById('refresh-indicator').style.display = 'inline';
}
});
document.addEventListener('htmx:afterRequest', function(evt) {
document.getElementById('refresh-indicator').style.display = 'none';
document.addEventListener('DOMContentLoaded', function() {
loadActiveTab();
});
</script>
{% endblock %}
+19 -39
View File
@@ -17,7 +17,6 @@
<tr>
<th>Zone</th>
<th style="width:120px;">Masquerade</th>
<th style="width:80px;">Action</th>
</tr>
</thead>
<tbody>
@@ -25,21 +24,23 @@
<tr>
<td><strong>{{ zone.get('name', 'unnamed') }}</strong></td>
<td>
<label class="switch">
<input type="checkbox"
{% if zone.get('masquerade') %}checked{% endif %}
onchange="toggleMasquerade('{{ zone.get('name', '') }}', this.checked)">
<span class="slider"></span>
</label>
</td>
<td>
<button class="btn btn-sm btn-primary" onclick="toggleMasquerade('{{ zone.get('name', '') }}', this.previousElementSibling.querySelector('input').checked)">Apply</button>
<form hx-post="/api/firewall/masquerade" hx-encoding="json" hx-vals='{"zone": "{{ zone.get('name', '') }}", "enable": JSON.stringify(this.checked)}' hx-swap="none" hx-on::after-request="if(evt.detail.successful){ showSuccessToast('Masquerade '+(this.checked?'enabled':'disabled')+' for {{ zone.get('name', '') }}') } else { this.checked=!this.checked; }">
<label class="switch">
<input type="checkbox"
{% if zone.get('masquerade') %}checked{% endif %}
id="masq-{{ zone.get('name', '') }}"
hx-trigger="change from:#masq-{{ zone.get('name', '') }}"
disabled>
<span class="slider"></span>
</label>
<button type="submit" style="display:none"></button>
</form>
</td>
</tr>
{% endfor %}
{% if not (zones or []) %}
<tr>
<td colspan="3" class="text-muted text-sm">No zones configured</td>
<td colspan="2" class="text-muted text-sm">No zones configured</td>
</tr>
{% endif %}
</tbody>
@@ -50,7 +51,7 @@
<div class="card mb-4">
<h3>Add Forward Rule</h3>
<form hx-post="/api/firewall/nat/forward" hx-swap="none" class="htmx-on-success" data-success="Forward rule added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/firewall/forward-port" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/firewall/config', document.getElementById('forward-rows'), renderForwardsFromConfig); showSuccessToast('Forward rule added'); }">
<div class="inline-form">
<div class="form-group">
<label for="fw-zone">Zone</label>
@@ -63,7 +64,7 @@
</div>
<div class="form-group">
<label for="fw-protocol">Protocol</label>
<select id="fw-protocol" name="protocol">
<select id="fw-protocol" name="proto">
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
@@ -74,11 +75,11 @@
</div>
<div class="form-group">
<label for="fw-target">Target Address</label>
<input type="text" id="fw-target" name="target" placeholder="192.168.1.100" required style="width:160px;">
<input type="text" id="fw-target" name="toaddr" placeholder="192.168.1.100" required style="width:160px;">
</div>
<div class="form-group">
<label for="fw-target-port">Target Port</label>
<input type="number" id="fw-target-port" name="target_port" placeholder="80" min="1" max="65535" style="width:90px;">
<input type="number" id="fw-target-port" name="toport" placeholder="80" min="1" max="65535" style="width:90px;">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</div>
@@ -97,7 +98,7 @@
<th style="width:80px;">Action</th>
</tr>
</thead>
<tbody>
<tbody id="forward-rows">
{% set all_forwards = [] %}
{% for zone in (zones or []) %}
{% for fwd in zone.get('forward_ports', []) %}
@@ -112,8 +113,8 @@
<td>{{ fwd['to-addr'] }}</td>
<td>{{ fwd['to-port'] }}</td>
<td>
<form hx-delete="/api/firewall/nat/forward/{{ fwd.zone | urlencode }}/{{ fwd['proxy-protocol'] }}/{{ fwd['to-addr'] }}/{{ fwd['to-port'] }}" hx-swap="none" class="htmx-on-success" data-success="Rule removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove this forward rule?')">Remove</button>
<form hx-delete="/api/firewall/forward-port/{{ fwd.zone }}/{{ fwd.port }}/{{ fwd['proxy-protocol'] }}" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/firewall/config', document.getElementById('forward-rows'), renderForwardsFromConfig); showSuccessToast('Rule removed'); }">
<button type="submit" class="btn btn-sm btn-danger" hx-confirm="Remove forward rule {{ fwd.port }}/{{ fwd['proxy-protocol'] }} → {{ fwd['to-addr'] }}:{{ fwd['to-port'] }}?">Remove</button>
</form>
</td>
</tr>
@@ -127,25 +128,4 @@
</table>
</div>
<script>
function toggleMasquerade(zoneName, enabled) {
var url = '/api/firewall/nat/masquerade/' + encodeURIComponent(zoneName);
var body = JSON.stringify({ enable: enabled });
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body
})
.then(function(res) {
if (res.ok) {
showToast('Masquerade ' + (enabled ? 'enabled' : 'disabled') + ' for ' + zoneName, 'success');
} else {
return res.text().then(function(t) { throw new Error(t); });
}
})
.catch(function(err) {
showToast('Failed: ' + err.message, 'error');
});
}
</script>
{% endblock %}
+6 -9
View File
@@ -9,7 +9,7 @@
</div>
<div class="flex gap-2">
<button class="btn btn-primary" onclick="openModal('add-domain-modal')">+ Add Domain</button>
<button class="btn btn-outline" hx-post="/api/proxy/reload" hx-swap="none" class="htmx-on-success" data-success="Nginx reloaded">Apply Changes (Reload Nginx)</button>
<button class="btn btn-outline" hx-post="/api/proxy/apply" hx-swap="none" hx-on::after-request="if(evt.detail.successful) showSuccessToast('Nginx reloaded')">Apply Changes (Reload Nginx)</button>
</div>
</div>
@@ -25,7 +25,7 @@
<th style="width:140px;">Actions</th>
</tr>
</thead>
<tbody>
<tbody id="domain-rows">
{% for domain in (domains or []) %}
<tr>
<td><strong>{{ domain.get('domain', 'unknown') }}</strong></td>
@@ -56,8 +56,8 @@
<td>
<div class="flex gap-2">
<button class="btn btn-sm btn-outline" onclick='openEditDomainModal('{{ domain.get("domain", "") }}', {{ domain | tojson | safe }})'>Edit</button>
<form hx-delete="/api/proxy/domains/{{ domain.get('domain', '') }}" hx-swap="none" class="htmx-on-success" data-success="Domain removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove proxy for {{ domain.domain }}?')">Delete</button>
<form hx-delete="/api/proxy/domains/{{ domain.get('domain', '') }}" hx-swap="none" hx-confirm="Remove proxy for {{ domain.domain }}?" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/proxy/domains', document.getElementById('domain-rows'), renderDomains); showSuccessToast('Domain removed'); }">
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
</div>
</td>
@@ -76,7 +76,7 @@
<div class="modal-overlay" id="add-domain-modal" onclick="if(event.target===this) closeModal('add-domain-modal')">
<div class="modal">
<h2>Add Proxy Domain</h2>
<form hx-post="/api/proxy/domains" hx-swap="none" class="htmx-on-success" data-success="Domain added" onsuccess="setTimeout(function(){closeModal('add-domain-modal'); location.reload();}, 300);">
<form hx-post="/api/proxy/domains" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ closeModal('add-domain-modal'); refreshTable('/api/proxy/domains', document.getElementById('domain-rows'), renderDomains); showSuccessToast('Domain added'); }">
<div class="form-group">
<label for="new-domain">Domain</label>
<input type="text" id="new-domain" name="domain" placeholder="example.com" required>
@@ -108,7 +108,7 @@
<div class="modal-overlay" id="edit-domain-modal" onclick="if(event.target===this) closeModal('edit-domain-modal')">
<div class="modal">
<h2>Edit Proxy Domain</h2>
<form id="edit-domain-form" hx-swap="none" class="htmx-on-success" data-success="Domain updated" onsuccess="setTimeout(function(){closeModal('edit-domain-modal'); location.reload();}, 300);">
<form id="edit-domain-form" hx-post="/api/proxy/domains" hx-swap="none" hx-encoding="json" hx-on::after-request="if(evt.detail.successful){ closeModal('edit-domain-modal'); refreshTable('/api/proxy/domains', document.getElementById('domain-rows'), renderDomains); showSuccessToast('Domain updated'); }">
<input type="hidden" id="edit-original-domain" name="original_domain">
<div class="form-group">
<label for="edit-domain">Domain</label>
@@ -144,9 +144,6 @@ function openEditDomainModal(domainName, d) {
document.getElementById('edit-backend-host').value = d.backend_host || '';
document.getElementById('edit-backend-port').value = d.backend_port || '';
document.getElementById('edit-protocol').value = d.protocol || 'http';
var form = document.getElementById('edit-domain-form');
var target = '/api/proxy/domains/' + encodeURIComponent(d.domain);
form.setAttribute('hx-put', target);
openModal('edit-domain-modal');
}
</script>
+7 -4
View File
@@ -11,7 +11,7 @@
<div class="card mb-4">
<h3>Add Rule</h3>
<form hx-post="/api/firewall/rules" hx-swap="none" class="htmx-on-success" data-success="Rule added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/firewall/rich-rules" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/firewall/config', document.getElementById('rules-container'), renderRules); showSuccessToast('Rule added'); }">
<div class="inline-form">
<div class="form-group">
<label for="rule-zone">Zone</label>
@@ -34,6 +34,7 @@
</div>
</div>
<div id="rules-container">
{% if rules or False %}
{% for zone_name, zone_rules in rules.items() %}
<div class="card">
@@ -49,12 +50,13 @@
</thead>
<tbody>
{% for rule in zone_rules %}
{% set rule_obj = rule if rule is mapping else {'id': None, 'rule': rule} %}
<tr>
<td class="text-muted">{{ loop.index }}</td>
<td style="font-family:monospace;font-size:12px;word-break:break-all;">{{ rule }}</td>
<td hx-disable style="font-family:monospace;font-size:12px;word-break:break-all;">{{ rule_obj.rule }}</td>
<td>
<form hx-delete="/api/firewall/rules/{{ zone_name | urlencode }}/{{ loop.index0 }}" hx-swap="none" class="htmx-on-success" data-success="Rule removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove this rule?')">Remove</button>
<form hx-delete="/api/firewall/rich-rules/{{ zone_name | urlencode }}/{{ rule_obj.id }}" hx-swap="none" hx-confirm="Remove rule {{ rule_obj.rule[:50] }}?" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/firewall/config', document.getElementById('rules-container'), renderRules); showSuccessToast('Rule removed'); }">
<button type="submit" class="btn btn-sm btn-danger">Remove</button>
</form>
</td>
</tr>
@@ -71,6 +73,7 @@
<div class="text-muted text-sm">No rules loaded. Add rules using the form above, or ensure the zones API is providing rule data.</div>
</div>
{% endif %}
</div>
{% if not (zones or []) %}
<div class="card" style="border-color:var(--warning);">
+8 -12
View File
@@ -11,17 +11,13 @@
<button class="btn {{ 'btn-outline' if (wg_status is defined and wg_status.get('state') == 'up') else 'btn-primary' }}"
hx-post="/api/wireguard/down"
hx-swap="none"
class="htmx-on-success"
data-success="Tunnel stopped"
onsuccess="setTimeout(function(){ location.reload(); }, 500);">
hx-on::after-request="if(evt.detail.successful){ showSuccessToast('Tunnel stopped'); }">
Stop Tunnel
</button>
<button class="btn {{ 'btn-outline' if (wg_status is not defined or wg_status.get('state') != 'up') else 'btn-primary' }}"
hx-post="/api/wireguard/up"
hx-post="/api/wireguard/apply"
hx-swap="none"
class="htmx-on-success"
data-success="Tunnel started"
onsuccess="setTimeout(function(){ location.reload(); }, 500);">
hx-on::after-request="if(evt.detail.successful){ showSuccessToast('Tunnel started'); }">
Start Tunnel
</button>
</div>
@@ -51,7 +47,7 @@
<div class="card mb-4">
<h3>Add Peer</h3>
<form hx-post="/api/wireguard/peers" hx-swap="none" class="htmx-on-success" data-success="Peer added" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<form hx-post="/api/wireguard/peers" hx-encoding="json" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/wireguard/peers', document.getElementById('peer-rows'), renderPeers); showSuccessToast('Peer added'); }">
<div class="inline-form">
<div class="form-group">
<label for="peer-name">Name</label>
@@ -63,7 +59,7 @@
</div>
<div class="form-group">
<label for="peer-allowed">Allowed IPs</label>
<input type="text" id="peer-allowed" name="allowed_ips" placeholder="10.8.0.2/32" value="10.8.0.{% set next = (peers|length + 2) %}{{ next }}/32" required style="width:160px;">
<input type="text" id="peer-allowed" name="allowed_ips" placeholder="10.8.0.2/32" value="10.8.0.{% set next = (peers or []|length + 2) %}{{ next }}/32" required style="width:160px;">
</div>
<button type="submit" class="btn btn-primary">Add Peer</button>
</div>
@@ -84,7 +80,7 @@
<th style="width:160px;">Actions</th>
</tr>
</thead>
<tbody>
<tbody id="peer-rows">
{% for peer in (peers or []) %}
<tr>
<td>
@@ -102,8 +98,8 @@
<td>
<div class="flex gap-2">
<button class="btn btn-sm btn-outline" onclick="downloadPeerConfig('{{ peer.get('name', '') }}')">Config</button>
<form hx-delete="/api/wireguard/peers/{{ peer.get('name', '') | urlencode }}" hx-swap="none" class="htmx-on-success" data-success="Peer removed" onsuccess="setTimeout(function(){ location.reload(); }, 300);">
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Remove peer {{ peer.name }}?')">Remove</button>
<form hx-delete="/api/wireguard/peers/{{ peer.get('name', '') }}" hx-swap="none" hx-confirm="Remove peer {{ peer.get('name', '') }}?" hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/wireguard/peers', document.getElementById('peer-rows'), renderPeers); showSuccessToast('Peer removed'); }">
<button type="submit" class="btn btn-sm btn-danger">Remove</button>
</form>
</div>
</td>
+3 -3
View File
@@ -10,7 +10,7 @@
<button class="btn btn-primary" onclick="openModal('create-zone-modal')">+ Create Zone</button>
</div>
<div class="card-grid">
<div id="zone-grid" class="card-grid">
{% for zone in (zones or []) %}
<div class="card" style="position:relative;">
<div style="display:flex;justify-content:space-between;align-items:flex-start;">
@@ -45,7 +45,7 @@
</div>
<div style="display:flex;justify-content:flex-end;gap:6px;margin-top:12px;">
<form method="POST" action="/api/firewall/zones/{{ zone.get('name', '') }}/delete" hx-post="/api/firewall/zones/{{ zone.get('name', '') }}/delete" hx-swap="none" onsubmit="return confirm('Delete zone {{ zone.name }}? This will affect traffic to its interfaces.');" class="htmx-on-success" data-success="Zone deleted">
<form hx-delete="/api/firewall/zones/{{ zone.get('name', '') }}" hx-swap="none" hx-confirm="Delete zone {{ zone.name }}? This will affect traffic to its interfaces." hx-on::after-request="if(evt.detail.successful){ refreshTable('/api/firewall/zones', document.getElementById('zone-grid'), renderZones); showSuccessToast('Zone deleted'); }">
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
</div>
@@ -62,7 +62,7 @@
<div class="modal-overlay" id="create-zone-modal" onclick="if(event.target===this) closeModal('create-zone-modal')">
<div class="modal">
<h2>Create Zone</h2>
<form hx-post="/api/firewall/zones" hx-swap="none" class="htmx-on-success" data-success="Zone created" onsuccess="setTimeout(function(){closeModal('create-zone-modal');},500); location.reload();">
<form hx-post="/api/firewall/zones" hx-swap="none" hx-on::after-request="if(evt.detail.successful){ closeModal('create-zone-modal'); refreshTable('/api/firewall/zones', document.getElementById('zone-grid'), renderZones); showSuccessToast('Zone created'); }">
<div class="form-group">
<label for="zone-name">Zone Name</label>
<input type="text" id="zone-name" name="name" placeholder="e.g., trusted, dmz, external" required>