Files
web-proxy-config/app.py
T

836 lines
30 KiB
Python

from __future__ import annotations
import hashlib
import hmac
import ipaddress
import os
import re
import secrets
import shutil
import subprocess
import tempfile
import threading
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from urllib.parse import urlsplit
from flask import Flask, abort, flash, redirect, render_template_string, request, session, url_for
# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
CADDYFILE = Path(os.getenv("CADDYFILE", "/etc/caddy/Caddyfile")).resolve()
DNSMASQ_CONF = Path(os.getenv("DNSMASQ_CONF", "/etc/dnsmasq.conf")).resolve()
BACKUP_DIR = Path(os.getenv("BACKUP_DIR", "/var/backups/web-proxy-config"))
try:
DNSMASQ_TARGET_IP = str(
ipaddress.ip_address(os.getenv("DNSMASQ_TARGET_IP", "192.168.7.251").strip())
)
except ValueError as exc:
raise RuntimeError("DNSMASQ_TARGET_IP is not a valid IPv4/IPv6 address.") from exc
BEGIN_MARKER = os.getenv("BEGIN_MARKER", "#begin marker")
END_MARKER = os.getenv("END_MARKER", "#end marker")
ADMIN_USER = os.getenv("ADMIN_USER", "admin")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "")
APP_SECRET = os.getenv("APP_SECRET", secrets.token_urlsafe(48))
LAN_NETWORKS = [
x.strip()
for x in os.getenv("LAN_NETWORKS", "192.168.7.0/24,10.10.10.0/24").split(",")
if x.strip()
]
MAX_BACKUPS = int(os.getenv("MAX_BACKUPS", "50"))
CADDY_VALIDATE_CMD = [
os.getenv("CADDY_BIN", "/usr/bin/caddy"),
"validate",
"--config",
str(CADDYFILE),
"--adapter",
"caddyfile",
]
CADDY_APPLY_CMD = ["/usr/bin/systemctl", "reload", "caddy"]
DNSMASQ_VALIDATE_CMD = [
os.getenv("DNSMASQ_BIN", "/usr/sbin/dnsmasq"),
"--test",
f"--conf-file={DNSMASQ_CONF}",
]
DNSMASQ_APPLY_CMD = ["/usr/bin/systemctl", "restart", "dnsmasq"]
if not ADMIN_PASSWORD:
raise RuntimeError(
"ADMIN_PASSWORD is not configured. Set it in the systemd EnvironmentFile."
)
app = Flask(__name__)
app.secret_key = APP_SECRET
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Strict",
)
CHANGE_LOCK = threading.Lock()
# -----------------------------------------------------------------------------
# Models / parsing
# -----------------------------------------------------------------------------
@dataclass
class CaddyRecord:
record_id: str
site: str
target: str
comment: str
lan_only: bool
start: int
end: int
raw: str
@dataclass
class DnsRecord:
record_id: str
domain: str
ip: str
index: int
raw: str
def _hash_id(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
@dataclass(frozen=True)
class ManagedSection:
# prefix includes the complete begin-marker line and its original newline.
# suffix starts at the end-marker line. Both are copied verbatim when a
# managed section is changed, so text outside the markers cannot be altered.
prefix: str
managed_text: str
suffix: str
def _marker_pattern(marker: str) -> re.Pattern[str]:
marker = marker.strip()
if not marker:
raise ValueError("Marker cannot be empty.")
# A marker must occupy a whole logical line. Case is ignored so existing
# '#Begin marker' and '#begin marker' variants are both accepted.
return re.compile(
rf"(?im)^[ \t]*{re.escape(marker)}[ \t]*(?:\r?\n|$)"
)
def split_managed_section(text: str) -> ManagedSection:
begin_matches = list(_marker_pattern(BEGIN_MARKER).finditer(text))
end_matches = list(_marker_pattern(END_MARKER).finditer(text))
if len(begin_matches) != 1 or len(end_matches) != 1:
raise ValueError(
"Config must contain exactly one begin marker and exactly one end marker. "
f"Found begin={len(begin_matches)}, end={len(end_matches)}."
)
begin = begin_matches[0]
end = end_matches[0]
if end.start() < begin.end():
raise ValueError("End marker must appear after begin marker.")
return ManagedSection(
prefix=text[: begin.end()],
managed_text=text[begin.end() : end.start()],
suffix=text[end.start() :],
)
def get_managed_lines(text: str) -> list[str]:
return split_managed_section(text).managed_text.splitlines()
def replace_managed_lines(text: str, managed: list[str]) -> str:
section = split_managed_section(text)
# Only the text BETWEEN markers is generated. Prefix and suffix are reused
# byte-for-byte at the Unicode text level from the original file.
newline = (
"\r\n"
if "\r\n" in section.managed_text or section.prefix.endswith("\r\n")
else "\n"
)
managed_text = newline.join(managed)
if managed_text:
# The end marker must remain on its own line. This newline is still
# inside the managed section, immediately before the end marker.
managed_text += newline
return section.prefix + managed_text + section.suffix
def assert_outside_markers_unchanged(old_text: str, new_text: str) -> None:
old = split_managed_section(old_text)
new = split_managed_section(new_text)
if old.prefix != new.prefix or old.suffix != new.suffix:
raise ValueError(
"Safety check failed: content outside the managed markers changed. "
"Nothing was written."
)
def _brace_delta(line: str) -> int:
"""Count braces outside double quotes/backticks and before comments."""
delta = 0
quote = None
escaped = False
for ch in line:
if escaped:
escaped = False
continue
if ch == "\\" and quote == '"':
escaped = True
continue
if quote:
if ch == quote:
quote = None
continue
if ch in ('"', "`"):
quote = ch
continue
if ch == "#":
break
if ch == "{":
delta += 1
elif ch == "}":
delta -= 1
return delta
def parse_caddy_records(managed: list[str]) -> list[CaddyRecord]:
records: list[CaddyRecord] = []
i = 0
while i < len(managed):
stripped = managed[i].strip()
if not stripped or stripped.startswith("#") or "{" not in managed[i]:
i += 1
continue
header = managed[i].split("{", 1)[0].strip()
if not header:
i += 1
continue
depth = 0
end = i
found_open = False
for j in range(i, len(managed)):
d = _brace_delta(managed[j])
if d > 0:
found_open = True
depth += d
end = j
if found_open and depth == 0:
break
else:
# Let caddy validate report the malformed structure; don't make it deletable.
i += 1
continue
# Attach immediately preceding comment lines to this record so delete is tidy.
start = i
k = i - 1
while k >= 0 and managed[k].strip().startswith("#"):
start = k
k -= 1
raw_lines = managed[start : end + 1]
raw = "\n".join(raw_lines)
comments = [
line.strip()[1:].strip()
for line in managed[start:i]
if line.strip().startswith("#")
]
comment = " / ".join(x for x in comments if x)
m = re.search(r"(?m)^\s*reverse_proxy\s+([^\s{]+)", raw)
target = m.group(1) if m else "—"
lan_only = bool(re.search(r"(?m)^\s*@\w+\s+remote_ip\s+", raw))
records.append(
CaddyRecord(
record_id=_hash_id(raw),
site=header,
target=target,
comment=comment,
lan_only=lan_only,
start=start,
end=end,
raw=raw,
)
)
i = end + 1
return records
def parse_dns_records(managed: list[str]) -> list[DnsRecord]:
records: list[DnsRecord] = []
rx = re.compile(r"^\s*address=/([^/]+)/([^/\s]+)\s*$")
for idx, line in enumerate(managed):
m = rx.match(line)
if not m:
continue
records.append(
DnsRecord(
record_id=_hash_id(line),
domain=m.group(1),
ip=m.group(2),
index=idx,
raw=line,
)
)
return records
# -----------------------------------------------------------------------------
# Validation helpers
# -----------------------------------------------------------------------------
HOST_RE = re.compile(
r"^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$",
re.IGNORECASE,
)
DOMAIN_RE = re.compile(
r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$",
re.IGNORECASE,
)
def validate_site(value: str) -> str:
value = value.strip().lower().rstrip(".")
if not HOST_RE.fullmatch(value):
raise ValueError("Invalid Caddy hostname.")
return value
def validate_upstream(value: str) -> str:
value = value.strip()
try:
parsed = urlsplit(value)
except ValueError as exc:
raise ValueError("Invalid upstream URL.") from exc
if parsed.scheme not in {"http", "https"}:
raise ValueError("Upstream must start with http:// or https://")
if not parsed.hostname:
raise ValueError("Upstream must contain a hostname or IP address.")
if parsed.username or parsed.password:
raise ValueError("Credentials in upstream URL are not allowed.")
if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:
raise ValueError("Upstream must not contain a path, query, or fragment.")
try:
port = parsed.port
except ValueError as exc:
raise ValueError("Invalid upstream port.") from exc
if port is not None and not (1 <= port <= 65535):
raise ValueError("Invalid upstream port.")
return value.rstrip("/")
def validate_comment(value: str) -> str:
value = " ".join(value.replace("\r", " ").replace("\n", " ").split()).strip()
if len(value) > 120:
raise ValueError("Comment is too long (max 120 characters).")
return value
def validate_dns_domain(value: str) -> str:
value = value.strip().lower().rstrip(".")
leading_dot = value.startswith(".")
bare = value[1:] if leading_dot else value
if not DOMAIN_RE.fullmatch(bare):
raise ValueError("Invalid dnsmasq domain.")
return ("." if leading_dot else "") + bare
def build_caddy_block(site: str, upstream: str, comment: str, lan_only: bool) -> list[str]:
lines: list[str] = []
if comment:
lines.append(f"#{comment}")
lines.append(f"{site} {{")
if lan_only:
networks = " ".join(LAN_NETWORKS)
lines.extend(
[
f" @lan remote_ip {networks}",
"",
" handle @lan {",
f" reverse_proxy {upstream}",
" }",
"",
' respond "Forbidden" 403',
]
)
else:
lines.append(f" reverse_proxy {upstream}")
lines.append("}")
return lines
# -----------------------------------------------------------------------------
# File transaction / commands
# -----------------------------------------------------------------------------
def read_text_exact(path: Path) -> str:
# newline="" disables universal-newline conversion, preserving CRLF/LF
# exactly as stored in the source file.
with path.open("r", encoding="utf-8", newline="") as fh:
return fh.read()
def run_cmd(cmd: list[str], timeout: int = 20) -> tuple[bool, str]:
try:
cp = subprocess.run(
cmd,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=timeout,
check=False,
env={**os.environ, "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},
)
output = (cp.stdout or "").strip()
return cp.returncode == 0, output or f"exit code {cp.returncode}"
except (OSError, subprocess.TimeoutExpired) as exc:
return False, str(exc)
def atomic_write(path: Path, content: str, original_stat: os.stat_result | None = None) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if original_stat is None:
original_stat = path.stat()
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent), text=True)
tmp = Path(tmp_name)
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
fh.write(content)
fh.flush()
os.fsync(fh.fileno())
os.chmod(tmp, original_stat.st_mode & 0o7777)
os.chown(tmp, original_stat.st_uid, original_stat.st_gid)
os.replace(tmp, path)
dir_fd = os.open(path.parent, os.O_DIRECTORY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
finally:
if tmp.exists():
tmp.unlink(missing_ok=True)
def create_backup(path: Path, old_text: str) -> Path:
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
backup = BACKUP_DIR / f"{path.name}.{stamp}.bak"
with backup.open("w", encoding="utf-8", newline="") as fh:
fh.write(old_text)
st = path.stat()
os.chmod(backup, st.st_mode & 0o7777)
prefix = f"{path.name}."
backups = sorted(
[p for p in BACKUP_DIR.iterdir() if p.name.startswith(prefix) and p.name.endswith(".bak")],
key=lambda p: p.stat().st_mtime,
reverse=True,
)
for stale in backups[MAX_BACKUPS:]:
stale.unlink(missing_ok=True)
return backup
def apply_transaction(
path: Path,
expected_old_text: str,
new_text: str,
validate_cmd: list[str],
apply_cmd: list[str],
) -> tuple[bool, str]:
with CHANGE_LOCK:
old_text = read_text_exact(path)
if old_text != expected_old_text:
return False, "Config file changed since the page action started; nothing was written. Reload the page and try again."
if old_text == new_text:
return True, "No changes were necessary."
# Defence in depth: even if a future route constructs new_text
# incorrectly, refuse to write unless everything outside the markers
# is exactly unchanged.
assert_outside_markers_unchanged(old_text, new_text)
stat = path.stat()
backup = create_backup(path, old_text)
atomic_write(path, new_text, stat)
valid, validation_output = run_cmd(validate_cmd)
if not valid:
atomic_write(path, old_text, stat)
return (
False,
"Validation failed; original file restored.\n"
f"Validator output:\n{validation_output}",
)
applied, apply_output = run_cmd(apply_cmd)
if applied:
return True, f"Applied successfully. Backup: {backup}"
# The file was valid, but service action failed. Restore the original
# config and make a best-effort attempt to reactivate it.
atomic_write(path, old_text, stat)
rollback_valid, rollback_validation = run_cmd(validate_cmd)
rollback_applied, rollback_apply = run_cmd(apply_cmd) if rollback_valid else (False, "rollback validation failed")
details = [
"Service reload/restart failed; original file restored.",
f"Apply output: {apply_output}",
f"Rollback validation: {rollback_validation}",
f"Rollback apply: {rollback_apply}",
]
if not rollback_applied:
details.append("WARNING: automatic rollback activation also failed; check the service immediately.")
return False, "\n".join(details)
# -----------------------------------------------------------------------------
# Auth / CSRF
# -----------------------------------------------------------------------------
def _auth_ok() -> bool:
auth = request.authorization
if not auth:
return False
return hmac.compare_digest(auth.username or "", ADMIN_USER) and hmac.compare_digest(
auth.password or "", ADMIN_PASSWORD
)
@app.before_request
def require_auth():
if not _auth_ok():
return (
"Authentication required",
401,
{"WWW-Authenticate": 'Basic realm="NAS Config"'},
)
def csrf_token() -> str:
token = session.get("csrf_token")
if not token:
token = secrets.token_urlsafe(32)
session["csrf_token"] = token
return token
app.jinja_env.globals["csrf_token"] = csrf_token
def require_csrf() -> None:
expected = session.get("csrf_token", "")
supplied = request.form.get("csrf_token", "")
if not expected or not hmac.compare_digest(expected, supplied):
abort(400, "Invalid CSRF token")
# -----------------------------------------------------------------------------
# Routes
# -----------------------------------------------------------------------------
def load_state():
caddy_text = read_text_exact(CADDYFILE)
dns_text = read_text_exact(DNSMASQ_CONF)
caddy_records = parse_caddy_records(get_managed_lines(caddy_text))
dns_records = parse_dns_records(get_managed_lines(dns_text))
caddy_status, caddy_status_text = run_cmd(CADDY_VALIDATE_CMD)
dns_status, dns_status_text = run_cmd(DNSMASQ_VALIDATE_CMD)
return caddy_records, dns_records, caddy_status, caddy_status_text, dns_status, dns_status_text
@app.get("/")
def index():
try:
state = load_state()
except Exception as exc:
state = ([], [], False, f"Cannot read Caddy config: {exc}", False, f"Cannot read dnsmasq config: {exc}")
return render_template_string(
TEMPLATE,
caddy_records=state[0],
dns_records=state[1],
caddy_ok=state[2],
caddy_status=state[3],
dns_ok=state[4],
dns_status=state[5],
lan_networks=", ".join(LAN_NETWORKS),
dns_target_ip=DNSMASQ_TARGET_IP,
)
@app.post("/caddy/add")
def caddy_add():
require_csrf()
try:
site = validate_site(request.form.get("site", ""))
upstream = validate_upstream(request.form.get("upstream", ""))
comment = validate_comment(request.form.get("comment", ""))
lan_only = request.form.get("lan_only") == "on"
old = read_text_exact(CADDYFILE)
managed = get_managed_lines(old)
records = parse_caddy_records(managed)
existing_sites = {r.site.strip().lower() for r in records}
if site.lower() in existing_sites:
raise ValueError(f"Caddy entry for {site} already exists in the managed section.")
new_block = build_caddy_block(site, upstream, comment, lan_only)
if managed and managed[-1].strip():
managed.append("")
managed.extend(new_block)
new = replace_managed_lines(old, managed)
ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD)
flash(message, "success" if ok else "error")
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.post("/caddy/delete")
def caddy_delete():
require_csrf()
record_id = request.form.get("record_id", "")
try:
old = read_text_exact(CADDYFILE)
managed = get_managed_lines(old)
records = parse_caddy_records(managed)
record = next((r for r in records if r.record_id == record_id), None)
if record is None:
raise ValueError("Caddy record not found; reload the page and try again.")
del managed[record.start : record.end + 1]
# Collapse excessive blank lines around the removed block.
compact: list[str] = []
for line in managed:
if line.strip() == "" and compact and compact[-1].strip() == "":
continue
compact.append(line)
while compact and compact[0].strip() == "":
compact.pop(0)
while compact and compact[-1].strip() == "":
compact.pop()
new = replace_managed_lines(old, compact)
ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD)
flash(message, "success" if ok else "error")
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.post("/dns/add")
def dns_add():
require_csrf()
try:
domain = validate_dns_domain(request.form.get("domain", ""))
ip = DNSMASQ_TARGET_IP
old = read_text_exact(DNSMASQ_CONF)
managed = get_managed_lines(old)
records = parse_dns_records(managed)
if domain.lower() in {r.domain.lower() for r in records}:
raise ValueError(f"dnsmasq entry for {domain} already exists in the managed section.")
if managed and managed[-1].strip() == "":
managed[-1] = f"address=/{domain}/{ip}"
else:
managed.append(f"address=/{domain}/{ip}")
new = replace_managed_lines(old, managed)
ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD)
flash(message, "success" if ok else "error")
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.post("/dns/delete")
def dns_delete():
require_csrf()
record_id = request.form.get("record_id", "")
try:
old = read_text_exact(DNSMASQ_CONF)
managed = get_managed_lines(old)
records = parse_dns_records(managed)
record = next((r for r in records if r.record_id == record_id), None)
if record is None:
raise ValueError("dnsmasq record not found; reload the page and try again.")
del managed[record.index]
new = replace_managed_lines(old, managed)
ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD)
flash(message, "success" if ok else "error")
except Exception as exc:
flash(str(exc), "error")
return redirect(url_for("index"))
@app.get("/health")
def health():
return {"ok": True}
# -----------------------------------------------------------------------------
# UI
# -----------------------------------------------------------------------------
TEMPLATE = r"""
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>NAS Config</title>
<style>
:root { color-scheme: dark; --bg:#101318; --card:#171b22; --muted:#8f99a8; --line:#2b313c; --good:#35c46a; --bad:#ff5d66; --accent:#5b9cff; }
* { box-sizing:border-box; }
body { margin:0; font:14px/1.45 system-ui,-apple-system,Segoe UI,sans-serif; background:var(--bg); color:#edf2f7; }
main { max-width:1180px; margin:0 auto; padding:28px 18px 60px; }
h1 { margin:0 0 6px; font-size:26px; }
h2 { margin:0; font-size:19px; }
.muted { color:var(--muted); }
.grid { display:grid; grid-template-columns:1fr 1fr; gap:18px; margin-top:18px; }
.card { background:var(--card); border:1px solid var(--line); border-radius:14px; padding:18px; box-shadow:0 8px 30px rgba(0,0,0,.16); }
.head { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:14px; }
.status { display:inline-flex; align-items:center; gap:7px; color:var(--muted); font-size:12px; }
.dot { width:9px; height:9px; border-radius:50%; background:var(--bad); box-shadow:0 0 0 3px rgba(255,93,102,.12); }
.dot.ok { background:var(--good); box-shadow:0 0 0 3px rgba(53,196,106,.12); }
form.add { display:grid; grid-template-columns:1fr 1fr; gap:10px; padding:13px; margin-bottom:16px; background:#12161c; border:1px solid var(--line); border-radius:11px; }
label { display:block; color:var(--muted); font-size:12px; }
input[type=text] { width:100%; margin-top:5px; padding:9px 10px; border-radius:8px; border:1px solid #343b47; background:#0e1116; color:#fff; outline:none; }
input[type=text]:focus { border-color:var(--accent); }
.wide { grid-column:1/-1; }
.check { display:flex; gap:8px; align-items:center; color:#dce3eb; }
button { border:0; border-radius:8px; padding:9px 12px; color:#fff; background:var(--accent); cursor:pointer; font-weight:600; }
button.delete { background:transparent; color:#ff8c92; border:1px solid #65343a; padding:6px 9px; }
table { width:100%; border-collapse:collapse; }
th { text-align:left; font-size:11px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); padding:8px 7px; border-bottom:1px solid var(--line); }
td { padding:10px 7px; border-bottom:1px solid #242a33; vertical-align:top; }
td code { color:#c9dbff; word-break:break-all; }
.flash { white-space:pre-wrap; padding:12px 14px; margin:0 0 12px; border-radius:9px; border:1px solid; }
.flash.success { background:rgba(53,196,106,.08); border-color:#2b6740; }
.flash.error { background:rgba(255,93,102,.08); border-color:#71383d; }
details { margin-top:10px; color:var(--muted); }
pre { white-space:pre-wrap; word-break:break-word; font-size:12px; }
.tag { display:inline-block; padding:2px 7px; border:1px solid #3a4657; border-radius:999px; color:#b8c6d9; font-size:11px; }
@media (max-width:900px) { .grid { grid-template-columns:1fr; } }
@media (max-width:560px) { form.add { grid-template-columns:1fr; } .wide { grid-column:auto; } table { display:block; overflow-x:auto; } }
</style>
</head>
<body>
<main>
<h1>NAS Config</h1>
<div class="muted">Управляемые секции Caddy и dnsmasq. Перед применением конфигурация проверяется, при ошибке выполняется откат.</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
{% endwith %}
<div class="grid">
<section class="card">
<div class="head">
<h2>Caddy</h2>
<span class="status"><span class="dot {{ 'ok' if caddy_ok else '' }}"></span>{{ 'config OK' if caddy_ok else 'config ERROR' }}</span>
</div>
<form class="add" method="post" action="{{ url_for('caddy_add') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label>Имя сайта<input type="text" name="site" required placeholder="grafana.example.ru"></label>
<label>Upstream<input type="text" name="upstream" required placeholder="http://nas.local:3000"></label>
<label class="wide">Комментарий<input type="text" name="comment" placeholder="Grafana"></label>
<label class="check wide"><input type="checkbox" name="lan_only"> Доступ только из LAN ({{ lan_networks }})</label>
<button class="wide" type="submit">Добавить Caddy proxy</button>
</form>
<table>
<thead><tr><th>Host</th><th>Upstream</th><th></th></tr></thead>
<tbody>
{% for r in caddy_records %}
<tr>
<td><strong>{{ r.site }}</strong>{% if r.comment %}<div class="muted">{{ r.comment }}</div>{% endif %}{% if r.lan_only %}<span class="tag">LAN only</span>{% endif %}</td>
<td><code>{{ r.target }}</code></td>
<td>
<form method="post" action="{{ url_for('caddy_delete') }}" onsubmit="return confirm('Удалить {{ r.site }}?')">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="record_id" value="{{ r.record_id }}">
<button class="delete" type="submit">Удалить</button>
</form>
</td>
</tr>
{% else %}<tr><td colspan="3" class="muted">Записей не найдено.</td></tr>{% endfor %}
</tbody>
</table>
<details><summary>Результат caddy validate</summary><pre>{{ caddy_status }}</pre></details>
</section>
<section class="card">
<div class="head">
<h2>dnsmasq</h2>
<span class="status"><span class="dot {{ 'ok' if dns_ok else '' }}"></span>{{ 'config OK' if dns_ok else 'config ERROR' }}</span>
</div>
<form class="add" method="post" action="{{ url_for('dns_add') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label class="wide">Домен<input type="text" name="domain" required placeholder="example.com или .example.com"></label>
<div class="muted wide">Все новые записи направляются на <code>{{ dns_target_ip }}</code> (настройка DNSMASQ_TARGET_IP).</div>
<button class="wide" type="submit">Добавить DNS-запись</button>
</form>
<table>
<thead><tr><th>Domain</th><th>IP</th><th></th></tr></thead>
<tbody>
{% for r in dns_records %}
<tr>
<td><strong>{{ r.domain }}</strong></td>
<td><code>{{ r.ip }}</code></td>
<td>
<form method="post" action="{{ url_for('dns_delete') }}" onsubmit="return confirm('Удалить {{ r.domain }}?')">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="record_id" value="{{ r.record_id }}">
<button class="delete" type="submit">Удалить</button>
</form>
</td>
</tr>
{% else %}<tr><td colspan="3" class="muted">Записей не найдено.</td></tr>{% endfor %}
</tbody>
</table>
<details><summary>Результат dnsmasq --test</summary><pre>{{ dns_status }}</pre></details>
</section>
</div>
</main>
</body>
</html>
"""
if __name__ == "__main__":
# For manual testing only. The systemd unit uses gunicorn.
app.run(host="127.0.0.1", port=8090, debug=False)