Commit 55b5723a by PLN (Algolia)

devname: derive the LAN-face host name instead of hard-coding mac.local

Names answer as <name>.<lan host>.local. The host is DEVNAME_LAN_HOST,
else lan_host in DEVNAME_HOME/config.json, else the platform default:
mac on macOS (unchanged, so phones and the issued cert keep working)
and the short hostname elsewhere, the name avahi already announces.
The ssh gate host is configurable the same way (lan_gate_ssh). The
index page script and CA banner follow the derived names.
parent c8f78544
#!/usr/bin/env python3 #!/usr/bin/env python3
"""devname: stable local names for dev servers, so nobody remembers ports. """devname: stable local names for dev servers, so nobody remembers ports.
One Caddy (agent pl.nech.devname) listens on :80/:443 and proxies each name to its port. An unprivileged process can bind a low port only One Caddy (the agent: launchd pl.nech.devname on macOS, systemd user unit devname.service on Linux,
on the wildcard address (not 127.0.0.1), so every site first aborts any connection whose source is not loopback. `devname serve` under any other init) listens on :80/:443 on the wildcard address and proxies each name
`*.localhost` resolves to loopback on this Mac with no DNS setup (RFC 6761), so the names are local-program-only. to its port. macOS lets an unprivileged process bind a low port only on the wildcard; Linux needs the
unprivileged-port sysctl (which opens low ports to every user) or setcap on caddy. Either way every site
first aborts any connection whose source is not loopback: the guard, not the bind, keeps names local.
`*.localhost` resolves to loopback with no DNS setup (RFC 6761; macOS natively, Linux via systemd-resolved
or nss-myhostname), so the names are local-program-only. `devname doctor` checks every link of that chain.
Names (all end in .localhost): Names (all end in .localhost):
<project>.localhost the project's main site <project>.localhost the project's main site
...@@ -17,7 +21,8 @@ allocates a port (17000-17999), registers the name and reloads Caddy. The servic ...@@ -17,7 +21,8 @@ allocates a port (17000-17999), registers the name and reloads Caddy. The servic
devname ensure [project] [--service S] [--branch B|auto] [--port N] [--keep-host] [--format url|port|json] devname ensure [project] [--service S] [--branch B|auto] [--port N] [--keep-host] [--format url|port|json]
devname ls [--json] devname rm <host> devname check <host> devname ls [--json] devname rm <host> devname check <host>
devname gc [--idle-hours N] [--yes] list/remove stale names (down, no ok probe in N h; default dry-run) devname gc [--idle-hours N] [--yes] list/remove stale names (down, no ok probe in N h; default dry-run)
devname render devname serve devname doctor devname agent install|status devname render devname serve devname doctor
devname agent install|uninstall|status|restart [--print] (--print: show the plist/unit, change nothing)
The agent also serves the index page devname.localhost: every registered name, live up/down status, The agent also serves the index page devname.localhost: every registered name, live up/down status,
plus /json. It reads names.json per request — no snapshot to stale. plus /json. It reads names.json per request — no snapshot to stale.
...@@ -29,10 +34,13 @@ the 24 h column is the one that catches "down for an hour at 3 am". ...@@ -29,10 +34,13 @@ the 24 h column is the one that catches "down for an hour at 3 am".
LAN face (2026-11-09): the agent runs a gate thread — every 60 s `ssh domovoy-admin true`; the Pi LAN face (2026-11-09): the agent runs a gate thread — every 60 s `ssh domovoy-admin true`; the Pi
proves itself with its pinned ssh host key. While it holds, every name also answers as proves itself with its pinned ssh host key. While it holds, every name also answers as
<name>.mac.local (phones on the home wifi): https, private-range guard, announced via dns-sd, links <name>.<lan host>.local (phones on the home wifi): https, private-range guard, announced via mDNS
on the gateway page mac.local rewritten to match. Handshake fails -> no announcements, LAN blocks (dns-sd on macOS, avahi-publish on Linux), links on the gateway page <lan host>.local rewritten to
out of Caddy, loopback untouched. http://mac.local/rootCA.pem stays on plain http on purpose: a match. Handshake fails, or no mDNS announcer -> no announcements, LAN blocks out of Caddy, loopback
phone that trusts no CA yet must be able to fetch it. untouched. http://<lan host>.local/rootCA.pem stays on plain http on purpose: a phone that trusts no
CA yet must be able to fetch it. <lan host> = $DEVNAME_LAN_HOST, else "lan_host" in
$DEVNAME_HOME/config.json, else "mac" on macOS (the historic name) and the short hostname elsewhere.
The ssh gate host is "lan_gate_ssh" in the same file (default domovoy-admin).
Registry: $DEVNAME_HOME (default ~/.config/devnames)/names.json. https needs the mkcert root CA (`mkcert -install`, once). Registry: $DEVNAME_HOME (default ~/.config/devnames)/names.json. https needs the mkcert root CA (`mkcert -install`, once).
""" """
...@@ -74,16 +82,15 @@ POOL = range(17000, 18000) ...@@ -74,16 +82,15 @@ POOL = range(17000, 18000)
# no JDK keystore here: mkcert's optional Java step exits 1 and would block issuing the cert (found 2026-11-03) # no JDK keystore here: mkcert's optional Java step exits 1 and would block issuing the cert (found 2026-11-03)
MKCERT_ENV = dict(os.environ, TRUST_STORES="system,nss") MKCERT_ENV = dict(os.environ, TRUST_STORES="system,nss")
SUFFIX = ".localhost" SUFFIX = ".localhost"
# LAN face (2026-11-09): every name also answers as <name>.mac.local for phones on the home wifi, # Optional per-machine overrides (JSON object), e.g. {"lan_host": "mac", "lan_gate_ssh": "domovoy-admin"}.
CONFIG = os.path.join(CONF, "config.json")
# LAN face (2026-11-09): every name also answers as <name>.<lan host>.local for phones on the home wifi,
# but ONLY while the domovoy handshake holds. Gate = `ssh domovoy-admin true` succeeding: the Pi # but ONLY while the domovoy handshake holds. Gate = `ssh domovoy-admin true` succeeding: the Pi
# authenticates with its ssh host key (a privkey-signed answer against the pinned known_hosts entry), # authenticates with its ssh host key (a privkey-signed answer against the pinned known_hosts entry),
# so a lookalike device on a foreign LAN cannot open the door. Gate closed = no mDNS announcements, # so a lookalike device on a foreign LAN cannot open the door. Gate closed = no mDNS announcements,
# no LAN site blocks in Caddy; loopback names keep working regardless. # no LAN site blocks in Caddy; loopback names keep working regardless.
LAN_SUFFIX = ".mac.local" # LAN_HOST / GATEWAY_HOST / LAN_SUFFIX / HANDSHAKE_ARGS are derived below the platform layer.
GATEWAY_HOST = "mac.local" # the index page's LAN name; its http face serves the root CA for phones
LAN_NETS = ("127.0.0.0/8 ::1 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12 fe80::/10 fd00::/8") LAN_NETS = ("127.0.0.0/8 ::1 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12 fe80::/10 fd00::/8")
HANDSHAKE_ARGS = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "RequestTTY=no",
"domovoy-admin", "true"]
HANDSHAKE_SECS = 60 HANDSHAKE_SECS = 60
LAN_GATE = os.path.join(CONF, "lan-gate.json") # announcer state: {"open": bool, "checked": ts, "detail": str} LAN_GATE = os.path.join(CONF, "lan-gate.json") # announcer state: {"open": bool, "checked": ts, "detail": str}
INDEX_PORT = 16999 # internal: the index page behind devname.localhost, served by the agent itself INDEX_PORT = 16999 # internal: the index page behind devname.localhost, served by the agent itself
...@@ -219,6 +226,22 @@ class Platform: ...@@ -219,6 +226,22 @@ class Platform:
def log_hint(self): def log_hint(self):
return "stderr of `devname serve`" return "stderr of `devname serve`"
def own_mdns_name(self):
"""The name the OS's own mDNS responder already announces for this machine (never re-announce it)."""
return short_hostname() + ".local"
def default_lan_host(self):
return short_hostname()
def short_hostname():
"""This machine's first hostname label as a DNS-safe slug (XPS24 -> xps24); avahi announces it as <it>.local."""
raw = socket.gethostname().split(".")[0]
try:
return slug(raw)
except Err:
return "devname"
class MacPlatform(Platform): class MacPlatform(Platform):
"""launchd agent, Homebrew tools. macOS lets an unprivileged process bind :80/:443 on the wildcard """launchd agent, Homebrew tools. macOS lets an unprivileged process bind :80/:443 on the wildcard
...@@ -231,6 +254,11 @@ class MacPlatform(Platform): ...@@ -231,6 +254,11 @@ class MacPlatform(Platform):
def state_dir(self): def state_dir(self):
return os.path.join(HOME, ".local", "state", "devname") # historic path: caddy's data stays put return os.path.join(HOME, ".local", "state", "devname") # historic path: caddy's data stays put
def default_lan_host(self):
# dns-sd -P announces a proxy name independent of the Mac's own Bonjour name; "mac" is the name
# this setup has always used (phones' bookmarks, the issued SAN cert). Override via config.json.
return "mac"
def log_dir(self): def log_dir(self):
return os.path.join(HOME, "Library", "Logs", "devname") return os.path.join(HOME, "Library", "Logs", "devname")
...@@ -497,6 +525,34 @@ CADDY = PLAT.find_tool("caddy") ...@@ -497,6 +525,34 @@ CADDY = PLAT.find_tool("caddy")
MKCERT = PLAT.find_tool("mkcert") MKCERT = PLAT.find_tool("mkcert")
def load_config():
"""config.json as a dict; absent or unreadable = no overrides."""
try:
with open(CONFIG) as fh:
c = json.load(fh)
return c if isinstance(c, dict) else {}
except (OSError, ValueError):
return {}
def lan_host(config=None):
"""The LAN face's host label: names answer as <name>.<lan_host>.local, the gateway page as <lan_host>.local.
$DEVNAME_LAN_HOST > config.json "lan_host" > the platform default (macOS: "mac", the historic name;
elsewhere this machine's short hostname, which avahi-daemon already announces)."""
config = load_config() if config is None else config
raw = os.environ.get("DEVNAME_LAN_HOST") or config.get("lan_host") or PLAT.default_lan_host()
return check_name("lan_host", slug(str(raw)))
_CONFIG = load_config()
LAN_HOST = lan_host(_CONFIG)
GATEWAY_HOST = LAN_HOST + ".local" # the index page's LAN name; its http face serves the root CA for phones
LAN_SUFFIX = "." + GATEWAY_HOST
HANDSHAKE_HOST = os.environ.get("DEVNAME_LAN_GATE") or _CONFIG.get("lan_gate_ssh") or "domovoy-admin"
HANDSHAKE_ARGS = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "RequestTTY=no",
HANDSHAKE_HOST, "true"]
def caddy_bin(): def caddy_bin():
if not CADDY: if not CADDY:
raise Err("caddy not found: " + PLAT.install_hint("caddy")) raise Err("caddy not found: " + PLAT.install_hint("caddy"))
...@@ -862,7 +918,7 @@ def render_caddyfile(reg, https, lan=False): ...@@ -862,7 +918,7 @@ def render_caddyfile(reg, https, lan=False):
def site_body(up, rewrite=True, lan=False): def site_body(up, rewrite=True, lan=False):
# loopback face: abort anything not from this Mac. LAN face: abort anything not from a # loopback face: abort anything not from this machine. LAN face: abort anything not from a
# private address (loopback, RFC1918, link-local, ULA) — home-lan scoped by construction. # private address (loopback, RFC1918, link-local, ULA) — home-lan scoped by construction.
nets = LAN_NETS if lan else "127.0.0.0/8 ::1" nets = LAN_NETS if lan else "127.0.0.0/8 ::1"
guard = "@notlan" if lan else "@notlocal" guard = "@notlan" if lan else "@notlocal"
...@@ -1187,8 +1243,8 @@ function sparkFor(d) { ...@@ -1187,8 +1243,8 @@ function sparkFor(d) {
} }
function row(d) { function row(d) {
var s = d.stats || {}, has = s.n > 0; var s = d.stats || {}, has = s.n > 0;
var LAN = /(^|\.)mac\.local$$/.test(location.hostname); // LAN face: link and label become .mac.local var LAN = /(^|\.)$lan_re$$/.test(location.hostname); // LAN face: link and label become $lan_suffix
var lh = LAN ? d.host.replace(/\.localhost$$/, ".mac.local") : d.host; var lh = LAN ? d.host.replace(/\.localhost$$/, "$lan_suffix") : d.host;
var name = '<a href="' + (LAN ? "https://" : "http://") + esc(lh) + '/">' + esc(lh) + "</a>"; var name = '<a href="' + (LAN ? "https://" : "http://") + esc(lh) + '/">' + esc(lh) + "</a>";
if (d.branch) name += ' <span class="muted">⎇ ' + esc(d.branch) + "</span>"; if (d.branch) name += ' <span class="muted">⎇ ' + esc(d.branch) + "</span>";
if (d.stale) name += ' <span class="stale" title="stale: ' + (d.last_ok ? "not ok for over 72 h" : "never answered") + if (d.stale) name += ' <span class="stale" title="stale: ' + (d.last_ok ? "not ok for over 72 h" : "never answered") +
...@@ -1272,7 +1328,7 @@ def index_page(view="24h", lan=False): ...@@ -1272,7 +1328,7 @@ def index_page(view="24h", lan=False):
days = host_days() if view == "14d" else {} days = host_days() if view == "14d" else {}
def face(h): def face(h):
"""(label, href) for one name: on the LAN face both become the https .mac.local form.""" """(label, href) for one name: on the LAN face both become the https LAN_SUFFIX form."""
if h.startswith("*."): if h.startswith("*."):
return h, None # a wildcard is documentation, not a browsable URL return h, None # a wildcard is documentation, not a browsable URL
if not lan: if not lan:
...@@ -1314,11 +1370,12 @@ def index_page(view="24h", lan=False): ...@@ -1314,11 +1370,12 @@ def index_page(view="24h", lan=False):
f'<td class="num"{n_title}>{avail}</td><td class="sparkcell">{spark}</td>' f'<td class="num"{n_title}>{avail}</td><td class="sparkcell">{spark}</td>'
f'<td{err_cls}>{err5}</td><td class="num lat">{p50}</td><td class="num lat">{p95}</td>' f'<td{err_cls}>{err5}</td><td class="num lat">{p50}</td><td class="num lat">{p95}</td>'
f'<td>{html.escape(e.get("note") or "")}</td></tr>') f'<td>{html.escape(e.get("note") or "")}</td></tr>')
lan_note = ('<b style="color:#d0483e">LAN face</b> — names served as <code>.mac.local</code> · ' lan_note = (f'<b style="color:#d0483e">LAN face</b> — names served as <code>{LAN_SUFFIX}</code> · '
'phone without the CA? fetch <a href="http://mac.local/CA">http://mac.local/CA</a> · ') f'phone without the CA? fetch <a href="http://{GATEWAY_HOST}/CA">http://{GATEWAY_HOST}/CA</a> · ')
return PAGE.substitute(n_names=len(rows), n_up=sum(1 for *_, up in rows if up), return PAGE.substitute(n_names=len(rows), n_up=sum(1 for *_, up in rows if up),
rows="\n".join(trs), poll_secs=POLL_SECS, view=view, rows="\n".join(trs), poll_secs=POLL_SECS, view=view,
lan_note=lan_note if lan else "") lan_note=lan_note if lan else "",
lan_re=re.escape(GATEWAY_HOST).replace("/", r"\/"), lan_suffix=LAN_SUFFIX)
def json_records(): def json_records():
...@@ -1347,7 +1404,7 @@ class IndexHandler(http.server.BaseHTTPRequestHandler): ...@@ -1347,7 +1404,7 @@ class IndexHandler(http.server.BaseHTTPRequestHandler):
data, ctype, code = b"no mkcert root CA on this machine\n", "text/plain", 404 data, ctype, code = b"no mkcert root CA on this machine\n", "text/plain", 404
else: else:
# Caddy rewrites Host to the upstream, but X-Forwarded-Host carries the real name: # Caddy rewrites Host to the upstream, but X-Forwarded-Host carries the real name:
# reached as mac.local (or any .mac.local) = the LAN face, links must follow it. # reached as GATEWAY_HOST (or any *LAN_SUFFIX) = the LAN face, links must follow it.
xfh = (self.headers.get("X-Forwarded-Host") or "").split(":")[0] xfh = (self.headers.get("X-Forwarded-Host") or "").split(":")[0]
lan = xfh == GATEWAY_HOST or xfh.endswith(LAN_SUFFIX) lan = xfh == GATEWAY_HOST or xfh.endswith(LAN_SUFFIX)
if path == "/json": if path == "/json":
......
...@@ -14,8 +14,9 @@ from unittest import mock ...@@ -14,8 +14,9 @@ from unittest import mock
ROOT = pathlib.Path(__file__).resolve().parent.parent ROOT = pathlib.Path(__file__).resolve().parent.parent
def load_module(conf): def load_module(conf, lan_host="mac"):
os.environ["DEVNAME_HOME"] = conf os.environ["DEVNAME_HOME"] = conf
os.environ["DEVNAME_LAN_HOST"] = lan_host # pinned: the LAN-face tests below speak the historic mac.local
loader = importlib.machinery.SourceFileLoader("devname_under_test", str(ROOT / "bin" / "devname")) loader = importlib.machinery.SourceFileLoader("devname_under_test", str(ROOT / "bin" / "devname"))
spec = importlib.util.spec_from_loader("devname_under_test", loader) spec = importlib.util.spec_from_loader("devname_under_test", loader)
mod = importlib.util.module_from_spec(spec) mod = importlib.util.module_from_spec(spec)
...@@ -377,6 +378,35 @@ class DevnameTests(unittest.TestCase): ...@@ -377,6 +378,35 @@ class DevnameTests(unittest.TestCase):
self.assertIn("domovoy-admin", self.dn.HANDSHAKE_ARGS) self.assertIn("domovoy-admin", self.dn.HANDSHAKE_ARGS)
self.assertIn("BatchMode=yes", self.dn.HANDSHAKE_ARGS) # never hangs on a passphrase prompt self.assertIn("BatchMode=yes", self.dn.HANDSHAKE_ARGS) # never hangs on a passphrase prompt
def test_lan_host_env_then_config_then_platform_default(self):
with mock.patch.dict(os.environ, {"DEVNAME_LAN_HOST": ""}):
with mock.patch.object(self.dn, "PLAT", self.dn.MacPlatform()):
self.assertEqual(self.dn.lan_host({}), "mac") # the Mac keeps mac.local with no config at all
with mock.patch.object(self.dn, "PLAT", self.dn.LinuxPlatform({}, systemd=True)), \
mock.patch.object(self.dn.socket, "gethostname", return_value="XPS24.lan"):
self.assertEqual(self.dn.lan_host({}), "xps24") # Linux: the short hostname avahi already announces
self.assertEqual(self.dn.PLAT.own_mdns_name(), "xps24.local")
self.assertEqual(self.dn.lan_host({"lan_host": "Desk Box"}), "desk-box") # config wins
with mock.patch.dict(os.environ, {"DEVNAME_LAN_HOST": "studio"}):
self.assertEqual(self.dn.lan_host({"lan_host": "desk"}), "studio") # env wins over config
def test_lan_host_from_config_file_drives_every_face(self):
conf = pathlib.Path(self._tmp.name)
(conf / "config.json").write_text('{"lan_host": "xps24", "lan_gate_ssh": "pi-admin"}')
with mock.patch.dict(os.environ, {"DEVNAME_LAN_HOST": ""}):
dn = load_module(self._tmp.name, lan_host="")
self.assertEqual((dn.GATEWAY_HOST, dn.LAN_SUFFIX), ("xps24.local", ".xps24.local"))
self.assertIn("pi-admin", dn.HANDSHAKE_ARGS)
reg = {"entries": {"bench.sre.localhost": {"port": 8895, "rewrite": True}}}
text = dn.render_caddyfile(reg, True, lan=True)
self.assertIn("https://bench.sre.xps24.local {", text)
self.assertIn("http://xps24.local {", text)
self.assertNotIn("mac.local", text)
page = dn.index_page(lan=True)
self.assertIn("http://xps24.local/CA", page)
self.assertIn(r"/(^|\.)xps24\.local$/", page) # the hydration script follows the same face
self.assertNotIn("mac.local", page)
def test_lan_page_rewrites_links_and_shows_the_ca_banner(self): def test_lan_page_rewrites_links_and_shows_the_ca_banner(self):
self.run_cli("ensure", "sre", "--service", "bench", "--port", "8895") self.run_cli("ensure", "sre", "--service", "bench", "--port", "8895")
local = self.dn.index_page() local = self.dn.index_page()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment