Automatically configure LAN networking without installer prompts

This commit is contained in:
2026-10-09 22:04:17 +01:00
parent a3e4d7817a
commit de3a3c2363
8 changed files with 219 additions and 17 deletions
+81
View File
@@ -0,0 +1,81 @@
"""Find a physical RFC1918 LAN IPv4 address without contacting another server."""
import ipaddress
import json
import re
import socket
import subprocess
import sys
def private_lan(address):
try:
ip = ipaddress.IPv4Address(address)
return any(ip in network for network in (
ipaddress.IPv4Network("10.0.0.0/8"),
ipaddress.IPv4Network("172.16.0.0/12"),
ipaddress.IPv4Network("192.168.0.0/16"),
))
except ipaddress.AddressValueError:
return False
def physical(interface):
return not interface.startswith(("lo", "docker", "veth", "br-", "virbr", "tun", "tap",
"utun", "wg", "tailscale", "zt", "vpn", "bridge"))
def detect_lan(runner=subprocess.run, platform=sys.platform, route_probe=None):
def output(*command):
try:
result = runner(list(command), capture_output=True, text=True, timeout=5)
return result.stdout if result.returncode == 0 else ""
except (OSError, subprocess.TimeoutExpired):
return ""
candidates, preferred = [], []
if platform.startswith("linux"):
try:
routes = json.loads(output("ip", "-j", "-4", "route", "show", "default") or "[]")
preferred = [r["dev"] for r in sorted(routes, key=lambda r: r.get("metric", 0))
if "dev" in r and physical(r["dev"])]
interfaces = json.loads(output("ip", "-j", "-4", "address", "show", "up") or "[]")
for interface in interfaces:
name = interface.get("ifname", "")
if not physical(name):
continue
for addr in interface.get("addr_info", []):
address = addr.get("local", "")
if addr.get("scope") == "global" and private_lan(address):
candidates.append((name, address))
except (ValueError, TypeError, KeyError):
pass
elif platform == "darwin":
route = output("/sbin/route", "-n", "get", "default")
match = re.search(r"interface:\s*(\S+)", route)
if match and physical(match[1]):
preferred.append(match[1])
name, up = "", False
for line in output("/sbin/ifconfig").splitlines():
if line and not line[0].isspace():
name = line.split(":", 1)[0]
up = "UP" in line and "RUNNING" in line
match = re.search(r"\binet\s+(\d+\.\d+\.\d+\.\d+)", line)
if up and physical(name) and match and private_lan(match[1]):
candidates.append((name, match[1]))
if candidates:
return min(candidates, key=lambda pair: (
preferred.index(pair[0]) if pair[0] in preferred else len(preferred), pair[0], pair[1]))[1]
# UDP connect selects a local route but sends no packets (no DNS involved).
def probe():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(("192.168.1.1", 9))
return sock.getsockname()[0]
try:
address = (route_probe or probe)()
if private_lan(address):
return address
except OSError:
pass
raise ValueError("No LAN IPv4 address detected. Connect this computer to your LAN and rerun ./install.sh, or override with --ntfy-url and --bind-address.")
+18 -12
View File
@@ -17,12 +17,13 @@ def module(name, file):
configure = module("configure_compose", "configure-compose.py")
tokens = module("save_ntfy_token", "save-ntfy-token.py")
lan = module("lan_address", "lan-address.py")
class Setup:
def __init__(self, directory, runner=subprocess.run, prompt=input):
def __init__(self, directory, runner=subprocess.run):
self.directory = Path(directory)
self.runner, self.prompt = runner, prompt
self.runner = runner
def compose(self, *args, capture=False, check=True, **kwargs):
result = self.runner(["docker", "compose", *args], cwd=self.directory,
@@ -39,17 +40,19 @@ class Setup:
raise ValueError(".env already exists; edit it explicitly rather than replace existing configuration")
print("Keeping existing .env and credentials.")
return
url = args.ntfy_url or self.prompt("Phone-facing ntfy base URL (HTTPS or trusted LAN/VPN, no topic): ").strip()
bind = args.bind_address or self.prompt("ntfy bind IP (LAN/VPN IP for direct phone access; 127.0.0.1 for reverse proxy): ").strip()
if not bind:
raise ValueError("Choose an explicit ntfy bind address; setup will not expose it by guessing")
address = lan.detect_lan() if not args.ntfy_url else None
url = args.ntfy_url or f"http://{address}:8090"
bind = args.bind_address or address or "127.0.0.1"
timezone = args.timezone
if not timezone:
try:
timezone = configure.host_timezone()
except ValueError:
timezone = self.prompt("Timezone (e.g. Europe/London): ").strip()
timezone = "UTC"
print("Host timezone unavailable; using UTC (override with --timezone if needed).")
configure.configure(self.directory, url, bind, timezone, args.port or 8081)
print(f"LAN notifications configured: {url} (bind {bind}; authentication required).")
print("Use this address on your phone on the same trusted LAN; do not forward this HTTP port to the Internet.")
def bootstrap_ntfy(self):
token = self.directory / "secrets/ntfy-token.txt"
@@ -101,7 +104,7 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
or not status.get("ntfy", {}).get("url") or status.get("topic") != "pipelines"):
raise ValueError("Pipelines did not report healthy ntfy; check docker compose logs pipelines ntfy")
print("Verified: Pipelines reports healthy ntfy and authenticated publishing succeeded.")
print("On your phone: add the ntfy server from .env, log in as phone-reader, subscribe to pipelines.")
print(f"On your phone: add {status['ntfy']['url']}, log in as phone-reader, subscribe to pipelines.")
print("Phone delivery and model inference are not verified by this setup check.")
address = self.compose("port", "pipelines", "8080", capture=True).stdout.strip()
port = address.rsplit(":", 1)[-1]
@@ -128,9 +131,9 @@ printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$PIPELINES_NTFY_TOKEN_FI
def arguments(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ntfy-url")
parser.add_argument("--bind-address")
parser.add_argument("--timezone")
parser.add_argument("--ntfy-url", help="Override the auto-detected LAN ntfy address")
parser.add_argument("--bind-address", help="Override the detected LAN bind IP")
parser.add_argument("--timezone", help="Override the detected timezone (fallback: UTC)")
parser.add_argument("--port", type=int)
parser.add_argument("--relogin", action="store_true", help="open OpenCode provider login again without deleting accounts")
return parser.parse_args(argv)
@@ -139,5 +142,8 @@ def arguments(argv=None):
if __name__ == "__main__":
try:
Setup(Path(__file__).resolve().parents[1]).run(arguments())
except (ValueError, OSError, EOFError, json.JSONDecodeError) as error:
except KeyboardInterrupt:
print("\nSetup canceled; existing configuration, credentials and Docker volumes were retained.", file=sys.stderr)
sys.exit(130)
except (ValueError, OSError, EOFError, json.JSONDecodeError, configure.ZoneInfoNotFoundError) as error:
sys.exit(f"Docker setup incomplete: {error}")
+42
View File
@@ -0,0 +1,42 @@
import importlib.util
import json
from pathlib import Path
import subprocess
import unittest
spec = importlib.util.spec_from_file_location("lan", Path(__file__).with_name("lan-address.py"))
lan = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lan)
class LanTests(unittest.TestCase):
def test_linux_prefers_default_physical_interface_not_vpn_or_docker(self):
def run(command, **kwargs):
if "route" in command:
data = [{"dev":"tailscale0", "metric":0}, {"dev":"wlan0", "metric":100}]
else:
data = [{"ifname":name, "addr_info":[{"local":ip, "scope":"global"}]}
for name,ip in [("docker0","172.17.0.1"),("tun0","10.7.0.1"),
("eth0","10.0.0.2"),("wlan0","192.168.1.25")]]
return subprocess.CompletedProcess(command, 0, stdout=json.dumps(data))
self.assertEqual(lan.detect_lan(run, "linux"), "192.168.1.25")
def test_macos_finds_wifi_even_when_default_route_is_vpn(self):
def run(command, **kwargs):
data = "interface: utun3" if "route" in command[0] else (
"utun3: flags=UP,RUNNING\n\tinet 10.7.0.1\n"
"en0: flags=UP,RUNNING\n\tinet 192.168.1.25 netmask 0xffffff00\n")
return subprocess.CompletedProcess(command, 0, stdout=data)
self.assertEqual(lan.detect_lan(run, "darwin"), "192.168.1.25")
def test_no_tools_uses_local_route_selection_without_remote_request(self):
def missing(*args, **kwargs):
raise FileNotFoundError()
self.assertEqual(lan.detect_lan(missing, "linux", lambda: "192.168.1.25"), "192.168.1.25")
for ip in ["127.0.0.1","100.85.25.33","169.254.1.2","8.8.8.8"]:
with self.assertRaises(ValueError):
lan.detect_lan(missing, "linux", lambda: ip)
if __name__ == "__main__":
unittest.main()
+61 -1
View File
@@ -1,8 +1,14 @@
import importlib.util
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location("setup", Path(__file__).with_name("setup-docker.py"))
setup = importlib.util.module_from_spec(spec)
@@ -10,6 +16,60 @@ spec.loader.exec_module(setup)
class DockerSetupTests(unittest.TestCase):
def test_ctrl_c_exits_cleanly_and_retains_configuration(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);scripts=root/"scripts";scripts.mkdir()
for name in ["setup-docker.py","lan-address.py","configure-compose.py","save-ntfy-token.py"]:
shutil.copy2(Path(__file__).with_name(name),scripts/name)
marker=root/"waiting"
docker=root/"docker"
docker.write_text('#!/bin/sh\ncase "$*" in *" up "*) touch "'+str(marker)+'"; exec sleep 30;; esac\n')
docker.chmod(0o700)
process=subprocess.Popen([sys.executable,str(scripts/"setup-docker.py"),
"--ntfy-url","http://192.168.1.25:8090","--bind-address","192.168.1.25","--timezone","UTC"],
env=dict(os.environ,PATH=str(root)+os.pathsep+os.environ["PATH"]),
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,start_new_session=True)
try:
deadline=time.monotonic()+5
while not marker.exists() and process.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
self.assertTrue(marker.exists(),"installer did not reach Docker startup")
os.killpg(process.pid,signal.SIGINT)
stdout,stderr=process.communicate(timeout=5)
self.assertEqual(process.returncode,130)
self.assertNotIn("Traceback",stdout+stderr)
self.assertIn("Setup canceled",stderr)
self.assertTrue((root/".env").exists())
finally:
if process.poll() is None:
os.killpg(process.pid,signal.SIGTERM)
process.communicate(timeout=5)
def test_fresh_defaults_configure_lan_without_any_input(self):
with tempfile.TemporaryDirectory() as directory, \
patch.object(setup.lan,"detect_lan",return_value="192.168.1.25"), \
patch.object(setup.configure,"host_timezone",return_value="Europe/London"), \
patch("builtins.input",side_effect=AssertionError("must not ask for network settings")):
setup.Setup(directory).settings(setup.arguments([]))
text=Path(directory,".env").read_text()
self.assertIn("NTFY_BASE_URL=http://192.168.1.25:8090\n",text)
self.assertIn("NTFY_BIND_ADDRESS=192.168.1.25\n",text)
self.assertIn("TZ=Europe/London\n",text)
def test_timezone_fallback_does_not_prompt(self):
with tempfile.TemporaryDirectory() as directory, \
patch.object(setup.lan,"detect_lan",return_value="192.168.1.25"), \
patch.object(setup.configure,"host_timezone",side_effect=ValueError("unknown")):
setup.Setup(directory).settings(setup.arguments([]))
self.assertIn("TZ=UTC\n",Path(directory,".env").read_text())
def test_missing_lan_fails_without_partial_settings_or_prompt(self):
with tempfile.TemporaryDirectory() as directory, \
patch.object(setup.lan,"detect_lan",side_effect=ValueError("No LAN")):
with self.assertRaises(ValueError):
setup.Setup(directory).settings(setup.arguments([]))
self.assertFalse(Path(directory,".env").exists())
def exercise(self, directory, existing=False, fail=None, confirm="yes"):
calls = []
token = "tk_" + "a" * 29
@@ -36,7 +96,7 @@ class DockerSetupTests(unittest.TestCase):
args = setup.arguments([] if existing else ["--ntfy-url", "http://192.168.1.20:8090",
"--bind-address", "192.168.1.20", "--timezone", "Europe/London"])
installer = setup.Setup(directory, runner=runner, prompt=lambda _: confirm)
installer = setup.Setup(directory, runner=runner)
installer.run(args)
return calls, token