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:
2026-11-10 01:02:02 +00:00
parent a706739088
commit ad6cdab418
18 changed files with 677 additions and 35 deletions
@@ -113,11 +113,16 @@ class DiscoveredServer {
DiscoveredAddress(route: DiscoveredRoute.public, endpoint: public),
);
}
// lan=0: the web proxy refuses LAN connections, so the address record is
// not a LAN route; the first tailnet or public route is the endpoint.
if (attributes['lan'] == '0') routes.removeAt(0);
if (routes.isEmpty) return null;
final first = routes.first.endpoint;
return DiscoveredServer(
name: name.isEmpty ? instance : name,
host: host,
port: port,
secure: secure,
host: first.host,
port: first.port,
secure: first.scheme == 'wss',
path: cleanPath,
passwordRequired: attributes['auth'] != 'none',
version: attributes['v'],
@@ -125,4 +125,35 @@ void main() {
expect(DiscoveredServer.isTailscaleIPv4('100.127.0.1'), isTrue);
expect(DiscoveredServer.isTailscaleIPv4('100.128.0.1'), isFalse);
});
test('lan=0 drops the LAN route and dials the tailnet first', () {
final server = DiscoveredServer.fromRecord(
instance: 'Pipelines-box',
addresses: ['100.85.25.33'],
port: 8083,
attributes: {
'name': 'box',
'path': '/connect',
'tls': '0',
'auth': 'password',
'lan': '0',
'ts': '100.85.25.33',
'public': 'https://box.tail1.ts.net:8443',
},
)!;
expect(server.addresses.map((a) => a.route), [
DiscoveredRoute.tailscale,
DiscoveredRoute.public,
]);
expect(server.endpoint, Uri.parse('ws://100.85.25.33:8083/connect'));
expect(
DiscoveredServer.fromRecord(
instance: 'Pipelines-box',
addresses: ['100.85.25.33'],
port: 8083,
attributes: {'lan': '0'},
),
isNull,
);
});
}
+2 -1
View File
@@ -38,6 +38,7 @@ func main() {
}
db := flag.String("db", defaultDB, "SQLite database path (honors XDG_DATA_HOME)")
mdnsOn := flag.Bool("mdns", envEnabled(os.Getenv("PIPELINES_MDNS")), "Advertise the server on the LAN with mDNS/DNS-SD ("+discovery.ServiceType+"); PIPELINES_MDNS=off disables")
mdnsLAN := flag.Bool("mdns-lan", true, "Advertise the LAN route; false when the web proxy refuses LAN connections (only the tailnet and public routes are advertised)")
mdnsPort := flag.Int("mdns-port", envPort(os.Getenv("PIPELINES_MDNS_PORT")), "Port LAN clients dial: the authenticated web proxy fronting this server (default: the -addr port when it is not loopback)")
flag.Parse()
if err := os.MkdirAll(filepath.Dir(*db), 0700); err != nil {
@@ -198,7 +199,7 @@ func main() {
chatNames = chats.Backends()
}
if *mdnsOn {
defer keepAdvertising(*addr, *mdnsPort)()
defer keepAdvertising(*addr, *mdnsPort, *mdnsLAN)()
}
printBanner(startup{Build: buildinfo.Current(), Addr: *addr, Database: *db, Artifacts: artifactsRoot,
Authoring: *allowAuthoring, OpenCode: openCodeStatus, Chat: chatNames})
+7 -7
View File
@@ -16,17 +16,17 @@ import (
// advertise publishes the server on the LAN. Any failure is logged and the
// server carries on: discovery is a convenience, never a startup requirement.
// The returned stop (nil when nothing was published) withdraws the advert.
func advertise(addr string, proxyPort int) func() {
return advertiseWith(addr, proxyPort, discovery.LANAddresses(), discovery.TailscaleAddresses())
func advertise(addr string, proxyPort int, lanRoute bool) func() {
return advertiseWith(addr, proxyPort, lanRoute, discovery.LANAddresses(), discovery.TailscaleAddresses())
}
func advertiseWith(addr string, proxyPort int, lan, tailnet []net.IP) func() {
func advertiseWith(addr string, proxyPort int, lanRoute bool, lan, tailnet []net.IP) func() {
hostname, _ := os.Hostname()
// The installer exports the TLS front's origin (tailscale serve) for the
// same proxy; it is advertised so clients can choose that route by name.
advert, err := discovery.Plan(discovery.Config{ListenAddr: addr, ProxyPort: proxyPort,
Version: buildinfo.Current().Version, Hostname: hostname, IPs: lan,
TailscaleIPs: tailnet, PublicURL: os.Getenv("PIPELINES_WEB_PUBLIC_URL")})
TailscaleIPs: tailnet, PublicURL: os.Getenv("PIPELINES_WEB_PUBLIC_URL"), NoLAN: !lanRoute})
if err != nil {
log.Printf("mDNS: not advertising: %v", err)
return nil
@@ -66,9 +66,9 @@ const addressRecheck = 30 * time.Second
// keepAdvertising publishes the server now and republishes whenever the
// host's LAN or tailnet addresses change. The returned stop ends both.
func keepAdvertising(addr string, proxyPort int) func() {
func keepAdvertising(addr string, proxyPort int, lanRoute bool) func() {
lan, tailnet := discovery.LANAddresses(), discovery.TailscaleAddresses()
stop := advertiseWith(addr, proxyPort, lan, tailnet)
stop := advertiseWith(addr, proxyPort, lanRoute, lan, tailnet)
done := make(chan struct{})
go func() {
ticker := time.NewTicker(addressRecheck)
@@ -87,7 +87,7 @@ func keepAdvertising(addr string, proxyPort int) func() {
}
lan, tailnet = nextLAN, nextTailnet
log.Printf("mDNS: addresses changed to %s; republishing", joinIPs(lan))
stop = advertiseWith(addr, proxyPort, lan, tailnet)
stop = advertiseWith(addr, proxyPort, lanRoute, lan, tailnet)
}
}
}()
+2 -2
View File
@@ -21,7 +21,7 @@ func TestMDNSEnvironmentSwitches(t *testing.T) {
// A loopback-only server with no proxy port publishes nothing and does not
// fail: the caller only defers a non-nil stop.
func TestAdvertiseSkipsLoopbackWithoutFailing(t *testing.T) {
if stop := advertise("127.0.0.1:0", 0); stop != nil {
if stop := advertise("127.0.0.1:0", 0, true); stop != nil {
stop()
t.Fatal("loopback-only server was advertised")
}
@@ -44,6 +44,6 @@ func TestSameAddressesIgnoresOrder(t *testing.T) {
// keepAdvertising on a loopback-only server publishes nothing, keeps its
// watcher running and stops cleanly.
func TestKeepAdvertisingStopsCleanly(t *testing.T) {
stop := keepAdvertising("127.0.0.1:0", 0)
stop := keepAdvertising("127.0.0.1:0", 0, true)
stop()
}
+21 -2
View File
@@ -42,6 +42,11 @@ type Config struct {
// PublicURL is the HTTPS origin a TLS front (tailscale serve) exposes for
// the same web proxy, for example https://box.tail1.ts.net:8443.
PublicURL string
// NoLAN means the proxy refuses LAN connections (the installer's loopback
// + tailnet default). The advert then carries no LAN route: its address
// records are the tailnet IPv4 addresses, TXT says lan=0, and tailnet
// clients on the same LAN still find the machine through ts= and public=.
NoLAN bool
}
// Advert is the record set the server publishes.
@@ -77,7 +82,18 @@ func Plan(cfg Config) (Advert, error) {
if port <= 0 || port > 65535 {
return Advert{}, fmt.Errorf("advertised port %d is out of range", port)
}
if len(cfg.IPs) == 0 {
ips := cfg.IPs
if cfg.NoLAN {
ips = nil
for _, ip := range cfg.TailscaleIPs {
if IsTailscaleIP(ip) {
ips = append(ips, ip.To4())
}
}
if len(ips) == 0 {
return Advert{}, fmt.Errorf("LAN connections are refused and there is no tailnet address: %w", ErrNotReachable)
}
} else if len(ips) == 0 {
return Advert{}, fmt.Errorf("no LAN IPv4 address: %w", ErrNotReachable)
}
label := hostLabel(cfg.Hostname)
@@ -96,6 +112,9 @@ func Plan(cfg Config) (Advert, error) {
"tls=0",
"auth=" + auth,
}
if cfg.NoLAN {
txt = append(txt, "lan=0")
}
if ts := joinIPs(cfg.TailscaleIPs); ts != "" {
txt = append(txt, "ts="+ts)
}
@@ -106,7 +125,7 @@ func Plan(cfg Config) (Advert, error) {
Instance: "Pipelines-" + label,
Host: label + ".local.",
Port: port,
IPs: cfg.IPs,
IPs: ips,
TXT: txt,
}, nil
}
+36
View File
@@ -157,3 +157,39 @@ func TestPlanAdvertisesTailnetAndPublicRoutes(t *testing.T) {
t.Fatal("tailnet range check")
}
}
// With LAN connections refused the advert names no LAN route: the address
// records are the tailnet IPs and TXT says lan=0, so tailnet clients on the
// same LAN still find the machine on the proxy port that answers them.
func TestPlanWithoutLANAdvertisesOnlyTailnetAndPublicRoutes(t *testing.T) {
tailnetIPs := []net.IP{net.ParseIP("100.85.25.33"), net.ParseIP("fd7a:115c:a1e0::d501:199e")}
advert, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Version: "v1", Hostname: "box", IPs: lan,
TailscaleIPs: tailnetIPs, PublicURL: "https://box.tail1.ts.net:8443", NoLAN: true})
if err != nil {
t.Fatal(err)
}
if advert.Port != 8083 || len(advert.IPs) != 1 || !advert.IPs[0].Equal(net.ParseIP("100.85.25.33")) {
t.Fatalf("advert = %+v", advert)
}
for _, want := range []string{"lan=0", "ts=100.85.25.33", "public=https://box.tail1.ts.net:8443"} {
if !slices.Contains(advert.TXT, want) {
t.Fatalf("TXT %q lacks %s", advert.TXT, want)
}
}
zone, err := advert.Zone()
if err != nil {
t.Fatal(err)
}
records := zone.Records(dns.Question{Name: advert.Host, Qtype: dns.TypeA, Qclass: dns.ClassINET})
if len(records) != 1 || !records[0].(*dns.A).A.Equal(net.ParseIP("100.85.25.33")) {
t.Fatalf("A records = %v", records)
}
if _, err := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Hostname: "box", IPs: lan, NoLAN: true,
PublicURL: "https://box.tail1.ts.net:8443"}); !errors.Is(err, ErrNotReachable) {
t.Fatalf("no tailnet address must not publish: %v", err)
}
withLAN, _ := Plan(Config{ListenAddr: "127.0.0.1:8080", ProxyPort: 8083, Hostname: "box", IPs: lan, TailscaleIPs: tailnetIPs})
if slices.Contains(withLAN.TXT, "lan=0") || !withLAN.IPs[0].Equal(lan[0]) {
t.Fatalf("LAN advert changed: %+v", withLAN)
}
}
+8 -1
View File
@@ -121,6 +121,10 @@ func discovered(entry *mdns.ServiceEntry) (FoundServer, bool) {
}
endpoint := (&url.URL{Scheme: scheme, Host: net.JoinHostPort(ip.String(), strconv.Itoa(entry.Port)), Path: path}).String()
addresses := []FoundAddress{{Kind: "lan", Endpoint: endpoint}}
if fields["lan"] == "0" {
// The proxy refuses LAN connections; the address record is a tailnet IP.
addresses = nil
}
for _, value := range strings.Split(fields["ts"], ",") {
ts := net.ParseIP(strings.TrimSpace(value))
if ts == nil || !IsTailscaleIP(ts) || len(addresses) > 5 {
@@ -137,5 +141,8 @@ func discovered(entry *mdns.ServiceEntry) (FoundServer, bool) {
}
addresses = append(addresses, FoundAddress{Kind: "public", Endpoint: (&url.URL{Scheme: wsScheme, Host: u.Host, Path: path}).String()})
}
return FoundServer{Name: name, Endpoint: endpoint, Auth: auth, Version: fields["v"], Addresses: addresses}, true
if len(addresses) == 0 {
return FoundServer{}, false
}
return FoundServer{Name: name, Endpoint: addresses[0].Endpoint, Auth: auth, Version: fields["v"], Addresses: addresses}, true
}
+18
View File
@@ -87,3 +87,21 @@ func TestBrowseListsEveryRouteToTheSameMachine(t *testing.T) {
t.Fatalf("unsafe routes accepted: %+v", found.Addresses)
}
}
func TestBrowseOmitsTheLANRouteWhenTheAdvertSaysLan0(t *testing.T) {
item := service("100.85.25.33")
item.InfoFields = append(item.InfoFields, "lan=0", "ts=100.85.25.33", "public=https://box.tail1.ts.net:8443")
found, ok := discovered(item)
want := []FoundAddress{
{Kind: "tailscale", Endpoint: "ws://100.85.25.33:8083/connect"},
{Kind: "public", Endpoint: "wss://box.tail1.ts.net:8443/connect"},
}
if !ok || !slices.Equal(found.Addresses, want) || found.Endpoint != want[0].Endpoint {
t.Fatalf("found = %+v (%v)", found, ok)
}
bare := service("100.85.25.33")
bare.InfoFields = append(bare.InfoFields, "lan=0")
if _, ok := discovered(bare); ok {
t.Fatal("an advert with no usable route was accepted")
}
}
+3 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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")
+46 -2
View File
@@ -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()
+98
View File
@@ -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()
+113
View File
@@ -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
+26 -3
View File
@@ -2,6 +2,7 @@
// web app, and a proxy to the Pipelines server, with no dependencies.
// node serve.mjs [--port 8090] [--host 0.0.0.0] [--pipelines 127.0.0.1:8080]
// [--root DIR] [--updates DIR]
// [--allow loopback,tailnet[,lan]] [--lan-plain-login]
//
// Serves the app (--root, default ../app/build/web) and proxies /connect,
// /artifacts/, /files and /chat-uploads to the Pipelines server, so the page, the
@@ -27,6 +28,7 @@ import { fileURLToPath } from "node:url";
import net from "node:net";
import { sameOriginUpgrade } from "./src/proxySecurity.js";
import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js";
import { accessPolicy, PLAIN_LAN_REFUSAL } from "./src/listenPolicy.js";
// The proxy's own directory holds the sign-in page's icons.
const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
@@ -34,6 +36,8 @@ const HERE = resolve(fileURLToPath(new URL(".", import.meta.url)));
// the checkout's app/build/web. `--updates DIR` serves the Android app's
// version.json and APK at /updates/, behind the same sign-in.
const ROOT = resolve(flag(process.argv, "--root", "") || join(HERE, "..", "app", "build", "web"));
// Which networks may connect (src/listenPolicy.js).
const access = accessPolicy(process.argv);
const UPDATES = flag(process.argv, "--updates", "") ? resolve(flag(process.argv, "--updates", "")) : null;
// ---------------------------------------------------------------------------
@@ -412,6 +416,10 @@ const server = createServer(async (req, res) => {
return;
}
}
if (access.plainLanBlocked(req)) {
res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }).end(PLAIN_LAN_REFUSAL);
return;
}
if (auth) {
if (pathname === "/login" && req.method === "GET") {
if (isAuthed(req)) {
@@ -566,7 +574,7 @@ server.on("upgrade", (req, clientSocket, clientHead) => {
return;
}
const pathname = (req.url ?? "").split("?")[0];
if (!sameOriginUpgrade(req.headers.origin, req.headers.host)) {
if (access.plainLanBlocked(req) || !sameOriginUpgrade(req.headers.origin, req.headers.host)) {
clientSocket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
clientSocket.destroy();
return;
@@ -584,12 +592,27 @@ server.on("upgrade", (req, clientSocket, clientHead) => {
proxyUpgrade(req, clientSocket, clientHead);
});
// Connections from a network the policy does not admit are dropped before
// any HTTP is read.
server.on("connection", (socket) => {
if (!access.admits(socket)) socket.destroy();
});
const port = parsePort(process.argv);
const host = flag(process.argv, "--host", "127.0.0.1");
let host = flag(process.argv, "--host", "127.0.0.1");
// "::" also reaches a tailnet IPv6 address; a host without IPv6 falls back.
function noIPv6(error) {
if (host !== "::" || !["EAFNOSUPPORT", "EADDRNOTAVAIL"].includes(error.code)) throw error;
host = "0.0.0.0";
server.listen(port, host);
}
server.once("error", noIPv6);
server.listen(port, host, () => {
const shown = host === "0.0.0.0" ? "127.0.0.1" : host;
server.off("error", noIPv6);
const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
console.log(`web spike: http://${shown}:${port}/ (bound ${host}:${port})`);
console.log(`proxying /connect (ws), /artifacts/ and /files (http) -> ${targetHost}:${targetPort}`);
console.log(auth ? "auth: sign-in required" : "auth: DISABLED (tests)");
console.log(access.describe());
console.log(`serving ${ROOT}${UPDATES ? `; app updates from ${UPDATES}` : ""}`);
});
+78
View File
@@ -0,0 +1,78 @@
// Which networks may reach the web proxy, decided per connection.
//
// The installer's default is "loopback + tailnet": the proxy binds the
// wildcard address but drops every connection that did not arrive on, and
// come from, a loopback or Tailscale address. Binding the wildcard and
// filtering is deliberate: Tailscale often comes up after the proxy (login
// autostart) and its address can change, and a filter needs no rebinding or
// retry loop. Both ends are checked: macOS accepts a packet for the tailnet
// address on any interface (weak host model), but a LAN peer cannot complete a
// TCP handshake from a tailnet source address because the reply is routed into
// the tunnel.
//
// A plain-HTTP LAN listener is opt-in (`--allow ...,lan`). Even then the
// password, the session cookie and every signed-in page stay off the LAN's
// cleartext unless `--lan-plain-login` says otherwise.
import net from "node:net";
const tailnet = new net.BlockList();
tailnet.addSubnet("100.64.0.0", 10, "ipv4"); // Tailscale's CGNAT range
tailnet.addSubnet("fd7a:115c:a1e0::", 48, "ipv6"); // Tailscale's ULA prefix
const loopback = new net.BlockList();
loopback.addSubnet("127.0.0.0", 8, "ipv4");
loopback.addAddress("::1", "ipv6");
export const ROUTES = ["loopback", "tailnet", "lan"];
/** "loopback", "tailnet" or "lan" for one address (IPv4-mapped IPv6 unwrapped). */
export function addressRoute(address) {
let value = String(address ?? "").replace(/%.*$/, "");
if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) value = value.slice(7);
const family = net.isIPv4(value) ? "ipv4" : net.isIPv6(value) ? "ipv6" : null;
if (!family) return "lan";
if (loopback.check(value, family)) return "loopback";
if (tailnet.check(value, family)) return "tailnet";
return "lan";
}
/** The route of a connection: loopback or tailnet only when both ends agree. */
export function socketRoute(socket) {
const local = addressRoute(socket?.localAddress);
return local !== "lan" && local === addressRoute(socket?.remoteAddress) ? local : "lan";
}
/**
* The policy from the proxy's flags. Without `--allow` every route is
* admitted with plain-HTTP sign-in, as before (a direct `node serve.mjs`
* binds 127.0.0.1 by default); the installer always passes `--allow`.
*/
export function accessPolicy(argv) {
const i = argv.indexOf("--allow");
const given = i !== -1 && argv[i + 1] ? argv[i + 1] : null;
const allow = new Set(given === null ? ROUTES : given.split(",").map((part) => part.trim()).filter(Boolean));
for (const route of allow) {
if (!ROUTES.includes(route)) throw new Error(`--allow: unknown route ${route} (use ${ROUTES.join(",")})`);
}
allow.add("loopback"); // the health check, tailscale serve and local tools
const lanPlainLogin = given === null || argv.includes("--lan-plain-login");
return {
allow,
lanPlainLogin,
/** Whether a new connection may proceed at all. */
admits(socket) {
return allow.has(socketRoute(socket));
},
/** Whether this request must not carry the password or a signed-in page. */
plainLanBlocked(req) {
return !lanPlainLogin && socketRoute(req.socket) === "lan";
},
describe() {
return `access: ${[...allow].join(" + ")}` +
(allow.has("lan") ? (lanPlainLogin ? " (plain-HTTP LAN sign-in ALLOWED)" : " (no sign-in over plain-HTTP LAN)") : "");
},
};
}
export const PLAIN_LAN_REFUSAL =
"Signing in over plain HTTP on this network is disabled: the password and session cookie would cross it unencrypted.\n" +
"Use this machine's Tailscale address (for example its https://<name>.ts.net address), or set web.lan_plain_login in the installation.\n";
+134
View File
@@ -0,0 +1,134 @@
import test from "node:test";
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { networkInterfaces, tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import net from "node:net";
import { accessPolicy, addressRoute, socketRoute } from "../src/listenPolicy.js";
const here = fileURLToPath(new URL("..", import.meta.url));
test("classifies loopback, tailnet and LAN addresses", () => {
for (const address of ["127.0.0.1", "127.8.0.2", "::1", "::ffff:127.0.0.1"]) assert.equal(addressRoute(address), "loopback", address);
for (const address of ["100.64.0.1", "100.101.7.9", "100.127.255.254", "::ffff:100.100.1.2", "fd7a:115c:a1e0::1", "fd7a:115c:a1e0:ab12::9"]) {
assert.equal(addressRoute(address), "tailnet", address);
}
for (const address of ["192.168.1.20", "10.0.0.5", "100.63.255.255", "100.128.0.1", "fd7a:115c:a1e1::1", "fe80::1%en0", "", undefined, "nonsense"]) {
assert.equal(addressRoute(address), "lan", String(address));
}
});
test("a connection is tailnet or loopback only when both ends are", () => {
assert.equal(socketRoute({ localAddress: "100.101.1.1", remoteAddress: "100.90.2.2" }), "tailnet");
assert.equal(socketRoute({ localAddress: "127.0.0.1", remoteAddress: "127.0.0.1" }), "loopback");
// A LAN peer aiming at the tailnet address (macOS weak host model) is LAN.
assert.equal(socketRoute({ localAddress: "100.101.1.1", remoteAddress: "192.168.1.9" }), "lan");
assert.equal(socketRoute({ localAddress: "127.0.0.1", remoteAddress: "100.90.2.2" }), "lan");
assert.equal(socketRoute({ localAddress: "192.168.1.20", remoteAddress: "192.168.1.9" }), "lan");
});
test("the policy admits only allowed routes and gates LAN sign-in", () => {
const lan = { localAddress: "192.168.1.20", remoteAddress: "192.168.1.9" };
const ts = { localAddress: "100.101.1.1", remoteAddress: "100.90.2.2" };
const local = { localAddress: "127.0.0.1", remoteAddress: "127.0.0.1" };
const strict = accessPolicy(["--allow", "tailnet"]);
assert.deepEqual([strict.admits(local), strict.admits(ts), strict.admits(lan)], [true, true, false]);
const withLan = accessPolicy(["--allow", "loopback,tailnet,lan"]);
assert.equal(withLan.admits(lan), true);
assert.equal(withLan.plainLanBlocked({ socket: lan }), true);
assert.equal(withLan.plainLanBlocked({ socket: ts }), false);
assert.equal(withLan.plainLanBlocked({ socket: local }), false);
assert.equal(accessPolicy(["--allow", "loopback,tailnet,lan", "--lan-plain-login"]).plainLanBlocked({ socket: lan }), false);
const legacy = accessPolicy([]);
assert.equal(legacy.admits(lan) && !legacy.plainLanBlocked({ socket: lan }), true);
assert.throws(() => accessPolicy(["--allow", "everything"]), /unknown route/);
});
function hostAddress(match) {
for (const entries of Object.values(networkInterfaces())) {
for (const entry of entries ?? []) {
if (entry.family === "IPv4" && !entry.internal && match(entry.address)) return entry.address;
}
}
return null;
}
const lanAddress = hostAddress((address) => addressRoute(address) === "lan");
const tailnetAddress = hostAddress((address) => addressRoute(address) === "tailnet");
async function freePort() {
const server = net.createServer().listen(0, "127.0.0.1");
await new Promise((done) => server.once("listening", done));
const { port } = server.address();
await new Promise((done) => server.close(done));
return port;
}
async function start(args) {
const dir = await mkdtemp(join(tmpdir(), "listen-"));
await mkdir(join(dir, "app"));
await writeFile(join(dir, "app", "index.html"), "<html><head></head><body>app</body></html>");
const port = await freePort();
const child = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--root", join(dir, "app"), ...args], {
cwd: here,
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
stdio: ["ignore", "pipe", "inherit"],
});
let output = "";
await new Promise((done) => child.stdout.on("data", (chunk) => {
output += chunk;
if (output.includes("access:")) done();
}));
return { port, output, stop: () => child.kill() };
}
/** Raw HTTP so a dropped connection is observed as such, not retried. */
function rawRequest(address, port, text) {
return new Promise((done) => {
const socket = net.connect(port, address, () => socket.write(text));
let reply = "";
socket.on("data", (chunk) => { reply += chunk; });
socket.on("error", () => done({ dropped: true, reply }));
socket.on("close", () => done({ dropped: reply === "", reply }));
socket.setTimeout(3000, () => socket.destroy());
});
}
const get = (path) => `GET ${path} HTTP/1.1\r\nHost: x\r\nAccept: text/html\r\nConnection: close\r\n\r\n`;
const login = "POST /login HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: 17\r\nConnection: close\r\n\r\npassword=whatever";
test("loopback + tailnet drops a LAN connection and serves loopback and tailnet", { skip: !lanAddress && "no LAN address" }, async (t) => {
const proxy = await start(["--host", "::", "--allow", "loopback,tailnet"]);
t.after(proxy.stop);
const lan = await rawRequest(lanAddress, proxy.port, get("/"));
assert.equal(lan.dropped, true, `LAN ${lanAddress} got ${lan.reply}`);
const local = await rawRequest("127.0.0.1", proxy.port, get("/"));
assert.match(local.reply, /^HTTP\/1.1 200/);
if (tailnetAddress) {
const ts = await rawRequest(tailnetAddress, proxy.port, get("/"));
assert.match(ts.reply, /^HTTP\/1.1 200/, `tailnet ${tailnetAddress}`);
}
});
test("an opted-in LAN refuses sign-in and signed-in pages over plain HTTP", { skip: !lanAddress && "no LAN address" }, async (t) => {
const proxy = await start(["--host", "0.0.0.0", "--allow", "loopback,tailnet,lan"]);
t.after(proxy.stop);
for (const request of [login, get("/login"), get("/"), get("/updates/version.json")]) {
const reply = await rawRequest(lanAddress, proxy.port, request);
assert.match(reply.reply, /^HTTP\/1.1 403/, request.split("\r\n")[0]);
assert.match(reply.reply, /plain HTTP on this network is disabled/);
}
assert.match((await rawRequest(lanAddress, proxy.port, get("/favicon.svg"))).reply, /^HTTP\/1.1 200/);
const upgrade = await rawRequest(lanAddress, proxy.port, "GET /connect HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\n" +
"Upgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n");
assert.match(upgrade.reply, /^HTTP\/1.1 403/);
assert.match((await rawRequest("127.0.0.1", proxy.port, get("/"))).reply, /^HTTP\/1.1 200/);
});
test("web.lan_plain_login restores plain-HTTP LAN sign-in explicitly", { skip: !lanAddress && "no LAN address" }, async (t) => {
const proxy = await start(["--host", "0.0.0.0", "--allow", "loopback,tailnet,lan", "--lan-plain-login"]);
t.after(proxy.stop);
assert.match(proxy.output, /plain-HTTP LAN sign-in ALLOWED/);
assert.match((await rawRequest(lanAddress, proxy.port, get("/"))).reply, /^HTTP\/1.1 200/);
});