okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
20.0 KiB460 linesraw
1"""Who can reach the server: this computer, the local network, a Cloudflare quick tunnel, Tailscale.
2
3Strata starts the server; this module only works out the addresses, checks that the helper programs exist (and says in plain
4words how to install them when they do not), and runs/stops the one helper Strata starts itself: the cloudflared quick tunnel.
5Nothing here changes a firewall, a router or a Tailscale setting. The cloudflared output is filtered: only the public address
6is ever kept or shown (a login or certificate line is dropped, never printed).
7"""
8
9from __future__ import annotations
10
11import json
12import os
13import re
14import shutil
15import socket
16import subprocess
17import sys
18import time
19from dataclasses import dataclass
20from pathlib import Path
21
22from strata_cli.launch.settings import LaunchSettings
23
24TUNNEL_URL = re.compile(r"https://[a-z0-9-]+\.trycloudflare\.com")
25WINDOWS = os.name == "nt"
26
27
28def host_for(kind: str) -> str:
29    """The address the server listens on: loopback for this computer only, every address for the rest.
30
31    Cloudflare's tunnel connects from the same computer, so it too can stay on loopback."""
32    return "127.0.0.1" if kind in ("local", "cloudflare") else "0.0.0.0"
33
34
35def lan_ips() -> list[str]:
36    """This computer's private IPv4 addresses, the one used for the default route first."""
37    found: list[str] = []
38    try:
39        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
40        s.settimeout(0.2)
41        s.connect(("10.255.255.255", 1))          # no packet is sent; it picks the interface of the default route
42        found.append(s.getsockname()[0])
43        s.close()
44    except OSError:
45        pass
46    try:
47        import psutil
48        for infos in psutil.net_if_addrs().values():
49            for i in infos:
50                if i.family == socket.AF_INET:
51                    found.append(i.address)
52    except Exception:                                      # noqa: BLE001
53        pass
54    private = [a for a in dict.fromkeys(found) if _is_private(a) and not a.startswith("127.") and not a.startswith("169.254.")]
55    return private
56
57
58def _is_private(address: str) -> bool:
59    try:
60        a, b = (int(x) for x in address.split(".")[:2])
61    except ValueError:
62        return False
63    return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 100 and 64 <= b <= 127)
64
65
66CLOUDFLARED_MIN = (2022, 1, 0)   # the quick-tunnel flags and the "Registered tunnel connection" line Strata waits for
67_cf_seen: dict[tuple[str, float], str | None] = {}
68
69
70def _cloudflared_places() -> list[str]:
71    """Where a cloudflared might be: STRATA_CLOUDFLARED if set, then PATH, then the usual install places."""
72    explicit = os.environ.get("STRATA_CLOUDFLARED", "").strip()
73    if explicit:
74        return [explicit]
75    name = "cloudflared.exe" if WINDOWS else "cloudflared"
76    out: list[str] = []
77    for d in os.environ.get("PATH", "").split(os.pathsep):
78        if d.strip():
79            out.append(str(Path(d.strip().strip('"')) / name))
80    home = Path.home()
81    if WINDOWS:
82        env = os.environ
83        for root in (env.get("ProgramFiles", r"C:\Program Files"), env.get("ProgramFiles(x86)", r"C:\Program Files (x86)")):
84            out.append(str(Path(root) / "cloudflared" / name))
85        if env.get("LOCALAPPDATA"):
86            out.append(str(Path(env["LOCALAPPDATA"]) / "Microsoft" / "WinGet" / "Links" / name))
87        out.append(str(Path(env.get("ProgramData", r"C:\ProgramData")) / "chocolatey" / "bin" / name))
88        out.append(str(home / "scoop" / "shims" / name))
89    else:
90        for d in ("/usr/bin", "/usr/local/bin", "/opt/homebrew/bin", "/home/linuxbrew/.linuxbrew/bin", "/snap/bin",
91                  str(home / ".local" / "bin"), str(home / "bin")):
92            out.append(str(Path(d) / name))
93    seen: set[str] = set()
94    return [p for p in out if not (p in seen or seen.add(p))]
95
96
97def cloudflared_version(path: str) -> str | None:
98    """`cloudflared --version` of this file as 'YYYY.M.P', '' when it runs but prints no version, None when it does not run."""
99    try:
100        key = (path, os.stat(path).st_mtime)
101    except OSError:
102        return None
103    if key in _cf_seen:
104        return _cf_seen[key]
105    try:
106        r = subprocess.run([path, "--version"], capture_output=True, text=True, errors="replace", timeout=10,
107                           creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if WINDOWS else 0)
108        text = (r.stdout or "") + (r.stderr or "")
109    except (OSError, subprocess.SubprocessError):
110        _cf_seen[key] = None
111        return None
112    m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,3})", text)
113    ok = r.returncode == 0 and ("cloudflared" in text.lower() or bool(m))
114    _cf_seen[key] = (".".join(m.groups()) if m else "") if ok else None
115    return _cf_seen[key]
116
117
118def _cf_new_enough(version: str) -> bool:
119    if not version:
120        return True                      # a custom build with no readable version is not refused
121    return tuple(int(x) for x in version.split(".")) >= CLOUDFLARED_MIN
122
123
124def cloudflared_info() -> dict | None:
125    """The cloudflared Strata would use: {'path', 'version'}, found on PATH or in the usual places and new enough."""
126    for place in _cloudflared_places():
127        if not os.path.isfile(place) or (not WINDOWS and not os.access(place, os.X_OK)):
128            continue
129        version = cloudflared_version(place)
130        if version is not None and _cf_new_enough(version):
131            return {"path": place, "version": version}
132    return None
133
134
135def find_cloudflared() -> str | None:
136    info = cloudflared_info()
137    return info["path"] if info else None
138
139
140def cloudflared_procs(exclude: tuple[int, ...] = ()) -> list[tuple[int, str]]:
141    """Every cloudflared running on this computer as (pid, command line), without the pids in `exclude`. The command line is for
142    matching only (it can hold a tunnel token) and is never shown. A failed look is an empty list: it never blocks a tunnel."""
143    out: list[tuple[int, str]] = []
144    try:
145        if WINDOWS:
146            text = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
147                                   "Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\" | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }"],
148                                  capture_output=True, text=True, errors="replace", timeout=15, creationflags=subprocess.CREATE_NO_WINDOW).stdout
149            for line in text.splitlines():
150                m = re.match(r"(\d+)\t(.*)$", line)
151                if m:
152                    out.append((int(m.group(1)), m.group(2)))
153        else:
154            text = subprocess.run(["ps", "-axo", "pid=,comm=,args="], capture_output=True, text=True, errors="replace", timeout=5).stdout
155            for line in text.splitlines():
156                m = re.match(r"\s*(\d+)\s+(\S+)\s*(.*)$", line)
157                if m and re.search(r"(^|/)cloudflared$", m.group(2)):
158                    out.append((int(m.group(1)), m.group(3)))
159    except (OSError, subprocess.SubprocessError):
160        return []
161    return [(pid, cmd) for pid, cmd in out if pid not in exclude]
162
163
164def own_tunnel_pids(procs: list[tuple[int, str]], port: int) -> list[int]:
165    """The processes that are clearly this server's own tunnel: their --url points at its port. The others serve other tunnels."""
166    pat = re.compile(rf"--url[= ]\S*:{int(port)}(?:/|\s|$)")
167    return [pid for pid, cmd in procs if pat.search(cmd)]
168
169
170def other_tunnel_note(pids: list[int]) -> str:
171    return (f"cloudflared is already running for another tunnel (PID {pids[0]})." if len(pids) == 1
172            else f"cloudflared is already running for other tunnels (PIDs {', '.join(map(str, pids))}).")
173
174
175def find_tailscale() -> str | None:
176    found = shutil.which("tailscale")
177    if found:
178        return found
179    for guess in ("/usr/bin/tailscale", "/usr/local/bin/tailscale", "/Applications/Tailscale.app/Contents/MacOS/Tailscale",
180                  r"C:\Program Files\Tailscale\tailscale.exe"):
181        if Path(guess).is_file():
182            return guess
183    return None
184
185
186def _run(argv: list[str], timeout: float = 8.0) -> str:
187    try:
188        r = subprocess.run(argv, capture_output=True, text=True, errors="replace", timeout=timeout)
189        return r.stdout or ""
190    except (OSError, subprocess.SubprocessError):
191        return ""
192
193
194def tailscale_status() -> dict:
195    """{"installed", "running", "ip", "name"}: the tailnet address of this computer when Tailscale is up."""
196    exe = find_tailscale()
197    out = {"installed": bool(exe), "running": False, "ip": None, "name": None}
198    if not exe:
199        return out
200    ip = _run([exe, "ip", "-4"]).strip().splitlines()
201    if ip and re.fullmatch(r"\d+\.\d+\.\d+\.\d+", ip[0].strip()):
202        out["running"], out["ip"] = True, ip[0].strip()
203        try:
204            data = json.loads(_run([exe, "status", "--json"]) or "{}")
205            name = (data.get("Self") or {}).get("DNSName")
206            out["name"] = name.rstrip(".") if isinstance(name, str) and name else None
207        except ValueError:
208            pass
209    return out
210
211
212INSTALL_HELP = {
213    "cloudflared": {
214        "linux": "Install cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/ "
215                 "(on Debian/Ubuntu download the .deb and run: sudo dpkg -i cloudflared-linux-amd64.deb). No account is needed for a quick tunnel.",
216        "windows": "Install cloudflared: winget install --id Cloudflare.cloudflared  (no account is needed for a quick tunnel).",
217        "darwin": "Install cloudflared: brew install cloudflared  (no account is needed for a quick tunnel).",
218    },
219    "tailscale": {
220        "linux": "Install Tailscale: curl -fsSL https://tailscale.com/install.sh | sh, then run: sudo tailscale up",
221        "windows": "Install Tailscale from https://tailscale.com/download, sign in, and leave it running.",
222        "darwin": "Install Tailscale from https://tailscale.com/download, sign in, and leave it running.",
223    },
224}
225
226
227def install_help(tool: str) -> str:
228    plat = "windows" if WINDOWS else "darwin" if sys.platform == "darwin" else "linux"
229    return INSTALL_HELP[tool][plat]
230
231
232@dataclass
233class AccessOption:
234    kind: str
235    label: str
236    url: str
237    note: str
238    ready: bool          # the helper it needs is there (or none is needed)
239    warn: bool = False
240
241
242def options(port: int, *, tunnel_url: str | None = None) -> list[AccessOption]:
243    """The four ways to share, with the address each would give and what is missing for it."""
244    ips = lan_ips()
245    lan = ips[0] if ips else None
246    cf = find_cloudflared()
247    ts = tailscale_status()
248    out = [AccessOption("local", "This computer only", f"http://127.0.0.1:{port}",
249                        "for apps on this computer", True)]
250    out.append(AccessOption("lan", "My local network", f"http://{lan or '<network address>'}:{port}",
251                            "other computers at home or the office" if lan else
252                            "no network address found on this computer", bool(lan), warn=not lan))
253    out.append(AccessOption("cloudflare", "Cloudflare tunnel", tunnel_url or "https://<random>.trycloudflare.com",
254                            "from anywhere · cloudflared found" if cf else "cloudflared is not installed",
255                            bool(cf), warn=not cf))
256    if ts["running"]:
257        out.append(AccessOption("tailscale", "Tailscale", f"http://{ts['name'] or ts['ip']}:{port}",
258                                "your Tailscale devices", True))
259    else:
260        out.append(AccessOption("tailscale", "Tailscale", f"http://<tailnet address>:{port}",
261                                "Tailscale is not connected" if ts["installed"] else
262                                "Tailscale is not installed", False, warn=True))
263    return out
264
265
266def option_for(kind: str, port: int) -> AccessOption:
267    return next(o for o in options(port) if o.kind == kind)
268
269
270def missing_helper(kind: str) -> str | None:
271    """Plain words about what to install before this access kind works, or None when it is ready."""
272    if kind == "cloudflare" and not find_cloudflared():
273        return "cloudflared is not installed on this computer. " + install_help("cloudflared")
274    if kind == "tailscale":
275        ts = tailscale_status()
276        if not ts["installed"]:
277            return "Tailscale is not installed on this computer. " + install_help("tailscale")
278        if not ts["running"]:
279            return "Tailscale is installed but not connected. Run: tailscale up"
280    if kind == "lan" and not lan_ips():
281        return "No local network address was found on this computer. Check that it is connected to your network."
282    return None
283
284
285def urls_for(s: LaunchSettings, *, tunnel_url: str | None = None) -> list[str]:
286    """The addresses a client can use for these choices (the first is the main one)."""
287    base = [f"http://127.0.0.1:{s.port}"]
288    if s.access == "lan":
289        base += [f"http://{ip}:{s.port}" for ip in lan_ips()[:1]]
290    elif s.access == "cloudflare" and tunnel_url:
291        base = [tunnel_url] + base
292    elif s.access == "tailscale":
293        ts = tailscale_status()
294        if ts["running"]:
295            base += [f"http://{ts['name'] or ts['ip']}:{s.port}"] + ([f"http://{ts['ip']}:{s.port}"] if ts["name"] else [])
296    return base
297
298
299def firewall_note(kind: str) -> str | None:
300    """Windows asks the first time a program listens for other computers: say so before it happens, in plain words."""
301    if WINDOWS and kind in ("lan", "tailscale"):
302        return ("Windows may ask whether to allow Strata (python.exe) on your network: choose Allow for private networks. "
303                "If you choose Cancel, the model still works on this computer.")
304    return None
305
306
307def new_key() -> str:
308    import secrets
309    return "sk-strata-" + secrets.token_urlsafe(24)
310
311
312def _config_key(path) -> str | None:
313    try:
314        key = str(json.loads(Path(path).read_text(encoding="utf-8-sig")).get("api_key") or "").strip()
315    except (OSError, ValueError, AttributeError):
316        return None
317    return key if key and key.lower() != "none" else None
318
319
320def kept_key(name: str | None = None) -> str | None:
321    """The API key an earlier launch already made, so a restart does not invalidate the apps set up with it (E05/G01): the key in this launch's
322    own config (profile `launch-<name>`), the saved preset's, else the one in the newest launch config. None when there is none; `--new-key`
323    and the key button are the only ways to rotate it."""
324    try:
325        from strata_control import profiles
326        from strata_cli.launch import settings as S, store
327        if name:
328            try:
329                prof, _rev = profiles.load("launch-" + S.slug(name))
330                key = _config_key(prof.get("source_config"))
331                if key:
332                    return key
333            except Exception:                                  # noqa: BLE001 - no such profile yet
334                pass
335            preset = store.load(name, missing_ok=True)
336            if preset and preset.api_key:
337                return preset.api_key
338        newest, found = -1.0, None
339        for row in profiles.list_profiles():
340            if not row["id"].startswith("launch-"):
341                continue
342            source = row.get("source_config")                  # an unreadable profile is listed as {id, error}: skip that row, keep looking
343            if not source:
344                continue
345            key = _config_key(source)
346            if not key:
347                continue
348            try:
349                stamp = Path(source).stat().st_mtime
350            except OSError:
351                continue
352            if stamp > newest:
353                newest, found = stamp, key
354        return found
355    except Exception:                                          # noqa: BLE001 - never block a launch over the lookup
356        return None
357
358
359def mask_key(key: str | None) -> str:
360    if not key:
361        return "off"
362    return key[:10] + "•" * 8 if len(key) > 12 else "•" * 8
363
364
365# ----------------------------------------------------------------------------------------------- the quick tunnel
366
367def _state_dir() -> Path:
368    from strata_control import paths
369    d = paths.state_base() / "launch"
370    d.mkdir(parents=True, exist_ok=True)
371    return d
372
373
374def _tunnel_state(name: str) -> Path:
375    from strata_cli.launch.settings import slug
376    return _state_dir() / f"{slug(name)}.tunnel.json"
377
378
379def start_tunnel(name: str, port: int, *, wait: float = 45.0) -> tuple[str | None, str]:
380    """Start `cloudflared tunnel --url` for the local server; returns (public url or None, plain message).
381
382    The process is detached (it keeps running after this terminal closes, like the server) and recorded with its start token so
383    `stop_tunnel` ends exactly this process and nothing else. Only the public address is read from its output."""
384    exe = find_cloudflared()
385    if not exe:
386        return None, missing_helper("cloudflare") or "cloudflared is not installed."
387    existing = tunnel_info(name)
388    if existing and existing.get("url") and existing.get("port") == port:
389        return existing["url"], "The tunnel was already running."
390    running = cloudflared_procs(exclude=(int(existing["pid"]),) if existing else ())
391    own = own_tunnel_pids(running, port)
392    if own:
393        return None, (f"Strata’s tunnel for this address is already running (PID {', '.join(map(str, own))}), so Strata did not start a "
394                      "second one. Stop it first (or use it as it is), then connect again here.")
395    note = other_tunnel_note([pid for pid, _ in running]) if running else ""
396    stop_tunnel(name)
397    log = _state_dir() / f"{Path(name).name}.tunnel.log"
398    argv = [exe, "tunnel", "--no-autoupdate", "--url", f"http://127.0.0.1:{port}"]
399    with open(log, "wb") as out:
400        kw = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW} if WINDOWS
401              else {"start_new_session": True})
402        proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, **kw)
403    from strata_control import procs
404    token = procs.start_token(proc.pid)
405    url = None
406    deadline = time.monotonic() + wait
407    while time.monotonic() < deadline and url is None and proc.poll() is None:
408        try:
409            m = TUNNEL_URL.search(log.read_text(encoding="utf-8", errors="replace"))
410        except OSError:
411            m = None
412        if m:
413            url = m.group(0)
414            break
415        time.sleep(0.4)
416    state = {"pid": proc.pid, "token": token, "cmd": list(procs.command_line(proc.pid) or argv), "url": url, "port": port}
417    _tunnel_state(name).write_text(json.dumps(state), encoding="utf-8")
418    try:
419        log.write_bytes(b"")                       # keep no log text: the address is all anyone needs from it
420    except OSError:
421        pass
422    if url is None:
423        stop_tunnel(name)
424        return None, ("The Cloudflare tunnel did not come up in time. Check your internet connection and try again; "
425                      "the server itself is running and still works on this computer.")
426    return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server; an API key keeps others out." + (" " + note if note else "")
427
428
429def tunnel_info(name: str) -> dict | None:
430    try:
431        state = json.loads(_tunnel_state(name).read_text(encoding="utf-8"))
432    except (OSError, ValueError):
433        return None
434    from strata_control import procs
435    if isinstance(state, dict) and procs.is_same(int(state.get("pid", 0)), state.get("token") or "", state.get("cmd")):
436        return state
437    return None
438
439
440def stop_tunnel(name: str) -> bool:
441    """End this launch's tunnel, only if the recorded process is still exactly the one Strata started."""
442    state = tunnel_info(name)
443    ok = False
444    if state:
445        from strata_control import procs
446        outcome = procs.end_one({"pid": state["pid"], "token": state["token"], "cmd": state["cmd"]}, grace=5.0)
447        ok = outcome in ("ended", "gone")
448    try:
449        _tunnel_state(name).unlink()
450    except OSError:
451        pass
452    return ok
453
454
455def filter_line(line: str) -> str:
456    """For any helper output shown to a person: drop login/certificate/token lines, keep the rest."""
457    low = line.lower()
458    if any(w in low for w in ("token", "cert", "login", "secret", "authorize", "credential")):
459        return ""
460    return line