sh2/d2ypp2/src/wireguard_config.py
eric 0317349eed Harden install-time proxy for apt/Docker and WireGuard Neko remote mode.
LAN Clash deploys were timing out on Neko image pulls because the Docker daemon ignored shell http_proxy; also keep NAT1TO1 on the overlay after wg-quick apply.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:56:21 -05:00

1514 lines
59 KiB
Python

"""WireGuard configuration import helpers for the live hub network module."""
from __future__ import annotations
import ipaddress
import json
import os
import platform
import re
import shutil
import subprocess
import time
from pathlib import Path
from typing import Any
MAX_WIREGUARD_CONFIG_BYTES = 128 * 1024
SENSITIVE_WG_KEYS = {"privatekey", "presharedkey", "publickey"}
_SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9_.-]+")
_BASE64_KEY_RE = re.compile(r"^[A-Za-z0-9+/]{43}=$")
_DEFAULT_ROUTES = {"0.0.0.0/0", "::/0"}
DEFAULT_OVERLAY_MTU = 1360
DEFAULT_KEEPALIVE_SECONDS = 25
GOOD_HANDSHAKE_SECONDS = 180
STALE_HANDSHAKE_SECONDS = 900
MAX_ENDPOINT_ROUTE_CHECKS = 8
class WireGuardConfigError(ValueError):
"""Raised when an imported WireGuard config is malformed."""
def _strip_inline_comment(line: str) -> str:
in_quote = False
quote = ""
for idx, ch in enumerate(line):
if ch in {"'", '"'}:
if in_quote and ch == quote:
in_quote = False
quote = ""
elif not in_quote:
in_quote = True
quote = ch
if not in_quote and ch in {"#", ";"}:
return line[:idx]
return line
def safe_wireguard_name(name: str | None) -> str:
raw = (name or "imported-wg").strip()
raw = raw[:-5] if raw.lower().endswith(".conf") else raw
safe = _SAFE_NAME_RE.sub("-", raw).strip(".-")
if not safe:
safe = "imported-wg"
return safe[:64]
def _parse_endpoint(value: str) -> tuple[str, int]:
raw = value.strip()
if not raw:
raise WireGuardConfigError("Endpoint is empty")
if raw.startswith("["):
end = raw.find("]")
if end < 0 or end + 2 > len(raw) or raw[end + 1] != ":":
raise WireGuardConfigError(f"Invalid WireGuard Endpoint: {raw}")
host = raw[1:end]
port_raw = raw[end + 2 :]
else:
host, sep, port_raw = raw.rpartition(":")
if not sep:
raise WireGuardConfigError(f"Invalid WireGuard Endpoint: {raw}")
host = host.strip()
try:
port = int(port_raw)
except ValueError as exc:
raise WireGuardConfigError(f"Invalid WireGuard Endpoint port: {raw}") from exc
if not host or port < 1 or port > 65535:
raise WireGuardConfigError(f"Invalid WireGuard Endpoint: {raw}")
return host, port
def _split_csv(value: str) -> list[str]:
return [item.strip() for item in value.split(",") if item.strip()]
def _normalized_config_text(content: str) -> str:
return content.replace("\r\n", "\n").replace("\r", "\n").strip() + "\n"
def _validate_ip_interfaces(values: list[str], label: str) -> list[str]:
parsed: list[str] = []
for item in values:
try:
parsed.append(str(ipaddress.ip_interface(item)))
except ValueError as exc:
raise WireGuardConfigError(f"Invalid {label}: {item}") from exc
return parsed
def _validate_ip_networks(values: list[str], label: str) -> list[str]:
parsed: list[str] = []
for item in values:
try:
parsed.append(str(ipaddress.ip_network(item, strict=False)))
except ValueError as exc:
raise WireGuardConfigError(f"Invalid {label}: {item}") from exc
return parsed
def _redact_value(key: str, value: str) -> str:
if key.strip().lower() in SENSITIVE_WG_KEYS:
if not value:
return "<redacted>"
return f"<redacted:{len(value)}>"
return value
def redact_wireguard_config(content: str) -> str:
redacted: list[str] = []
for raw in content.replace("\r\n", "\n").replace("\r", "\n").splitlines():
if "=" not in raw or raw.lstrip().startswith(("#", ";")):
redacted.append(raw)
continue
key, sep, value = raw.partition("=")
redacted.append(f"{key}{sep} {_redact_value(key, value.strip())}")
return "\n".join(redacted).strip() + "\n"
def parse_wireguard_config(content: str, *, name: str | None = None) -> dict[str, Any]:
if "\x00" in content:
raise WireGuardConfigError("WireGuard config contains NUL bytes")
if len(content.encode("utf-8")) > MAX_WIREGUARD_CONFIG_BYTES:
raise WireGuardConfigError("WireGuard config is too large")
sections: list[dict[str, Any]] = []
current: dict[str, Any] | None = None
warnings: list[str] = []
for lineno, raw in enumerate(content.replace("\r\n", "\n").replace("\r", "\n").splitlines(), start=1):
line = _strip_inline_comment(raw).strip()
if not line:
continue
if line.startswith("[") and line.endswith("]"):
section_name = line[1:-1].strip()
if section_name not in {"Interface", "Peer"}:
warnings.append(f"Line {lineno}: ignored unknown section [{section_name}]")
current = {"name": section_name, "items": {}, "lineno": lineno}
sections.append(current)
continue
if current is None:
raise WireGuardConfigError(f"Line {lineno}: key/value appears before a section")
if "=" not in line:
raise WireGuardConfigError(f"Line {lineno}: expected key = value")
key, _, value = line.partition("=")
key = key.strip()
value = value.strip().strip('"').strip("'")
if not key:
raise WireGuardConfigError(f"Line {lineno}: empty key")
items = current["items"]
items.setdefault(key, []).append(value)
interfaces = [s for s in sections if s["name"] == "Interface"]
peers = [s for s in sections if s["name"] == "Peer"]
if not interfaces:
raise WireGuardConfigError("WireGuard config must include [Interface]")
if len(interfaces) > 1:
warnings.append("Multiple [Interface] sections found; using the first one")
if not peers:
raise WireGuardConfigError("WireGuard config must include at least one [Peer]")
iface_items = interfaces[0]["items"]
addresses = _validate_ip_interfaces(_split_csv(",".join(iface_items.get("Address", []))), "Address")
dns = _split_csv(",".join(iface_items.get("DNS", [])))
mtu = None
if iface_items.get("MTU"):
try:
mtu = int(iface_items["MTU"][-1])
except ValueError as exc:
raise WireGuardConfigError("Invalid MTU") from exc
if mtu < 576 or mtu > 9000:
warnings.append(f"MTU {mtu} is outside the usual WireGuard range")
peer_summaries: list[dict[str, Any]] = []
for idx, peer in enumerate(peers, start=1):
items = peer["items"]
allowed_ips = _validate_ip_networks(_split_csv(",".join(items.get("AllowedIPs", []))), "AllowedIPs")
routes_default = any(item in _DEFAULT_ROUTES for item in allowed_ips)
if routes_default:
warnings.append(
f"Peer {idx}: AllowedIPs contains a default route; overlay mode is safer when ShellCrash/soft-router proxy must keep working"
)
endpoint_raw = (items.get("Endpoint") or [""])[-1]
endpoint_host = ""
endpoint_port: int | None = None
if endpoint_raw:
endpoint_host, endpoint_port = _parse_endpoint(endpoint_raw)
keepalive = None
if items.get("PersistentKeepalive"):
try:
keepalive = int(items["PersistentKeepalive"][-1])
except ValueError as exc:
raise WireGuardConfigError("Invalid PersistentKeepalive") from exc
if endpoint_raw and keepalive is None:
warnings.append(f"Peer {idx}: PersistentKeepalive is missing; 25 is recommended for NAT/VPS relay links")
public_key = (items.get("PublicKey") or [""])[-1]
if public_key and not _BASE64_KEY_RE.match(public_key):
warnings.append(f"Peer {idx}: PublicKey does not look like a standard WireGuard key")
peer_summaries.append(
{
"id": idx,
"public_key": _redact_value("PublicKey", public_key) if public_key else "",
"endpoint": endpoint_raw,
"endpoint_host": endpoint_host,
"endpoint_port": endpoint_port,
"allowed_ips": allowed_ips,
"routes_default": routes_default,
"persistent_keepalive": keepalive,
}
)
private_key = (iface_items.get("PrivateKey") or [""])[-1]
if private_key and not _BASE64_KEY_RE.match(private_key):
warnings.append("Interface PrivateKey does not look like a standard WireGuard key")
safe_name = safe_wireguard_name(name)
return {
"name": safe_name,
"interface": {
"addresses": addresses,
"dns": dns,
"mtu": mtu,
"private_key": _redact_value("PrivateKey", private_key) if private_key else "",
"listen_port": (iface_items.get("ListenPort") or [""])[-1],
},
"peers": peer_summaries,
"peer_count": len(peer_summaries),
"warnings": warnings,
"redacted_config": redact_wireguard_config(content),
}
def _wireguard_config_health(summary: dict[str, Any]) -> dict[str, Any]:
peers = summary.get("peers") if isinstance(summary.get("peers"), list) else []
endpoint_hosts: list[str] = []
endpoint_ports: list[int] = []
missing_keepalive = 0
default_route_peers = 0
for peer in peers:
if not isinstance(peer, dict):
continue
host = str(peer.get("endpoint_host") or "").strip()
port = peer.get("endpoint_port")
if host and host not in endpoint_hosts:
endpoint_hosts.append(host)
if isinstance(port, int) and port not in endpoint_ports:
endpoint_ports.append(port)
if peer.get("endpoint") and peer.get("persistent_keepalive") in {None, "", 0}:
missing_keepalive += 1
if peer.get("routes_default"):
default_route_peers += 1
interface = summary.get("interface") if isinstance(summary.get("interface"), dict) else {}
return {
"endpoint_hosts": endpoint_hosts,
"endpoint_ports": endpoint_ports,
"missing_keepalive_peer_count": missing_keepalive,
"default_route_peer_count": default_route_peers,
"mtu": interface.get("mtu"),
"address_count": len(interface.get("addresses") or []),
}
def _infer_overlay_allowed_ips(summary: dict[str, Any]) -> list[str]:
out: list[str] = []
for raw in (summary.get("interface") or {}).get("addresses") or []:
try:
iface = ipaddress.ip_interface(str(raw))
except ValueError:
continue
ip = iface.ip
if not isinstance(ip, ipaddress.IPv4Address) or not ip.is_private:
continue
if iface.network.prefixlen < 32:
network = iface.network
else:
network = ipaddress.ip_network(f"{ip}/24", strict=False)
value = str(network)
if value not in out:
out.append(value)
return out
def normalize_wireguard_overlay_config(content: str, *, name: str | None = None) -> tuple[str, dict[str, Any]]:
summary = parse_wireguard_config(content, name=name)
overlay_allowed = _infer_overlay_allowed_ips(summary)
warnings: list[str] = []
if not overlay_allowed:
warnings.append("No private Interface Address was found; kept AllowedIPs unchanged")
normalized, keepalive = normalize_wireguard_keepalive_config(content)
warnings.extend(keepalive.get("warnings") or [])
return normalized, {
"changed": bool(keepalive.get("changed")),
"allowed_ips": [],
"warnings": warnings,
"keepalive": keepalive,
}
lines = _normalized_config_text(content).splitlines()
next_lines: list[str] = []
section = ""
peer_has_keepalive = False
peer_seen_endpoint = False
changed = False
added_keepalive = 0
added_mtu = False
interface_has_mtu = False
interface_seen_address = False
def maybe_add_keepalive() -> None:
nonlocal added_keepalive, changed, peer_has_keepalive, peer_seen_endpoint
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
added_keepalive += 1
changed = True
peer_has_keepalive = False
peer_seen_endpoint = False
for raw in lines:
stripped = _strip_inline_comment(raw).strip()
if stripped.startswith("[") and stripped.endswith("]"):
if section == "Interface" and interface_seen_address and not interface_has_mtu:
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
added_mtu = True
changed = True
maybe_add_keepalive()
section = stripped[1:-1].strip()
if section == "Interface":
interface_has_mtu = False
interface_seen_address = False
next_lines.append(raw)
continue
if "=" not in stripped:
next_lines.append(raw)
continue
key, _, value = stripped.partition("=")
key_l = key.strip().lower()
if section == "Interface":
if key_l == "address":
interface_seen_address = True
elif key_l == "mtu":
interface_has_mtu = True
elif section == "Peer":
if key_l == "endpoint":
peer_seen_endpoint = True
elif key_l == "persistentkeepalive":
peer_has_keepalive = True
elif key_l == "allowedips":
allowed = _validate_ip_networks(_split_csv(value), "AllowedIPs")
if any(item in _DEFAULT_ROUTES for item in allowed):
next_lines.append(f"AllowedIPs = {', '.join(overlay_allowed)}")
changed = True
continue
next_lines.append(raw)
if section == "Interface" and interface_seen_address and not interface_has_mtu:
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
added_mtu = True
changed = True
maybe_add_keepalive()
if changed:
warnings.append("Overlay mode removed default routes so WireGuard will not hijack ShellCrash/soft-router traffic")
if added_mtu:
warnings.append(f"Overlay mode added MTU {DEFAULT_OVERLAY_MTU} for VPS relay stability")
if added_keepalive:
warnings.append(f"Overlay mode added PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS} to {added_keepalive} peer(s)")
return "\n".join(next_lines).strip() + "\n", {"changed": changed, "allowed_ips": overlay_allowed, "warnings": warnings}
def normalize_wireguard_keepalive_config(content: str) -> tuple[str, dict[str, Any]]:
lines = _normalized_config_text(content).splitlines()
next_lines: list[str] = []
section = ""
peer_has_keepalive = False
peer_seen_endpoint = False
changed = False
added_keepalive = 0
def maybe_add_keepalive() -> None:
nonlocal added_keepalive, changed, peer_has_keepalive, peer_seen_endpoint
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
added_keepalive += 1
changed = True
peer_has_keepalive = False
peer_seen_endpoint = False
for raw in lines:
stripped = _strip_inline_comment(raw).strip()
if stripped.startswith("[") and stripped.endswith("]"):
maybe_add_keepalive()
section = stripped[1:-1].strip()
next_lines.append(raw)
continue
if "=" in stripped:
key, _, _value = stripped.partition("=")
key_l = key.strip().lower()
if section == "Peer":
if key_l == "endpoint":
peer_seen_endpoint = True
elif key_l == "persistentkeepalive":
peer_has_keepalive = True
next_lines.append(raw)
maybe_add_keepalive()
warnings = []
if added_keepalive:
warnings.append(f"Added PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS} to {added_keepalive} WireGuard peer(s)")
return "\n".join(next_lines).strip() + "\n", {"changed": changed, "added_keepalive": added_keepalive, "warnings": warnings}
def _save_wireguard_summary(summary: dict[str, Any], target: Path) -> Path:
summary_path = target.with_suffix(".summary.json")
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return summary_path
def save_imported_wireguard_config(
content: str,
*,
name: str | None,
repo_root: Path,
route_mode: str = "preserve",
) -> dict[str, Any]:
route_mode = (route_mode or "preserve").strip().lower()
overlay: dict[str, Any] = {"changed": False, "allowed_ips": [], "warnings": []}
if route_mode == "overlay":
normalized, overlay = normalize_wireguard_overlay_config(content, name=name)
elif route_mode == "preserve":
normalized, keepalive = normalize_wireguard_keepalive_config(content)
if keepalive.get("warnings"):
overlay["warnings"] = [*overlay.get("warnings", []), *keepalive["warnings"]]
overlay["changed"] = bool(overlay.get("changed") or keepalive.get("changed"))
overlay["keepalive"] = keepalive
else:
raise WireGuardConfigError(f"Unsupported WireGuard route mode: {route_mode}")
summary = parse_wireguard_config(normalized, name=name)
if overlay.get("warnings"):
summary["warnings"] = [*summary.get("warnings", []), *overlay["warnings"]]
summary["route_mode"] = route_mode
summary["overlay"] = overlay
summary["health"] = _wireguard_config_health(summary)
safe_name = str(summary["name"])
target_dir = repo_root / "config" / "wireguard" / "imports"
target_dir.mkdir(parents=True, exist_ok=True)
target = target_dir / f"{safe_name}.conf"
target.write_text(normalized, encoding="utf-8")
try:
os.chmod(target, 0o600)
except OSError:
pass
summary_path = _save_wireguard_summary(summary, target)
result = dict(summary)
result.update(
{
"path": str(target),
"relative_path": str(target.relative_to(repo_root)),
"summary_path": str(summary_path),
"linux_apply_commands": [
f"install -m 600 {target} /etc/wireguard/{safe_name}.conf",
f"systemctl enable --now wg-quick@{safe_name}",
],
}
)
first_endpoint = next((p for p in summary["peers"] if p.get("endpoint_host")), None)
if first_endpoint:
endpoint_host = str(first_endpoint["endpoint_host"])
result["windows_route_template"] = {
"endpoint_host": endpoint_host,
"powershell": f"route -p add {endpoint_host} mask 255.255.255.255 <gateway> metric 1 if <ifIndex>",
"delete": f"route delete {endpoint_host}",
}
return result
def list_imported_wireguard_configs(repo_root: Path) -> list[dict[str, Any]]:
target_dir = repo_root / "config" / "wireguard" / "imports"
if not target_dir.is_dir():
return []
out: list[dict[str, Any]] = []
for path in sorted(target_dir.glob("*.conf")):
try:
content = path.read_text(encoding="utf-8")
summary = parse_wireguard_config(content, name=path.stem)
except (OSError, WireGuardConfigError) as exc:
summary = {"name": path.stem, "warnings": [str(exc)], "peer_count": 0}
summary.update(
{
"path": str(path),
"relative_path": str(path.relative_to(repo_root)),
"size": path.stat().st_size if path.exists() else 0,
"readable": True,
"health": _wireguard_config_health(summary),
}
)
out.append(summary)
return out
def _read_wireguard_config_record(path: Path, *, source: str, repo_root: Path | None = None) -> dict[str, Any]:
record: dict[str, Any] = {
"name": path.stem,
"path": str(path),
"source": source,
"readable": False,
"peer_count": 0,
"warnings": [],
}
if repo_root is not None:
try:
record["relative_path"] = str(path.relative_to(repo_root))
except ValueError:
pass
try:
record["size"] = path.stat().st_size
except OSError as exc:
record["warnings"] = [f"WireGuard config metadata unavailable: {exc}"]
return record
try:
content = path.read_text(encoding="utf-8", errors="ignore")
summary = parse_wireguard_config(content, name=path.stem)
except (OSError, WireGuardConfigError) as exc:
record["warnings"] = [str(exc)]
return record
record.update(
{
"readable": True,
"interface": summary.get("interface") or {},
"peers": summary.get("peers") or [],
"peer_count": summary.get("peer_count") or 0,
"warnings": summary.get("warnings") or [],
"health": _wireguard_config_health(summary),
}
)
return record
def _system_wireguard_configs() -> list[dict[str, Any]]:
etc_wg = Path("/etc/wireguard")
if not etc_wg.is_dir():
return []
try:
paths = sorted(etc_wg.glob("*.conf"))
except OSError:
return []
return [_read_wireguard_config_record(path, source="system") for path in paths]
def _address_ips(addresses: list[str] | None) -> set[str]:
out: set[str] = set()
for raw in addresses or []:
try:
out.add(str(ipaddress.ip_interface(str(raw)).ip))
except ValueError:
continue
return out
def _config_match_score(iface: dict[str, Any], config: dict[str, Any]) -> int:
score = 0
iface_name = str(iface.get("name") or "").strip()
cfg_name = str(config.get("name") or "").strip()
if iface_name and cfg_name and iface_name == cfg_name:
score += 100
elif iface_name and cfg_name and iface_name.lower() == cfg_name.lower():
score += 80
cfg_iface = config.get("interface") if isinstance(config.get("interface"), dict) else {}
if _address_ips(iface.get("addresses") or []) & _address_ips(cfg_iface.get("addresses") or []):
score += 60
return score
def _best_config_for_interface(
iface: dict[str, Any],
configs: list[dict[str, Any]],
*,
single_interface: bool,
) -> dict[str, Any] | None:
readable = [cfg for cfg in configs if cfg.get("readable") and cfg.get("peer_count")]
if not readable:
return None
ranked = sorted(((_config_match_score(iface, cfg), cfg) for cfg in readable), key=lambda item: item[0], reverse=True)
if ranked and ranked[0][0] > 0:
return ranked[0][1]
if single_interface and len(readable) == 1:
return readable[0]
return None
def _attach_configured_wireguard_peers(
interfaces: list[dict[str, Any]],
*,
system_configs: list[dict[str, Any]],
repo_configs: list[dict[str, Any]],
) -> None:
configs = [*system_configs, *repo_configs]
single_interface = len(interfaces) == 1
for iface in interfaces:
config = _best_config_for_interface(iface, configs, single_interface=single_interface)
if not config:
continue
cfg_iface = config.get("interface") if isinstance(config.get("interface"), dict) else {}
configured_peers: list[dict[str, Any]] = []
for peer in config.get("peers") or []:
if not isinstance(peer, dict):
continue
configured = dict(peer)
configured["status_source"] = "config"
configured["config_source"] = config.get("source") or ("repo" if config.get("relative_path") else "system")
configured_peers.append(configured)
iface["configured_from"] = {
"name": config.get("name") or "",
"path": config.get("relative_path") or config.get("path") or "",
"source": config.get("source") or ("repo" if config.get("relative_path") else "system"),
"readable": bool(config.get("readable")),
}
iface["configured_interface"] = cfg_iface
iface["configured_peers"] = configured_peers
if not iface.get("addresses") and cfg_iface.get("addresses"):
iface["addresses"] = list(cfg_iface.get("addresses") or [])
def _configured_wireguard_peer_count(interfaces: list[dict[str, Any]]) -> int:
return sum(len(iface.get("configured_peers") or []) for iface in interfaces)
def _all_wireguard_endpoint_hosts(
interfaces: list[dict[str, Any]],
*,
system_configs: list[dict[str, Any]],
repo_configs: list[dict[str, Any]],
) -> list[str]:
hosts: list[str] = []
def add(host: Any) -> None:
value = str(host or "").strip().strip("[]")
if value and value not in hosts:
hosts.append(value)
for iface in interfaces:
for peer in [*(iface.get("peers") or []), *(iface.get("configured_peers") or [])]:
if isinstance(peer, dict):
add(peer.get("endpoint_host") or _endpoint_host_from_value(str(peer.get("endpoint") or "")))
for config in [*system_configs, *repo_configs]:
for peer in config.get("peers") or []:
if isinstance(peer, dict):
add(peer.get("endpoint_host"))
return hosts
def _endpoint_host_from_value(value: str) -> str:
raw = value.strip()
if not raw:
return ""
if raw.startswith("["):
end = raw.find("]")
return raw[1:end] if end > 0 else ""
host, sep, _port = raw.rpartition(":")
return host.strip() if sep else raw
def _endpoint_route_diagnostics(hosts: list[str], wireguard_names: set[str]) -> list[dict[str, Any]]:
if not shutil.which("ip"):
return []
out: list[dict[str, Any]] = []
for host in hosts[:MAX_ENDPOINT_ROUTE_CHECKS]:
result = _run_command(["ip", "route", "get", host], timeout=2.0)
stdout = str(result.get("stdout") or "")
first_line = stdout.splitlines()[0] if stdout else ""
item: dict[str, Any] = {
"host": host,
"ok": bool(result.get("ok")),
"route": first_line,
}
for key in ("dev", "via", "src"):
match = re.search(rf"(?:^|\s){key}\s+(\S+)", first_line)
if match:
item[key] = match.group(1)
dev = str(item.get("dev") or "")
if dev and dev in wireguard_names:
item["uses_wireguard_interface"] = True
item["warning"] = "Endpoint route resolves through WireGuard; add a physical gateway bypass route"
if not result.get("ok"):
item["error"] = str(result.get("stderr") or result.get("stdout") or "")
out.append(item)
return out
def read_imported_wireguard_config(name: str, *, repo_root: Path) -> dict[str, Any]:
safe_name = safe_wireguard_name(name)
path = repo_root / "config" / "wireguard" / "imports" / f"{safe_name}.conf"
if not path.is_file():
raise WireGuardConfigError(f"WireGuard config not found: {safe_name}")
content = path.read_text(encoding="utf-8")
return {"name": safe_name, "content": content, "wireguard": parse_wireguard_config(content, name=safe_name)}
def _run_command(args: list[str], *, timeout: float = 5.0) -> dict[str, Any]:
try:
proc = subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
return {"ok": False, "code": 124, "stdout": "", "stderr": str(exc), "args": args}
return {
"ok": proc.returncode == 0,
"code": proc.returncode,
"stdout": (proc.stdout or "").strip(),
"stderr": (proc.stderr or "").strip(),
"args": args,
}
def _redact_wg_key(value: str) -> str:
return _redact_value("PublicKey", value.strip()) if value else ""
def _wireguard_addresses() -> dict[str, list[str]]:
result = _run_command(["ip", "-j", "address", "show"], timeout=3.0)
if not result["ok"] or not result["stdout"]:
return {}
try:
payload = json.loads(result["stdout"])
except json.JSONDecodeError:
return {}
out: dict[str, list[str]] = {}
if not isinstance(payload, list):
return out
for item in payload:
if not isinstance(item, dict):
continue
ifname = str(item.get("ifname") or "")
if not ifname:
continue
addresses: list[str] = []
for addr in item.get("addr_info") or []:
if not isinstance(addr, dict):
continue
local = addr.get("local")
prefix = addr.get("prefixlen")
if local and prefix is not None:
addresses.append(f"{local}/{prefix}")
if addresses:
out[ifname] = addresses
return out
def _wireguard_link_kinds() -> dict[str, str]:
result = _run_command(["ip", "-d", "-j", "link", "show"], timeout=3.0)
if not result["ok"] or not result["stdout"]:
return {}
try:
payload = json.loads(result["stdout"])
except json.JSONDecodeError:
return {}
out: dict[str, str] = {}
if not isinstance(payload, list):
return out
for item in payload:
if not isinstance(item, dict):
continue
ifname = str(item.get("ifname") or "")
linkinfo = item.get("linkinfo") if isinstance(item.get("linkinfo"), dict) else {}
kind = str(linkinfo.get("info_kind") or "")
if ifname and kind:
out[ifname] = kind
return out
def _ip_detected_wireguard_interfaces(wg_error: str = "") -> list[dict[str, Any]]:
addresses = _wireguard_addresses()
kinds = _wireguard_link_kinds()
names = {
name
for name in addresses
if kinds.get(name) == "wireguard" or name.lower().startswith(("wg", "wireguard"))
}
out: list[dict[str, Any]] = []
for name in sorted(names):
item: dict[str, Any] = {
"name": name,
"addresses": addresses.get(name, []),
"peers": [],
"status_source": "ip",
"details_available": False,
}
if wg_error:
item["details_error"] = wg_error
out.append(item)
return out
def _parse_wg_dump(text: str) -> list[dict[str, Any]]:
addresses = _wireguard_addresses()
interfaces: dict[str, dict[str, Any]] = {}
now = int(time.time())
for raw in text.splitlines():
cols = raw.split("\t")
if len(cols) == 5:
name, private_key, public_key, listen_port, fwmark = cols
interfaces[name] = {
"name": name,
"private_key": _redact_wg_key(private_key),
"public_key": _redact_wg_key(public_key),
"listen_port": listen_port,
"fwmark": fwmark,
"addresses": addresses.get(name, []),
"peers": [],
}
elif len(cols) >= 9:
name, public_key, preshared_key, endpoint, allowed_ips, latest, rx, tx, keepalive = cols[:9]
iface = interfaces.setdefault(name, {"name": name, "addresses": addresses.get(name, []), "peers": []})
try:
latest_i = int(latest or "0")
except ValueError:
latest_i = 0
try:
rx_i = int(rx or "0")
tx_i = int(tx or "0")
except ValueError:
rx_i = tx_i = 0
endpoint_host = ""
endpoint_port: int | None = None
if endpoint and endpoint != "(none)":
try:
endpoint_host, endpoint_port = _parse_endpoint(endpoint)
except WireGuardConfigError:
endpoint_host = _endpoint_host_from_value(endpoint)
iface["peers"].append(
{
"public_key": _redact_wg_key(public_key),
"preshared_key": _redact_wg_key(preshared_key),
"endpoint": endpoint,
"endpoint_host": endpoint_host,
"endpoint_port": endpoint_port,
"allowed_ips": _split_csv(allowed_ips),
"latest_handshake": latest_i,
"latest_handshake_age_seconds": max(0, now - latest_i) if latest_i > 0 else None,
"transfer_rx_bytes": rx_i,
"transfer_tx_bytes": tx_i,
"persistent_keepalive": keepalive,
"routes_default": any(item in _DEFAULT_ROUTES for item in _split_csv(allowed_ips)),
"status_source": "wg",
}
)
return list(interfaces.values())
def _systemd_unit_state(unit: str) -> dict[str, str]:
active = _run_command(["systemctl", "is-active", unit], timeout=2.0)
enabled = _run_command(["systemctl", "is-enabled", unit], timeout=2.0)
return {
"unit": unit,
"active": active["stdout"] or ("active" if active["ok"] else "inactive"),
"enabled": enabled["stdout"] or ("enabled" if enabled["ok"] else "disabled"),
}
def _shellcrash_status() -> dict[str, Any]:
cfg = Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash")) / "configs" / "ShellCrash.cfg"
values: dict[str, str] = {}
if cfg.is_file():
try:
for raw in cfg.read_text(encoding="utf-8", errors="ignore").splitlines():
if "=" not in raw or raw.lstrip().startswith("#"):
continue
key, _, value = raw.partition("=")
values[key.strip()] = value.strip()
except OSError:
pass
unit = _systemd_unit_state("shellcrash.service") if shutil.which("systemctl") else {"active": "unknown"}
pgrep = _run_command(["pgrep", "-fa", "CrashCore|mihomo|sing-box"], timeout=2.0) if shutil.which("pgrep") else {}
return {
"installed": (Path(os.environ.get("SHELLCRASH_DIR", "/etc/ShellCrash")) / "start.sh").exists()
or unit.get("active") not in {"unknown", "inactive"},
"running": unit.get("active") == "active" or bool((pgrep.get("stdout") or "").strip()),
"unit": unit,
"mixed_port": values.get("mix_port") or "7890",
"redir_mode": values.get("redir_mod") or "",
"firewall_area": values.get("firewall_area") or "",
"dns_mode": values.get("dns_mod") or "",
"process": pgrep.get("stdout") or "",
}
def _read_stack_env(repo_root: Path) -> dict[str, str]:
env_path = repo_root / "config" / "system-stack.env"
if not env_path.is_file():
env_path = repo_root / "config" / "system-stack.env.example"
out: dict[str, str] = {}
if not env_path.is_file():
return out
try:
lines = env_path.read_text(encoding="utf-8", errors="ignore").splitlines()
except OSError:
return out
for raw in lines:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
out[key.strip()] = value.strip().strip('"').strip("'")
return out
def _upsert_stack_env_values(repo_root: Path, values: dict[str, str]) -> bool:
env_path = repo_root / "config" / "system-stack.env"
env_path.parent.mkdir(parents=True, exist_ok=True)
lines = env_path.read_text(encoding="utf-8", errors="replace").splitlines() if env_path.is_file() else []
changed = False
for key, value in values.items():
prefix = f"{key}="
next_line = f"{key}={value}"
for idx, raw in enumerate(lines):
if raw.strip().startswith(prefix):
if raw != next_line:
lines[idx] = next_line
changed = True
break
else:
if lines and lines[-1].strip():
lines.append("")
lines.append(next_line)
changed = True
if changed:
env_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
return changed
def _env_int(env: dict[str, str], key: str, default: int) -> int:
raw = str(env.get(key, "")).strip()
if not raw:
return default
try:
return int(raw)
except ValueError:
return default
def _split_host_list(*values: str | None) -> list[str]:
hosts: list[str] = []
for value in values:
if not value:
continue
for raw in re.split(r"[,;\s]+", value):
host = raw.strip()
if not host or "://" in host or "/" in host:
continue
if host not in hosts:
hosts.append(host)
return hosts
def _normalize_neko_access_mode(value: str | None) -> str:
raw = str(value or "lan").strip().lower()
if raw in {"remote", "wg", "wireguard", "wan"}:
return "remote"
return "lan"
def _interface_name_is_physical_lan(name: str) -> bool:
low = name.strip().lower()
if not low:
return False
prefixes = ("lo", "docker", "br-", "veth", "virbr", "tun", "tap", "zt", "tailscale", "wg", "wireguard", "sit", "dummy")
return not low.startswith(prefixes) and not low.startswith("p2p-dev-") and not low.startswith("mon.")
def _extract_route_token(text: str, token: str) -> str:
parts = text.split()
for idx, part in enumerate(parts):
if part == token and idx + 1 < len(parts):
return parts[idx + 1]
return ""
def _addr_for_iface(name: str) -> str:
if not name:
return ""
result = _run_command(["ip", "-4", "addr", "show", "dev", name], timeout=2.0)
if not result["ok"]:
return ""
for raw in result["stdout"].splitlines():
parts = raw.strip().split()
if len(parts) >= 2 and parts[0] == "inet":
return parts[1].split("/", 1)[0]
return ""
def _detect_preferred_lan_ip() -> str:
route = _run_command(["ip", "-4", "route", "get", "1.1.1.1"], timeout=2.0)
if route["ok"] and route["stdout"]:
iface = _extract_route_token(route["stdout"], "dev")
src = _extract_route_token(route["stdout"], "src")
if src and _interface_name_is_physical_lan(iface):
return src
default_route = _run_command(["ip", "route", "show", "default"], timeout=2.0)
if default_route["ok"] and default_route["stdout"]:
iface = _extract_route_token(default_route["stdout"].splitlines()[0], "dev")
if _interface_name_is_physical_lan(iface):
addr = _addr_for_iface(iface)
if addr:
return addr
hostname = _run_command(["hostname", "-I"], timeout=2.0)
if hostname["ok"]:
for raw in hostname["stdout"].split():
if raw.startswith(("127.", "169.254.")):
continue
try:
ip = ipaddress.ip_address(raw)
except ValueError:
continue
if isinstance(ip, ipaddress.IPv4Address):
return str(ip)
return ""
def _ip_from_interface(value: str) -> str:
try:
return str(ipaddress.ip_interface(str(value)).ip)
except ValueError:
return ""
def _wireguard_candidate_hosts(interfaces: list[dict[str, Any]]) -> list[str]:
hosts: list[str] = []
for item in interfaces:
for raw in item.get("addresses") or []:
host = _ip_from_interface(str(raw))
if not host:
continue
try:
ip = ipaddress.ip_address(host)
except ValueError:
continue
if isinstance(ip, ipaddress.IPv4Address) and not ip.is_loopback and host not in hosts:
hosts.append(host)
return hosts
def _configured_neko_wireguard_hosts(env: dict[str, str]) -> list[str]:
return _split_host_list(
env.get("NEKO_WIREGUARD_HOSTS"),
env.get("NEKO_WIREGUARD_HOST"),
env.get("NEKO_WG_HOST"),
env.get("WIREGUARD_HOST"),
)
def _neko_http_ports(env: dict[str, str]) -> list[int]:
max_count = max(2, min(64, _env_int(env, "NEKO_MAX_INSTANCE_COUNT", 64)))
count = max(2, min(max_count, _env_int(env, "NEKO_INSTANCE_COUNT", 2)))
base = _env_int(env, "NEKO_HTTP_PORT", 9200)
return [_env_int(env, f"NEKO_HTTP_PORT_{idx}", base + idx - 1) for idx in range(1, count + 1)]
def _neko_access_urls(env: dict[str, str], *, mode: str, target_host: str) -> list[dict[str, Any]]:
urls: list[dict[str, Any]] = []
if not target_host:
return urls
kind = "wireguard" if mode == "remote" else "lan"
for idx, port in enumerate(_neko_http_ports(env), start=1):
urls.append({"id": idx, "kind": kind, "host": target_host, "port": port, "url": f"http://{target_host}:{port}"})
return urls
def _neko_access_status(
repo_root: Path,
*,
interfaces: list[dict[str, Any]],
active: bool,
) -> dict[str, Any]:
env = _read_stack_env(repo_root)
mode = _normalize_neko_access_mode(env.get("NEKO_ACCESS_MODE"))
configured_hosts = _configured_neko_wireguard_hosts(env)
candidates = _wireguard_candidate_hosts(interfaces)
wireguard_host = next((host for host in configured_hosts if host), "") or next(iter(candidates), "")
lan_host = _detect_preferred_lan_ip()
target = wireguard_host if mode == "remote" else lan_host
nat1to1 = str(env.get("NEKO_WEBRTC_NAT1TO1") or "").strip()
return {
"mode": mode,
"mode_label": "remote" if mode == "remote" else "lan",
"wireguard_active": bool(active),
"remote_ready": bool(active and wireguard_host),
"nat1to1": nat1to1,
"lan_host": lan_host,
"wireguard_host": wireguard_host,
"configured_wireguard_hosts": configured_hosts,
"detected_wireguard_hosts": candidates,
"target_nat1to1": target,
"needs_reconfigure": bool(target and nat1to1 != target),
"remote_urls": _neko_access_urls(env, mode=mode, target_host=target),
}
def _reconfigure_neko_containers(repo_root: Path) -> dict[str, Any]:
service_ctl = repo_root / "scripts" / "linux" / "service_ctl.sh"
if not service_ctl.is_file():
return {"ok": False, "reason": "service_ctl_missing"}
try:
completed = subprocess.run(
["bash", str(service_ctl), "neko", "reconfigure"],
cwd=str(repo_root),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=180,
check=False,
)
except subprocess.TimeoutExpired:
return {"ok": False, "reason": "reconfigure_timeout"}
except OSError as exc:
return {"ok": False, "reason": f"reconfigure_failed: {exc}"}
output = (completed.stdout or "").strip()
return {
"ok": completed.returncode == 0,
"reason": "" if completed.returncode == 0 else f"reconfigure_exit_{completed.returncode}",
"output": "\n".join(output.splitlines()[-20:]),
}
def _wireguard_quality(
interfaces: list[dict[str, Any]],
*,
wg_error: str = "",
configured_peer_count: int | None = None,
) -> dict[str, Any]:
peers = [peer for iface in interfaces for peer in iface.get("peers", [])]
peer_count = len(peers)
if configured_peer_count is None:
configured_peer_count = _configured_wireguard_peer_count(interfaces)
details_available = any(bool(iface.get("details_available")) for iface in interfaces)
reasons: list[str] = []
fresh = [
peer
for peer in peers
if isinstance(peer.get("latest_handshake_age_seconds"), int)
and int(peer["latest_handshake_age_seconds"]) <= GOOD_HANDSHAKE_SECONDS
]
stale = [
peer
for peer in peers
if isinstance(peer.get("latest_handshake_age_seconds"), int)
and int(peer["latest_handshake_age_seconds"]) > STALE_HANDSHAKE_SECONDS
]
best_age = min(
(
int(peer["latest_handshake_age_seconds"])
for peer in peers
if isinstance(peer.get("latest_handshake_age_seconds"), int)
),
default=None,
)
transfer_rx = sum(int(peer.get("transfer_rx_bytes") or 0) for peer in peers)
transfer_tx = sum(int(peer.get("transfer_tx_bytes") or 0) for peer in peers)
routes_default = any(bool(peer.get("routes_default")) for peer in peers)
if not interfaces:
if configured_peer_count:
status = "configured"
score = 25
reasons.append("WireGuard config exists, but no active interface was detected")
else:
status = "down"
score = 0
reasons.append("No active WireGuard interface detected")
elif not details_available:
status = "detected"
score = 55 if configured_peer_count else 45
if configured_peer_count:
reasons.append("Interface is up; VPS endpoint was loaded from config")
reasons.append("Runtime peer details require root or CAP_NET_ADMIN")
if wg_error:
reasons.append(wg_error)
elif fresh:
status = "connected"
score = 92
reasons.append("Fresh peer handshake detected")
elif peer_count and best_age is not None:
status = "stale" if stale else "idle"
score = 35 if stale else 60
reasons.append("WireGuard peer handshake is not fresh")
elif peer_count:
status = "idle"
score = 40
reasons.append("WireGuard peers exist but no handshake has been recorded")
else:
status = "detected"
score = 50
reasons.append("WireGuard interface is up but no peers were reported")
if routes_default:
score = min(score, 70)
reasons.append("A peer routes default traffic; overlay mode is safer with ShellCrash/Mihomo")
if peer_count and transfer_rx == 0 and transfer_tx == 0 and details_available:
score = min(score, 55)
reasons.append("No WireGuard traffic has been observed yet")
return {
"status": status,
"score": score,
"peer_count": peer_count,
"configured_peer_count": configured_peer_count,
"fresh_peer_count": len(fresh),
"best_handshake_age_seconds": best_age,
"transfer_rx_bytes": transfer_rx,
"transfer_tx_bytes": transfer_tx,
"routes_default": routes_default,
"details_available": details_available,
"reasons": reasons,
}
def wireguard_runtime_status(*, repo_root: Path) -> dict[str, Any]:
auto_neko = ensure_neko_browser_proxy_for_network(repo_root, restart=True)
commands = {name: bool(shutil.which(name)) for name in ("wg", "wg-quick", "ip", "systemctl")}
system_configs = _system_wireguard_configs()
repo_configs = list_imported_wireguard_configs(repo_root)
dump = _run_command(["wg", "show", "all", "dump"], timeout=4.0) if commands["wg"] else {"ok": False, "stdout": ""}
wg_error = ""
if dump.get("ok"):
interfaces = _parse_wg_dump(dump.get("stdout") or "")
for item in interfaces:
item["status_source"] = "wg"
item["details_available"] = True
else:
wg_error = dump.get("stderr") or dump.get("stdout") or ""
interfaces = _ip_detected_wireguard_interfaces(wg_error) if commands["ip"] else []
_attach_configured_wireguard_peers(interfaces, system_configs=system_configs, repo_configs=repo_configs)
for item in interfaces:
if commands["systemctl"]:
item["systemd"] = _systemd_unit_state(f"wg-quick@{item['name']}.service")
configured_peer_count = _configured_wireguard_peer_count(interfaces)
if not configured_peer_count and not interfaces:
configured_peer_count = sum(int(cfg.get("peer_count") or 0) for cfg in [*system_configs, *repo_configs])
endpoint_hosts = _all_wireguard_endpoint_hosts(interfaces, system_configs=system_configs, repo_configs=repo_configs)
endpoint_routes = _endpoint_route_diagnostics(
endpoint_hosts,
{str(item.get("name") or "") for item in interfaces if item.get("name")},
)
quality = _wireguard_quality(interfaces, wg_error=wg_error, configured_peer_count=configured_peer_count)
recommendations: list[str] = []
if not interfaces:
if configured_peer_count:
names = ", ".join(str(cfg.get("name") or "wg") for cfg in [*system_configs, *repo_configs] if cfg.get("peer_count")) or "wg"
recommendations.append(f"WireGuard config exists but no interface is active; start wg-quick@{names.split(', ')[0]}")
else:
recommendations.append("No active WireGuard interface detected")
elif wg_error:
recommendations.append("WireGuard interface detected; runtime peer details require root or CAP_NET_ADMIN, so VPS config is shown as a fallback")
if any(peer.get("routes_default") for iface in interfaces for peer in iface.get("peers", [])):
recommendations.append("Active WireGuard peer routes default traffic; ShellCrash/soft-router compatibility may be affected")
if any(peer.get("routes_default") for iface in interfaces for peer in iface.get("configured_peers", [])):
recommendations.append("Configured WireGuard peer routes default traffic; overlay mode is safer with ShellCrash/Mihomo")
if any((cfg.get("health") or {}).get("missing_keepalive_peer_count") for cfg in [*system_configs, *repo_configs]):
recommendations.append("Add PersistentKeepalive=25 to VPS Endpoint peers for stable NAT traversal")
if any(route.get("uses_wireguard_interface") for route in endpoint_routes):
recommendations.append("WireGuard Endpoint route points at the WireGuard interface; add a physical gateway bypass route")
if quality["status"] in {"idle", "stale"}:
recommendations.append("Peer handshake is stale; check VPS UDP 51820 firewall, endpoint bypass route, and PersistentKeepalive=25")
neko_access = _neko_access_status(repo_root, interfaces=interfaces, active=bool(interfaces))
if neko_access["mode"] == "remote" and not neko_access["remote_ready"]:
recommendations.append("Neko remote mode is selected, but no active WireGuard address is available")
return {
"platform": {
"system": platform.system(),
"machine": platform.machine(),
"is_linux": platform.system().lower() == "linux",
},
"commands": commands,
"available": bool(commands["wg"] and commands["wg-quick"]),
"interfaces": interfaces,
"active": bool(interfaces),
"quality": quality,
"endpoint_routes": endpoint_routes,
"system_configs": system_configs,
"repo_configs": repo_configs,
"shellcrash": _shellcrash_status(),
"neko_access": neko_access,
"neko_browser_proxy": _neko_browser_proxy_status(repo_root),
"neko_browser_proxy_auto": auto_neko,
"recommendations": recommendations,
"last_checked_at": int(time.time()),
}
def configure_neko_wireguard_access(
*,
repo_root: Path,
mode: str,
restart: bool = True,
status: dict[str, Any] | None = None,
) -> dict[str, Any]:
mode = _normalize_neko_access_mode(mode)
if status is None:
status = wireguard_runtime_status(repo_root=repo_root)
interfaces = status.get("interfaces") if isinstance(status.get("interfaces"), list) else []
access = _neko_access_status(repo_root, interfaces=interfaces, active=bool(status.get("active")))
if mode == "remote":
if not access.get("remote_ready"):
raise WireGuardConfigError("WireGuard is not active or no local WireGuard address is available; cannot switch Neko to remote mode")
target = str(access.get("wireguard_host") or "").strip()
else:
target = str(access.get("lan_host") or "").strip()
if not target:
raise WireGuardConfigError("No physical LAN IP was detected; cannot switch Neko to LAN mode")
updates = {
"NEKO_ACCESS_MODE": mode,
"NEKO_WEBRTC_NAT1TO1": target,
}
if mode == "remote" and not _configured_neko_wireguard_hosts(_read_stack_env(repo_root)):
updates["NEKO_WIREGUARD_HOST"] = target
changed = _upsert_stack_env_values(repo_root, updates)
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "unchanged"}
if restart and changed:
reconfigure = _reconfigure_neko_containers(repo_root)
next_status = wireguard_runtime_status(repo_root=repo_root)
result = dict(next_status.get("neko_access") or {})
result.update(
{
"changed": changed,
"restart_requested": restart,
"reconfigured": bool(reconfigure.get("ok") and not reconfigure.get("skipped")),
"reconfigure": reconfigure,
}
)
return result
def _env_flag_enabled(env: dict[str, str], key: str, *, default: bool = False) -> bool:
raw = str(env.get(key, "1" if default else "0")).strip().lower()
return raw in {"1", "true", "yes", "on", "enable", "enabled"}
def _resolve_neko_docker_host_ip() -> str:
if platform.system().lower() != "linux" or not shutil.which("docker"):
return ""
try:
proc = subprocess.run(
[
"docker",
"inspect",
"live-neko-1",
"--format",
"{{range .NetworkSettings.Networks}}{{.Gateway}}{{end}}",
],
capture_output=True,
text=True,
timeout=4,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return ""
gw = (proc.stdout or "").strip().split()[0] if (proc.stdout or "").strip() else ""
from src.neko_docker_host import sanitize_docker_host_ip
return sanitize_docker_host_ip(gw)
def _neko_browser_proxy_status(repo_root: Path) -> dict[str, Any]:
env = _read_stack_env(repo_root)
enabled = _env_flag_enabled(env, "ENABLE_NEKO_BROWSER_PROXY", default=False)
explicit = str(env.get("NEKO_BROWSER_PROXY") or "").strip()
port = str(env.get("NEKO_SHELLCRASH_PROXY_PORT") or "7894").strip() or "7894"
node = str(env.get("SHELLCRASH_NEKO_PROXY_NODE") or "proxycheap").strip() or "proxycheap"
attach = str(env.get("SHELLCRASH_ATTACH_NEKO") or "auto").strip() or "auto"
docker_host_ip = _resolve_neko_docker_host_ip()
resolved = ""
if enabled:
if explicit and explicit.lower() not in {"0", "false", "off", "none", "direct"}:
from src.neko_docker_host import sanitize_neko_browser_proxy
resolved = sanitize_neko_browser_proxy(explicit)
if not resolved and attach.lower() not in {"0", "false", "off", "none", "direct"}:
from src.neko_docker_host import build_neko_browser_proxy_url
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
elif attach.lower() not in {"0", "false", "off", "none", "direct"}:
from src.neko_docker_host import build_neko_browser_proxy_url
resolved = build_neko_browser_proxy_url(docker_host_ip, port)
return {
"enabled": enabled,
"switch": "ENABLE_NEKO_BROWSER_PROXY",
"manual": _env_flag_enabled(env, "NEKO_BROWSER_PROXY_MANUAL", default=False),
"explicit_proxy": explicit,
"resolved_proxy": resolved,
"docker_host_ip": docker_host_ip,
"shellcrash_port": port,
"shellcrash_node": node,
"attach_mode": attach,
}
def ensure_neko_browser_proxy_for_network(repo_root: Path, *, restart: bool = True) -> dict[str, Any]:
"""Turn on Neko browser proxy when direct egress fails but ShellCrash proxy is healthy."""
from src.network_preflight import neko_browser_proxy_auto_desired, system_network_probe
env = _read_stack_env(repo_root)
if _env_flag_enabled(env, "NEKO_BROWSER_PROXY_MANUAL", default=False):
return {"applied": False, "reason": "manual"}
if _env_flag_enabled(env, "ENABLE_NEKO_BROWSER_PROXY", default=False):
return {"applied": False, "reason": "already_enabled"}
probe = system_network_probe()
if not neko_browser_proxy_auto_desired(probe):
return {"applied": False, "reason": "not_needed", "mode": probe.get("mode")}
result = configure_neko_browser_proxy(
repo_root=repo_root,
enabled=True,
restart=restart,
manual=False,
)
return {"applied": True, "reason": "direct_blocked_shellcrash_ok", "mode": probe.get("mode"), **result}
def configure_neko_browser_proxy(
*,
repo_root: Path,
enabled: bool,
restart: bool = True,
manual: bool = True,
) -> dict[str, Any]:
updates: dict[str, str] = {"ENABLE_NEKO_BROWSER_PROXY": "1" if enabled else "0"}
if manual:
updates["NEKO_BROWSER_PROXY_MANUAL"] = "1"
changed = _upsert_stack_env_values(repo_root, updates)
reconfigure: dict[str, Any] = {"ok": True, "skipped": True, "reason": "unchanged"}
if restart and changed:
reconfigure = _reconfigure_neko_containers(repo_root)
status = _neko_browser_proxy_status(repo_root)
return {
**status,
"changed": changed,
"restart_requested": restart,
"reconfigured": bool(reconfigure.get("ok") and not reconfigure.get("skipped")),
"reconfigure": reconfigure,
}
def apply_wireguard_config(
content: str,
*,
name: str | None,
repo_root: Path,
route_mode: str = "overlay",
) -> dict[str, Any]:
result = save_imported_wireguard_config(content, name=name, repo_root=repo_root, route_mode=route_mode)
safe_name = str(result["name"])
source = Path(str(result["path"]))
target = Path("/etc/wireguard") / f"{safe_name}.conf"
if platform.system().lower() != "linux":
result["applied"] = False
result["apply_error"] = "WireGuard apply is only supported on Linux"
return result
if not shutil.which("wg-quick"):
raise WireGuardConfigError("wg-quick is not installed")
if hasattr(os, "geteuid") and os.geteuid() != 0:
raise WireGuardConfigError("live-console must run as root to apply WireGuard config")
commands = [
["mkdir", "-p", "/etc/wireguard"],
["install", "-m", "600", str(source), str(target)],
]
for cmd in commands:
run = _run_command(cmd, timeout=8.0)
if not run["ok"]:
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"command failed: {' '.join(cmd)}")
unit = f"wg-quick@{safe_name}.service"
active = _run_command(["systemctl", "is-active", unit], timeout=2.0) if shutil.which("systemctl") else {"ok": False}
if shutil.which("systemctl"):
action = "restart" if active.get("ok") else "enable"
cmd = ["systemctl", action, unit] if action == "restart" else ["systemctl", "enable", "--now", unit]
run = _run_command(cmd, timeout=20.0)
if not run["ok"]:
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"command failed: {' '.join(cmd)}")
result["applied"] = True
result["system_path"] = str(target)
result["status"] = wireguard_runtime_status(repo_root=repo_root)
# Applying WG means overlay access is intended: switch Neko to remote NAT1TO1 when ready.
try:
env = _read_stack_env(repo_root)
mode = _normalize_neko_access_mode(env.get("NEKO_ACCESS_MODE") or "lan")
status = result.get("status") if isinstance(result.get("status"), dict) else None
access = (status or {}).get("neko_access") if isinstance(status, dict) else None
remote_ready = bool(isinstance(access, dict) and access.get("remote_ready"))
if mode == "remote" or remote_ready:
result["neko_access"] = configure_neko_wireguard_access(
repo_root=repo_root,
mode="remote",
restart=False,
status=status,
)
except Exception as exc: # noqa: BLE001 - WireGuard apply already succeeded
result["neko_access_error"] = str(exc)
allow_script = Path("/usr/local/sbin/shellcrash-allow-trusted.sh")
if allow_script.is_file():
_run_command(["bash", str(allow_script)], timeout=8.0)
return result