1457 lines
271 KiB
Python
1457 lines
271 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
Avaya / Extreme Avaya / Extreme ERS 5952 Switch Manager — One File Setup
|
||
─────────────────────────────────────────
|
||
Copy this single file to your always on management computer
|
||
(Raspberry Pi, HP T620 thin client, old computer or laptop) and run:
|
||
|
||
python Avaya_5952_setup.py
|
||
|
||
It will:
|
||
- Install Python dependencies
|
||
- Generate SSH keypair
|
||
- Guide you through loading the key on the switch (one manual step)
|
||
- Test SSH connectivity
|
||
- Pin the switch host key
|
||
- Set up TOTP authenticator
|
||
- Write switch_backend.py and build the React frontend
|
||
- Install and start the systemd service
|
||
- Open the browser
|
||
|
||
Re-running is safe — skips steps already done.
|
||
─────────────────────────────────────────
|
||
"""
|
||
|
||
import os, sys, time, shutil, subprocess, textwrap, socket
|
||
from pathlib import Path
|
||
|
||
# ── Colour helpers ──────────────────────────────────────────────────────────
|
||
def c(t, code): return f"\033[{code}m{t}\033[0m"
|
||
def green(t): return c(t, "32")
|
||
def yellow(t): return c(t, "33")
|
||
def red(t): return c(t, "31")
|
||
def cyan(t): return c(t, "36")
|
||
def bold(t): return c(t, "1")
|
||
def dim(t): return c(t, "2")
|
||
def ok(m): print(f" {green(chr(10003))} {m}")
|
||
def warn(m): print(f" {yellow(chr(9888))} {m}")
|
||
def err(m): print(f" {red(chr(10007))} {m}")
|
||
def info(m): print(f" {cyan(chr(9672))} {m}")
|
||
def step(n,m): print(f"\n{bold(cyan(f'[{n}]'))} {bold(m)}")
|
||
def sep(): print(dim(" " + chr(8212)*58))
|
||
|
||
def ask(prompt, default=""):
|
||
try:
|
||
v = input(f" {cyan(chr(63))} {prompt}" + (f" [{default}]" if default else "") + ": ").strip()
|
||
return v if v else default
|
||
except KeyboardInterrupt:
|
||
print("\n\nAborted."); sys.exit(0)
|
||
|
||
def ask_yn(prompt, default=True):
|
||
v = ask(f"{prompt} ({'Y/n' if default else 'y/N'})", "").lower()
|
||
return default if not v else v.startswith("y")
|
||
|
||
def pause(m="Press Enter to continue..."):
|
||
try: input(f"\n {yellow(chr(9654))} {m}")
|
||
except KeyboardInterrupt: print("\n\nAborted."); sys.exit(0)
|
||
|
||
def sudo(cmd):
|
||
prefix = "sudo " if os.geteuid() != 0 else ""
|
||
return subprocess.run(f"{prefix}{cmd}", shell=True, capture_output=True, text=True)
|
||
|
||
def run(cmd, capture=True, check=False):
|
||
return subprocess.run(cmd, shell=True, capture_output=capture, text=True, check=check)
|
||
|
||
def local_ip():
|
||
try:
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
s.connect(("8.8.8.8", 80))
|
||
ip = s.getsockname()[0]; s.close(); return ip
|
||
except: return "localhost"
|
||
|
||
# ── Paths ────────────────────────────────────────────────────────────────────
|
||
HERE = Path(__file__).parent.absolute()
|
||
CONF_DIR = Path("/etc/switch-manager")
|
||
KEY_PATH = CONF_DIR / "ers5952_key"
|
||
KNOWN_HOSTS = CONF_DIR / "known_hosts"
|
||
TOTP_FILE = CONF_DIR / "totp_secret"
|
||
BACKEND = HERE / "switch_backend.py"
|
||
FRONTEND = HERE / "frontend"
|
||
DIST = FRONTEND / "dist"
|
||
APP_JSX = HERE / "ers5952-manager.jsx"
|
||
SERVICE = Path("/etc/systemd/system/switch-manager.service")
|
||
PACKAGES = ["fastapi", "uvicorn", "paramiko", "pyotp"]
|
||
# ── Console software download links ───────────────────────────────────────────
|
||
CONSOLE_SOFTWARE = {
|
||
"PuTTY (Windows)": "https://www.putty.org",
|
||
"TeraTerm (Windows)": "https://github.com/TeraTermProject/teraterm/releases",
|
||
"Serial (Mac)": "https://apps.apple.com/app/serial/id877615577",
|
||
"CoolTerm (Mac/Win)": "https://freeware.the-meiers.org",
|
||
"CP2102 USB driver": "https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers",
|
||
"FTDI USB driver": "https://ftdichip.com/drivers/vcp-drivers/",
|
||
}
|
||
|
||
CONSOLE_CABLE_SEARCH = "RJ45 console cable USB Cisco compatible"
|
||
|
||
|
||
|
||
BACKEND_SRC = '"""\nERS 5952 Switch Manager — Backend v3\n────────────────────────────────────────────────────────────────────────\nChanges from v2:\n - Connection pool (30s lifetime, liveness check, auto-invalidate)\n - Visitor-aware polling — starts when someone hits the page,\n pauses when no active visitors, stops completely when idle\n - Hard-block danger patterns (no force override for lethal commands)\n - Session-based TOTP (one auth → session token → many pushes)\n - Per-command execution with stop-on-error\n - Config saved only on full success\n\nRequirements:\n pip install fastapi uvicorn paramiko pyotp\n\nRun:\n python switch_backend.py # start server\n python switch_backend.py --setup-totp # first-time TOTP setup\n────────────────────────────────────────────────────────────────────────\n"""\n\nimport re, sys, time, secrets, logging, threading, os\nfrom pathlib import Path\nfrom typing import Optional\n\nimport paramiko, pyotp\nfrom fastapi import FastAPI, HTTPException, Request\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.responses import JSONResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom pydantic import BaseModel, field_validator\n\nlogging.basicConfig(level=logging.INFO,\n format="%(asctime)s [%(levelname)s] %(message)s")\nlog = logging.getLogger("switch-manager")\n\n# ══════════════════════════════════════════════════════════════════════\n# CONFIG\n# ══════════════════════════════════════════════════════════════════════\nSWITCH_HOST = "192.168.99.1"\nSWITCH_PORT = 22\nSWITCH_USER = "admin"\nKEY_PATH = "/etc/switch-manager/ers5952_key"\nKNOWN_HOSTS = "/etc/switch-manager/known_hosts"\nTOTP_FILE = "/etc/switch-manager/totp_secret"\nSTATIC_DIR = "./frontend/dist"\n\nPOLL_ACTIVE_S = 15 # poll interval when visitors present\nPOLL_BG_S = 60 # poll interval when tab backgrounded\nPOLL_IDLE_AFTER = 300 # stop polling after this many seconds with no visitors\nCONN_POOL_MAX_S = 25 # max connection age before refresh (< switch idle timeout)\nSESSION_TTL_S = 600 # TOTP session — 10 minutes, reset on activity\n\nALLOWED_ORIGINS = ["*"] # tighten to http://192.168.99.X in production\n\n# ══════════════════════════════════════════════════════════════════════\n# TOTP\n# ══════════════════════════════════════════════════════════════════════\n\ndef get_or_create_totp_secret() -> str:\n p = Path(TOTP_FILE)\n if p.exists():\n return p.read_text().strip()\n secret = pyotp.random_base32()\n p.parent.mkdir(parents=True, exist_ok=True)\n p.write_text(secret)\n p.chmod(0o600)\n log.info(f"New TOTP secret created at {TOTP_FILE}")\n return secret\n\ndef setup_totp():\n secret = get_or_create_totp_secret()\n uri = pyotp.TOTP(secret).provisioning_uri(\n name="ERS5952", issuer_name="SwitchManager")\n print("\\n══════════════════════════════════════════════════")\n print(" ERS 5952 Switch Manager — TOTP Setup")\n print("══════════════════════════════════════════════════")\n print(f"\\n Manual entry secret:\\n {secret}")\n print(f"\\n Provisioning URI (paste into authenticator app):\\n {uri}")\n print("\\n Or generate a QR code:")\n print(f" python -c \\"import qrcode; qrcode.make(\'{uri}\').show()\\"")\n print("\\n══════════════════════════════════════════════════\\n")\n\nTOTP_SECRET: str = ""\n\n# ── Session tokens (one TOTP → session, multiple pushes) ──────────────\n# { token: { expires: float, last_activity: float } }\n_sessions: dict[str, dict] = {}\n_sessions_lock = threading.Lock()\n\ndef create_session() -> str:\n token = secrets.token_hex(32)\n now = time.time()\n with _sessions_lock:\n _sessions[token] = {"expires": now + SESSION_TTL_S, "last_activity": now}\n return token\n\ndef validate_session(token: str) -> bool:\n """Returns True and refreshes activity timestamp if session is valid."""\n now = time.time()\n with _sessions_lock:\n # Prune expired\n expired = [t for t, s in _sessions.items() if s["expires"] < now]\n for t in expired:\n del _sessions[t]\n if token not in _sessions:\n return False\n # Refresh on activity\n _sessions[token]["last_activity"] = now\n _sessions[token]["expires"] = now + SESSION_TTL_S\n return True\n\ndef session_remaining(token: str) -> Optional[int]:\n with _sessions_lock:\n s = _sessions.get(token)\n if not s:\n return None\n return max(0, int(s["expires"] - time.time()))\n\ndef revoke_session(token: str):\n with _sessions_lock:\n _sessions.pop(token, None)\n\ndef require_session(token: str):\n if not validate_session(token):\n raise HTTPException(401, "Session expired or invalid — re-authenticate with TOTP")\n\n# ══════════════════════════════════════════════════════════════════════\n# DANGER DETECTION\n# Two tiers:\n# HARD_BLOCK — refused entirely, must run at console\n# WARN — flagged, push still offered with explicit override\n# ══════════════════════════════════════════════════════════════════════\n\nHARD_BLOCK_PATTERNS = [\n # Management VLAN removal — all variants\n (re.compile(r\'no\\s+vlan\\s+99\\b\', re.I), "Deletes management VLAN 99"),\n (re.compile(r\'vlan\\s+members\\s+remove\\b.*\\b99\\b\', re.I), "Removes VLAN 99 from a port — kills management trunk"),\n (re.compile(r\'no\\s+vlan\\s+tagging\\b.*\\b99\\b\', re.I), "Removes VLAN 99 tagging — kills management trunk"),\n (re.compile(r\'vlan\\s+pvid\\s+\\S+\\s+\\S+\', re.I), "Changes native VLAN — verify not management port"),\n # SSH / IP removal\n (re.compile(r\'no\\s+ip\\s+ssh\', re.I), "Disables SSH entirely — permanent lockout"),\n (re.compile(r\'no\\s+ip\\s+address\\b\', re.I), "Removes IP address — will lose connectivity"),\n # Management interface\n (re.compile(r\'interface\\s+vlan\\s+99\\b\', re.I), "Modifies management VLAN interface — run at console"),\n # Boot / factory\n (re.compile(r\'boot\\s+config\\s+flags\\s+factory\', re.I), "Factory reset — run at console"),\n]\n\nWARN_PATTERNS = [\n (re.compile(r\'\\bshutdown\\b\', re.I), "Shuts down an interface — confirm it is not your uplink"),\n (re.compile(r\'default\\s+interface\\b\', re.I), "Resets interface to defaults"),\n (re.compile(r\'no\\s+vlan\\s+\\d+\\b\', re.I), "Deletes a VLAN — confirm no active ports depend on it"),\n (re.compile(r\'spanning-tree\\s+.*\\s+disable\', re.I), "Disables spanning tree — loop risk"),\n]\n\ndef check_danger(commands: list[str]) -> dict:\n hard, warn = [], []\n for cmd in commands:\n for pat, reason in HARD_BLOCK_PATTERNS:\n if pat.search(cmd):\n hard.append({"command": cmd, "reason": reason})\n break\n else:\n for pat, reason in WARN_PATTERNS:\n if pat.search(cmd):\n warn.append({"command": cmd, "reason": reason})\n break\n return {\n "hard_blocked": hard,\n "warnings": warn,\n "has_hard_block": bool(hard),\n "has_warnings": bool(warn),\n }\n\n# ══════════════════════════════════════════════════════════════════════\n# SANITIZATION\n# ══════════════════════════════════════════════════════════════════════\n\n_BAD_CHARS = re.compile(r\'[;&|`$<>(){}\\\\"\\\']\')\n_BAD_PATS = [re.compile(p) for p in [r\'\\n\', r\'\\r\', r\'--\', r\'/\\*\']]\n_RE_VID = re.compile(r\'^\\d{1,4}$\')\n_RE_VNAME = re.compile(r\'^[a-zA-Z0-9\\-_]{1,32}$\')\n_RE_MODE = re.compile(r\'^(access|trunk|disabled)$\')\n_RE_ANAME = re.compile(r\'^[a-zA-Z0-9\\-_]{1,32}$\')\n_RE_DIR = re.compile(r\'^(in|out)$\')\n_RE_PROTO = re.compile(r\'^(ip|tcp|udp|icmp)$\')\n_RE_ACTION = re.compile(r\'^(permit|deny)$\')\n_RE_DESC = re.compile(r\'^[a-zA-Z0-9\\-_ ]{0,64}$\')\n\ndef _san(v: str, pat: re.Pattern, field: str) -> str:\n if _BAD_CHARS.search(v):\n raise ValueError(f"{field}: disallowed characters")\n for p in _BAD_PATS:\n if p.search(v):\n raise ValueError(f"{field}: injection pattern")\n if not pat.match(v):\n raise ValueError(f"{field}: invalid format — {repr(v)}")\n return v\n\ndef san_vid(v, field="vlan_id") -> int:\n _san(str(v), _RE_VID, field)\n vid = int(v)\n if not 1 <= vid <= 4094:\n raise ValueError(f"{field}: must be 1–4094")\n return vid\n\ndef san_port(v) -> int:\n p = int(v)\n if not 1 <= p <= 52:\n raise ValueError("port: must be 1–52")\n return p\n\n_ALLOWED_CMD_RE = [\n re.compile(r\'^vlan\\s+(create|members|tagging|pvid)\\s\'),\n re.compile(r\'^no\\s+vlan\\s+\\d+$\'),\n re.compile(r\'^interface\\s+(FastEthernet|GigabitEthernet|vlan)\\s\'),\n re.compile(r\'^\\s+(name|no\\s+shutdown|poe|speed|duplex|ip\\s+access-group|shutdown)\\b\'),\n re.compile(r\'^hostname\\s+\\S+$\'),\n re.compile(r\'^ip\\s+access-list\\s+extended\\s\'),\n re.compile(r\'^\\s+\\d+\\s+(permit|deny)\\s\'),\n re.compile(r\'^!\\s*\'), re.compile(r\'^\\s*$\'),\n]\n\ndef is_allowed(cmd: str) -> bool:\n return any(p.match(cmd) for p in _ALLOWED_CMD_RE)\n\n# ══════════════════════════════════════════════════════════════════════\n# CONNECTION POOL\n# ══════════════════════════════════════════════════════════════════════\n\nclass SwitchConnectionPool:\n """\n Keeps one SSH connection alive for up to CONN_POOL_MAX_S seconds.\n On liveness check failure or expiry → opens a fresh connection.\n Thread-safe.\n """\n def __init__(self):\n self._conn: Optional[paramiko.SSHClient] = None\n self._born: float = 0\n self._lock = threading.Lock()\n\n def get(self) -> paramiko.SSHClient:\n with self._lock:\n now = time.time()\n age = now - self._born\n if self._conn and age < CONN_POOL_MAX_S:\n try:\n transport = self._conn.get_transport()\n if transport and transport.is_active():\n transport.send_ignore() # lightweight liveness ping\n return self._conn\n except Exception:\n log.info("Pool: liveness check failed — opening fresh connection")\n self._close_unsafe()\n self._conn = _open_connection()\n self._born = time.time()\n log.info("Pool: new connection opened")\n return self._conn\n\n def invalidate(self):\n with self._lock:\n self._close_unsafe()\n\n def _close_unsafe(self):\n if self._conn:\n try:\n self._conn.close()\n except Exception:\n pass\n self._conn = None\n self._born = 0\n\n_pool = SwitchConnectionPool()\n\n\ndef _open_connection() -> paramiko.SSHClient:\n client = paramiko.SSHClient()\n known = Path(KNOWN_HOSTS)\n if known.exists():\n client.load_host_keys(str(known))\n client.set_missing_host_key_policy(paramiko.RejectPolicy())\n else:\n log.warning("No known_hosts — trust on first use")\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n try:\n client.connect(\n hostname=SWITCH_HOST, port=SWITCH_PORT, username=SWITCH_USER,\n key_filename=KEY_PATH, look_for_keys=False, allow_agent=False,\n timeout=10, banner_timeout=10,\n )\n except paramiko.AuthenticationException:\n raise HTTPException(503, "SSH auth failed — is the public key loaded on the switch?")\n except Exception as e:\n raise HTTPException(503, f"Cannot reach switch at {SWITCH_HOST}: {e}")\n if not known.exists():\n known.parent.mkdir(parents=True, exist_ok=True)\n client.save_host_keys(str(known))\n log.info("Host key pinned to known_hosts")\n return client\n\n\ndef read_cmd(cmd: str) -> str:\n """Run a read-only command via the pool. Invalidates pool on error."""\n try:\n conn = _pool.get()\n _, stdout, _ = conn.exec_command(cmd, timeout=10)\n return stdout.read().decode("utf-8", errors="replace")\n except HTTPException:\n raise\n except Exception as e:\n log.warning(f"read_cmd failed ({cmd}): {e} — invalidating pool")\n _pool.invalidate()\n raise HTTPException(503, f"Switch read failed: {e}")\n\n\n# ── Per-command interactive push ───────────────────────────────────────\n\n_SWITCH_ERR = re.compile(\n r\'%\\s*(invalid|error|unknown|bad|failed|cannot|not\\s+found|does\\s+not\\s+exist\'\n r\'|incomplete|ambiguous|out\\s+of\\s+range|already\\s+exists)\',\n re.I\n)\n\ndef _run_one(channel, cmd: str) -> tuple[str, bool]:\n channel.send(cmd + "\\n")\n time.sleep(0.35)\n out, deadline = "", time.time() + 6\n while time.time() < deadline:\n if channel.recv_ready():\n out += channel.recv(4096).decode("utf-8", errors="replace")\n time.sleep(0.1)\n else:\n if out:\n break\n time.sleep(0.1)\n return out.strip(), bool(_SWITCH_ERR.search(out))\n\n\ndef push_one_by_one(commands: list[str]) -> dict:\n """\n Opens a FRESH dedicated connection for push (not from pool —\n we don\'t want a push session to corrupt the pool\'s read connection).\n Runs commands one at a time, stops on first error.\n Saves config only on full success.\n """\n _pool.invalidate() # invalidate pool — switch will be busy during push\n client = _open_connection()\n results = []\n stopped_at = None\n try:\n ch = client.invoke_shell()\n ch.settimeout(10)\n time.sleep(0.5)\n if ch.recv_ready():\n ch.recv(4096) # drain banner\n\n for setup in ["enable", "configure terminal"]:\n out, err = _run_one(ch, setup)\n if err:\n return {"success": False, "saved": False,\n "error": f"Failed entering config mode: {out}",\n "results": [], "hint": "Check switch is reachable and credentials are correct"}\n\n for i, cmd in enumerate(commands):\n s = cmd.strip()\n if not s or s.startswith("!"):\n results.append({"index": i, "command": cmd,\n "output": "", "success": True, "skipped": True})\n continue\n log.info(f" [{i+1}/{len(commands)}] {s}")\n out, had_err = _run_one(ch, s)\n results.append({"index": i, "command": cmd,\n "output": out, "success": not had_err, "skipped": False})\n if had_err:\n stopped_at = i\n log.warning(f" Error at command {i+1}: {out}")\n break\n\n _run_one(ch, "end")\n saved = False\n if stopped_at is None:\n _, save_err = _run_one(ch, "copy running-config nvram:config.cfg")\n saved = not save_err\n if saved:\n log.info("Config saved to NVRAM")\n else:\n log.warning("Config save may have failed — verify at console")\n else:\n log.warning("Config NOT saved — push stopped on error")\n\n ch.close()\n return {\n "success": stopped_at is None,\n "saved": saved,\n "commands_total": len(commands),\n "commands_sent": len([r for r in results if not r.get("skipped")]),\n "stopped_at": stopped_at,\n "error": results[stopped_at]["output"] if stopped_at is not None else None,\n "hint": "Remaining commands must be run at the switch console" if stopped_at is not None else None,\n "results": results,\n }\n finally:\n client.close()\n # Pool will reopen on next poll naturally\n\n# ══════════════════════════════════════════════════════════════════════\n# VISITOR-AWARE POLLER\n# ══════════════════════════════════════════════════════════════════════\n\n_cache: dict = {\n "port_status": None, "poe_status": None,\n "vlan_members": None, "sys_info": None,\n "last_poll": 0, "poll_error": None,\n}\n_cache_lock = threading.Lock()\n\n# Visitor tracking\n_visitors: dict[str, float] = {} # { visitor_id: last_seen }\n_visitors_lock = threading.Lock()\n_poll_mode = "idle" # idle | active | background\n\ndef heartbeat(visitor_id: str, mode: str = "active"):\n """Called by frontend to indicate a visitor is present."""\n global _poll_mode\n with _visitors_lock:\n _visitors[visitor_id] = time.time()\n _poll_mode = mode\n\ndef prune_visitors():\n global _poll_mode\n with _visitors_lock:\n now = time.time()\n gone = [v for v, t in _visitors.items() if now - t > POLL_IDLE_AFTER]\n for v in gone:\n del _visitors[v]\n if not _visitors:\n _poll_mode = "idle"\n\ndef _poll_loop():\n log.info("Poller thread started")\n while True:\n prune_visitors()\n with _visitors_lock:\n mode = _poll_mode\n has_visitors = bool(_visitors)\n\n if not has_visitors:\n # No visitors — sleep and check again, don\'t poll switch\n time.sleep(30)\n continue\n\n # Poll the switch\n try:\n data = {\n "port_status": read_cmd("show interfaces"),\n "poe_status": read_cmd("show poe-port-status"),\n "vlan_members": read_cmd("show vlan members"),\n "sys_info": read_cmd("show sys-info"),\n }\n with _cache_lock:\n _cache.update(data)\n _cache["last_poll"] = time.time()\n _cache["poll_error"] = None\n except Exception as e:\n with _cache_lock:\n _cache["poll_error"] = str(e)\n log.warning(f"Poll error: {e}")\n\n interval = POLL_ACTIVE_S if mode == "active" else POLL_BG_S\n time.sleep(interval)\n\ndef start_poller():\n t = threading.Thread(target=_poll_loop, daemon=True)\n t.start()\n log.info("Poller started")\n\n# ══════════════════════════════════════════════════════════════════════\n# PYDANTIC MODELS\n# ══════════════════════════════════════════════════════════════════════\n\nclass TotpVerify(BaseModel):\n code: str\n\nclass SessionCheck(BaseModel):\n token: str\n\nclass SessionRevoke(BaseModel):\n token: str\n\nclass Heartbeat(BaseModel):\n visitor_id: str\n mode: str = "active" # active | background\n\nclass PushBatch(BaseModel):\n token: str\n commands: list[str]\n\nclass VlanCreate(BaseModel):\n token: str\n vlan_id: int\n name: str\n @field_validator("vlan_id")\n @classmethod\n def cv(cls, v): return san_vid(v)\n @field_validator("name")\n @classmethod\n def cn(cls, v): return _san(v, _RE_VNAME, "name")\n\nclass VlanDelete(BaseModel):\n token: str\n vlan_id: int\n @field_validator("vlan_id")\n @classmethod\n def cv(cls, v):\n vid = san_vid(v)\n if vid == 1: raise ValueError("Cannot delete VLAN 1")\n return vid\n\nclass AclRule(BaseModel):\n action: str\n proto: str\n src: Optional[str] = "any"\n src_mask: Optional[str] = "0.0.0.255"\n src_any: Optional[bool] = True\n dst: Optional[str] = "any"\n dst_mask: Optional[str] = "0.0.0.255"\n dst_any: Optional[bool] = True\n port: Optional[str] = ""\n @field_validator("action")\n @classmethod\n def ca(cls, v): return _san(v, _RE_ACTION, "action")\n @field_validator("proto")\n @classmethod\n def cp(cls, v): return _san(v, _RE_PROTO, "proto")\n\nclass AclCreate(BaseModel):\n token: str\n name: str\n apply_vlan: int\n direction: str\n rules: list[AclRule]\n @field_validator("name")\n @classmethod\n def cn(cls, v): return _san(v, _RE_ANAME, "name")\n @field_validator("direction")\n @classmethod\n def cd(cls, v): return _san(v, _RE_DIR, "direction")\n\nclass PortConfig(BaseModel):\n token: str\n port: int\n mode: str\n access_vlan: Optional[int] = 1\n tagged_vlans: Optional[list[int]] = []\n native_vlan: Optional[int] = 1\n poe: Optional[bool] = True\n poe_limit_mw: Optional[int] = 30000\n description: Optional[str] = ""\n @field_validator("port")\n @classmethod\n def cp(cls, v): return san_port(v)\n @field_validator("mode")\n @classmethod\n def cm(cls, v): return _san(v, _RE_MODE, "mode")\n @field_validator("poe_limit_mw")\n @classmethod\n def cpoe(cls, v):\n if v is not None and not 1000 <= v <= 30000:\n raise ValueError("PoE limit: 1000–30000 mW")\n return v\n\n# ══════════════════════════════════════════════════════════════════════\n# COMMAND BUILDERS\n# ══════════════════════════════════════════════════════════════════════\n\ndef build_port(cfg: PortConfig) -> list[str]:\n p = cfg.port\n iface = f"FastEthernet {p}" if p <= 48 else f"GigabitEthernet {p}"\n cmds = []\n if cfg.description:\n cmds += [f"interface {iface}", f\' name "{cfg.description}"\']\n if cfg.mode == "disabled":\n cmds += [f"interface {iface}", " shutdown"]\n elif cfg.mode == "access":\n vid = san_vid(cfg.access_vlan, "access_vlan")\n cmds += [f"vlan members add {vid} {p}", f"vlan pvid {p} {vid}"]\n elif cfg.mode == "trunk":\n native = san_vid(cfg.native_vlan, "native_vlan")\n tagged = [san_vid(v, f"tagged_{v}") for v in (cfg.tagged_vlans or [])]\n if tagged:\n ts = ",".join(str(v) for v in tagged)\n cmds += [f"vlan members add {ts} {p}", f"vlan tagging {ts} {p}"]\n cmds.append(f"vlan pvid {p} {native}")\n if p <= 48:\n cmds += [f"interface {iface}",\n " poe enable" if cfg.poe else " no poe enable"]\n if cfg.poe:\n cmds.append(f" poe poe-limit {cfg.poe_limit_mw}")\n return cmds\n\ndef build_acl(acl: AclCreate) -> list[str]:\n cmds = [f"ip access-list extended {acl.name}"]\n for i, r in enumerate(acl.rules):\n src = "any" if r.src_any else f"{r.src} {r.src_mask}"\n dst = "any" if r.dst_any else f"{r.dst} {r.dst_mask}"\n port_str = f" eq {r.port}" if r.port else ""\n cmds.append(f" {i+1} {r.action} {r.proto} {src} {dst}{port_str}")\n vid = san_vid(acl.apply_vlan, "apply_vlan")\n cmds += [f"interface vlan {vid}",\n f" ip access-group {acl.name} {acl.direction}"]\n return cmds\n\n# ══════════════════════════════════════════════════════════════════════\n# APP\n# ══════════════════════════════════════════════════════════════════════\n\napp = FastAPI(title="ERS 5952 Switch Manager", version="3.0.0",\n docs_url="/api/docs", redoc_url=None)\n\napp.add_middleware(CORSMiddleware, allow_origins=ALLOWED_ORIGINS,\n allow_methods=["GET","POST","DELETE"],\n allow_headers=["Content-Type"])\n\n@app.exception_handler(ValueError)\nasync def val_err(req: Request, exc: ValueError):\n return JSONResponse(400, {"detail": str(exc)})\n\n@app.on_event("startup")\ndef startup():\n global TOTP_SECRET\n TOTP_SECRET = get_or_create_totp_secret()\n log.info("TOTP secret loaded")\n start_poller()\n\n# ── Heartbeat (visitor tracking) ──────────────────────────────────────\n\n@app.post("/api/heartbeat")\ndef hb(body: Heartbeat):\n """\n Frontend calls this every 30s to indicate visitor is present.\n mode = \'active\' when tab is visible, \'background\' when hidden.\n Poller adjusts interval accordingly.\n """\n heartbeat(body.visitor_id, body.mode)\n with _cache_lock:\n last = _cache["last_poll"]\n err = _cache["poll_error"]\n return {\n "poll_mode": _poll_mode,\n "last_poll": last,\n "poll_age": round(time.time() - last, 1) if last else None,\n "poll_error": err,\n }\n\n# ── Auth ───────────────────────────────────────────────────────────────\n\n@app.post("/api/auth/verify")\ndef verify_totp(body: TotpVerify):\n """Verify TOTP code — returns session token for multiple pushes."""\n if not pyotp.TOTP(TOTP_SECRET).verify(body.code.strip(), valid_window=1):\n log.warning("TOTP verify failed")\n raise HTTPException(401, "Invalid TOTP code")\n token = create_session()\n log.info("TOTP OK — session created")\n return {\n "token": token,\n "expires_in": SESSION_TTL_S,\n "message": "Session active — re-authenticates on expiry or manual lock"\n }\n\n@app.post("/api/auth/check")\ndef check_session(body: SessionCheck):\n """Check if a session is still valid. Returns remaining seconds."""\n remaining = session_remaining(body.token)\n if remaining is None:\n raise HTTPException(401, "Session expired")\n return {"valid": True, "remaining": remaining}\n\n@app.post("/api/auth/revoke")\ndef revoke(body: SessionRevoke):\n """Manually lock — invalidates the session immediately."""\n revoke_session(body.token)\n log.info("Session manually revoked")\n return {"revoked": True}\n\n# ── Read endpoints (no auth) ───────────────────────────────────────────\n\n@app.get("/api/status")\ndef status():\n with _cache_lock:\n return {\n "backend": "online",\n "switch_host": SWITCH_HOST,\n "key_exists": Path(KEY_PATH).exists(),\n "known_hosts_pinned": Path(KNOWN_HOSTS).exists(),\n "last_poll": _cache["last_poll"],\n "poll_age": round(time.time() - _cache["last_poll"], 1)\n if _cache["last_poll"] else None,\n "poll_error": _cache["poll_error"],\n "poll_mode": _poll_mode,\n }\n\n@app.get("/api/live")\ndef live():\n """Cached live switch data — updated by background poller."""\n with _cache_lock:\n age = time.time() - _cache["last_poll"] if _cache["last_poll"] else None\n return {\n **_cache,\n "stale": age is None or age > max(POLL_ACTIVE_S, POLL_BG_S) * 3\n }\n\n@app.get("/api/switch/config")\ndef running_config():\n out = read_cmd("show running-config")\n return {"config": out, "lines": len(out.splitlines())}\n\n# ── Danger pre-flight (no auth — check before prompting TOTP) ─────────\n\n@app.post("/api/check/danger")\ndef danger_check(body: dict):\n cmds = body.get("commands", [])\n result = check_danger(cmds)\n rejected = [c for c in cmds if not is_allowed(c)]\n result["rejected_by_allowlist"] = rejected\n result["safe_to_push"] = (\n not result["has_hard_block"] and not rejected\n )\n return result\n\n# ── Push endpoints (require session token) ────────────────────────────\n\n@app.post("/api/switch/push")\ndef push(body: PushBatch):\n """\n Push CLI batch one command at a time.\n Requires valid session token.\n Hard-blocked commands are refused — no override.\n Warn-level commands proceed (user was already shown the warning).\n Stops on first switch error. Config saved only on full success.\n """\n require_session(body.token)\n\n danger = check_danger(body.commands)\n if danger["has_hard_block"]:\n raise HTTPException(400, {\n "message": "Hard-blocked commands detected — these must be run at the switch console",\n "blocked": danger["hard_blocked"],\n })\n\n rejected = [c for c in body.commands if not is_allowed(c)]\n if rejected:\n raise HTTPException(400, {\n "message": "Commands failed allowlist validation",\n "rejected": rejected[:10],\n })\n\n log.info(f"Push: {len(body.commands)} commands")\n return push_one_by_one(body.commands)\n\n@app.post("/api/switch/vlan")\ndef create_vlan(body: VlanCreate):\n require_session(body.token)\n return push_one_by_one(\n [f\'vlan create {body.vlan_id} name "{body.name}" type port\'])\n\n@app.delete("/api/switch/vlan/{vlan_id}")\ndef delete_vlan(vlan_id: int, token: str):\n require_session(token)\n return push_one_by_one([f"no vlan {san_vid(vlan_id)}"])\n\n@app.post("/api/switch/port")\ndef configure_port(body: PortConfig):\n require_session(body.token)\n return push_one_by_one(build_port(body))\n\n@app.post("/api/switch/acl")\ndef create_acl(body: AclCreate):\n require_session(body.token)\n return push_one_by_one(build_acl(body))\n\n# ── Serve React app ────────────────────────────────────────────────────\nif os.path.isdir(STATIC_DIR):\n app.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="frontend")\n\n# ══════════════════════════════════════════════════════════════════════\nif __name__ == "__main__":\n if "--setup-totp" in sys.argv:\n setup_totp()\n sys.exit(0)\n import uvicorn\n uvicorn.run("switch_backend:app", host="0.0.0.0", port=8765,\n log_level="info")\n\n# ══════════════════════════════════════════════════════════════════════\n# DEVICE ACCESS — DHCP LEASES, MAC RESERVATIONS, ACL PINHOLES\n# ══════════════════════════════════════════════════════════════════════\n\nimport json as _json\nfrom pathlib import Path as _Path\n\nDEVICES_FILE = _Path("/etc/switch-manager/devices.json")\n\ndef _load_devices() -> list:\n if DEVICES_FILE.exists():\n try: return _json.loads(DEVICES_FILE.read_text())\n except: pass\n return []\n\ndef _save_devices(devices: list):\n DEVICES_FILE.write_text(_json.dumps(devices, indent=2))\n\ndef _parse_dhcp_leases(raw: str) -> list:\n """Parse ERS 5952 \'show dhcp-server leases\' output."""\n import re\n leases = []\n for line in raw.splitlines():\n # Format: IP MAC State Remaining Hostname\n m = re.match(\n r\'\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+\'\n r\'([0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}\'\n r\'[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2})\\s+\'\n r\'(\\S+)\\s+(\\S+)\\s*(.*)\', line)\n if m:\n leases.append({\n "ip": m.group(1),\n "mac": m.group(2).lower().replace(\'-\',\':\'),\n "state": m.group(3),\n "remaining": m.group(4),\n "hostname": m.group(5).strip() or "unknown",\n })\n return leases\n\ndef _parse_arp_table(raw: str) -> list:\n """Parse \'show arp\' for additional device discovery."""\n import re\n entries = []\n for line in raw.splitlines():\n m = re.match(\n r\'\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+\'\n r\'([0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}\'\n r\'[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2}[:\\-][0-9a-fA-F]{2})\',\n line)\n if m:\n entries.append({\n "ip": m.group(1),\n "mac": m.group(2).lower().replace(\'-\',\':\'),\n "state": "arp",\n "remaining": "-",\n "hostname": "",\n })\n return entries\n\nclass DeviceEntry(BaseModel):\n name: str\n mac: str\n ip: str\n vlan: int = 10\n management_access: bool = False\n static_ip: bool = False\n notes: Optional[str] = ""\n\nclass DeviceUpdate(BaseModel):\n token: str\n device: DeviceEntry\n\nclass DeviceDelete(BaseModel):\n token: str\n mac: str\n\nclass PinholeRequest(BaseModel):\n token: str\n mac: str\n allow: bool = True\n\ndef _build_dhcp_reservation_cmds(device: DeviceEntry) -> list:\n """Generate ERS 5952 CLI for DHCP reservation (static binding)."""\n mac_clean = device.mac.replace(\':\',\'-\').upper()\n return [\n f"ip dhcp-server static-binding {device.ip}",\n f" mac-address {mac_clean}",\n f" client-name \\"{device.name}\\"",\n ]\n\ndef _build_pinhole_acl_cmds(device: DeviceEntry, mgmt_ip: str, allow: bool) -> list:\n """Generate ACL commands to allow/deny a device IP to reach management."""\n acl_name = f"MGMT-ACCESS"\n if allow:\n return [\n f"ip access-list extended {acl_name}",\n f" permit tcp host {device.ip} host {mgmt_ip} eq 443",\n f" permit tcp host {device.ip} host {mgmt_ip} eq 8765",\n ]\n else:\n return [\n f"ip access-list extended {acl_name}",\n f" no permit tcp host {device.ip} host {mgmt_ip}",\n ]\n\n@app.get("/api/devices")\ndef get_devices():\n """Return saved device list plus live DHCP leases from switch."""\n saved = _load_devices()\n live_leases = []\n try:\n dhcp_raw = read_cmd("show dhcp-server leases")\n arp_raw = read_cmd("show arp")\n live_leases = _parse_dhcp_leases(dhcp_raw)\n # Merge ARP entries not already in leases\n arp = _parse_arp_table(arp_raw)\n lease_ips = {l["ip"] for l in live_leases}\n for entry in arp:\n if entry["ip"] not in lease_ips:\n live_leases.append(entry)\n except Exception as e:\n log.warning(f"Could not pull DHCP/ARP from switch: {e}")\n return {\n "saved": saved,\n "live": live_leases,\n "mgmt_ip": SWITCH_HOST,\n }\n\n@app.post("/api/devices/save")\ndef save_device(body: DeviceUpdate):\n require_session(body.token)\n devices = _load_devices()\n existing = next((i for i, d in enumerate(devices) if d["mac"] == body.device.mac), None)\n device_dict = body.device.dict()\n if existing is not None:\n devices[existing] = device_dict\n else:\n devices.append(device_dict)\n _save_devices(devices)\n log.info(f"Device saved: {body.device.name} ({body.device.mac})")\n return {"success": True, "devices": devices}\n\n@app.post("/api/devices/delete")\ndef delete_device(body: DeviceDelete):\n require_session(body.token)\n devices = [d for d in _load_devices() if d["mac"] != body.mac]\n _save_devices(devices)\n return {"success": True}\n\n@app.post("/api/devices/push-reservation")\ndef push_reservation(body: DeviceUpdate):\n """Push a DHCP static binding for this device to the switch."""\n require_session(body.token)\n cmds = _build_dhcp_reservation_cmds(body.device)\n danger = check_danger(cmds)\n if danger["has_hard_block"]:\n raise HTTPException(400, {"message": "Blocked", "blocked": danger["hard_blocked"]})\n log.info(f"Pushing DHCP reservation for {body.device.name}")\n return push_one_by_one(cmds)\n\n@app.post("/api/devices/push-pinhole")\ndef push_pinhole(body: PinholeRequest):\n """Add or remove an ACL pinhole for a device to reach management."""\n require_session(body.token)\n devices = _load_devices()\n device = next((DeviceEntry(**d) for d in devices if d["mac"] == body.mac), None)\n if not device:\n raise HTTPException(404, "Device not found — save it first")\n import socket\n try:\n mgmt_ip = socket.gethostbyname(socket.gethostname())\n except Exception:\n mgmt_ip = SWITCH_HOST.rsplit(\'.\',1)[0] + \'.50\'\n cmds = _build_pinhole_acl_cmds(device, mgmt_ip, body.allow)\n log.info(f"Pinhole {\'allow\' if body.allow else \'deny\'} for {device.name} ({device.ip})")\n return push_one_by_one(cmds)\n\n# ══════════════════════════════════════════════════════════════════════\n# WIREGUARD PEER MANAGEMENT\n# ══════════════════════════════════════════════════════════════════════\n\nWG_CLIENT_DIR_API = _Path("/etc/switch-manager/clients")\nWG_CONF_PATH = _Path("/etc/wireguard/wg0.conf")\n\nclass WGClientRequest(BaseModel):\n token: str\n name: str\n\nclass WGRevokeRequest(BaseModel):\n token: str\n name: str\n\ndef _wg_genkey_api():\n import subprocess as _sp\n priv = _sp.run(["wg","genkey"], capture_output=True, text=True).stdout.strip()\n pub = _sp.run(["wg","pubkey"], input=priv, capture_output=True, text=True).stdout.strip()\n return priv, pub\n\ndef _wg_status() -> dict:\n import subprocess as _sp\n try:\n raw = _sp.run(["wg","show"], capture_output=True, text=True).stdout\n peers = []\n current = {}\n for line in raw.splitlines():\n line = line.strip()\n if line.startswith("peer:"):\n if current: peers.append(current)\n current = {"public_key": line.split(":",1)[1].strip()}\n elif line.startswith("endpoint:"):\n current["endpoint"] = line.split(":",1)[1].strip()\n elif line.startswith("latest handshake:"):\n current["last_handshake"] = line.split(":",1)[1].strip()\n elif line.startswith("transfer:"):\n current["transfer"] = line.split(":",1)[1].strip()\n elif line.startswith("allowed ips:"):\n current["allowed_ips"] = line.split(":",1)[1].strip()\n if current: peers.append(current)\n\n # Match peers to named client files\n named = {}\n if WG_CLIENT_DIR_API.exists():\n for f in WG_CLIENT_DIR_API.glob("*.conf"):\n txt = f.read_text()\n import re\n m = re.search(r\'PublicKey\\s*=\\s*(\\S+)\', txt)\n if m: named[m.group(1)] = f.stem\n\n for p in peers:\n p["name"] = named.get(p.get("public_key",""), "unknown")\n\n return {"running": True, "peers": peers}\n except Exception as e:\n return {"running": False, "error": str(e), "peers": []}\n\n@app.get("/api/wireguard/status")\ndef wg_status():\n return _wg_status()\n\n@app.get("/api/wireguard/clients")\ndef wg_clients():\n clients = []\n if WG_CLIENT_DIR_API.exists():\n for f in sorted(WG_CLIENT_DIR_API.glob("*.conf")):\n clients.append({"name": f.stem, "file": str(f)})\n return {"clients": clients}\n\n@app.post("/api/wireguard/add-client")\ndef wg_add_client(body: WGClientRequest):\n require_session(body.token)\n if not WG_CONF_PATH.exists():\n raise HTTPException(503, "WireGuard not configured on this machine")\n\n import re, subprocess as _sp, socket\n\n # Next available IP\n conf_text = WG_CONF_PATH.read_text()\n used = set()\n for m in re.finditer(r\'AllowedIPs\\s*=\\s*(\\S+)\', conf_text):\n used.add(m.group(1).split(\'/\')[0])\n\n subnet = "10.99.0"\n num = 2\n while f"{subnet}.{num}" in used and num < 254: num += 1\n client_ip = f"{subnet}.{num}"\n\n # Server public key\n server_pub_path = _Path("/etc/switch-manager/wg_server_public")\n if not server_pub_path.exists():\n raise HTTPException(503, "Server public key not found")\n server_pub = server_pub_path.read_text().strip()\n\n # Client keys\n c_priv, c_pub = _wg_genkey_api()\n\n # Peer entry in server config\n peer = f"\\n[Peer]\\n# {body.name}\\nPublicKey = {c_pub}\\nAllowedIPs = {client_ip}/32\\n"\n with open(WG_CONF_PATH, \'a\') as f:\n f.write(peer)\n\n # Reload live\n _sp.run(["wg","addconf","wg0","/dev/stdin"],\n input=f"[Peer]\\nPublicKey = {c_pub}\\nAllowedIPs = {client_ip}/32\\n",\n capture_output=True, text=True)\n\n # Public IP for endpoint\n try:\n pub_ip = _sp.run(["curl","-s","--max-time","5","https://api.ipify.org"],\n capture_output=True, text=True).stdout.strip()\n except Exception:\n pub_ip = socket.gethostbyname(socket.gethostname())\n\n # Get management IP from switch config\n mgmt_subnet = \'.\'.join(SWITCH_HOST.split(\'.\')[:3]) + \'.0/24\'\n\n client_conf = (\n f"[Interface]\\nPrivateKey = {c_priv}\\nAddress = {client_ip}/24\\n"\n f"DNS = {subnet}.1\\n\\n"\n f"[Peer]\\nPublicKey = {server_pub}\\n"\n f"Endpoint = {pub_ip}:51820\\n"\n f"AllowedIPs = {mgmt_subnet}, {subnet}.0/24\\n"\n f"PersistentKeepalive = 25\\n"\n )\n\n WG_CLIENT_DIR_API.mkdir(exist_ok=True)\n client_file = WG_CLIENT_DIR_API / f"{body.name}.conf"\n client_file.write_text(client_conf)\n client_file.chmod(0o600)\n\n log.info(f"WireGuard client added: {body.name} → {client_ip}")\n return {\n "success": True,\n "name": body.name,\n "client_ip": client_ip,\n "config": client_conf,\n "file": str(client_file),\n }\n\n@app.post("/api/wireguard/revoke-client")\ndef wg_revoke_client(body: WGRevokeRequest):\n require_session(body.token)\n import re, subprocess as _sp\n\n client_file = WG_CLIENT_DIR_API / f"{body.name}.conf"\n if not client_file.exists():\n raise HTTPException(404, f"Client \'{body.name}\' not found")\n\n # Get client public key\n txt = client_file.read_text()\n m = re.search(r\'\\[Peer\\].*?PublicKey\\s*=\\s*(\\S+)\', txt, re.DOTALL)\n client_pub = m.group(1) if m else None\n\n # Remove from server config\n if WG_CONF_PATH.exists():\n conf = WG_CONF_PATH.read_text()\n # Remove the [Peer] block for this client\n cleaned = re.sub(\n rf\'\\n\\[Peer\\]\\n# {re.escape(body.name)}\\n.*?(?=\\n\\[Peer\\]|\\Z)\',\n \'\', conf, flags=re.DOTALL\n )\n WG_CONF_PATH.write_text(cleaned)\n\n # Remove live peer\n if client_pub:\n _sp.run(["wg","set","wg0","peer",client_pub,"remove"],\n capture_output=True, text=True)\n\n # Delete client file\n client_file.unlink()\n log.info(f"WireGuard client revoked: {body.name}")\n return {"success": True}\n\n@app.get("/api/wireguard/client-qr/{name}")\ndef wg_client_qr(name: str):\n """Return client config as text for QR generation in frontend."""\n client_file = WG_CLIENT_DIR_API / f"{name}.conf"\n if not client_file.exists():\n raise HTTPException(404, f"Client \'{name}\' not found")\n return {"name": name, "config": client_file.read_text()}\n\n# ══════════════════════════════════════════════════════════════════════\n# DHCP MANAGEMENT — SWITCH + OPNSENSE UNIFIED VIEW\n# ══════════════════════════════════════════════════════════════════════\n\nimport urllib.request as _urlreq\nimport urllib.error as _urlerr\nimport ssl as _ssl\nimport base64 as _b64\n\nOPNSENSE_FILE = _Path("/etc/switch-manager/opnsense.json")\n\ndef _load_opnsense_cfg() -> dict:\n if OPNSENSE_FILE.exists():\n try: return _json.loads(OPNSENSE_FILE.read_text())\n except: pass\n return {}\n\ndef _save_opnsense_cfg(cfg: dict):\n OPNSENSE_FILE.write_text(_json.dumps(cfg, indent=2))\n OPNSENSE_FILE.chmod(0o600)\n\ndef _opnsense_request(cfg: dict, path: str, method="GET", body=None) -> dict:\n """Make an authenticated request to the OPNsense API."""\n host = cfg.get("host","")\n key = cfg.get("key","")\n secret = cfg.get("secret","")\n if not host or not key or not secret:\n raise ValueError("OPNsense not configured")\n url = f"https://{host}/api/{path}"\n creds = _b64.b64encode(f"{key}:{secret}".encode()).decode()\n ctx = _ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = _ssl.CERT_NONE\n headers = {\n "Authorization": f"Basic {creds}",\n "Content-Type": "application/json",\n }\n data = _json.dumps(body).encode() if body else None\n req = _urlreq.Request(url, data=data, headers=headers, method=method)\n try:\n with _urlreq.urlopen(req, timeout=5, context=ctx) as r:\n return _json.loads(r.read().decode())\n except _urlerr.HTTPError as e:\n raise ValueError(f"OPNsense API error {e.code}: {e.reason}")\n except Exception as e:\n raise ValueError(f"OPNsense unreachable: {e}")\n\ndef _detect_opnsense_host(gateway_ip: str) -> str | None:\n """Try to reach OPNsense API at the gateway IP."""\n try:\n ctx = _ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = _ssl.CERT_NONE\n url = f"https://{gateway_ip}/api/core/firmware/status"\n req = _urlreq.Request(url, headers={"User-Agent":"switch-manager/1"})\n _urlreq.urlopen(req, timeout=3, context=ctx)\n return gateway_ip\n except Exception:\n return None\n\ndef _get_opnsense_reservations(cfg: dict) -> list:\n """Fetch DHCP static mappings from OPNsense."""\n try:\n data = _opnsense_request(cfg, "dhcpv4/leases/searchReservation")\n rows = data.get("rows", [])\n return [\n {\n "ip": r.get("ipaddr",""),\n "mac": r.get("mac","").lower(),\n "hostname": r.get("hostname",""),\n "descr": r.get("descr",""),\n "if": r.get("if",""),\n "source": "opnsense",\n "uuid": r.get("uuid",""),\n }\n for r in rows if r.get("mac")\n ]\n except Exception as e:\n log.warning(f"OPNsense reservations fetch failed: {e}")\n return []\n\ndef _get_opnsense_leases(cfg: dict) -> list:\n """Fetch active DHCP leases from OPNsense."""\n try:\n data = _opnsense_request(cfg, "dhcpv4/leases/searchLease")\n rows = data.get("rows", [])\n return [\n {\n "ip": r.get("address",""),\n "mac": r.get("mac","").lower(),\n "hostname": r.get("hostname",""),\n "state": r.get("state",""),\n "if": r.get("if",""),\n "source": "opnsense_lease",\n }\n for r in rows if r.get("mac")\n ]\n except Exception as e:\n log.warning(f"OPNsense leases fetch failed: {e}")\n return []\n\ndef _get_switch_reservations() -> list:\n """Fetch DHCP static bindings from ERS 5952."""\n import re as _re\n try:\n raw = read_cmd("show dhcp-server static-binding")\n bindings = []\n current = {}\n for line in raw.splitlines():\n m = _re.match(r\'\\s*IP Address:\\s*(\\S+)\', line)\n if m:\n if current: bindings.append(current)\n current = {"ip": m.group(1), "mac":"", "hostname":"", "source":"switch"}\n m2 = _re.match(r\'\\s*MAC Address:\\s*(\\S+)\', line)\n if m2 and current:\n current["mac"] = m2.group(1).lower().replace(\'-\',\':\')\n m3 = _re.match(r\'\\s*Client Name:\\s*(\\S+)\', line)\n if m3 and current:\n current["hostname"] = m3.group(1)\n if current and current.get("ip"):\n bindings.append(current)\n return bindings\n except Exception as e:\n log.warning(f"Switch DHCP reservation fetch failed: {e}")\n return []\n\ndef _get_switch_dhcp_status() -> dict:\n """Check if switch DHCP server is running and which VLANs it serves."""\n import re as _re\n try:\n raw = read_cmd("show dhcp-server")\n running = "enabled" in raw.lower() or "active" in raw.lower()\n vlans = _re.findall(r\'VLAN\\s+(\\d+)\', raw, _re.I)\n return {"running": running, "vlans": list(set(vlans))}\n except Exception:\n return {"running": False, "vlans": []}\n\ndef _find_conflicts(switch_res: list, opnsense_res: list) -> list:\n """\n Find same MAC in both switch and OPNsense.\n Flag if IPs differ (conflict) or same (duplicate — harmless but messy).\n """\n switch_by_mac = {r["mac"]: r for r in switch_res if r.get("mac")}\n conflicts = []\n for r in opnsense_res:\n mac = r.get("mac","")\n if mac and mac in switch_by_mac:\n sw = switch_by_mac[mac]\n conflicts.append({\n "mac": mac,\n "hostname": r.get("hostname") or sw.get("hostname",""),\n "switch_ip": sw["ip"],\n "opnsense_ip": r["ip"],\n "ip_conflict": sw["ip"] != r["ip"],\n "opnsense_uuid": r.get("uuid",""),\n })\n return conflicts\n\n# ── OPNsense config models ─────────────────────────────────────────────────\n\nclass OPNsenseConfig(BaseModel):\n host: str\n key: str\n secret: str\n\nclass OPNsenseReservationPush(BaseModel):\n token: str\n mac: str\n ip: str\n hostname: str\n descr: Optional[str] = ""\n iface: Optional[str] = "lan"\n\nclass SyncRequest(BaseModel):\n token: str\n mac: str\n direction: str # "to_switch" | "to_opnsense" | "remove_switch" | "remove_opnsense"\n\n# ── DHCP endpoints ─────────────────────────────────────────────────────────\n\n@app.get("/api/dhcp/overview")\ndef dhcp_overview():\n """\n Unified DHCP view:\n - Switch static bindings + active leases\n - OPNsense reservations + leases (if configured)\n - Conflicts (same MAC, different IP)\n - Which DHCP server is active per VLAN\n """\n switch_res = _get_switch_reservations()\n switch_leases = []\n switch_status = _get_switch_dhcp_status()\n\n # Also pull ARP for discovery\n try:\n arp_raw = read_cmd("show arp")\n dhcp_raw = read_cmd("show dhcp-server leases")\n switch_leases = _parse_dhcp_leases(dhcp_raw) + _parse_arp_table(arp_raw)\n # Deduplicate by IP\n seen_ips = set()\n unique_leases = []\n for l in switch_leases:\n if l["ip"] not in seen_ips:\n seen_ips.add(l["ip"])\n unique_leases.append(l)\n switch_leases = unique_leases\n except Exception as e:\n log.warning(f"Switch lease fetch failed: {e}")\n\n cfg = _load_opnsense_cfg()\n opnsense_res = _get_opnsense_reservations(cfg) if cfg.get("key") else []\n opnsense_leases = _get_opnsense_leases(cfg) if cfg.get("key") else []\n conflicts = _find_conflicts(switch_res, opnsense_res)\n\n # Which VLANs have switch DHCP vs OPNsense\n # Switch DHCP VLANs from status, OPNsense VLANs inferred from interface names\n opnsense_ifaces = list({r.get("if","") for r in opnsense_res + opnsense_leases if r.get("if")})\n\n return {\n "switch": {\n "status": switch_status,\n "reservations": switch_res,\n "leases": switch_leases,\n },\n "opnsense": {\n "configured": bool(cfg.get("key")),\n "host": cfg.get("host",""),\n "reservations": opnsense_res,\n "leases": opnsense_leases,\n "interfaces": opnsense_ifaces,\n },\n "conflicts": conflicts,\n "has_conflicts": len(conflicts) > 0,\n }\n\n@app.get("/api/dhcp/detect-opnsense")\ndef detect_opnsense_endpoint():\n """Auto-detect OPNsense at the gateway IP."""\n import re as _re\n try:\n route = read_cmd("show ip route default")\n m = _re.search(r\'(\\d+\\.\\d+\\.\\d+\\.\\d+)\', route)\n gateway = m.group(1) if m else None\n except Exception:\n gateway = None\n\n if not gateway:\n # Try from switch management IP\n parts = SWITCH_HOST.split(\'.\')\n parts[-1] = \'1\'\n gateway = \'.\'.join(parts)\n\n host = _detect_opnsense_host(gateway)\n return {\n "detected": host is not None,\n "host": host,\n "gateway": gateway,\n "configured": bool(_load_opnsense_cfg().get("key")),\n }\n\n@app.post("/api/dhcp/configure-opnsense")\ndef configure_opnsense(body: OPNsenseConfig):\n """Save OPNsense API credentials. Tests connectivity first."""\n cfg = {"host": body.host, "key": body.key, "secret": body.secret}\n try:\n result = _opnsense_request(cfg, "core/firmware/status")\n _save_opnsense_cfg(cfg)\n log.info(f"OPNsense configured: {body.host}")\n return {"success": True, "version": result.get("product_version","unknown")}\n except ValueError as e:\n raise HTTPException(400, str(e))\n\n@app.delete("/api/dhcp/configure-opnsense")\ndef remove_opnsense_config():\n """Remove OPNsense API credentials."""\n if OPNSENSE_FILE.exists():\n OPNSENSE_FILE.unlink()\n return {"success": True}\n\n@app.post("/api/dhcp/push-to-opnsense")\ndef push_reservation_to_opnsense(body: OPNsenseReservationPush):\n """Create a DHCP static mapping in OPNsense."""\n require_session(body.token)\n cfg = _load_opnsense_cfg()\n if not cfg.get("key"):\n raise HTTPException(503, "OPNsense not configured")\n try:\n result = _opnsense_request(cfg, "dhcpv4/reservations/addReservation", "POST", {\n "reservation": {\n "interface": body.iface,\n "mac": body.mac,\n "ipaddr": body.ip,\n "hostname": body.hostname,\n "descr": body.descr or f"Added by switch-manager",\n }\n })\n # Apply changes\n _opnsense_request(cfg, "dhcpv4/service/reconfigure", "POST")\n log.info(f"OPNsense reservation pushed: {body.mac} → {body.ip}")\n return {"success": True, "result": result}\n except ValueError as e:\n raise HTTPException(400, str(e))\n\n@app.post("/api/dhcp/sync")\ndef sync_reservation(body: SyncRequest):\n """\n Sync a reservation between switch and OPNsense.\n Directions:\n to_switch — copy OPNsense reservation to switch\n to_opnsense — copy switch reservation to OPNsense\n remove_switch — remove from switch only\n remove_opnsense — remove from OPNsense only\n """\n require_session(body.token)\n cfg = _load_opnsense_cfg()\n overview = dhcp_overview()\n\n # Find the device in both sources\n sw_res = next((r for r in overview["switch"]["reservations"] if r["mac"]==body.mac), None)\n ops_res = next((r for r in overview["opnsense"]["reservations"] if r["mac"]==body.mac), None)\n\n if body.direction == "to_switch":\n if not ops_res:\n raise HTTPException(404, "OPNsense reservation not found")\n cmds = _build_dhcp_reservation_cmds(type(\'D\',(),{\n "ip": ops_res["ip"], "mac": ops_res["mac"], "name": ops_res.get("hostname","")\n })())\n return push_one_by_one(cmds)\n\n elif body.direction == "to_opnsense":\n if not sw_res:\n raise HTTPException(404, "Switch reservation not found")\n if not cfg.get("key"):\n raise HTTPException(503, "OPNsense not configured")\n result = _opnsense_request(cfg, "dhcpv4/reservations/addReservation", "POST", {\n "reservation": {\n "mac": sw_res["mac"], "ipaddr": sw_res["ip"],\n "hostname": sw_res.get("hostname",""), "descr": "Synced from switch",\n "interface": "lan",\n }\n })\n _opnsense_request(cfg, "dhcpv4/service/reconfigure", "POST")\n return {"success": True, "result": result}\n\n elif body.direction == "remove_switch":\n if not sw_res:\n raise HTTPException(404, "Switch reservation not found")\n return push_one_by_one([f"no ip dhcp-server static-binding {sw_res[\'ip\']}"])\n\n elif body.direction == "remove_opnsense":\n if not ops_res or not ops_res.get("uuid"):\n raise HTTPException(404, "OPNsense reservation not found or missing UUID")\n if not cfg.get("key"):\n raise HTTPException(503, "OPNsense not configured")\n _opnsense_request(cfg, f"dhcpv4/reservations/delReservation/{ops_res[\'uuid\']}", "DELETE")\n _opnsense_request(cfg, "dhcpv4/service/reconfigure", "POST")\n return {"success": True}\n\n raise HTTPException(400, f"Unknown direction: {body.direction}")\n\n# ══════════════════════════════════════════════════════════════════════\n# CONTROL D / ctrld DNS MANAGEMENT\n# ══════════════════════════════════════════════════════════════════════\n\nCTRLD_FILE = _Path("/etc/switch-manager/ctrld.json")\nCTRLD_BIN = _Path("/usr/local/bin/ctrld")\n\ndef _load_ctrld_cfg() -> dict:\n if CTRLD_FILE.exists():\n try: return _json.loads(CTRLD_FILE.read_text())\n except: pass\n return {}\n\ndef _save_ctrld_cfg(cfg: dict):\n CTRLD_FILE.write_text(_json.dumps(cfg, indent=2))\n CTRLD_FILE.chmod(0o600)\n\ndef _ctrld_status() -> dict:\n """Check if ctrld is running and which mode."""\n import subprocess as _sp\n try:\n r = _sp.run([str(CTRLD_BIN), "status"],\n capture_output=True, text=True, timeout=5)\n running = r.returncode == 0\n return {\n "installed": CTRLD_BIN.exists(),\n "running": running,\n "output": r.stdout.strip() or r.stderr.strip(),\n }\n except Exception as e:\n return {\n "installed": CTRLD_BIN.exists(),\n "running": False,\n "output": str(e),\n }\n\ndef _ctrld_config_path() -> _Path:\n """Find ctrld config file location."""\n candidates = [\n _Path("/etc/controld/ctrld.toml"),\n _Path("/usr/local/etc/controld/ctrld.toml"),\n _Path.home() / ".config" / "controld" / "ctrld.toml",\n ]\n for p in candidates:\n if p.exists(): return p\n return candidates[0] # default for new install\n\ndef _build_ctrld_toml(vlan_profiles: list) -> str:\n """\n Build a ctrld.toml config for per-VLAN DNS filtering.\n Each VLAN gets its own upstream pointing to its Control D Resolver ID.\n Source IP routing directs traffic to the correct profile automatically.\n\n vlan_profiles: list of { vlan_id, name, subnet, resolver_id }\n """\n lines = [\n "# ctrld configuration — generated by Avaya 5952 Switch Manager",\n "# https://github.com/Control-D-Inc/ctrld",\n "",\n "[service]",\n \'name = "ctrld"\',\n "",\n "# Single listener on port 53 — all VLANs send DNS here",\n "[[listener]]",\n \'ip = "0.0.0.0"\',\n "port = 53",\n \'tag = "all-vlans"\',\n "",\n ]\n\n # One upstream per VLAN\n for vp in vlan_profiles:\n rid = vp.get("resolver_id","").strip()\n if not rid:\n continue\n tag = f"vlan{vp[\'vlan_id\']}"\n lines += [\n f"# VLAN {vp[\'vlan_id\']} — {vp[\'name\']}",\n f"[[upstream]]",\n f\'id = "{tag}"\',\n f\'type = "doh3"\',\n f\'endpoint = "https://dns.controld.com/{rid}"\',\n f\'tag = "{tag}"\',\n "",\n ]\n\n # Routing rules — match source subnet to upstream\n lines += ["# Route each VLAN subnet to its profile"]\n for vp in vlan_profiles:\n rid = vp.get("resolver_id","").strip()\n if not rid:\n continue\n subnet = vp.get("subnet", f"192.168.{vp[\'vlan_id\']}.0/24")\n tag = f"vlan{vp[\'vlan_id\']}"\n lines += [\n f"[[rule]]",\n f\'listener = "all-vlans"\',\n f\'source_ip = "{subnet}"\',\n f\'upstream = "{tag}"\',\n "",\n ]\n\n # Fallback upstream (first valid profile or safe default)\n first_valid = next((vp for vp in vlan_profiles if vp.get("resolver_id")), None)\n if first_valid:\n lines += [\n "# Fallback for unmatched source IPs",\n "[[upstream]]",\n f\'id = "fallback"\',\n f\'type = "doh3"\',\n f\'endpoint = "https://dns.controld.com/{first_valid["resolver_id"]}"\',\n f\'tag = "fallback"\',\n "",\n ]\n\n return "\\n".join(lines)\n\n# ── ctrld API models ────────────────────────────────────────────────────────\n\nclass CtrldVlanProfile(BaseModel):\n vlan_id: int\n name: str\n subnet: str\n resolver_id: str\n\nclass CtrldConfig(BaseModel):\n mode: str # "local" | "opnsense" | "manual"\n vlan_profiles: list[CtrldVlanProfile]\n opnsense_host: Optional[str] = ""\n\nclass CtrldInstallRequest(BaseModel):\n token: str\n config: CtrldConfig\n\nclass CtrldUpdateProfile(BaseModel):\n token: str\n vlan_profiles: list[CtrldVlanProfile]\n\n# ── ctrld endpoints ─────────────────────────────────────────────────────────\n\n@app.get("/api/ctrld/status")\ndef ctrld_status():\n """Return ctrld installation and running status."""\n cfg = _load_ctrld_cfg()\n status = _ctrld_status()\n return {\n **status,\n "configured": bool(cfg.get("mode")),\n "mode": cfg.get("mode",""),\n "vlan_profiles": cfg.get("vlan_profiles",[]),\n "opnsense_host": cfg.get("opnsense_host",""),\n "config_path": str(_ctrld_config_path()),\n "docs_url": "https://docs.controld.com/docs/ctrld",\n }\n\n@app.get("/api/ctrld/toml-preview")\ndef ctrld_toml_preview():\n """Generate and return the ctrld.toml without installing it."""\n cfg = _load_ctrld_cfg()\n profiles = cfg.get("vlan_profiles",[])\n if not profiles:\n raise HTTPException(400, "No VLAN profiles configured yet")\n toml = _build_ctrld_toml(profiles)\n return {"toml": toml}\n\n@app.post("/api/ctrld/save-config")\ndef ctrld_save_config(body: CtrldInstallRequest):\n """\n Save ctrld configuration.\n For \'local\' mode: installs ctrld on this machine, writes config, starts service.\n For \'opnsense\' mode: generates the SSH install command.\n For \'manual\' mode: saves config for reference, generates toml only.\n """\n require_session(body.token)\n\n cfg_dict = {\n "mode": body.config.mode,\n "vlan_profiles": [p.dict() for p in body.config.vlan_profiles],\n "opnsense_host": body.config.opnsense_host,\n }\n _save_ctrld_cfg(cfg_dict)\n\n profiles = [p.dict() for p in body.config.vlan_profiles]\n toml = _build_ctrld_toml(profiles)\n\n if body.config.mode == "local":\n return _ctrld_install_local(toml, profiles)\n elif body.config.mode == "opnsense":\n return _ctrld_generate_opnsense_cmd(body.config.opnsense_host, profiles)\n else:\n # Manual — just return the toml and instructions\n return {\n "success": True,\n "mode": "manual",\n "toml": toml,\n "message": "Config saved. Install ctrld manually and use the toml below.",\n "install_cmd": "sh -c \'sh -c \\"$(curl -sL https://api.controld.com/dl)\\"\'",\n "config_path": str(_ctrld_config_path()),\n }\n\ndef _ctrld_install_local(toml: str, profiles: list) -> dict:\n """Download and install ctrld on this machine, write config, start service."""\n import subprocess as _sp, platform as _platform\n\n # Detect architecture\n arch = _platform.machine().lower()\n os_name = _platform.system().lower()\n\n if os_name != "linux":\n return {\n "success": False,\n "mode": "local",\n "message": f"Auto-install only supported on Linux. "\n f"Download ctrld from https://github.com/Control-D-Inc/ctrld/releases",\n "toml": toml,\n }\n\n # Use ctrld\'s own installer with the first profile\'s resolver ID\n first_rid = next((p["resolver_id"] for p in profiles if p.get("resolver_id")), None)\n if not first_rid:\n return {"success": False, "message": "No Resolver ID provided"}\n\n # Download the binary directly (more reliable than the shell installer for service control)\n log.info("Installing ctrld...")\n\n # Use the official installer\n install_result = _sp.run(\n f\'sh -c \\\'sh -c "$(curl -sL https://api.controld.com/dl)" -s {first_rid} forced\\\'\',\n shell=True, capture_output=True, text=True, timeout=120\n )\n\n if install_result.returncode != 0 and not CTRLD_BIN.exists():\n return {\n "success": False,\n "mode": "local",\n "message": f"Install failed: {install_result.stderr or install_result.stdout}",\n "toml": toml,\n }\n\n # Write our multi-VLAN config (overrides the default single-profile config)\n cfg_path = _ctrld_config_path()\n cfg_path.parent.mkdir(parents=True, exist_ok=True)\n cfg_path.write_text(toml)\n log.info(f"ctrld config written to {cfg_path}")\n\n # Restart ctrld to pick up new config\n _sp.run([str(CTRLD_BIN), "stop"], capture_output=True)\n _sp.run([str(CTRLD_BIN), "start"], capture_output=True)\n\n # Update DHCP on switch — set DNS option 6 per VLAN pool to this machine\'s IP\n import socket as _sock\n try:\n mgmt_ip = _sock.gethostbyname(_sock.gethostname())\n except Exception:\n mgmt_ip = "192.168.99.50"\n\n status = _ctrld_status()\n return {\n "success": status["running"],\n "mode": "local",\n "message": "ctrld installed and running" if status["running"] else "ctrld installed but may not be running — check logs",\n "dns_ip": mgmt_ip,\n "dhcp_action": f"Set DNS (option 6) to {mgmt_ip} on each VLAN pool in the DHCP tab",\n "toml": toml,\n "config_path": str(cfg_path),\n "docs": "https://docs.controld.com/docs/ctrld",\n }\n\ndef _ctrld_generate_opnsense_cmd(opnsense_host: str, profiles: list) -> dict:\n """\n Generate the SSH command to install ctrld on OPNsense.\n User runs this in OPNsense shell.\n """\n first_rid = next((p["resolver_id"] for p in profiles if p.get("resolver_id")), None)\n if not first_rid:\n return {"success": False, "message": "No Resolver ID provided"}\n\n install_cmd = (\n f"sh -c \'sh -c \\"$(curl -sL https://api.controld.com/dl)\\" "\n f"-s {first_rid} forced\'"\n )\n\n toml = _build_ctrld_toml(profiles)\n\n # For OPNsense the config path is different\n opnsense_cfg = "/usr/local/etc/controld/ctrld.toml"\n\n return {\n "success": True,\n "mode": "opnsense",\n "message": "Run the install command in OPNsense shell (SSH or console)",\n "install_cmd": install_cmd,\n "ssh_cmd": f"ssh root@{opnsense_host or \'your-opnsense-ip\'} \'{install_cmd}\'",\n "toml": toml,\n "config_path": opnsense_cfg,\n "step2": f"After install, replace {opnsense_cfg} with the toml config shown below",\n "step3": "Run: ctrld restart",\n "step4": f"Set DNS (option 6) to {opnsense_host or \'OPNsense IP\'} on each VLAN pool",\n "docs": "https://docs.controld.com/docs/routers-platform",\n }\n\n@app.post("/api/ctrld/update-profiles")\ndef ctrld_update_profiles(body: CtrldUpdateProfile):\n """Update VLAN profiles and regenerate/reload ctrld config."""\n require_session(body.token)\n cfg = _load_ctrld_cfg()\n cfg["vlan_profiles"] = [p.dict() for p in body.vlan_profiles]\n _save_ctrld_cfg(cfg)\n\n toml = _build_ctrld_toml(cfg["vlan_profiles"])\n cfg_path = _ctrld_config_path()\n\n if cfg.get("mode") == "local" and cfg_path.exists():\n cfg_path.write_text(toml)\n import subprocess as _sp\n _sp.run([str(CTRLD_BIN), "stop"], capture_output=True)\n _sp.run([str(CTRLD_BIN), "start"], capture_output=True)\n return {"success": True, "message": "Profiles updated and ctrld reloaded", "toml": toml}\n\n return {"success": True, "message": "Profiles saved", "toml": toml,\n "note": "Restart ctrld manually to apply changes" if cfg.get("mode") == "opnsense" else ""}\n\n@app.delete("/api/ctrld/uninstall")\ndef ctrld_uninstall(token: str):\n require_session(token)\n import subprocess as _sp\n if CTRLD_BIN.exists():\n _sp.run([str(CTRLD_BIN), "uninstall", "--cleanup"], capture_output=True)\n if CTRLD_FILE.exists():\n CTRLD_FILE.unlink()\n return {"success": True}\n'
|
||
|
||
JSX_SRC = 'import { useState, useCallback, useEffect, useRef } from "react";\n\nconst FONT = `@import url(\'https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Barlow:wght@300;400;500;600;700&display=swap\');`;\nconst VLAN_COLORS = ["#00e5ff","#00e676","#ffea00","#ff6d00","#d500f9","#ff1744","#76ff03","#2979ff","#ff4081","#18ffff"];\n\nconst DEFAULT_VLANS = [\n { id: 1, name: "Management", color: VLAN_COLORS[0] },\n { id: 10, name: "Staff", color: VLAN_COLORS[1] },\n { id: 20, name: "Servers", color: VLAN_COLORS[2] },\n { id: 30, name: "IoT", color: VLAN_COLORS[3] },\n { id: 40, name: "Guest", color: VLAN_COLORS[4] },\n { id: 50, name: "Cameras", color: VLAN_COLORS[5] },\n];\n\nconst mkPort = n => ({\n id: n, mode: "access", accessVlan: 1, taggedVlans: [],\n nativeVlan: 1, poe: true, poeLimit: 30000, description: "",\n});\nconst DEFAULT_PORTS = Array.from({ length: 52 }, (_, i) => mkPort(i + 1));\nDEFAULT_PORTS.forEach((p, i) => {\n if (i >= 48) {\n p.mode = "trunk"; p.taggedVlans = [1,10,20,30,40,50];\n p.poe = false; p.description = `SFP+ Uplink ${i-47}`;\n }\n});\n\nconst VISITOR_ID = Math.random().toString(36).slice(2);\n\n// ── CLI Generator with explanations ────────────────────────────────────────\n// Each entry: { cmd: string, explain: string, group: string }\nfunction generateAnnotatedCLI({ ports, vlans, acls, hostname }) {\n const entries = [];\n const h = hostname || "ERS-5952";\n\n const add = (cmd, explain, group) => entries.push({ cmd, explain, group });\n\n add(`hostname ${h}`, `Set switch hostname to "${h}"`, "System");\n\n vlans.forEach(v => {\n add(`vlan create ${v.id} name "${v.name}" type port`,\n `Create VLAN ${v.id} named "${v.name}" — port-based VLAN`, "VLANs");\n });\n\n ports.forEach(p => {\n const iface = p.id <= 48 ? `FastEthernet ${p.id}` : `GigabitEthernet ${p.id}`;\n const portLabel = p.description ? `port ${p.id} (${p.description})` : `port ${p.id}`;\n const vlanName = vlans.find(v => v.id === p.accessVlan)?.name || `VLAN ${p.accessVlan}`;\n const group = `Port ${p.id}${p.description ? ` — ${p.description}` : ""}`;\n\n if (p.description) {\n add(`interface ${iface}`, `Select ${portLabel} for configuration`, group);\n add(` name "${p.description}"`, `Label ${portLabel} as "${p.description}"`, group);\n }\n\n if (p.mode === "disabled") {\n add(`interface ${iface}`, `Select ${portLabel}`, group);\n add(` shutdown`, `Disable ${portLabel} — no traffic will pass`, group);\n } else if (p.mode === "access") {\n add(`vlan members add ${p.accessVlan} ${p.id}`,\n `Assign ${portLabel} to ${vlanName} (VLAN ${p.accessVlan})`, group);\n add(`vlan pvid ${p.id} ${p.accessVlan}`,\n `Set ${portLabel} untagged VLAN to ${vlanName} — devices here join ${vlanName}`, group);\n } else if (p.mode === "trunk") {\n const tagged = p.taggedVlans;\n const names = tagged.map(id => vlans.find(v=>v.id===id)?.name || `VLAN ${id}`).join(", ");\n if (tagged.length) {\n add(`vlan members add ${tagged.join(",")} ${p.id}`,\n `Add ${portLabel} to VLANs: ${names}`, group);\n add(`vlan tagging ${tagged.join(",")} ${p.id}`,\n `Tag traffic on ${portLabel} for VLANs: ${names} — used for uplinks and inter-switch connections`, group);\n }\n const nativeName = vlans.find(v=>v.id===p.nativeVlan)?.name || `VLAN ${p.nativeVlan}`;\n add(`vlan pvid ${p.id} ${p.nativeVlan}`,\n `Set ${portLabel} native (untagged) VLAN to ${nativeName}`, group);\n }\n\n if (p.id <= 48) {\n add(`interface ${iface}`, `Select ${portLabel} for PoE configuration`, group);\n if (!p.poe) {\n add(` no poe enable`, `Disable Power over Ethernet on ${portLabel}`, group);\n } else {\n add(` poe enable`, `Enable Power over Ethernet on ${portLabel}`, group);\n add(` poe poe-limit ${p.poeLimit}`,\n `Limit PoE draw on ${portLabel} to ${(p.poeLimit/1000).toFixed(1)}W — protects switch power budget`, group);\n }\n }\n });\n\n acls.forEach(acl => {\n const vlanName = vlans.find(v=>v.id===acl.applyVlan)?.name || `VLAN ${acl.applyVlan}`;\n const group = `ACL: ${acl.name}`;\n add(`ip access-list extended ${acl.name}`,\n `Create access control list named "${acl.name}"`, group);\n acl.rules.forEach((r, i) => {\n const src = r.srcAny ? "any source" : `source ${r.src}`;\n const dst = r.dstAny ? "any destination" : `destination ${r.dst}`;\n const port = r.port ? ` on port ${r.port}` : "";\n add(` ${i+1} ${r.action} ${r.proto} ${r.srcAny?"any":`${r.src} ${r.srcMask||"0.0.0.255"}`} ${r.dstAny?"any":`${r.dst} ${r.dstMask||"0.0.0.255"}`}${r.port?` eq ${r.port}`:""}`,\n `Rule ${i+1}: ${r.action.toUpperCase()} ${r.proto.toUpperCase()} from ${src} to ${dst}${port}`, group);\n });\n add(`interface vlan ${acl.applyVlan}`,\n `Select ${vlanName} interface to apply the ACL`, group);\n add(` ip access-group ${acl.name} ${acl.direction}`,\n `Apply "${acl.name}" to ${vlanName} — filter traffic going ${acl.direction === "in" ? "INTO" : "OUT OF"} this VLAN`, group);\n });\n\n return entries;\n}\n\nfunction entriesToCLI(entries, hostname) {\n const lines = [\n `! ERS 5952 — ${hostname || "ERS-5952"}`,\n "enable", "configure terminal", "",\n ];\n entries.forEach(e => lines.push(e.cmd));\n lines.push("", "end", "copy running-config nvram:config.cfg");\n return lines.join("\\n");\n}\n\n// ── API ─────────────────────────────────────────────────────────────────────\nconst API = async (path, opts = {}) => {\n const r = await fetch(`/api${path}`, {\n headers: { "Content-Type": "application/json" },\n ...opts,\n body: opts.body ? JSON.stringify(opts.body) : undefined,\n });\n const data = await r.json().catch(() => ({}));\n if (!r.ok) throw new Error(data.detail?.message || data.detail || `HTTP ${r.status}`);\n return data;\n};\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CSS\n// ══════════════════════════════════════════════════════════════════════════════\nconst css = `\n${FONT}\n*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}\n:root{\n --bg:#0a0c10;--sf:#111318;--b1:#1e2230;--b2:#2a2f42;\n --ac:#00e5ff;--ac2:#0077ff;--tx:#c8d0e0;--dm:#5a6070;\n --err:#ff1744;--ok:#00e676;--warn:#ffea00;--warn2:#ff6d00;\n --mono:\'Share Tech Mono\',monospace;--sans:\'Barlow\',sans-serif;\n}\nbody{background:var(--bg);color:var(--tx);font-family:var(--sans);font-size:13px;line-height:1.5;min-height:100vh}\n.app{display:flex;flex-direction:column;min-height:100vh}\n\n/* banner */\n.conn-banner{display:flex;align-items:center;gap:10px;padding:8px 20px;font-size:12px;font-family:var(--mono);border-bottom:1px solid;transition:all .4s}\n.conn-banner.connecting{background:rgba(255,234,0,.06);border-color:rgba(255,234,0,.2);color:var(--warn)}\n.conn-banner.connected{background:rgba(0,230,118,.06);border-color:rgba(0,230,118,.2);color:var(--ok)}\n.conn-banner.error{background:rgba(255,23,68,.06);border-color:rgba(255,23,68,.2);color:var(--err)}\n.conn-banner.hidden{display:none}\n.conn-spin{width:12px;height:12px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:spin .8s linear infinite;flex-shrink:0}\n@keyframes spin{to{transform:rotate(360deg)}}\n.conn-dot{width:8px;height:8px;border-radius:50%;background:currentColor;flex-shrink:0}\n\n/* topbar */\n.topbar{display:flex;align-items:center;gap:14px;padding:10px 20px;background:var(--sf);border-bottom:1px solid var(--b1);position:sticky;top:0;z-index:100;flex-wrap:wrap}\n.logo{font-family:var(--mono);font-size:14px;color:var(--ac);letter-spacing:2px}\n.logo-sub{font-size:10px;color:var(--dm);font-family:var(--mono)}\n.sp{flex:1}\n.ti{background:var(--bg);border:1px solid var(--b2);color:var(--tx);padding:4px 8px;font-family:var(--mono);font-size:12px;border-radius:3px;width:130px}\n.ti:focus{outline:none;border-color:var(--ac)}\n.tl{font-size:11px;color:var(--dm)}\n\n/* session */\n.sess-btn{display:flex;align-items:center;gap:8px;padding:5px 12px;border-radius:4px;border:1px solid;font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;cursor:pointer;font-family:var(--sans);transition:all .15s}\n.sess-btn.locked{border-color:var(--b2);color:var(--dm);background:transparent}\n.sess-btn.locked:hover{border-color:var(--ac);color:var(--ac)}\n.sess-btn.unlocked{border-color:var(--ok);color:var(--ok);background:rgba(0,230,118,.08)}\n.sess-btn.unlocked:hover{background:rgba(255,23,68,.1);border-color:var(--err);color:var(--err)}\n.sess-timer{font-family:var(--mono);font-size:12px;letter-spacing:1px}\n\n/* settings icon */\n.settings-btn{background:none;border:1px solid var(--b2);color:var(--dm);border-radius:4px;padding:5px 9px;cursor:pointer;font-size:14px;transition:all .15s;line-height:1}\n.settings-btn:hover{border-color:var(--ac);color:var(--ac)}\n\n/* settings panel */\n.settings-overlay{position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:150;display:flex;align-items:flex-start;justify-content:flex-end}\n.settings-panel{background:var(--sf);border-left:1px solid var(--b2);width:320px;min-height:100vh;padding:20px}\n.settings-panel h2{font-family:var(--mono);font-size:13px;color:var(--ac);letter-spacing:2px;margin-bottom:16px}\n.settings-section{margin-bottom:20px;padding-bottom:20px;border-bottom:1px solid var(--b1)}\n.settings-section:last-child{border-bottom:none}\n.settings-section h3{font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--dm);margin-bottom:10px}\n.setting-row{display:flex;align-items:center;justify-content:space-between;padding:6px 0}\n.setting-label{font-size:12px}\n.setting-sub{font-size:11px;color:var(--dm);margin-top:2px}\n\n/* poll pill */\n.poll-pill{display:flex;align-items:center;gap:5px;font-size:10px;color:var(--dm);font-family:var(--mono);padding:3px 8px;border:1px solid var(--b1);border-radius:20px}\n.dot{width:6px;height:6px;border-radius:50%}\n.dot.ok{background:var(--ok)}.dot.warn{background:var(--warn)}.dot.err{background:var(--err)}.dot.idle{background:var(--dm)}\n\n/* tabs */\n.tabs{display:flex;gap:2px;padding:0 20px;background:var(--sf);border-bottom:1px solid var(--b1)}\n.tab{padding:10px 18px;font-size:12px;font-weight:600;letter-spacing:1px;text-transform:uppercase;cursor:pointer;border-bottom:2px solid transparent;color:var(--dm);transition:all .15s;background:none;border-top:none;border-left:none;border-right:none;font-family:var(--sans)}\n.tab:hover{color:var(--tx)}.tab.active{color:var(--ac);border-bottom-color:var(--ac)}\n\n/* main */\n.main{flex:1;padding:20px;display:flex;gap:16px;align-items:flex-start}\n\n/* panel */\n.panel{background:var(--sf);border:1px solid var(--b1);border-radius:6px;overflow:hidden}\n.ph{padding:10px 14px;border-bottom:1px solid var(--b1);font-size:11px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--ac);font-family:var(--mono);display:flex;align-items:center;gap:8px}\n.pb{padding:14px}\n\n/* chassis */\n.chassis{background:#0d0f14;border:1px solid var(--b2);border-radius:8px;padding:16px;margin-bottom:12px}\n.cl{font-family:var(--mono);font-size:10px;color:var(--dm);letter-spacing:3px;text-transform:uppercase;margin-bottom:10px}\n.pgrid{display:grid;grid-template-columns:repeat(24,1fr);gap:4px}\n.pgrid-sfp{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;margin-top:8px;padding-top:8px;border-top:1px solid var(--b1);width:calc(4*(100%/24)+3*4px)}\n.port{aspect-ratio:1;border-radius:3px;border:1px solid transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:8px;font-weight:700;transition:all .1s;position:relative}\n.port:hover{filter:brightness(1.3);transform:scale(1.1);z-index:2}\n.port.sel{border-color:white!important;box-shadow:0 0 0 2px white;z-index:3}\n.poe-dot{position:absolute;top:1px;right:1px;width:4px;height:4px;border-radius:50%;background:var(--ok)}\n.legend{display:flex;flex-wrap:wrap;gap:8px;padding:10px 14px;border-top:1px solid var(--b1)}\n.li{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dm)}\n.ld{width:10px;height:10px;border-radius:2px}\n\n/* fields */\n.field{margin-bottom:12px}\n.field label{display:block;font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--dm);margin-bottom:4px}\n.field input,.field select{width:100%;background:var(--bg);border:1px solid var(--b2);color:var(--tx);padding:6px 8px;font-family:var(--mono);font-size:12px;border-radius:3px}\n.field input:focus,.field select:focus{outline:none;border-color:var(--ac)}\n.field select option{background:var(--bg)}\n.rgrp{display:flex;gap:6px}\n.rbtn{flex:1;padding:5px;text-align:center;border:1px solid var(--b2);border-radius:3px;cursor:pointer;font-size:11px;font-weight:600;letter-spacing:1px;text-transform:uppercase;transition:all .1s;background:none;color:var(--dm);font-family:var(--sans)}\n.rbtn:hover{border-color:var(--ac);color:var(--ac)}\n.rbtn.ra{background:var(--ac);border-color:var(--ac);color:#000}\n.rbtn.rt{background:var(--ac2);border-color:var(--ac2);color:#fff}\n.rbtn.rd{background:var(--err);border-color:var(--err);color:#fff}\n.trow{display:flex;align-items:center;justify-content:space-between;padding:6px 0}\n.tog{width:36px;height:20px;background:var(--b2);border-radius:10px;cursor:pointer;position:relative;transition:background .2s;border:none}\n.tog.on{background:var(--ok)}\n.tog::after{content:\'\';position:absolute;top:3px;left:3px;width:14px;height:14px;background:#fff;border-radius:50%;transition:transform .2s}\n.tog.on::after{transform:translateX(16px)}\n.vtags{display:flex;flex-wrap:wrap;gap:4px;padding:6px;background:var(--bg);border:1px solid var(--b2);border-radius:3px;min-height:34px}\n.vtag{padding:2px 7px;border-radius:2px;font-family:var(--mono);font-size:11px;cursor:pointer;font-weight:700;transition:opacity .1s}\n.vtag.von{opacity:1}.vtag.voff{opacity:.25}\n\n/* buttons */\n.btn{padding:7px 14px;border-radius:3px;border:none;cursor:pointer;font-size:11px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;font-family:var(--sans);transition:all .1s;white-space:nowrap}\n.bp{background:var(--ac);color:#000}.bp:hover{background:#33ecff}\n.bd{background:var(--err);color:#fff}.bd:hover{background:#ff4569}\n.bg{background:transparent;border:1px solid var(--b2);color:var(--tx)}.bg:hover{border-color:var(--ac);color:var(--ac)}\n.bs{background:var(--ok);color:#000}.bs:hover{background:#33eb91}\n.bw{background:var(--warn);color:#000}.bw:hover{filter:brightness(1.1)}\n.btn:disabled{opacity:.4;cursor:not-allowed}\n.btn-row{display:flex;gap:6px;margin-top:12px;flex-wrap:wrap}\n\n/* vlan table */\n.vtbl{width:100%;border-collapse:collapse}\n.vtbl th{text-align:left;padding:6px 10px;font-size:10px;letter-spacing:2px;text-transform:uppercase;color:var(--dm);border-bottom:1px solid var(--b1)}\n.vtbl td{padding:8px 10px;border-bottom:1px solid var(--b1);font-family:var(--mono);font-size:12px}\n.vtbl tr:last-child td{border-bottom:none}\n.vtbl tr:hover td{background:rgba(255,255,255,.02)}\n.sw{width:16px;height:16px;border-radius:3px;display:inline-block;vertical-align:middle}\n.ii{background:var(--bg);border:1px solid var(--b2);color:var(--tx);padding:3px 6px;font-family:var(--mono);font-size:12px;border-radius:3px;width:100%}\n.ii:focus{outline:none;border-color:var(--ac)}\n\n/* acl */\n.acl-card{background:var(--bg);border:1px solid var(--b2);border-radius:5px;overflow:hidden;margin-bottom:10px}\n.acl-hd{padding:8px 12px;display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.03);border-bottom:1px solid var(--b1)}\n.acl-nm{font-family:var(--mono);font-size:13px;color:var(--ac);flex:1}\n.acl-rules{padding:8px 12px}\n.acl-rule{display:grid;grid-template-columns:60px 50px 1fr 1fr 60px 24px;gap:6px;align-items:center;margin-bottom:6px;font-size:11px}\n.acl-rule select,.acl-rule input{background:var(--sf);border:1px solid var(--b2);color:var(--tx);padding:3px 5px;font-family:var(--mono);font-size:11px;border-radius:3px;width:100%}\n\n/* ── ANNOTATED CLI TABLE ── */\n.cli-table{width:100%;border-collapse:collapse;font-size:12px;margin-bottom:12px}\n.cli-table th{text-align:left;padding:6px 10px;font-size:10px;letter-spacing:2px;text-transform:uppercase;color:var(--dm);border-bottom:1px solid var(--b1);font-family:var(--sans)}\n.cli-group-header td{padding:8px 10px 4px;font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--ac);font-family:var(--mono);border-top:1px solid var(--b1);background:rgba(0,229,255,.04)}\n.cli-row{transition:background .1s}\n.cli-row:hover{background:rgba(255,255,255,.03)}\n.cli-row td{padding:5px 10px;border-bottom:1px solid rgba(255,255,255,.03);vertical-align:top}\n.cli-cmd{font-family:var(--mono);color:var(--tx);white-space:pre}\n.cli-explain{color:var(--dm);font-size:11px;padding-left:8px}\n.cli-row.pending td{opacity:.5}\n.cli-row.running td .cli-cmd{color:var(--warn)}\n.cli-row.running td .cli-explain{color:var(--warn)}\n.cli-row.success td .cli-cmd{color:var(--ok)}\n.cli-row.success td .cli-explain{color:#3a6040}\n.cli-row.failed td .cli-cmd{color:var(--err)}\n.cli-row.failed td .cli-explain{color:#6a2030}\n.cli-row.waiting td{opacity:.35}\n.cli-status{width:20px;text-align:center;font-size:13px}\n.cli-err-out{font-family:var(--mono);font-size:10px;color:var(--warn);padding:3px 10px 5px;background:rgba(255,23,68,.05);border-bottom:1px solid var(--b1)}\n\n/* raw cli textarea (cli mode) */\n.cli-raw{width:100%;background:#060809;border:1px solid var(--b1);color:#a0b0c0;padding:14px;font-family:var(--mono);font-size:12px;line-height:1.7;border-radius:4px;min-height:300px;resize:vertical}\n.cli-raw:focus{outline:none;border-color:var(--ac)}\n\n/* totp modal */\n.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:200;display:flex;align-items:center;justify-content:center}\n.modal{background:var(--sf);border:1px solid var(--b2);border-radius:8px;padding:28px;width:360px;text-align:center}\n.modal h2{font-family:var(--mono);color:var(--ac);font-size:14px;letter-spacing:2px;margin-bottom:8px}\n.modal p{font-size:12px;color:var(--dm);margin-bottom:20px;line-height:1.7}\n.totp-in{width:100%;background:var(--bg);border:2px solid var(--b2);color:var(--tx);padding:12px;font-family:var(--mono);font-size:28px;letter-spacing:10px;border-radius:4px;text-align:center;margin-bottom:12px}\n.totp-in:focus{outline:none;border-color:var(--ac)}\n\n/* danger */\n.hard-box{background:rgba(255,23,68,.07);border:1px solid rgba(255,23,68,.3);border-radius:4px;padding:10px 14px;margin-bottom:10px}\n.hard-box h4{color:var(--err);font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:6px}\n.warn-box{background:rgba(255,234,0,.07);border:1px solid rgba(255,234,0,.3);border-radius:4px;padding:10px 14px;margin-bottom:10px}\n.warn-box h4{color:var(--warn);font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;margin-bottom:6px}\n.danger-item{font-size:11px;margin-bottom:5px}\n.danger-cmd{font-family:var(--mono);color:var(--tx)}\n.danger-why{font-size:10px;color:var(--dm);margin-top:1px}\n\n/* push mode choice */\n.push-choice{display:flex;gap:10px;margin-bottom:14px}\n.push-choice-btn{flex:1;padding:10px 12px;border-radius:5px;border:1px solid var(--b2);background:var(--bg);color:var(--tx);cursor:pointer;text-align:left;transition:all .15s;font-family:var(--sans)}\n.push-choice-btn:hover{border-color:var(--ac)}\n.push-choice-btn.chosen{border-color:var(--ac);background:rgba(0,229,255,.06)}\n.push-choice-btn h4{font-size:12px;font-weight:700;margin-bottom:3px;color:var(--ac)}\n.push-choice-btn p{font-size:11px;color:var(--dm);line-height:1.4}\n\n/* push summary bar */\n.push-summary{display:flex;align-items:center;gap:12px;padding:8px 12px;border-radius:4px;font-size:12px;font-family:var(--mono);margin-bottom:10px}\n.push-summary.ok{background:rgba(0,230,118,.08);border:1px solid rgba(0,230,118,.2);color:var(--ok)}\n.push-summary.fail{background:rgba(255,23,68,.08);border:1px solid rgba(255,23,68,.2);color:var(--err)}\n.push-summary.running{background:rgba(255,234,0,.05);border:1px solid rgba(255,234,0,.15);color:var(--warn)}\n\n\n/* ── Device Access ── */\n.device-card{background:var(--bg);border:1px solid var(--b2);border-radius:4px;padding:10px 12px;margin-bottom:8px}\n.device-badges{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}\n/* misc */\n.sect{font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--dm);margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid var(--b1)}\n.empty{text-align:center;padding:40px 20px;color:var(--dm);font-size:12px}\n.badge{padding:1px 6px;border-radius:10px;font-size:10px;font-family:var(--mono);font-weight:700}\n.poe-bar-wrap{height:4px;background:var(--b2);border-radius:2px;margin-top:4px;overflow:hidden}\n.poe-bar{height:100%;border-radius:2px;background:var(--ok);transition:width .3s}\n`;\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CONNECTION BANNER\n// ══════════════════════════════════════════════════════════════════════════════\nfunction ConnBanner({ state, info }) {\n if (state === "hidden") return null;\n return (\n <div className={`conn-banner ${state}`}>\n {state === "connecting" && <span className="conn-spin"/>}\n {state !== "connecting" && <span className="conn-dot"/>}\n <span>\n {state === "connecting" && "Connecting to switch..."}\n {state === "connected" && (info || "Connected")}\n {state === "error" && (info || "Switch unreachable — retrying...")}\n </span>\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// TOTP MODAL\n// ══════════════════════════════════════════════════════════════════════════════\nfunction TotpModal({ onSuccess, onCancel, commandCount }) {\n const [code, setCode] = useState("");\n const [error, setError] = useState("");\n const [loading, setLoading] = useState(false);\n\n const verify = async () => {\n if (code.length !== 6) return;\n setLoading(true); setError("");\n try {\n const data = await API("/auth/verify", { method: "POST", body: { code } });\n onSuccess(data.token);\n } catch(e) {\n setError(e.message); setCode("");\n } finally { setLoading(false); }\n };\n\n return (\n <div className="modal-bg" onClick={onCancel}>\n <div className="modal" onClick={e => e.stopPropagation()}>\n <h2>◈ AUTHENTICATE</h2>\n <p>\n Enter your 6-digit TOTP code to authorize this push.<br/>\n <span style={{color:"var(--ac)"}}>{commandCount} command{commandCount!==1?"s":""}</span> ready to send.<br/>\n <span style={{color:"var(--dm)"}}>Session locks automatically when push completes.</span>\n </p>\n <input className="totp-in" value={code}\n onChange={e => setCode(e.target.value.replace(/\\D/g,"").slice(0,6))}\n onKeyDown={e => e.key==="Enter" && verify()}\n placeholder="000000" autoFocus maxLength={6}/>\n {error && <div style={{color:"var(--err)",fontSize:12,marginBottom:10}}>{error}</div>}\n <div style={{display:"flex",gap:8,justifyContent:"center"}}>\n <button className="btn bg" onClick={onCancel}>Cancel</button>\n <button className="btn bp" onClick={verify} disabled={code.length!==6||loading}>\n {loading ? "Verifying..." : "Authorize Push"}\n </button>\n </div>\n </div>\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// SESSION BUTTON — shows "Authenticate to Push" only, no timer\n// Session is scoped to one push batch, lock happens automatically after push\n// ══════════════════════════════════════════════════════════════════════════════\nfunction SessionBtn({ session, onUnlock }) {\n if (session) {\n return (\n <div className="sess-btn unlocked" style={{cursor:"default"}}>\n 🔓 <span>Session Active</span>\n </div>\n );\n }\n return (\n <button className="sess-btn locked" onClick={onUnlock}>\n 🔒 <span>Authenticate to Push</span>\n </button>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// SETTINGS PANEL\n// ══════════════════════════════════════════════════════════════════════════════\nfunction SettingsPanel({ settings, setSettings, onClose }) {\n return (\n <div className="settings-overlay" onClick={onClose}>\n <div className="settings-panel" onClick={e => e.stopPropagation()}>\n <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:20}}>\n <h2>◈ SETTINGS</h2>\n <button className="btn bg" style={{padding:"3px 10px",fontSize:11}} onClick={onClose}>✕ Close</button>\n </div>\n\n <div className="settings-section">\n <h3>Interface</h3>\n <div className="setting-row">\n <div>\n <div className="setting-label">CLI Mode</div>\n <div className="setting-sub">Advanced — type raw ERS commands directly</div>\n </div>\n <button className={`tog ${settings.cliMode?"on":""}`}\n onClick={() => setSettings(s => ({...s, cliMode: !s.cliMode}))}/>\n </div>\n </div>\n\n <div className="settings-section">\n <h3>Push Behaviour</h3>\n <div className="setting-row">\n <div>\n <div className="setting-label">Default push mode</div>\n <div className="setting-sub">Batch or step-by-step</div>\n </div>\n <select value={settings.defaultPushMode}\n onChange={e => setSettings(s => ({...s, defaultPushMode: e.target.value}))}\n style={{background:"var(--bg)",border:"1px solid var(--b2)",color:"var(--tx)",padding:"4px 6px",fontFamily:"var(--mono)",fontSize:11,borderRadius:3}}>\n <option value="batch">Batch</option>\n <option value="step">Step-by-step</option>\n </select>\n </div>\n </div>\n\n <div className="settings-section">\n <h3>About</h3>\n <div style={{fontSize:11,color:"var(--dm)",lineHeight:1.7}}>\n ERS 5952 Switch Manager<br/>\n Runs on your management computer on VLAN 99.<br/>\n SSH key lives on the management computer only.<br/>\n You never write CLI commands.<br/>\n <span style={{color:"var(--ac)"}}>README.md</span> has full documentation.\n </div>\n </div>\n </div>\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// ANNOTATED CLI TABLE — the main inspect view\n// ══════════════════════════════════════════════════════════════════════════════\nfunction AnnotatedCLITable({ entries, pushState, currentIdx, pushMode, onConfirmOne }) {\n // Group entries by group field\n const groups = [];\n let lastGroup = null;\n entries.forEach((e, i) => {\n if (e.group !== lastGroup) {\n groups.push({ label: e.group, entries: [] });\n lastGroup = e.group;\n }\n groups[groups.length-1].entries.push({ ...e, globalIdx: i });\n });\n\n const getRowState = (globalIdx) => {\n if (!pushState) return "pending";\n if (globalIdx < currentIdx) return "success";\n if (globalIdx === currentIdx) return "running";\n return "waiting";\n };\n\n const getRowResult = (globalIdx) => {\n if (!pushState?.results) return null;\n return pushState.results.find(r => r.index === globalIdx);\n };\n\n return (\n <table className="cli-table">\n <thead>\n <tr>\n <th style={{width:24}}></th>\n <th>Command</th>\n <th>What it does</th>\n {pushMode === "step" && !pushState?.done && <th style={{width:80}}></th>}\n </tr>\n </thead>\n <tbody>\n {groups.map((grp, gi) => (\n <>\n <tr key={`g${gi}`} className="cli-group-header">\n <td colSpan={pushMode==="step" && !pushState?.done ? 4 : 3}>{grp.label}</td>\n </tr>\n {grp.entries.map((e, ei) => {\n const rowState = getRowState(e.globalIdx);\n const result = getRowResult(e.globalIdx);\n const isCurrentStep = pushMode === "step" && pushState && !pushState.done && e.globalIdx === currentIdx;\n return (\n <>\n <tr key={`e${gi}-${ei}`} className={`cli-row ${rowState}`}>\n <td className="cli-status">\n {rowState === "success" && "✓"}\n {rowState === "failed" && "✗"}\n {rowState === "running" && <span className="conn-spin" style={{display:"inline-block"}}/>}\n {(rowState === "pending" || rowState === "waiting") && "·"}\n </td>\n <td className="cli-cmd">{e.cmd}</td>\n <td className="cli-explain">{e.explain}</td>\n {pushMode === "step" && !pushState?.done && (\n <td>\n {isCurrentStep && (\n <button className="btn bs" style={{padding:"2px 10px",fontSize:10}}\n onClick={() => onConfirmOne(e.globalIdx)}>Send ↵</button>\n )}\n </td>\n )}\n </tr>\n {result && !result.success && result.output && (\n <tr key={`err${gi}-${ei}`}>\n <td colSpan={4} className="cli-err-out">\n Switch error: {result.output}\n </td>\n </tr>\n )}\n </>\n );\n })}\n </>\n ))}\n </tbody>\n </table>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// CLI & PUSH TAB\n// ══════════════════════════════════════════════════════════════════════════════\nfunction CliTab({ ports, vlans, acls, hostname, session, setSession, onNeedAuth, backendOk, settings }) {\n const annotated = generateAnnotatedCLI({ ports, vlans, acls, hostname });\n const pushCommands = annotated.map(e => e.cmd).filter(c => {\n const t = c.trim();\n return t && !t.startsWith("!");\n });\n\n const [stage, setStage] = useState("idle"); // idle|checking|danger|choosePushMode|pushing|done\n const [dangerResult, setDangerResult] = useState(null);\n const [pushMode, setPushMode] = useState(settings.defaultPushMode || "batch");\n const [pushState, setPushState] = useState(null);\n const [currentIdx, setCurrentIdx] = useState(0);\n const [rawCli, setRawCli] = useState("");\n\n // Reset when ports/vlans/acls change\n useEffect(() => { setStage("idle"); setPushState(null); setCurrentIdx(0); }, [ports, vlans, acls]);\n\n const handleReviewPush = async () => {\n setStage("checking");\n try {\n const check = await API("/check/danger", { method:"POST", body:{ commands: pushCommands } });\n setDangerResult(check);\n setStage("danger");\n } catch(e) {\n setDangerResult({ error: e.message }); setStage("danger");\n }\n };\n\n const proceedToChoose = () => setStage("choosePushMode");\n\n const startPush = async (mode, token) => {\n const t = token || session?.token;\n if (!t) { onNeedAuth(); return; }\n setPushMode(mode);\n setStage("pushing");\n setCurrentIdx(0);\n setPushState({ results: [], done: false });\n\n if (mode === "batch") {\n await executeBatch(t);\n }\n // step mode is driven by onConfirmOne\n };\n\n const executeBatch = async (token) => {\n try {\n const result = await API("/switch/push", {\n method:"POST",\n body: { token, commands: pushCommands }\n });\n setPushState({ ...result, done: true });\n setCurrentIdx(result.commands_sent || pushCommands.length);\n setStage("done");\n setSession(null); // lock session after push completes\n } catch(e) {\n setPushState({ success:false, error:e.message, results:[], commands_sent:0, done:true });\n setStage("done");\n setSession(null);\n }\n };\n\n const onConfirmOne = async (idx) => {\n if (!session?.token) { onNeedAuth(); return; }\n const cmd = pushCommands[idx];\n try {\n const result = await API("/switch/push", {\n method:"POST",\n body: { token: session.token, commands: [cmd] }\n });\n const r = result.results?.[0] || { index: idx, command: cmd, success: result.success, output: result.error || "", skipped: false };\n r.index = idx;\n setPushState(prev => {\n const results = [...(prev?.results||[]), r];\n if (!result.success) {\n setStage("done");\n setSession(null);\n return { ...prev, results, done: true, success: false, error: result.error };\n }\n const nextIdx = idx + 1;\n setCurrentIdx(nextIdx);\n if (nextIdx >= pushCommands.length) {\n // Save config\n API("/switch/push", { method:"POST", body:{ token: session.token, commands:["copy running-config nvram:config.cfg"] } })\n .catch(() => {});\n setStage("done");\n setSession(null);\n return { ...prev, results, done:true, success:true, saved:true };\n }\n return { ...prev, results };\n });\n } catch(e) {\n setStage("done"); setSession(null);\n setPushState(prev => ({ ...prev, done:true, success:false, error:e.message }));\n }\n };\n\n const handleRawPush = async () => {\n if (!session?.token) { onNeedAuth(); return; }\n const cmds = rawCli.split("\\n").filter(l => l.trim() && !l.trim().startsWith("!"));\n try {\n setStage("pushing");\n const result = await API("/switch/push", { method:"POST", body:{ token:session.token, commands:cmds } });\n setPushState({ ...result, done:true });\n setStage("done");\n setSession(null);\n } catch(e) {\n setPushState({ success:false, error:e.message, results:[], done:true });\n setStage("done"); setSession(null);\n }\n };\n\n const fullCLI = entriesToCLI(annotated, hostname);\n const cmdCount = pushCommands.length;\n\n // ── CLI Mode (raw text) ──\n if (settings.cliMode) {\n return (\n <div className="main" style={{flexDirection:"column"}}>\n <div className="panel">\n <div className="ph">◈ CLI Mode — Advanced\n <span style={{marginLeft:"auto",fontSize:10,color:"var(--dm)"}}>Danger check and allowlist still apply</span>\n </div>\n <div className="pb">\n <div style={{marginBottom:8,fontSize:11,color:"var(--dm)"}}>\n Type or paste ERS CLI commands. Do not include enable, configure terminal, end, or copy — these are added automatically.\n </div>\n <textarea className="cli-raw" value={rawCli}\n onChange={e => setRawCli(e.target.value)}\n placeholder={"vlan create 100 name Finance type port\\nvlan members add 100 22\\nvlan pvid 22 100"}/>\n <div className="btn-row">\n <button className="btn bg" onClick={() => navigator.clipboard?.writeText(rawCli)}>Copy</button>\n <button className="btn bp" onClick={handleRawPush} disabled={!rawCli.trim()||!backendOk||stage==="pushing"}>\n {stage==="pushing" ? "Pushing..." : "Review & Push →"}\n </button>\n </div>\n {pushState?.done && (\n <div className={`push-summary ${pushState.success?"ok":"fail"}`} style={{marginTop:12}}>\n {pushState.success ? `✓ All commands succeeded — config saved` : `✗ Failed: ${pushState.error}`}\n </div>\n )}\n </div>\n </div>\n </div>\n );\n }\n\n // ── GUI Mode ──\n return (\n <div className="main" style={{flexDirection:"column"}}>\n <div className="panel">\n <div className="ph">\n ◈ Review & Push — {cmdCount} command{cmdCount!==1?"s":""}\n <span style={{marginLeft:"auto",display:"flex",gap:8}}>\n <button className="btn bg" onClick={() => navigator.clipboard?.writeText(fullCLI)}>Copy CLI</button>\n <button className="btn bg" onClick={() => {\n const a = document.createElement("a");\n a.href = URL.createObjectURL(new Blob([fullCLI],{type:"text/plain"}));\n a.download=`${hostname||"ers5952"}-config.txt`; a.click();\n }}>Download</button>\n {stage==="idle" && (\n <button className="btn bp" onClick={handleReviewPush} disabled={!backendOk||cmdCount===0}>\n {!backendOk ? "Backend Offline" : cmdCount===0 ? "No Changes" : "Review & Push →"}\n </button>\n )}\n </span>\n </div>\n <div className="pb">\n\n {/* ── Danger stage ── */}\n {stage==="danger" && dangerResult && (\n <div style={{marginBottom:14}}>\n {dangerResult.hard_blocked?.length > 0 && (\n <div className="hard-box">\n <h4>✗ Hard Blocked — Run These at the Switch Console</h4>\n {dangerResult.hard_blocked.map((d,i) => (\n <div key={i} className="danger-item">\n <div className="danger-cmd">{d.command}</div>\n <div className="danger-why">{d.reason}</div>\n </div>\n ))}\n <button className="btn bg" style={{marginTop:10}} onClick={()=>setStage("idle")}>Back</button>\n </div>\n )}\n {dangerResult.warnings?.length > 0 && (\n <div className="warn-box">\n <h4>⚠ Review These Commands</h4>\n {dangerResult.warnings.map((d,i) => (\n <div key={i} className="danger-item">\n <div className="danger-cmd">{d.command}</div>\n <div className="danger-why">{d.reason}</div>\n </div>\n ))}\n </div>\n )}\n {!dangerResult.has_hard_block && (\n <div className="btn-row">\n <button className="btn bg" onClick={()=>setStage("idle")}>Cancel</button>\n <button className="btn bs" onClick={proceedToChoose}>\n {dangerResult.has_warnings ? "Acknowledge & Continue →" : "Looks Good — Choose Push Mode →"}\n </button>\n </div>\n )}\n </div>\n )}\n\n {/* ── Push mode choice ── */}\n {stage==="choosePushMode" && (\n <div style={{marginBottom:14}}>\n <div className="sect">How do you want to push these {cmdCount} commands?</div>\n <div className="push-choice">\n <button className={`push-choice-btn ${pushMode==="batch"?"chosen":""}`}\n onClick={() => setPushMode("batch")}>\n <h4>⚡ Send All at Once</h4>\n <p>All commands sent in sequence. Results shown when complete. Faster — good when you\'ve reviewed and are confident.</p>\n </button>\n <button className={`push-choice-btn ${pushMode==="step"?"chosen":""}`}\n onClick={() => setPushMode("step")}>\n <h4>◈ Step by Step</h4>\n <p>Send one command at a time. Confirm each before the next is sent. Good for complex changes or when you want full control.</p>\n </button>\n </div>\n <div className="btn-row">\n <button className="btn bg" onClick={()=>setStage("danger")}>Back</button>\n {session\n ? <button className="btn bs" onClick={() => startPush(pushMode, session.token)}>\n Start Push →\n </button>\n : <button className="btn bw" onClick={onNeedAuth}>Authenticate First →</button>\n }\n </div>\n </div>\n )}\n\n {/* ── Push summary bar ── */}\n {(stage==="pushing" || stage==="done") && pushState && (\n <div className={`push-summary ${stage==="pushing"?"running":pushState.success?"ok":"fail"}`}>\n {stage==="pushing" && `Sending commands... (${currentIdx}/${cmdCount})`}\n {stage==="done" && pushState.success && `✓ All ${pushState.commands_sent} commands succeeded — config saved to NVRAM`}\n {stage==="done" && !pushState.success && `✗ Stopped at command ${(pushState.stopped_at||0)+1} — config NOT saved`}\n {stage==="done" && (\n <button className="btn bg" style={{marginLeft:"auto",padding:"2px 10px",fontSize:10}}\n onClick={() => { setStage("idle"); setPushState(null); setCurrentIdx(0); }}>\n Reset\n </button>\n )}\n </div>\n )}\n\n {/* ── Annotated command table ── */}\n {(stage==="idle" || stage==="checking" || stage==="pushing" || stage==="done") && (\n <AnnotatedCLITable\n entries={annotated}\n pushState={pushState}\n currentIdx={currentIdx}\n pushMode={pushMode}\n onConfirmOne={onConfirmOne}\n />\n )}\n\n {stage==="done" && !pushState?.success && pushState?.error && (\n <div style={{background:"rgba(255,23,68,.06)",border:"1px solid rgba(255,23,68,.2)",borderRadius:4,padding:"10px 14px",fontFamily:"var(--mono)",fontSize:11,color:"var(--err)"}}>\n {pushState.error}\n {pushState.hint && <div style={{color:"var(--dm)",marginTop:4}}>{pushState.hint}</div>}\n </div>\n )}\n\n {stage==="done" && (\n <div style={{marginTop:12,fontSize:11,color:"var(--dm)"}}>\n Session locked. To make more changes, configure them in the tabs above then click Review & Push and authenticate again.\n </div>\n )}\n </div>\n </div>\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// PORT BUTTON + EDITOR (unchanged from previous version)\n// ══════════════════════════════════════════════════════════════════════════════\nfunction PortBtn({ port, vlans, selected, onClick }) {\n const vlan = vlans.find(v => v.id === port.accessVlan);\n let bg = "#1a1c22", color = "#3a4050";\n if (port.mode==="disabled") { bg="#13151a"; color="#2a2f3a"; }\n else if (port.mode==="trunk") { bg="#0a1a2e"; color="#2979ff"; }\n else if (vlan) { bg=vlan.color+"22"; color=vlan.color; }\n return (\n <button className={`port ${selected?"sel":""}`}\n style={{background:bg,color,borderColor:selected?"white":color+"66"}}\n onClick={() => onClick(port.id)}\n title={`Port ${port.id}${port.description?` — ${port.description}`:""}`}>\n {port.id}\n {port.poe && port.id<=48 && port.mode!=="disabled" && <span className="poe-dot"/>}\n </button>\n );\n}\n\nfunction PortEditor({ port, vlans, onChange }) {\n if (!port) return <div className="empty"><div style={{fontSize:28,marginBottom:8}}>◈</div>Select a port</div>;\n const isSFP = port.id > 48;\n const up = (k,v) => onChange({...port,[k]:v});\n const toggleTagged = vid => {\n const cur = port.taggedVlans||[];\n up("taggedVlans", cur.includes(vid) ? cur.filter(v=>v!==vid) : [...cur,vid]);\n };\n return (\n <div>\n <div className="sect">Port {port.id}{isSFP?" (SFP+)":""}</div>\n <div className="field">\n <label>Description</label>\n <input value={port.description} onChange={e=>up("description",e.target.value)} placeholder="e.g. AP-Corridor-1"/>\n </div>\n <div className="field">\n <label>Mode</label>\n <div className="rgrp">\n {["access","trunk","disabled"].map(m=>(\n <button key={m} className={`rbtn ${port.mode===m?m==="trunk"?"rt":m==="disabled"?"rd":"ra":""}`}\n onClick={()=>up("mode",m)}>{m}</button>\n ))}\n </div>\n </div>\n {port.mode==="access" && (\n <div className="field">\n <label>Access VLAN</label>\n <select value={port.accessVlan} onChange={e=>up("accessVlan",+e.target.value)}>\n {vlans.map(v=><option key={v.id} value={v.id}>{v.id} — {v.name}</option>)}\n </select>\n </div>\n )}\n {port.mode==="trunk" && (<>\n <div className="field">\n <label>Native VLAN</label>\n <select value={port.nativeVlan} onChange={e=>up("nativeVlan",+e.target.value)}>\n {vlans.map(v=><option key={v.id} value={v.id}>{v.id} — {v.name}</option>)}\n </select>\n </div>\n <div className="field">\n <label>Tagged VLANs</label>\n <div className="vtags">\n {vlans.map(v=>(\n <span key={v.id} className={`vtag ${port.taggedVlans?.includes(v.id)?"von":"voff"}`}\n style={{background:v.color+"33",color:v.color,border:`1px solid ${v.color}66`}}\n onClick={()=>toggleTagged(v.id)}>{v.id}</span>\n ))}\n </div>\n </div>\n </>)}\n {!isSFP && (<>\n <div className="trow">\n <span>PoE+</span>\n <button className={`tog ${port.poe?"on":""}`} onClick={()=>up("poe",!port.poe)}/>\n </div>\n {port.poe && (\n <div className="field" style={{marginTop:8}}>\n <label>PoE Limit (mW)</label>\n <input type="number" value={port.poeLimit} min={1000} max={30000} step={1000}\n onChange={e=>up("poeLimit",+e.target.value)}/>\n <div className="poe-bar-wrap"><div className="poe-bar" style={{width:`${port.poeLimit/300}%`}}/></div>\n </div>\n )}\n </>)}\n </div>\n );\n}\n\nfunction PortTab({ ports, vlans, selected, setSelected, updatePort, pollStatus }) {\n const port = ports.find(p=>p.id===selected);\n return (\n <div className="main">\n <div style={{flex:1}}>\n <div className="panel">\n <div className="ph">◈ ERS 5952 — Port Map\n {pollStatus==="stale" && <span style={{marginLeft:"auto",fontSize:10,color:"var(--warn)",fontFamily:"var(--mono)"}}>⚠ Data stale</span>}\n {pollStatus==="ok" && <span style={{marginLeft:"auto",fontSize:10,color:"var(--ok)",fontFamily:"var(--mono)"}}>● Live</span>}\n </div>\n <div className="pb">\n <div className="chassis">\n <div className="cl">48× GigE PoE+</div>\n <div className="pgrid">\n {ports.slice(0,48).map(p=><PortBtn key={p.id} port={p} vlans={vlans} selected={selected===p.id} onClick={setSelected}/>)}\n </div>\n <div className="cl" style={{marginTop:12}}>4× SFP+ Uplinks</div>\n <div className="pgrid-sfp">\n {ports.slice(48,52).map(p=><PortBtn key={p.id} port={p} vlans={vlans} selected={selected===p.id} onClick={setSelected}/>)}\n </div>\n </div>\n <div className="legend">\n {vlans.map(v=>(\n <div key={v.id} className="li"><span className="ld" style={{background:v.color}}/><span>VLAN {v.id} — {v.name}</span></div>\n ))}\n <div className="li"><span className="ld" style={{background:"#0a1a2e",border:"1px solid #2979ff"}}/><span>Trunk</span></div>\n <div className="li"><span className="ld" style={{background:"#13151a"}}/><span>Disabled</span></div>\n </div>\n </div>\n </div>\n </div>\n <div className="panel" style={{width:280,flexShrink:0}}>\n <div className="ph">◈ Port Config</div>\n <div className="pb"><PortEditor port={port} vlans={vlans} onChange={updatePort}/></div>\n </div>\n </div>\n );\n}\n\nfunction VlanTab({ vlans, setVlans, ports }) {\n const [nid,setNid]=useState(""); const [nm,setNm]=useState("");\n const add = () => {\n const id=parseInt(nid);\n if(!id||id<1||id>4094||vlans.find(v=>v.id===id)) return;\n setVlans([...vlans,{id,name:nm||`VLAN-${id}`,color:VLAN_COLORS[vlans.length%VLAN_COLORS.length]}]);\n setNid(""); setNm("");\n };\n const cnt = vid => ports.filter(p=>p.mode==="access"?p.accessVlan===vid:p.taggedVlans?.includes(vid)).length;\n return (\n <div className="main">\n <div style={{flex:1}}>\n <div className="panel">\n <div className="ph">◈ VLAN Manager</div>\n <div className="pb">\n <table className="vtbl">\n <thead><tr><th>ID</th><th>Color</th><th>Name</th><th>Ports</th><th>Subnet</th><th></th></tr></thead>\n <tbody>\n {vlans.map(v=>(\n <tr key={v.id}>\n <td style={{color:"var(--ac)",fontWeight:700}}>{v.id}</td>\n <td><span className="sw" style={{background:v.color}}/></td>\n <td><input className="ii" value={v.name} onChange={e=>setVlans(vlans.map(x=>x.id===v.id?{...x,name:e.target.value}:x))}/></td>\n <td><span className="badge" style={{background:"var(--b2)"}}>{cnt(v.id)}</span></td>\n <td style={{color:"var(--dm)"}}>192.168.{v.id}.0/24</td>\n <td>{v.id!==1&&<button className="btn bd" style={{padding:"2px 8px",fontSize:10}} onClick={()=>setVlans(vlans.filter(x=>x.id!==v.id))}>✕</button>}</td>\n </tr>\n ))}\n </tbody>\n </table>\n <div style={{marginTop:16,paddingTop:12,borderTop:"1px solid var(--b1)"}}>\n <div className="sect">Add VLAN</div>\n <div style={{display:"flex",gap:8,alignItems:"flex-end"}}>\n <div className="field" style={{margin:0,width:90}}><label>ID</label><input value={nid} onChange={e=>setNid(e.target.value)} type="number" placeholder="100"/></div>\n <div className="field" style={{margin:0,flex:1}}><label>Name</label><input value={nm} onChange={e=>setNm(e.target.value)} placeholder="e.g. POS"/></div>\n <button className="btn bp" onClick={add}>Add</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n}\n\nfunction AclTab({ acls, setAcls, vlans }) {\n const [nn,setNn]=useState(""); const [nv,setNv]=useState(vlans[0]?.id||1); const [nd,setNd]=useState("in");\n const addAcl=()=>{if(!nn)return;setAcls([...acls,{name:nn,applyVlan:nv,direction:nd,rules:[]}]);setNn("");};\n const addRule=name=>setAcls(acls.map(a=>a.name!==name?a:{...a,rules:[...a.rules,{action:"deny",proto:"ip",src:"",srcMask:"0.0.0.255",srcAny:true,dst:"",dstMask:"0.0.0.255",dstAny:true,port:""}]}));\n const upRule=(name,idx,k,v)=>setAcls(acls.map(a=>a.name!==name?a:{...a,rules:a.rules.map((r,i)=>i===idx?{...r,[k]:v}:r)}));\n const delRule=(name,idx)=>setAcls(acls.map(a=>a.name!==name?a:{...a,rules:a.rules.filter((_,i)=>i!==idx)}));\n return (\n <div className="main">\n <div style={{flex:1}}>\n <div className="panel">\n <div className="ph">◈ ACL Builder</div>\n <div className="pb">\n {acls.length===0&&<div className="empty">No ACLs defined.</div>}\n {acls.map(acl=>(\n <div key={acl.name} className="acl-card">\n <div className="acl-hd">\n <span className="acl-nm">{acl.name}</span>\n <span style={{fontSize:11,color:"var(--dm)"}}>VLAN {acl.applyVlan} / {acl.direction.toUpperCase()}</span>\n <button className="btn bd" style={{padding:"2px 8px",fontSize:10}} onClick={()=>setAcls(acls.filter(a=>a.name!==acl.name))}>✕</button>\n </div>\n <div className="acl-rules">\n {acl.rules.map((r,i)=>(\n <div key={i} className="acl-rule">\n <select value={r.action} onChange={e=>upRule(acl.name,i,"action",e.target.value)}>{["permit","deny"].map(a=><option key={a}>{a}</option>)}</select>\n <select value={r.proto} onChange={e=>upRule(acl.name,i,"proto",e.target.value)}>{["ip","tcp","udp","icmp"].map(p=><option key={p}>{p}</option>)}</select>\n <div style={{display:"flex",gap:4,alignItems:"center"}}>\n <input placeholder={r.srcAny?"any":"10.0.0.0"} value={r.src} disabled={r.srcAny} onChange={e=>upRule(acl.name,i,"src",e.target.value)} style={{flex:1}}/>\n <label style={{fontSize:10,color:"var(--dm)",display:"flex",gap:3,alignItems:"center",whiteSpace:"nowrap"}}><input type="checkbox" checked={r.srcAny} onChange={e=>upRule(acl.name,i,"srcAny",e.target.checked)}/>any</label>\n </div>\n <div style={{display:"flex",gap:4,alignItems:"center"}}>\n <input placeholder={r.dstAny?"any":"10.0.0.0"} value={r.dst} disabled={r.dstAny} onChange={e=>upRule(acl.name,i,"dst",e.target.value)} style={{flex:1}}/>\n <label style={{fontSize:10,color:"var(--dm)",display:"flex",gap:3,alignItems:"center",whiteSpace:"nowrap"}}><input type="checkbox" checked={r.dstAny} onChange={e=>upRule(acl.name,i,"dstAny",e.target.checked)}/>any</label>\n </div>\n <input placeholder="port" value={r.port} onChange={e=>upRule(acl.name,i,"port",e.target.value)}/>\n <button className="btn bd" style={{padding:"2px 6px"}} onClick={()=>delRule(acl.name,i)}>✕</button>\n </div>\n ))}\n <button className="btn bg" style={{marginTop:6,fontSize:10}} onClick={()=>addRule(acl.name)}>+ Add Rule</button>\n </div>\n </div>\n ))}\n <div style={{marginTop:16,paddingTop:12,borderTop:"1px solid var(--b1)"}}>\n <div className="sect">New ACL</div>\n <div style={{display:"flex",gap:8,alignItems:"flex-end"}}>\n <div className="field" style={{margin:0,flex:1}}><label>Name</label><input value={nn} onChange={e=>setNn(e.target.value)} placeholder="BLOCK-IOT"/></div>\n <div className="field" style={{margin:0,width:130}}><label>VLAN</label><select value={nv} onChange={e=>setNv(+e.target.value)}>{vlans.map(v=><option key={v.id} value={v.id}>{v.id} — {v.name}</option>)}</select></div>\n <div className="field" style={{margin:0,width:75}}><label>Direction</label><select value={nd} onChange={e=>setNd(e.target.value)}><option value="in">in</option><option value="out">out</option></select></div>\n <button className="btn bp" onClick={addAcl}>Create</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// APP\n// ══════════════════════════════════════════════════════════════════════════════\nexport default function App() {\n const [tab, setTab] = useState("ports");\n const [ports, setPorts] = useState(DEFAULT_PORTS);\n const [vlans, setVlans] = useState(DEFAULT_VLANS);\n const [acls, setAcls] = useState([]);\n const [selected, setSelected] = useState(null);\n const [hostname, setHostname] = useState("ERS-5952");\n const [switchIP, setSwitchIP] = useState("192.168.99.1");\n const [settings, setSettings] = useState({ cliMode: false, defaultPushMode: "batch" });\n const [showSettings, setShowSettings] = useState(false);\n\n const [connState, setConnState] = useState("connecting");\n const [connInfo, setConnInfo] = useState("");\n const connTimer = useRef(null);\n\n const [pollStatus, setPollStatus] = useState("idle");\n const [session, setSession] = useState(null);\n const [showTotp, setShowTotp] = useState(false);\n\n const updatePort = useCallback(p => setPorts(prev => prev.map(x => x.id===p.id?p:x)), []);\n\n // Heartbeat\n useEffect(() => {\n let firstPoll = true;\n const beat = async () => {\n const mode = document.hidden ? "background" : "active";\n try {\n const data = await API("/heartbeat", { method:"POST", body:{ visitor_id: VISITOR_ID, mode } });\n if (firstPoll) {\n firstPoll = false;\n setConnState("connected");\n setConnInfo(`Connected — ${switchIP}`);\n if (connTimer.current) clearTimeout(connTimer.current);\n connTimer.current = setTimeout(() => setConnState("hidden"), 3000);\n } else if (connState === "error") {\n setConnState("connected");\n setConnInfo(`Reconnected`);\n connTimer.current = setTimeout(() => setConnState("hidden"), 3000);\n }\n setPollStatus(data.poll_error ? "warn" : data.last_poll ? "ok" : "idle");\n } catch {\n setConnState("error");\n setPollStatus("err");\n firstPoll = true;\n }\n };\n beat();\n const t = setInterval(beat, 30000);\n const onVis = () => beat();\n document.addEventListener("visibilitychange", onVis);\n return () => { clearInterval(t); document.removeEventListener("visibilitychange", onVis); };\n }, [switchIP]);\n\n const handleTotpSuccess = (token) => {\n setShowTotp(false);\n setSession({ token });\n };\n\n const TABS = [\n { id:"ports", label:"Port Map" },\n { id:"vlans", label:"VLANs" },\n { id:"acls", label:"ACL Builder" },\n { id:"cli", label:"Review & Push" },\n { id:"devices", label:"Device Access" },\n { id:"dhcp", label:"DHCP" },\n { id:"dns", label:"DNS Filtering" },\n { id:"vpn", label:"VPN" },\n ];\n\n return (\n <>\n <style>{css}</style>\n <div className="app">\n <ConnBanner state={connState} info={connInfo}/>\n <div className="topbar">\n <div>\n <div className="logo">ERS-5952 MANAGER</div>\n <div className="logo-sub">Extreme Networks / Avaya ERS 5900 Series</div>\n </div>\n <div className="sp"/>\n <span className="tl">Hostname</span>\n <input className="ti" value={hostname} onChange={e=>setHostname(e.target.value)} placeholder="ERS-5952"/>\n <span className="tl">Switch IP</span>\n <input className="ti" value={switchIP} onChange={e=>setSwitchIP(e.target.value)} placeholder="192.168.99.1"/>\n <div className="poll-pill">\n <span className={`dot ${pollStatus}`}/>\n {pollStatus==="ok"?"Live":pollStatus==="warn"?"Poll error":pollStatus==="err"?"Offline":"Idle"}\n </div>\n <SessionBtn session={session} onUnlock={() => setShowTotp(true)}/>\n <button className="settings-btn" onClick={() => setShowSettings(true)} title="Settings">⚙</button>\n </div>\n\n <div className="tabs">\n {TABS.map(t=>(\n <button key={t.id} className={`tab ${tab===t.id?"active":""}`} onClick={()=>setTab(t.id)}>{t.label}</button>\n ))}\n </div>\n\n {tab==="ports" && <PortTab ports={ports} vlans={vlans} selected={selected} setSelected={setSelected} updatePort={updatePort} pollStatus={pollStatus==="ok"?"ok":"stale"}/>}\n {tab==="vlans" && <VlanTab vlans={vlans} setVlans={setVlans} ports={ports}/>}\n {tab==="acls" && <AclTab acls={acls} setAcls={setAcls} vlans={vlans}/>}\n {tab==="cli" && <CliTab\n ports={ports} vlans={vlans} acls={acls} hostname={hostname}\n session={session} setSession={setSession}\n onNeedAuth={() => setShowTotp(true)}\n backendOk={pollStatus!=="err"}\n settings={settings}\n />}\n {tab==="devices" && <DeviceAccessTab\n session={session}\n onNeedAuth={() => setShowTotp(true)}\n backendOk={pollStatus!=="err"}\n />}\n {tab==="dhcp" && <DHCPTab\n session={session}\n onNeedAuth={() => setShowTotp(true)}\n backendOk={pollStatus!=="err"}\n />}\n {tab==="dns" && <DNSTab\n vlans={vlans}\n session={session}\n onNeedAuth={() => setShowTotp(true)}\n backendOk={pollStatus!=="err"}\n />}\n {tab==="vpn" && <WireGuardTab\n session={session}\n onNeedAuth={() => setShowTotp(true)}\n backendOk={pollStatus!=="err"}\n />}\n\n {showTotp && <TotpModal\n onSuccess={handleTotpSuccess}\n onCancel={() => setShowTotp(false)}\n commandCount={generateAnnotatedCLI({ports,vlans,acls,hostname}).length}\n />}\n\n {showSettings && <SettingsPanel\n settings={settings} setSettings={setSettings}\n onClose={() => setShowSettings(false)}\n />}\n </div>\n </>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// DEVICE ACCESS TAB\n// ══════════════════════════════════════════════════════════════════════════════\n\nconst MAC_TIPS = {\n ios: "Settings → Wi-Fi → your network → Private Wi-Fi Address → OFF\\nThen reconnect. Find real MAC: Settings → General → About → Wi-Fi Address",\n android: "Settings → Network → Wi-Fi → your network → Privacy → Use device MAC\\nThen reconnect.",\n macos: "System Settings → Network → your connection → Details → Hardware → Manually set MAC",\n windows: "Settings → Network → your adapter → Hardware properties → Random hardware addresses → OFF",\n};\n\nfunction DeviceAccessTab({ session, onNeedAuth, backendOk }) {\n const [devices, setDevices] = useState({ saved: [], live: [], mgmt_ip: "" });\n const [loading, setLoading] = useState(false);\n const [showForm, setShowForm] = useState(false);\n const [editDevice, setEditDevice] = useState(null);\n const [showMacTip, setShowMacTip] = useState(null);\n const [pushResult, setPushResult] = useState(null);\n const [form, setForm] = useState({ name:"", mac:"", ip:"", vlan:10, management_access:false, static_ip:false, notes:"" });\n\n const load = async () => {\n setLoading(true);\n try { setDevices(await API("/devices")); } catch(e) { console.error(e); }\n setLoading(false);\n };\n\n useEffect(() => { if (backendOk) load(); }, [backendOk]);\n\n const openAdd = () => { setForm({ name:"", mac:"", ip:"", vlan:10, management_access:false, static_ip:false, notes:"" }); setEditDevice(null); setShowForm(true); };\n const openEdit = (d) => { setForm({...d}); setEditDevice(d); setShowForm(true); };\n\n const save = async () => {\n if (!session) { onNeedAuth(); return; }\n try {\n const r = await API("/devices/save", { method:"POST", body:{ token: session.token, device: form } });\n setDevices(d => ({ ...d, saved: r.devices }));\n setShowForm(false);\n } catch(e) { alert(e.message); }\n };\n\n const del = async (mac) => {\n if (!session) { onNeedAuth(); return; }\n if (!confirm("Remove this device?")) return;\n try {\n const r = await API("/devices/delete", { method:"POST", body:{ token: session.token, mac } });\n setDevices(d => ({ ...d, saved: r.devices }));\n } catch(e) { alert(e.message); }\n };\n\n const pushReservation = async (device) => {\n if (!session) { onNeedAuth(); return; }\n try {\n const r = await API("/devices/push-reservation", { method:"POST", body:{ token: session.token, device } });\n setPushResult(r);\n } catch(e) { setPushResult({ success:false, error:e.message }); }\n };\n\n const pushPinhole = async (mac, allow) => {\n if (!session) { onNeedAuth(); return; }\n try {\n const r = await API("/devices/push-pinhole", { method:"POST", body:{ token: session.token, mac, allow } });\n setPushResult(r);\n } catch(e) { setPushResult({ success:false, error:e.message }); }\n };\n\n const adoptLive = (live) => {\n setForm({ name: live.hostname||"", mac: live.mac, ip: live.ip, vlan:10, management_access:false, static_ip:false, notes:"" });\n setEditDevice(null); setShowForm(true);\n };\n\n const savedMacs = new Set(devices.saved.map(d => d.mac));\n const unregistered = (devices.live||[]).filter(l => !savedMacs.has(l.mac));\n\n return (\n <div className="main" style={{flexDirection:"column",gap:12}}>\n\n {/* MAC randomization warning */}\n <div className="panel">\n <div className="ph">◈ Device Access — Management Network Pinhole</div>\n <div className="pb">\n <div style={{fontSize:12,color:"var(--dm)",marginBottom:12,lineHeight:1.7}}>\n Devices listed here can reach the switch manager UI directly from their normal VLAN\n without needing to be on VLAN 99 or connected to VPN. The switch enforces access\n via an ACL pinhole. TOTP still gates any changes.\n </div>\n <div style={{background:"rgba(255,234,0,.06)",border:"1px solid rgba(255,234,0,.2)",borderRadius:4,padding:"10px 14px",marginBottom:12}}>\n <div style={{color:"var(--warn)",fontSize:11,fontWeight:700,letterSpacing:1,textTransform:"uppercase",marginBottom:6}}>\n ⚠ MAC Address Randomization\n </div>\n <div style={{fontSize:11,color:"var(--tx)",marginBottom:8,lineHeight:1.6}}>\n Modern phones and laptops use random MAC addresses per network by default.\n This breaks DHCP reservations and makes stable IP assignment impossible.\n Disable it on each device before adding it here.\n </div>\n <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>\n {Object.entries({iOS:"ios",Android:"android",macOS:"macos",Windows:"windows"}).map(([label,key])=>(\n <button key={key} className="btn bg" style={{padding:"3px 10px",fontSize:10}}\n onClick={()=>setShowMacTip(showMacTip===key?null:key)}>\n {label}\n </button>\n ))}\n </div>\n {showMacTip && (\n <div style={{marginTop:8,background:"var(--bg)",borderRadius:3,padding:"8px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--tx)",whiteSpace:"pre-line"}}>\n {MAC_TIPS[showMacTip]}\n </div>\n )}\n </div>\n <button className="btn bp" onClick={openAdd}>+ Add Device</button>\n <button className="btn bg" style={{marginLeft:8}} onClick={load}>↻ Refresh</button>\n </div>\n </div>\n\n {/* Saved devices */}\n <div className="panel">\n <div className="ph">◈ Registered Devices ({devices.saved.length})</div>\n <div className="pb">\n {devices.saved.length === 0 && <div className="empty">No devices registered yet.</div>}\n {devices.saved.map(d => (\n <div key={d.mac} style={{background:"var(--bg)",border:"1px solid var(--b2)",borderRadius:4,padding:"10px 12px",marginBottom:8}}>\n <div style={{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"}}>\n <div style={{flex:1}}>\n <div style={{fontWeight:700,marginBottom:2}}>{d.name}</div>\n <div style={{fontFamily:"var(--mono)",fontSize:11,color:"var(--dm)"}}>\n {d.mac} · {d.ip} · VLAN {d.vlan}\n </div>\n {d.notes && <div style={{fontSize:11,color:"var(--dm)",marginTop:2}}>{d.notes}</div>}\n </div>\n <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>\n {d.static_ip && (\n <button className="btn bg" style={{fontSize:10,padding:"3px 8px"}}\n onClick={() => pushReservation(d)}>\n Push DHCP Reservation\n </button>\n )}\n <button\n className={`btn ${d.management_access?"bd":"bs"}`}\n style={{fontSize:10,padding:"3px 8px"}}\n onClick={() => pushPinhole(d.mac, !d.management_access)}>\n {d.management_access ? "Revoke Access" : "Grant Access"}\n </button>\n <button className="btn bg" style={{fontSize:10,padding:"3px 8px"}} onClick={()=>openEdit(d)}>Edit</button>\n <button className="btn bd" style={{fontSize:10,padding:"3px 8px"}} onClick={()=>del(d.mac)}>✕</button>\n </div>\n </div>\n <div style={{display:"flex",gap:8,marginTop:6}}>\n <span className={`badge ${d.management_access?"":"" }`}\n style={{background:d.management_access?"rgba(0,230,118,.15)":"rgba(90,96,112,.15)",\n color:d.management_access?"var(--ok)":"var(--dm)"}}>\n {d.management_access ? "✓ Management access" : "✗ No management access"}\n </span>\n <span className="badge" style={{background:d.static_ip?"rgba(0,229,255,.12)":"rgba(90,96,112,.12)",\n color:d.static_ip?"var(--ac)":"var(--dm)"}}>\n {d.static_ip ? "Static IP reserved" : "Dynamic IP"}\n </span>\n </div>\n </div>\n ))}\n </div>\n </div>\n\n {/* Live DHCP leases */}\n {unregistered.length > 0 && (\n <div className="panel">\n <div className="ph">◈ Live DHCP Leases — Unregistered ({unregistered.length})</div>\n <div className="pb">\n <div style={{fontSize:11,color:"var(--dm)",marginBottom:10}}>\n These devices are on the network but not registered. Click to add them.\n </div>\n {unregistered.map(l => (\n <div key={l.mac} style={{display:"flex",alignItems:"center",gap:10,padding:"8px 0",borderBottom:"1px solid var(--b1)"}}>\n <div style={{flex:1,fontFamily:"var(--mono)",fontSize:11}}>\n <span style={{color:"var(--tx)"}}>{l.ip}</span>\n <span style={{color:"var(--dm)",margin:"0 8px"}}>·</span>\n <span style={{color:"var(--dm)"}}>{l.mac}</span>\n {l.hostname && l.hostname !== "unknown" && (\n <span style={{color:"var(--ac)",marginLeft:8}}>{l.hostname}</span>\n )}\n </div>\n <button className="btn bg" style={{fontSize:10,padding:"3px 8px"}} onClick={()=>adoptLive(l)}>\n + Register\n </button>\n </div>\n ))}\n </div>\n </div>\n )}\n\n {/* Push result */}\n {pushResult && (\n <div className="panel">\n <div className={`ph ${pushResult.success?"":"" }`}\n style={{color:pushResult.success?"var(--ok)":"var(--err)"}}>\n {pushResult.success ? "✓ Push successful — config saved" : `✗ Push failed: ${pushResult.error}`}\n <button className="btn bg" style={{marginLeft:"auto",padding:"2px 8px",fontSize:10}}\n onClick={()=>setPushResult(null)}>✕</button>\n </div>\n </div>\n )}\n\n {/* Add/Edit form modal */}\n {showForm && (\n <div className="modal-bg" onClick={()=>setShowForm(false)}>\n <div className="modal" style={{width:440,textAlign:"left"}} onClick={e=>e.stopPropagation()}>\n <h2 style={{marginBottom:16}}>{editDevice?"EDIT DEVICE":"ADD DEVICE"}</h2>\n <div className="field"><label>Device Name</label>\n <input value={form.name} onChange={e=>setForm(f=>({...f,name:e.target.value}))} placeholder="e.g. Dev Laptop, iPhone"/></div>\n <div className="field"><label>MAC Address</label>\n <input value={form.mac} onChange={e=>setForm(f=>({...f,mac:e.target.value}))}\n placeholder="aa:bb:cc:dd:ee:ff" style={{fontFamily:"var(--mono)"}}/></div>\n <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>\n <div className="field"><label>IP Address</label>\n <input value={form.ip} onChange={e=>setForm(f=>({...f,ip:e.target.value}))}\n placeholder="192.168.10.50" style={{fontFamily:"var(--mono)"}}/></div>\n <div className="field"><label>VLAN</label>\n <input type="number" value={form.vlan} onChange={e=>setForm(f=>({...f,vlan:+e.target.value}))}/></div>\n </div>\n <div className="field"><label>Notes (optional)</label>\n <input value={form.notes} onChange={e=>setForm(f=>({...f,notes:e.target.value}))} placeholder="e.g. Main dev laptop"/></div>\n <div style={{display:"flex",gap:16,marginBottom:14}}>\n <label style={{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"}}>\n <input type="checkbox" checked={form.static_ip}\n onChange={e=>setForm(f=>({...f,static_ip:e.target.checked}))}/>\n Reserve static IP (DHCP binding)\n </label>\n <label style={{display:"flex",alignItems:"center",gap:6,fontSize:12,cursor:"pointer"}}>\n <input type="checkbox" checked={form.management_access}\n onChange={e=>setForm(f=>({...f,management_access:e.target.checked}))}/>\n Grant management access\n </label>\n </div>\n <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>\n <button className="btn bg" onClick={()=>setShowForm(false)}>Cancel</button>\n <button className="btn bp" onClick={save}>Save Device</button>\n </div>\n </div>\n </div>\n )}\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// WIREGUARD TAB\n// ══════════════════════════════════════════════════════════════════════════════\n\nfunction QRModal({ config, name, onClose }) {\n // Render QR using a simple API since we can\'t use native qrencode in browser\n const [qrUrl, setQrUrl] = useState(\'\');\n useEffect(() => {\n // Use Google Charts QR API (works offline-ish, data URI approach)\n const encoded = encodeURIComponent(config);\n setQrUrl(`https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encoded}`);\n }, [config]);\n\n return (\n <div className="modal-bg" onClick={onClose}>\n <div className="modal" onClick={e=>e.stopPropagation()}>\n <h2>◈ {name.toUpperCase()}</h2>\n <p style={{marginBottom:12}}>Scan with WireGuard app<br/>\n <span style={{fontSize:10,color:"var(--dm)"}}>iOS App Store / Android Play Store: search "WireGuard"<br/>\n Desktop: wireguard.com/install</span>\n </p>\n {qrUrl && <img src={qrUrl} alt="WireGuard QR" style={{width:220,height:220,margin:"0 auto 12px",display:"block",borderRadius:4}}/>}\n <div style={{background:"var(--bg)",borderRadius:3,padding:8,fontFamily:"var(--mono)",fontSize:10,\n color:"var(--dm)",textAlign:"left",whiteSpace:"pre",overflowX:"auto",\n maxHeight:120,overflowY:"auto",marginBottom:12}}>\n {config}\n </div>\n <div style={{display:"flex",gap:8,justifyContent:"center"}}>\n <button className="btn bg" onClick={()=>{\n const a=document.createElement(\'a\');\n a.href=URL.createObjectURL(new Blob([config],{type:\'text/plain\'}));\n a.download=`${name}.conf`; a.click();\n }}>Download .conf</button>\n <button className="btn bg" onClick={()=>navigator.clipboard?.writeText(config)}>Copy</button>\n <button className="btn bp" onClick={onClose}>Done</button>\n </div>\n </div>\n </div>\n );\n}\n\nfunction WireGuardTab({ session, onNeedAuth, backendOk }) {\n const [status, setStatus] = useState(null);\n const [clients, setClients] = useState([]);\n const [newName, setNewName] = useState(\'\');\n const [adding, setAdding] = useState(false);\n const [qrModal, setQrModal] = useState(null); // { config, name }\n const [error, setError] = useState(\'\');\n\n const load = async () => {\n try {\n const [s, c] = await Promise.all([API("/wireguard/status"), API("/wireguard/clients")]);\n setStatus(s); setClients(c.clients||[]);\n } catch(e) { setError(e.message); }\n };\n\n useEffect(() => { if (backendOk) load(); }, [backendOk]);\n\n const addClient = async () => {\n if (!newName.trim()) return;\n if (!session) { onNeedAuth(); return; }\n setAdding(true); setError(\'\');\n try {\n const r = await API("/wireguard/add-client", {\n method:"POST", body:{ token: session.token, name: newName.trim() }\n });\n setQrModal({ config: r.config, name: r.name });\n setNewName(\'\');\n await load();\n } catch(e) { setError(e.message); }\n setAdding(false);\n };\n\n const showQR = async (name) => {\n try {\n const r = await API(`/wireguard/client-qr/${name}`);\n setQrModal({ config: r.config, name: r.name });\n } catch(e) { setError(e.message); }\n };\n\n const revoke = async (name) => {\n if (!session) { onNeedAuth(); return; }\n if (!confirm(`Revoke access for "${name}"? They will be disconnected immediately.`)) return;\n try {\n await API("/wireguard/revoke-client", { method:"POST", body:{ token: session.token, name } });\n await load();\n } catch(e) { setError(e.message); }\n };\n\n const isRunning = status?.running;\n\n return (\n <div className="main" style={{flexDirection:"column",gap:12}}>\n <div className="panel">\n <div className="ph">◈ WireGuard VPN\n <span style={{marginLeft:"auto",fontFamily:"var(--mono)",fontSize:10,\n color:isRunning?"var(--ok)":"var(--err)"}}>\n {isRunning ? "● Running" : "○ Not running"}\n </span>\n </div>\n <div className="pb">\n <div style={{fontSize:12,color:"var(--dm)",lineHeight:1.7,marginBottom:12}}>\n WireGuard lets you connect from anywhere — home WiFi, coffee shop, anywhere —\n and reach the switch manager as if you were on the management network.\n Each device gets its own key. Revoking a key disconnects that device immediately.\n </div>\n {!isRunning && (\n <div style={{background:"rgba(255,23,68,.07)",border:"1px solid rgba(255,23,68,.2)",\n borderRadius:4,padding:"10px 14px",marginBottom:12,fontSize:11,color:"var(--err)"}}>\n WireGuard is not running on this machine. Run setup again and choose the WireGuard option,\n or run: <span style={{fontFamily:"var(--mono)"}}>sudo systemctl start wg-quick@wg0</span>\n </div>\n )}\n {error && <div style={{color:"var(--err)",fontSize:11,marginBottom:10}}>{error}</div>}\n </div>\n </div>\n\n {/* Connected peers */}\n {isRunning && status?.peers?.length > 0 && (\n <div className="panel">\n <div className="ph">◈ Connected Peers ({status.peers.length})</div>\n <div className="pb">\n {status.peers.map((p,i) => (\n <div key={i} style={{padding:"8px 0",borderBottom:"1px solid var(--b1)",\n display:"flex",alignItems:"center",gap:12}}>\n <div style={{flex:1}}>\n <div style={{fontWeight:700,marginBottom:2}}>{p.name}</div>\n <div style={{fontFamily:"var(--mono)",fontSize:10,color:"var(--dm)"}}>\n {p.allowed_ips} · {p.endpoint||"not connected"}\n </div>\n {p.last_handshake && (\n <div style={{fontSize:10,color:"var(--dm)"}}>Last seen: {p.last_handshake}</div>\n )}\n {p.transfer && (\n <div style={{fontSize:10,color:"var(--dm)"}}>Transfer: {p.transfer}</div>\n )}\n </div>\n <div style={{width:8,height:8,borderRadius:"50%",\n background:p.last_handshake&&!p.last_handshake.includes("never")?"var(--ok)":"var(--dm)"}}/>\n </div>\n ))}\n </div>\n </div>\n )}\n\n {/* Client management */}\n <div className="panel">\n <div className="ph">◈ VPN Clients</div>\n <div className="pb">\n {clients.length === 0 && <div className="empty" style={{padding:"16px 0"}}>No clients configured yet.</div>}\n {clients.map(c => (\n <div key={c.name} style={{display:"flex",alignItems:"center",gap:8,\n padding:"8px 0",borderBottom:"1px solid var(--b1)"}}>\n <span style={{flex:1,fontWeight:600}}>{c.name}</span>\n <button className="btn bg" style={{fontSize:10,padding:"3px 8px"}} onClick={()=>showQR(c.name)}>\n QR / .conf\n </button>\n <button className="btn bd" style={{fontSize:10,padding:"3px 8px"}} onClick={()=>revoke(c.name)}>\n Revoke\n </button>\n </div>\n ))}\n\n <div style={{marginTop:14,paddingTop:12,borderTop:"1px solid var(--b1)",display:"flex",gap:8,alignItems:"flex-end"}}>\n <div className="field" style={{margin:0,flex:1}}>\n <label>Add New Client</label>\n <input value={newName} onChange={e=>setNewName(e.target.value)}\n onKeyDown={e=>e.key==="Enter"&&addClient()}\n placeholder="e.g. laptop, phone, tablet"/>\n </div>\n <button className="btn bp" onClick={addClient} disabled={!newName.trim()||adding||!isRunning}>\n {adding?"Adding...":"Add Client"}\n </button>\n </div>\n {!session && (\n <div style={{fontSize:11,color:"var(--dm)",marginTop:8}}>\n <button className="btn bg" style={{fontSize:10,padding:"3px 8px",marginRight:6}}\n onClick={onNeedAuth}>Authenticate</button>\n to add or revoke clients\n </div>\n )}\n </div>\n </div>\n\n {/* SSH tunnel info */}\n <div className="panel">\n <div className="ph">◈ SSH Tunnel — Power User Alternative</div>\n <div className="pb">\n <div style={{fontSize:12,color:"var(--dm)",lineHeight:1.7,marginBottom:8}}>\n If WireGuard is not available, SSH port forwarding gives secure access\n in one command. Run this on your remote machine:\n </div>\n <div style={{background:"#060809",borderRadius:4,padding:"10px 14px",\n fontFamily:"var(--mono)",fontSize:12,color:"#a0b0c0",marginBottom:8}}>\n ssh -L 8765:localhost:8765 user@your-management-computer-ip\n </div>\n <div style={{fontSize:11,color:"var(--dm)"}}>\n Then open <span style={{color:"var(--ac)",fontFamily:"var(--mono)"}}>http://localhost:8765</span> in your browser.\n The management computer needs SSH accessible from outside (key auth only, consider fail2ban).\n </div>\n </div>\n </div>\n\n {qrModal && <QRModal config={qrModal.config} name={qrModal.name} onClose={()=>setQrModal(null)}/>}\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// DHCP MANAGEMENT TAB\n// ══════════════════════════════════════════════════════════════════════════════\n\nfunction ConflictBadge({ conflict }) {\n return (\n <div style={{\n background: conflict.ip_conflict\n ? "rgba(255,23,68,.1)" : "rgba(255,234,0,.08)",\n border: `1px solid ${conflict.ip_conflict ? "rgba(255,23,68,.3)" : "rgba(255,234,0,.25)"}`,\n borderRadius: 4, padding: "8px 12px", marginBottom: 8,\n }}>\n <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:4}}>\n <span style={{\n color: conflict.ip_conflict ? "var(--err)" : "var(--warn)",\n fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1\n }}>\n {conflict.ip_conflict ? "✗ IP Conflict" : "⚠ Duplicate Entry"}\n </span>\n <span style={{fontFamily:"var(--mono)",fontSize:11,color:"var(--dm)"}}>{conflict.mac}</span>\n {conflict.hostname && <span style={{fontSize:11,color:"var(--tx)"}}>{conflict.hostname}</span>}\n </div>\n <div style={{fontSize:11,color:"var(--dm)",fontFamily:"var(--mono)",marginBottom:8}}>\n Switch: <span style={{color:"var(--ac)"}}>{conflict.switch_ip}</span>\n <span style={{margin:"0 8px"}}>·</span>\n OPNsense: <span style={{color:"var(--ac)"}}>{conflict.opnsense_ip}</span>\n </div>\n {conflict.ip_conflict\n ? <div style={{fontSize:11,color:"var(--err)",marginBottom:8}}>\n Same device has different IPs on switch and OPNsense. One will win — decide which is correct.\n </div>\n : <div style={{fontSize:11,color:"var(--warn)",marginBottom:8}}>\n Same reservation exists in both places. Not harmful but messy — consider removing one.\n </div>\n }\n </div>\n );\n}\n\nfunction OPNsenseSetup({ onConfigured }) {\n const [detecting, setDetecting] = useState(false);\n const [detected, setDetected] = useState(null);\n const [host, setHost] = useState(\'\');\n const [key, setKey] = useState(\'\');\n const [secret, setSecret] = useState(\'\');\n const [testing, setTesting] = useState(false);\n const [error, setError] = useState(\'\');\n\n const detect = async () => {\n setDetecting(true); setError(\'\');\n try {\n const r = await API("/dhcp/detect-opnsense");\n setDetected(r);\n if (r.detected) setHost(r.host);\n } catch(e) { setError(e.message); }\n setDetecting(false);\n };\n\n const connect = async () => {\n if (!host || !key || !secret) return;\n setTesting(true); setError(\'\');\n try {\n const r = await API("/dhcp/configure-opnsense", {\n method: "POST", body: { host, key, secret }\n });\n onConfigured(r);\n } catch(e) { setError(e.message); }\n setTesting(false);\n };\n\n return (\n <div style={{background:"var(--bg)",border:"1px solid var(--b2)",borderRadius:5,padding:14}}>\n <div style={{fontSize:12,fontWeight:700,marginBottom:8,color:"var(--ac)"}}>Connect OPNsense</div>\n <div style={{fontSize:11,color:"var(--dm)",lineHeight:1.7,marginBottom:12}}>\n Optional — provides a unified view of all DHCP reservations across your network.\n The switch manager will show reservations from both the switch and OPNsense side-by-side,\n flag conflicts, and let you sync between them.<br/><br/>\n In OPNsense: System → Access → Users → your user → API keys → Create key\n </div>\n <div style={{display:"flex",gap:8,marginBottom:10}}>\n <button className="btn bg" onClick={detect} disabled={detecting} style={{fontSize:11}}>\n {detecting ? "Detecting..." : "Auto-detect OPNsense"}\n </button>\n {detected && !detected.detected && (\n <span style={{fontSize:11,color:"var(--dm)",alignSelf:"center"}}>\n Not found at {detected.gateway}\n </span>\n )}\n {detected?.detected && (\n <span style={{fontSize:11,color:"var(--ok)",alignSelf:"center"}}>\n ✓ Found at {detected.host}\n </span>\n )}\n </div>\n <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginBottom:10}}>\n <div className="field" style={{margin:0}}>\n <label>OPNsense IP</label>\n <input value={host} onChange={e=>setHost(e.target.value)} placeholder="192.168.99.1"\n style={{fontFamily:"var(--mono)"}}/>\n </div>\n <div className="field" style={{margin:0}}>\n <label>API Key</label>\n <input value={key} onChange={e=>setKey(e.target.value)} placeholder="key"\n style={{fontFamily:"var(--mono)"}}/>\n </div>\n <div className="field" style={{margin:0}}>\n <label>API Secret</label>\n <input type="password" value={secret} onChange={e=>setSecret(e.target.value)}\n placeholder="secret"/>\n </div>\n </div>\n {error && <div style={{color:"var(--err)",fontSize:11,marginBottom:8}}>{error}</div>}\n <button className="btn bp" onClick={connect} disabled={!host||!key||!secret||testing}>\n {testing ? "Testing..." : "Connect & Save"}\n </button>\n </div>\n );\n}\n\nfunction DHCPRow({ res, source, onSync, session, onNeedAuth }) {\n const [syncing, setSyncing] = useState(false);\n\n const doSync = async (direction) => {\n if (!session) { onNeedAuth(); return; }\n setSyncing(true);\n try {\n await onSync(res.mac, direction);\n } finally { setSyncing(false); }\n };\n\n const sourceColor = source === "switch" ? "var(--ac)" : "var(--warn)";\n const sourceName = source === "switch" ? "Switch" : "OPNsense";\n\n return (\n <tr style={{borderBottom:"1px solid var(--b1)"}}>\n <td style={{padding:"7px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--dm)"}}>\n {res.mac}\n </td>\n <td style={{padding:"7px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--ac)"}}>\n {res.ip}\n </td>\n <td style={{padding:"7px 10px",fontSize:12}}>\n {res.hostname || res.descr || <span style={{color:"var(--dm)"}}>—</span>}\n </td>\n <td style={{padding:"7px 10px"}}>\n <span style={{\n background: `${sourceColor}18`, color: sourceColor,\n borderRadius: 10, padding: "1px 7px", fontSize: 10,\n fontFamily: "var(--mono)", fontWeight: 700\n }}>{sourceName}</span>\n {res.if && <span style={{fontSize:10,color:"var(--dm)",marginLeft:6}}>{res.if}</span>}\n </td>\n <td style={{padding:"7px 10px"}}>\n <div style={{display:"flex",gap:4}}>\n {source === "switch" && (\n <button className="btn bg" style={{fontSize:10,padding:"2px 7px"}} disabled={syncing}\n onClick={() => doSync("to_opnsense")}>→ OPNsense</button>\n )}\n {source === "opnsense" && (\n <button className="btn bg" style={{fontSize:10,padding:"2px 7px"}} disabled={syncing}\n onClick={() => doSync("to_switch")}>→ Switch</button>\n )}\n <button className="btn bd" style={{fontSize:10,padding:"2px 7px"}} disabled={syncing}\n onClick={() => doSync(source === "switch" ? "remove_switch" : "remove_opnsense")}>\n Remove\n </button>\n </div>\n </td>\n </tr>\n );\n}\n\nfunction DHCPTab({ session, onNeedAuth, backendOk }) {\n const [overview, setOverview] = useState(null);\n const [loading, setLoading] = useState(false);\n const [showSetup, setShowSetup] = useState(false);\n const [syncResult, setSyncResult] = useState(null);\n const [showConflictSync, setShowConflictSync] = useState(null); // conflict obj\n\n const load = async () => {\n setLoading(true);\n try { setOverview(await API("/dhcp/overview")); }\n catch(e) { console.error(e); }\n setLoading(false);\n };\n\n useEffect(() => { if (backendOk) load(); }, [backendOk]);\n\n const handleSync = async (mac, direction) => {\n if (!session) { onNeedAuth(); return; }\n try {\n const r = await API("/dhcp/sync", { method:"POST", body:{ token:session.token, mac, direction } });\n setSyncResult({ success: true, mac, direction });\n await load();\n } catch(e) {\n setSyncResult({ success: false, error: e.message });\n }\n };\n\n const disconnectOPNsense = async () => {\n if (!confirm("Remove OPNsense connection?")) return;\n await API("/dhcp/configure-opnsense", { method:"DELETE" });\n await load();\n };\n\n const sw = overview?.switch;\n const ops = overview?.opnsense;\n const conflicts = overview?.conflicts || [];\n\n // Merge all reservations for the unified table\n const allRes = [\n ...(sw?.reservations||[]).map(r=>({...r,source:"switch"})),\n ...(ops?.reservations||[]).map(r=>({...r,source:"opnsense"})),\n ];\n\n // Find MACs that appear in both (for conflict highlighting)\n const conflictMacs = new Set(conflicts.map(c=>c.mac));\n\n return (\n <div className="main" style={{flexDirection:"column",gap:12}}>\n\n {/* Header + status */}\n <div className="panel">\n <div className="ph">◈ DHCP Management\n <button className="btn bg" style={{marginLeft:"auto",fontSize:10,padding:"3px 8px"}}\n onClick={load}>↻ Refresh</button>\n </div>\n <div className="pb">\n <div style={{fontSize:12,color:"var(--dm)",lineHeight:1.7,marginBottom:14}}>\n DHCP reservations tie a MAC address to a permanent IP so device access rules\n stay stable. Setting them in two places causes confusion — this panel shows\n everything in one view and helps you keep it consistent.\n </div>\n\n {/* DHCP server status */}\n <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:14}}>\n <div style={{background:"var(--bg)",border:"1px solid var(--b2)",borderRadius:4,padding:"10px 12px"}}>\n <div style={{fontSize:10,fontWeight:700,letterSpacing:2,textTransform:"uppercase",\n color:"var(--dm)",marginBottom:6}}>Switch DHCP</div>\n <div style={{display:"flex",alignItems:"center",gap:6}}>\n <span style={{width:8,height:8,borderRadius:"50%",\n background:sw?.status?.running?"var(--ok)":"var(--dm)"}}/>\n <span style={{fontSize:12}}>\n {sw?.status?.running\n ? `Active — VLAN${sw.status.vlans?.length>1?"s":""} ${sw.status.vlans?.join(", ")||"?"}`\n : "Not running"}\n </span>\n </div>\n {sw?.status?.running && (\n <div style={{fontSize:10,color:"var(--dm)",marginTop:4}}>\n Use for VLAN 99 management — devices get IPs before OPNsense is reachable\n </div>\n )}\n </div>\n <div style={{background:"var(--bg)",border:"1px solid var(--b2)",borderRadius:4,padding:"10px 12px"}}>\n <div style={{fontSize:10,fontWeight:700,letterSpacing:2,textTransform:"uppercase",\n color:"var(--dm)",marginBottom:6}}>OPNsense DHCP</div>\n <div style={{display:"flex",alignItems:"center",gap:6}}>\n <span style={{width:8,height:8,borderRadius:"50%",\n background:ops?.configured?"var(--ok)":"var(--dm)"}}/>\n <span style={{fontSize:12}}>\n {ops?.configured ? `Connected — ${ops.host}` : "Not connected"}\n </span>\n </div>\n <div style={{marginTop:6,display:"flex",gap:6}}>\n {!ops?.configured && (\n <button className="btn bg" style={{fontSize:10,padding:"2px 8px"}}\n onClick={()=>setShowSetup(s=>!s)}>\n {showSetup?"Hide":"Connect OPNsense"}\n </button>\n )}\n {ops?.configured && (\n <button className="btn bg" style={{fontSize:10,padding:"2px 8px"}}\n onClick={disconnectOPNsense}>Disconnect</button>\n )}\n </div>\n </div>\n </div>\n\n {showSetup && (\n <OPNsenseSetup onConfigured={() => { setShowSetup(false); load(); }}/>\n )}\n\n {/* Recommendation */}\n <div style={{background:"rgba(0,229,255,.05)",border:"1px solid rgba(0,229,255,.15)",\n borderRadius:4,padding:"10px 14px",fontSize:11,color:"var(--dm)",lineHeight:1.7}}>\n <span style={{color:"var(--ac)",fontWeight:700}}>Recommendation: </span>\n Use switch DHCP for VLAN 99 (management) only.\n Let OPNsense handle DHCP for all other VLANs — it integrates with DNS,\n firewall rules, and shows everything in one place.\n Never run both for the same VLAN.\n </div>\n </div>\n </div>\n\n {/* Conflicts */}\n {conflicts.length > 0 && (\n <div className="panel">\n <div className="ph" style={{color:"var(--err)"}}>\n ✗ Conflicts Detected ({conflicts.length})\n </div>\n <div className="pb">\n <div style={{fontSize:11,color:"var(--dm)",marginBottom:12}}>\n The same MAC address has reservations in both the switch and OPNsense.\n Decide which one is correct and remove the other.\n </div>\n {conflicts.map(c => (\n <div key={c.mac}>\n <ConflictBadge conflict={c}/>\n <div style={{display:"flex",gap:6,marginBottom:12,flexWrap:"wrap"}}>\n <button className="btn bw" style={{fontSize:11}}\n onClick={()=>setShowConflictSync(showConflictSync?.mac===c.mac?null:c)}>\n {showConflictSync?.mac===c.mac ? "Hide options" : "Resolve →"}\n </button>\n </div>\n {showConflictSync?.mac === c.mac && (\n <div style={{background:"var(--bg)",border:"1px solid var(--b2)",\n borderRadius:4,padding:"10px 14px",marginBottom:12}}>\n <div style={{fontSize:11,fontWeight:700,marginBottom:8}}>Choose which IP wins:</div>\n <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>\n <button className="btn bs" style={{fontSize:11}}\n onClick={()=>{handleSync(c.mac,"to_opnsense");setShowConflictSync(null);}}>\n Switch wins ({c.switch_ip}) — update OPNsense\n </button>\n <button className="btn bs" style={{fontSize:11}}\n onClick={()=>{handleSync(c.mac,"to_switch");setShowConflictSync(null);}}>\n OPNsense wins ({c.opnsense_ip}) — update switch\n </button>\n <button className="btn bd" style={{fontSize:11}}\n onClick={()=>{handleSync(c.mac,"remove_switch");setShowConflictSync(null);}}>\n Remove from switch only\n </button>\n <button className="btn bd" style={{fontSize:11}}\n onClick={()=>{handleSync(c.mac,"remove_opnsense");setShowConflictSync(null);}}>\n Remove from OPNsense only\n </button>\n </div>\n </div>\n )}\n </div>\n ))}\n </div>\n </div>\n )}\n\n {/* Sync result */}\n {syncResult && (\n <div className="panel">\n <div className="ph" style={{color:syncResult.success?"var(--ok)":"var(--err)"}}>\n {syncResult.success ? "✓ Sync complete" : `✗ Sync failed: ${syncResult.error}`}\n <button className="btn bg" style={{marginLeft:"auto",fontSize:10,padding:"2px 8px"}}\n onClick={()=>setSyncResult(null)}>✕</button>\n </div>\n </div>\n )}\n\n {/* Unified reservations table */}\n <div className="panel">\n <div className="ph">◈ All Reservations ({allRes.length})</div>\n <div className="pb" style={{padding:0}}>\n {allRes.length === 0 && (\n <div className="empty">No reservations found. Add devices in the Device Access tab.</div>\n )}\n {allRes.length > 0 && (\n <table style={{width:"100%",borderCollapse:"collapse"}}>\n <thead>\n <tr style={{borderBottom:"1px solid var(--b1)"}}>\n {["MAC","IP","Name / Description","Source","Actions"].map(h=>(\n <th key={h} style={{textAlign:"left",padding:"6px 10px",fontSize:10,\n letterSpacing:2,textTransform:"uppercase",color:"var(--dm)"}}>\n {h}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {allRes.map((r,i) => (\n <tr key={`${r.mac}-${r.source}`}\n style={{\n background: conflictMacs.has(r.mac) ? "rgba(255,234,0,.03)" : "transparent",\n borderLeft: conflictMacs.has(r.mac) ? "2px solid var(--warn)" : "2px solid transparent",\n }}>\n <DHCPRow\n res={r} source={r.source}\n onSync={handleSync}\n session={session} onNeedAuth={onNeedAuth}\n />\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </div>\n </div>\n\n {/* Active leases */}\n {((sw?.leases||[]).length > 0 || (ops?.leases||[]).length > 0) && (\n <div className="panel">\n <div className="ph">◈ Active Leases\n <span style={{marginLeft:6,fontSize:10,color:"var(--dm)"}}>\n ({(sw?.leases||[]).length + (ops?.leases||[]).length} total)\n </span>\n </div>\n <div className="pb" style={{padding:0}}>\n <table style={{width:"100%",borderCollapse:"collapse"}}>\n <thead>\n <tr style={{borderBottom:"1px solid var(--b1)"}}>\n {["MAC","IP","Hostname","Source"].map(h=>(\n <th key={h} style={{textAlign:"left",padding:"6px 10px",fontSize:10,\n letterSpacing:2,textTransform:"uppercase",color:"var(--dm)"}}>\n {h}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {[...(sw?.leases||[]).map(l=>({...l,source:"switch"})),\n ...(ops?.leases||[]).map(l=>({...l,source:"opnsense"}))\n ].map((l,i)=>(\n <tr key={i} style={{borderBottom:"1px solid var(--b1)"}}>\n <td style={{padding:"6px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--dm)"}}>{l.mac}</td>\n <td style={{padding:"6px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--ac)"}}>{l.ip}</td>\n <td style={{padding:"6px 10px",fontSize:11}}>{l.hostname||<span style={{color:"var(--dm)"}}>—</span>}</td>\n <td style={{padding:"6px 10px"}}>\n <span style={{\n background:l.source==="switch"?"rgba(0,229,255,.12)":"rgba(255,234,0,.12)",\n color:l.source==="switch"?"var(--ac)":"var(--warn)",\n borderRadius:10,padding:"1px 7px",fontSize:10,fontFamily:"var(--mono)",fontWeight:700\n }}>{l.source==="switch"?"Switch":"OPNsense"}</span>\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </div>\n )}\n </div>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════════════\n// DNS FILTERING TAB — Control D / ctrld\n// ══════════════════════════════════════════════════════════════════════════════\n\nconst CTRLD_MODES = {\n local: {\n label: "Option A — ctrld on this management computer",\n color: "var(--ok)",\n badge: "Fully automated",\n description: `Installs the ctrld daemon directly on this machine alongside the\nswitch manager. One command downloads and installs it, writes a\nper-VLAN config, and starts it as a system service.\n\nHow it works:\n • ctrld listens on port 53 on this machine\'s IP\n • The switch DHCP hands out this machine\'s IP as DNS for each VLAN\n • ctrld sees the source VLAN subnet and routes to the right profile\n • Each VLAN gets filtered by its own Control D profile via DoH3\n\nBest for: most setups. Self-contained, no OPNsense required.\nRequires: a Resolver ID per VLAN from your Control D dashboard.`,\n docsUrl: "https://docs.controld.com/docs/ctrld",\n },\n opnsense: {\n label: "Option B — ctrld on OPNsense",\n color: "var(--warn)",\n badge: "Semi-automated",\n description: `Installs ctrld on your OPNsense router instead of this machine.\nThe setup generates a single SSH command you paste into OPNsense shell.\nOPNsense then becomes the DNS resolver for your network.\n\nHow it works:\n • You run one command in OPNsense shell (via SSH or console)\n • ctrld installs as a service on OPNsense\n • OPNsense\'s IP becomes the DNS server for each VLAN\n • Per-VLAN routing uses source IP matching in ctrld config\n\nBest for: setups where OPNsense is already the DNS server, or where\nyou want DNS handled at the router rather than the switch manager machine.\nRequires: SSH access to OPNsense and a Resolver ID per VLAN.`,\n docsUrl: "https://docs.controld.com/docs/routers-platform",\n },\n manual: {\n label: "Option C — manual / existing setup",\n color: "var(--dm)",\n badge: "Config generated",\n description: `Generates the ctrld.toml config file and install command for you\nto apply manually wherever you choose to run ctrld.\n\nThis option is for:\n • Running ctrld on a separate dedicated machine\n • Integrating with an existing DNS setup\n • Using dnscrypt-proxy or another DoH3 proxy instead of ctrld\n • Advanced users who want full control\n\nThe site generates the correct ctrld.toml and DHCP option 6 values.\nYou install and configure ctrld yourself.\n\nInstall command (any Linux/Mac/OPNsense):\n sh -c \'sh -c "$(curl -sL https://api.controld.com/dl)" -s RESOLVER_ID forced\'`,\n docsUrl: "https://docs.controld.com/docs/ctrld",\n },\n};\n\nfunction CtrldVlanRow({ vlan, profile, onChange }) {\n return (\n <tr style={{borderBottom:"1px solid var(--b1)"}}>\n <td style={{padding:"8px 10px"}}>\n <div style={{display:"flex",alignItems:"center",gap:8}}>\n <span style={{width:10,height:10,borderRadius:2,background:vlan.color,flexShrink:0}}/>\n <span style={{fontWeight:600}}>VLAN {vlan.id}</span>\n <span style={{color:"var(--dm)",fontSize:11}}>{vlan.name}</span>\n </div>\n </td>\n <td style={{padding:"8px 10px",fontFamily:"var(--mono)",fontSize:11,color:"var(--dm)"}}>\n 192.168.{vlan.id}.0/24\n </td>\n <td style={{padding:"8px 10px"}}>\n <input\n value={profile?.resolver_id || ""}\n onChange={e => onChange(vlan.id, "resolver_id", e.target.value)}\n placeholder="Resolver ID from Control D dashboard"\n style={{\n width:"100%", background:"var(--bg)", border:"1px solid var(--b2)",\n color:"var(--tx)", padding:"4px 8px", fontFamily:"var(--mono)",\n fontSize:11, borderRadius:3,\n }}\n />\n </td>\n <td style={{padding:"8px 10px"}}>\n {profile?.resolver_id\n ? <span style={{color:"var(--ok)",fontSize:11}}>✓ configured</span>\n : <span style={{color:"var(--dm)",fontSize:11}}>not set — will use fallback</span>\n }\n </td>\n </tr>\n );\n}\n\nfunction DNSTab({ vlans, session, onNeedAuth, backendOk }) {\n const [status, setStatus] = useState(null);\n const [mode, setMode] = useState(null);\n const [profiles, setProfiles] = useState({});\n const [opnsenseHost, setOpnsenseHost] = useState("");\n const [loading, setLoading] = useState(false);\n const [saving, setSaving] = useState(false);\n const [result, setResult] = useState(null);\n const [showToml, setShowToml] = useState(false);\n\n const load = async () => {\n setLoading(true);\n try {\n const s = await API("/ctrld/status");\n setStatus(s);\n if (s.mode) setMode(s.mode);\n if (s.vlan_profiles?.length) {\n const p = {};\n s.vlan_profiles.forEach(vp => { p[vp.vlan_id] = vp; });\n setProfiles(p);\n }\n } catch(e) { console.error(e); }\n setLoading(false);\n };\n\n useEffect(() => { if (backendOk) load(); }, [backendOk]);\n\n // Initialise profiles from VLANs\n useEffect(() => {\n if (vlans.length && Object.keys(profiles).length === 0) {\n const p = {};\n vlans.forEach(v => {\n p[v.id] = {\n vlan_id: v.id,\n name: v.name,\n subnet: `192.168.${v.id}.0/24`,\n resolver_id: "",\n };\n });\n setProfiles(p);\n }\n }, [vlans]);\n\n const updateProfile = (vlanId, field, value) => {\n setProfiles(prev => ({\n ...prev,\n [vlanId]: {\n ...prev[vlanId],\n vlan_id: vlanId,\n name: vlans.find(v=>v.id===vlanId)?.name || `VLAN ${vlanId}`,\n subnet: `192.168.${vlanId}.0/24`,\n [field]: value,\n }\n }));\n };\n\n const save = async () => {\n if (!session) { onNeedAuth(); return; }\n if (!mode) { alert("Choose an option first"); return; }\n setSaving(true); setResult(null);\n try {\n const vlan_profiles = Object.values(profiles).filter(p => p.resolver_id);\n const r = await API("/ctrld/save-config", {\n method: "POST",\n body: {\n token: session.token,\n config: { mode, vlan_profiles, opnsense_host: opnsenseHost },\n }\n });\n setResult(r);\n await load();\n } catch(e) {\n setResult({ success: false, message: e.message });\n }\n setSaving(false);\n };\n\n const updateProfiles = async () => {\n if (!session) { onNeedAuth(); return; }\n setSaving(true);\n try {\n const vlan_profiles = Object.values(profiles).filter(p => p.resolver_id);\n const r = await API("/ctrld/update-profiles", {\n method: "POST",\n body: { token: session.token, vlan_profiles }\n });\n setResult(r);\n } catch(e) {\n setResult({ success: false, message: e.message });\n }\n setSaving(false);\n };\n\n const configuredProfiles = Object.values(profiles).filter(p => p.resolver_id);\n const isInstalled = status?.installed;\n const isRunning = status?.running;\n\n return (\n <div className="main" style={{flexDirection:"column",gap:12}}>\n\n {/* Status header */}\n <div className="panel">\n <div className="ph">◈ DNS Filtering — Control D\n <span style={{marginLeft:"auto",display:"flex",alignItems:"center",gap:6,\n fontFamily:"var(--mono)",fontSize:10}}>\n {isRunning\n ? <><span style={{width:7,height:7,borderRadius:"50%",background:"var(--ok)"}}/> ctrld running</>\n : isInstalled\n ? <><span style={{width:7,height:7,borderRadius:"50%",background:"var(--warn)"}}/> ctrld installed, not running</>\n : <><span style={{width:7,height:7,borderRadius:"50%",background:"var(--dm)"}}/> not configured</>\n }\n </span>\n </div>\n <div className="pb">\n <div style={{fontSize:12,color:"var(--dm)",lineHeight:1.8,marginBottom:14}}>\n Control D filters DNS queries per VLAN — ads, malware, adult content,\n social media, and more. Each VLAN gets its own profile with different rules.\n The <code style={{fontFamily:"var(--mono)",color:"var(--ac)"}}>ctrld</code> daemon\n acts as a local DNS proxy, accepting plain DNS from devices and forwarding\n upstream via DoH3 to Control D. Your switch DHCP points each VLAN to it.\n <br/><br/>\n <span style={{color:"var(--ac)"}}>\n You need a Control D account and a Resolver ID per VLAN.\n </span>\n {" "}Get them at{" "}\n <a href="https://controld.com" target="_blank"\n style={{color:"var(--ac)"}}>controld.com</a>\n {" "}→ Add Device → Router → copy the Resolver ID shown.\n </div>\n\n {/* Mode selection */}\n {!isInstalled && (\n <div style={{marginBottom:14}}>\n <div className="sect">Choose how to run ctrld</div>\n <div style={{display:"flex",flexDirection:"column",gap:8}}>\n {Object.entries(CTRLD_MODES).map(([key, m]) => (\n <div key={key}\n onClick={() => setMode(key)}\n style={{\n background: mode===key ? "rgba(0,229,255,.05)" : "var(--bg)",\n border: `1px solid ${mode===key ? "var(--ac)" : "var(--b2)"}`,\n borderRadius: 5, padding:"12px 14px", cursor:"pointer",\n transition:"all .15s",\n }}>\n <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:6}}>\n <div style={{width:16,height:16,borderRadius:"50%",border:`2px solid ${m.color}`,\n background:mode===key?m.color:"transparent",flexShrink:0}}/>\n <span style={{fontWeight:700,fontSize:12}}>{m.label}</span>\n <span style={{\n background:`${m.color}20`,color:m.color,\n fontSize:10,fontFamily:"var(--mono)",fontWeight:700,\n padding:"1px 7px",borderRadius:10,marginLeft:"auto"\n }}>{m.badge}</span>\n </div>\n <pre style={{\n fontFamily:"var(--sans)",fontSize:11,color:"var(--dm)",\n lineHeight:1.7,margin:0,whiteSpace:"pre-wrap",\n paddingLeft:26,\n }}>{m.description}</pre>\n <div style={{paddingLeft:26,marginTop:6}}>\n <a href={m.docsUrl} target="_blank"\n style={{fontSize:10,color:"var(--ac)"}}\n onClick={e=>e.stopPropagation()}>\n Documentation →\n </a>\n </div>\n </div>\n ))}\n </div>\n\n {mode === "opnsense" && (\n <div className="field" style={{marginTop:12}}>\n <label>OPNsense IP address</label>\n <input value={opnsenseHost}\n onChange={e=>setOpnsenseHost(e.target.value)}\n placeholder="192.168.99.1"\n style={{fontFamily:"var(--mono)",maxWidth:220}}/>\n </div>\n )}\n </div>\n )}\n\n {/* Already installed — show current mode */}\n {isInstalled && (\n <div style={{\n background:"rgba(0,230,118,.06)",border:"1px solid rgba(0,230,118,.2)",\n borderRadius:4,padding:"10px 14px",marginBottom:14,\n display:"flex",alignItems:"center",gap:10,\n }}>\n <span style={{color:"var(--ok)",fontSize:13}}>✓</span>\n <div style={{fontSize:12}}>\n ctrld is installed — <strong>{CTRLD_MODES[status?.mode||"local"]?.label || status?.mode}</strong>\n <div style={{fontSize:10,color:"var(--dm)",fontFamily:"var(--mono)",marginTop:2}}>\n {status?.output}\n </div>\n </div>\n </div>\n )}\n </div>\n </div>\n\n {/* Per-VLAN Resolver IDs */}\n <div className="panel">\n <div className="ph">◈ Control D Resolver IDs — per VLAN\n <span style={{marginLeft:"auto",fontSize:10,color:"var(--dm)"}}>\n From controld.com → Add Device → Router → Resolver ID\n </span>\n </div>\n <div className="pb" style={{padding:0}}>\n <table style={{width:"100%",borderCollapse:"collapse"}}>\n <thead>\n <tr style={{borderBottom:"1px solid var(--b1)"}}>\n {["VLAN","Subnet","Resolver ID","Status"].map(h=>(\n <th key={h} style={{textAlign:"left",padding:"6px 10px",fontSize:10,\n letterSpacing:2,textTransform:"uppercase",color:"var(--dm)"}}>\n {h}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {vlans.map(v => (\n <CtrldVlanRow\n key={v.id}\n vlan={v}\n profile={profiles[v.id]}\n onChange={updateProfile}\n />\n ))}\n </tbody>\n </table>\n\n <div style={{padding:"12px 14px",borderTop:"1px solid var(--b1)",\n display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"}}>\n <div style={{fontSize:11,color:"var(--dm)",flex:1}}>\n {configuredProfiles.length} of {vlans.length} VLANs have a Resolver ID.\n {configuredProfiles.length < vlans.length &&\n " VLANs without a Resolver ID will use the first configured profile as fallback."}\n </div>\n {isInstalled\n ? <button className="btn bp" onClick={updateProfiles} disabled={saving||!session}>\n {saving ? "Saving..." : "Update Profiles"}\n </button>\n : <button className="btn bp" onClick={save}\n disabled={saving||!session||!mode||configuredProfiles.length===0}>\n {saving ? "Installing..." : mode==="local" ? "Install & Start ctrld" :\n mode==="opnsense" ? "Generate OPNsense Command" : "Save & Generate Config"}\n </button>\n }\n {!session && (\n <button className="btn bg" style={{fontSize:10}} onClick={onNeedAuth}>\n Authenticate\n </button>\n )}\n </div>\n </div>\n </div>\n\n {/* Result panel */}\n {result && (\n <div className="panel">\n <div className="ph" style={{color:result.success?"var(--ok)":"var(--err)"}}>\n {result.success ? "✓ " : "✗ "}\n {result.message}\n <button className="btn bg" style={{marginLeft:"auto",fontSize:10,padding:"2px 8px"}}\n onClick={()=>setResult(null)}>✕</button>\n </div>\n {result.success && (\n <div className="pb">\n {/* Option A result */}\n {result.mode === "local" && result.dns_ip && (\n <div style={{fontSize:12,lineHeight:1.8}}>\n <div style={{marginBottom:8}}>\n <span style={{color:"var(--ac)",fontFamily:"var(--mono)"}}>\n DNS IP for DHCP option 6: {result.dns_ip}\n </span>\n </div>\n <div style={{color:"var(--dm)",marginBottom:12}}>{result.dhcp_action}</div>\n <div style={{fontSize:11,color:"var(--dm)"}}>\n Go to the <strong>DHCP tab</strong> → select each VLAN pool →\n set DNS server to <code style={{fontFamily:"var(--mono)",color:"var(--ac)"}}>{result.dns_ip}</code>\n </div>\n </div>\n )}\n\n {/* Option B result */}\n {result.mode === "opnsense" && (\n <div style={{fontSize:12,lineHeight:1.9}}>\n <div className="sect">Run this in OPNsense shell</div>\n <div style={{\n background:"#060809",borderRadius:4,padding:"10px 14px",\n fontFamily:"var(--mono)",fontSize:12,color:"#a0b0c0",marginBottom:12,\n overflowX:"auto",whiteSpace:"pre",\n }}>{result.ssh_cmd || result.install_cmd}</div>\n <div style={{color:"var(--dm)",fontSize:11,lineHeight:1.8}}>\n <div>After install:</div>\n <div>1. {result.step2}</div>\n <div>2. {result.step3}</div>\n <div>3. {result.step4}</div>\n </div>\n <button className="btn bg" style={{marginTop:10,fontSize:10}}\n onClick={()=>navigator.clipboard?.writeText(result.ssh_cmd||result.install_cmd)}>\n Copy Command\n </button>\n </div>\n )}\n\n {/* Option C result */}\n {result.mode === "manual" && (\n <div style={{fontSize:12,lineHeight:1.8}}>\n <div style={{color:"var(--dm)",marginBottom:10}}>\n Install command (run on whichever machine will run ctrld):\n </div>\n <div style={{\n background:"#060809",borderRadius:4,padding:"10px 14px",\n fontFamily:"var(--mono)",fontSize:11,color:"#a0b0c0",marginBottom:12,\n }}>{result.install_cmd}</div>\n <div style={{color:"var(--dm)",marginBottom:6}}>\n Then place the config below at: <code style={{fontFamily:"var(--mono)",color:"var(--ac)"}}>{result.config_path}</code>\n </div>\n </div>\n )}\n\n {/* TOML config — shown for B and C, toggleable for A */}\n {result.toml && (\n <div>\n <button className="btn bg" style={{fontSize:10,marginBottom:8}}\n onClick={()=>setShowToml(s=>!s)}>\n {showToml ? "Hide" : "Show"} ctrld.toml config\n </button>\n <button className="btn bg" style={{fontSize:10,marginBottom:8,marginLeft:6}}\n onClick={()=>navigator.clipboard?.writeText(result.toml)}>\n Copy toml\n </button>\n {showToml && (\n <div style={{\n background:"#060809",borderRadius:4,padding:"12px 14px",\n fontFamily:"var(--mono)",fontSize:11,color:"#a0b0c0",\n whiteSpace:"pre",overflowX:"auto",maxHeight:300,overflowY:"auto",\n }}>{result.toml}</div>\n )}\n </div>\n )}\n\n {/* DHCP reminder */}\n {result.success && (\n <div style={{\n marginTop:12,background:"rgba(0,229,255,.05)",\n border:"1px solid rgba(0,229,255,.15)",borderRadius:4,\n padding:"10px 14px",fontSize:11,color:"var(--dm)",lineHeight:1.7,\n }}>\n <span style={{color:"var(--ac)",fontWeight:700}}>Next step: </span>\n In the <strong>DHCP tab</strong>, configure each VLAN pool to use\n the ctrld machine\'s IP as DNS (option 6). The switch will then hand\n out the correct DNS server to every device on each VLAN automatically.\n </div>\n )}\n </div>\n )}\n </div>\n )}\n\n {/* Quick reference */}\n <div className="panel">\n <div className="ph">◈ How It Works</div>\n <div className="pb">\n <div style={{\n display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:10,\n fontSize:11,textAlign:"center",\n }}>\n {[\n {icon:"📱", label:"Device", sub:"sends DNS query\\nto switch DHCP\\nassigned DNS IP"},\n {icon:"⚡", label:"ctrld", sub:"receives query\\nidentifies VLAN\\nby source subnet"},\n {icon:"🔒", label:"DoH3", sub:"forwards via\\nencrypted HTTPS/3\\nto Control D"},\n {icon:"🛡️", label:"Control D", sub:"applies your\\nVLAN profile\\nreturns answer"},\n ].map((s,i)=>(\n <div key={i} style={{\n background:"var(--bg)",border:"1px solid var(--b2)",borderRadius:5,\n padding:"12px 8px",\n }}>\n <div style={{fontSize:22,marginBottom:6}}>{s.icon}</div>\n <div style={{fontWeight:700,marginBottom:4,color:"var(--tx)"}}>{s.label}</div>\n <div style={{color:"var(--dm)",whiteSpace:"pre-line",lineHeight:1.6}}>{s.sub}</div>\n </div>\n ))}\n </div>\n <div style={{marginTop:12,fontSize:11,color:"var(--dm)",lineHeight:1.8}}>\n <span style={{color:"var(--ac)",fontWeight:700}}>Per-VLAN enforcement: </span>\n ctrld identifies which VLAN a DNS query came from by the source IP subnet.\n Each VLAN subnet maps to a different Control D profile. Staff get permissive\n filtering. IoT devices get strict filtering. Guests get aggressive ad/malware blocking.\n All encrypted via DoH3 — your ISP sees HTTPS traffic, not DNS queries.\n </div>\n </div>\n </div>\n </div>\n );\n}\n'
|
||
|
||
README_SRC = '# Avaya / Extreme ERS 5952 Switch Manager\n\nA browser-based management interface for the Avaya / Extreme Networks ERS 5952 switch. You click buttons. The software figures out the CLI. You never type a switch command.\n\nCompatible with: ERS 5928, ERS 5948, ERS 5952, ERS 5952-PWR+\n\n---\n\n## Installation\n\nCopy `Avaya_5952_setup.py` to your always-on management computer (Raspberry Pi, HP T620 thin client, old computer or laptop) and run:\n\n```\npython Avaya_5952_setup.py\n```\n\nThat is the entire installation process. The script handles everything automatically. The only step requiring human intervention is loading the SSH public key onto the switch via console cable — the script pauses, shows you exactly what to type, and waits for you to confirm before continuing.\n\n---\n\n## What the Setup Script Does\n\nThe script runs 21 steps automatically:\n\n1. Writes all project files (backend, frontend source, this README)\n2. Installs system packages (picocom, qrencode, wireguard-tools)\n3. Adds your user to the dialout group for console cable access\n4. Installs Python dependencies\n5. Creates the config directory `/etc/switch-manager/`\n6. Sets a static IP on your management network interface\n7. Asks whether to deploy with Docker (recommended) or native Python\n8. Guides you through console cable setup and software links\n9. Generates an ed25519 SSH keypair\n10. Shows you exactly what to paste on the switch console\n11. Tests the SSH connection and retries if it fails\n12. Pins the switch host key (MITM protection)\n13. Generates your TOTP authenticator secret with QR code\n14. Verifies your authenticator app is working before continuing\n15. Patches the backend config with your switch IP and credentials\n16. Builds the React frontend (requires Node.js)\n17. Installs and enables a systemd service (or Docker container)\n18. Starts the service\n19. Optionally sets up Docker with Caddy HTTPS\n20. Optionally configures WireGuard VPN for remote access\n21. Optionally installs Control D DNS filtering via ctrld\n\nRe-running is safe — completed steps are skipped.\n\n---\n\n## Deployment Options\n\nThe script explains both options before asking:\n\n**Docker + Caddy (recommended default)**\nRuns the switch manager in a container with all dependencies baked in. Caddy provides automatic HTTPS at a hostname you choose (default: `switch.mgmt.lan`). Caddy generates its own internal CA — the setup script installs it into your system trust store automatically so browsers show a clean padlock. Updates with one command: `docker compose pull && docker compose up -d`.\n\n**Native Python (bare metal)**\nRuns directly as a Python process managed by systemd. Simpler, lower memory, no Docker required. Access via `http://IP:8765` directly. Right choice for very low memory machines or users who prefer managing services directly.\n\n---\n\n## Accessing the Interface\n\n```\nhttp://[management computer IP]:8765\n```\n\nOr with Docker + Caddy:\n```\nhttps://switch.mgmt.lan\n```\n\nYou must be on VLAN 99 (management VLAN) or connected via WireGuard VPN to reach this address. This is intentional — the switch enforces isolation at the network layer.\n\n### Getting onto VLAN 99 from your laptop\n\n**Linux:**\n```bash\nsudo ip link add link eth0 name eth0.99 type vlan id 99\nsudo ip addr add 192.168.99.50/24 dev eth0.99\nsudo ip link set eth0.99 up\n```\n\n**Mac:** System Settings → Network → Add VLAN interface → VLAN ID 99\n\n**Dedicated port:** Ask the switch to put one port on VLAN 99 as an access port. Plug in when managing.\n\n**VPN:** Connect via WireGuard (configured during setup or via the VPN tab).\n\n---\n\n## The Interface — Eight Tabs\n\n### Port Map\n\nVisual 48+4 port chassis, colour-coded by VLAN. Each port shows its VLAN assignment, mode (access/trunk/disabled), and a green dot when PoE is active. Click any port to configure it in the right panel.\n\n**Port configuration panel:**\n- Description (e.g. "AP-Corridor-1", "Camera-NE")\n- Mode: Access, Trunk, or Disabled\n- VLAN assignment (access) or tagged/native VLANs (trunk)\n- PoE on/off and wattage limit (copper ports, 1W–30W)\n\nLive status pulls from the switch every 15 seconds while the tab is active, 60 seconds when backgrounded, and pauses when nobody has the page open.\n\n### VLANs\n\nCreate, rename, and delete VLANs. Shows port count and subnet per VLAN. VLAN 1 cannot be deleted.\n\n### ACL Builder\n\nBuild Access Control Lists visually. Each rule specifies action (permit/deny), protocol (ip/tcp/udp/icmp), source, destination, and optional port. The ACL is assigned to a VLAN interface with a direction. The tool generates all CLI syntax — you never write it yourself.\n\n### Review & Push\n\nEvery change across all tabs is translated into the exact CLI commands the ERS 5952 understands. This tab shows those commands before anything is sent.\n\n**You never write CLI commands.** The tool generates them. The review step exists so you can inspect what will be sent.\n\n**Push mode choice:**\n- **Batch** — all commands sent in sequence, results shown when complete\n- **Step by step** — one command at a time, confirm each before the next is sent\n\nEach command is displayed with a plain-English explanation of what it does and what it affects. You can read exactly what is about to happen.\n\n### Device Access\n\nManages which devices can reach the management interface from their normal VLAN without needing VPN. The switch enforces access via an ACL pinhole. TOTP still gates any changes.\n\n**MAC address randomization warning:** Modern phones and laptops randomize MAC addresses per network. This breaks DHCP reservations. The tab shows per-platform instructions to disable it (iOS, Android, macOS, Windows) before adding a device.\n\n**Live DHCP leases** pulled from the switch appear as unregistered devices — click Register to add them.\n\n**Per device:**\n- Name, MAC, IP, VLAN\n- Reserve static IP (DHCP binding pushed to switch)\n- Grant/revoke management access (ACL pinhole pushed to switch)\n\n### DHCP\n\nUnified view of all DHCP reservations across switch and OPNsense (if configured).\n\n**DHCP server recommendation:**\n- Use switch DHCP for VLAN 99 (management) — devices get IPs before OPNsense is reachable\n- Use OPNsense for all other VLANs — integrates with DNS, firewall rules, lease history\n- Never run both for the same VLAN\n\n**OPNsense integration (optional):**\nAuto-detects OPNsense at your gateway IP. If found, prompts for API key. Once connected, shows reservations from both switch and OPNsense in one table, colour-coded by source.\n\n**Conflict detection:** If the same MAC has reservations in both places, a badge appears — red for IP conflicts (same MAC, different IP), yellow for duplicates (same MAC, same IP). Each conflict has a Resolve button with four options: Switch wins, OPNsense wins, Remove from switch, Remove from OPNsense.\n\n### DNS Filtering\n\nConfigures Control D DNS filtering per VLAN via the `ctrld` daemon.\n\n**How it works:** `ctrld` runs as a local DNS proxy. Devices send normal DNS queries to it. `ctrld` identifies the source VLAN subnet and routes each query to the correct Control D profile via DoH3. Each VLAN gets different filtering rules. Your ISP sees encrypted HTTPS traffic, not DNS queries.\n\n**Three deployment options presented with full explanations:**\n\n*Option A — ctrld on the management computer (fully automated)*\nInstalls ctrld alongside the switch manager. One command downloads and installs it, writes the per-VLAN config, starts it as a system service. The switch DHCP points each VLAN to this machine\'s IP for DNS.\n\n*Option B — ctrld on OPNsense (semi-automated)*\nGenerates a single SSH command to paste into OPNsense shell. ctrld installs as a service on OPNsense. OPNsense\'s IP becomes the DNS server for the network.\n\n*Option C — manual / existing setup*\nGenerates the `ctrld.toml` config and install command. You install wherever you choose.\n\n**Per-VLAN Resolver IDs:** Each VLAN gets its own Control D profile. Enter the Resolver ID from the Control D dashboard (controld.com → Add Device → Router → Resolver ID). VLANs without a Resolver ID use the first configured profile as fallback.\n\n**References:**\n- Control D documentation: https://docs.controld.com/docs/ctrld\n- Router setup guide: https://docs.controld.com/docs/routers-platform\n\n### VPN\n\nManages WireGuard VPN for remote access to the management interface from outside the management VLAN.\n\n**Add clients:** Enter a name (laptop, phone, tablet) and the tool generates a keypair, adds the peer to the server config, reloads WireGuard live, and displays a QR code to scan with the WireGuard app. Also saves a `.conf` file for desktop import.\n\n**Revoke clients:** Disconnects the peer immediately and removes it from the server config.\n\n**Connected peers:** Shows last handshake time and transfer stats for each peer.\n\n**SSH tunnel alternative:** For power users — one command gives secure access without WireGuard installed:\n```bash\nssh -L 8765:localhost:8765 user@management-computer-ip\n```\n\n---\n\n## Making Changes — Step by Step\n\n1. **Configure** across any tabs — nothing happens on the switch yet\n2. **Go to Review & Push** — read the generated commands with explanations\n3. **Check for dangers** — automatic pre-flight runs before authentication\n4. **Authenticate** — enter 6-digit TOTP code to unlock a push session\n5. **Choose push mode** — batch (faster) or step-by-step (full control)\n6. **Push** — commands go one at a time, checked after each\n7. **Review results** — each command shows success or failure with the switch\'s error output\n8. **Auto-lock** — session closes when push completes. New changes need a new TOTP code\n\n---\n\n## Authentication and Sessions\n\n**Read-only** — no authentication required. Anyone on VLAN 99 can view the dashboard.\n\n**Push mode** — requires TOTP. One code unlocks exactly one push session. The session closes automatically when the push completes or you cancel. The next set of changes requires a new TOTP code.\n\n**Why TOTP and not a password:** VLAN 99 isolation is the primary barrier. TOTP adds a second factor confirming it is you making a change. A code is useless after 30 seconds and requires physical access to your authenticator app.\n\n---\n\n## How Commands Reach the Switch\n\nExact sequence on every push:\n\n1. Browser sends the command list to the management computer backend\n2. Backend runs a danger check against known lethal patterns\n3. Backend validates every command against an allowlist\n4. Backend opens a fresh SSH connection using the ed25519 key stored on the management computer\n5. Commands execute one at a time via interactive shell\n6. After each command the switch\'s response is checked for error patterns\n7. On error: push stops immediately, no further commands sent, config not saved\n8. On full success: `end` then `copy running-config nvram:config.cfg` — config saved to NVRAM\n\n---\n\n## Blocked Commands\n\n**Hard-blocked — refused entirely, must run at the switch console:**\n\n| Pattern | Reason |\n|---|---|\n| `no vlan 99` | Deletes management VLAN |\n| `vlan members remove ... 99` | Removes VLAN 99 from a port — kills management trunk |\n| `no vlan tagging ... 99` | Removes VLAN 99 tagging — kills management trunk |\n| `no ip ssh` | Disables SSH — permanent lockout |\n| `no ip address` | Removes IP — management computer loses connectivity |\n| `interface vlan 99` | Modifies management VLAN interface |\n| `boot config flags factory` | Factory reset |\n\n**Warning-level — shown for review, push proceeds with confirmation:**\n\n| Pattern | Reason |\n|---|---|\n| `shutdown` | Shuts down an interface — confirm not your uplink |\n| `default interface` | Resets interface to defaults |\n| `no vlan [id]` | Deletes a VLAN — confirm no active ports depend on it |\n| `spanning-tree ... disable` | Disables spanning tree — loop risk |\n\n---\n\n## SSH Key Security\n\nThe ed25519 private key lives at `/etc/switch-manager/ers5952_key` on the management computer. It never leaves that machine. Your laptop, phone, or tablet never touches it.\n\nThe switch host key is pinned after the first connection. If the switch\'s host key ever changes the backend refuses to connect and reports the mismatch — MITM protection even on the management VLAN.\n\n---\n\n## Console Cable\n\nNeeded once only — to configure VLAN 99 and load the SSH public key. After that, the ethernet cable from the management computer to the switch handles everything.\n\n**What to buy:** Search "RJ45 console cable USB Cisco compatible" — get the RJ-45 to USB version (~$8). Works on any laptop with a USB port.\n\n**Software:**\n- Windows: PuTTY (putty.org) or TeraTerm\n- Mac: `screen /dev/tty.usbserial-* 9600` in Terminal\n- Linux: `sudo picocom -b 9600 /dev/ttyUSB0`\n\n**Settings:** 9600 baud · 8 data bits · No parity · 1 stop bit · No flow control\n\nEnter one command at a time. Wait for the `5952(config)#` prompt before sending the next.\n\n**Switch password rules:** 8–32 characters. Special characters allowed: `! @ # $ % ^ & * - _ = + [ ] ; : , . /`. No spaces. No quotes.\n\n---\n\n## Bootstrap — VLAN 99 First-Time Setup\n\nBefore the management tool can run, the switch needs VLAN 99 configured. Connect the console cable and enter these commands one at a time:\n\n```\nenable\nconfigure terminal\nvlan create 99 name "Management" type port\ninterface vlan 99\nip address 192.168.99.1 255.255.255.0\nno shutdown\nexit\nvlan members add 99 1\nvlan pvid 1 99\nip ssh\nusername admin password YourPassword\nend\ncopy running-config nvram:config.cfg\n```\n\nReplace `1` with the port your management computer plugs into. Replace `YourPassword` with a strong password following the rules above.\n\nThen give your management computer a static IP:\n\n```bash\n# Temporary (immediate, lost on reboot)\nsudo ip addr add 192.168.99.50/24 dev eth0\nsudo ip link set eth0 up\n\n# Find your interface name first: ip link show\n# Replace eth0 with your actual interface name\n```\n\nVerify it works: `ping 192.168.99.1` — then run `python Avaya_5952_setup.py`.\n\n---\n\n## Live Polling\n\nThe backend polls the switch using a connection pool:\n- Pool lifetime: 25 seconds (shorter than switch idle timeout)\n- Tab active/visible: polls every 15 seconds\n- Tab backgrounded: polls every 60 seconds\n- No visitors for 5 minutes: polling pauses completely\n- New visitor opens page: immediate poll, resumes normal interval\n\nThe switch is never being polled when nobody is looking at the dashboard.\n\n---\n\n## Files Created\n\n| File | Location | Purpose |\n|---|---|---|\n| `switch_backend.py` | Project folder | Python API server (34 endpoints) |\n| `ers5952-manager.jsx` | Project folder | React app source (8 tabs) |\n| `README.md` | Project folder | This file |\n| `Dockerfile` | Project folder | Docker image definition |\n| `docker-compose.yml` | Project folder | Caddy + switch manager services |\n| `Caddyfile` | Project folder | HTTPS reverse proxy config |\n| `ctrld.toml` | Project folder | Control D per-VLAN DNS config (if configured) |\n| `frontend/dist/` | Project folder | Built React app |\n| `ers5952_key` | `/etc/switch-manager/` | SSH private key (chmod 600) |\n| `ers5952_key.pub` | `/etc/switch-manager/` | SSH public key |\n| `known_hosts` | `/etc/switch-manager/` | Pinned switch host key |\n| `totp_secret` | `/etc/switch-manager/` | TOTP seed (chmod 600) — back this up |\n| `devices.json` | `/etc/switch-manager/` | Registered device list |\n| `opnsense.json` | `/etc/switch-manager/` | OPNsense API credentials (chmod 600) |\n| `ctrld.json` | `/etc/switch-manager/` | Control D config (chmod 600) |\n| `wg_server_private` | `/etc/switch-manager/` | WireGuard server private key (chmod 600) |\n| `wg_server_public` | `/etc/switch-manager/` | WireGuard server public key |\n| `clients/` | `/etc/switch-manager/` | WireGuard client .conf files |\n| `switch-manager.service` | `/etc/systemd/system/` | Systemd service (native mode) |\n\n**Back up `/etc/switch-manager/totp_secret`** — if the management computer fails and you have not backed this up you will need to regenerate the TOTP secret and re-scan it into your authenticator app.\n\n---\n\n## Troubleshooting\n\n**Connection banner stuck on "Connecting..."**\nBackend not running or device not on VLAN 99. Check: `sudo systemctl status switch-manager` or `docker compose ps`\n\n**"Switch unreachable" in status pill**\nBackend running but cannot reach switch. Check: `ping 192.168.99.1` from the management computer.\n\n**TOTP code rejected**\nEnsure time is synchronised on both the management computer and your phone. Backend allows one 30-second window of clock drift. Sync: `sudo timedatectl set-ntp true`\n\n**Command failed — switch error shown**\nRead the error text — the switch says exactly what was wrong. Fix the configuration and push again. Already-succeeded commands do not need to be resent.\n\n**Host key rejection after switch reset**\nRe-pin: `ssh-keyscan -H 192.168.99.1 > /etc/switch-manager/known_hosts`\n\n**ctrld not filtering DNS**\nCheck DHCP option 6 is set to the ctrld machine\'s IP on each VLAN pool. Check ctrld is running: `ctrld status`. Check the switch is handing out the right DNS: from a device, run `nslookup example.com` and verify the server IP matches.\n\n**WireGuard not connecting**\nCheck port 51820 UDP is reachable from outside your network (router port forwarding may be needed for external access). Check: `sudo systemctl status wg-quick@wg0`\n\n**Service logs**\n```bash\n# Native\njournalctl -u switch-manager -f\n\n# Docker\ndocker compose logs -f\ndocker compose ps\n```\n\n---\n\n## What This Tool Does Not Do\n\n- Does not manage OPNsense, pfSense, or any other device directly (OPNsense integration is read/sync only)\n- Does not provide a terminal or shell — there is no way to type arbitrary commands through the main interface (CLI mode in settings is available for advanced users but still runs through the safety pipeline)\n- Does not support multiple switches simultaneously\n- Does not provide traffic analytics or bandwidth graphs\n- Does not automatically discover or adopt new network devices\n\n---\n\n## On the ERS 5952\n\nThis switch has no REST API. Everything this tool does is via SSH sessions that parse text output and send CLI commands — the same thing a human would do at a terminal, automated and wrapped in a browser interface.\n\nThere is an inherent limit to how reliably the tool can detect every possible error condition. The danger blocking system catches the known lethal patterns but cannot anticipate every possible misconfiguration. Use the CLI review step. Read what is about to be sent.\n\nThe console cable is always your fallback. Keep it accessible.\n'
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# SETUP STEPS
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
import ipaddress
|
||
|
||
def detect_os():
|
||
import platform
|
||
s = platform.system().lower()
|
||
if s == 'linux': return 'linux'
|
||
if s == 'darwin': return 'mac'
|
||
return 'windows'
|
||
|
||
OS = detect_os()
|
||
|
||
# ── Dockerfile and compose templates ───────────────────────────────────────
|
||
|
||
DOCKERFILE = """\
|
||
FROM python:3.11-slim
|
||
WORKDIR /app
|
||
RUN pip install --no-cache-dir fastapi uvicorn paramiko pyotp
|
||
COPY switch_backend.py .
|
||
COPY frontend/dist ./frontend/dist
|
||
EXPOSE 8765
|
||
CMD ["uvicorn", "switch_backend:app", "--host", "0.0.0.0", "--port", "8765"]
|
||
"""
|
||
|
||
COMPOSE_YML = """services:
|
||
caddy:
|
||
image: caddy:2-alpine
|
||
ports:
|
||
- "80:80"
|
||
- "443:443"
|
||
volumes:
|
||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||
- caddy_data:/data
|
||
- caddy_config:/config
|
||
restart: unless-stopped
|
||
depends_on:
|
||
- switch-manager
|
||
|
||
switch-manager:
|
||
build: .
|
||
expose:
|
||
- "8765"
|
||
volumes:
|
||
- /etc/switch-manager:/etc/switch-manager:ro
|
||
- ./frontend/dist:/app/frontend/dist:ro
|
||
restart: unless-stopped
|
||
environment:
|
||
- PYTHONUNBUFFERED=1
|
||
|
||
volumes:
|
||
caddy_data:
|
||
caddy_config:
|
||
"""
|
||
|
||
CADDYFILE_TEMPLATE = """{fqdn} {{
|
||
reverse_proxy switch-manager:8765
|
||
tls internal
|
||
}}
|
||
|
||
:80 {{
|
||
redir https://{{host}}{{uri}} permanent
|
||
}}
|
||
"""
|
||
|
||
# ── WireGuard helpers ──────────────────────────────────────────────────────
|
||
|
||
WG_CONF_DIR = Path("/etc/wireguard")
|
||
WG_SERVER_KEY = CONF_DIR / "wg_server_private"
|
||
WG_CLIENT_DIR = CONF_DIR / "clients"
|
||
WG_PORT = 51820
|
||
WG_SUBNET = "10.99.0" # VPN: server=10.99.0.1, clients=10.99.0.x
|
||
|
||
def wg_genkey():
|
||
priv = run("wg genkey").stdout.strip()
|
||
pub = subprocess.run(["wg","pubkey"], input=priv,
|
||
capture_output=True, text=True).stdout.strip()
|
||
return priv, pub
|
||
|
||
def detect_opnsense(gateway_ip):
|
||
try:
|
||
import urllib.request, ssl
|
||
ctx = ssl.create_default_context()
|
||
ctx.check_hostname = False
|
||
ctx.verify_mode = ssl.CERT_NONE
|
||
url = f"https://{gateway_ip}/api/core/firmware/status"
|
||
urllib.request.urlopen(
|
||
urllib.request.Request(url, headers={"User-Agent":"switch-manager/1"}),
|
||
timeout=3, context=ctx)
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# STEP FUNCTIONS
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
def write_files():
|
||
step(1, "Write project files")
|
||
for fname, content in [
|
||
("switch_backend.py", BACKEND_SRC),
|
||
("ers5952-manager.jsx", JSX_SRC),
|
||
("README.md", README_SRC),
|
||
]:
|
||
target = HERE / fname
|
||
if not target.exists() or ask_yn(f"Overwrite {fname}?", False):
|
||
target.write_text(content)
|
||
ok(f"{fname} written")
|
||
else:
|
||
ok(f"{fname} already exists — skipped")
|
||
|
||
|
||
def install_system_packages():
|
||
step(2, "System packages")
|
||
if OS != 'linux':
|
||
info(f"On {OS} — skipping system package install")
|
||
return
|
||
pkgmgr = ("apt" if shutil.which("apt") else
|
||
"dnf" if shutil.which("dnf") else
|
||
"pacman" if shutil.which("pacman") else None)
|
||
if not pkgmgr:
|
||
warn("Cannot detect package manager — install picocom and qrencode manually")
|
||
return
|
||
needed = []
|
||
for pkg, binary in [("picocom","picocom"),("qrencode","qrencode"),
|
||
("wireguard-tools","wg"),("curl","curl")]:
|
||
if shutil.which(binary):
|
||
ok(f"{pkg} already installed")
|
||
else:
|
||
needed.append(pkg)
|
||
if needed:
|
||
info(f"Installing: {', '.join(needed)}")
|
||
if pkgmgr == "apt":
|
||
sudo("apt-get update -qq")
|
||
sudo(f"apt-get install -y {' '.join(needed)}")
|
||
elif pkgmgr == "dnf":
|
||
sudo(f"dnf install -y {' '.join(needed)}")
|
||
elif pkgmgr == "pacman":
|
||
sudo(f"pacman -S --noconfirm {' '.join(needed)}")
|
||
for pkg in needed:
|
||
ok(f"{pkg} installed") if shutil.which(pkg.split('-')[0]) else warn(f"{pkg} may not have installed")
|
||
|
||
|
||
def ensure_dialout_group():
|
||
if OS != 'linux': return
|
||
step(3, "Serial port access")
|
||
import grp
|
||
user = os.getenv("USER","")
|
||
try:
|
||
members = grp.getgrnam("dialout").gr_mem
|
||
except KeyError:
|
||
warn("dialout group not found"); return
|
||
if user in members:
|
||
ok(f"{user} already in dialout group"); return
|
||
sudo(f"usermod -aG dialout {user}")
|
||
ok(f"{user} added to dialout group — active for this session")
|
||
|
||
|
||
def install_deps():
|
||
step(4, "Python dependencies")
|
||
import importlib.util
|
||
missing = [p for p in PACKAGES
|
||
if not importlib.util.find_spec(p.replace("-","_"))]
|
||
for p in PACKAGES:
|
||
if p not in missing: ok(f"{p} present")
|
||
if missing:
|
||
info(f"Installing: {', '.join(missing)}")
|
||
run(f"{sys.executable} -m pip install {' '.join(missing)} --break-system-packages",
|
||
capture=False)
|
||
try:
|
||
import qrcode; ok("qrcode library present")
|
||
except ImportError:
|
||
run(f"{sys.executable} -m pip install qrcode --break-system-packages", capture=False)
|
||
|
||
|
||
def create_conf_dir():
|
||
step(5, "Config directory")
|
||
if CONF_DIR.exists():
|
||
ok(f"{CONF_DIR} exists"); return
|
||
sudo(f"mkdir -p {CONF_DIR}")
|
||
sudo(f"chown {os.getenv('USER','root')} {CONF_DIR}")
|
||
sudo(f"chmod 750 {CONF_DIR}")
|
||
ok(f"Created {CONF_DIR}")
|
||
|
||
|
||
def set_static_ip():
|
||
step(6, "Network — management IP")
|
||
sep()
|
||
info("This machine needs a static IP on the switch management subnet.")
|
||
info("Default: switch = 192.168.99.1, this machine = 192.168.99.50")
|
||
sep()
|
||
|
||
if not ask_yn("Set a static IP now?", True):
|
||
info("Skipping — configure manually before SSH test")
|
||
return "192.168.99.50", "192.168.99.1"
|
||
|
||
import re
|
||
|
||
result = run("ip link show") if OS == 'linux' else run("ifconfig -l")
|
||
ifaces = []
|
||
if OS == 'linux' and result:
|
||
for line in result.stdout.splitlines():
|
||
m = re.match(r'^\d+: ([\w]+):', line)
|
||
if m:
|
||
name = m.group(1)
|
||
skip = ('lo','vir','docker','br-','veth','wl','tun','wg')
|
||
if not any(name.startswith(s) for s in skip):
|
||
ifaces.append(name)
|
||
elif OS == 'mac' and result:
|
||
ifaces = [n for n in result.stdout.split() if n.startswith("en")]
|
||
|
||
if not ifaces:
|
||
iface = ask("Interface name (e.g. eth0, enp2s0, en0)", "eth0")
|
||
ifaces = [iface]
|
||
|
||
sep()
|
||
print(f"\n {bold('Available interfaces:')}")
|
||
for i, iface in enumerate(ifaces):
|
||
r = run(f"ip addr show {iface}" if OS=='linux' else f"ifconfig {iface}")
|
||
cur = "no IP"
|
||
for line in r.stdout.splitlines():
|
||
m = re.search(r'inet (\S+)', line)
|
||
if m and not m.group(1).startswith("127"):
|
||
cur = m.group(1); break
|
||
print(f" {cyan(str(i+1))}. {bold(iface)} {dim(f'({cur})')}")
|
||
print()
|
||
|
||
if len(ifaces) == 1:
|
||
chosen = ifaces[0]
|
||
ok(f"Using {chosen}")
|
||
else:
|
||
try:
|
||
idx = int(ask(f"Interface (1-{len(ifaces)})", "1")) - 1
|
||
chosen = ifaces[max(0, min(idx, len(ifaces)-1))]
|
||
except ValueError:
|
||
chosen = ifaces[0]
|
||
|
||
ip = ask("IP for this machine", "192.168.99.50")
|
||
mask = ask("Prefix length", "24")
|
||
gateway = ask("Switch IP (gateway)", "192.168.99.1")
|
||
sep()
|
||
|
||
if OS == 'linux':
|
||
run(f"sudo ip addr flush dev {chosen}", check=False)
|
||
run(f"sudo ip addr add {ip}/{mask} dev {chosen}")
|
||
run(f"sudo ip link set {chosen} up")
|
||
run(f"sudo ip route add default via {gateway}", check=False)
|
||
elif OS == 'mac':
|
||
sudo(f"ifconfig {chosen} {ip} netmask 255.255.255.0")
|
||
sudo(f"route add default {gateway}", check=False)
|
||
|
||
time.sleep(1)
|
||
r = run(f"ping -c 2 -W 2 {gateway}" if OS=='linux' else f"ping -c 2 -t 2 {gateway}",
|
||
check=False)
|
||
if r.returncode == 0:
|
||
ok(f"Switch at {gateway} responds to ping")
|
||
else:
|
||
warn(f"Cannot reach {gateway} — check cable and which port on the switch")
|
||
|
||
if OS == 'linux' and ask_yn("Make permanent (survives reboot)?", True):
|
||
_make_permanent_linux(chosen, ip, mask, gateway)
|
||
elif OS == 'mac':
|
||
info(f"Mac: System Settings → Network → {chosen} → TCP/IP → Manual")
|
||
info(f"IP: {ip} Mask: 255.255.255.0 Router: {gateway}")
|
||
|
||
return ip, gateway
|
||
|
||
|
||
def _make_permanent_linux(iface, ip, mask, gateway):
|
||
if shutil.which("netplan"):
|
||
cfg = Path("/etc/netplan/99-switch-manager.yaml")
|
||
tmp = Path("/tmp/99-switch-manager.yaml")
|
||
tmp.write_text(
|
||
f"network:\n version: 2\n ethernets:\n {iface}:\n"
|
||
f" addresses:\n - {ip}/{mask}\n"
|
||
f" routes:\n - to: default\n via: {gateway}\n"
|
||
)
|
||
sudo(f"mv {tmp} {cfg}")
|
||
sudo("netplan apply")
|
||
ok(f"Permanent via netplan — {cfg}")
|
||
else:
|
||
ifaces_file = Path("/etc/network/interfaces")
|
||
cur = ifaces_file.read_text() if ifaces_file.exists() else ""
|
||
if iface not in cur:
|
||
tmp = Path("/tmp/ifaces_append")
|
||
tmp.write_text(
|
||
cur + f"\nauto {iface}\niface {iface} inet static\n"
|
||
f" address {ip}/{mask}\n gateway {gateway}\n"
|
||
)
|
||
sudo(f"mv {tmp} {ifaces_file}")
|
||
sudo("systemctl restart networking")
|
||
ok("Permanent via /etc/network/interfaces")
|
||
else:
|
||
warn(f"{iface} already in /etc/network/interfaces — edit manually if needed")
|
||
|
||
|
||
def choose_deployment():
|
||
step(7, "Deployment method")
|
||
sep()
|
||
print(f"""
|
||
{bold('About the deployment options:')}
|
||
|
||
{bold('Docker')} {cyan('(recommended default)')}
|
||
Runs the switch manager in a container with all dependencies
|
||
baked in. The host machine only needs Docker itself.
|
||
|
||
Why Docker is recommended:
|
||
- Self-contained: Python version and all libraries are locked inside
|
||
the container. Nothing installed on your system, no version conflicts.
|
||
- Easy updates: one command updates everything:
|
||
{dim('docker compose pull && docker compose up -d')}
|
||
- Includes Caddy: automatic HTTPS with a proper hostname
|
||
({dim('https://switch.mgmt.lan')}) instead of a raw IP and port.
|
||
- Reliable restarts: Docker's restart policy is simpler than systemd
|
||
for users who are not system administrators.
|
||
- Caddy generates its own certificate authority. The setup script
|
||
installs it into your system trust store automatically so browsers
|
||
show a clean padlock with no warnings.
|
||
|
||
{bold('Native Python')} {cyan('(bare metal — for specific situations)')}
|
||
Runs directly as a Python process on this machine.
|
||
|
||
Why you might prefer bare metal:
|
||
- Very low memory machine (Docker adds ~100MB overhead)
|
||
- You already know systemd and prefer managing services directly
|
||
- Corporate or personal policy against running Docker
|
||
- Simpler mental model — one Python process, easy to inspect and kill
|
||
- No Caddy: access via http://IP:8765 directly
|
||
""")
|
||
sep()
|
||
choice = ask("Deployment method (1=Docker recommended, 2=Native Python)", "1")
|
||
use_docker = choice.strip() != "2"
|
||
ok("Docker + Caddy selected") if use_docker else ok("Native Python selected")
|
||
sep()
|
||
return use_docker
|
||
|
||
|
||
def setup_docker():
|
||
step(8, "Docker setup")
|
||
if OS != 'linux':
|
||
warn("Docker auto-install supported on Linux only")
|
||
info("Install Docker Desktop: https://docs.docker.com/desktop/")
|
||
info(f"Then run in {HERE}: docker compose up -d")
|
||
return False
|
||
|
||
# Install Docker via official convenience script
|
||
if shutil.which("docker"):
|
||
ok("Docker already installed")
|
||
else:
|
||
info("Downloading Docker install script...")
|
||
r = run("curl -fsSL https://get.docker.com -o /tmp/get-docker.sh", check=False)
|
||
if r.returncode != 0:
|
||
err("Could not download Docker script — check internet connection")
|
||
return False
|
||
info("Installing Docker (this may take a minute)...")
|
||
run("sudo sh /tmp/get-docker.sh", capture=False)
|
||
if not shutil.which("docker"):
|
||
err("Docker install failed"); return False
|
||
ok("Docker installed")
|
||
|
||
# Add user to docker group
|
||
user = os.getenv("USER","")
|
||
import grp
|
||
try:
|
||
docker_members = grp.getgrnam("docker").gr_mem
|
||
except KeyError:
|
||
docker_members = []
|
||
if user not in docker_members:
|
||
sudo(f"usermod -aG docker {user}")
|
||
ok(f"{user} added to docker group")
|
||
else:
|
||
ok(f"{user} already in docker group")
|
||
|
||
# Ensure compose is available
|
||
compose_ok = run("docker compose version", check=False).returncode == 0
|
||
if not compose_ok:
|
||
info("Installing docker compose plugin...")
|
||
if shutil.which("apt"):
|
||
sudo("apt-get install -y docker-compose-plugin")
|
||
compose_ok = run("docker compose version", check=False).returncode == 0
|
||
if not compose_ok:
|
||
warn("docker compose not found — trying pip install")
|
||
run(f"{sys.executable} -m pip install docker-compose --break-system-packages", capture=False)
|
||
|
||
# Write Dockerfile and compose
|
||
(HERE / "Dockerfile").write_text(DOCKERFILE)
|
||
ok("Dockerfile written")
|
||
(HERE / "docker-compose.yml").write_text(COMPOSE_YML)
|
||
ok("docker-compose.yml written")
|
||
|
||
# Ask for FQDN
|
||
sep()
|
||
fqdn = ask("Hostname for the switch manager UI", "switch.mgmt.lan")
|
||
FQDN_FILE = CONF_DIR / "fqdn"
|
||
FQDN_FILE.write_text(fqdn)
|
||
|
||
# Write Caddyfile
|
||
caddyfile = HERE / "Caddyfile"
|
||
caddyfile.write_text(CADDYFILE_TEMPLATE.format(fqdn=fqdn))
|
||
ok(f"Caddyfile written — will serve https://{fqdn}")
|
||
|
||
# Update backend ALLOWED_ORIGINS with the FQDN
|
||
if BACKEND.exists():
|
||
content = BACKEND.read_text()
|
||
content = content.replace(
|
||
'ALLOWED_ORIGINS = ["*"]',
|
||
f'ALLOWED_ORIGINS = ["https://{fqdn}", "http://{fqdn}", "*"]'
|
||
)
|
||
BACKEND.write_text(content)
|
||
ok("Backend CORS updated")
|
||
|
||
# Build image
|
||
info("Building container image (first build downloads Python base image)...")
|
||
r = run(f"cd {HERE} && docker compose build", capture=False, check=False)
|
||
if r.returncode != 0:
|
||
err("Docker build failed — check output above"); return False
|
||
ok("Container image built")
|
||
|
||
# Start temporarily to extract Caddy CA cert
|
||
info("Starting containers to generate Caddy CA...")
|
||
run(f"cd {HERE} && docker compose up -d", capture=False, check=False)
|
||
time.sleep(5)
|
||
|
||
# Install Caddy CA into system trust store
|
||
_install_caddy_ca()
|
||
|
||
ok(f"Access at: https://{fqdn}")
|
||
info(f"Add DNS: {fqdn} → {local_ip()} in your router/OPNsense split DNS")
|
||
return True
|
||
|
||
|
||
def console_cable_guidance():
|
||
step(9, "Console cable — one-time switch bootstrap")
|
||
sep()
|
||
print(f"""
|
||
{bold('The console cable is only needed once')} — to set up VLAN 99
|
||
and load the SSH public key. After that, the ethernet cable
|
||
from this machine to the switch handles everything permanently.
|
||
|
||
{bold('What to buy:')}
|
||
Search Amazon/eBay: {cyan(CONSOLE_CABLE_SEARCH)}
|
||
Get the RJ-45 to USB version (~$8). Works on any laptop.
|
||
No serial port on your laptop needed.
|
||
|
||
{bold('Software — all free:')}""")
|
||
for name, url in CONSOLE_SOFTWARE.items():
|
||
print(f" {cyan(name)}")
|
||
print(f" {dim(url)}")
|
||
if OS == 'linux':
|
||
print(f"""
|
||
{bold('On Linux — no extra software needed:')}
|
||
Find device: {cyan('ls /dev/ttyUSB*')} (appears when cable is plugged in)
|
||
Connect: {cyan('sudo picocom -b 9600 /dev/ttyUSB0')}
|
||
Or: {cyan('sudo screen /dev/ttyUSB0 9600')}""")
|
||
elif OS == 'mac':
|
||
print(f"""
|
||
{bold('On Mac — Terminal is built in:')}
|
||
{cyan('screen /dev/tty.usbserial-* 9600')}
|
||
(Tab-complete after /dev/tty.usb to find the right name)""")
|
||
elif OS == 'windows':
|
||
print(f"""
|
||
{bold('On Windows:')}
|
||
1. Install driver for your cable (links above)
|
||
2. Device Manager → Ports (COM & LPT) → note COM number
|
||
3. PuTTY → Connection: Serial → Speed: 9600 → Open""")
|
||
print(f"""
|
||
{bold('Settings (same everywhere):')}
|
||
9600 baud · 8 data bits · No parity · 1 stop bit · No flow control
|
||
|
||
{bold('Send one command at a time.')}
|
||
Wait for the {cyan('5952(config)#')} prompt before sending the next line.
|
||
""")
|
||
sep()
|
||
pause("Press Enter when ready (or to skip if VLAN 99 already configured)...")
|
||
|
||
|
||
def gen_ssh_key():
|
||
step(10, "SSH keypair")
|
||
if KEY_PATH.exists():
|
||
ok(f"Key exists at {KEY_PATH}"); return
|
||
run(f'ssh-keygen -t ed25519 -f {KEY_PATH} -C "switch-manager" -N ""')
|
||
KEY_PATH.chmod(0o600)
|
||
ok("Keypair created")
|
||
|
||
|
||
def get_switch_details():
|
||
step(11, "Switch details")
|
||
sep()
|
||
host = ask("Switch management IP", "192.168.99.1")
|
||
port = ask("SSH port", "22")
|
||
user = ask("Switch username", "admin")
|
||
sep()
|
||
return host, int(port), user
|
||
|
||
|
||
def load_key_on_switch(host, user):
|
||
step(12, "Load public key on switch")
|
||
pub = Path(str(KEY_PATH) + ".pub").read_text().strip()
|
||
sep()
|
||
print(f"""
|
||
{yellow("Console step")} — enter these one at a time on the switch:
|
||
|
||
{cyan("enable")}
|
||
{cyan("configure terminal")}
|
||
{cyan(f'username {user} ssh-key "{pub}"')}
|
||
{cyan("end")}
|
||
{cyan("copy running-config nvram:config.cfg")}
|
||
|
||
{bold("Switch password rules:")}
|
||
{dim("8 to 32 characters. Special chars OK: ! @ # $ % ^ & * - _ = + [ ] ; : , . /")}
|
||
{dim("No spaces. No quotes (' or \"). Spaces end the command.")}
|
||
|
||
{dim("Public key also saved at: " + str(KEY_PATH) + ".pub")}
|
||
""")
|
||
pause("Press Enter once the key is loaded...")
|
||
|
||
|
||
def test_ssh(host, port, user):
|
||
step(13, "Test SSH connection")
|
||
info(f"Connecting to {user}@{host}:{port}...")
|
||
try:
|
||
import paramiko
|
||
client = paramiko.SSHClient()
|
||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||
client.connect(hostname=host, port=port, username=user,
|
||
key_filename=str(KEY_PATH), look_for_keys=False,
|
||
allow_agent=False, timeout=10, banner_timeout=10)
|
||
_, stdout, _ = client.exec_command("show sys-info")
|
||
out = stdout.read().decode("utf-8", errors="replace")
|
||
client.close()
|
||
ok("SSH connection successful")
|
||
for line in out.splitlines():
|
||
if any(x in line for x in ["SysName","Hostname","Name"]):
|
||
info(f"Switch: {line.strip()}"); break
|
||
return True
|
||
except Exception as e:
|
||
err(f"SSH failed: {e}")
|
||
print(f"""
|
||
{yellow("Troubleshooting:")}
|
||
ping {host} ← can this machine reach the switch?
|
||
show ip ssh ← on switch console: confirms SSH is enabled
|
||
show ssh ← on switch console: confirms key is loaded
|
||
ls /dev/ttyUSB* ← confirm console cable is still connected
|
||
""")
|
||
return ask_yn("Retry?", True) and test_ssh(host, port, user)
|
||
|
||
|
||
def pin_host_key(host):
|
||
step(14, "Pin switch host key")
|
||
if KNOWN_HOSTS.exists():
|
||
ok("Host key already pinned"); return
|
||
result = run(f"ssh-keyscan -H {host} 2>/dev/null")
|
||
if result.returncode == 0 and result.stdout.strip():
|
||
KNOWN_HOSTS.write_text(result.stdout)
|
||
KNOWN_HOSTS.chmod(0o644)
|
||
ok("Host key pinned — MITM protection active")
|
||
else:
|
||
warn("Could not pin host key — trust-on-first-use applies")
|
||
|
||
|
||
def setup_totp():
|
||
step(15, "TOTP authenticator")
|
||
import pyotp
|
||
if TOTP_FILE.exists():
|
||
ok("TOTP secret exists")
|
||
if not ask_yn("Show QR / secret again?", False): return
|
||
else:
|
||
secret = pyotp.random_base32()
|
||
TOTP_FILE.write_text(secret)
|
||
TOTP_FILE.chmod(0o600)
|
||
ok("TOTP secret created")
|
||
_display_totp()
|
||
|
||
|
||
def _display_totp():
|
||
import pyotp
|
||
secret = TOTP_FILE.read_text().strip()
|
||
totp = pyotp.TOTP(secret)
|
||
uri = totp.provisioning_uri(name="ERS5952", issuer_name="SwitchManager")
|
||
sep()
|
||
print(f"\n {bold('Secret (for manual entry):')}\n {cyan(secret)}\n")
|
||
shown = False
|
||
if shutil.which("qrencode"):
|
||
r = run(f'qrencode -t ANSIUTF8 "{uri}"', capture=True)
|
||
if r.returncode == 0:
|
||
print(r.stdout)
|
||
ok("QR code above — scan with Google Authenticator, Authy, etc.")
|
||
shown = True
|
||
if not shown:
|
||
try:
|
||
import qrcode
|
||
qr = qrcode.QRCode()
|
||
qr.add_data(uri)
|
||
qr.make()
|
||
print(" Scan this QR code:\n")
|
||
qr.print_ascii(invert=True)
|
||
ok("QR code above — scan with your authenticator app")
|
||
shown = True
|
||
except ImportError:
|
||
pass
|
||
if not shown:
|
||
info("Paste this URI into Google Authenticator or Authy:")
|
||
print(f"\n {dim(uri)}\n")
|
||
sep()
|
||
pause("Press Enter once scanned...")
|
||
while True:
|
||
code = ask("Enter the 6-digit code to verify").strip()
|
||
if totp.verify(code, valid_window=1):
|
||
ok("TOTP verified — authenticator working"); break
|
||
else:
|
||
err("Incorrect — codes rotate every 30 seconds, try again")
|
||
|
||
|
||
def patch_backend(host, port, user):
|
||
step(16, "Patch backend config")
|
||
if not BACKEND.exists():
|
||
warn("switch_backend.py not found — skipping"); return
|
||
content = BACKEND.read_text()
|
||
for old, new in [
|
||
('SWITCH_HOST = "192.168.99.1"', f'SWITCH_HOST = "{host}"'),
|
||
('SWITCH_PORT = 22', f'SWITCH_PORT = {port}'),
|
||
('SWITCH_USER = "admin"', f'SWITCH_USER = "{user}"'),
|
||
]:
|
||
content = content.replace(old, new)
|
||
BACKEND.write_text(content)
|
||
ok(f"Config patched — {host}:{port} user={user}")
|
||
|
||
|
||
def build_frontend():
|
||
step(17, "React frontend build")
|
||
if not shutil.which("node"):
|
||
warn("Node.js not found — skipping")
|
||
info("Install from https://nodejs.org then re-run this script")
|
||
return False
|
||
if DIST.exists() and not ask_yn("Already built — rebuild?", False):
|
||
ok("Using existing build"); return True
|
||
if not APP_JSX.exists():
|
||
warn("ers5952-manager.jsx not found"); return False
|
||
info("Creating Vite project...")
|
||
run(f"npm create vite@latest {FRONTEND} -- --template react --yes", capture=False)
|
||
shutil.copy(APP_JSX, FRONTEND / "src" / "App.jsx")
|
||
main_jsx = FRONTEND / "src" / "main.jsx"
|
||
main_jsx.write_text(
|
||
main_jsx.read_text()
|
||
.replace("import './index.css'\n","")
|
||
.replace("import './index.css'","")
|
||
)
|
||
info("Installing packages...")
|
||
run(f"cd {FRONTEND} && npm install", capture=False)
|
||
info("Building...")
|
||
run(f"cd {FRONTEND} && npm run build", capture=False)
|
||
if DIST.exists():
|
||
ok("Frontend built"); return True
|
||
err("Build failed — check output above"); return False
|
||
|
||
|
||
def _install_caddy_ca():
|
||
"""Extract Caddy internal CA cert and install into system trust store."""
|
||
import base64
|
||
info("Installing Caddy CA certificate into system trust store...")
|
||
|
||
# Extract cert from running Caddy container
|
||
result = run(
|
||
"docker exec $(docker compose ps -q caddy) "
|
||
"cat /data/caddy/pki/authorities/local/root.crt 2>/dev/null",
|
||
check=False
|
||
)
|
||
|
||
if result.returncode != 0 or not result.stdout.strip():
|
||
# Wait a bit more and retry
|
||
time.sleep(5)
|
||
result = run(
|
||
"docker exec $(docker compose ps -q caddy) "
|
||
"cat /data/caddy/pki/authorities/local/root.crt 2>/dev/null",
|
||
check=False
|
||
)
|
||
|
||
if not result.stdout.strip():
|
||
warn("Could not extract Caddy CA cert — browser will show cert warning")
|
||
info("After startup, run: docker exec switch-manager-caddy-1 cat /data/caddy/pki/authorities/local/root.crt | sudo tee /usr/local/share/ca-certificates/caddy-local.crt && sudo update-ca-certificates")
|
||
return
|
||
|
||
cert = result.stdout.strip()
|
||
cert_path = Path("/usr/local/share/ca-certificates/caddy-switch-manager.crt")
|
||
tmp = Path("/tmp/caddy-switch-manager.crt")
|
||
tmp.write_text(cert)
|
||
sudo(f"mv {tmp} {cert_path}")
|
||
sudo("update-ca-certificates")
|
||
ok("Caddy CA installed — browsers on this machine will trust the cert")
|
||
|
||
info("For other devices on VLAN 99, install the CA cert:")
|
||
info(f"Download from: https://{(CONF_DIR / 'fqdn').read_text().strip() if (CONF_DIR / 'fqdn').exists() else 'switch.mgmt.lan'}/caddy-ca.crt")
|
||
info("iOS: AirDrop or email the .crt file, tap it, go to Settings → Profile Downloaded")
|
||
info("Android: Settings → Security → Install certificate")
|
||
info("Mac: double-click the .crt, add to Keychain, set to Always Trust")
|
||
info("Windows: double-click the .crt, Install Certificate, Local Machine, Trusted Root")
|
||
|
||
|
||
|
||
def install_service():
|
||
step(18, "Systemd service")
|
||
if not shutil.which("systemctl"):
|
||
info("No systemd — run manually: python switch_backend.py"); return False
|
||
if SERVICE.exists() and not ask_yn("Service exists — reinstall?", False):
|
||
ok("Service unchanged"); return True
|
||
user = os.getenv("USER","root")
|
||
svc = textwrap.dedent(f"""
|
||
[Unit]
|
||
Description=Avaya ERS 5952 Switch Manager
|
||
After=network.target
|
||
|
||
[Service]
|
||
Type=simple
|
||
User={user}
|
||
WorkingDirectory={HERE}
|
||
ExecStart={sys.executable} {BACKEND}
|
||
Restart=on-failure
|
||
RestartSec=10
|
||
|
||
[Install]
|
||
WantedBy=multi-user.target
|
||
""").strip()
|
||
tmp = Path("/tmp/switch-manager.service")
|
||
tmp.write_text(svc)
|
||
sudo(f"mv {tmp} {SERVICE}")
|
||
sudo("systemctl daemon-reload")
|
||
sudo("systemctl enable switch-manager")
|
||
ok("Service installed and enabled"); return True
|
||
|
||
|
||
def start_service(use_docker=False):
|
||
step(19, "Start service")
|
||
if use_docker:
|
||
run(f"cd {HERE} && docker compose up -d", capture=False, check=False)
|
||
time.sleep(3)
|
||
r = run("docker compose ps", check=False)
|
||
ok("Container running") if ("running" in r.stdout.lower() or "Up" in r.stdout) else warn("Check: docker compose ps")
|
||
return
|
||
if shutil.which("systemctl") and SERVICE.exists():
|
||
sudo("systemctl restart switch-manager")
|
||
time.sleep(2)
|
||
r = run("systemctl is-active switch-manager")
|
||
ok("Service running") if r.stdout.strip()=="active" else warn("Check: journalctl -u switch-manager -n 30")
|
||
else:
|
||
p = __import__('subprocess').Popen(
|
||
[sys.executable, str(BACKEND)],
|
||
stdout=__import__('subprocess').DEVNULL,
|
||
stderr=__import__('subprocess').DEVNULL)
|
||
time.sleep(2)
|
||
ok(f"Backend running (PID {p.pid})") if p.poll() is None else err("Failed — run: python switch_backend.py")
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# WIREGUARD VPN
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
def setup_wireguard(mgmt_ip, gateway_ip):
|
||
step(20, "WireGuard VPN — remote access")
|
||
sep()
|
||
print(f"""
|
||
{bold('WireGuard lets your laptop or phone connect over WiFi')}
|
||
and reach the switch manager as if on the management network.
|
||
|
||
Your device → WireGuard VPN → management computer → VLAN 99 → switch
|
||
|
||
{cyan('1. WireGuard on this management computer')} {dim('(fully automated)')}
|
||
Works without OPNsense. Server runs here.
|
||
|
||
{cyan('2. WireGuard on OPNsense')} {dim('(semi-automated)')}
|
||
More robust for multi-device setups.
|
||
Only available if OPNsense is detected.
|
||
""")
|
||
sep()
|
||
|
||
opnsense_found = False
|
||
if gateway_ip:
|
||
info(f"Checking for OPNsense at {gateway_ip}...")
|
||
opnsense_found = detect_opnsense(gateway_ip)
|
||
ok(f"OPNsense detected at {gateway_ip}") if opnsense_found else info("OPNsense not detected")
|
||
|
||
choice = "1"
|
||
if opnsense_found:
|
||
choice = ask("WireGuard server (1=this computer, 2=OPNsense)", "1")
|
||
|
||
if choice.strip() == "2" and opnsense_found:
|
||
_wg_opnsense(gateway_ip, mgmt_ip)
|
||
else:
|
||
_wg_local(mgmt_ip)
|
||
|
||
|
||
|
||
def setup_ctrld(vlans_config: list):
|
||
"""
|
||
Optional step — set up Control D DNS filtering via ctrld.
|
||
Presents all three options with explanations, user chooses.
|
||
vlans_config: list of { id, name } from VLAN setup
|
||
"""
|
||
step(21, "DNS Filtering — Control D (optional)")
|
||
sep()
|
||
print(f"""
|
||
{bold('Control D')} filters DNS per VLAN — ads, malware, adult content,
|
||
social media, and more. Each VLAN gets its own filtering profile.
|
||
|
||
{cyan('ctrld')} is a local DNS proxy daemon that:
|
||
- Listens on port 53 for normal DNS from your devices
|
||
- Routes queries by source VLAN subnet to the right profile
|
||
- Forwards upstream via encrypted DoH3 to Control D
|
||
- Runs as a system service, starts on boot
|
||
|
||
{bold('You need a Control D account:')} {dim('https://controld.com')}
|
||
Create a Device (type: Router) per VLAN to get a Resolver ID.
|
||
|
||
{bold('Three deployment options:')}
|
||
|
||
{cyan('A — On this management computer')} {dim('(fully automated)')}
|
||
ctrld runs here alongside the switch manager.
|
||
Pros: self-contained, no other machine needed.
|
||
Cons: if this machine is down, DNS filtering stops
|
||
(devices still get IPs, just no filtering).
|
||
|
||
{cyan('B — On OPNsense')} {dim('(semi-automated — one SSH command)')}
|
||
ctrld runs on your router.
|
||
Pros: DNS filtering survives management computer outage.
|
||
Cons: requires SSH access to OPNsense.
|
||
|
||
{cyan('C — Manual / skip')} {dim('(config generated, you install)')}
|
||
Site generates ctrld.toml and install commands.
|
||
Install wherever you want, whenever you want.
|
||
""")
|
||
sep()
|
||
|
||
if not ask_yn("Set up Control D DNS filtering now?", False):
|
||
info("Skipping — you can configure this in the DNS Filtering tab later")
|
||
return
|
||
|
||
choice = ask("Option (A/B/C)", "A").strip().upper()
|
||
|
||
if choice not in ("A","B","C"):
|
||
warn("Invalid choice — skipping"); return
|
||
|
||
# Collect Resolver IDs per VLAN
|
||
sep()
|
||
print(f" {bold('Enter your Control D Resolver ID for each VLAN.')}")
|
||
print(f" {dim('Find it at: controld.com → Endpoints → your device → Resolver ID')}")
|
||
print(f" {dim('Press Enter to skip a VLAN (it will use the first configured profile as fallback).')}")
|
||
print()
|
||
|
||
profiles = []
|
||
for vlan in (vlans_config or [{"id":10,"name":"Staff"},{"id":20,"name":"Servers"},
|
||
{"id":30,"name":"IoT"},{"id":40,"name":"Guest"},
|
||
{"id":50,"name":"Cameras"}]):
|
||
rid = ask(f" VLAN {vlan['id']} ({vlan['name']}) Resolver ID", "").strip()
|
||
if rid:
|
||
profiles.append({
|
||
"vlan_id": vlan["id"],
|
||
"name": vlan["name"],
|
||
"subnet": f"192.168.{vlan['id']}.0/24",
|
||
"resolver_id": rid,
|
||
})
|
||
else:
|
||
info(f"Skipping VLAN {vlan['id']} — will use fallback")
|
||
|
||
if not profiles:
|
||
warn("No Resolver IDs entered — skipping DNS setup")
|
||
return
|
||
|
||
sep()
|
||
|
||
if choice == "A":
|
||
_ctrld_install_local_setup(profiles)
|
||
elif choice == "B":
|
||
_ctrld_opnsense_setup(profiles)
|
||
else:
|
||
_ctrld_manual_setup(profiles)
|
||
|
||
|
||
def _build_toml(profiles: list) -> str:
|
||
lines = [
|
||
"# ctrld config — generated by Avaya 5952 Switch Manager",
|
||
"# https://docs.controld.com/docs/ctrld",
|
||
"",
|
||
"[service]",
|
||
'name = "ctrld"',
|
||
"",
|
||
"[[listener]]",
|
||
'ip = "0.0.0.0"',
|
||
"port = 53",
|
||
'tag = "all-vlans"',
|
||
"",
|
||
]
|
||
for p in profiles:
|
||
tag = f"vlan{p['vlan_id']}"
|
||
lines += [
|
||
f"# VLAN {p['vlan_id']} — {p['name']}",
|
||
f"[[upstream]]",
|
||
f'id = "{tag}"',
|
||
f'type = "doh3"',
|
||
f'endpoint = "https://dns.controld.com/{p['resolver_id']}"',
|
||
f'tag = "{tag}"',
|
||
"",
|
||
]
|
||
lines += ["# Source routing — match VLAN subnet to profile"]
|
||
for p in profiles:
|
||
lines += [
|
||
f"[[rule]]",
|
||
f'listener = "all-vlans"',
|
||
f'source_ip = "{p['subnet']}"',
|
||
f'upstream = "vlan{p['vlan_id']}"',
|
||
"",
|
||
]
|
||
if profiles:
|
||
lines += [
|
||
"[[upstream]]",
|
||
f'id = "fallback"',
|
||
f'type = "doh3"',
|
||
f'endpoint = "https://dns.controld.com/{profiles[0]['resolver_id']}"',
|
||
f'tag = "fallback"',
|
||
"",
|
||
]
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _ctrld_install_local_setup(profiles: list):
|
||
info("Installing ctrld on this machine...")
|
||
first_rid = profiles[0]["resolver_id"]
|
||
|
||
# Download and install via official installer
|
||
install_cmd = f'sh -c \'sh -c "$(curl -sL https://api.controld.com/dl)" -s {first_rid} forced\''
|
||
result = run(install_cmd, capture=False, check=False)
|
||
|
||
ctrld_bin = shutil.which("ctrld") or "/usr/local/bin/ctrld"
|
||
if not Path(ctrld_bin).exists():
|
||
err("ctrld install may have failed — check output above")
|
||
info("Manual install: https://docs.controld.com/docs/ctrld")
|
||
return
|
||
|
||
ok("ctrld installed")
|
||
|
||
# Write multi-VLAN config
|
||
cfg_path = Path("/etc/controld/ctrld.toml")
|
||
cfg_path.parent.mkdir(parents=True, exist_ok=True)
|
||
toml = _build_toml(profiles)
|
||
cfg_path.write_text(toml)
|
||
ok(f"Config written to {cfg_path}")
|
||
|
||
# Restart with new config
|
||
run(f"{ctrld_bin} stop", check=False)
|
||
run(f"{ctrld_bin} start", check=False)
|
||
time.sleep(2)
|
||
|
||
r = run(f"{ctrld_bin} status", check=False)
|
||
if r.returncode == 0:
|
||
ok("ctrld running")
|
||
else:
|
||
warn("ctrld may not be running — check: ctrld status")
|
||
|
||
mgmt_ip = local_ip()
|
||
sep()
|
||
print(f"""
|
||
{bold('ctrld is running on this machine at:')} {cyan(mgmt_ip)}
|
||
|
||
{bold('Next:')} In the switch manager DHCP tab, set DNS (option 6)
|
||
to {cyan(mgmt_ip)} for each VLAN pool. The switch will then hand
|
||
out this machine as the DNS server and ctrld will route each
|
||
VLAN to its Control D profile automatically.
|
||
""")
|
||
|
||
|
||
def _ctrld_opnsense_setup(profiles: list):
|
||
opnsense_ip = ask("OPNsense IP address", "192.168.99.1")
|
||
first_rid = profiles[0]["resolver_id"]
|
||
install_cmd = f'sh -c \'sh -c "$(curl -sL https://api.controld.com/dl)" -s {first_rid} forced\''
|
||
ssh_cmd = f"ssh root@{opnsense_ip} '{install_cmd}'"
|
||
toml = _build_toml(profiles)
|
||
cfg_path = "/usr/local/etc/controld/ctrld.toml"
|
||
|
||
sep()
|
||
print(f"""
|
||
{bold('Step 1 — Run this command (installs ctrld on OPNsense):')}
|
||
{cyan(ssh_cmd)}
|
||
|
||
{bold('Step 2 — Replace the config file on OPNsense:')}
|
||
{dim(f'scp your-toml-file root@{opnsense_ip}:{cfg_path}')}
|
||
{dim('then: ssh root@{opnsense_ip} "ctrld restart"')}
|
||
|
||
{bold('Step 3 — In the switch manager DHCP tab:')}
|
||
Set DNS (option 6) to {cyan(opnsense_ip)} for each VLAN pool.
|
||
""")
|
||
|
||
toml_file = HERE / "ctrld.toml"
|
||
toml_file.write_text(toml)
|
||
ok(f"ctrld.toml written to {toml_file}")
|
||
|
||
if ask_yn("Copy command to clipboard?", False):
|
||
try:
|
||
import subprocess
|
||
subprocess.run(["xclip","-selection","clipboard"],
|
||
input=ssh_cmd.encode(), check=False)
|
||
ok("Copied")
|
||
except Exception:
|
||
info("xclip not available — copy manually from above")
|
||
|
||
|
||
def _ctrld_manual_setup(profiles: list):
|
||
toml = _build_toml(profiles)
|
||
toml_file = HERE / "ctrld.toml"
|
||
toml_file.write_text(toml)
|
||
first_rid = profiles[0]["resolver_id"]
|
||
|
||
sep()
|
||
print(f"""
|
||
{bold('ctrld.toml written to:')} {cyan(str(toml_file))}
|
||
|
||
{bold('Install ctrld on any Linux/Mac/OPNsense machine:')}
|
||
{cyan(f"sh -c 'sh -c \"$(curl -sL https://api.controld.com/dl)\" -s {first_rid} forced'")}
|
||
|
||
{bold('Replace the default config with the generated ctrld.toml')}
|
||
{bold('then restart: ctrld restart')}
|
||
|
||
{bold('Set switch DHCP option 6 to the IP where ctrld is running.')}
|
||
{bold('Configure this in the DNS Filtering tab once the site is running.')}
|
||
|
||
Full docs: {dim('https://docs.controld.com/docs/ctrld')}
|
||
""")
|
||
|
||
|
||
|
||
def _wg_local(mgmt_ip):
|
||
info("Setting up WireGuard server on this machine...")
|
||
if OS != 'linux':
|
||
warn("WireGuard server auto-setup is Linux only")
|
||
info("Install from https://www.wireguard.com/install/")
|
||
return
|
||
|
||
if not shutil.which("wg"):
|
||
err("WireGuard not installed — run system package step first"); return
|
||
|
||
# Server keys
|
||
if not WG_SERVER_KEY.exists():
|
||
priv, pub = wg_genkey()
|
||
WG_SERVER_KEY.write_text(priv); WG_SERVER_KEY.chmod(0o600)
|
||
(CONF_DIR / "wg_server_public").write_text(pub)
|
||
ok("Server keypair generated")
|
||
else:
|
||
priv = WG_SERVER_KEY.read_text().strip()
|
||
pub = (CONF_DIR / "wg_server_public").read_text().strip()
|
||
ok("Using existing server keypair")
|
||
|
||
# IP forwarding
|
||
fwd = Path("/etc/sysctl.d/99-wireguard.conf")
|
||
if not fwd.exists():
|
||
tmp = Path("/tmp/99-wg.conf")
|
||
tmp.write_text("net.ipv4.ip_forward=1\n")
|
||
sudo(f"mv {tmp} {fwd}")
|
||
sudo("sysctl -p /etc/sysctl.d/99-wireguard.conf")
|
||
ok("IP forwarding enabled")
|
||
|
||
# Detect outbound interface for NAT
|
||
nat_iface = run("ip route get 1.1.1.1 2>/dev/null | awk '{print $5; exit}'").stdout.strip() or "eth0"
|
||
|
||
WG_CONF_DIR.mkdir(exist_ok=True)
|
||
wg_conf = WG_CONF_DIR / "wg0.conf"
|
||
|
||
# Preserve existing peers
|
||
existing_peers = ""
|
||
if wg_conf.exists():
|
||
txt = wg_conf.read_text()
|
||
peer_idx = txt.find("\n[Peer]")
|
||
if peer_idx >= 0:
|
||
existing_peers = txt[peer_idx:]
|
||
|
||
server_conf = (
|
||
f"[Interface]\n"
|
||
f"Address = {WG_SUBNET}.1/24\n"
|
||
f"ListenPort = {WG_PORT}\n"
|
||
f"PrivateKey = {priv}\n\n"
|
||
f"# NAT — clients reach the management network\n"
|
||
f"PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; "
|
||
f"iptables -t nat -A POSTROUTING -o {nat_iface} -j MASQUERADE\n"
|
||
f"PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; "
|
||
f"iptables -t nat -D POSTROUTING -o {nat_iface} -j MASQUERADE\n"
|
||
)
|
||
tmp = Path("/tmp/wg0.conf")
|
||
tmp.write_text(server_conf + existing_peers)
|
||
sudo(f"mv {tmp} {wg_conf}")
|
||
sudo(f"chmod 600 {wg_conf}")
|
||
ok("WireGuard server config written")
|
||
|
||
WG_CLIENT_DIR.mkdir(exist_ok=True)
|
||
_wg_add_client(pub, mgmt_ip, wg_conf)
|
||
|
||
sudo("systemctl enable wg-quick@wg0")
|
||
sudo("systemctl restart wg-quick@wg0")
|
||
time.sleep(2)
|
||
r = run("systemctl is-active wg-quick@wg0")
|
||
ok("WireGuard running") if r.stdout.strip()=="active" else warn("Check: journalctl -u wg-quick@wg0 -n 20")
|
||
|
||
|
||
def _wg_add_client(server_pub, mgmt_ip, wg_conf):
|
||
import re
|
||
# Find next available IP
|
||
used = set()
|
||
if wg_conf.exists():
|
||
for m in re.finditer(r'AllowedIPs\s*=\s*(\S+)', wg_conf.read_text()):
|
||
used.add(m.group(1).split('/')[0])
|
||
num = 2
|
||
while f"{WG_SUBNET}.{num}" in used and num < 254:
|
||
num += 1
|
||
client_ip = f"{WG_SUBNET}.{num}"
|
||
|
||
name = ask("Client name (e.g. laptop, phone, tablet)", f"client{num-1}")
|
||
c_priv, c_pub = wg_genkey()
|
||
|
||
# Append peer to server config
|
||
peer = f"\n[Peer]\n# {name}\nPublicKey = {c_pub}\nAllowedIPs = {client_ip}/32\n"
|
||
with open(wg_conf, 'a') as f:
|
||
f.write(peer)
|
||
ok(f"Peer '{name}' added")
|
||
|
||
# Reload live config if WireGuard is running
|
||
run("wg syncconf wg0 <(wg-quick strip wg0) 2>/dev/null", check=False)
|
||
|
||
# Get server public IP for endpoint
|
||
pub_ip = run("curl -s --max-time 5 https://api.ipify.org 2>/dev/null",
|
||
check=False).stdout.strip() or mgmt_ip
|
||
|
||
# Split tunnel — only management subnets go through VPN
|
||
mgmt_subnet = '.'.join(mgmt_ip.split('.')[:3]) + '.0/24'
|
||
vpn_subnet = f"{WG_SUBNET}.0/24"
|
||
|
||
client_conf = (
|
||
f"[Interface]\n"
|
||
f"PrivateKey = {c_priv}\n"
|
||
f"Address = {client_ip}/24\n"
|
||
f"DNS = {WG_SUBNET}.1\n\n"
|
||
f"[Peer]\n"
|
||
f"PublicKey = {server_pub}\n"
|
||
f"Endpoint = {pub_ip}:{WG_PORT}\n"
|
||
f"AllowedIPs = {mgmt_subnet}, {vpn_subnet}\n"
|
||
f"PersistentKeepalive = 25\n"
|
||
)
|
||
|
||
client_file = WG_CLIENT_DIR / f"{name}.conf"
|
||
client_file.write_text(client_conf)
|
||
client_file.chmod(0o600)
|
||
ok(f"Client config: {client_file}")
|
||
|
||
# Output QR
|
||
sep()
|
||
print(f"\n {bold('Scan this QR code with the WireGuard app:')}")
|
||
print(f" {dim('iOS / Android: search WireGuard in App Store / Play Store')}")
|
||
print(f" {dim('Desktop: https://www.wireguard.com/install/')}\n")
|
||
|
||
shown = False
|
||
if shutil.which("qrencode"):
|
||
r = run(f"qrencode -t ANSIUTF8 -r {client_file}", capture=True)
|
||
if r.returncode == 0:
|
||
print(r.stdout); shown = True
|
||
if not shown:
|
||
try:
|
||
import qrcode
|
||
qr = qrcode.QRCode()
|
||
qr.add_data(client_conf)
|
||
qr.make()
|
||
qr.print_ascii(invert=True)
|
||
shown = True
|
||
except ImportError:
|
||
pass
|
||
if not shown:
|
||
info(f"Config at {client_file} — import manually into WireGuard app")
|
||
|
||
sep()
|
||
print(f"""
|
||
{bold('Config file:')} {cyan(str(client_file))}
|
||
{bold('Desktop import:')} WireGuard → Import tunnel → {client_file.name}
|
||
|
||
{bold('Once connected, open:')}
|
||
{cyan(f'http://{mgmt_ip}:8765')} — switch manager UI
|
||
{cyan(mgmt_subnet)} — full management subnet accessible
|
||
""")
|
||
if ask_yn("Add another client (another device)?", False):
|
||
_wg_add_client(server_pub, mgmt_ip, wg_conf)
|
||
|
||
|
||
def _wg_opnsense(gateway_ip, mgmt_ip):
|
||
sep()
|
||
print(f"""
|
||
{bold('OPNsense WireGuard — semi-automated')}
|
||
|
||
Keys and peer config generated here.
|
||
Add the peer in OPNsense UI: VPN → WireGuard → Peers
|
||
""")
|
||
c_priv, c_pub = wg_genkey()
|
||
server_pub = ask("OPNsense WireGuard server public key")
|
||
client_ip = ask("VPN IP for this client", f"{WG_SUBNET}.2")
|
||
mgmt_subnet = '.'.join(mgmt_ip.split('.')[:3]) + '.0/24'
|
||
|
||
client_conf = (
|
||
f"[Interface]\n"
|
||
f"PrivateKey = {c_priv}\n"
|
||
f"Address = {client_ip}/24\n\n"
|
||
f"[Peer]\n"
|
||
f"PublicKey = {server_pub}\n"
|
||
f"Endpoint = {gateway_ip}:{WG_PORT}\n"
|
||
f"AllowedIPs = {mgmt_subnet}, {WG_SUBNET}.0/24\n"
|
||
f"PersistentKeepalive = 25\n"
|
||
)
|
||
|
||
WG_CLIENT_DIR.mkdir(exist_ok=True)
|
||
client_file = WG_CLIENT_DIR / "opnsense-client.conf"
|
||
client_file.write_text(client_conf)
|
||
client_file.chmod(0o600)
|
||
|
||
print(f"""
|
||
{bold('Add this peer in OPNsense → VPN → WireGuard → Peers:')}
|
||
Public Key: {cyan(c_pub)}
|
||
Allowed IPs: {cyan(f'{client_ip}/32')}
|
||
""")
|
||
sep()
|
||
shown = False
|
||
if shutil.which("qrencode"):
|
||
r = run(f"qrencode -t ANSIUTF8 -r {client_file}", capture=True)
|
||
if r.returncode == 0:
|
||
print(r.stdout); shown = True
|
||
if not shown:
|
||
try:
|
||
import qrcode
|
||
qr = qrcode.QRCode()
|
||
qr.add_data(client_conf)
|
||
qr.make()
|
||
qr.print_ascii(invert=True)
|
||
except ImportError:
|
||
info(f"Import {client_file} into WireGuard app manually")
|
||
ok(f"Client config: {client_file}")
|
||
|
||
|
||
def summary(host, use_docker, mgmt_ip):
|
||
ip = mgmt_ip or local_ip()
|
||
fqdn_file = CONF_DIR / "fqdn"
|
||
fqdn = fqdn_file.read_text().strip() if fqdn_file.exists() else None
|
||
url = f"https://{fqdn}" if (use_docker and fqdn) else f"http://{ip}:8765"
|
||
url_note = f"also http://{ip}:8765" if use_docker and fqdn else ""
|
||
method = "Docker + Caddy (HTTPS)" if use_docker else "Native Python / systemd"
|
||
logs = "docker compose logs -f" if use_docker else "journalctl -u switch-manager -f"
|
||
status = "docker compose ps" if use_docker else "systemctl status switch-manager"
|
||
print(f"""
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
{bold(cyan(" Avaya ERS 5952 Switch Manager — Ready"))}
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
|
||
{bold("URL (VLAN 99 or WireGuard connected):")}
|
||
{green(url)}
|
||
{dim(url_note) if url_note else ""}
|
||
|
||
{bold("Switch:")} {cyan(host)}
|
||
{bold("Running as:")} {method}
|
||
{(bold("DNS needed: ") + dim(f"Add {fqdn} → {ip} in your router split DNS")) if use_docker and fqdn else ""}
|
||
{bold("TOTP secret:")} {dim(str(TOTP_FILE))} ← back this up
|
||
{bold("VPN configs:")} {dim(str(WG_CLIENT_DIR))}
|
||
|
||
{bold("Read-only:")} open the URL — no auth needed
|
||
{bold("To push:")} Authenticate → TOTP → push → auto-locks
|
||
Next set of changes needs a new TOTP code.
|
||
|
||
{bold("Console cable:")} only if you lock yourself out
|
||
{bold("Ethernet:")} handles all normal management
|
||
|
||
{bold("Logs:")} {logs}
|
||
{bold("Status:")} {status}
|
||
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
""")
|
||
if ask_yn(f"Open {url} in browser?", True):
|
||
import webbrowser; time.sleep(1); webbrowser.open(url)
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# MAIN
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
def main():
|
||
print(f"""
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
{bold(cyan(" Avaya ERS 5952 Switch Manager — Setup"))}
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
Browser-based management for your Avaya / Extreme
|
||
ERS 5952 switch. No CLI knowledge needed.
|
||
|
||
Copy this single file to your always-on management
|
||
computer (Raspberry Pi, HP T620 thin client, old
|
||
computer or laptop) and run:
|
||
python Avaya_5952_setup.py
|
||
|
||
{yellow("One manual step:")} loading the SSH key onto the
|
||
switch via console cable. Everything else is automated.
|
||
|
||
{dim("Compatible: ERS 5928, 5948, 5952, 5952-PWR+")}
|
||
{bold(cyan("══════════════════════════════════════════════════"))}
|
||
""")
|
||
if not ask_yn("Begin setup?", True): sys.exit(0)
|
||
|
||
write_files()
|
||
install_system_packages()
|
||
ensure_dialout_group()
|
||
install_deps()
|
||
create_conf_dir()
|
||
|
||
mgmt_ip, gateway_ip = "192.168.99.50", "192.168.99.1"
|
||
result = set_static_ip()
|
||
if result:
|
||
mgmt_ip, gateway_ip = result
|
||
|
||
use_docker = choose_deployment()
|
||
console_cable_guidance()
|
||
gen_ssh_key()
|
||
host, port, user = get_switch_details()
|
||
load_key_on_switch(host, user)
|
||
|
||
ssh_ok = test_ssh(host, port, user)
|
||
if not ssh_ok:
|
||
warn("SSH test failed — continuing, fix before using push feature")
|
||
|
||
pin_host_key(host)
|
||
setup_totp()
|
||
patch_backend(host, port, user)
|
||
build_frontend()
|
||
|
||
if use_docker:
|
||
setup_docker()
|
||
else:
|
||
install_service()
|
||
|
||
start_service(use_docker)
|
||
|
||
if ask_yn("Set up Control D DNS filtering?", False):
|
||
setup_ctrld([
|
||
{"id":10,"name":"Staff"},
|
||
{"id":20,"name":"Servers"},
|
||
{"id":30,"name":"IoT"},
|
||
{"id":40,"name":"Guest"},
|
||
{"id":50,"name":"Cameras"},
|
||
])
|
||
|
||
if ask_yn("Set up WireGuard VPN for remote access from laptop/phone?", True):
|
||
setup_wireguard(mgmt_ip, gateway_ip)
|
||
|
||
summary(host, use_docker, mgmt_ip)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|