Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ The set of network addresses the daemon's HTTP/WS surface listens on. Configured
_Avoid_: host, listen address, exposed interface

**Pairing URL**:
The single `http://<bind-host>:<port>/` URL a phone types into its browser to reach the daemon. Surfaced as the `url` field on `/health` and `/diag`, and prepended above the JSON body of `deckctl status`. Prefers IPv4 over IPv6 so a phone on a typical home LAN doesn't get a `http://[::1]:.../` link it can't resolve. The password gate still has to be cleared by every non-localhost client; the pairing URL is a convenience, not a bypass.
The single `http://<bind-host>:<port>/` URL a phone types into its browser to reach the daemon. Surfaced as the `url` field on `/health` and `/diag`, and prepended above the JSON body of `deckctl status`. Prefers IPv4 over IPv6 so a phone on a typical home LAN doesn't get a `http://[::1]:.../` link it can't resolve. A wildcard bind (`0.0.0.0` or `::`) is shown as the host's LAN IPv4 — the wildcard itself is not reachable from a phone — falling back to `127.0.0.1` when no LAN address is found. The password gate still has to be cleared by every non-localhost client; the pairing URL is a convenience, not a bypass.
_Avoid_: connection URL, daemon URL

**Health issue**:
Expand Down
99 changes: 94 additions & 5 deletions daemon/deckd/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import logging
import socket
from dataclasses import dataclass
from typing import Iterable
from typing import Callable, Iterable

log = logging.getLogger("deckd.bind")

Expand Down Expand Up @@ -181,24 +181,113 @@ def _iface_addresses(name: str) -> list[tuple[str, int]]:
return results


def url_for(binds: Iterable[ResolvedBind], port: int, scheme: str = "http") -> str:
def url_for(
binds: Iterable[ResolvedBind],
port: int,
scheme: str = "http",
*,
lan_host: Callable[[], str | None] | None = None,
) -> str:
"""Build a pairing URL from the first resolved bind.

Prefers IPv4 over IPv6 because phones on the same LAN more often
have working v4 than a clean v6 path. The port is the
actually-listening port (``self.port`` after ``start()``
resolved any ``port=0`` sentinel).

A wildcard bind (``0.0.0.0`` / ``::``) is replaced with an address
the phone can actually open, because ``http://0.0.0.0:8765/`` is
not reachable from another device (issue #206). ``lan_host`` is
the discovery hook — callers leave it unset; tests inject a stub
so no real network is touched.
"""
family_priority: dict[int, int] = {socket.AF_INET: 0, socket.AF_INET6: 1}
sorted_binds = sorted(binds, key=lambda b: family_priority.get(b.family, 99))
if not sorted_binds:
return ""
host = _url_host(sorted_binds[0])
host = _url_host(sorted_binds[0], lan_host or local_lan_ipv4)
return f"{scheme}://{host}:{port}/"


def _url_host(bind: ResolvedBind) -> str:
"""Wrap an IPv6 literal in brackets for use inside a URL."""
def _url_host(bind: ResolvedBind, lan_host: Callable[[], str | None]) -> str:
"""Host part of the pairing URL, substituting wildcard binds.

IPv6 literals are wrapped in brackets so ``http://[::1]:8765/``
reads as one URL. The wildcard substitution happens first so a
``::`` bind with a reachable IPv4 gets no brackets (issue #206).
"""
if _is_wildcard(bind.host):
return lan_host() or "127.0.0.1"
if bind.is_ipv6:
return f"[{bind.host}]"
return bind.host


def local_lan_ipv4() -> str | None:
"""Best-effort IPv4 address another device on the LAN can reach.

The default-route trick asks the kernel which source address it
would use without sending a packet; hosts with no default route
fall back to the addresses the host name resolves to. Returns
``None`` when only loopback / link-local addresses exist, so the
caller can fall back to ``127.0.0.1`` (issue #206).
"""
host = _default_route_ipv4()
if host is not None:
return host
candidates = _hostname_ipv4_addresses()
return candidates[0] if candidates else None


def _default_route_ipv4() -> str | None:
"""Source address of the default route via a connected UDP socket."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# ``connect`` on UDP only selects a route; nothing is sent.
sock.connect(("8.8.8.8", 80))
host = sock.getsockname()[0]
except OSError:
return None
finally:
sock.close()
return host if _usable_lan_ipv4(host) else None


def _hostname_ipv4_addresses() -> list[str]:
"""Every usable IPv4 address the host name resolves to, in order."""
try:
infos = socket.getaddrinfo(
socket.gethostname(), None, socket.AF_INET, socket.SOCK_STREAM
)
except OSError:
return []
hosts: list[str] = []
for info in infos:
host = info[4][0]
if not isinstance(host, str):
continue
if _usable_lan_ipv4(host) and host not in hosts:
hosts.append(host)
return hosts


def _usable_lan_ipv4(host: str) -> bool:
"""True for an IPv4 address a LAN peer could connect to."""
try:
ip = ipaddress.ip_address(host)
except ValueError:
return False
return (
ip.version == 4
and not ip.is_unspecified
and not ip.is_loopback
and not ip.is_link_local
)


def _is_wildcard(host: str) -> bool:
"""True for the IPv4/IPv6 any-address (``0.0.0.0`` / ``::``)."""
try:
return ipaddress.ip_address(host).is_unspecified
except ValueError:
return False
2 changes: 1 addition & 1 deletion docs/GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,7 @@ Each spec is either a literal IPv4/IPv6 address or `iface:<name>` (every usable

The active bind surface is exposed for tooling:

- `GET /health` returns `bind`, `addresses`, and `url` (the preferred pairing URL — IPv4 wins, IPv6 only when nothing else is bound).
- `GET /health` returns `bind`, `addresses`, and `url` (the preferred pairing URL — IPv4 wins, IPv6 only when nothing else is bound; a wildcard bind is reported as the host's LAN IPv4, falling back to `127.0.0.1`).
- `GET /diag` mirrors the same fields for AI-assisted debugging.
- `deckctl status` prints the pairing URL above the JSON.

Expand Down
2 changes: 1 addition & 1 deletion docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ All are read-only and unauthenticated unless noted.

| Endpoint | Description |
|----------|-------------|
| `GET /health` | Host identity (`hostname`, `os`, `desktop`), sessions, current app, bind surface (`bind`, `addresses`, `url`). Used by `deckctl status` and the client Settings panel. |
| `GET /health` | Host identity (`hostname`, `os`, `desktop`), sessions, current app, bind surface (`bind`, `addresses`, `url`). A wildcard bind (`0.0.0.0` / `::`) is reported in `url` as the host's LAN IPv4, falling back to `127.0.0.1` (#206). Used by `deckctl status` and the client Settings panel. |
| `GET /diag` | Full snapshot: focus watcher status (`focus.healthy` = context switching is working right now; `focus.query_error` = current poll failure), input sink, deck store, active health issues (`health.issues`, the same list the client banner shows, #195), sessions, tasks, MPRIS state (if active). Machine-readable for AI-assisted debugging. |
| `GET /metrics` | Prometheus text-format scrape target. Counters: `deckd_actions_total{primitive,outcome}`, `deckd_dbus_calls*`, `deckd_deck_reloads*`, `deckd_ws_sessions_active`, `deckd_mpris_*`, etc. |
| `GET /decks` | Enumeration of every loaded deck with safe widget summaries (id, kind, label, grid, `has_action`; no raw shell/dbus/url/text command bodies). |
Expand Down
48 changes: 48 additions & 0 deletions tests/test_bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,54 @@ def test_url_for_respects_scheme() -> None:
assert url_for(binds, 443, scheme="https") == "https://127.0.0.1:443/"


def test_url_for_replaces_wildcard_with_lan_address() -> None:
"""``0.0.0.0`` is a listen address, not something a phone can
type into its browser (issue #206)."""
binds = [ResolvedBind(host="0.0.0.0", family=socket.AF_INET, original="0.0.0.0")]
assert (
url_for(binds, 8765, lan_host=lambda: "192.168.1.20")
== "http://192.168.1.20:8765/"
)


def test_url_for_ipv6_wildcard_prefers_reachable_ipv4() -> None:
"""``::`` behaves like ``0.0.0.0``: the substitution is IPv4, so
the host must not be bracketed as an IPv6 literal."""
binds = [ResolvedBind(host="::", family=socket.AF_INET6, original="::")]
assert (
url_for(binds, 8765, lan_host=lambda: "192.168.1.20")
== "http://192.168.1.20:8765/"
)


def test_url_for_wildcard_falls_back_to_loopback() -> None:
"""With no LAN address discoverable, the URL stays usable on the
host itself instead of returning the wildcard."""
binds = [ResolvedBind(host="0.0.0.0", family=socket.AF_INET, original="0.0.0.0")]
assert url_for(binds, 8765, lan_host=lambda: None) == "http://127.0.0.1:8765/"


def test_url_for_concrete_bind_skips_lan_discovery() -> None:
"""Literal and ``iface:`` binds are already reachable — discovery
must not run (or override what the operator asked for)."""

def fail() -> str | None:
raise AssertionError("LAN discovery must not run for a concrete bind")

binds = [
ResolvedBind(host="192.168.1.20", family=socket.AF_INET, original="iface:wlan0")
]
assert url_for(binds, 8765, lan_host=fail) == "http://192.168.1.20:8765/"


def test_url_for_uses_lan_discovery_by_default(monkeypatch) -> None:
"""Callers leave ``lan_host`` unset; the module-level discovery
is used and must stay monkeypatchable for the endpoint tests."""
monkeypatch.setattr("deckd.bind.local_lan_ipv4", lambda: "10.0.0.7")
binds = [ResolvedBind(host="0.0.0.0", family=socket.AF_INET, original="0.0.0.0")]
assert url_for(binds, 8765) == "http://10.0.0.7:8765/"


def test_iface_prefix_constant_matches_documented_shape() -> None:
"""The CLI / NixOS surface is documented as ``iface:<name>`` —
changing the prefix is a breaking change."""
Expand Down