Listen on loopback and tailnet by default; make the plain-HTTP LAN opt-in
The web proxy binds the wildcard and drops connections that are not loopback or Tailscale at both ends. A LAN listener is opt-in (web.lan) and refuses sign-in and signed-in pages over plain HTTP unless web.lan_plain_login is set. Existing installs keep their bind address with a warning. Without the LAN the mDNS advert carries only the tailnet and public routes (lan=0).
This commit is contained in:
@@ -380,9 +380,10 @@ def print_web_urls(manifest, lan_host=None):
|
||||
if not web.get("port"):
|
||||
return
|
||||
host = web.get("host", "0.0.0.0")
|
||||
local = "localhost" if host in ("0.0.0.0", "127.0.0.1") else host
|
||||
local = "localhost" if host in ("0.0.0.0", "127.0.0.1", "tailnet") else host
|
||||
urls = [f"http://{local}:{web['port']}/"]
|
||||
if host == "0.0.0.0":
|
||||
# The LAN URL only where a LAN browser can sign in (see web_access.py).
|
||||
if host == "0.0.0.0" or (host == "tailnet" and web.get("lan") is True and web.get("lan_plain_login") is True):
|
||||
lan_host = lan_host or urlsplit(manifest.get("public_url", "")).hostname
|
||||
if lan_host and lan_host not in ("localhost", "127.0.0.1", "0.0.0.0"):
|
||||
urls.append(f"http://{lan_host}:{web['port']}/")
|
||||
|
||||
+18
-4
@@ -46,10 +46,24 @@ def mdns_args(config):
|
||||
"""
|
||||
web = config.get("web") or {}
|
||||
if web.get("port") and web.get("host") not in (None, "", "127.0.0.1", "localhost", "::1"):
|
||||
return ["-mdns-port", str(web["port"])]
|
||||
# Loopback + tailnet: the advert carries only the tailnet/public routes.
|
||||
lan = web.get("host") != "tailnet" or web.get("lan") is True
|
||||
return ["-mdns-port", str(web["port"])] + ([] if lan else ["-mdns-lan=false"])
|
||||
return []
|
||||
|
||||
|
||||
def web_listen_args(web):
|
||||
"""The proxy's bind and access flags. "tailnet" (the installer default)
|
||||
binds the wildcard and admits only loopback and tailnet connections, plus
|
||||
the LAN when web.lan is set; sign-in over plain-HTTP LAN additionally needs
|
||||
web.lan_plain_login. A literal address is bound as before, unfiltered."""
|
||||
if web.get("host") != "tailnet":
|
||||
return ["--host", web["host"]]
|
||||
lan = web.get("lan") is True
|
||||
return (["--host", "::", "--allow", "loopback,tailnet" + (",lan" if lan else "")]
|
||||
+ (["--lan-plain-login"] if lan and web.get("lan_plain_login") is True else []))
|
||||
|
||||
|
||||
def load(prefix):
|
||||
prefix = Path(prefix).expanduser().resolve()
|
||||
path = prefix / MARKER
|
||||
@@ -218,7 +232,7 @@ def start(config):
|
||||
wait_health(f"http://127.0.0.1:{config['server_port']}/healthz", timeout=75)
|
||||
if config.get("web"):
|
||||
web = config["web"]
|
||||
host = "127.0.0.1" if web["host"] == "0.0.0.0" else web["host"]
|
||||
host = "127.0.0.1" if web["host"] in ("0.0.0.0", "tailnet") else web["host"]
|
||||
end = time.monotonic() + 20
|
||||
while True:
|
||||
try:
|
||||
@@ -319,7 +333,7 @@ def report(config):
|
||||
if web:
|
||||
public = (config.get("opencode_env") or {}).get("PIPELINES_WEB_PUBLIC_URL")
|
||||
print("== Access")
|
||||
address = public or f"http://{web['host']}:{web['port']}"
|
||||
address = public or f"http://{'127.0.0.1' if web['host'] == 'tailnet' else web['host']}:{web['port']}"
|
||||
print(f" {'Web':<10} {address} (password in {web['auth_file']})")
|
||||
root = Path(web["root"]) if web.get("root") else None
|
||||
built = root is not None and (root / "index.html").is_file()
|
||||
@@ -431,7 +445,7 @@ def supervise(config):
|
||||
with (root / "logs/web.log").open("a") as web_log:
|
||||
web_child = subprocess.Popen(
|
||||
[web["node"], web["script"], "--port", str(web["port"]),
|
||||
"--host", web["host"], "--pipelines", f"127.0.0.1:{config['server_port']}",
|
||||
*web_listen_args(web), "--pipelines", f"127.0.0.1:{config['server_port']}",
|
||||
*(["--root", web["root"]] if web.get("root") else []),
|
||||
*(["--updates", web["updates"]] if web.get("updates") else [])],
|
||||
env=web_env, stdout=web_log, stderr=web_log)
|
||||
|
||||
+28
-8
@@ -44,6 +44,7 @@ lan = module("lan_address", "lan-address.py")
|
||||
release_lookup = module("resolve_releases", "resolve-releases.py")
|
||||
tokens = module("save_ntfy_token", "save-ntfy-token.py")
|
||||
app_build = module("app_build", "app_build.py")
|
||||
web_access = module("web_access", "web_access.py")
|
||||
|
||||
DEFAULT_PREFIX = Path.home() / ".local/share/pipelines"
|
||||
MARKER = "pipelines-install.json"
|
||||
@@ -310,10 +311,12 @@ class Setup:
|
||||
saved = {"port": existing.get("server_port"),
|
||||
"ntfy_port": existing.get("ntfy_port"),
|
||||
"bind_address": existing.get("bind_address"),
|
||||
"web_port": web.get("port"), "web_host": web.get("host")}
|
||||
"web_port": web.get("port"), "web_host": web.get("host"),
|
||||
"web_lan": web.get("lan"), "web_lan_plain_login": web.get("lan_plain_login")}
|
||||
supplied = {argument.split("=", 1)[0] for argument in args.argv}
|
||||
for name, value in saved.items():
|
||||
if value is not None and "--" + name.replace("_", "-") not in supplied:
|
||||
flag = name.replace("_", "-")
|
||||
if value is not None and not {"--" + flag, "--no-" + flag} & supplied:
|
||||
setattr(args, name, value)
|
||||
|
||||
# --- prefix layout ---------------------------------------------------
|
||||
@@ -366,6 +369,7 @@ class Setup:
|
||||
updates.mkdir(parents=True, exist_ok=True)
|
||||
return {"node": node, "script": str(target / "serve.mjs"),
|
||||
"auth_file": str(auth), "host": args.web_host, "port": args.web_port,
|
||||
"lan": args.web_lan, "lan_plain_login": args.web_lan_plain_login,
|
||||
"root": self.install_app_web(prefix, args, web_build), "updates": str(updates)}
|
||||
|
||||
def choose_password(self):
|
||||
@@ -805,9 +809,11 @@ class Setup:
|
||||
raise ValueError("Web port must be between 1024 and 65535 and differ from server/ntfy ports")
|
||||
try:
|
||||
ipaddress.IPv4Address(args.bind_address)
|
||||
ipaddress.IPv4Address(args.web_host)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid API/web bind address; use an IPv4 address such as 0.0.0.0 or 127.0.0.1") from None
|
||||
raise ValueError("Invalid API bind address; use an IPv4 address such as 127.0.0.1") from None
|
||||
listen, web_warnings = web_access.resolve(args.web_host, args.web_lan, args.web_lan_plain_login,
|
||||
{argument.split("=", 1)[0] for argument in args.argv})
|
||||
args.web_host, args.web_lan, args.web_lan_plain_login = listen["host"], listen["lan"], listen["lan_plain_login"]
|
||||
allow_authoring = self.authoring_role(prefix, args.allow_authoring)
|
||||
web_public_url = self.environ.get("PIPELINES_WEB_PUBLIC_URL", "")
|
||||
previous = prefix / MARKER
|
||||
@@ -869,7 +875,8 @@ class Setup:
|
||||
if self.environ.get(key):
|
||||
opencode_env[key] = self.environ[key]
|
||||
opencode_env["PIPELINES_DEFAULT_MODEL"] = args.model or pipeline_model
|
||||
opencode_env["PIPELINES_WEB_PUBLIC_URL"] = web_public_url or f"http://{lan_ip if args.web_host == '0.0.0.0' else args.web_host}:{args.web_port}"
|
||||
web_url = f"http://{web_access.default_url_host(web, lan_ip, web_access.tailnet_ipv4(self.runner))}:{args.web_port}"
|
||||
opencode_env["PIPELINES_WEB_PUBLIC_URL"] = web_public_url or web_url
|
||||
path_value = str(prefix / "bin") + os.pathsep + self.environ.get("PATH", "")
|
||||
manifest = {
|
||||
"format": 1,
|
||||
@@ -926,8 +933,13 @@ class Setup:
|
||||
self.serve_on_tailnet(opencode_env["PIPELINES_WEB_PUBLIC_URL"], args.web_port)
|
||||
print(f"ntfy is configured for {base_url}; server, web proxy and ntfy have login autostart ({service_path}).")
|
||||
print("Phone notifications: subscribe to the 'pipelines' topic as phone-reader with the web password.")
|
||||
print(f"Web: http://{lan_ip if args.web_host == '0.0.0.0' else args.web_host}:{args.web_port}/ "
|
||||
f"(sign-in password in {web['auth_file']}; existing credentials retained).")
|
||||
print(f"Web: {web_url}/ (sign-in password in {web['auth_file']}; existing credentials retained).")
|
||||
print("Web proxy access: " + ("loopback + tailnet" + (" + LAN" if args.web_lan else "")
|
||||
if args.web_host == web_access.TAILNET else f"bound to {args.web_host}"))
|
||||
for note in (*web_warnings, web_access.public_url_warning(opencode_env["PIPELINES_WEB_PUBLIC_URL"], web),
|
||||
web_access.firewall_note(self.runner)):
|
||||
if note:
|
||||
print(note)
|
||||
print("Login autostart is already enabled. To enable/start it again, run:\n "
|
||||
+ shlex.join([str(prefix / "bin/pipelines"), "service", "enable"]))
|
||||
print("Android app (optional, slower): ./install --apk builds it in Docker and offers it at "
|
||||
@@ -951,7 +963,15 @@ def arguments(argv=None):
|
||||
parser.add_argument("--timezone", help="Override the detected timezone (fallback: UTC)")
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_SERVER_PORT, help="Pipelines server port")
|
||||
parser.add_argument("--web-port", type=int, default=8082, help="Authenticated web proxy port (default 8082)")
|
||||
parser.add_argument("--web-host", default="0.0.0.0", help="Web proxy bind address (default 0.0.0.0)")
|
||||
parser.add_argument("--web-host", help="Web proxy access: 'tailnet' (default for new installs: loopback and "
|
||||
"this machine's Tailscale addresses only) or an IPv4 bind address such as 0.0.0.0 "
|
||||
"(plain HTTP on every interface); reinstalls keep the saved value")
|
||||
parser.add_argument("--web-lan", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="Also accept plain-HTTP connections from the LAN (with --web-host tailnet); "
|
||||
"sign-in over them still needs --web-lan-plain-login")
|
||||
parser.add_argument("--web-lan-plain-login", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="Allow the password and signed-in pages over plain-HTTP LAN connections "
|
||||
"(unencrypted; only on a trusted network)")
|
||||
parser.add_argument("--bind-address", default=DEFAULT_BIND_ADDRESS,
|
||||
help="Unauthenticated server bind address (default 127.0.0.1; expose only the web proxy)")
|
||||
parser.add_argument("--ntfy-port", type=int, default=DEFAULT_NTFY_PORT, help="ntfy listen port")
|
||||
|
||||
@@ -445,7 +445,11 @@ class SetupNativeTests(unittest.TestCase):
|
||||
self.assertEqual(config["opencode"], "/usr/bin/opencode")
|
||||
self.assertEqual(config["pi"], "")
|
||||
self.assertEqual(config["opencode_env"]["PIPELINES_DEFAULT_MODEL"], "fixture/host-default")
|
||||
self.assertEqual(config["opencode_env"]["PIPELINES_WEB_PUBLIC_URL"], "http://192.168.1.20:8082")
|
||||
# A fresh install's proxy admits loopback and tailnet only, so the
|
||||
# default web URL is not the LAN address.
|
||||
self.assertEqual(config["opencode_env"]["PIPELINES_WEB_PUBLIC_URL"], "http://127.0.0.1:8082")
|
||||
self.assertEqual((config["web"]["host"], config["web"]["lan"], config["web"]["lan_plain_login"]),
|
||||
("tailnet", False, False))
|
||||
host = json.loads(installer.harness_config_path().read_text())["profiles"]["opencode"]
|
||||
self.assertEqual(host["model"], "fixture/host-default")
|
||||
self.assertEqual(host["pipeline_model"], "fixture/host-default")
|
||||
@@ -491,11 +495,51 @@ class SetupNativeTests(unittest.TestCase):
|
||||
self.assertEqual((prefix / "secrets/publisher-token").read_text(), before)
|
||||
self.assertEqual(manage.load(prefix)["web"]["port"], 8096)
|
||||
self.assertEqual(output.getvalue().splitlines()[-4:], [
|
||||
" http://localhost:8096/", " http://192.168.1.20:8096/",
|
||||
" http://localhost:8096/", " http://127.0.0.1:8096/",
|
||||
"OpenCode is required (default stage and chat harness) and is set up by ./install.",
|
||||
"Next: set up your agent harnesses: pipelines harness setup claude|codex|opencode|pi"])
|
||||
self.assertFalse(any("token" in call for call in recorder.calls), "reinstall re-created the token")
|
||||
|
||||
def test_upgrade_keeps_an_all_interfaces_web_host_with_a_warning_and_lan_is_opt_in(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
installer = self.installer(directory, Recorder())
|
||||
prefix = Path(directory) / "prefix"
|
||||
|
||||
def install(argv):
|
||||
with redirect_stdout(io.StringIO()) as output:
|
||||
installer.run(setup_native.arguments(argv))
|
||||
return manage.load(prefix)["web"], output.getvalue()
|
||||
|
||||
with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \
|
||||
patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \
|
||||
patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"):
|
||||
# An install from before: the proxy on every interface.
|
||||
install(["--web-host", "0.0.0.0"])
|
||||
web, text = install([])
|
||||
self.assertEqual(web["host"], "0.0.0.0")
|
||||
self.assertIn("WARNING: the web proxy listens on 0.0.0.0 over plain HTTP", text)
|
||||
self.assertIn("./install --web-host tailnet", text)
|
||||
self.assertIn(" http://192.168.1.20:8082/", text)
|
||||
# Opting into the LAN listener selects the new model; sign-in
|
||||
# over the plain-HTTP LAN stays off until asked for.
|
||||
web, text = install(["--web-lan"])
|
||||
self.assertEqual((web["host"], web["lan"], web["lan_plain_login"]), ("tailnet", True, False))
|
||||
self.assertNotIn("WARNING: the web proxy listens", text)
|
||||
self.assertIn("Web proxy access: loopback + tailnet + LAN", text)
|
||||
# The URL recorded by the old install is kept, and flagged.
|
||||
self.assertIn("WARNING: the recorded web URL http://192.168.1.20:8082 is a plain-HTTP LAN", text)
|
||||
web, text = install(["--web-lan-plain-login"])
|
||||
self.assertEqual((web["host"], web["lan"], web["lan_plain_login"]), ("tailnet", True, True))
|
||||
self.assertIn("WARNING: web.lan_plain_login is on", text)
|
||||
web, _ = install(["--no-web-lan"])
|
||||
self.assertEqual((web["host"], web["lan"], web["lan_plain_login"]), ("tailnet", False, False))
|
||||
web, _ = install([])
|
||||
self.assertEqual((web["host"], web["lan"]), ("tailnet", False))
|
||||
with self.assertRaisesRegex(ValueError, "--web-lan applies to --web-host tailnet"):
|
||||
installer.run(setup_native.arguments(["--web-host", "0.0.0.0", "--web-lan"]))
|
||||
with self.assertRaisesRegex(ValueError, "Invalid --web-host"):
|
||||
installer.run(setup_native.arguments(["--web-host", "everywhere"]))
|
||||
|
||||
def test_ntfy_is_built_from_the_pinned_module(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
recorder = Recorder()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location("web_access", Path(__file__).with_name("web_access.py"))
|
||||
web_access = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(web_access)
|
||||
manage_spec = importlib.util.spec_from_file_location("manage_web", Path(__file__).with_name("manage.py"))
|
||||
manage = importlib.util.module_from_spec(manage_spec)
|
||||
manage_spec.loader.exec_module(manage)
|
||||
|
||||
|
||||
def reply(stdout="", code=0):
|
||||
return subprocess.CompletedProcess([], code, stdout=stdout, stderr="")
|
||||
|
||||
|
||||
class ResolveTests(unittest.TestCase):
|
||||
def test_fresh_install_defaults_to_loopback_and_tailnet(self):
|
||||
self.assertEqual(web_access.resolve(None, None, None, set()),
|
||||
({"host": "tailnet", "lan": False, "lan_plain_login": False}, []))
|
||||
|
||||
def test_an_existing_all_interfaces_host_is_kept_with_a_warning(self):
|
||||
listen, warnings = web_access.resolve("0.0.0.0", None, None, set())
|
||||
self.assertEqual(listen["host"], "0.0.0.0")
|
||||
self.assertEqual(len(warnings), 1)
|
||||
self.assertIn("cross it unencrypted", warnings[0])
|
||||
self.assertIn("--web-host tailnet", warnings[0])
|
||||
self.assertEqual(web_access.resolve("127.0.0.1", None, None, set())[1], [])
|
||||
|
||||
def test_lan_is_opt_in_and_plain_login_needs_lan(self):
|
||||
listen, warnings = web_access.resolve("0.0.0.0", True, None, {"--web-lan"})
|
||||
self.assertEqual(listen, {"host": "tailnet", "lan": True, "lan_plain_login": False})
|
||||
self.assertEqual(warnings, [])
|
||||
listen, warnings = web_access.resolve("tailnet", True, True, set())
|
||||
self.assertTrue(listen["lan_plain_login"])
|
||||
self.assertIn("lan_plain_login is on", warnings[0])
|
||||
self.assertFalse(web_access.resolve("tailnet", False, True, set())[0]["lan_plain_login"])
|
||||
with self.assertRaisesRegex(ValueError, "applies to --web-host tailnet"):
|
||||
web_access.resolve("0.0.0.0", True, None, {"--web-host", "--web-lan"})
|
||||
with self.assertRaisesRegex(ValueError, "Invalid --web-host"):
|
||||
web_access.resolve("0.0.0.0\nX=1", None, None, {"--web-host"})
|
||||
|
||||
def test_urls_follow_where_a_browser_can_sign_in(self):
|
||||
tailnet = {"host": "tailnet", "lan": False}
|
||||
self.assertEqual(web_access.default_url_host(tailnet, "192.168.1.20", "100.85.25.33"), "100.85.25.33")
|
||||
self.assertEqual(web_access.default_url_host(tailnet, "192.168.1.20", None), "127.0.0.1")
|
||||
self.assertEqual(web_access.default_url_host({"host": "tailnet", "lan": True, "lan_plain_login": True},
|
||||
"192.168.1.20", None), "192.168.1.20")
|
||||
self.assertEqual(web_access.default_url_host({"host": "0.0.0.0"}, "192.168.1.20", None), "192.168.1.20")
|
||||
self.assertIsNotNone(web_access.public_url_warning("http://192.168.1.20:8083", tailnet))
|
||||
for url in ("https://box.tail1.ts.net:8443", "http://100.85.25.33:8083", "http://127.0.0.1:8083", ""):
|
||||
self.assertIsNone(web_access.public_url_warning(url, tailnet), url)
|
||||
self.assertIsNone(web_access.public_url_warning("http://192.168.1.20:8083", {"host": "0.0.0.0"}))
|
||||
|
||||
def test_tailnet_address_and_firewall_are_read_only_probes(self):
|
||||
calls = []
|
||||
|
||||
def runner(command, **_):
|
||||
calls.append(command)
|
||||
return reply("100.85.25.33\n") if command[-1] == "-4" else reply("Firewall is disabled. (State = 0)\n")
|
||||
|
||||
with patch.object(web_access.shutil, "which", return_value="/usr/bin/tailscale"):
|
||||
self.assertEqual(web_access.tailnet_ipv4(runner), "100.85.25.33")
|
||||
self.assertIsNone(web_access.tailnet_ipv4(lambda *a, **k: reply("10.0.0.5\n")))
|
||||
self.assertIsNone(web_access.tailnet_ipv4(lambda *a, **k: reply("", 1)))
|
||||
with patch.object(web_access.shutil, "which", return_value=None):
|
||||
self.assertIsNone(web_access.tailnet_ipv4(runner))
|
||||
with patch.object(web_access.platform, "system", return_value="Darwin"), \
|
||||
patch.object(web_access, "FIREWALL", Path(__file__)):
|
||||
self.assertIn("firewall is off", web_access.firewall_note(runner))
|
||||
self.assertIsNone(web_access.firewall_note(lambda *a, **k: reply("Firewall is enabled. (State = 1)\n")))
|
||||
self.assertEqual(calls[-1], [__file__, "--getglobalstate"])
|
||||
|
||||
|
||||
class ManageWebTests(unittest.TestCase):
|
||||
def test_proxy_flags_follow_the_manifest(self):
|
||||
self.assertEqual(manage.web_listen_args({"host": "0.0.0.0"}), ["--host", "0.0.0.0"])
|
||||
self.assertEqual(manage.web_listen_args({"host": "tailnet"}),
|
||||
["--host", "::", "--allow", "loopback,tailnet"])
|
||||
self.assertEqual(manage.web_listen_args({"host": "tailnet", "lan": True}),
|
||||
["--host", "::", "--allow", "loopback,tailnet,lan"])
|
||||
self.assertEqual(manage.web_listen_args({"host": "tailnet", "lan": True, "lan_plain_login": True}),
|
||||
["--host", "::", "--allow", "loopback,tailnet,lan", "--lan-plain-login"])
|
||||
self.assertEqual(manage.web_listen_args({"host": "tailnet", "lan_plain_login": True}),
|
||||
["--host", "::", "--allow", "loopback,tailnet"])
|
||||
|
||||
def test_mdns_omits_the_lan_route_when_the_proxy_refuses_the_lan(self):
|
||||
port = {"port": 8083}
|
||||
self.assertEqual(manage.mdns_args({"web": {**port, "host": "tailnet"}}), ["-mdns-port", "8083", "-mdns-lan=false"])
|
||||
self.assertEqual(manage.mdns_args({"web": {**port, "host": "tailnet", "lan": True}}), ["-mdns-port", "8083"])
|
||||
self.assertEqual(manage.mdns_args({"web": {**port, "host": "0.0.0.0"}}), ["-mdns-port", "8083"])
|
||||
self.assertEqual(manage.mdns_args({"web": {**port, "host": "127.0.0.1"}}), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Where the authenticated web proxy listens, as the native installer decides it.
|
||||
|
||||
`web.host` in the installation manifest is either "tailnet" (the default for
|
||||
new installs: the proxy admits only loopback and this machine's Tailscale
|
||||
addresses, see web/src/listenPolicy.js) or a literal IPv4 bind address (the
|
||||
behaviour before; existing installs keep it, with a warning when it reaches
|
||||
beyond loopback). A plain-HTTP LAN listener is opt-in with `web.lan`, and
|
||||
signing in over it additionally needs `web.lan_plain_login`.
|
||||
"""
|
||||
import ipaddress
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
TAILNET = "tailnet"
|
||||
FIREWALL = Path("/usr/libexec/ApplicationFirewall/socketfilterfw")
|
||||
|
||||
|
||||
def resolve(host, lan, lan_plain_login, supplied):
|
||||
"""The web settings for this install and the warnings to print.
|
||||
|
||||
host/lan/lan_plain_login are the parsed flags after the saved settings were
|
||||
applied (None when neither gave a value); supplied is the set of flag names
|
||||
on the command line."""
|
||||
if lan and "--web-lan" in supplied and "--web-host" not in supplied:
|
||||
host = TAILNET # opting into the LAN listener selects the new model
|
||||
host = host or TAILNET
|
||||
if host != TAILNET:
|
||||
try:
|
||||
ipaddress.IPv4Address(host)
|
||||
except ValueError:
|
||||
raise ValueError("Invalid --web-host; use 'tailnet' (loopback + Tailscale) "
|
||||
"or an IPv4 address such as 127.0.0.1") from None
|
||||
if lan and "--web-lan" in supplied:
|
||||
raise ValueError("--web-lan applies to --web-host tailnet; a literal --web-host binds that address only")
|
||||
lan = bool(lan) and host == TAILNET
|
||||
plain = bool(lan_plain_login) and lan
|
||||
warnings = []
|
||||
if host != TAILNET and not ipaddress.IPv4Address(host).is_loopback:
|
||||
warnings.append(
|
||||
f"WARNING: the web proxy listens on {host} over plain HTTP, so on an untrusted network "
|
||||
"(cafe or hotel Wi-Fi) the web password and the 30-day session cookie cross it unencrypted. "
|
||||
"Recommended: ./install --web-host tailnet (loopback and Tailscale only; add --web-lan "
|
||||
"for a trusted LAN).")
|
||||
if plain:
|
||||
warnings.append(
|
||||
"WARNING: web.lan_plain_login is on: the web password and session cookie are accepted over "
|
||||
"plain HTTP on the LAN. Use it only on a network you trust; prefer the tailnet HTTPS address.")
|
||||
return {"host": host, "lan": lan, "lan_plain_login": plain}, warnings
|
||||
|
||||
|
||||
def lan_sign_in(web):
|
||||
"""Whether a browser on the LAN can sign in over plain HTTP."""
|
||||
if web.get("host") == TAILNET:
|
||||
return web.get("lan") is True and web.get("lan_plain_login") is True
|
||||
return not ipaddress.IPv4Address(web["host"]).is_loopback
|
||||
|
||||
|
||||
def tailnet_ipv4(runner=subprocess.run):
|
||||
"""This machine's Tailscale IPv4 address, or None."""
|
||||
tailscale = shutil.which("tailscale")
|
||||
if not tailscale:
|
||||
return None
|
||||
try:
|
||||
result = runner([tailscale, "ip", "-4"], capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
if result.returncode:
|
||||
return None
|
||||
for line in (result.stdout or "").split():
|
||||
try:
|
||||
if ipaddress.IPv4Address(line) in ipaddress.IPv4Network("100.64.0.0/10"):
|
||||
return line
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def default_url_host(web, lan_ip, tailnet_ip):
|
||||
"""The host of the default web URL when PIPELINES_WEB_PUBLIC_URL is unset."""
|
||||
if web["host"] == TAILNET:
|
||||
return lan_ip if lan_sign_in(web) else (tailnet_ip or "127.0.0.1")
|
||||
return lan_ip if web["host"] == "0.0.0.0" else web["host"]
|
||||
|
||||
|
||||
def public_url_warning(url, web):
|
||||
"""A recorded plain-HTTP LAN web URL that the proxy now refuses."""
|
||||
parsed = urlsplit(url or "")
|
||||
try:
|
||||
address = ipaddress.ip_address(parsed.hostname or "")
|
||||
except ValueError:
|
||||
return None
|
||||
if (parsed.scheme == "http" and not address.is_loopback
|
||||
and address not in ipaddress.ip_network("100.64.0.0/10") and not lan_sign_in(web)):
|
||||
return (f"WARNING: the recorded web URL {url} is a plain-HTTP LAN address that no longer accepts "
|
||||
"sign-in. Set PIPELINES_WEB_PUBLIC_URL to the tailnet HTTPS address and rerun ./install.")
|
||||
return None
|
||||
|
||||
|
||||
def firewall_note(runner=subprocess.run):
|
||||
"""A read-only report of the macOS application firewall (never changed)."""
|
||||
if platform.system() != "Darwin" or not FIREWALL.exists():
|
||||
return None
|
||||
try:
|
||||
result = runner([str(FIREWALL), "--getglobalstate"], capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
if "disabled" in (result.stdout or "").lower():
|
||||
return ("Note: the macOS firewall is off. The installer does not change it; consider turning it on "
|
||||
"(System Settings > Network > Firewall) so other local services are not exposed either.")
|
||||
return None
|
||||
Reference in New Issue
Block a user